IV-48 / Part XII · KV Cache
Keys, Values and the Cache Invariant
Build a real key/value cache from observed tokens, derive its absolute-position invariant, and distinguish reusable past features from new queries and unverified external payloads.
Review the ideas this chapter uses
Suppose a decoder has processed ab, and another a arrives. Earlier attention keys and values already exist. Can we retain those numbers and calculate only the new row? We can, provided we preserve exactly which prefix, positions and model produced them.
Learning objective: Identify which per-layer past tensors a decoder can reuse.
Keys, Values and the Cache Invariant
Observe actual a/b tokens entering a one-layer cache. Each append computes one new query, rotates its Q/K at the absolute position and retains prior K/V unchanged. A separate complete final-prefix call supplies real comparison operands. The hand-set model is untrained.
Use raw a/b letters only: at most six UTF-8 bytes and one to three actual BPE tokens. Empty input is UNAVAILABLE. Fixed-corpus merges may compress text; no trimming, normalization or cropping occurs. All 26 numeric fields validate, including inactive embedding/readout entries.
Full embedding E [5,2]
Full readout U [2,5]
Full readout biases [5]
Exact starting inputs for this saved calculation
observedTokens 3. cacheEntries 3. cachedQueryRows 3. YMaxError 0. Validate every raw field before interpreting text; start with empty cache metadata. 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.
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.
Saved inputs
- merges
- 0
- e00
- 1
- e01
- 0
- e10
- 0
- e11
- 1
- e20
- 0
- e21
- 0
- e30
- 0.5
- e31
- 0.5
- e40
- 1
- e41
- 1
- u00
- 1
- u01
- 0
- u02
- 0
- u03
- 0
- u04
- 0
- u10
- 0
- u11
- 1
- u12
- 0
- u13
- 0
- u14
- 0
- b0
- 0
- b1
- 0
- b2
- 0
- b3
- 0
- b4
- 0
Saved outputs
- utf16Units
- 3
- byteBound
- 6
- tokenBound
- 3
- observedTokens
- 3
- classCount
- 3
- initialCacheEntries
- 0
Grow actual K/V from empty metadata
Exact input "aba" encoded once as [97,98,97]; reconstructed text "aba". There are 3 observed tokens and 3 active classes.
| Append | Observed ID | Saved new query rows | Available keys | Cumulative score cells | Retained old K/V exact? |
|---|---|---|---|---|---|
| 0 | a / ID97 | 1 | 1 | 1 | true |
| 1 | b / ID98 | 1 | 2 | 3 | true |
| 2 | a / ID97 | 1 | 3 | 6 | true |
Cached rows=3, reference rows=3, actual harness rows=6. Raw score cells=6 cached / 9 final reference. These are actual toy work counts, not timing.
Inspecting growth0, absolute query 0, key 0, class 0. These selectors only read saved records; trace selection and graded answers are unchanged.
Selected trace operation: setup. Matching arithmetic rows are marked current.
Before append0: zero cache entries, IDs=[], positions=[], K=[], V=[] are empty metadata. There is no before tensor or padded zero row.
After growth append 0
growth0_AfterKeys [1,1,1,2] · B,H,CachePosition,Dk · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.
growth0_AfterValues [1,1,1,2] · B,H,CachePosition,Dv · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Saved unrotated projected V in observed-prefix order.
| Cache row | Observed public ID | Absolute position | Already rotated K0 | K1 | Unrotated V0 | V1 |
|---|---|---|---|---|---|---|
| 0 | a / ID97 | 0 | 0.4472135954999579 | -0.4472135954999579 | 0.4472135954999579 | -0.4472135954999579 |
| Saved operation / equation | Actual inputs | Actual outputs |
|---|---|---|
| growth0_append after=[before,new]; retained_i=(before_i===after_i) True one-query append: local row0 is absolute position 0; 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=0 newID=97 newK0=0.4472135954999579 newK1=-0.4472135954999579 newV0=0.4472135954999579 newV1=-0.4472135954999579 | cacheEntries=1 afterID0=97 afterPosition0=0 afterK0=0.4472135954999579 afterK1=-0.4472135954999579 afterV0=0.4472135954999579 afterV1=-0.4472135954999579 retainedExact=1 |
growth0: actual query at absolute position 0
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.
growth0_RotatedQHeads [1,1,1,2] · B,H,Query,Dk · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New query rotated at absolute N; Query length1.
growth0_AfterKeys [1,1,1,2] · B,H,CachePosition,Dk · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.
growth0_Attentionprobabilities [1,1,1,1] · B,H,Query,Key · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Stable softmax over the complete cached key axis; Query length1.
| Saved stage | Feature0 | Feature1 |
|---|---|---|
| X | 1 | 0 |
| LN1 | 0.4472135954999579 | -0.4472135954999579 |
| AttentionOutput | 0.4472135954999579 | -0.4472135954999579 |
| R1 | 1.4472135954999579 | -0.4472135954999579 |
| LN2 | 0.6876854075163181 | -0.6876854075163181 |
| F | 0.6876854075163181 | 0 |
| Y | 2.134899003016276 | -0.4472135954999579 |
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.
| Pair | Absolute position | Unrotated pair | Angle | Cosine | Sine | Rotated pair |
|---|---|---|---|---|---|---|
| Q | 0 | [0.4472135954999579,-0.4472135954999579] | 0 | 1 | 0 | [0.4472135954999579,-0.4472135954999579] |
| K | 0 | [0.4472135954999579,-0.4472135954999579] | 0 | 1 | 0 | [0.4472135954999579,-0.4472135954999579] |
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.
| Key / observed ID | Rotated K pair | Raw dot | Scaled score | Allowed? | Attention probability | Unrotated V pair |
|---|---|---|---|---|---|---|
| 0 / a / ID97 | [0.4472135954999579,-0.4472135954999579] | 0.39999999999999997 | 0.28284271247461895 | true — allowed | 1 | [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.
| Saved operation / equation | Actual inputs | Actual outputs |
|---|---|---|
| growth0_score_0 product0=q0*k0; product1=q1*k1; raw=product0+product1; score=raw/sqrt(Dk) True one-query append: local row0 is absolute position 0; 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=0 j=0 Dk=2 divisor=1.4142135623730951 q0=0.4472135954999579 k0=0.4472135954999579 q1=-0.4472135954999579 k1=-0.4472135954999579 | product0=0.19999999999999998 product1=0.19999999999999998 raw=0.39999999999999997 score=0.28284271247461895 |
| growth0_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 0; 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=0 shift=0 score0=0.28284271247461895 keyPosition0=0 allowed0=1 | max=0.28284271247461895 logit0=0.28284271247461895 shifted0=0 term0=1 running0=1 denominator=1 p0=1 |
| growth0_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 0; no prior query or old K/V projection is recomputed. Multiply then immediately accumulate in ascending cached-key order. | d=0 p0=1 v0=0.4472135954999579 | product0=0.4472135954999579 running0=0.4472135954999579 value=0.4472135954999579 |
| growth0_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 0; no prior query or old K/V projection is recomputed. Multiply then immediately accumulate in ascending cached-key order. | d=1 p0=1 v0=-0.4472135954999579 | product0=-0.4472135954999579 running0=-0.4472135954999579 value=-0.4472135954999579 |
| Hidden coordinate | Affine Z | ReLU activation |
|---|---|---|
| 0 | 0.6876854075163181 | 0.6876854075163181 |
| 1 | -0.6876854075163181 | 0 |
| 2 | 0 | 0 |
growth0_Logits [1,3] · Position,Class · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Actual new Y times active U, then active Bias.
growth0_ChoiceP [3] · Class · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Terms/Denominator for active classes only, without clipping or padding.
| Compact class / public ID | Logit | Shifted logit | Exponential term | Stored probability |
|---|---|---|---|---|
| 0 / a / ID97 | 2.134899003016276 | 0 | 1 | 0.8376116959343609 |
| 1 / b / ID98 | -0.4472135954999579 | -2.582112598516234 | 0.0756140929478022 | 0.063335248630547 |
| 2 / EOS / ID512 | 0 | -2.134899003016276 | 0.11825653332669596 | 0.09905305543509206 |
Saved maximum=2.134899003016276, denominator=1.1938706262744982, logS=0.17720065589584005, LSE=2.312099658912116. Winner=a / ID97; probability=0.8376116959343609. Argmax uses strict computed logits and lowest compact index for exact ties. This winner does not select the observed input.
| Saved operation / equation | Actual inputs | Actual outputs |
|---|---|---|
| growth0_readout_0 product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias True one-query append: local row0 is absolute position 0; 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=2.134899003016276 u0=1 y1=-0.4472135954999579 u1=0 bias=0 | product0=2.134899003016276 product1=0 sum=2.134899003016276 logit=2.134899003016276 |
| growth0_class_max max=max(z0,...,z[V-1]) True one-query append: local row0 is absolute position 0; 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=2.134899003016276 z1=-0.4472135954999579 z2=0 | max=2.134899003016276 |
| growth0_class_exp_0 shifted=logit-max; term=exp(shifted) True one-query append: local row0 is absolute position 0; 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=2.134899003016276 max=2.134899003016276 | shifted=0 term=1 |
| growth0_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 0; 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.0756140929478022 term2=0.11825653332669596 max=2.134899003016276 | running0=1 running1=1.0756140929478022 running2=1.1938706262744982 denominator=1.1938706262744982 logS=0.17720065589584005 lse=2.312099658912116 |
| growth0_class_probability_0 probability=term/S True one-query append: local row0 is absolute position 0; 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.1938706262744982 | probability=0.8376116959343609 |
| growth0_class_argmax strict greater-than updates the winner; exact ties retain lowest compact index True one-query append: local row0 is absolute position 0; 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=2.134899003016276 z1=-0.4472135954999579 z2=0 | nextRow=0 nextID=97 nextProbability=0.8376116959343609 |
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.
| Saved operation / equation | Actual inputs | Actual outputs |
|---|---|---|
| growth0_input_0 inputRow=compactRow(newID); X=E[inputRow,:] True one-query append: local row0 is absolute position 0; no prior query or old K/V projection is recomputed. Numeric helpers permit observed EOS; outer wrappers separately implement logical EOS stopping. | position=0 newID=97 | inputRow=0 x0=1 x1=0 |
| growth0_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 0; 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 |
| growth0_ln1_0_feature_0 normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta True one-query append: local row0 is absolute position 0; 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 |
| growth0_ln1_0_feature_1 normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta True one-query append: local row0 is absolute position 0; 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 |
| growth0_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 0; 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 |
| growth0_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 0; 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 |
| growth0_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 0; 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 |
| growth0_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 0; 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 |
| growth0_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 0; 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 |
| growth0_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 0; 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 |
| growth0_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 0; 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 |
| growth0_heads_reshape_Q [B,T,H*F] → [B,T,H,F]; feature=h*F+f True one-query append: local row0 is absolute position 0; 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 |
| growth0_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 0; 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 |
| growth0_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 0; 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 |
| growth0_heads_reshape_K [B,T,H*F] → [B,T,H,F]; feature=h*F+f True one-query append: local row0 is absolute position 0; 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 |
| growth0_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 0; 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 |
| growth0_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 0; 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 |
| growth0_heads_reshape_V [B,T,H*F] → [B,T,H,F]; feature=h*F+f True one-query append: local row0 is absolute position 0; 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 |
| growth0_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 0; 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 |
| growth0_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 0; 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 |
| growth0_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 0; 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=0 x0=0.4472135954999579 x1=-0.4472135954999579 base=10000 exponent=0 | frequency=1 angle=0 cos=1 sin=0 product0=0.4472135954999579 product1=0 product2=0 product3=-0.4472135954999579 rotated0=0.4472135954999579 rotated1=-0.4472135954999579 |
| growth0_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 0; 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=0 x0=0.4472135954999579 x1=-0.4472135954999579 base=10000 exponent=0 | frequency=1 angle=0 cos=1 sin=0 product0=0.4472135954999579 product1=0 product2=0 product3=-0.4472135954999579 rotated0=0.4472135954999579 rotated1=-0.4472135954999579 |
| growth0_append after=[before,new]; retained_i=(before_i===after_i) True one-query append: local row0 is absolute position 0; 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=0 newID=97 newK0=0.4472135954999579 newK1=-0.4472135954999579 newV0=0.4472135954999579 newV1=-0.4472135954999579 | cacheEntries=1 afterID0=97 afterPosition0=0 afterK0=0.4472135954999579 afterK1=-0.4472135954999579 afterV0=0.4472135954999579 afterV1=-0.4472135954999579 retainedExact=1 |
| growth0_score_0 product0=q0*k0; product1=q1*k1; raw=product0+product1; score=raw/sqrt(Dk) True one-query append: local row0 is absolute position 0; 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=0 j=0 Dk=2 divisor=1.4142135623730951 q0=0.4472135954999579 k0=0.4472135954999579 q1=-0.4472135954999579 k1=-0.4472135954999579 | product0=0.19999999999999998 product1=0.19999999999999998 raw=0.39999999999999997 score=0.28284271247461895 |
| growth0_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 0; 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=0 shift=0 score0=0.28284271247461895 keyPosition0=0 allowed0=1 | max=0.28284271247461895 logit0=0.28284271247461895 shifted0=0 term0=1 running0=1 denominator=1 p0=1 |
| growth0_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 0; no prior query or old K/V projection is recomputed. Multiply then immediately accumulate in ascending cached-key order. | d=0 p0=1 v0=0.4472135954999579 | product0=0.4472135954999579 running0=0.4472135954999579 value=0.4472135954999579 |
| growth0_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 0; no prior query or old K/V projection is recomputed. Multiply then immediately accumulate in ascending cached-key order. | d=1 p0=1 v0=-0.4472135954999579 | product0=-0.4472135954999579 running0=-0.4472135954999579 value=-0.4472135954999579 |
| growth0_concat C[d]=OHeads[0,0,0,d]; sourceOffset=d; destinationOffset=d True one-query append: local row0 is absolute position 0; 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.4472135954999579 sourceOffset1=1 sourceValue1=-0.4472135954999579 | destinationOffset0=0 c0=0.4472135954999579 destinationOffset1=1 c1=-0.4472135954999579 |
| growth0_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 0; 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.4472135954999579 w0=1 c1=-0.4472135954999579 w1=0 | product0=0.4472135954999579 running0=0.4472135954999579 product1=0 running1=0.4472135954999579 value=0.4472135954999579 |
| growth0_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 0; 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.4472135954999579 w0=0 c1=-0.4472135954999579 w1=1 | product0=0 running0=0 product1=-0.4472135954999579 running1=-0.4472135954999579 value=-0.4472135954999579 |
| growth0_residual1 value_d=left_d+right_d True one-query append: local row0 is absolute position 0; 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.4472135954999579 left1=0 right1=-0.4472135954999579 | value0=1.4472135954999579 value1=-0.4472135954999579 |
| growth0_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 0; 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.4472135954999579 x1=-0.4472135954999579 epsilon=1 | sum=1 mean=0.5 centered0=0.9472135954999579 centered1=-0.9472135954999579 square0=0.8972135954999578 square1=0.8972135954999578 squareSum=1.7944271909999157 variance=0.8972135954999578 variancePlusEpsilon=1.8972135954999578 denominator=1.3773937692250382 |
| growth0_ln2_0_feature_0 normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta True one-query append: local row0 is absolute position 0; 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.9472135954999579 denominator=1.3773937692250382 gamma=1 beta=0 | normalized=0.6876854075163181 scaled=0.6876854075163181 value=0.6876854075163181 |
| growth0_ln2_0_feature_1 normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta True one-query append: local row0 is absolute position 0; 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.9472135954999579 denominator=1.3773937692250382 gamma=1 beta=0 | normalized=-0.6876854075163181 scaled=-0.6876854075163181 value=-0.6876854075163181 |
| growth0_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 0; 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.6876854075163181 x1=-0.6876854075163181 w0=1 w1=0 bias=0 | product0=0.6876854075163181 product1=0 sum=0.6876854075163181 preactivation=0.6876854075163181 |
| growth0_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 0; 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.6876854075163181 x1=-0.6876854075163181 w0=0 w1=1 bias=0 | product0=0 product1=-0.6876854075163181 sum=-0.6876854075163181 preactivation=-0.6876854075163181 |
| growth0_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 0; 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.6876854075163181 x1=-0.6876854075163181 w0=0 w1=0 bias=0 | product0=0 product1=0 sum=0 preactivation=0 |
| growth0_ffn_relu_0_0_0 activation=max(0,preactivation) True one-query append: local row0 is absolute position 0; 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.6876854075163181 | activation=0.6876854075163181 |
| growth0_ffn_relu_0_0_1 activation=max(0,preactivation) True one-query append: local row0 is absolute position 0; 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.6876854075163181 | activation=0 |
| growth0_ffn_relu_0_0_2 activation=max(0,preactivation) True one-query append: local row0 is absolute position 0; 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 |
| growth0_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 0; 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.6876854075163181 w0=1 h1=0 w1=0 h2=0 w2=0 bias=0 | product0=0.6876854075163181 product1=0 product2=0 running0=0.6876854075163181 running1=0.6876854075163181 running2=0.6876854075163181 sum=0.6876854075163181 value=0.6876854075163181 |
| growth0_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 0; 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.6876854075163181 w0=0 h1=0 w1=1 h2=0 w2=0 bias=0 | product0=0 product1=0 product2=0 running0=0 running1=0 running2=0 sum=0 value=0 |
| growth0_residual2 value_d=left_d+right_d True one-query append: local row0 is absolute position 0; 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.4472135954999579 right0=0.6876854075163181 left1=-0.4472135954999579 right1=0 | value0=2.134899003016276 value1=-0.4472135954999579 |
| growth0_readout_0 product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias True one-query append: local row0 is absolute position 0; 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=2.134899003016276 u0=1 y1=-0.4472135954999579 u1=0 bias=0 | product0=2.134899003016276 product1=0 sum=2.134899003016276 logit=2.134899003016276 |
| growth0_readout_1 product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias True one-query append: local row0 is absolute position 0; 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=2.134899003016276 u0=0 y1=-0.4472135954999579 u1=1 bias=0 | product0=0 product1=-0.4472135954999579 sum=-0.4472135954999579 logit=-0.4472135954999579 |
| growth0_readout_2 product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias True one-query append: local row0 is absolute position 0; 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=2.134899003016276 u0=0 y1=-0.4472135954999579 u1=0 bias=0 | product0=0 product1=0 sum=0 logit=0 |
| growth0_class_max max=max(z0,...,z[V-1]) True one-query append: local row0 is absolute position 0; 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=2.134899003016276 z1=-0.4472135954999579 z2=0 | max=2.134899003016276 |
| growth0_class_exp_0 shifted=logit-max; term=exp(shifted) True one-query append: local row0 is absolute position 0; 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=2.134899003016276 max=2.134899003016276 | shifted=0 term=1 |
| growth0_class_exp_1 shifted=logit-max; term=exp(shifted) True one-query append: local row0 is absolute position 0; 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.4472135954999579 max=2.134899003016276 | shifted=-2.582112598516234 term=0.0756140929478022 |
| growth0_class_exp_2 shifted=logit-max; term=exp(shifted) True one-query append: local row0 is absolute position 0; 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=2.134899003016276 | shifted=-2.134899003016276 term=0.11825653332669596 |
| growth0_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 0; 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.0756140929478022 term2=0.11825653332669596 max=2.134899003016276 | running0=1 running1=1.0756140929478022 running2=1.1938706262744982 denominator=1.1938706262744982 logS=0.17720065589584005 lse=2.312099658912116 |
| growth0_class_probability_0 probability=term/S True one-query append: local row0 is absolute position 0; 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.1938706262744982 | probability=0.8376116959343609 |
| growth0_class_probability_1 probability=term/S True one-query append: local row0 is absolute position 0; 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.0756140929478022 denominator=1.1938706262744982 | probability=0.063335248630547 |
| growth0_class_probability_2 probability=term/S True one-query append: local row0 is absolute position 0; 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.11825653332669596 denominator=1.1938706262744982 | probability=0.09905305543509206 |
| growth0_class_argmax strict greater-than updates the winner; exact ties retain lowest compact index True one-query append: local row0 is absolute position 0; 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=2.134899003016276 z1=-0.4472135954999579 z2=0 | nextRow=0 nextID=97 nextProbability=0.8376116959343609 |
All saved path tensor shapes and provenance
growth0_AllClassIDs [5] · ModelRow · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. All possible compact model rows; public IDs are labels.
growth0_ClassIDs [3] · Class · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Active compact prefix; V=3+merges.
growth0_E [5,2] · ModelRow,D · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. All ten validated editable embeddings, including inactive rows.
growth0_U [2,5] · D,ModelRow · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. All ten validated readout weights; active prefix alone produces logits.
growth0_Bias [5] · ModelRow · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. All five validated biases; inactive columns remain outside the distribution.
growth0_InputIDs [1] · LocalPosition · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Exactly one new observed token is processed.
growth0_InputRows [1] · LocalPosition · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Compact embedding row for the new token.
growth0_AbsoluteQueryPosition [1] · Query · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Absolute N, distinct from the single local query index0.
growth0_X [1,1,2] · B,T,D · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Only the new embedding row; local T=1, absolute position is saved separately.
growth0_LN1 [1,1,2] · B,T,D · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New-row feature LayerNorm; population variance, epsilon1, gamma1, beta0.
growth0_ProjectionX [1,1,2] · B,T,D · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. Active token rows; D=2 input features always retained.
growth0_ProjectionWQ [2,2] · D,QueryFeature · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. Query columns packed by h*Dk+f from wq{d}{h}{f}.
growth0_ProjectionWK [2,2] · D,KeyFeature · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. Key columns packed by h*Dk+f from wk{d}{h}{f}.
growth0_ProjectionWV [2,2] · D,ValueFeature · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. Value columns packed by h*Dv+f from wv{d}{h}{f}.
growth0_ProjectionQConcat [1,1,2] · B,T,QueryFeature · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. XWQ; each packed coordinate has two products and one sum.
growth0_ProjectionKConcat [1,1,2] · B,T,KeyFeature · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. XWK; each packed coordinate has two products and one sum.
growth0_ProjectionVConcat [1,1,2] · B,T,ValueFeature · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. XWV; values are projected separately from queries and keys.
growth0_ProjectionQSplit [1,1,1,2] · B,T,H,Dk · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. QConcat reshaped without changing flat order; feature=h*F+f.
growth0_ProjectionQHeads [1,1,1,2] · B,H,T,Dk · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; 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.
growth0_ProjectionKSplit [1,1,1,2] · B,T,H,Dk · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. KConcat reshaped without changing flat order; feature=h*F+f.
growth0_ProjectionKHeads [1,1,1,2] · B,H,T,Dk · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; 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.
growth0_ProjectionVSplit [1,1,1,2] · B,T,H,Dv · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. VConcat reshaped without changing flat order; feature=h*F+f.
growth0_ProjectionVHeads [1,1,1,2] · B,H,T,Dv · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; 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.
growth0_RotatedQHeads [1,1,1,2] · B,H,Query,Dk · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New query rotated at absolute N; Query length1.
growth0_NewRotatedKHeads [1,1,1,2] · B,H,NewPosition,Dk · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Only the newly computed key, rotated once at absolute N.
growth0_RoPEAngles [1] · Query · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Actual absolute N times frequency1, radians.
growth0_RoPECos [1] · Query · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Cosine used by new Q/K rotations.
growth0_RoPESin [1] · Query · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Sine used by new Q/K rotations.
growth0_AfterIDs [1] · CachePosition · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Ordered observed public IDs; cache coherence is an external-helper input precondition.
growth0_AfterPositions [1] · CachePosition · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Absolute positions 0..N-1, not local append-query indices.
growth0_AfterKeys [1,1,1,2] · B,H,CachePosition,Dk · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.
growth0_AfterValues [1,1,1,2] · B,H,CachePosition,Dv · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Saved unrotated projected V in observed-prefix order.
growth0_Attentionraw [1,1,1,1] · B,H,Query,Key · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Actual two-product new Q dot every cached K.
growth0_Attentionscores [1,1,1,1] · B,H,Query,Key · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Raw dot products divided by sqrt(Dk=2).
growth0_Attentionallowed [1,1,1,1] · B,H,Query,Key · bool · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Allowed iff cached absolute key position <= absolute query N.
growth0_Attentionlogits [1,1,1,1] · B,H,Query,Key · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Actual scaled scores plus the fixed common shift0.
growth0_Attentionprobabilities [1,1,1,1] · B,H,Query,Key · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Stable softmax over the complete cached key axis; Query length1.
growth0_AttentionOHeads [1,1,1,2] · B,H,Query,Dv · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New query weighted sum of all unrotated cached V.
growth0_AttentionC [1,1,2] · B,T,JoinedValue · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. One-head Query to local token-major joined-feature copy.
growth0_AttentionWO [2,2] · JoinedValue,D · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Explicit identity2 output projection.
growth0_AttentionOutput [1,1,2] · B,T,D · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. C WO for one local row, with explicit identity WO.
growth0_R1 [1,1,2] · B,T,D · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Exact named-shape addition of X and AttentionOutput; no broadcasting.
growth0_LN2 [1,1,2] · B,T,D · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New-row feature LayerNorm of R1; population variance, epsilon1, gamma1, beta0.
growth0_W1 [2,3] · D,HiddenFeature · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.
growth0_b1 [3] · HiddenFeature · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Shared hidden bias, added after the two products.
growth0_Z [1,1,3] · B,T,HiddenFeature · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Hidden preactivations X W1+b1; no batch or token mixing.
growth0_Hidden [1,1,3] · B,T,HiddenFeature · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. ReLU(Z)=max(0,Z), before the second affine layer.
growth0_W2 [3,2] · HiddenFeature,D · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Shared hidden-to-output weights, f2{m}{d}.
growth0_b2 [2] · D · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Shared output bias, added after all three running sums.
growth0_F [1,1,2] · B,T,D · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. ReLU(X W1+b1) W2+b2, independently per token with shared parameters.
growth0_Y [1,1,2] · B,T,D · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Exact named-shape addition of R1 and F; no broadcasting.
growth0_Logits [1,3] · Position,Class · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Actual new Y times active U, then active Bias.
growth0_ChoiceClassIDs [3] · Class · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Active compact prefix [97,98,512,256,257]; public IDs are labels, not offsets.
growth0_ChoiceZ [3] · Class · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Actual finite computed input logits; no derived-input clipping.
growth0_ChoiceShifted [3] · Class · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Z minus the saved active maximum.
growth0_ChoiceTerms [3] · Class · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Actual exp(Shifted), before normalization.
growth0_ChoiceDenominator [1] · Scalar · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Actual left-to-right sum of active shifted terms.
growth0_ChoiceLogS [1] · Scalar · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Natural logarithm of Denominator.
growth0_ChoiceLSE [1] · Scalar · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Saved max+LogS in binary64.
growth0_ChoiceP [3] · Class · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Terms/Denominator for active classes only, without clipping or padding.
growth0_ChoiceNextRow [1] · Decision · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Lowest compact index among highest computed logits.
growth0_ChoiceNextID [1] · Decision · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Public class ID gathered at NextRow.
growth0_ChoiceNextProbability [1] · Decision · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Stored P gathered at the computed-logit winner.
Six comparisons from real operands
Read every coordinate, not only the winning ID. Delta is cached−full; the running maximum follows flat storage order. These are computed differences, never a forced zero.
K: maximum absolute error 0
CompareKDelta [3,2] · Position,Dk · float64 · precision 8 · Actual cached-full subtraction.
| Flat coordinate | Cached | Full | Signed delta | Absolute error | Running maximum |
|---|---|---|---|---|---|
| 0 | 0.4472135954999579 | 0.4472135954999579 | 0 | 0 | 0 |
| 1 | -0.4472135954999579 | -0.4472135954999579 | 0 | 0 | 0 |
| 2 | -0.6179478014890387 | -0.6179478014890387 | 0 | 0 | 0 |
| 3 | -0.1346867277606211 | -0.1346867277606211 | 0 | 0 | 0 |
| 4 | 0.22054364860139217 | 0.22054364860139217 | 0 | 0 | 0 |
| 5 | 0.5927566946577538 | 0.5927566946577538 | 0 | 0 | 0 |
| Saved operation / equation | Actual inputs | Actual outputs |
|---|---|---|
| compare_K delta_i=cached_i-full_i; absolute_i=abs(delta_i); runningMax_i=max(previous,absolute_i) These are actual saved operands, subtractions and maxima. No zero fill, rounding or universal cross-library bitwise assertion is used. | count=6 initialMaximum=0 cached0=0.4472135954999579 full0=0.4472135954999579 cached1=-0.4472135954999579 full1=-0.4472135954999579 cached2=-0.6179478014890387 full2=-0.6179478014890387 cached3=-0.1346867277606211 full3=-0.1346867277606211 cached4=0.22054364860139217 full4=0.22054364860139217 cached5=0.5927566946577538 full5=0.5927566946577538 | delta0=0 absolute0=0 runningMax0=0 delta1=0 absolute1=0 runningMax1=0 delta2=0 absolute2=0 runningMax2=0 delta3=0 absolute3=0 runningMax3=0 delta4=0 absolute4=0 runningMax4=0 delta5=0 absolute5=0 runningMax5=0 maximum=0 |
V: maximum absolute error 0
CompareVDelta [3,2] · Position,Dv · float64 · precision 8 · Actual cached-full subtraction.
| Flat coordinate | Cached | Full | Signed delta | Absolute error | Running maximum |
|---|---|---|---|---|---|
| 0 | 0.4472135954999579 | 0.4472135954999579 | 0 | 0 | 0 |
| 1 | -0.4472135954999579 | -0.4472135954999579 | 0 | 0 | 0 |
| 2 | -0.4472135954999579 | -0.4472135954999579 | 0 | 0 | 0 |
| 3 | 0.4472135954999579 | 0.4472135954999579 | 0 | 0 | 0 |
| 4 | 0.4472135954999579 | 0.4472135954999579 | 0 | 0 | 0 |
| 5 | -0.4472135954999579 | -0.4472135954999579 | 0 | 0 | 0 |
| Saved operation / equation | Actual inputs | Actual outputs |
|---|---|---|
| compare_V delta_i=cached_i-full_i; absolute_i=abs(delta_i); runningMax_i=max(previous,absolute_i) These are actual saved operands, subtractions and maxima. No zero fill, rounding or universal cross-library bitwise assertion is used. | count=6 initialMaximum=0 cached0=0.4472135954999579 full0=0.4472135954999579 cached1=-0.4472135954999579 full1=-0.4472135954999579 cached2=-0.4472135954999579 full2=-0.4472135954999579 cached3=0.4472135954999579 full3=0.4472135954999579 cached4=0.4472135954999579 full4=0.4472135954999579 cached5=-0.4472135954999579 full5=-0.4472135954999579 | delta0=0 absolute0=0 runningMax0=0 delta1=0 absolute1=0 runningMax1=0 delta2=0 absolute2=0 runningMax2=0 delta3=0 absolute3=0 runningMax3=0 delta4=0 absolute4=0 runningMax4=0 delta5=0 absolute5=0 runningMax5=0 maximum=0 |
Attention: maximum absolute error 0
CompareAttentionDelta [3,2] · Position,Dv · float64 · precision 8 · Actual cached-full subtraction.
| Flat coordinate | Cached | Full | Signed delta | Absolute error | Running maximum |
|---|---|---|---|---|---|
| 0 | 0.4472135954999579 | 0.4472135954999579 | 0 | 0 | 0 |
| 1 | -0.4472135954999579 | -0.4472135954999579 | 0 | 0 | 0 |
| 2 | -0.0959051290352784 | -0.0959051290352784 | 0 | 0 | 0 |
| 3 | 0.0959051290352784 | 0.0959051290352784 | 0 | 0 | 0 |
| 4 | 0.19749416642975512 | 0.19749416642975512 | 0 | 0 | 0 |
| 5 | -0.19749416642975512 | -0.19749416642975512 | 0 | 0 | 0 |
| Saved operation / equation | Actual inputs | Actual outputs |
|---|---|---|
| compare_Attention delta_i=cached_i-full_i; absolute_i=abs(delta_i); runningMax_i=max(previous,absolute_i) These are actual saved operands, subtractions and maxima. No zero fill, rounding or universal cross-library bitwise assertion is used. | count=6 initialMaximum=0 cached0=0.4472135954999579 full0=0.4472135954999579 cached1=-0.4472135954999579 full1=-0.4472135954999579 cached2=-0.0959051290352784 full2=-0.0959051290352784 cached3=0.0959051290352784 full3=0.0959051290352784 cached4=0.19749416642975512 full4=0.19749416642975512 cached5=-0.19749416642975512 full5=-0.19749416642975512 | delta0=0 absolute0=0 runningMax0=0 delta1=0 absolute1=0 runningMax1=0 delta2=0 absolute2=0 runningMax2=0 delta3=0 absolute3=0 runningMax3=0 delta4=0 absolute4=0 runningMax4=0 delta5=0 absolute5=0 runningMax5=0 maximum=0 |
Y: maximum absolute error 0
CompareYDelta [3,2] · Position,D · float64 · precision 8 · Actual cached-full subtraction.
| Flat coordinate | Cached | Full | Signed delta | Absolute error | Running maximum |
|---|---|---|---|---|---|
| 0 | 2.134899003016276 | 2.134899003016276 | 0 | 0 | 0 |
| 1 | -0.4472135954999579 | -0.4472135954999579 | 0 | 0 | 0 |
| 2 | -0.0959051290352784 | -0.0959051290352784 | 0 | 0 | 0 |
| 3 | 1.6078120278761694 | 1.6078120278761694 | 0 | 0 | 0 |
| 4 | 1.7695763183879745 | 1.7695763183879745 | 0 | 0 | 0 |
| 5 | -0.19749416642975512 | -0.19749416642975512 | 0 | 0 | 0 |
| Saved operation / equation | Actual inputs | Actual outputs |
|---|---|---|
| compare_Y delta_i=cached_i-full_i; absolute_i=abs(delta_i); runningMax_i=max(previous,absolute_i) These are actual saved operands, subtractions and maxima. No zero fill, rounding or universal cross-library bitwise assertion is used. | count=6 initialMaximum=0 cached0=2.134899003016276 full0=2.134899003016276 cached1=-0.4472135954999579 full1=-0.4472135954999579 cached2=-0.0959051290352784 full2=-0.0959051290352784 cached3=1.6078120278761694 full3=1.6078120278761694 cached4=1.7695763183879745 full4=1.7695763183879745 cached5=-0.19749416642975512 full5=-0.19749416642975512 | delta0=0 absolute0=0 runningMax0=0 delta1=0 absolute1=0 runningMax1=0 delta2=0 absolute2=0 runningMax2=0 delta3=0 absolute3=0 runningMax3=0 delta4=0 absolute4=0 runningMax4=0 delta5=0 absolute5=0 runningMax5=0 maximum=0 |
Logits: maximum absolute error 0
CompareLogitsDelta [3,3] · Position,Class · float64 · precision 8 · Actual cached-full subtraction.
| Flat coordinate | Cached | Full | Signed delta | Absolute error | Running maximum |
|---|---|---|---|---|---|
| 0 | 2.134899003016276 | 2.134899003016276 | 0 | 0 | 0 |
| 1 | -0.4472135954999579 | -0.4472135954999579 | 0 | 0 | 0 |
| 2 | 0 | 0 | 0 | 0 | 0 |
| 3 | -0.0959051290352784 | -0.0959051290352784 | 0 | 0 | 0 |
| 4 | 1.6078120278761694 | 1.6078120278761694 | 0 | 0 | 0 |
| 5 | 0 | 0 | 0 | 0 | 0 |
| 6 | 1.7695763183879745 | 1.7695763183879745 | 0 | 0 | 0 |
| 7 | -0.19749416642975512 | -0.19749416642975512 | 0 | 0 | 0 |
| 8 | 0 | 0 | 0 | 0 | 0 |
| Saved operation / equation | Actual inputs | Actual outputs |
|---|---|---|
| compare_Logits delta_i=cached_i-full_i; absolute_i=abs(delta_i); runningMax_i=max(previous,absolute_i) These are actual saved operands, subtractions and maxima. No zero fill, rounding or universal cross-library bitwise assertion is used. | count=9 initialMaximum=0 cached0=2.134899003016276 full0=2.134899003016276 cached1=-0.4472135954999579 full1=-0.4472135954999579 cached2=0 full2=0 cached3=-0.0959051290352784 full3=-0.0959051290352784 cached4=1.6078120278761694 full4=1.6078120278761694 cached5=0 full5=0 cached6=1.7695763183879745 full6=1.7695763183879745 cached7=-0.19749416642975512 full7=-0.19749416642975512 cached8=0 full8=0 | delta0=0 absolute0=0 runningMax0=0 delta1=0 absolute1=0 runningMax1=0 delta2=0 absolute2=0 runningMax2=0 delta3=0 absolute3=0 runningMax3=0 delta4=0 absolute4=0 runningMax4=0 delta5=0 absolute5=0 runningMax5=0 delta6=0 absolute6=0 runningMax6=0 delta7=0 absolute7=0 runningMax7=0 delta8=0 absolute8=0 runningMax8=0 maximum=0 |
P: maximum absolute error 0
ComparePDelta [3,3] · Position,Class · float64 · precision 8 · Actual cached-full subtraction.
| Flat coordinate | Cached | Full | Signed delta | Absolute error | Running maximum |
|---|---|---|---|---|---|
| 0 | 0.8376116959343609 | 0.8376116959343609 | 0 | 0 | 0 |
| 1 | 0.063335248630547 | 0.063335248630547 | 0 | 0 | 0 |
| 2 | 0.09905305543509206 | 0.09905305543509206 | 0 | 0 | 0 |
| 3 | 0.13166578760192524 | 0.13166578760192524 | 0 | 0 | 0 |
| 4 | 0.7234156524931242 | 0.7234156524931242 | 0 | 0 | 0 |
| 5 | 0.14491855990495064 | 0.14491855990495064 | 0 | 0 | 0 |
| 6 | 0.7632007976561935 | 0.7632007976561935 | 0 | 0 | 0 |
| 7 | 0.1067458398578614 | 0.1067458398578614 | 0 | 0 | 0 |
| 8 | 0.13005336248594518 | 0.13005336248594518 | 0 | 0 | 0 |
| Saved operation / equation | Actual inputs | Actual outputs |
|---|---|---|
| compare_P delta_i=cached_i-full_i; absolute_i=abs(delta_i); runningMax_i=max(previous,absolute_i) These are actual saved operands, subtractions and maxima. No zero fill, rounding or universal cross-library bitwise assertion is used. | count=9 initialMaximum=0 cached0=0.8376116959343609 full0=0.8376116959343609 cached1=0.063335248630547 full1=0.063335248630547 cached2=0.09905305543509206 full2=0.09905305543509206 cached3=0.13166578760192524 full3=0.13166578760192524 cached4=0.7234156524931242 full4=0.7234156524931242 cached5=0.14491855990495064 full5=0.14491855990495064 cached6=0.7632007976561935 full6=0.7632007976561935 cached7=0.1067458398578614 full7=0.1067458398578614 cached8=0.13005336248594518 full8=0.13005336248594518 | delta0=0 absolute0=0 runningMax0=0 delta1=0 absolute1=0 runningMax1=0 delta2=0 absolute2=0 runningMax2=0 delta3=0 absolute3=0 runningMax3=0 delta4=0 absolute4=0 runningMax4=0 delta5=0 absolute5=0 runningMax5=0 delta6=0 absolute6=0 runningMax6=0 delta7=0 absolute7=0 runningMax7=0 delta8=0 absolute8=0 runningMax8=0 maximum=0 |
Actual prompt bytes, BPE rules and reconstruction
Fixed corpus="abab". Rules=[]. Expansions=[]. Labels=["ID 97, bytes [97]","ID 98, bytes [98]","ID 97, bytes [97]"]. Zero merges requested: no training round or pair selection occurs.
| Saved operation / equation | Actual inputs | Actual outputs |
|---|---|---|
| tokenizer_setup byte IDs=0..255; learned ID=256+rank; EOS=512; each text field<=24 UTF-8 bytes Validate every raw field before corpus then target Unicode semantics. Train on the corpus byte stream including spaces; encode the separate target using learned ranks. No normalization, word splitting, inferred EOS or pretrained vocabulary is used. | requestedMerges=0 eos=0 | corpusUnits=4 corpusScalars=4 utf16Units=3 scalarCount=3 byteBound=24 mergeBase=256 mergeBound=4 EOS=512 |
| tokenizer_corpus_scalar_0 supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs. | scalarIndex=0 utf16Offset=0 utf16Width=1 codePoint=97 unit0=97 | byteOffset=0 byteWidth=1 payload0=97 byte0=97 |
| tokenizer_corpus_scalar_1 supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs. | scalarIndex=1 utf16Offset=1 utf16Width=1 codePoint=98 unit0=98 | byteOffset=1 byteWidth=1 payload0=98 byte0=98 |
| tokenizer_corpus_scalar_2 supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs. | scalarIndex=2 utf16Offset=2 utf16Width=1 codePoint=97 unit0=97 | byteOffset=2 byteWidth=1 payload0=97 byte0=97 |
| tokenizer_corpus_scalar_3 supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs. | scalarIndex=3 utf16Offset=3 utf16Width=1 codePoint=98 unit0=98 | byteOffset=3 byteWidth=1 payload0=98 byte0=98 |
| tokenizer_source_scalar_0 supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs. | scalarIndex=0 utf16Offset=0 utf16Width=1 codePoint=97 unit0=97 | byteOffset=0 byteWidth=1 payload0=97 byte0=97 |
| tokenizer_source_scalar_1 supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs. | scalarIndex=1 utf16Offset=1 utf16Width=1 codePoint=98 unit0=98 | byteOffset=1 byteWidth=1 payload0=98 byte0=98 |
| tokenizer_source_scalar_2 supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs. | scalarIndex=2 utf16Offset=2 utf16Width=1 codePoint=97 unit0=97 | byteOffset=2 byteWidth=1 payload0=97 byte0=97 |
| tokenizer_corpus_expand_0 ID → validated byte expansion Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used. | index=0 id=97 | byteOffset=0 byteWidth=1 byte0=97 |
| tokenizer_corpus_expand_1 ID → validated byte expansion Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used. | index=1 id=98 | byteOffset=1 byteWidth=1 byte0=98 |
| tokenizer_corpus_expand_2 ID → validated byte expansion Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used. | index=2 id=97 | byteOffset=2 byteWidth=1 byte0=97 |
| tokenizer_corpus_expand_3 ID → validated byte expansion Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used. | index=3 id=98 | byteOffset=3 byteWidth=1 byte0=98 |
| tokenizer_corpus_decode_0 accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved. | scalarIndex=0 byteOffset=0 byteWidth=1 byte0=97 | payload0=97 accumulator0=97 codePoint=97 utf16Width=1 unit0=97 |
| tokenizer_corpus_decode_1 accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved. | scalarIndex=1 byteOffset=1 byteWidth=1 byte0=98 | payload0=98 accumulator0=98 codePoint=98 utf16Width=1 unit0=98 |
| tokenizer_corpus_decode_2 accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved. | scalarIndex=2 byteOffset=2 byteWidth=1 byte0=97 | payload0=97 accumulator0=97 codePoint=97 utf16Width=1 unit0=97 |
| tokenizer_corpus_decode_3 accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved. | scalarIndex=3 byteOffset=3 byteWidth=1 byte0=98 | payload0=98 accumulator0=98 codePoint=98 utf16Width=1 unit0=98 |
| tokenizer_target_expand_0 ID → validated byte expansion Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used. | index=0 id=97 | byteOffset=0 byteWidth=1 byte0=97 |
| tokenizer_target_expand_1 ID → validated byte expansion Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used. | index=1 id=98 | byteOffset=1 byteWidth=1 byte0=98 |
| tokenizer_target_expand_2 ID → validated byte expansion Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used. | index=2 id=97 | byteOffset=2 byteWidth=1 byte0=97 |
| tokenizer_target_decode_0 accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved. | scalarIndex=0 byteOffset=0 byteWidth=1 byte0=97 | payload0=97 accumulator0=97 codePoint=97 utf16Width=1 unit0=97 |
| tokenizer_target_decode_1 accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved. | scalarIndex=1 byteOffset=1 byteWidth=1 byte0=98 | payload0=98 accumulator0=98 codePoint=98 utf16Width=1 unit0=98 |
| tokenizer_target_decode_2 accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved. | scalarIndex=2 byteOffset=2 byteWidth=1 byte0=97 | payload0=97 accumulator0=97 codePoint=97 utf16Width=1 unit0=97 |
| tokenizer_roundtrip corpusEqual=(corpusDecoded===corpus); equal=(targetDecoded===text) Expand real corpus and target IDs separately, concatenate real bytes, strictly reconstruct Unicode scalars, and only then compare strings. Empty content reconstructs the empty string; optional target EOS emits no bytes. | corpusOriginalUnits=4 corpusDecodedUnits=4 corpusDecodedByteCount=4 originalUnits=3 decodedUnits=3 decodedByteCount=3 | corpusTokens=4 tokenCount=3 corpusEqual=1 equal=1 |
Cache trust, model identity and numerical limits
External helper callers must supply coherent K/V. Finite metadata, freezing and structural checks do not certify arbitrary supplied payloads. The app constructs every cache internally.
All26 numeric parameters must agree under numeric ===, including readout and inactive embeddings; signed zeros are equivalent. This is a conservative reuse policy, not the minimal mathematical K/V dependency.
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.
Exact unchanged copies within one implementation are a separate fact from independently witnessing numeric coherence. Exact-real equivalence does not promise bitwise agreement across math libraries. Stored binary64 operands and actual computed differences remain visible; no timing or trained-model quality is measured.
Inspect all stored values, text metadata and tensor storage
Every scalar output, including flattened operation outputs
Exact text evidence from the same record
These are the stored values, shown without display rounding. Each tensor names its axes, dtype and display precision. Empty arrays are omitted rather than padded.
tokenizer_CorpusCodePoints
Scalars=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Validated Unicode scalars in exact input order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
| 3 | 98 |
tokenizer_CorpusUTF16Offsets
Scalars=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Zero-based UTF-16 storage offset for each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
tokenizer_CorpusUTF16Widths
Scalars=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. UTF-16 storage units consumed by each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
tokenizer_CorpusByteOffsets
Scalars=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Zero-based UTF-8 byte offset for each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
tokenizer_CorpusByteWidths
Scalars=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Actual UTF-8 bytes emitted by each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
tokenizer_CorpusBytes
Bytes=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Manual UTF-8 encoding in source order, preserving all data.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
| 3 | 98 |
tokenizer_SourceCodePoints
Scalars=3 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Validated Unicode scalars in exact input order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
tokenizer_SourceUTF16Offsets
Scalars=3 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Zero-based UTF-16 storage offset for each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
tokenizer_SourceUTF16Widths
Scalars=3 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. UTF-16 storage units consumed by each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
tokenizer_SourceByteOffsets
Scalars=3 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Zero-based UTF-8 byte offset for each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
tokenizer_SourceByteWidths
Scalars=3 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Actual UTF-8 bytes emitted by each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
tokenizer_SourceBytes
Bytes=3 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Manual UTF-8 encoding in source order, preserving all data.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
tokenizer_TrainInitialIDs
Tokens=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Initial training byte IDs, one ID for each actual corpus byte.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
| 3 | 98 |
tokenizer_CorpusIDs
Tokens=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Final learned corpus token IDs; corpus training never contains EOS.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
| 3 | 98 |
tokenizer_EncodeInitialIDs
Tokens=3 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Initial target byte IDs before any ranked application.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
tokenizer_TargetIDs
Tokens=3 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Final target token IDs after all learned ranks, then optional unique EOS tail.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
tokenizer_CorpusDecodedBytes
Bytes=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Actual final corpus ID expansions passed to strict UTF-8 decoding.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
| 3 | 98 |
tokenizer_TargetDecodedBytes
Bytes=3 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Actual final target ID expansions passed to strict UTF-8 decoding.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
growth0_AllClassIDs
ModelRow=5 · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. All possible compact model rows; public IDs are labels.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
| 3 | 256 |
| 4 | 257 |
growth0_ClassIDs
Class=3 · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Active compact prefix; V=3+merges.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
growth0_E
ModelRow=5 × D=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. All ten validated editable embeddings, including inactive rows.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0.5 |
| 7 | 0.5 |
| 8 | 1 |
| 9 | 1 |
growth0_U
D=2 × ModelRow=5 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. All ten validated readout weights; active prefix alone produces logits.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 1 |
| 7 | 0 |
| 8 | 0 |
| 9 | 0 |
growth0_Bias
ModelRow=5 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. All five validated biases; inactive columns remain outside the distribution.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
growth0_InputIDs
LocalPosition=1 · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Exactly one new observed token is processed.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
growth0_InputRows
LocalPosition=1 · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Compact embedding row for the new token.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
growth0_AbsoluteQueryPosition
Query=1 · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Absolute N, distinct from the single local query index0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
growth0_X
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Only the new embedding row; local T=1, absolute position is saved separately.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
growth0_LN1
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New-row feature LayerNorm; population variance, epsilon1, gamma1, beta0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_ProjectionX
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. Active token rows; D=2 input features always retained.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_ProjectionWQ
D=2 × QueryFeature=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. Query columns packed by h*Dk+f from wq{d}{h}{f}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
growth0_ProjectionWK
D=2 × KeyFeature=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. Key columns packed by h*Dk+f from wk{d}{h}{f}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
growth0_ProjectionWV
D=2 × ValueFeature=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. Value columns packed by h*Dv+f from wv{d}{h}{f}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
growth0_ProjectionQConcat
B=1 × T=1 × QueryFeature=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. XWQ; each packed coordinate has two products and one sum.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_ProjectionKConcat
B=1 × T=1 × KeyFeature=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. XWK; each packed coordinate has two products and one sum.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_ProjectionVConcat
B=1 × T=1 × ValueFeature=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. XWV; values are projected separately from queries and keys.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_ProjectionQSplit
B=1 × T=1 × H=1 × Dk=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. QConcat reshaped without changing flat order; feature=h*F+f.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_ProjectionQHeads
B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_ProjectionKSplit
B=1 × T=1 × H=1 × Dk=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. KConcat reshaped without changing flat order; feature=h*F+f.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_ProjectionKHeads
B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_ProjectionVSplit
B=1 × T=1 × H=1 × Dv=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. VConcat reshaped without changing flat order; feature=h*F+f.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_ProjectionVHeads
B=1 × H=1 × T=1 × Dv=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New LN1 row only. VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_RotatedQHeads
B=1 × H=1 × Query=1 × Dk=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New query rotated at absolute N; Query length1.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_NewRotatedKHeads
B=1 × H=1 × NewPosition=1 × Dk=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Only the newly computed key, rotated once at absolute N.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_RoPEAngles
Query=1 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Actual absolute N times frequency1, radians.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
growth0_RoPECos
Query=1 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Cosine used by new Q/K rotations.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
growth0_RoPESin
Query=1 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Sine used by new Q/K rotations.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
growth0_AfterIDs
CachePosition=1 · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Ordered observed public IDs; cache coherence is an external-helper input precondition.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
growth0_AfterPositions
CachePosition=1 · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Absolute positions 0..N-1, not local append-query indices.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
growth0_AfterKeys
B=1 × H=1 × CachePosition=1 × Dk=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_AfterValues
B=1 × H=1 × CachePosition=1 × Dv=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Saved unrotated projected V in observed-prefix order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_Attentionraw
B=1 × H=1 × Query=1 × Key=1 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Actual two-product new Q dot every cached K.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.39999999999999997 |
growth0_Attentionscores
B=1 × H=1 × Query=1 × Key=1 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Raw dot products divided by sqrt(Dk=2).
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.28284271247461895 |
growth0_Attentionallowed
B=1 × H=1 × Query=1 × Key=1 · bool · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Allowed iff cached absolute key position <= absolute query N.
| Zero-based storage index | Stored value |
|---|---|
| 0 | true |
growth0_Attentionlogits
B=1 × H=1 × Query=1 × Key=1 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Actual scaled scores plus the fixed common shift0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.28284271247461895 |
growth0_Attentionprobabilities
B=1 × H=1 × Query=1 × Key=1 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Stable softmax over the complete cached key axis; Query length1.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
growth0_AttentionOHeads
B=1 × H=1 × Query=1 × Dv=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New query weighted sum of all unrotated cached V.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_AttentionC
B=1 × T=1 × JoinedValue=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. One-head Query to local token-major joined-feature copy.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_AttentionWO
JoinedValue=2 × D=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Explicit identity2 output projection.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
growth0_AttentionOutput
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. C WO for one local row, with explicit identity WO.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_R1
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Exact named-shape addition of X and AttentionOutput; no broadcasting.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.4472135954999579 |
| 1 | -0.4472135954999579 |
growth0_LN2
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. New-row feature LayerNorm of R1; population variance, epsilon1, gamma1, beta0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.6876854075163181 |
| 1 | -0.6876854075163181 |
growth0_W1
D=2 × HiddenFeature=3 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 1 |
| 5 | 0 |
growth0_b1
HiddenFeature=3 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Shared hidden bias, added after the two products.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
growth0_Z
B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Hidden preactivations X W1+b1; no batch or token mixing.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.6876854075163181 |
| 1 | -0.6876854075163181 |
| 2 | 0 |
growth0_Hidden
B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. ReLU(Z)=max(0,Z), before the second affine layer.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.6876854075163181 |
| 1 | 0 |
| 2 | 0 |
growth0_W2
HiddenFeature=3 × D=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Shared hidden-to-output weights, f2{m}{d}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 0 |
| 5 | 0 |
growth0_b2
D=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Shared output bias, added after all three running sums.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
growth0_F
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. ReLU(X W1+b1) W2+b2, independently per token with shared parameters.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.6876854075163181 |
| 1 | 0 |
growth0_Y
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Exact named-shape addition of R1 and F; no broadcasting.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.4472135954999579 |
growth0_Logits
Position=1 × Class=3 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Actual new Y times active U, then active Bias.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.4472135954999579 |
| 2 | 0 |
growth0_ChoiceClassIDs
Class=3 · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Active compact prefix [97,98,512,256,257]; public IDs are labels, not offsets.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
growth0_ChoiceZ
Class=3 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Actual finite computed input logits; no derived-input clipping.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.4472135954999579 |
| 2 | 0 |
growth0_ChoiceShifted
Class=3 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Z minus the saved active maximum.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | -2.582112598516234 |
| 2 | -2.134899003016276 |
growth0_ChoiceTerms
Class=3 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Actual exp(Shifted), before normalization.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0.0756140929478022 |
| 2 | 0.11825653332669596 |
growth0_ChoiceDenominator
Scalar=1 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Actual left-to-right sum of active shifted terms.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.1938706262744982 |
growth0_ChoiceLogS
Scalar=1 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Natural logarithm of Denominator.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.17720065589584005 |
growth0_ChoiceLSE
Scalar=1 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Saved max+LogS in binary64.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.312099658912116 |
growth0_ChoiceP
Class=3 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Terms/Denominator for active classes only, without clipping or padding.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8376116959343609 |
| 1 | 0.063335248630547 |
| 2 | 0.09905305543509206 |
growth0_ChoiceNextRow
Decision=1 · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Lowest compact index among highest computed logits.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
growth0_ChoiceNextID
Decision=1 · int32 · precision 0 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Public class ID gathered at NextRow.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
growth0_ChoiceNextProbability
Decision=1 · float64 · precision 8 · Actual cached append growth0: local row0 is absolute 0; no old query/K/V recomputation. Stored P gathered at the computed-logit winner.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8376116959343609 |
growth1_AllClassIDs
ModelRow=5 · int32 · precision 0 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. All possible compact model rows; public IDs are labels.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
| 3 | 256 |
| 4 | 257 |
growth1_ClassIDs
Class=3 · int32 · precision 0 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Active compact prefix; V=3+merges.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
growth1_E
ModelRow=5 × D=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. All ten validated editable embeddings, including inactive rows.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0.5 |
| 7 | 0.5 |
| 8 | 1 |
| 9 | 1 |
growth1_U
D=2 × ModelRow=5 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. All ten validated readout weights; active prefix alone produces logits.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 1 |
| 7 | 0 |
| 8 | 0 |
| 9 | 0 |
growth1_Bias
ModelRow=5 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. All five validated biases; inactive columns remain outside the distribution.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
growth1_InputIDs
LocalPosition=1 · int32 · precision 0 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Exactly one new observed token is processed.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 98 |
growth1_InputRows
LocalPosition=1 · int32 · precision 0 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Compact embedding row for the new token.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
growth1_AbsoluteQueryPosition
Query=1 · int32 · precision 0 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Absolute N, distinct from the single local query index0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
growth1_BeforeIDs
CachePosition=1 · int32 · precision 0 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Ordered observed public IDs; cache coherence is an external-helper input precondition.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
growth1_BeforePositions
CachePosition=1 · int32 · precision 0 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Absolute positions 0..N-1, not local append-query indices.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
growth1_BeforeKeys
B=1 × H=1 × CachePosition=1 × Dk=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth1_BeforeValues
B=1 × H=1 × CachePosition=1 × Dv=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Saved unrotated projected V in observed-prefix order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth1_X
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Only the new embedding row; local T=1, absolute position is saved separately.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
growth1_LN1
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New-row feature LayerNorm; population variance, epsilon1, gamma1, beta0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.4472135954999579 |
| 1 | 0.4472135954999579 |
growth1_ProjectionX
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New LN1 row only. Active token rows; D=2 input features always retained.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.4472135954999579 |
| 1 | 0.4472135954999579 |
growth1_ProjectionWQ
D=2 × QueryFeature=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New LN1 row only. Query columns packed by h*Dk+f from wq{d}{h}{f}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
growth1_ProjectionWK
D=2 × KeyFeature=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New LN1 row only. Key columns packed by h*Dk+f from wk{d}{h}{f}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
growth1_ProjectionWV
D=2 × ValueFeature=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New LN1 row only. Value columns packed by h*Dv+f from wv{d}{h}{f}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
growth1_ProjectionQConcat
B=1 × T=1 × QueryFeature=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New LN1 row only. XWQ; each packed coordinate has two products and one sum.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.4472135954999579 |
| 1 | 0.4472135954999579 |
growth1_ProjectionKConcat
B=1 × T=1 × KeyFeature=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New LN1 row only. XWK; each packed coordinate has two products and one sum.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.4472135954999579 |
| 1 | 0.4472135954999579 |
growth1_ProjectionVConcat
B=1 × T=1 × ValueFeature=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New LN1 row only. XWV; values are projected separately from queries and keys.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.4472135954999579 |
| 1 | 0.4472135954999579 |
growth1_ProjectionQSplit
B=1 × T=1 × H=1 × Dk=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New LN1 row only. QConcat reshaped without changing flat order; feature=h*F+f.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.4472135954999579 |
| 1 | 0.4472135954999579 |
growth1_ProjectionQHeads
B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New LN1 row only. QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.4472135954999579 |
| 1 | 0.4472135954999579 |
growth1_ProjectionKSplit
B=1 × T=1 × H=1 × Dk=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New LN1 row only. KConcat reshaped without changing flat order; feature=h*F+f.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.4472135954999579 |
| 1 | 0.4472135954999579 |
growth1_ProjectionKHeads
B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New LN1 row only. KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.4472135954999579 |
| 1 | 0.4472135954999579 |
growth1_ProjectionVSplit
B=1 × T=1 × H=1 × Dv=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New LN1 row only. VConcat reshaped without changing flat order; feature=h*F+f.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.4472135954999579 |
| 1 | 0.4472135954999579 |
growth1_ProjectionVHeads
B=1 × H=1 × T=1 × Dv=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New LN1 row only. VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.4472135954999579 |
| 1 | 0.4472135954999579 |
growth1_RotatedQHeads
B=1 × H=1 × Query=1 × Dk=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New query rotated at absolute N; Query length1.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.6179478014890387 |
| 1 | -0.1346867277606211 |
growth1_NewRotatedKHeads
B=1 × H=1 × NewPosition=1 × Dk=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Only the newly computed key, rotated once at absolute N.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.6179478014890387 |
| 1 | -0.1346867277606211 |
growth1_RoPEAngles
Query=1 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Actual absolute N times frequency1, radians.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
growth1_RoPECos
Query=1 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Cosine used by new Q/K rotations.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.5403023058681398 |
growth1_RoPESin
Query=1 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Sine used by new Q/K rotations.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8414709848078965 |
growth1_AfterIDs
CachePosition=2 · int32 · precision 0 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Ordered observed public IDs; cache coherence is an external-helper input precondition.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
growth1_AfterPositions
CachePosition=2 · int32 · precision 0 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Absolute positions 0..N-1, not local append-query indices.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
growth1_AfterKeys
B=1 × H=1 × CachePosition=2 × Dk=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.6179478014890387 |
| 3 | -0.1346867277606211 |
growth1_AfterValues
B=1 × H=1 × CachePosition=2 × Dv=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Saved unrotated projected V in observed-prefix order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.4472135954999579 |
| 3 | 0.4472135954999579 |
growth1_Attentionraw
B=1 × H=1 × Query=1 × Key=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Actual two-product new Q dot every cached K.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.2161209223472559 |
| 1 | 0.4000000000000001 |
growth1_Attentionscores
B=1 × H=1 × Query=1 × Key=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Raw dot products divided by sqrt(Dk=2).
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.1528205697480359 |
| 1 | 0.28284271247461906 |
growth1_Attentionallowed
B=1 × H=1 × Query=1 × Key=2 · bool · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Allowed iff cached absolute key position <= absolute query N.
| Zero-based storage index | Stored value |
|---|---|
| 0 | true |
| 1 | true |
growth1_Attentionlogits
B=1 × H=1 × Query=1 × Key=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Actual scaled scores plus the fixed common shift0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.1528205697480359 |
| 1 | 0.28284271247461906 |
growth1_Attentionprobabilities
B=1 × H=1 × Query=1 × Key=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Stable softmax over the complete cached key axis; Query length1.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.3927748060431144 |
| 1 | 0.6072251939568857 |
growth1_AttentionOHeads
B=1 × H=1 × Query=1 × Dv=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New query weighted sum of all unrotated cached V.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.0959051290352784 |
| 1 | 0.0959051290352784 |
growth1_AttentionC
B=1 × T=1 × JoinedValue=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. One-head Query to local token-major joined-feature copy.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.0959051290352784 |
| 1 | 0.0959051290352784 |
growth1_AttentionWO
JoinedValue=2 × D=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Explicit identity2 output projection.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
growth1_AttentionOutput
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. C WO for one local row, with explicit identity WO.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.0959051290352784 |
| 1 | 0.0959051290352784 |
growth1_R1
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Exact named-shape addition of X and AttentionOutput; no broadcasting.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.0959051290352784 |
| 1 | 1.0959051290352784 |
growth1_LN2
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. New-row feature LayerNorm of R1; population variance, epsilon1, gamma1, beta0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.5119068988408909 |
| 1 | 0.5119068988408909 |
growth1_W1
D=2 × HiddenFeature=3 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 1 |
| 5 | 0 |
growth1_b1
HiddenFeature=3 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Shared hidden bias, added after the two products.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
growth1_Z
B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Hidden preactivations X W1+b1; no batch or token mixing.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.5119068988408909 |
| 1 | 0.5119068988408909 |
| 2 | 0 |
growth1_Hidden
B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. ReLU(Z)=max(0,Z), before the second affine layer.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0.5119068988408909 |
| 2 | 0 |
growth1_W2
HiddenFeature=3 × D=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Shared hidden-to-output weights, f2{m}{d}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 0 |
| 5 | 0 |
growth1_b2
D=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Shared output bias, added after all three running sums.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
growth1_F
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. ReLU(X W1+b1) W2+b2, independently per token with shared parameters.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0.5119068988408909 |
growth1_Y
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Exact named-shape addition of R1 and F; no broadcasting.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.0959051290352784 |
| 1 | 1.6078120278761694 |
growth1_Logits
Position=1 × Class=3 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Actual new Y times active U, then active Bias.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.0959051290352784 |
| 1 | 1.6078120278761694 |
| 2 | 0 |
growth1_ChoiceClassIDs
Class=3 · int32 · precision 0 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Active compact prefix [97,98,512,256,257]; public IDs are labels, not offsets.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
growth1_ChoiceZ
Class=3 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Actual finite computed input logits; no derived-input clipping.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.0959051290352784 |
| 1 | 1.6078120278761694 |
| 2 | 0 |
growth1_ChoiceShifted
Class=3 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Z minus the saved active maximum.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -1.7037171569114478 |
| 1 | 0 |
| 2 | -1.6078120278761694 |
growth1_ChoiceTerms
Class=3 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Actual exp(Shifted), before normalization.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.1820057212588121 |
| 1 | 1 |
| 2 | 0.20032544140497158 |
growth1_ChoiceDenominator
Scalar=1 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Actual left-to-right sum of active shifted terms.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.3823311626637835 |
growth1_ChoiceLogS
Scalar=1 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Natural logarithm of Denominator.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.3237713223010388 |
growth1_ChoiceLSE
Scalar=1 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Saved max+LogS in binary64.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.9315833501772082 |
growth1_ChoiceP
Class=3 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Terms/Denominator for active classes only, without clipping or padding.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.13166578760192524 |
| 1 | 0.7234156524931242 |
| 2 | 0.14491855990495064 |
growth1_ChoiceNextRow
Decision=1 · int32 · precision 0 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Lowest compact index among highest computed logits.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
growth1_ChoiceNextID
Decision=1 · int32 · precision 0 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Public class ID gathered at NextRow.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 98 |
growth1_ChoiceNextProbability
Decision=1 · float64 · precision 8 · Actual cached append growth1: local row0 is absolute 1; no old query/K/V recomputation. Stored P gathered at the computed-logit winner.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.7234156524931242 |
growth2_AllClassIDs
ModelRow=5 · int32 · precision 0 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. All possible compact model rows; public IDs are labels.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
| 3 | 256 |
| 4 | 257 |
growth2_ClassIDs
Class=3 · int32 · precision 0 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Active compact prefix; V=3+merges.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
growth2_E
ModelRow=5 × D=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. All ten validated editable embeddings, including inactive rows.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0.5 |
| 7 | 0.5 |
| 8 | 1 |
| 9 | 1 |
growth2_U
D=2 × ModelRow=5 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. All ten validated readout weights; active prefix alone produces logits.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 1 |
| 7 | 0 |
| 8 | 0 |
| 9 | 0 |
growth2_Bias
ModelRow=5 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. All five validated biases; inactive columns remain outside the distribution.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
growth2_InputIDs
LocalPosition=1 · int32 · precision 0 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Exactly one new observed token is processed.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
growth2_InputRows
LocalPosition=1 · int32 · precision 0 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Compact embedding row for the new token.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
growth2_AbsoluteQueryPosition
Query=1 · int32 · precision 0 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Absolute N, distinct from the single local query index0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2 |
growth2_BeforeIDs
CachePosition=2 · int32 · precision 0 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Ordered observed public IDs; cache coherence is an external-helper input precondition.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
growth2_BeforePositions
CachePosition=2 · int32 · precision 0 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Absolute positions 0..N-1, not local append-query indices.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
growth2_BeforeKeys
B=1 × H=1 × CachePosition=2 × Dk=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.6179478014890387 |
| 3 | -0.1346867277606211 |
growth2_BeforeValues
B=1 × H=1 × CachePosition=2 × Dv=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Saved unrotated projected V in observed-prefix order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.4472135954999579 |
| 3 | 0.4472135954999579 |
growth2_X
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Only the new embedding row; local T=1, absolute position is saved separately.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
growth2_LN1
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New-row feature LayerNorm; population variance, epsilon1, gamma1, beta0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth2_ProjectionX
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. Active token rows; D=2 input features always retained.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth2_ProjectionWQ
D=2 × QueryFeature=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. Query columns packed by h*Dk+f from wq{d}{h}{f}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
growth2_ProjectionWK
D=2 × KeyFeature=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. Key columns packed by h*Dk+f from wk{d}{h}{f}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
growth2_ProjectionWV
D=2 × ValueFeature=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. Value columns packed by h*Dv+f from wv{d}{h}{f}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
growth2_ProjectionQConcat
B=1 × T=1 × QueryFeature=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. XWQ; each packed coordinate has two products and one sum.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth2_ProjectionKConcat
B=1 × T=1 × KeyFeature=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. XWK; each packed coordinate has two products and one sum.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth2_ProjectionVConcat
B=1 × T=1 × ValueFeature=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. XWV; values are projected separately from queries and keys.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth2_ProjectionQSplit
B=1 × T=1 × H=1 × Dk=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. QConcat reshaped without changing flat order; feature=h*F+f.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth2_ProjectionQHeads
B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth2_ProjectionKSplit
B=1 × T=1 × H=1 × Dk=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. KConcat reshaped without changing flat order; feature=h*F+f.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth2_ProjectionKHeads
B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth2_ProjectionVSplit
B=1 × T=1 × H=1 × Dv=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. VConcat reshaped without changing flat order; feature=h*F+f.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth2_ProjectionVHeads
B=1 × H=1 × T=1 × Dv=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
growth2_RotatedQHeads
B=1 × H=1 × Query=1 × Dk=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New query rotated at absolute N; Query length1.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.22054364860139217 |
| 1 | 0.5927566946577538 |
growth2_NewRotatedKHeads
B=1 × H=1 × NewPosition=1 × Dk=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Only the newly computed key, rotated once at absolute N.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.22054364860139217 |
| 1 | 0.5927566946577538 |
growth2_RoPEAngles
Query=1 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Actual absolute N times frequency1, radians.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2 |
growth2_RoPECos
Query=1 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Cosine used by new Q/K rotations.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.4161468365471424 |
growth2_RoPESin
Query=1 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Sine used by new Q/K rotations.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.9092974268256817 |
growth2_AfterIDs
CachePosition=3 · int32 · precision 0 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Ordered observed public IDs; cache coherence is an external-helper input precondition.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
growth2_AfterPositions
CachePosition=3 · int32 · precision 0 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Absolute positions 0..N-1, not local append-query indices.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
growth2_AfterKeys
B=1 × H=1 × CachePosition=3 × Dk=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.6179478014890387 |
| 3 | -0.1346867277606211 |
| 4 | 0.22054364860139217 |
| 5 | 0.5927566946577538 |
growth2_AfterValues
B=1 × H=1 × CachePosition=3 × Dv=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Saved unrotated projected V in observed-prefix order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.4472135954999579 |
| 3 | 0.4472135954999579 |
| 4 | 0.4472135954999579 |
| 5 | -0.4472135954999579 |
growth2_Attentionraw
B=1 × H=1 × Query=1 × Key=3 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Actual two-product new Q dot every cached K.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.1664587346188569 |
| 1 | -0.21612092234725588 |
| 2 | 0.39999999999999997 |
growth2_Attentionscores
B=1 × H=1 × Query=1 × Key=3 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Raw dot products divided by sqrt(Dk=2).
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.11770410003672563 |
| 1 | -0.15282056974803587 |
| 2 | 0.28284271247461895 |
growth2_Attentionallowed
B=1 × H=1 × Query=1 × Key=3 · bool · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Allowed iff cached absolute key position <= absolute query N.
| Zero-based storage index | Stored value |
|---|---|
| 0 | true |
| 1 | true |
| 2 | true |
growth2_Attentionlogits
B=1 × H=1 × Query=1 × Key=3 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Actual scaled scores plus the fixed common shift0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.11770410003672563 |
| 1 | -0.15282056974803587 |
| 2 | 0.28284271247461895 |
growth2_Attentionprobabilities
B=1 × H=1 × Query=1 × Key=3 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Stable softmax over the complete cached key axis; Query length1.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.2891733251316062 |
| 1 | 0.2791948093517053 |
| 2 | 0.43163186551668853 |
growth2_AttentionOHeads
B=1 × H=1 × Query=1 × Dv=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New query weighted sum of all unrotated cached V.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.19749416642975512 |
| 1 | -0.19749416642975512 |
growth2_AttentionC
B=1 × T=1 × JoinedValue=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. One-head Query to local token-major joined-feature copy.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.19749416642975512 |
| 1 | -0.19749416642975512 |
growth2_AttentionWO
JoinedValue=2 × D=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Explicit identity2 output projection.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
growth2_AttentionOutput
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. C WO for one local row, with explicit identity WO.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.19749416642975512 |
| 1 | -0.19749416642975512 |
growth2_R1
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Exact named-shape addition of X and AttentionOutput; no broadcasting.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.1974941664297551 |
| 1 | -0.19749416642975512 |
growth2_LN2
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. New-row feature LayerNorm of R1; population variance, epsilon1, gamma1, beta0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.5720821519582194 |
| 1 | -0.5720821519582194 |
growth2_W1
D=2 × HiddenFeature=3 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 1 |
| 5 | 0 |
growth2_b1
HiddenFeature=3 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Shared hidden bias, added after the two products.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
growth2_Z
B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Hidden preactivations X W1+b1; no batch or token mixing.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.5720821519582194 |
| 1 | -0.5720821519582194 |
| 2 | 0 |
growth2_Hidden
B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. ReLU(Z)=max(0,Z), before the second affine layer.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.5720821519582194 |
| 1 | 0 |
| 2 | 0 |
growth2_W2
HiddenFeature=3 × D=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Shared hidden-to-output weights, f2{m}{d}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 0 |
| 5 | 0 |
growth2_b2
D=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Shared output bias, added after all three running sums.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
growth2_F
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. ReLU(X W1+b1) W2+b2, independently per token with shared parameters.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.5720821519582194 |
| 1 | 0 |
growth2_Y
B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Exact named-shape addition of R1 and F; no broadcasting.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.7695763183879745 |
| 1 | -0.19749416642975512 |
growth2_Logits
Position=1 × Class=3 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Actual new Y times active U, then active Bias.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.7695763183879745 |
| 1 | -0.19749416642975512 |
| 2 | 0 |
growth2_ChoiceClassIDs
Class=3 · int32 · precision 0 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Active compact prefix [97,98,512,256,257]; public IDs are labels, not offsets.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
growth2_ChoiceZ
Class=3 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Actual finite computed input logits; no derived-input clipping.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.7695763183879745 |
| 1 | -0.19749416642975512 |
| 2 | 0 |
growth2_ChoiceShifted
Class=3 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Z minus the saved active maximum.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | -1.9670704848177296 |
| 2 | -1.7695763183879745 |
growth2_ChoiceTerms
Class=3 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Actual exp(Shifted), before normalization.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0.1398659961908848 |
| 2 | 0.17040517107076136 |
growth2_ChoiceDenominator
Scalar=1 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Actual left-to-right sum of active shifted terms.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.310271167261646 |
growth2_ChoiceLogS
Scalar=1 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Natural logarithm of Denominator.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.2702341137016024 |
growth2_ChoiceLSE
Scalar=1 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Saved max+LogS in binary64.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.0398104320895767 |
growth2_ChoiceP
Class=3 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Terms/Denominator for active classes only, without clipping or padding.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.7632007976561935 |
| 1 | 0.1067458398578614 |
| 2 | 0.13005336248594518 |
growth2_ChoiceNextRow
Decision=1 · int32 · precision 0 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Lowest compact index among highest computed logits.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
growth2_ChoiceNextID
Decision=1 · int32 · precision 0 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Public class ID gathered at NextRow.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
growth2_ChoiceNextProbability
Decision=1 · float64 · precision 8 · Actual cached append growth2: local row0 is absolute 2; no old query/K/V recomputation. Stored P gathered at the computed-logit winner.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.7632007976561935 |
reference_AllClassIDs
ModelRow=5 · int32 · precision 0 · Actual full-prefix call reference, absolute positions 0..2. Full compact model row map: a,b,EOS,ab,abab; public IDs are not storage offsets.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
| 3 | 256 |
| 4 | 257 |
reference_ClassIDs
Class=3 · int32 · precision 0 · Actual full-prefix call reference, absolute positions 0..2. Active prefix of the full model row map; V=3+merges.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
reference_E
ModelRow=5 × D=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. All ten validated editable embeddings, including EOS and inactive learned pieces.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0.5 |
| 7 | 0.5 |
| 8 | 1 |
| 9 | 1 |
reference_U
D=2 × ModelRow=5 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. All ten validated editable readout weights; only the first V columns contribute logits.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 1 |
| 7 | 0 |
| 8 | 0 |
| 9 | 0 |
reference_Bias
ModelRow=5 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. All five validated editable biases; inactive columns have no objective dependency.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
reference_InputIDs
Position=3 · int32 · precision 0 · Actual full-prefix call reference, absolute positions 0..2. Observed public IDs supplied directly to the numeric kernel; active EOS is permitted.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
reference_InputRows
Position=3 · int32 · precision 0 · Actual full-prefix call reference, absolute positions 0..2. Compact model row gathered for each observed ID; never index by public ID512.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 0 |
reference_X
B=1 × T=3 × D=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Actual gathered E rows; B=1, token-major storage and D=2.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 0 |
reference_LN1
B=1 × T=3 × D=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Per-token feature layer norm of X; population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside sqrt.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.4472135954999579 |
| 3 | 0.4472135954999579 |
| 4 | 0.4472135954999579 |
| 5 | -0.4472135954999579 |
reference_ProjectionX
B=1 × T=3 × D=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Active token rows; D=2 input features always retained. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.4472135954999579 |
| 3 | 0.4472135954999579 |
| 4 | 0.4472135954999579 |
| 5 | -0.4472135954999579 |
reference_ProjectionWQ
D=2 × QueryFeature=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Query columns packed by h*Dk+f from wq{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
reference_ProjectionWK
D=2 × KeyFeature=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Key columns packed by h*Dk+f from wk{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
reference_ProjectionWV
D=2 × ValueFeature=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Value columns packed by h*Dv+f from wv{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
reference_ProjectionQConcat
B=1 × T=3 × QueryFeature=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. XWQ; each packed coordinate has two products and one sum. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.4472135954999579 |
| 3 | 0.4472135954999579 |
| 4 | 0.4472135954999579 |
| 5 | -0.4472135954999579 |
reference_ProjectionKConcat
B=1 × T=3 × KeyFeature=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. XWK; each packed coordinate has two products and one sum. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.4472135954999579 |
| 3 | 0.4472135954999579 |
| 4 | 0.4472135954999579 |
| 5 | -0.4472135954999579 |
reference_ProjectionVConcat
B=1 × T=3 × ValueFeature=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. XWV; values are projected separately from queries and keys. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.4472135954999579 |
| 3 | 0.4472135954999579 |
| 4 | 0.4472135954999579 |
| 5 | -0.4472135954999579 |
reference_ProjectionQSplit
B=1 × T=3 × H=1 × Dk=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. QConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.4472135954999579 |
| 3 | 0.4472135954999579 |
| 4 | 0.4472135954999579 |
| 5 | -0.4472135954999579 |
reference_ProjectionQHeads
B=1 × H=1 × T=3 × Dk=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.4472135954999579 |
| 3 | 0.4472135954999579 |
| 4 | 0.4472135954999579 |
| 5 | -0.4472135954999579 |
reference_ProjectionKSplit
B=1 × T=3 × H=1 × Dk=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. KConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.4472135954999579 |
| 3 | 0.4472135954999579 |
| 4 | 0.4472135954999579 |
| 5 | -0.4472135954999579 |
reference_ProjectionKHeads
B=1 × H=1 × T=3 × Dk=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.4472135954999579 |
| 3 | 0.4472135954999579 |
| 4 | 0.4472135954999579 |
| 5 | -0.4472135954999579 |
reference_ProjectionVSplit
B=1 × T=3 × H=1 × Dv=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. VConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.4472135954999579 |
| 3 | 0.4472135954999579 |
| 4 | 0.4472135954999579 |
| 5 | -0.4472135954999579 |
reference_ProjectionVHeads
B=1 × H=1 × T=3 × Dv=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.4472135954999579 |
| 3 | 0.4472135954999579 |
| 4 | 0.4472135954999579 |
| 5 | -0.4472135954999579 |
reference_RotatedQHeads
B=1 × H=1 × T=3 × Dk=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Actual RoPE(ProjectionQHeads) supplied as attendHeads QHeads; original projection is retained separately.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.6179478014890387 |
| 3 | -0.1346867277606211 |
| 4 | 0.22054364860139217 |
| 5 | 0.5927566946577538 |
reference_RotatedKHeads
B=1 × H=1 × T=3 × Dk=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Actual RoPE(ProjectionKHeads) supplied as attendHeads KHeads; original projection is retained separately.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.6179478014890387 |
| 3 | -0.1346867277606211 |
| 4 | 0.22054364860139217 |
| 5 | 0.5927566946577538 |
reference_RoPEAngles
Position=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Absolute position t times the single-pair frequency1, in radians.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
reference_RoPECos
Position=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Stored cos(angle) used in the Q pair rotation; K uses the same angle.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0.5403023058681398 |
| 2 | -0.4161468365471424 |
reference_RoPESin
Position=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Stored sin(angle) used in the Q pair rotation; K uses the same angle.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0.8414709848078965 |
| 2 | 0.9092974268256817 |
reference_Attentionraw
B=1 × H=1 × Query=3 × Key=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Separate QHeads KHeads transpose products within every batch and head. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.39999999999999997 |
| 1 | -0.2161209223472559 |
| 2 | -0.1664587346188569 |
| 3 | -0.2161209223472559 |
| 4 | 0.4000000000000001 |
| 5 | -0.21612092234725588 |
| 6 | -0.1664587346188569 |
| 7 | -0.21612092234725588 |
| 8 | 0.39999999999999997 |
reference_Attentionscores
B=1 × H=1 × Query=3 × Key=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. raw/sqrt(Dk); the two-product order matches IV25 for H1,Dk2. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.28284271247461895 |
| 1 | -0.1528205697480359 |
| 2 | -0.11770410003672563 |
| 3 | -0.1528205697480359 |
| 4 | 0.28284271247461906 |
| 5 | -0.15282056974803587 |
| 6 | -0.11770410003672563 |
| 7 | -0.15282056974803587 |
| 8 | 0.28284271247461895 |
reference_Attentionallowed
B=1 × H=1 × Query=3 × Key=3 · bool · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Causal and/or valid-key mask; shared validity across B and H; every query retained. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.
| Zero-based storage index | Stored value |
|---|---|
| 0 | true |
| 1 | false |
| 2 | false |
| 3 | true |
| 4 | true |
| 5 | false |
| 6 | true |
| 7 | true |
| 8 | true |
reference_Attentionlogits
B=1 × H=1 × Query=3 × Key=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Finite score+shift, including forbidden cells; mask applied separately. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.28284271247461895 |
| 1 | -0.1528205697480359 |
| 2 | -0.11770410003672563 |
| 3 | -0.1528205697480359 |
| 4 | 0.28284271247461906 |
| 5 | -0.15282056974803587 |
| 6 | -0.11770410003672563 |
| 7 | -0.15282056974803587 |
| 8 | 0.28284271247461895 |
reference_Attentionprobabilities
B=1 × H=1 × Query=3 × Key=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Stable allowed-key softmax for each B/H/query independently; forbidden probabilities exactly zero. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0.3927748060431144 |
| 4 | 0.6072251939568857 |
| 5 | 0 |
| 6 | 0.2891733251316062 |
| 7 | 0.2791948093517053 |
| 8 | 0.43163186551668853 |
reference_AttentionOHeads
B=1 × H=1 × Query=3 × Dv=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Actual per-head P times VHeads; every product and running sum is traced. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.0959051290352784 |
| 3 | 0.0959051290352784 |
| 4 | 0.19749416642975512 |
| 5 | -0.19749416642975512 |
reference_AttentionC
B=1 × T=3 × JoinedValue=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. OHeads permuted to token-major order then joined by c=h*Dv+f; values unchanged. Source is AttentionOHeads; active WO is explicitly identity2.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.0959051290352784 |
| 3 | 0.0959051290352784 |
| 4 | 0.19749416642975512 |
| 5 | -0.19749416642975512 |
reference_AttentionWO
JoinedValue=2 × D=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. wo{h}{f}{d} packed in h,f,d order, preserving parameter identity. Source is AttentionOHeads; active WO is explicitly identity2.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
reference_AttentionOutput
B=1 × T=3 × D=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Y=C WO, summing products in ascending joined-feature order from zero; no normalization. Source is AttentionOHeads; active WO is explicitly identity2.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.0959051290352784 |
| 3 | 0.0959051290352784 |
| 4 | 0.19749416642975512 |
| 5 | -0.19749416642975512 |
reference_R1
B=1 × T=3 × D=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Exact named-shape addition of X and AttentionOutput; no broadcasting.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.0959051290352784 |
| 3 | 1.0959051290352784 |
| 4 | 1.1974941664297551 |
| 5 | -0.19749416642975512 |
reference_LN2
B=1 × T=3 × D=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Per-token feature layer norm of R1; population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside sqrt.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.6876854075163181 |
| 1 | -0.6876854075163181 |
| 2 | -0.5119068988408909 |
| 3 | 0.5119068988408909 |
| 4 | 0.5720821519582194 |
| 5 | -0.5720821519582194 |
reference_W1
D=2 × HiddenFeature=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 1 |
| 5 | 0 |
reference_b1
HiddenFeature=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Shared hidden bias, added after the two products.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
reference_Z
B=1 × T=3 × HiddenFeature=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Hidden preactivations X W1+b1; no batch or token mixing.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.6876854075163181 |
| 1 | -0.6876854075163181 |
| 2 | 0 |
| 3 | -0.5119068988408909 |
| 4 | 0.5119068988408909 |
| 5 | 0 |
| 6 | 0.5720821519582194 |
| 7 | -0.5720821519582194 |
| 8 | 0 |
reference_Hidden
B=1 × T=3 × HiddenFeature=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. ReLU(Z)=max(0,Z), before the second affine layer.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.6876854075163181 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0.5119068988408909 |
| 5 | 0 |
| 6 | 0.5720821519582194 |
| 7 | 0 |
| 8 | 0 |
reference_W2
HiddenFeature=3 × D=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Shared hidden-to-output weights, f2{m}{d}.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 0 |
| 5 | 0 |
reference_b2
D=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Shared output bias, added after all three running sums.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
reference_F
B=1 × T=3 × D=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. ReLU(X W1+b1) W2+b2, independently per token with shared parameters.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.6876854075163181 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0.5119068988408909 |
| 4 | 0.5720821519582194 |
| 5 | 0 |
reference_Y
B=1 × T=3 × D=2 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Exact named-shape addition of R1 and F; no broadcasting.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.4472135954999579 |
| 2 | -0.0959051290352784 |
| 3 | 1.6078120278761694 |
| 4 | 1.7695763183879745 |
| 5 | -0.19749416642975512 |
reference_Logits
Position=3 × Class=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Final Y times the active U prefix, then active Bias; targets are not operands.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.4472135954999579 |
| 2 | 0 |
| 3 | -0.0959051290352784 |
| 4 | 1.6078120278761694 |
| 5 | 0 |
| 6 | 1.7695763183879745 |
| 7 | -0.19749416642975512 |
| 8 | 0 |
reference_Max
Position=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Maximum computed active class logit at each position.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | 1.6078120278761694 |
| 2 | 1.7695763183879745 |
reference_Shifted
Position=3 × Class=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Computed class logit minus its saved row maximum.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | -2.582112598516234 |
| 2 | -2.134899003016276 |
| 3 | -1.7037171569114478 |
| 4 | 0 |
| 5 | -1.6078120278761694 |
| 6 | 0 |
| 7 | -1.9670704848177296 |
| 8 | -1.7695763183879745 |
reference_Terms
Position=3 × Class=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Actual exp(Shifted) before left-to-right class summation.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0.0756140929478022 |
| 2 | 0.11825653332669596 |
| 3 | 0.1820057212588121 |
| 4 | 1 |
| 5 | 0.20032544140497158 |
| 6 | 1 |
| 7 | 0.1398659961908848 |
| 8 | 0.17040517107076136 |
reference_Denominator
Position=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Shifted exponential sum from zero in ascending compact class order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.1938706262744982 |
| 1 | 1.3823311626637835 |
| 2 | 1.310271167261646 |
reference_LogS
Position=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. ln(Denominator), saved for factored NLL.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.17720065589584005 |
| 1 | 0.3237713223010388 |
| 2 | 0.2702341137016024 |
reference_LSE
Position=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Max+LogS; saved evidence, not subtracted from target logits to compute NLL.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.312099658912116 |
| 1 | 1.9315833501772082 |
| 2 | 2.0398104320895767 |
reference_P
Position=3 × Class=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Terms/Denominator for real active classes only; no inactive-class probabilities.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8376116959343609 |
| 1 | 0.063335248630547 |
| 2 | 0.09905305543509206 |
| 3 | 0.13166578760192524 |
| 4 | 0.7234156524931242 |
| 5 | 0.14491855990495064 |
| 6 | 0.7632007976561935 |
| 7 | 0.1067458398578614 |
| 8 | 0.13005336248594518 |
reference_NextRows
Position=3 · int32 · precision 0 · Actual full-prefix call reference, absolute positions 0..2. Highest computed logit; exact ties keep the smallest compact class.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 0 |
reference_NextIDs
Position=3 · int32 · precision 0 · Actual full-prefix call reference, absolute positions 0..2. Public ID mapped from each computed-logit winner.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
reference_NextProbability
Position=3 · float64 · precision 8 · Actual full-prefix call reference, absolute positions 0..2. Stored class probability of the computed-logit winner; never fed back as an observed input.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8376116959343609 |
| 1 | 0.7234156524931242 |
| 2 | 0.7632007976561935 |
CompareKCached
Position=3 × Dk=2 · float64 · precision 8 · Actual cached operands.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.6179478014890387 |
| 3 | -0.1346867277606211 |
| 4 | 0.22054364860139217 |
| 5 | 0.5927566946577538 |
CompareKFull
Position=3 × Dk=2 · float64 · precision 8 · Actual independently recomputed full-prefix operands.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.6179478014890387 |
| 3 | -0.1346867277606211 |
| 4 | 0.22054364860139217 |
| 5 | 0.5927566946577538 |
CompareKDelta
Position=3 × Dk=2 · float64 · precision 8 · Actual cached-full subtraction.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
CompareKAbs
Position=3 × Dk=2 · float64 · precision 8 · Actual abs(Delta).
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
CompareKRunningMax
Position=3 × Dk=2 · float64 · precision 8 · Actual running maximum from0 in flat coordinate order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
CompareVCached
Position=3 × Dv=2 · float64 · precision 8 · Actual cached operands.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.4472135954999579 |
| 3 | 0.4472135954999579 |
| 4 | 0.4472135954999579 |
| 5 | -0.4472135954999579 |
CompareVFull
Position=3 × Dv=2 · float64 · precision 8 · Actual independently recomputed full-prefix operands.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.4472135954999579 |
| 3 | 0.4472135954999579 |
| 4 | 0.4472135954999579 |
| 5 | -0.4472135954999579 |
CompareVDelta
Position=3 × Dv=2 · float64 · precision 8 · Actual cached-full subtraction.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
CompareVAbs
Position=3 × Dv=2 · float64 · precision 8 · Actual abs(Delta).
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
CompareVRunningMax
Position=3 × Dv=2 · float64 · precision 8 · Actual running maximum from0 in flat coordinate order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
CompareAttentionCached
Position=3 × Dv=2 · float64 · precision 8 · Actual cached operands.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.0959051290352784 |
| 3 | 0.0959051290352784 |
| 4 | 0.19749416642975512 |
| 5 | -0.19749416642975512 |
CompareAttentionFull
Position=3 × Dv=2 · float64 · precision 8 · Actual independently recomputed full-prefix operands.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | -0.0959051290352784 |
| 3 | 0.0959051290352784 |
| 4 | 0.19749416642975512 |
| 5 | -0.19749416642975512 |
CompareAttentionDelta
Position=3 × Dv=2 · float64 · precision 8 · Actual cached-full subtraction.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
CompareAttentionAbs
Position=3 × Dv=2 · float64 · precision 8 · Actual abs(Delta).
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
CompareAttentionRunningMax
Position=3 × Dv=2 · float64 · precision 8 · Actual running maximum from0 in flat coordinate order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
CompareYCached
Position=3 × D=2 · float64 · precision 8 · Actual cached operands.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.4472135954999579 |
| 2 | -0.0959051290352784 |
| 3 | 1.6078120278761694 |
| 4 | 1.7695763183879745 |
| 5 | -0.19749416642975512 |
CompareYFull
Position=3 × D=2 · float64 · precision 8 · Actual independently recomputed full-prefix operands.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.4472135954999579 |
| 2 | -0.0959051290352784 |
| 3 | 1.6078120278761694 |
| 4 | 1.7695763183879745 |
| 5 | -0.19749416642975512 |
CompareYDelta
Position=3 × D=2 · float64 · precision 8 · Actual cached-full subtraction.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
CompareYAbs
Position=3 × D=2 · float64 · precision 8 · Actual abs(Delta).
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
CompareYRunningMax
Position=3 × D=2 · float64 · precision 8 · Actual running maximum from0 in flat coordinate order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
CompareLogitsCached
Position=3 × Class=3 · float64 · precision 8 · Actual cached operands.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.4472135954999579 |
| 2 | 0 |
| 3 | -0.0959051290352784 |
| 4 | 1.6078120278761694 |
| 5 | 0 |
| 6 | 1.7695763183879745 |
| 7 | -0.19749416642975512 |
| 8 | 0 |
CompareLogitsFull
Position=3 × Class=3 · float64 · precision 8 · Actual independently recomputed full-prefix operands.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.4472135954999579 |
| 2 | 0 |
| 3 | -0.0959051290352784 |
| 4 | 1.6078120278761694 |
| 5 | 0 |
| 6 | 1.7695763183879745 |
| 7 | -0.19749416642975512 |
| 8 | 0 |
CompareLogitsDelta
Position=3 × Class=3 · float64 · precision 8 · Actual cached-full subtraction.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
CompareLogitsAbs
Position=3 × Class=3 · float64 · precision 8 · Actual abs(Delta).
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
CompareLogitsRunningMax
Position=3 × Class=3 · float64 · precision 8 · Actual running maximum from0 in flat coordinate order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
ComparePCached
Position=3 × Class=3 · float64 · precision 8 · Actual cached operands.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8376116959343609 |
| 1 | 0.063335248630547 |
| 2 | 0.09905305543509206 |
| 3 | 0.13166578760192524 |
| 4 | 0.7234156524931242 |
| 5 | 0.14491855990495064 |
| 6 | 0.7632007976561935 |
| 7 | 0.1067458398578614 |
| 8 | 0.13005336248594518 |
ComparePFull
Position=3 × Class=3 · float64 · precision 8 · Actual independently recomputed full-prefix operands.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8376116959343609 |
| 1 | 0.063335248630547 |
| 2 | 0.09905305543509206 |
| 3 | 0.13166578760192524 |
| 4 | 0.7234156524931242 |
| 5 | 0.14491855990495064 |
| 6 | 0.7632007976561935 |
| 7 | 0.1067458398578614 |
| 8 | 0.13005336248594518 |
ComparePDelta
Position=3 × Class=3 · float64 · precision 8 · Actual cached-full subtraction.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
ComparePAbs
Position=3 × Class=3 · float64 · precision 8 · Actual abs(Delta).
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
ComparePRunningMax
Position=3 × Class=3 · float64 · precision 8 · Actual running maximum from0 in flat coordinate order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
ObservedIDs
Position=3 · int32 · precision 0 · Actual EOS-off observed BPE IDs, never sampled or retokenized.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
GrowthQueryRows
Append=3 · int32 · precision 0 · Actual new query-row count for each genuine append.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
GrowthKeyCounts
Append=3 · int32 · precision 0 · Actual available cached keys for each append.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | 3 |
GrowthRetainedExact
Append=3 · int32 · precision 0 · Computed same-implementation prior K/V equality flags; not a cross-library assertion.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
Check your understanding
Use the inputs stated in each question. Live questions use the current calculation. Each option pairs a value or conclusion with its mechanism. Editing a raw input, resetting or selecting a trace step clears graded answers; local inspection selectors preserve them.
Try merges1 with ab, then inspect the saved growth prefix. Input edits, reset and trace navigation clear graded answers; inspection selectors only choose saved evidence. No training, sampling or timing is performed.
Start with text aba, zero merges and the reset parameters. Follow the cache as observed IDs97,98,97 enter at positions0,1,2. Each stage adds one key and one value; its query is new. Compare saved rows with the separate full-prefix calculation. Editing the text, merge count or model parameters starts a fresh calculation, rather than carrying an old cache into a changed model.
Use Saved growth prefix to select the third append, at absolute position2. The Cached path shows its one new query at local row0. Switch Saved neural path to Full: the query selector now selects the corresponding absolute row2 of the single final-prefix reference. You can then explicitly select an earlier full row to inspect its causal mask. The full call still contains all final-prefix keys; its earlier queries assign future keys probability0. Switching paths again restores the row corresponding to the selected growth prefix.
Attention key chooses the saved dot-product operands, and Active compact class chooses the saved readout and probability operands. Open the operation tables to follow each product and running sum; the complete-path details retain every operation, and the tensor inspector supplies all values and named axes. These selectors read the saved record and preserve the trace cursor and graded answers. Editing a native text or numeric control, pressing Reset example, or seeking with Previous step, Next step or Calculation step clears answers. Invalid input displays its reason and removes the unavailable calculation and its questions; it does not reuse a previous answer.
Review IV-44 — Prefill and Single-Token Decode for prefill and IV-25 — Self-Attention: Complete Numerical Trace for causal attention. Book II’s II.9 — Matrix × vector explains products; Book III’s III-16 — Multiclass Classification and Softmax Regression explains class probabilities. These are the same disclosed, hand-set, untrained weights. Reusing intermediate values neither trains the model nor improves its learned capabilities.
What exactly do we retain?
A token is a piece named by an integer ID. An embedding looks that ID up in a table E; it does not treat97 as a numerical feature. A query Q compares the current token with candidate keys K. Their normalized comparison weights mix values V into an attention output. One head performs one such mixture; this model has one head and two features per row.
A KV cache stores past keys and values for later queries. Its invariant is the statement that must remain true after every append. Let N be the number of cached IDs, j a past position and E[id_j] the embedding gathered through the compact ID map. Write LN1 for the first feature layer normalization and R_j for rotation at absolute position j. Here the query, key and value projection matrices are all identity matrices, so
The cache contains these already rotated keys and unrotated values, in exactly that ID order. It also records the model parameters, kernel revision and positions0 through N−1. It contains no old queries, attention outputs, logits or class probabilities. Those can remain in the learning trace without becoming cache contents.
Why omit old queries? At the next position we ask a new comparison question. We need its new Q against all available K, then the corresponding V mixture. Recalculating an earlier query’s answer is unnecessary for that new row. A larger decoder repeats this arrangement separately at each layer; one layer’s cache cannot stand in for another’s.
Read the dimensions before the numbers
A tensor is an array with named dimensions; its shape gives their lengths. B is batch count, H head count, D feature width, Dk query/key width and Dv value width. Here B=H=1 and D=Dk=Dv=2. At append let Tk=N+1 be the available key count. V in a shape for class probabilities means vocabulary count, rather than the value tensor.
| Quantity | Shape; named axes | Meaning |
|---|---|---|
| New embedding, LN1, residuals, LN2, final Y | [1,1,2]; B, local T, D | One new feature row, at absolute position N |
| New rotated Q | [1,1,1,2]; B, H, Query, Dk | One comparison vector |
| Cached rotated K | [1,1,Tk,2]; B, H, CachePosition, Dk | Every available key |
| Cached unrotated values | [1,1,Tk,2]; B, H, CachePosition, Dv | Every available value |
| Scores, allowed mask, attention weights | [1,1,1,Tk]; B, H, Query, Key | One query against Tk keys |
| FFN hidden row | [1,1,3]; B, local T, HiddenFeature | Three computed hidden coordinates |
| New logits | [1,V]; Position, Class | One new active readout row |
| New class probability vector | [V]; Class | Distribution over V possible next tokens |
A logit is a class score before normalization. The stored E is [5,2], readout U is [2,5], and bias is [5]. Their compact row map is [97,98,512,256,257]: a, b, EOS, ab, abab. With m merges only V=3+m classes are active. At reset V=3, including EOS512; five stored rows do not imply five prediction classes. IDs and position evidence are int32, permissions are boolean, and neural arithmetic is binary64. Display precision does not alter saved operands.
The comparison stacks the N actual probability vectors into matching [N,V] cached/full operands with axes Position,Class. This stacking does not compute extra queries.
The raw state has27 fields: text plus merges, ten E entries, ten U entries and five biases. For example, e30 is embedding row3/feature0, u12 is feature1/class2, and b2 is EOS bias. E/U entries lie in [−2,2], biases in [−4,4], and merges is integer0..2.
The empty cache has N=0 and empty metadata arrays. It has no artificial zero-length TensorRecord. After each append there are N keys and N values, with two scalar coordinates apiece.
Work through a, then b, then a
The following expressions are exact real mathematics, separate from machine evaluation. Layer normalization centers a row’s features and divides by the square root of population variance plus epsilon1. Its scale gamma is1 and offset beta is0. For reset a=(1,0), mean=1/2, centered features=(1/2,−1/2), variance=(1/4+1/4)/2=1/4. Thus its denominator is √5/2. Define α=1/√5 and u=(α,−α). Then LN1(a)=u and LN1(b)=−u.
RoPE, rotary positional encoding, rotates Q and K through t radians at absolute position t:
Values never undergo that rotation. At position0, R₀ is identity. The first key and value are u; the first query is u. Its dot product is α²+(−α)²=2/5; dividing by √Dk=√2 gives g=√2/5. Only that key exists, so softmax gives weight1 and attention output u.
At position1, observed b supplies −u. Append key −R₁u and value −u; retain the first pair unchanged. The new query −R₁u gives scores (−g cos1,g) in key order. Softmax subtracts maximum g and exponentiates. Put e=exp(−g(1+cos1)); the denominator is (0+e)+1, and weights are (e/(e+1),1/(e+1)). The first mixed coordinate is 0+p0·α+p1·(−α), the second 0+p0·(−α)+p1·α. Thus attention is (2p0−1)u, with a negative coefficient because p0<1/2.
At position2, a supplies u again. Append R₂u and u. The cache is now
Query R₂u has scores (g cos2,−g cos1,g). The self dot product is2α²; the earlier products simplify to2α²cos2 and −2α²cos1 before division by√2. Define
The attention weights are (e0/Z,e1/Z,1/Z). Let h=(e0−e1+1)/Z=1−2e1/Z; then the mixed value is (αh,−αh). Here 0<h<1. Earlier queries were not recomputed to obtain it.
The remaining operations are row-local. A residual adds the original embedding: R1=(1+αh,−αh). Its mean is1/2; put d=1/2+αh and r=d/√(1+d²). The second normalization gives (r,−r). The fixed feed-forward network, or FFN, projects to (r,−r,0), applies ReLU (negative values become0), then projects (r,0,0) back to (r,0). The second residual gives Y=(1+αh+r,−αh).
Reset readout maps Y to active logits (Y0,Y1,0). With maximum M=Y0, the class denominator is ((0+1)+exp(Y1−M))+exp(−M). Dividing those three terms by that denominator gives all class probabilities. The largest logit chooses a/97. That is a prediction after observed aba, separate from the a we supplied as input.
Why reuse works, and when it stops working
Causal attention allows key j only when j≤the query’s absolute position. A future token cannot alter an earlier row through attention. Normalization and the FFN act within each row, so they cannot carry a future token backward either. Earlier K/V stay valid for the same model, IDs and positions. The separate full-prefix reference can therefore compare each incremental result with its corresponding full row.
The append row’s local array index is0; its absolute position is N. At ab plus a, all three available keys satisfy j≤2. Using local0 would wrongly hide keys1 and2. Rotating at0 would also change scores. Rotating retained keys again or rotating values violates the invariant.
Equal values can conceal a bug: for aaa, every value is u, so any normalized weight row mixes to u in exact arithmetic. Wrong position-dependent scores might leave the final answer unchanged. Inspect K and scores as well as predictions. Agreement on one chosen ID is weaker evidence than agreement on the complete calculation.
The reuse policy compares all26 numeric model fields and the revision. A changed embedding can invalidate old K/V. A readout-only edit need not mathematically change these one-layer K/V, but the deliberately conservative policy invalidates them too. An inactive embedding edit is similarly rejected for reuse. Numerical equality treats signed zeros as equal. Requested prefix order must match separately: a cache for ab cannot answer a request for ba merely because both have two entries.
Trust boundary: structural checks establish supported shapes, finite entries, IDs, positions and matching metadata. They cannot establish that external finite K/V were actually computed from the claimed model. Freezing prevents later mutation; it does not certify provenance. External helper callers must supply a coherent cache as a precondition. The app constructs caches internally; it accepts no raw learner K/V. Independent numerical witnesses remain a separate later check.
Bounds and useful edits
Raw text must be a/b only, at most6 UTF-8 bytes, without trimming or normalization. Actual BPE learns from fixed abab, uses0..2 merges and inserts no EOS. It runs once; the resulting observed sequence must contain1..3 tokens. Oversized input is rejected rather than cropped. Exact own fields, actual string type and all26 numeric fields validate before text semantics, including unused parameters. The text guard checks the outer UTF-16 limit before strict surrogate handling, then actual bytes, alphabet and emptiness.
Try aaa to expose equal-value camouflage; then restore aba. Change merges to see that character count and cache-entry count differ. Change an embedding and inspect both new projections and the rebuilt cache. The five graded checks belong to the lab and use its actual saved calculation; their corrective feedback explains the relevant dependency or arithmetic.
For the work check, each of N growth appends contributes one query row. Their key counts are1,2,…,N, so the cached raw-score-cell total is N(N+1)/2. The single full reference computes N rows and N² raw scores. At reset N=3: the two paths use3+3=6 neural rows in this comparison harness, with6 cached score cells and9 full score cells. These counts describe operations, not elapsed time.
The lab’s five checks progress from cache contents to live shapes, live work, interpretation of the saved winner/probability and error magnitudes, then the equal-value counterexample. For the shape check, use the final growth append even if your current inspector shows an earlier prefix: its Q has one query, K has N positions, attention probabilities have N keys and class probabilities have V entries. For the evidence check, expand all six comparison families. Each table shows both actual operands, signed delta, absolute error and running maximum; the retained-copy flag answers a separate question about unchanged old coordinates. The exercise definitions and corrective explanations are rendered once in the lab above.
Follow the actual Python source
Each panel imports a maintained file as raw text. Keep the relative directories intact: the loaders resolve dependencies from their own file locations. NumPy and Python’s standard library are required for later execution. Reading these panels does not run code or establish Python/TypeScript parity. The entry point accepts no arguments for fresh defaults, one complete replacement JSON state, or - for a complete state on standard input; a partial object is not an edit patch. Its strict JSON parser rejects duplicate keys and non-JSON NaN, Infinity and -Infinity. Invalid input returns an unavailable record with a code and reason, rather than stale numerical results. The explicit --self-check mode is separate from a state query; ordinary queries invoke no self-checks.
Chapter entry — code/python/p12/iv48.py. Begin with guarded derive_iv48, which calls cache_growth in the adjacent cache module. _raw_state(state) checks all27 fields through the old Tiny raw/numeric validators before text semantics. cache_prompt(text,merges) calls actual IV39 once, with fixed corpus abab, EOS off and the three-token bound. Follow setup and tokenizer evidence, empty_cache, then one genuine append_cached and growth-count record for each observed ID. One scoped_forward under reference computes the entire final prefix independently. Six compare_values calls compare actual K, V, weighted attention, Y, logits and class probabilities. Growth metadata and finish evidence then reach chapter_record, which detaches the complete ordered status, outputs, steps, tensors, texts record. Summary outputs precede every saved step-output alias; no arithmetic evidence is dropped.
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.
"""IV48: complete canonical growing-cache record, all execution deferred.
No args uses defaults; full JSON or '-' stdin replaces all27 raw fields.
--self-check invokes only this file's declared leaf, outside query fault catch.
"""
import importlib.util
from pathlib import Path
from types import MappingProxyType
_path = Path(__file__).resolve().with_name("cache_reference.py")
_spec = importlib.util.spec_from_file_location("_p12_iv48_cache", _path)
if _spec is None or _spec.loader is None:
raise ImportError(f"Cannot load canonical dependency: {_path}")
_helper = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_helper)
DEFAULT_IV48 = MappingProxyType(dict(_helper.DEFAULT_IV48))
@_helper.guarded
def derive_iv48(state):
"""Derive the full adopted IV48 record; no implicit self-checks."""
return _helper.cache_growth(state)
def source_self_check():
"""DEFERRED complete-record/guard leaf; never calls dependency checks."""
assert __debug__, "Deferred checks require assertions enabled."
assert Path(_helper.__file__).resolve() == _path
assert list(DEFAULT_IV48) == ["text", *_helper.NUMERIC_DEFAULTS]
state = dict(DEFAULT_IV48)
record = derive_iv48(state)
_helper._assert_complete_record(record, 371, 306)
outputs, tensors = record["outputs"], {item["id"]: item for item in record["tensors"]}
summary_names = ["observedTokens", "cacheEntries", "cachedQueryRows", "YMaxError", "cachedScoreCells", "referenceQueryRows", "referenceScoreCells", "actualHarnessRows", "retainedExact", "KMaxError", "VMaxError", "AttentionMaxError", "LogitsMaxError", "PMaxError", "classCount", "actualMerges", "B", "D", "H", "Dk", "Dv", "hiddenWidth", "byteBound", "lastNextRow", "lastNextID", "lastNextProbability"]
assert list(outputs)[:37] == [*summary_names, *(f"tokenizer_{key}" for key in _helper._TOKENIZER_SUMMARY)]
assert list(record["texts"]) == ["input", "decoded", "cacheRevision", "cacheTrust", "modelIdentityPolicy", "positionPolicy", "modelVocabulary", "tokenizer_corpus", "tokenizer_input", "tokenizer_corpusDecoded", "tokenizer_decoded", "tokenizer_corpusLabels", "tokenizer_corpusExpansions", "tokenizer_targetLabels", "tokenizer_targetExpansions", "tokenizer_ruleLabels", "tokenizer_ruleExpansions", "tokenizer_trainingStop"]
assert tensors["ObservedIDs"]["values"] == [97, 98, 97]
assert tensors["GrowthQueryRows"]["values"] == [1, 1, 1]
assert tensors["GrowthKeyCounts"]["values"] == [1, 2, 3]
assert tensors["GrowthRetainedExact"]["values"] == [1, 1, 1]
assert outputs["actualHarnessRows"] == 6 and outputs["cachedScoreCells"] == 6 and outputs["referenceScoreCells"] == 9
assert outputs["lastNextID"] == 97 and outputs["classCount"] == 3
assert record["texts"]["decoded"] == "aba"
assert sum(item["id"].startswith("reference_") for item in record["tensors"]) == 57
assert sum(step["id"].startswith("reference_") for step in record["steps"]) == 169
for t, count in enumerate((63, 67, 67)):
stem = f"growth{t}_"
assert sum(item["id"].startswith(stem) for item in record["tensors"]) == count
assert sum(step["id"].startswith(stem) for step in record["steps"]) == 55 + t
assert tensors[f"{stem}AbsoluteQueryPosition"]["values"] == [t]
assert tensors[f"{stem}ChoiceP"]["shape"] == [3]
assert tensors[f"{stem}Logits"]["shape"] == [1, 3]
assert tensors[f"{stem}Attentionallowed"]["values"] == [True] * (t + 1)
if t:
assert tensors[f"{stem}BeforeKeys"]["values"] == tensors[f"{stem}AfterKeys"]["values"][:-2]
assert tensors[f"{stem}BeforeValues"]["values"] == tensors[f"{stem}AfterValues"]["values"][:-2]
_helper._assert_comparisons(record, [3, 2], [3, 3])
steps = {step["id"]: step for step in record["steps"]}
assert list(steps["growth1_append"]["inputs"]) == ["N", "newID", "newK0", "newK1", "newV0", "newV1", "beforeID0", "beforePosition0", "beforeK0", "beforeK1", "beforeV0", "beforeV1"]
assert list(steps["compare_K"]["inputs"])[:4] == ["count", "initialMaximum", "cached0", "full0"]
assert list(steps["compare_K"]["outputs"])[:3] == ["delta0", "absolute0", "runningMax0"]
assert steps["growth2_row"]["inputs"]["allowed2"] == 1
assert steps["growth2_input_0"]["label"] == "growth2: Gather only new observed ID97 at absolute position 2"
assert steps["reference_input_0"]["label"] == "reference: Gather observed token at position 0"
for text, merges, ids in (("a", 0, [97]), ("aaa", 0, [97, 97, 97]), ("ab", 1, [256]), ("abab", 2, [257])):
other = derive_iv48({**state, "text": text, "merges": merges})
assert _helper._tensor_values(other, "ObservedIDs") == ids
assert len(other["steps"]) <= 439 and len(other["tensors"]) <= 325
maximum = derive_iv48({**state, "text": "ababaa", "merges": 2})
_helper._assert_complete_record(maximum, 431, 325)
assert _helper._tensor_values(maximum, "ObservedIDs") == [257, 97, 97]
for patch, code in (({"text": ""}, "UNAVAILABLE"), ({"text": "c"}, "UNAVAILABLE"),
({"text": "a" * 7}, "UNSUPPORTED_SIZE"), ({"text": "aaaa"}, "UNSUPPORTED_SIZE"),
({"text": "\ud800"}, "INVALID_INPUT"), ({"text": "🦊🦊"}, "UNSUPPORTED_SIZE"),
({"text": "\ud800", "b4": float("nan")}, "NONFINITE"), ({"text": [], "b4": float("nan")}, "INVALID_INPUT"),
({"text": "a" * 6 + "\ud800"}, "UNSUPPORTED_SIZE"), ({"text": "é" * 4}, "UNSUPPORTED_SIZE"),
({"text": "é"}, "UNAVAILABLE"), ({"text": "a", "u04": True}, "NONFINITE"), ({"text": "a", "e40": 3}, "INVALID_INPUT")):
fault = derive_iv48({**state, **patch})
assert list(fault) == ["status", "code", "reason"] and fault["code"] == code
assert derive_iv48({})["code"] == derive_iv48({**state, "extra": 0})["code"] == "INVALID_INPUT"
record["tensors"][0]["values"].clear()
record["texts"]["modelVocabulary"].clear()
record["steps"][0]["inputs"].clear()
assert derive_iv48(state)["texts"]["modelVocabulary"] == list(_helper._MODEL_VOCABULARY)
assert derive_iv48(state)["tensors"][0]["values"] and state == dict(DEFAULT_IV48)
if __name__ == "__main__":
_helper.run(derive_iv48, DEFAULT_IV48, source_self_check)
Cache mechanics — code/python/p12/cache_reference.py. empty_cache validates parameters and creates empty metadata. prefill_cache performs the real full forward and copies its rotated K and unrotated V. append_cached first checks structure, model identity and requested prefix, then gathers only the new embedding. Follow its two-product score sums, ascending-key softmax and value mixture, residuals, normalization, FFN and active readout. The scalar products and running sums correspond to the hand derivation above; they are not an animation or a slice of recomputed old queries. Its external coherence precondition remains explicit.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""Part XII canonical NumPy and complete owner-adopted ordered records.
Keep the disclosed twelve-file relative source closure. External cache numeric
coherence is an INPUT PRECONDITION; metadata cannot certify finite forgeries.
Helpers return detached plain data and never mutate inputs. Python callers can
mutate their own returns; no freezing is claimed. All execution is deferred.
"""
import argparse
import importlib.util
import json
import math
from pathlib import Path
import sys
from types import MappingProxyType
import numpy as np
_ROOT = Path(__file__).resolve().parent.parent
def _load(name, path):
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise ImportError(f"Cannot load canonical dependency: {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
_inference = _load("_p12_inference", _ROOT / "p11" / "inference_reference.py")
_choice = _load("_p12_choice", _ROOT / "p11" / "choice_reference.py")
_tiny, _iv39 = _inference._tiny, _inference._iv39
_bpe, _token = _inference._bpe, _inference._token
_component, _head, _ffn = _tiny._component, _tiny._head, _tiny._ffn
NumericalFault = _tiny.NumericalFault
_DEPENDENCY_FAULTS = (*_inference._DEPENDENCY_FAULTS, _choice.NumericalFault)
NUMERIC_DEFAULTS, ALL_IDS = _tiny.NUMERIC_DEFAULTS, _tiny.ALL_IDS
DEFAULT_IV48 = MappingProxyType(dict(text="aba", **NUMERIC_DEFAULTS))
DEFAULT_IV49 = MappingProxyType(dict(_inference.DEFAULT_IV44))
REVISION = "tiny-kv-v1"
CACHE_FIELDS = ("revision", "parameters", "ids", "positions", "keys", "values")
def detached(value):
"""Copy finite JSON; returned Python lists belong to their caller."""
return json.loads(json.dumps(value, allow_nan=False, ensure_ascii=False))
def guarded(derive):
def call(state):
try:
return derive(state)
except _DEPENDENCY_FAULTS as error:
return dict(status="unavailable", code=error.code, reason=str(error))
except (OverflowError, FloatingPointError) as error:
return dict(status="unavailable", code="NONFINITE", reason=str(error))
call.__name__, call.__doc__ = derive.__name__, derive.__doc__
return call
def _prefix(prefix):
if type(prefix) is not str or not prefix:
raise NumericalFault("INVALID_INPUT", "prefix must be an actual nonempty string.")
def _array(values, label):
# Exact built-ins reject custom access before reading numerical entries.
if type(values) is not list:
raise NumericalFault("INVALID_INPUT", f"{label} must have the ordinary Array prototype.")
if len(values) > 6:
raise NumericalFault("UNSUPPORTED_SIZE", f"{label} exceeds 6 stored entries.")
def _token_length(length, allow_empty=True):
if not allow_empty and not length:
raise NumericalFault("UNAVAILABLE", "Numeric prefill requires at least one observed token.")
if length > 3:
raise NumericalFault("UNSUPPORTED_SIZE", "Cache prefixes support at most 3 observed tokens.")
def _active_id(value, active, label):
if type(value) not in (int, float):
raise NumericalFault("INVALID_INPUT", f"{label} must be an active public model ID.")
try:
number = float(value)
except (ValueError, OverflowError) as error:
raise NumericalFault("INVALID_INPUT", f"{label} must be an active public model ID.") from error
if not math.isfinite(number) or not number.is_integer() or number not in active:
raise NumericalFault("INVALID_INPUT", f"{label} must be an active public model ID.")
return int(number)
def _cache(parameters, ids, keys, values):
return detached(dict(revision=REVISION, parameters=parameters, ids=ids,
positions=list(range(len(ids))), keys=keys, values=values))
def empty_cache(parameters):
"""Validate all26; empty metadata emits no neural step or empty tensor."""
return _cache(_tiny.numeric_parameters(parameters), [], [], [])
def _validated_append(parameters, expected_prefix_ids, cache, new_id, prefix):
"""Signed guard order, with zero new neural arithmetic before acceptance."""
_prefix(prefix)
target = _tiny.numeric_parameters(parameters)
if type(cache) is not dict:
raise NumericalFault("INVALID_INPUT", "cache must be a plain object.")
if any(type(key) is not str for key in cache) or set(cache) != set(CACHE_FIELDS):
raise NumericalFault("INVALID_INPUT", "cache requires exactly revision, parameters, ids, positions, keys, values as own data fields.")
if type(cache["revision"]) is not str or cache["revision"] != REVISION:
raise NumericalFault("INVALID_INPUT", "cache.revision must be tiny-kv-v1.")
old = _tiny.numeric_parameters(cache["parameters"])
for key in ("ids", "positions", "keys", "values"):
_array(cache[key], f"cache.{key}")
N = len(cache["ids"])
_token_length(N)
if len(cache["positions"]) != N or len(cache["keys"]) != 2 * N or len(cache["values"]) != 2 * N:
raise NumericalFault("SHAPE_MISMATCH", "cache positions length must be N; keys and values lengths must be 2N.")
ids = [_active_id(value, ALL_IDS[:3 + old["merges"]], f"cache.ids[{j}]") for j, value in enumerate(cache["ids"])]
for j, value in enumerate(cache["positions"]):
if type(value) not in (int, float) or value != j:
raise NumericalFault("INVALID_INPUT", "CACHE_POSITION_MISMATCH: positions must be exact ordered integers 0..N-1.")
keys = [_tiny.finite(value, f"cache.keys[{j}]") for j, value in enumerate(cache["keys"])]
values = [_tiny.finite(value, f"cache.values[{j}]") for j, value in enumerate(cache["values"])]
_array(expected_prefix_ids, "expectedPrefixIDs")
_token_length(len(expected_prefix_ids))
expected = [_active_id(value, ALL_IDS[:3 + target["merges"]], f"expectedPrefixIDs[{j}]") for j, value in enumerate(expected_prefix_ids)]
scalar = _tiny.finite(new_id, "newID")
if not scalar.is_integer() or scalar not in ALL_IDS[:3 + target["merges"]]:
raise NumericalFault("INVALID_INPUT", "newID must be an active public model ID.")
if any(target[key] != old[key] for key in NUMERIC_DEFAULTS):
raise NumericalFault("UNAVAILABLE", "CACHE_MODEL_MISMATCH: all 26 numeric parameters must agree under numeric ===.")
if expected != ids:
raise NumericalFault("UNAVAILABLE", "CACHE_PREFIX_MISMATCH: the requested ordered prefix must equal cache.ids.")
if N >= 3:
raise NumericalFault("UNSUPPORTED_SIZE", "Appending would exceed 3 observed cache entries.")
return target, old, ids, keys, values, int(scalar)
def _scope(trace, saved, prefix, context):
for step in saved.steps:
trace.add(f"{prefix}_{step['id']}", f"{prefix}: {step['label']}", step["equation"],
f"{context} {step['explanation']}", step["inputs"], step["outputs"])
def _old_step(step):
"""Literal adopted old primitive prose; never parse TS or interpret math."""
identifier, inputs = step["id"], step["inputs"]
label, equation, explanation = step["label"], step["equation"], step["explanation"]
head_id = identifier.removeprefix("heads_")
if identifier.startswith(("ln1_", "ln2_")):
if identifier.endswith("_statistics"):
stem = identifier.removesuffix("_statistics")
label = f"{stem}: feature-only mean and population variance"
equation = "sum=x0+x1; mean=sum/2; centered=x-mean; squareSum=centered0²+centered1²; variance=squareSum/2; denominator=sqrt(variance+epsilon)"
explanation = "Only these two features contribute. Epsilon is inside the square root; no batch or token statistics are mixed."
else:
explanation = "The source is the saved centered feature. Gamma and beta may change output mean and variance."
elif identifier.startswith("ffn_hidden_"):
explanation = "The same W1 and b1 apply separately to each token. Add bias after the two input products; no token sum occurs."
elif identifier.startswith("ffn_relu_"):
explanation = "ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself."
elif identifier.startswith("ffn_output_"):
explanation = "Multiply then immediately accumulate hidden features in ascending order 0,1,2. Add b2 last. Output may be signed; there is no softmax or residual inside the FFN."
elif head_id == "setup":
label, equation = "Validate every scalar slot, then select active dimensions", "D=2; X[B,T,2]; WQ,WK[2,H*Dk]; WV[2,H*Dv]"
explanation = "All inactive fields remain finite and bounded. Parameter names identify input d, head h and feature f, so changing width never relabels a head’s weights."
elif head_id.startswith("project_"):
role = head_id.split("_")[1]
b, t, h, f = (int(inputs[key]) for key in ("b", "t", "h", "f"))
label = f"{role}[{b},{t},head {h},feature {f}]: both input contributions"
explanation = "One token row times the packed column h*F+f, keeping both input-feature rows. Weights are hand-set; no bias, activation or learning is hidden."
elif head_id.startswith("reshape_"):
role = head_id.split("_")[1]
label, equation = f"{role}: reshape the packed feature axis", "[B,T,H*F] → [B,T,H,F]; feature=h*F+f"
explanation = "Reshaping preserves every flat value and its order. H counts attention heads; F counts features within each head. No projection feature is dropped."
elif head_id.startswith("permute_"):
role = head_id.split("_")[1]
b, t, h, f = (int(inputs[key]) for key in ("b", "t", "h", "f"))
label = f"{role}: copy [{b},{t},{h},{f}] to [{b},{h},{t},{f}]"
equation = "axes [0,2,1,3]; destination[b,h,t,f]=source[b,t,h,f]"
explanation = "Moving the head axis is a declared permutation, separate from reshape. The recorded offsets are actual row-major flat indices; this indexed value is copied unchanged."
elif head_id.startswith("score_"):
explanation = "Matching features are multiplied inside this batch and head only. Dk, not H or T or Dv, supplies the scaling width. Signed scores are not probabilities."
elif head_id.startswith("row_"):
b, h, i = (int(inputs[key]) for key in ("b", "h", "i"))
label = f"Batch {b}, head {h}, query {i}: key-axis stable softmax"
explanation = "Each head has its own probabilities. Key validity is shared across batches and heads; queries remain. Forbidden terms are exactly zero, without an infinity sentinel or invented shifted value. Allowed terms can underflow; a large common shift can change low bits."
elif head_id.startswith("head_mix_"):
b, h, i, f = (int(inputs[key]) for key in ("b", "h", "i", "f"))
label = f"OHeads[{b},{h},{i},{f}]: this head’s weighted values"
explanation = "Use the real probability row and values in the same head and batch. Compute each product, then immediately accumulate in ascending key order, including actual zero times V for forbidden keys. No averaging across heads or extra division."
elif head_id.startswith("concat_"):
b, t, h, f, c = (int(inputs[key]) for key in ("b", "t", "h", "f", "concatFeature"))
label = f"Join head {h}, feature {f} into C[{b},{t},{c}]"
explanation = "Copy one actual head output unchanged. Concatenate in head order then within-head feature order; never average heads or mix batches."
elif head_id.startswith("output_"):
b, t, d = (int(inputs[key]) for key in ("b", "t", "d"))
label = f"Y[{b},{t},{d}]: explicit output projection"
equation = "product_c=C_c*WO[c,d]; running starts at 0; running_c=previous+product_c; Y=last running sum"
explanation = "WO rows preserve named head/feature identity when Dv changes. Every joined feature contributes one recorded product and running sum. Y may be signed; no output softmax, bias, residual, dropout or normalization is added."
elif identifier.startswith("input_"):
t = int(inputs["t"])
label, equation = f"Gather observed token at position {t}", "inputRow=compactRow(inputID); X[0,t,:]=E[inputRow,:]"
explanation = "EOS is an ordinary available embedding row in this numeric kernel. There is no implicit stop rule or target lookup."
elif identifier.startswith("rope_"):
role, t = identifier.split("_")[1], int(inputs["t"])
label = f"Rotate {role} pair at absolute position {t}"
equation = "frequency=10000^0; angle=t*frequency; cos=cos(angle); sin=sin(angle); rotated0=x0*cos-x1*sin; rotated1=x0*sin+x1*cos"
explanation = "The only adjacent feature pair has frequency1 and angle t radians. Q and K rotate; V keeps its original projection. Every product and both final coordinates are saved."
elif identifier.startswith(("residual1_", "residual2_")):
t, d = int(inputs["t"]), int(inputs["d"])
if identifier.startswith("residual1_"):
label, equation = f"First residual position {t}, feature {d}", "value=X+AttentionOutput"
explanation = "Add identical named [B,T,D] shapes without broadcasting. The shortcut carries the original embedding."
else:
label, equation = f"Second residual position {t}, feature {d}", "value=R1+F"
explanation = "The FFN applies to each token separately; the real third hidden coordinate is computed with zero weights."
elif identifier.startswith("readout_"):
t, c = int(inputs["t"]), int(inputs["c"])
label = f"Readout position {t}, class {c}"
explanation = "Final decoder features multiply only the active class columns. Bias is added last; targets are not operands."
elif identifier.startswith("class_"):
t, kind = int(identifier.split("_")[1]), identifier.split("_")[2]
if kind == "max":
label = f"Position {t}: active class maximum"
explanation = "The maximum stabilizes exponentiation; every active class participates before the target is selected."
elif kind == "exp":
label = f"Position {t}: exponentiate class {int(inputs['c'])}"
explanation = "At least one term is exp(0)=1. No probability is clipped or rounded for this calculation."
elif kind == "normalize":
label = f"Position {t}: class denominator and logsumexp"
equation = "running starts at 0; running_c=previous+term_c; S=last running; logS=ln(S); LSE=max+logS"
explanation = "Terms accumulate left to right in compact class order. NLL later uses the factored max-minus-target form, not subtraction of a rounded LSE."
elif kind == "probability":
label, equation = f"Position {t}: normalize class {int(inputs['c'])}", "probability=term/S"
explanation = "This is the stored binary64 probability for a real active class, before display formatting."
elif kind == "argmax":
label, equation = f"Position {t}: computed-logit winner", "argmax computed logits; exact ties choose smallest compact class"
explanation = "Stored probabilities can appear tied even for different computed logits. This prediction is inspected, never fed back into teacher forcing."
return label, equation, explanation
def _copy_old_steps(saved, trace, prefix="", context=""):
for step in saved.steps:
label, equation, explanation = _old_step(step)
trace.add(f"{prefix}_{step['id']}" if prefix else step["id"], f"{prefix}: {label}" if prefix else label,
equation, f"{context} {explanation}" if context else explanation, step["inputs"], step["outputs"])
def _float(identifier, shape, axes, values, provenance):
return _tiny._float_tensor(identifier, shape, axes, np.array(values, dtype=np.float64).reshape(shape), provenance)
def _integer(identifier, axis, values, provenance):
return _token.tensor(identifier, axis, np.array(values, dtype=np.int32), provenance)
def _tensor_values(forward, identifier):
return next(record["values"] for record in forward["tensors"] if record["id"] == identifier)
def cache_tensors(cache, stem):
if not cache["ids"]:
return []
N = len(cache["ids"])
return [
_integer(f"{stem}IDs", "CachePosition", cache["ids"], "Ordered observed public IDs; cache coherence is an external-helper input precondition."),
_integer(f"{stem}Positions", "CachePosition", cache["positions"], "Absolute positions 0..N-1, not local append-query indices."),
_float(f"{stem}Keys", [1, 1, N, 2], ["B", "H", "CachePosition", "Dk"], cache["keys"], "Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation."),
_float(f"{stem}Values", [1, 1, N, 2], ["B", "H", "CachePosition", "Dv"], cache["values"], "Saved unrotated projected V in observed-prefix order."),
]
def scoped_forward(parameters, ids, trace, prefix):
_prefix(prefix)
numeric = _tiny.numeric_parameters(parameters)
_array(ids, "inputIDs")
_token_length(len(ids), False)
ids = [_active_id(value, ALL_IDS[:3 + numeric["merges"]], f"inputIDs[{i}]") for i, value in enumerate(ids)]
saved = _tiny.tiny_trace()
forward = _tiny.forward_tiny(numeric, ids, saved)
context = f"Actual full-prefix call {prefix}, absolute positions 0..{len(ids) - 1}."
_copy_old_steps(saved, trace, prefix, context)
return dict(forward=forward, tensors=_copy_records(forward["tensors"], f"{prefix}_", context))
def prefill_cache(parameters, input_ids, trace, prefix="prefill"):
_prefix(prefix)
numeric = _tiny.numeric_parameters(parameters)
saved = scoped_forward(numeric, input_ids, trace, prefix)
forward = saved["forward"]
keys, values = _tensor_values(forward, "RotatedKHeads"), _tensor_values(forward, "ProjectionVHeads")
cache = _cache(numeric, forward["inputIDs"], keys, values)
inputs, outputs = dict(N=forward["T"]), dict(cacheEntries=len(cache["ids"]))
for j, identifier in enumerate(cache["ids"]):
inputs[f"inputID{j}"] = identifier
outputs[f"id{j}"], outputs[f"position{j}"] = identifier, cache["positions"][j]
for i, value in enumerate(keys):
inputs[f"rotatedK{i}"], outputs[f"key{i}"] = value, cache["keys"][i]
for i, value in enumerate(values):
inputs[f"projectedV{i}"], outputs[f"value{i}"] = value, cache["values"][i]
trace.add(f"{prefix}_capture", "Capture actual full-prefill rotated keys and unrotated values", "cache.K=RotatedKHeads; cache.V=ProjectionVHeads; positions=0..N-1",
"The constructor establishes coherence from real forward outputs. It retains no old queries, hidden rows, logits or probabilities in the cache. Full prefill evidence remains separately saved.", inputs, outputs)
return detached(dict(cache=cache, forward=forward, tensors=[*saved["tensors"], *cache_tensors(cache, f"{prefix}_Cache")]))
def _new_norm(name, source, trace, provenance):
saved = _tiny.tiny_trace()
row = _component.feature_norm("layer", f"{name.lower()}_0", source["values"], [1, 1], [0, 0], 1, saved)
_copy_old_steps(saved, trace)
return _float(name, [1, 1, 2], ["B", "T", "D"], row["values"], provenance)
def _new_residual(identifier, prefix, left, right, trace):
result = _component.same_shape_add(identifier, left, right)
inputs, outputs = {}, {}
for d in range(2):
inputs[f"left{d}"], inputs[f"right{d}"] = left["values"][d], right["values"][d]
outputs[f"value{d}"] = result["values"][d]
trace.add(prefix, f"{identifier}: both new-row residual coordinates", "value_d=left_d+right_d",
"Exact same named [B,T,D] shapes; no broadcast or hidden coordinate omission.", inputs, outputs)
return result
def append_cached(parameters, expected_prefix_ids, cache, new_id, trace, prefix="cache"):
"""Compute one new neural row; external cache coherence is a precondition."""
s, old, ids, old_keys, old_values, new_id = _validated_append(parameters, expected_prefix_ids, cache, new_id, prefix)
N, V, Tk = len(ids), 3 + s["merges"], len(ids) + 1
before, saved = _cache(old, ids, old_keys, old_values), _tiny.tiny_trace()
row = ALL_IDS.index(new_id)
E = np.array([[s[f"e{r}{d}"] for d in range(2)] for r in range(5)], dtype=np.float64)
U = np.array([[s[f"u{d}{c}"] for c in range(5)] for d in range(2)], dtype=np.float64)
bias = np.array([s[f"b{c}"] for c in range(5)], dtype=np.float64)
X = E[row].copy().reshape(1, 1, 2)
saved.add("input_0", f"Gather only new observed ID{new_id} at absolute position {N}", "inputRow=compactRow(newID); X=E[inputRow,:]",
"Numeric helpers permit observed EOS; outer wrappers separately implement logical EOS stopping.",
dict(position=N, newID=new_id), dict(inputRow=row, x0=float(X[0, 0, 0]), x1=float(X[0, 0, 1])))
x_tensor = _float("X", [1, 1, 2], ["B", "T", "D"], X, "Only the new embedding row; local T=1, absolute position is saved separately.")
n1 = _new_norm("LN1", x_tensor, saved, "New-row feature LayerNorm; population variance, epsilon1, gamma1, beta0.")
tensors = [
_integer("AllClassIDs", "ModelRow", ALL_IDS, "All possible compact model rows; public IDs are labels."),
_integer("ClassIDs", "Class", ALL_IDS[:V], "Active compact prefix; V=3+merges."),
_float("E", [5, 2], ["ModelRow", "D"], E, "All ten validated editable embeddings, including inactive rows."),
_float("U", [2, 5], ["D", "ModelRow"], U, "All ten validated readout weights; active prefix alone produces logits."),
_float("Bias", [5], ["ModelRow"], bias, "All five validated biases; inactive columns remain outside the distribution."),
_integer("InputIDs", "LocalPosition", [new_id], "Exactly one new observed token is processed."),
_integer("InputRows", "LocalPosition", [row], "Compact embedding row for the new token."),
_integer("AbsoluteQueryPosition", "Query", [N], "Absolute N, distinct from the single local query index0."),
*cache_tensors(before, "Before"), x_tensor, n1,
]
hs = dict(_head.OUTPUT_HEAD_DEFAULTS)
hs.update(B=1, T=1, H=1, Dk=2, Dv=2, mode=1, shift=0, x000=n1["values"][0], x001=n1["values"][1])
for role in ("wq", "wk", "wv"):
for d in range(2):
for f in range(2):
hs[f"{role}{d}0{f}"] = int(d == f)
for f in range(2):
for d in range(2):
hs[f"wo0{f}{d}"] = int(f == d)
child = _head.head_trace()
projected = _head.project_heads(hs, child)
_copy_old_steps(child, saved, "heads", "Source is the new LN1 row, local T=1.")
tensors.extend({**record, "id": f"Projection{record['id']}", "provenance": f"New LN1 row only. {_tiny._PROJECTION_PROVENANCE[record['id']]}"} for record in projected["tensors"])
rotated = {}
angle = cosine = sine = 0.0
for role in ("Q", "K"):
x0, x1 = (float(projected[f"{role}Heads"][0, 0, 0, d]) for d in range(2))
frequency = 10000 ** 0
angle = _tiny.finite(N * frequency, "RoPE angle")
cosine, sine = _tiny.finite(math.cos(angle), "RoPE cosine"), _tiny.finite(math.sin(angle), "RoPE sine")
p0, p1 = _tiny.finite(x0 * cosine, "RoPE x0*cos"), _tiny.finite(x1 * sine, "RoPE x1*sin")
p2, p3 = _tiny.finite(x0 * sine, "RoPE x0*sin"), _tiny.finite(x1 * cosine, "RoPE x1*cos")
r0, r1 = _tiny.finite(p0 - p1, "RoPE first coordinate"), _tiny.finite(p2 + p3, "RoPE second coordinate")
rotated[role] = np.array([r0, r1], dtype=np.float64).reshape(1, 1, 1, 2)
saved.add(f"rope_{role}_0", f"Rotate new {role} at absolute position {N}", "frequency=10000^0; angle=N*frequency; rotated0=x0*cos-x1*sin; rotated1=x0*sin+x1*cos",
"Only the new Q/K rotate. Cached K is already rotated and V never rotates. Each product and coordinate is real arithmetic.",
dict(position=N, x0=x0, x1=x1, base=10000, exponent=0),
dict(frequency=frequency, angle=angle, cos=cosine, sin=sine, product0=p0, product1=p1, product2=p2, product3=p3, rotated0=r0, rotated1=r1))
new_key, new_value = rotated["K"].reshape(-1).tolist(), projected["VHeads"].reshape(-1).tolist()
tensors.extend([
_float("RotatedQHeads", [1, 1, 1, 2], ["B", "H", "Query", "Dk"], rotated["Q"], "New query rotated at absolute N; Query length1."),
_float("NewRotatedKHeads", [1, 1, 1, 2], ["B", "H", "NewPosition", "Dk"], rotated["K"], "Only the newly computed key, rotated once at absolute N."),
_float("RoPEAngles", [1], ["Query"], [angle], "Actual absolute N times frequency1, radians."),
_float("RoPECos", [1], ["Query"], [cosine], "Cosine used by new Q/K rotations."),
_float("RoPESin", [1], ["Query"], [sine], "Sine used by new Q/K rotations."),
])
after = _cache(s, [*ids, new_id], [*old_keys, *new_key], [*old_values, *new_value])
copy_inputs = dict(N=N, newID=new_id, newK0=new_key[0], newK1=new_key[1], newV0=new_value[0], newV1=new_value[1])
copy_outputs, retained_exact = dict(cacheEntries=Tk), 1
for family, previous, current in (("ID", ids, after["ids"]), ("Position", before["positions"], after["positions"]), ("K", old_keys, after["keys"]), ("V", old_values, after["values"])):
for i, value in enumerate(previous):
copy_inputs[f"before{family}{i}"] = value
equal = int(value == current[i])
copy_outputs[f"retained{family}{i}"] = equal
retained_exact = int(retained_exact and equal)
for i, value in enumerate(current):
copy_outputs[f"after{family}{i}"] = value
copy_outputs["retainedExact"] = retained_exact
if not retained_exact:
raise NumericalFault("UNAVAILABLE", "Retained cache coordinates changed during append.")
saved.add("append", "Copy prior K/V unchanged and append one actual new row", "after=[before,new]; retained_i=(before_i===after_i)",
"Same-implementation retained-copy equality is a narrow check, separate from cross-library numerical witnesses. Empty-before has metadata only, never a zero-shape tensor.", copy_inputs, copy_outputs)
tensors.extend(cache_tensors(after, "After"))
K = np.array(after["keys"], dtype=np.float64).reshape(1, 1, Tk, 2)
values = np.array(after["values"], dtype=np.float64).reshape(1, 1, Tk, 2)
q = rotated["Q"]
shape, axes = [1, 1, 1, Tk], ["B", "H", "Query", "Key"]
raw, scores, logits, terms, probabilities = (np.empty(shape, dtype=np.float64) for _ in range(5))
allowed = np.array([j <= N for j in after["positions"]], dtype=np.bool_).reshape(shape)
divisor = _tiny.finite(math.sqrt(2), "sqrt(Dk)")
for j in range(Tk):
q0, q1, k0, k1 = float(q[0, 0, 0, 0]), float(q[0, 0, 0, 1]), float(K[0, 0, j, 0]), float(K[0, 0, j, 1])
p0, p1 = _tiny.finite(q0 * k0, "score product0"), _tiny.finite(q1 * k1, "score product1")
dot = _tiny.finite(p0 + p1, "raw score")
score = _tiny.finite(dot / divisor, "scaled score")
raw[0, 0, 0, j], scores[0, 0, 0, j] = dot, score
saved.add(f"score_{j}", f"New absolute query {N} against cached key {j}", "product0=q0*k0; product1=q1*k1; raw=product0+product1; score=raw/sqrt(Dk)",
"The query axis has length1; the key axis has length N+1. Only this new query is evaluated.",
dict(position=N, j=j, Dk=2, divisor=divisor, q0=q0, k0=k0, q1=q1, k1=k1), dict(product0=p0, product1=p1, raw=dot, score=score))
for j in range(Tk):
logits[0, 0, 0, j] = _tiny.finite(float(scores[0, 0, 0, j]) + 0, "attention common shift")
maximum = max(float(logits[0, 0, 0, j]) for j in range(Tk) if allowed[0, 0, 0, j])
inputs, outputs, denominator = dict(position=N, shift=0), dict(max=maximum), 0.0
for j in range(Tk):
inputs.update({f"score{j}": float(scores[0, 0, 0, j]), f"keyPosition{j}": after["positions"][j], f"allowed{j}": int(allowed[0, 0, 0, j])})
logit = float(logits[0, 0, 0, j])
shift = _tiny.finite(logit - maximum, "attention shifted logit")
term = _tiny.finite(math.exp(shift), "attention exp") if allowed[0, 0, 0, j] else 0.0
terms[0, 0, 0, j] = term
denominator = _tiny.finite(denominator + term, "attention denominator")
outputs.update({f"logit{j}": logit, f"shifted{j}": shift, f"term{j}": term, f"running{j}": denominator})
if not denominator > 0:
raise NumericalFault("FULLY_MASKED_ROW", "The new query has no allowed key.")
outputs["denominator"] = denominator
for j in range(Tk):
probability = _tiny.finite(float(terms[0, 0, 0, j]) / denominator, "attention probability")
probabilities[0, 0, 0, j], outputs[f"p{j}"] = probability, probability
saved.add("row", "Normalize every available key at the absolute append position", "logit=score+0; allowed=(keyPosition<=N); max=max(allowed logits); term=exp(logit-max); running starts0; p=term/denominator",
"All available positions0..N are allowed. Comparing keys to local query0 would be wrong. Every shift, exponential and left-to-right running sum is retained.", inputs, outputs)
O = np.empty((1, 1, 1, 2), dtype=np.float64)
for d in range(2):
inputs, outputs, running = dict(d=d), {}, 0.0
for j in range(Tk):
probability, value = float(probabilities[0, 0, 0, j]), float(values[0, 0, j, d])
product = _tiny.finite(probability * value, "weighted V product")
running = _tiny.finite(running + product, "weighted V running sum")
inputs[f"p{j}"], inputs[f"v{j}"] = probability, value
outputs[f"product{j}"], outputs[f"running{j}"] = product, running
O[0, 0, 0, d], outputs["value"] = running, running
saved.add(f"mix_{d}", f"Mix unrotated value feature {d}", "product_j=p_j*v_j; running starts0; running_j=previous+product_j; value=last running",
"Multiply then immediately accumulate in ascending cached-key order.", inputs, outputs)
tensors.extend([
_float("Attentionraw", shape, axes, raw, "Actual two-product new Q dot every cached K."),
_float("Attentionscores", shape, axes, scores, "Raw dot products divided by sqrt(Dk=2)."),
_head.tensor("Attentionallowed", shape, axes, allowed, "Allowed iff cached absolute key position <= absolute query N."),
_float("Attentionlogits", shape, axes, logits, "Actual scaled scores plus the fixed common shift0."),
_float("Attentionprobabilities", shape, axes, probabilities, "Stable softmax over the complete cached key axis; Query length1."),
_float("AttentionOHeads", [1, 1, 1, 2], ["B", "H", "Query", "Dv"], O, "New query weighted sum of all unrotated cached V."),
])
C = O.transpose(0, 2, 1, 3).copy().reshape(1, 1, 2)
saved.add("concat", "Copy the one-head output into joined feature order", "C[d]=OHeads[0,0,0,d]; sourceOffset=d; destinationOffset=d",
"H=1 still has a real declared copy; both coordinates and offsets are retained.",
dict(sourceOffset0=0, sourceValue0=float(O[0, 0, 0, 0]), sourceOffset1=1, sourceValue1=float(O[0, 0, 0, 1])),
dict(destinationOffset0=0, c0=float(C[0, 0, 0]), destinationOffset1=1, c1=float(C[0, 0, 1])))
WO, attention = np.eye(2, dtype=np.float64), np.empty((1, 1, 2), dtype=np.float64)
for d in range(2):
inputs, outputs, running = dict(d=d), {}, 0.0
for f in range(2):
c, w = float(C[0, 0, f]), float(WO[f, d])
product = _tiny.finite(c * w, "WO product")
running = _tiny.finite(running + product, "WO running sum")
inputs[f"c{f}"], inputs[f"w{f}"] = c, w
outputs[f"product{f}"], outputs[f"running{f}"] = product, running
attention[0, 0, d], outputs["value"] = running, running
saved.add(f"output_{d}", f"Identity output projection feature {d}", "product0=c0*w0; running0=0+product0; product1=c1*w1; running1=running0+product1; value=running1",
"Identity WO is actually multiplied in the same order as the full-prefix kernel; neither products nor zero additions are bypassed.", inputs, outputs)
tensors.extend([
_float("AttentionC", [1, 1, 2], ["B", "T", "JoinedValue"], C, "One-head Query to local token-major joined-feature copy."),
_float("AttentionWO", [2, 2], ["JoinedValue", "D"], WO, "Explicit identity2 output projection."),
_float("AttentionOutput", [1, 1, 2], ["B", "T", "D"], attention, "C WO for one local row, with explicit identity WO."),
])
r1 = _new_residual("R1", "residual1", x_tensor, tensors[-1], saved)
n2 = _new_norm("LN2", r1, saved, "New-row feature LayerNorm of R1; population variance, epsilon1, gamma1, beta0.")
fs = dict(B=1, T=1, f100=1, f101=0, f102=0, f110=0, f111=1, f112=0,
fb10=0, fb11=0, fb12=0, f200=1, f201=0, f210=0, f211=1, f220=0, f221=0, fb20=0, fb21=0)
child = _tiny.tiny_trace()
ffn = _ffn.feed_forward(fs, n2, child, "ffn")
_copy_old_steps(child, saved)
ft = [{**record, "provenance": _tiny._FFN_PROVENANCE[record["id"]]} for record in ffn["tensors"]]
y = _new_residual("Y", "residual2", r1, ffn["output"], saved)
tensors.extend([r1, n2, *ft, y])
z = np.empty(V, dtype=np.float64)
for c in range(V):
y0, y1, u0, u1, b = y["values"][0], y["values"][1], float(U[0, c]), float(U[1, c]), float(bias[c])
p0, p1 = _tiny.finite(y0 * u0, "readout product0"), _tiny.finite(y1 * u1, "readout product1")
summed = _tiny.finite(p0 + p1, "readout sum")
z[c] = _tiny.finite(summed + b, "readout logit")
saved.add(f"readout_{c}", f"Read out active compact class {c}", "product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias",
"Only V=3+merges active columns are output classes; all five storage columns were validated.",
dict(c=c, y0=y0, u0=u0, y1=y1, u1=u1, bias=b), dict(product0=p0, product1=p1, sum=summed, logit=float(z[c])))
tensors.append(_float("Logits", [1, V], ["Position", "Class"], z, "Actual new Y times active U, then active Bias."))
distribution = _choice.direct_distribution(z, np.array(ALL_IDS[:V], dtype=np.int32), saved, "class")
tensors.extend({**record, "id": f"Choice{record['id']}"} for record in distribution["tensors"])
_scope(trace, saved, prefix, f"True one-query append: local row0 is absolute position {N}; no prior query or old K/V projection is recomputed.")
tensors = _copy_records(tensors, f"{prefix}_", f"Actual cached append {prefix}: local row0 is absolute {N}; no old query/K/V recomputation.")
return detached(dict(before=before, cache=after, position=N, newID=new_id, distribution=distribution, tensors=tensors))
def _raw_state(state, observed_append=False):
defaults = DEFAULT_IV49 if observed_append else DEFAULT_IV48
if type(state) is not dict:
reason = "Provide a plain object with exactly the named input fields." if observed_append else "Provide a plain object with exactly the named data fields."
raise NumericalFault("INVALID_INPUT", reason)
if any(type(key) is not str for key in state) or set(state) != set(defaults):
reason = "Provide every field, including inactive parameters, and no extra or symbol fields." if observed_append else "Provide every own field and no extra or symbol fields, including inactive parameters."
raise NumericalFault("INVALID_INPUT", reason)
checked = _tiny.tiny_state({key: state[key] for key in DEFAULT_IV48})
if observed_append:
next_id = _tiny.finite(state["nextID"], "nextID")
if not next_id.is_integer() or next_id not in ALL_IDS[:3 + checked["numeric"]["merges"]]:
raise NumericalFault("INVALID_INPUT", "nextID must be an active public ID: a97, b98, EOS512, ab256 with merges>=1, or abab257 with merges=2.")
checked["nextID"] = int(next_id)
return checked
def cache_prompt(text, merges, token_bound=3):
"""Real IV39 once, then the adopted outer text/token semantics in order."""
if type(text) is not str:
raise NumericalFault("INVALID_INPUT", "text must be an actual string.")
merges = _tiny.finite(merges, "merges")
if not merges.is_integer() or not 0 <= merges <= 2:
raise NumericalFault("INVALID_INPUT", "merges must be an integer from 0 to 2.")
if _token.utf16_length(text) > 6:
raise NumericalFault("UNSUPPORTED_SIZE", "text exceeds the outer 6 UTF-16-unit guard for a 6-byte prompt.")
prompt = _iv39.derive_iv39(dict(corpus="abab", text=text, merges=int(merges), eos=0))
if prompt["status"] != "defined":
raise NumericalFault(prompt["code"], prompt["reason"])
values = lambda identifier: next((record["values"] for record in prompt["tensors"] if record["id"] == identifier), [])
data = values("SourceBytes")
if len(data) > 6:
raise NumericalFault("UNSUPPORTED_SIZE", "The actual UTF-8 prompt exceeds 6 bytes.")
if any(byte not in (97, 98) for byte in data):
reason = "This toy prompt accepts raw a/b letters only, without normalization, unknown tokens or truncation." if token_bound == 3 else "This toy prompt accepts raw a/b letters only; no normalization, unknown token or truncation is applied."
raise NumericalFault("UNAVAILABLE", reason)
if not data:
reason = "An empty prompt has no observed first token." if token_bound == 3 else "An empty prompt has no observed first token to prefill."
raise NumericalFault("UNAVAILABLE", reason)
ids = np.array(values("TargetIDs"), dtype=np.int32)
if len(ids) > token_bound:
reason = "The actual BPE prompt exceeds 3 tokens; change text or merges explicitly." if token_bound == 3 else "The actual BPE prompt exceeds 2 tokens; change the text or merges explicitly."
raise NumericalFault("UNSUPPORTED_SIZE", reason)
return prompt, ids
def _copy_records(records, stem, context):
return [{**record, "id": f"{stem}{record['id']}", "provenance": f"{context} {record['provenance']}"} for record in records]
def _prompt_evidence(prompt, trace):
for step in prompt["steps"]:
trace.add(f"tokenizer_{step['id']}", step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
return _copy_records(prompt["tensors"], "tokenizer_", "Actual prompt BPE once, fixed corpus abab and EOS off.")
def compare_values(name, cached, full, shape, axes, trace, tensors):
"""Save each actual subtraction, absolute value and running maximum."""
if len(cached) != len(full):
raise NumericalFault("SHAPE_MISMATCH", f"{name}: comparison operands must have identical lengths.")
a, b = (np.array(values, dtype=np.float64).reshape(shape) for values in (cached, full))
delta, absolute, running = (np.empty(shape, dtype=np.float64) for _ in range(3))
inputs, outputs, maximum = dict(count=len(cached), initialMaximum=0), {}, 0.0
for i, (left, right) in enumerate(zip(cached, full)):
inputs[f"cached{i}"], inputs[f"full{i}"] = left, right
difference = _tiny.finite(left - right, f"{name} subtraction")
error = _tiny.finite(abs(difference), f"{name} absolute error")
maximum = max(maximum, error)
delta.flat[i], absolute.flat[i], running.flat[i] = difference, error, maximum
outputs[f"delta{i}"], outputs[f"absolute{i}"], outputs[f"runningMax{i}"] = difference, error, maximum
outputs["maximum"] = maximum
trace.add(f"compare_{name}", f"Compare every actual {name} coordinate", "delta_i=cached_i-full_i; absolute_i=abs(delta_i); runningMax_i=max(previous,absolute_i)",
"These are actual saved operands, subtractions and maxima. No zero fill, rounding or universal cross-library bitwise assertion is used.", inputs, outputs)
for suffix, data, provenance in (("Cached", a, "Actual cached operands."), ("Full", b, "Actual independently recomputed full-prefix operands."),
("Delta", delta, "Actual cached-full subtraction."), ("Abs", absolute, "Actual abs(Delta)."),
("RunningMax", running, "Actual running maximum from0 in flat coordinate order.")):
tensors.append(_float(f"Compare{name}{suffix}", shape, axes, data, provenance))
return maximum
_TOKENIZER_SUMMARY = ("corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges", "corpusTokens", "eos", "byteBound", "vocabularyItems", "corpusEqual", "equal")
_MODEL_VOCABULARY = ["0: a / ID97", "1: b / ID98", "2: EOS / ID512", "3: ab / ID256 (merges>=1)", "4: abab / ID257 (merges=2)"]
_CACHE_TRUST = "External helper callers must supply coherent K/V. Finite metadata, freezing and structural checks do not certify arbitrary supplied payloads. The app constructs every cache internally."
def chapter_record(summary, trace, tensors, texts):
"""Detach the complete root, summary then every ordered scalar alias."""
outputs = dict(summary)
for step in trace.steps:
outputs.update({f"{step['id']}_{key}": value for key, value in step["outputs"].items()})
return detached(dict(status="defined", outputs=outputs, steps=trace.steps, tensors=tensors, texts=texts))
def cache_growth(state):
"""Complete IV48: genuine observed-token growth and one full reference."""
checked = _raw_state(state)
text, numeric = checked["text"], checked["numeric"]
prompt, observed = cache_prompt(text, numeric["merges"])
ids, trace, N, V = observed.tolist(), _tiny.tiny_trace(), len(observed), 3 + numeric["merges"]
trace.add("setup", "Validate every raw field before interpreting text; start with empty cache metadata", "N=actual BPE token count1..3; active V=3+merges; fixed corpus abab; EOS off",
"All26 numeric fields validate before Unicode/domain checks. The app accepts no raw K/V. Each cache row is constructed internally at its absolute position; the final reference is one genuine full-prefix call.",
numeric, dict(utf16Units=_token.utf16_length(text), byteBound=6, tokenBound=3, observedTokens=N, classCount=V, initialCacheEntries=0))
tensors = _prompt_evidence(prompt, trace)
cache, cached_score_cells, retained_exact = empty_cache(numeric), 0, 1
growth, query_rows, key_counts, copies = [], [], [], []
for t, identifier in enumerate(ids):
saved = append_cached(numeric, ids[:t], cache, identifier, trace, f"growth{t}")
growth.append(saved)
tensors.extend(saved["tensors"])
cache = saved["cache"]
cached_score_cells += len(cache["ids"])
exact = int(saved["before"]["keys"] == cache["keys"][:2 * t] and saved["before"]["values"] == cache["values"][:2 * t])
retained_exact = int(retained_exact and exact)
query_rows.append(1)
key_counts.append(len(cache["ids"]))
copies.append(exact)
trace.add(f"growth_count_{t}", f"Count actual query work after observed token {t}", "newQueryRows=1; runningQueryRows=previous+1; keyCount=t+1; runningScoreCells=previous+keyCount",
"One append computes one new neural row. Prior K/V is copied, not reprojected. These are toy operation counts, never timings.",
dict(t=t, previousQueryRows=t, previousScoreCells=cached_score_cells - len(cache["ids"]), newQueryRows=1, keyCount=len(cache["ids"])),
dict(cachedQueryRows=t + 1, cachedScoreCells=cached_score_cells, cacheEntries=len(cache["ids"]), retainedExact=exact))
reference = scoped_forward(numeric, ids, trace, "reference")
tensors.extend(reference["tensors"])
full = reference["forward"]
from_growth = lambda identifier: [value for t, saved in enumerate(growth) for value in _tensor_values(saved, f"growth{t}_{identifier}")]
comparisons = {}
for name, left, right, width, feature in (
("K", cache["keys"], _tensor_values(full, "RotatedKHeads"), 2, "Dk"),
("V", cache["values"], _tensor_values(full, "ProjectionVHeads"), 2, "Dv"),
("Attention", from_growth("AttentionOHeads"), _tensor_values(full, "AttentionOHeads"), 2, "Dv"),
("Y", from_growth("Y"), _tensor_values(full, "Y"), 2, "D"),
("Logits", from_growth("Logits"), _tensor_values(full, "Logits"), V, "Class"),
("P", [value for saved in growth for value in saved["distribution"]["probabilities"]], _tensor_values(full, "P"), V, "Class"),
):
comparisons[f"{name}MaxError"] = compare_values(name, left, right, [N, width], ["Position", feature], trace, tensors)
tensors.extend([
_integer("ObservedIDs", "Position", ids, "Actual EOS-off observed BPE IDs, never sampled or retokenized."),
_integer("GrowthQueryRows", "Append", query_rows, "Actual new query-row count for each genuine append."),
_integer("GrowthKeyCounts", "Append", key_counts, "Actual available cached keys for each append."),
_integer("GrowthRetainedExact", "Append", copies, "Computed same-implementation prior K/V equality flags; not a cross-library assertion."),
])
trace.add("finish", "Report true cache growth and one complete reference", "cachedQueryRows=N; referenceQueryRows=N; actualHarnessRows=2*N",
"Causality lets each new cached row be compared with its corresponding row of the single final full-prefix call. Every error is computed from actual saved operands.",
dict(observedTokens=N, cachedQueryRows=len(growth), referenceQueryRows=full["T"], cachedScoreCells=cached_score_cells, referenceScoreCells=N * N),
dict(cacheEntries=len(cache["ids"]), actualHarnessRows=len(growth) + full["T"], retainedExact=retained_exact, **comparisons))
last = growth[-1]["distribution"]
summary = dict(observedTokens=N, cacheEntries=len(cache["ids"]), cachedQueryRows=len(growth), YMaxError=comparisons["YMaxError"],
cachedScoreCells=cached_score_cells, referenceQueryRows=full["T"], referenceScoreCells=N * N, actualHarnessRows=len(growth) + full["T"],
retainedExact=retained_exact, KMaxError=comparisons["KMaxError"], VMaxError=comparisons["VMaxError"], AttentionMaxError=comparisons["AttentionMaxError"],
LogitsMaxError=comparisons["LogitsMaxError"], PMaxError=comparisons["PMaxError"], classCount=V, actualMerges=numeric["merges"],
B=1, D=2, H=1, Dk=2, Dv=2, hiddenWidth=3, byteBound=6, lastNextRow=last["nextRow"], lastNextID=last["nextID"], lastNextProbability=last["nextProbability"])
summary.update({f"tokenizer_{key}": prompt["outputs"][key] for key in _TOKENIZER_SUMMARY})
texts = dict(input=text, decoded=prompt["texts"]["decoded"], cacheRevision=cache["revision"], cacheTrust=_CACHE_TRUST,
modelIdentityPolicy="All26 numeric parameters must agree under numeric ===, including readout and inactive embeddings; signed zeros are equivalent. This is a conservative reuse policy, not the minimal mathematical K/V dependency.",
positionPolicy="Each cache entry stores absolute position j; each append has local query0 at absolute agreed prefix length N. Q/K rotate once; V never rotates.", modelVocabulary=_MODEL_VOCABULARY)
texts.update({f"tokenizer_{key}": value for key, value in prompt["texts"].items()})
return chapter_record(summary, trace, tensors, texts)
def cached_vs_full(state):
"""Complete IV49: one shared prefill, genuine new row/full path, EOS absence."""
checked = _raw_state(state, True)
text, numeric, next_id = checked["text"], checked["numeric"], checked["nextID"]
prompt, observed = cache_prompt(text, numeric["merges"], 2)
ids, trace, N, V = observed.tolist(), _tiny.tiny_trace(), len(observed), 3 + numeric["merges"]
stopped, result_ids = int(next_id == 512), [*ids, next_id]
trace.add("setup", "Validate all raw fields before text semantics; tokenize exactly once", "N=actual prompt tokens1..2; nextID is external observed input; active V=3+merges",
"All numeric parameters and nextID validate before Unicode/domain interpretation, even when nextID is EOS. Both real comparison paths share one actual full-prefill call.",
dict(**numeric, nextID=next_id), dict(utf16Units=_token.utf16_length(text), byteBound=6, tokenBound=2, promptTokens=N, classCount=V))
tensors = _prompt_evidence(prompt, trace)
prefill = prefill_cache(numeric, ids, trace, "prefill")
tensors.extend(prefill["tensors"])
before, comparisons, predictions = prefill["forward"]["rows"][-1], {}, {}
decode_executed = 1 - stopped
cached_rows, full_rows = decode_executed, 0 if stopped else N + 1
cached_cells, full_cells = (0, 0) if stopped else (N + 1, (N + 1) * (N + 1))
cache_entries = len(prefill["cache"]["ids"])
trace.add("append_decision", "Append the external ID logically and apply EOS stopping", "ResultIDs=[PromptIDs,nextID]; nextID=512 => no append neural work",
"The supplied nextID is not replaced by a model prediction. EOS is a logical tail marker decoded without an EOS gather, new cache row, second forward, copy comparison or phantom delta.",
dict(promptTokens=N, nextID=next_id, EOS=512),
dict(logicalResultTokens=len(result_ids), stoppedEOS=stopped, decodeExecuted=decode_executed, absoluteAppendPosition=N,
cachedNewQueryRows=cached_rows, fullNewQueryRows=full_rows, cachedScoreCells=cached_cells, fullScoreCells=full_cells))
if not stopped:
cached = append_cached(numeric, ids, prefill["cache"], next_id, trace, "cached")
tensors.extend(cached["tensors"])
uncached = scoped_forward(numeric, result_ids, trace, "uncached")
tensors.extend(uncached["tensors"])
full, cache_entries = uncached["forward"], len(cached["cache"]["ids"])
for name, left, right, shape, axes in (
("K", cached["cache"]["keys"], _tensor_values(full, "RotatedKHeads"), [N + 1, 2], ["Position", "Dk"]),
("V", cached["cache"]["values"], _tensor_values(full, "ProjectionVHeads"), [N + 1, 2], ["Position", "Dv"]),
("Attention", _tensor_values(cached, "cached_AttentionOHeads"), _tensor_values(full, "AttentionOHeads")[N * 2:], [1, 2], ["Position", "Dv"]),
("Y", _tensor_values(cached, "cached_Y"), _tensor_values(full, "Y")[N * 2:], [1, 2], ["Position", "D"]),
("Logits", cached["distribution"]["logits"], _tensor_values(full, "Logits")[N * V:], [1, V], ["Position", "Class"]),
("P", cached["distribution"]["probabilities"], _tensor_values(full, "P")[N * V:], [1, V], ["Position", "Class"]),
):
comparisons[f"{name}MaxError"] = compare_values(name, left, right, shape, axes, trace, tensors)
last, distribution = full["rows"][N], cached["distribution"]
retained_exact = int(cached["before"]["keys"] == cached["cache"]["keys"][:N * 2] and cached["before"]["values"] == cached["cache"]["values"][:N * 2])
predictions.update(cachedNextRow=distribution["nextRow"], cachedNextID=distribution["nextID"], cachedNextProbability=distribution["nextProbability"],
fullNextRow=last["nextRow"], fullNextID=last["nextID"], fullNextProbability=last["nextProbability"],
predictionsEqual=int(distribution["nextID"] == last["nextID"]), retainedExact=retained_exact)
trace.add("prediction_comparison", "Compare actual computed-logit decisions and retained copies", "predictionsEqual=(cachedNextID===fullNextID); exact ties use lowest compact index in each real path",
"Agreement of IDs alone does not establish numerical equivalence. Six complete operand/error families are retained separately; same-implementation copied K/V equality is a narrower fact.",
dict(cachedNextRow=distribution["nextRow"], cachedNextID=distribution["nextID"], fullNextRow=last["nextRow"], fullNextID=last["nextID"]),
dict(predictionsEqual=predictions["predictionsEqual"], retainedExact=retained_exact))
reverse = _token.TokenTrace()
decoded = _bpe.decode_bpe_ids(np.array(result_ids, dtype=np.int32), _inference._tokenizer_rules(prompt), stopped, "result", reverse)
for step in reverse.steps:
trace.add(step["id"], step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
tensors.extend([
_integer("PromptIDs", "PromptPosition", ids, "Actual EOS-off prompt BPE IDs."),
_integer("ResultIDs", "LogicalPosition", result_ids, "Retained prompt IDs plus exactly one supplied ID; terminal EOS is logical only."),
_integer("ResultBytes", "Bytes", decoded["bytes"], "Actual strict reverse-decoder expansions with the same learned rules; EOS emits no bytes."),
])
harness_rows = N + cached_rows + full_rows
trace.add("finish", "Count actual harness work and distinguish overlapping cold logical paths", "harness=N+cachedNewQueryRows+fullNewQueryRows; coldCached=N+cachedNewQueryRows; coldFull=N+fullNewQueryRows",
"The prefill is shared once. Do not add the two cold logical path totals as actual work. Counts concern this one-layer toy, with no latency, training-quality or universal speedup claim.",
dict(promptTokens=N, cachedNewQueryRows=cached_rows, fullNewQueryRows=full_rows, prefillScoreCells=N * N, cachedScoreCells=cached_cells, fullScoreCells=full_cells),
dict(actualHarnessRows=harness_rows, cacheEntries=cache_entries, resultByteCount=len(decoded["bytes"]), coldCachedRows=N + cached_rows, coldFullRows=N + full_rows))
summary = dict(promptTokens=N, cacheEntries=cache_entries, cachedNewQueryRows=cached_rows, comparisonAvailable=decode_executed,
stoppedEOS=stopped, decodeExecuted=decode_executed, nextID=next_id, logicalResultTokens=len(result_ids), absoluteAppendPosition=N,
prefillQueryRows=N, fullNewQueryRows=full_rows, actualHarnessRows=harness_rows, coldCachedRows=N + cached_rows, coldFullRows=N + full_rows,
prefillScoreCells=N * N, cachedScoreCells=cached_cells, fullScoreCells=full_cells, actualHarnessScoreCells=N * N + cached_cells + full_cells,
classCount=V, actualMerges=numeric["merges"], B=1, D=2, H=1, Dk=2, Dv=2, hiddenWidth=3, byteBound=6,
prefillNextRow=before["nextRow"], prefillNextID=before["nextID"], prefillNextProbability=before["nextProbability"],
**predictions, **comparisons, resultByteCount=len(decoded["bytes"]))
summary.update({f"tokenizer_{key}": prompt["outputs"][key] for key in _TOKENIZER_SUMMARY})
texts = dict(input=text, decoded=decoded["decoded"],
nextIDSource="External observed input; not asserted to be a model-generated selection. A generator can later feed its selected public ID into the same append primitive.",
stopPolicy="EOS512 is appended logically then strict reverse-decoded; no new neural row, full append call, cache entry or comparison is computed.",
cacheRevision=prefill["cache"]["revision"], cacheTrust=_CACHE_TRUST,
modelIdentityPolicy="All26 numeric parameters must agree under numeric ===, including readout and inactive embeddings; signed zeros are equivalent. This conservative policy exceeds the minimal K/V dependency.",
comparisonPolicy="One shared real prefill, one genuine cached new query and one separate full-prefix append call. Inspection selects saved paths only. Compare all six error families as well as actual computed-logit decisions.",
modelVocabulary=_MODEL_VOCABULARY)
texts.update({f"tokenizer_{key}": value for key, value in prompt["texts"].items()})
return chapter_record(summary, trace, tensors, texts)
def _json_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError(f"Duplicate JSON key: {key}")
result[key] = value
return result
def _json_constant(value):
raise ValueError(f"Invalid JSON constant: {value}")
_JSON_INT = int
def _json_integer(token):
return -0.0 if token == "-0" else _JSON_INT(token)
def run(derive, defaults, self_check):
"""Default/full replacement JSON/'-' queries; --self-check is explicit only."""
parser = argparse.ArgumentParser(description=derive.__doc__)
parser.add_argument("state", nargs="?")
parser.add_argument("--self-check", action="store_true")
args = parser.parse_args()
if args.self_check:
if args.state is not None:
parser.error("--self-check cannot be combined with a state query")
self_check() # Deliberately outside query fault catch: assertions must fail.
return
try:
if args.state is None:
state = dict(defaults)
else:
raw = sys.stdin.read() if args.state == "-" else args.state
state = json.loads(raw, object_pairs_hook=_json_object,
parse_constant=_json_constant, parse_int=_json_integer)
result = derive(state)
except (ValueError, OSError) as error:
result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
print(json.dumps(result, allow_nan=False, ensure_ascii=False, separators=(",", ":")))
def _assert_complete_record(record, frame_count, tensor_count):
"""Deferred assertion utility, reached only from explicit check leaves."""
assert list(record) == ["status", "outputs", "steps", "tensors", "texts"] and record["status"] == "defined"
assert len(record["steps"]) == frame_count < 480 and len(record["tensors"]) == tensor_count
assert len({step["id"] for step in record["steps"]}) == frame_count
assert len({item["id"] for item in record["tensors"]}) == tensor_count
flattened = {}
for step in record["steps"]:
assert list(step) == ["id", "label", "equation", "explanation", "inputs", "outputs"]
assert all(type(step[key]) is str and step[key] for key in ("id", "label", "equation", "explanation"))
assert all(type(value) in (int, float) and math.isfinite(value) for value in (*step["inputs"].values(), *step["outputs"].values()))
for key, value in step["outputs"].items():
alias = f"{step['id']}_{key}"
assert alias not in flattened
flattened[alias] = value
assert list(record["outputs"])[-len(flattened):] == list(flattened)
assert {key: record["outputs"][key] for key in flattened} == flattened
assert all(type(value) in (int, float) and math.isfinite(value) for value in record["outputs"].values())
for item in record["tensors"]:
assert list(item) == ["id", "shape", "axes", "dtype", "values", "provenance", "precision"]
assert len(item["shape"]) == len(item["axes"]) == len(set(item["axes"]))
assert all(type(size) is int and 1 <= size <= 64 for size in item["shape"])
assert math.prod(item["shape"]) == len(item["values"]) <= 4096
expected_type = {"float64": float, "int32": int, "bool": bool}[item["dtype"]]
assert all(type(value) is expected_type and math.isfinite(value) for value in item["values"])
assert item["precision"] == (0 if item["dtype"] == "int32" else 8)
assert type(item["provenance"]) is str and item["provenance"]
assert all(type(value) is str or (type(value) is list and all(type(entry) is str for entry in value)) for value in record["texts"].values())
assert detached(record) == record
def _assert_comparisons(record, row_shape, class_shape):
"""Actual errors/copies within Python; not independent numerical authority."""
tensors = {item["id"]: item for item in record["tensors"]}
steps = {step["id"]: step for step in record["steps"]}
for name in ("K", "V", "Attention", "Y", "Logits", "P"):
stem, maximum = f"Compare{name}", 0.0
cached, full = tensors[f"{stem}Cached"]["values"], tensors[f"{stem}Full"]["values"]
shape = [len(cached) // 2, 2] if name in ("K", "V") else class_shape if name in ("Logits", "P") else row_shape
axes = ["Position", {"K": "Dk", "V": "Dv", "Attention": "Dv", "Y": "D", "Logits": "Class", "P": "Class"}[name]]
inputs, outputs = ["count", "initialMaximum"], []
for i, (left, right) in enumerate(zip(cached, full)):
difference, error = left - right, abs(left - right)
maximum = max(maximum, error)
assert tensors[f"{stem}Delta"]["values"][i] == difference
assert tensors[f"{stem}Abs"]["values"][i] == error
assert tensors[f"{stem}RunningMax"]["values"][i] == maximum
inputs.extend((f"cached{i}", f"full{i}"))
outputs.extend((f"delta{i}", f"absolute{i}", f"runningMax{i}"))
outputs.append("maximum")
assert record["outputs"][f"{name}MaxError"] == steps[f"compare_{name}"]["outputs"]["maximum"] == maximum
assert list(steps[f"compare_{name}"]["inputs"]) == inputs
assert list(steps[f"compare_{name}"]["outputs"]) == outputs
for suffix, provenance in (("Cached", "Actual cached operands."), ("Full", "Actual independently recomputed full-prefix operands."), ("Delta", "Actual cached-full subtraction."), ("Abs", "Actual abs(Delta)."), ("RunningMax", "Actual running maximum from0 in flat coordinate order.")):
assert tensors[f"{stem}{suffix}"]["shape"] == shape and tensors[f"{stem}{suffix}"]["axes"] == axes
assert tensors[f"{stem}{suffix}"]["provenance"] == provenance
def source_self_check():
"""DEFERRED explicit helper leaf; invokes NO dependency self-check."""
assert __debug__, "Deferred checks require assertions enabled."
parameters = dict(NUMERIC_DEFAULTS)
assert len(parameters) == 26 and len(DEFAULT_IV48) == 27 and len(DEFAULT_IV49) == 28
assert Path(_inference.__file__).resolve() == _ROOT / "p11" / "inference_reference.py"
assert Path(_choice.__file__).resolve() == _ROOT / "p11" / "choice_reference.py"
cache, rows = empty_cache(parameters), []
assert list(cache) == list(CACHE_FIELDS) and cache["ids"] == cache["keys"] == cache["values"] == []
for identifier in (97, 98, 97):
before = detached(cache)
trace = _tiny.tiny_trace()
saved = append_cached(parameters, cache["ids"], cache, identifier, trace)
assert cache == before and saved["before"] == before
assert saved["cache"]["keys"][:-2] == before["keys"]
assert saved["cache"]["values"][:-2] == before["values"]
assert len(trace.steps) == len(saved["cache"]["ids"]) + 3 * (3 + parameters["merges"]) + 45
assert len(saved["tensors"]) == (63 if not before["ids"] else 67)
assert all(step["id"].startswith("cache_") for step in trace.steps)
assert saved["before"]["parameters"] is not saved["cache"]["parameters"]
for record in saved["tensors"]:
assert list(record) == ["id", "shape", "axes", "dtype", "values", "provenance", "precision"]
assert len(record["shape"]) == len(record["axes"]) == len(set(record["axes"]))
assert all(type(size) is int and 1 <= size <= 64 for size in record["shape"])
assert math.prod(record["shape"]) == len(record["values"]) <= 4096
assert record["precision"] == (0 if record["dtype"] == "int32" else 8)
expected_type = {"float64": float, "int32": int, "bool": bool}[record["dtype"]]
assert all(type(value) is expected_type for value in record["values"])
assert all(list(step) == ["id", "label", "equation", "explanation", "inputs", "outputs"] for step in trace.steps)
rows.append(saved)
cache = saved["cache"]
full = _tiny.forward_tiny(parameters, [97, 98, 97], _tiny.tiny_trace())
assert cache["keys"] == _tensor_values(full, "RotatedKHeads")
assert cache["values"] == _tensor_values(full, "ProjectionVHeads")
for position, saved in enumerate(rows):
assert saved["distribution"]["logits"] == full["rows"][position]["logits"]
assert saved["distribution"]["probabilities"] == full["rows"][position]["probabilities"]
assert saved["distribution"]["nextID"] == (97, 98, 97)[position]
prefill = prefill_cache(parameters, [97, 98], _tiny.tiny_trace())
trace = _tiny.tiny_trace()
numeric_eos = append_cached(parameters, [97, 98], prefill["cache"], 512, trace)
assert numeric_eos["cache"]["ids"] == [97, 98, 512]
assert numeric_eos["cache"]["keys"][-2:] == [0, 0]
assert numeric_eos["cache"]["values"][-2:] == [0, 0]
def rejects(call, code, reason=""):
try:
call()
except _DEPENDENCY_FAULTS as error:
assert error.code == code and reason in str(error), (error.code, str(error))
else:
raise AssertionError("Invalid helper boundary accepted")
def attempt(model=parameters, expected=None, supplied=None, identifier=97, prefix="cache"):
saved_trace = _tiny.tiny_trace()
try:
return append_cached(model, [97, 98] if expected is None else expected,
prefill["cache"] if supplied is None else supplied, identifier, saved_trace, prefix)
except _DEPENDENCY_FAULTS:
assert not saved_trace.steps
raise
class HostileList(list):
def __getitem__(self, index):
raise AssertionError("Custom list indexing must not run")
class HostileDict(dict):
def __getitem__(self, key):
raise AssertionError("Custom dict indexing must not run")
rejects(lambda: attempt(prefix=None, model={}), "INVALID_INPUT", "prefix")
rejects(lambda: attempt(supplied=HostileDict(prefill["cache"])), "INVALID_INPUT")
rejects(lambda: attempt(supplied={**prefill["cache"], "keys": HostileList()}), "INVALID_INPUT")
rejects(lambda: attempt(supplied={**prefill["cache"], "ids": [float("nan"), 98], "values": []}), "SHAPE_MISMATCH")
rejects(lambda: attempt(expected=HostileList([97, 98])), "INVALID_INPUT")
rejects(lambda: attempt(supplied={**prefill["cache"], "keys": [0] * 7}), "UNSUPPORTED_SIZE")
rejects(lambda: attempt(supplied={**prefill["cache"], "ids": [float("nan"), 98], "values": [0] * 7}), "UNSUPPORTED_SIZE")
rejects(lambda: attempt(expected=[97] * 4), "UNSUPPORTED_SIZE")
rejects(lambda: attempt(expected=[97] * 7), "UNSUPPORTED_SIZE")
rejects(lambda: attempt(supplied={**prefill["cache"], "positions": [0, 0]}), "INVALID_INPUT", "CACHE_POSITION_MISMATCH")
rejects(lambda: attempt(supplied={**prefill["cache"], "ids": [True, 98]}), "INVALID_INPUT")
rejects(lambda: attempt(identifier=True), "NONFINITE")
rejects(lambda: attempt(identifier=float("nan")), "NONFINITE")
rejects(lambda: attempt(identifier=256), "INVALID_INPUT")
rejects(lambda: attempt(model={**parameters, "u04": 1}), "UNAVAILABLE", "CACHE_MODEL_MISMATCH")
rejects(lambda: attempt(model={**parameters, "e40": 0}), "UNAVAILABLE", "CACHE_MODEL_MISMATCH")
rejects(lambda: attempt(expected=[98, 97]), "UNAVAILABLE", "CACHE_PREFIX_MISMATCH")
rejects(lambda: attempt(supplied=cache, expected=[97, 98, 97]), "UNSUPPORTED_SIZE")
rejects(lambda: attempt(supplied=cache, expected=[98, 97, 97]), "UNAVAILABLE", "CACHE_PREFIX_MISMATCH")
rejects(lambda: prefill_cache(parameters, HostileList([97]), _tiny.tiny_trace()), "INVALID_INPUT")
rejects(lambda: prefill_cache(parameters, [], _tiny.tiny_trace()), "UNAVAILABLE")
# Simultaneous faults pin the signed structural -> entries -> request order.
rejects(lambda: attempt(model={}, supplied=HostileDict()), "INVALID_INPUT", "every own field")
rejects(lambda: attempt(supplied={**prefill["cache"], "revision": "other", "parameters": {}}), "INVALID_INPUT", "revision")
rejects(lambda: attempt(supplied={**prefill["cache"], "parameters": {}, "keys": HostileList()}), "INVALID_INPUT", "every own field")
rejects(lambda: attempt(supplied={**prefill["cache"], "ids": [97] * 4, "values": HostileList()}), "INVALID_INPUT", "ordinary Array prototype")
rejects(lambda: attempt(supplied={**prefill["cache"], "ids": [97] * 4}), "UNSUPPORTED_SIZE")
rejects(lambda: attempt(supplied={**prefill["cache"], "ids": [True, 98], "positions": [0, 0]}), "INVALID_INPUT", "cache.ids")
rejects(lambda: attempt(supplied={**prefill["cache"], "positions": [0, 0], "keys": [float("nan")] * 4}), "INVALID_INPUT", "CACHE_POSITION_MISMATCH")
rejects(lambda: attempt(supplied={**prefill["cache"], "keys": [float("nan")] * 4}, expected=HostileList()), "NONFINITE", "cache.keys")
rejects(lambda: attempt(supplied={**prefill["cache"], "values": [True] * 4}, identifier=256), "NONFINITE", "cache.values")
rejects(lambda: attempt(expected=[True], identifier=float("nan")), "INVALID_INPUT", "expectedPrefixIDs")
rejects(lambda: attempt(model={**parameters, "u04": 1}, expected=[98, 97], identifier=True), "NONFINITE", "newID")
rejects(lambda: attempt(model={**parameters, "u04": 1}, expected=[98, 97]), "UNAVAILABLE", "CACHE_MODEL_MISMATCH")
rejects(lambda: attempt(supplied={**cache, "positions": [1, 2, 3]}, expected=[98, 97, 97]), "INVALID_INPUT", "CACHE_POSITION_MISMATCH")
for invalid_ids, code in (((), "INVALID_INPUT"), ([97] * 4, "UNSUPPORTED_SIZE"), ([True], "INVALID_INPUT")):
rejected_trace = _tiny.tiny_trace()
rejects(lambda: prefill_cache(parameters, invalid_ids, rejected_trace), code)
assert not rejected_trace.steps
# Numeric equality deliberately equates signed zero and rounded-away edits.
assert attempt(model={**parameters, "u04": -0.0})["cache"]["parameters"]["u04"] == 0
assert attempt(model={**parameters, "e00": 1 + math.ulp(0.0)})["cache"]["parameters"]["e00"] == 1
for model in ({**parameters, "merges": 2, "e00": -0.75, "e01": 1.25, "u00": -1.5, "b4": 0.5},
{**parameters, **{key: 0 for key in parameters if key != "merges"}}):
coherent = prefill_cache(model, [97, 98], _tiny.tiny_trace())["cache"]
appended = append_cached(model, [97, 98], coherent, 97, _tiny.tiny_trace())
reference_full = _tiny.forward_tiny(model, [97, 98, 97], _tiny.tiny_trace())
assert appended["cache"]["keys"] == _tensor_values(reference_full, "RotatedKHeads")
assert appended["cache"]["values"] == _tensor_values(reference_full, "ProjectionVHeads")
assert appended["distribution"]["logits"] == reference_full["rows"][-1]["logits"]
assert appended["distribution"]["probabilities"] == reference_full["rows"][-1]["probabilities"]
if not any(model[key] for key in model if key != "merges"):
assert appended["distribution"]["nextRow"] == 0 and appended["distribution"]["nextID"] == 97
try:
json.loads('{"text":"a","text":"b"}', object_pairs_hook=_json_object)
except ValueError as error:
assert "Duplicate JSON key: text" in str(error)
else:
raise AssertionError("Duplicate CLI JSON keys were accepted")
assert list(prefill) == ["cache", "forward", "tensors"]
assert len(prefill["tensors"]) == 61
assert list(saved) == ["before", "cache", "position", "newID", "distribution", "tensors"]
assert list(saved["distribution"]) == ["classIDs", "logits", "max", "shifted", "terms", "denominator", "logS", "lse", "probabilities", "nextRow", "nextID", "nextProbability", "tensors"]
assert len(saved["distribution"]["tensors"]) == 11
for bad in (10 ** 1000, float("inf"), True, None):
rejects(lambda: attempt(supplied={**prefill["cache"], "ids": [bad, 98]}), "INVALID_INPUT")
rejects(lambda: attempt(supplied={**prefill["cache"], "positions": [bad, 1]}), "INVALID_INPUT", "CACHE_POSITION_MISMATCH")
# Exercise CLI routing with local streams; no subprocess or dependency checks.
class Stream:
def __init__(self, value=""):
self.value = value
def read(self):
return self.value
def write(self, value):
self.value += value
return len(value)
def flush(self):
pass
original = sys.argv, sys.stdin, sys.stdout
calls = []
def query(value):
calls.append(value)
return dict(status="defined", value=value)
def forbidden_check():
raise AssertionError("Ordinary CLI query invoked a self-check")
try:
raw = json.dumps(dict(DEFAULT_IV48), allow_nan=False)
for argument in ([], [raw], ["-"]):
sys.argv, sys.stdin, sys.stdout = ["iv48.py", *argument], Stream(raw), Stream()
run(query, DEFAULT_IV48, forbidden_check)
assert json.loads(sys.stdout.value)["value"] == dict(DEFAULT_IV48)
assert len(calls) == 3
for raw in ('{"text":"a","text":"b"}', '[]', '{"text":"a"}'):
sys.argv, sys.stdin, sys.stdout = ["iv48.py", "-"], Stream(raw), Stream()
run(guarded(cache_growth), DEFAULT_IV48, forbidden_check)
fault = json.loads(sys.stdout.value)
assert list(fault) == ["status", "code", "reason"] and fault["code"] == "INVALID_INPUT"
for constant in ("NaN", "Infinity", "-Infinity"):
sys.argv, sys.stdin, sys.stdout = ["iv48.py", "-"], Stream(constant), Stream()
run(query, DEFAULT_IV48, forbidden_check)
fault = json.loads(sys.stdout.value)
assert fault == dict(status="unavailable", code="INVALID_INPUT", reason=f"Invalid JSON constant: {constant}")
assert len(calls) == 3
sys.argv, sys.stdout = ["iv48.py", "--self-check"], Stream()
try:
run(query, DEFAULT_IV48, forbidden_check)
except AssertionError as error:
assert "invoked a self-check" in str(error)
else:
raise AssertionError("--self-check assertion was swallowed")
assert not sys.stdout.value
finally:
sys.argv, sys.stdin, sys.stdout = original
# A finite forged cache is structurally accepted under the EXPLICIT precondition.
forged = detached(prefill["cache"])
forged["keys"][0] += 0.25
accepted = attempt(supplied=forged)
assert accepted["cache"]["keys"][0] == forged["keys"][0]
assert forged["keys"][0] != prefill["cache"]["keys"][0]
saved = attempt()
saved["cache"]["keys"].clear()
saved["tensors"][0]["values"].clear()
assert attempt()["cache"]["keys"] and attempt()["tensors"][0]["values"]
assert parameters == dict(NUMERIC_DEFAULTS)
if __name__ == "__main__":
run(guarded(cache_growth), DEFAULT_IV48, source_self_check)
Dependency loader and saved rules — code/python/p11/inference_reference.py. The cache module loads this file to obtain its Tiny decoder, IV39 tokenizer and BPE/codec bindings. The new wrappers use their own _raw_state and cache_prompt; they do not call this file’s old inference_state, prompt_bpe or uncached inference composition. Its _tokenizer_rules extracts actual learned rules from saved tokenizer tensors for IV-49’s reverse decoder. IV-48 instead retains IV39’s existing prompt reconstruction. The complete file stays visible because loading its dependencies is part of the actual source closure.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""IV44 canonical NumPy mechanics, source-authored under the resource hold.
Reuse the actual IV39 tokenizer and IV43 observed-ID forward, without any
objective/gradient call. One externally supplied ID is appended without
retokenization. EOS is a logical stop; otherwise recompute the entire prefix.
The full chapter record follows the owner-adopted ordered A inventory.
All execution and self-checks remain DEFERRED.
"""
import importlib.util
import json
from pathlib import Path
from types import MappingProxyType
from functools import wraps
import numpy as np
_ROOT = Path(__file__).resolve().parent.parent
def _load(name, path):
"""Load exactly the disclosed file, independently of cwd and sys.path."""
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise ImportError(f"Cannot load canonical dependency: {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
_tiny = _load("_iv44_tiny_reference", _ROOT / "p10" / "tiny_reference.py")
_iv39 = _load("_iv44_iv39", _ROOT / "p09" / "iv39.py")
_bpe = _iv39._bpe
_token = _bpe._token
NumericalFault = _tiny.NumericalFault
# IV39 and tiny load distinct instances of the same readonly codec source.
_DEPENDENCY_FAULTS = (*_tiny._DEPENDENCY_FAULTS, _bpe.NumericalFault)
ALL_IDS = _tiny.ALL_IDS
NUMERIC_DEFAULTS = _tiny.NUMERIC_DEFAULTS
DEFAULT_IV44 = MappingProxyType(dict(text="ab", **NUMERIC_DEFAULTS, nextID=97))
def guarded(derive):
@wraps(derive)
def call(state):
try:
return derive(state)
except _DEPENDENCY_FAULTS as error:
return dict(status="unavailable", code=error.code, reason=str(error))
except (OverflowError, FloatingPointError) as error:
return dict(status="unavailable", code="NONFINITE", reason=str(error))
return call
def inference_state(state):
"""Exact own fields; string type, all26 numeric fields, then nextID."""
_tiny._object(state, DEFAULT_IV44, "state")
if type(state["text"]) is not str:
raise NumericalFault("INVALID_INPUT", "text must be an actual string, without coercion.")
numeric = _tiny.numeric_parameters({key: state[key] for key in NUMERIC_DEFAULTS})
next_id = _tiny.finite(state["nextID"], "nextID")
if not next_id.is_integer() or next_id not in ALL_IDS[:3 + numeric["merges"]]:
raise NumericalFault("INVALID_INPUT", "nextID must be an active public model ID.")
return dict(text=state["text"], numeric=numeric, nextID=int(next_id))
def prompt_bpe(text, merges):
"""Validate the outer boundary, then tokenize ONCE using actual IV39.
No native codec or guessed segmentation supplies the answer. The precheck
uses the existing manual encoder solely for strict Unicode/byte validation;
IV39 alone supplies the saved tokenization and every displayed BPE record.
"""
if type(text) is not str:
raise NumericalFault("INVALID_INPUT", "text must be an actual string, without coercion.")
merges = _tiny.finite(merges, "merges")
if not merges.is_integer() or not 0 <= merges <= 2:
raise NumericalFault("INVALID_INPUT", "merges must be an integer from 0 to 2.")
merges = int(merges)
if _token.utf16_length(text) > 6:
raise NumericalFault("UNSUPPORTED_SIZE", "text: more than 6 UTF-16 units exceeds the 6-byte input bound.")
encoded = _token.utf8_encode(text)
if len(encoded["bytes"]) > 6:
raise NumericalFault("UNSUPPORTED_SIZE", "text: the actual UTF-8 encoding exceeds 6 bytes.")
if any(character not in "ab" for character in text):
raise NumericalFault("UNAVAILABLE", "This toy model supports only raw a and b letters, without normalization or truncation.")
if not text:
raise NumericalFault("UNAVAILABLE", "Empty text has no observed prompt token.")
result = _iv39.derive_iv39(dict(corpus="abab", text=text, merges=merges, eos=0))
if result["status"] != "defined":
raise NumericalFault(result["code"], result["reason"])
ids = np.array(next(t["values"] for t in result["tensors"] if t["id"] == "TargetIDs"), dtype=np.int32)
if len(ids) > 2:
raise NumericalFault("UNSUPPORTED_SIZE", "The actual BPE prompt exceeds 2 tokens; change text or merges explicitly.")
return result, ids
def _tokenizer_rules(tokenized):
"""Rebuild only actual saved IV39 rules, including their actual byte arrays."""
tensors = {record["id"]: record for record in tokenized["tensors"]}
if "RuleIDs" not in tensors:
return []
ids = tensors["RuleIDs"]["values"]
left, right = tensors["RuleLeft"]["values"], tensors["RuleRight"]["values"]
rules = [dict(id=identifier, left=left[rank], right=right[rank],
bytes=np.array(tensors[f"Rule{identifier}Bytes"]["values"], dtype=np.int32))
for rank, identifier in enumerate(ids)]
_bpe.rule_table(rules)
return rules
def _tensor_values(forward, identifier):
return next(record["values"] for record in forward["tensors"] if record["id"] == identifier)
def _compare_prefix(prefill, decode, trace, tensors):
"""Save complete prior-row operands and computed differences in family order."""
N, V = prefill["T"], prefill["V"]
if decode["T"] != N + 1 or decode["V"] != V or decode["inputIDs"][:N] != prefill["inputIDs"]:
raise NumericalFault("SHAPE_MISMATCH", "Prefix comparison requires the same model classes and an extended observed prefix.")
maxima = {}
for identifier, width in (("Y", 2), ("Logits", V), ("P", V)):
before = np.array(_tensor_values(prefill, identifier), dtype=np.float64).reshape(N, width)
after = np.array(_tensor_values(decode, identifier), dtype=np.float64).reshape(N + 1, width)[:N].copy()
differences = np.empty((N, width), dtype=np.float64)
maximum = 0.0
for t in range(N):
inputs, outputs = dict(t=t), {}
for c in range(width):
previous, current = float(before[t, c]), float(after[t, c])
inputs[f"before{c}"], inputs[f"after{c}"] = previous, current
difference = _tiny.finite(abs(_tiny.finite(current - previous, "prefix subtraction")), "prefix absolute difference")
differences[t, c] = difference
outputs[f"difference{c}"] = difference
maximum = max(maximum, difference)
outputs[f"runningMax{c}"] = maximum
outputs["maxDifference"] = maximum
trace.add(f"compare_{identifier}_{t}", f"Compare saved prior {identifier} row {t}",
"difference_c=abs(after_c-before_c); runningMax=max(previous,difference_c)",
"Both operands come from actual saved calls with identical prior IDs, parameters and absolute positions. Differences are computed, never forced to zero. Signed zeros compare equivalently; future masked raw scores need not match.",
inputs, outputs)
maxima[f"prefix{identifier}MaxDiff"] = maximum
axes = ["PriorPosition", "D" if identifier == "Y" else "Class"]
tensors.extend([
_tiny._float_tensor(f"Prefix{identifier}Before", [N, width], axes, before,
"Actual complete prefill rows copied from the saved forward tensor."),
_tiny._float_tensor(f"Prefix{identifier}After", [N, width], axes, after,
"Actual first N rows copied from the extended-prefix forward tensor."),
_tiny._float_tensor(f"Prefix{identifier}AbsDiff", [N, width], axes, differences,
"Computed abs(after-before) for every prior-row coordinate; no synthetic zero fill."),
])
return maxima
def prefill_and_decode(state):
"""Full ordered IV44 record: actual BPE, uncached forwards and strict inverse.
IDs/positions/bytes use real int32 arrays; comparisons and the reused neural
arithmetic use float64 arrays. Returned JSON data is detached from all state.
EOS contributes logical control only, with no second forward or comparison.
"""
s = inference_state(state)
numeric, next_id = s["numeric"], s["nextID"]
prompt, prompt_ids = prompt_bpe(s["text"], numeric["merges"])
N, V = len(prompt_ids), 3 + numeric["merges"]
stopped = int(next_id == 512)
result_ids = np.concatenate((prompt_ids, np.array([next_id], dtype=np.int32)))
trace = _tiny.tiny_trace()
trace.add("setup", "Validate the complete input before interpreting prompt text", "outer bytes<=6; actual prompt tokens N in {1,2}; nextID is externally supplied",
"All raw fields validate, including inactive and EOS parameters. The prompt is tokenized once with EOS off. No probability of the external choice is asserted.",
{**numeric, "nextID": next_id}, dict(utf16Units=_token.utf16_length(s["text"]), byteBound=6, promptTokenBound=2))
for step in prompt["steps"]:
trace.add(f"tokenizer_{step['id']}", step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
trace.add("class_map", "Keep public token IDs distinct from model storage rows", "V=3+merges; active classIDs=prefix([97,98,512,256,257],V)",
"The same real learned rules supply the prompt and final reverse decoder. Public ID512 does not allocate 513 embeddings.",
dict(actualMerges=prompt["outputs"]["actualMerges"], vocabularyItems=prompt["outputs"]["vocabularyItems"]), dict(classCount=V))
tensors = [{**record, "id": f"Tokenizer{record['id']}", "provenance": f"Prompt BPE with EOS off. {record['provenance']}"}
for record in prompt["tensors"]]
def call(phase, ids):
saved = _tiny.tiny_trace()
forward = _tiny.forward_tiny(numeric, ids, saved)
for step in saved.steps:
trace.add(f"{phase.lower()}_{step['id']}", f"{phase}: {step['label']}", step["equation"],
f"{phase} uncached inference call. Reused generic forward arithmetic; no target, loss, gradient or cache operation is called here. Kernel explanation: {step['explanation']}",
step["inputs"], step["outputs"])
tensors.extend({**record, "id": f"{phase}{record['id']}",
"provenance": f"{phase} full-prefix inference, absolute positions 0..{len(ids) - 1}; inherited kernel provenance: {record['provenance']}"}
for record in forward["tensors"])
return forward
prefill = call("Prefill", prompt_ids)
before = prefill["rows"][N - 1]
trace.add("append", "Append exactly the externally selected public ID", "ResultIDs=PromptIDs followed by nextID; logicalResultTokenCount=N+1",
"Appending a piece preserves the ID stream even if retokenizing its decoded characters would merge across this boundary.",
dict(promptTokens=N, nextID=next_id), dict(logicalResultTokenCount=len(result_ids)))
decode_executed = 1 - stopped
decode_work = 0 if stopped else N + 1
trace.add("stop_decision", "Apply the declared terminal EOS policy", "nextID=512 => stop; otherwise recompute the full extended prefix",
"A stopping EOS enters the logical result only. It triggers no second neural call or EOS embedding gather. A non-EOS call consumes one novel ID but recomputes N+1 rows; no K/V cache is implemented.",
dict(nextID=next_id, EOS=512, promptTokens=N),
dict(stoppedEOS=stopped, decodeExecuted=decode_executed, newTokensConsumed=decode_executed,
decodeWorkTokens=decode_work, newPosition=N, cacheUsed=0, cacheEntries=0))
prediction, comparisons = {}, {}
if not stopped:
decode = call("Decode", result_ids)
last = decode["rows"][N]
prediction = dict(decodeNextRow=last["nextRow"], decodeNextID=last["nextID"], decodeNextProbability=last["nextProbability"])
comparisons = _compare_prefix(prefill, decode, trace, tensors)
tensors.append(_token.tensor("DecodePositions", "Position", np.arange(N + 1, dtype=np.int32),
"Actual absolute positions consumed by the uncached extended-prefix call."))
reverse = _token.TokenTrace()
reconstructed = _bpe.decode_bpe_ids(result_ids, _tokenizer_rules(prompt), stopped, "result", reverse)
result_bytes = reconstructed["bytes"]
if len(result_bytes) > 10:
raise NumericalFault("UNSUPPORTED_SIZE", "Result expansions exceed the declared 10-byte bound.")
for step in reverse.steps:
trace.add(step["id"], step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
tensors.extend([
_token.tensor("PromptIDs", "PromptPosition", prompt_ids, "Actual EOS-off BPE prompt, tokenized once."),
_token.tensor("ResultIDs", "LogicalPosition", result_ids, "Prompt IDs plus exactly the externally supplied ID; a final EOS is logical control only."),
_token.tensor("PrefillPositions", "Position", np.arange(N, dtype=np.int32), "Actual absolute positions processed by prefill."),
_token.tensor("ResultBytes", "Bytes", result_bytes, "Actual strict reverse-decoder expansion bytes; a stopping EOS emits none."),
])
trace.add("finish", "Keep novel input, total work and actual reconstruction distinct", "prefillWorkTokens=N; decodeWorkTokens=stoppedEOS?0:N+1; newTokensConsumed=stoppedEOS?0:1",
"This is a bounded uncached inference walkthrough with hand-set parameters. All probabilities belong to actual model calls; the supplied nextID is not claimed as a model prediction.",
dict(promptTokens=N, nextID=next_id, stoppedEOS=stopped),
dict(promptTokens=N, newTokensConsumed=decode_executed, prefillWorkTokens=N, decodeWorkTokens=decode_work, resultByteCount=len(result_bytes)))
summary = dict(promptTokens=N, newTokensConsumed=decode_executed, prefillWorkTokens=N, decodeWorkTokens=decode_work,
nextID=next_id, logicalResultTokenCount=len(result_ids), newPosition=N, decodeExecuted=decode_executed,
stoppedEOS=stopped, cacheUsed=0, cacheEntries=0, prefillScoreCells=N * N,
decodeScoreCells=0 if stopped else (N + 1) * (N + 1), classCount=V, actualMerges=numeric["merges"],
B=1, D=2, H=1, Dk=2, Dv=2, hiddenWidth=3, byteBound=6,
prefillNextRow=before["nextRow"], prefillNextID=before["nextID"], prefillNextProbability=before["nextProbability"],
**prediction, **comparisons, resultByteCount=len(result_bytes))
tokenizer_names = ("corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges", "corpusTokens",
"eos", "byteBound", "vocabularyItems", "corpusEqual", "equal")
summary.update({f"tokenizer_{key}": prompt["outputs"][key] for key in tokenizer_names})
result = trace.result(summary, tensors)
result["texts"] = dict(input=s["text"], decoded=reconstructed["decoded"],
nextIDSource="Externally selected observed/chosen ID; not asserted to be the model prediction.",
stopPolicy="EOS512 is a terminal logical marker: no second forward call and no EOS embedding gather.",
cachePolicy="No K/V reuse; a non-EOS call recomputes all N+1 rows at absolute positions 0..N.",
modelVocabulary=["0: a / ID97", "1: b / ID98", "2: EOS / ID512", "3: ab / ID256 (merges>=1)", "4: abab / ID257 (merges=2)"],
**{f"tokenizer_{key}": value for key, value in prompt["texts"].items()})
return json.loads(json.dumps(result, allow_nan=False, ensure_ascii=False))
def source_self_check():
"""DEFERRED helper assertions; does NOT call any other file's self-check."""
assert __debug__, "Deferred checks require assertions enabled."
assert Path(_tiny.__file__).resolve() == _ROOT / "p10" / "tiny_reference.py"
assert Path(_iv39.__file__).resolve() == _ROOT / "p09" / "iv39.py"
assert Path(_bpe.__file__).resolve() == _ROOT / "p09" / "bpe_reference.py"
assert Path(_token.__file__).resolve() == _ROOT / "p09" / "token_reference.py"
assert _tiny._ffn.NumericalFault is _tiny._component.NumericalFault
assert _tiny._ffn.tensor is _tiny._component.tensor
assert list(DEFAULT_IV44) == ["text", *NUMERIC_DEFAULTS, "nextID"] and len(DEFAULT_IV44) == 28
state = dict(DEFAULT_IV44)
result = prefill_and_decode(state)
tensors = {record["id"]: record for record in result["tensors"]}
assert tensors["PromptIDs"]["values"] == [97, 98] and tensors["ResultIDs"]["values"] == [97, 98, 97]
assert result["texts"]["decoded"] == "aba" and tensors["ResultBytes"]["values"] == [97, 98, 97]
assert tensors["PrefillPositions"]["values"] == [0, 1] and tensors["DecodePositions"]["values"] == [0, 1, 2]
assert result["outputs"]["prefillNextID"] == 98 and result["outputs"]["decodeNextID"] == 97
for identifier in ("Y", "Logits", "P"):
assert result["outputs"][f"prefix{identifier}MaxDiff"] == 0
assert all(value == 0 for value in tensors[f"Prefix{identifier}AbsDiff"]["values"])
assert tensors[f"Prefix{identifier}Before"]["values"] == tensors[f"Prefix{identifier}After"]["values"]
stopped = prefill_and_decode({**state, "nextID": 512})
assert stopped["texts"]["decoded"] == "ab"
assert stopped["outputs"]["newTokensConsumed"] == stopped["outputs"]["decodeWorkTokens"] == 0
assert not any(record["id"].startswith(("Decode", "Prefix")) for record in stopped["tensors"])
assert not any(step["id"].startswith(("decode_", "compare_")) for step in stopped["steps"])
fixed = prefill_and_decode({**state, "merges": 2, "nextID": 256})
fixed_tensors = {record["id"]: record for record in fixed["tensors"]}
assert fixed_tensors["PromptIDs"]["values"] == [256] and fixed_tensors["ResultIDs"]["values"] == [256, 256]
assert fixed["texts"]["decoded"] == "abab"
# Retokenizing is shown only as a counterexample in this explicit future check.
fresh, ids = prompt_bpe("abab", 2)
assert ids.dtype == np.dtype(np.int32) and ids.tolist() == [257]
assert fresh["texts"]["decoded"] == fixed["texts"]["decoded"]
for patch, code in (({"text": ""}, "UNAVAILABLE"), ({"text": "c"}, "UNAVAILABLE"),
({"text": "a" * 7}, "UNSUPPORTED_SIZE"), ({"text": "\ud800"}, "INVALID_INPUT"),
({"text": "ababab"}, "UNSUPPORTED_SIZE"), ({"text": "🦊🦊"}, "UNSUPPORTED_SIZE"),
({"nextID": 256}, "INVALID_INPUT"), ({"nextID": True}, "NONFINITE"),
({"text": "\ud800", "nextID": float("inf")}, "NONFINITE"),
({"text": [], "merges": float("nan")}, "INVALID_INPUT"),
({"nextID": 512, "e40": 3}, "INVALID_INPUT"),
({"nextID": 512, "b4": float("nan")}, "NONFINITE")):
fault = guarded(prefill_and_decode)({**state, **patch})
assert list(fault) == ["status", "code", "reason"] and fault["code"] == code
for text, merges, code in (("ab", 3, "INVALID_INPUT"), ("ab", 4, "INVALID_INPUT"),
("\ud800", float("nan"), "NONFINITE"),
("a" * 7, float("nan"), "NONFINITE"),
([], float("nan"), "INVALID_INPUT")):
try:
prompt_bpe(text, merges)
except _DEPENDENCY_FAULTS as error:
assert error.code == code
else:
raise AssertionError("Invalid prompt helper boundary was accepted")
class Hostile(dict):
def __getitem__(self, key):
raise AssertionError("Custom indexing must not be read")
assert guarded(prefill_and_decode)(Hostile(state))["code"] == "INVALID_INPUT"
result["tensors"][0]["values"][0] = -1
result["steps"][0]["outputs"].clear()
result["texts"]["modelVocabulary"].clear()
repeated = prefill_and_decode(state)
assert repeated["tensors"][0]["values"][0] != -1 and repeated["steps"][0]["outputs"]
assert len(repeated["texts"]["modelVocabulary"]) == 5 and state == dict(DEFAULT_IV44)
def run(derive, defaults):
"""Default / full replacement JSON argument / '-' stdin; no self-check call."""
_tiny.run(derive, defaults)
Class normalization and choice — code/python/p11/choice_reference.py. direct_distribution takes all active computed logits, subtracts their maximum, exponentiates and accumulates the denominator in compact class order. Its strict greater-than winner update keeps the lowest compact class on exact ties. Attention weights over positions and these probabilities over next-token classes are different arrays.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""Direct logits -> stable probabilities -> strict-logit greedy choice.
NumPy float64/int32 arrays are the actual storage. Scalar binary64 arithmetic
preserves exp, left-to-right denominator and division order. No neural/tokenizer
import is needed for the literal five-ID model contract. Full ordered chapter
records follow the owner-adopted A inventory. All execution remains DEFERRED.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np
ALL_IDS = (97, 98, 512, 256, 257)
DEFAULT_IV45 = MappingProxyType(dict(V=3, z0=1, z1=0, z2=0, z3=0, z4=0))
class NumericalFault(ValueError):
def __init__(self, code, reason):
super().__init__(reason)
self.code = code
def finite(value, label):
"""No coercion, bools, custom scalar conversions, infinities or NaNs."""
if type(value) not in (int, float):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
try:
value = float(value)
except (OverflowError, ValueError) as error:
raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
if not math.isfinite(value):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
return value
def choice_state(state):
"""Validate all six own fields in raw order, including inactive logits."""
if type(state) is not dict:
raise NumericalFault("INVALID_INPUT", "Provide a plain object with exactly V,z0,z1,z2,z3,z4.")
if any(type(key) is not str for key in state) or set(state) != set(DEFAULT_IV45):
raise NumericalFault("INVALID_INPUT", "Provide every own field and no extra or symbol fields, including inactive logits.")
checked = {}
for key in DEFAULT_IV45:
value = finite(state[key], key)
if key == "V":
if not value.is_integer() or not 3 <= value <= 5:
raise NumericalFault("INVALID_INPUT", "V must be an integer from 3 to 5.")
checked[key] = int(value)
else:
if not -40 <= value <= 40:
raise NumericalFault("INVALID_INPUT", f"{key} must be between -40 and 40.")
checked[key] = value
return checked
def guarded(derive):
@wraps(derive)
def call(state):
try:
return derive(state)
except NumericalFault as error:
return dict(status="unavailable", code=error.code, reason=str(error))
except (OverflowError, FloatingPointError) as error:
return dict(status="unavailable", code="NONFINITE", reason=str(error))
return call
class ChoiceTrace:
"""Finite detached scalar records; no implicit invocation of self-checks."""
def __init__(self):
self.steps = []
def add(self, identifier, label, equation, explanation, inputs, outputs):
if len(self.steps) >= 512:
raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 operations are supported.")
self.steps.append(dict(id=identifier, label=label, equation=equation, explanation=explanation,
inputs={key: finite(value, key) for key, value in inputs.items()},
outputs={key: finite(value, key) for key, value in outputs.items()}))
def _dense(values, label):
"""Inspect both containers before either helper operand is read."""
if type(values) is np.ndarray:
if values.ndim != 1 or values.dtype.kind not in "iuf":
raise NumericalFault("INVALID_INPUT", f"{label} must be a dense one-dimensional numeric array.")
elif type(values) not in (list, tuple):
raise NumericalFault("INVALID_INPUT", f"{label} must be an actual dense array.")
if not 3 <= len(values) <= 5:
raise NumericalFault("UNSUPPORTED_SIZE", f"{label} must have 3 to 5 entries.")
def _tensor(identifier, axis, values, provenance):
"""Serialize actual internal float64/int32 vectors into detached metadata."""
if type(values) is not np.ndarray or values.ndim != 1 or values.dtype not in (np.dtype(np.float64), np.dtype(np.int32)):
raise NumericalFault("SHAPE_MISMATCH", f"{identifier} requires actual float64/int32 vector storage.")
if not 1 <= len(values) <= 5:
raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier} requires 1 to 5 entries.")
flat = values.tolist()
for value in flat:
finite(value, identifier)
integer = values.dtype == np.dtype(np.int32)
return dict(id=identifier, shape=[len(flat)], axes=[axis], dtype="int32" if integer else "float64",
values=flat, provenance=provenance, precision=0 if integer else 8)
def direct_distribution(logits, class_ids, trace, prefix="choice"):
"""Dynamic V3..5 distribution; no slider bound on finite derived logits.
Prefix precedes both container guards; both descriptors precede entries.
Highest computed input logit wins; ties keep the lowest compact index.
"""
if type(prefix) is not str or not prefix:
raise NumericalFault("INVALID_INPUT", "prefix must be an actual nonempty string.")
_dense(logits, "logits")
_dense(class_ids, "classIDs")
if len(logits) != len(class_ids):
raise NumericalFault("SHAPE_MISMATCH", "logits and classIDs must have equal lengths.")
raw_z = logits.tolist() if type(logits) is np.ndarray else logits
raw_ids = class_ids.tolist() if type(class_ids) is np.ndarray else class_ids
V = len(raw_z)
z = np.array([finite(value, f"logits[{c}]") for c, value in enumerate(raw_z)], dtype=np.float64)
numeric_ids = [finite(value, f"classIDs[{c}]") for c, value in enumerate(raw_ids)]
checked_ids = []
for c, identifier in enumerate(numeric_ids):
if not identifier.is_integer() or identifier != ALL_IDS[c]:
raise NumericalFault("INVALID_INPUT", "classIDs must be the active prefix of [97,98,512,256,257].")
checked_ids.append(int(identifier))
ids = np.array(checked_ids, dtype=np.int32)
maximum_inputs = {f"z{c}": float(z[c]) for c in range(V)}
maximum = max(maximum_inputs.values())
trace.add(f"{prefix}_max", "Find the maximum active computed logit", "max=max(z0,...,z[V-1])",
"All active computed input logits participate. The maximum stabilizes exponentiation; it is not a rounded probability.",
maximum_inputs, dict(max=maximum))
shifted, terms, probabilities = (np.empty(V, dtype=np.float64) for _ in range(3))
denominator, running = 0.0, {}
for c in range(V):
logit = float(z[c])
shift = finite(logit - maximum, "shifted logit")
term = finite(math.exp(shift), "shifted exponential")
shifted[c], terms[c] = shift, term
trace.add(f"{prefix}_exp_{c}", f"Exponentiate active class {c}", "shifted=logit-max; term=exp(shifted)",
"No clipping, epsilon or display rounding feeds the distribution. Underflow is retained if a derived input reaches it.",
dict(c=c, logit=logit, max=maximum), dict(shifted=shift, term=term))
denominator = finite(denominator + term, "denominator")
running[f"running{c}"] = denominator
if denominator <= 0:
raise NumericalFault("UNAVAILABLE", "The shifted exponential denominator must be positive.")
log_s = finite(math.log(denominator), "logS")
lse = finite(maximum + log_s, "logsumexp")
trace.add(f"{prefix}_normalize", "Accumulate terms and compute logsumexp",
"running starts at 0; running_c=previous+term_c; logS=ln(S); LSE=max+logS",
"The denominator adds terms in ascending compact class order. Every actual running sum is saved.",
{**{f"term{c}": float(terms[c]) for c in range(V)}, "max": maximum},
{**running, "denominator": denominator, "logS": log_s, "lse": lse})
for c in range(V):
term = float(terms[c])
probability = finite(term / denominator, "probability")
probabilities[c] = probability
trace.add(f"{prefix}_probability_{c}", f"Normalize active class {c}", "probability=term/S",
"This stored binary64 probability is displayed without feeding its formatting back into arithmetic.",
dict(c=c, term=term, denominator=denominator), dict(probability=probability))
next_row = 0
for c in range(1, V):
if float(z[c]) > float(z[next_row]):
next_row = c
next_id, next_probability = int(ids[next_row]), float(probabilities[next_row])
trace.add(f"{prefix}_argmax", "Choose the highest computed input logit",
"strict greater-than updates the winner; exact ties retain lowest compact index",
"Greedy choice uses the saved logits, never argmax of rounded or stored probabilities. Compact index order differs from ascending public ID order.",
maximum_inputs, dict(nextRow=next_row, nextID=next_id, nextProbability=next_probability))
tensors = [
_tensor("ClassIDs", "Class", ids, "Active compact prefix [97,98,512,256,257]; public IDs are labels, not offsets."),
_tensor("Z", "Class", z, "Actual finite computed input logits; no derived-input clipping."),
_tensor("Shifted", "Class", shifted, "Z minus the saved active maximum."),
_tensor("Terms", "Class", terms, "Actual exp(Shifted), before normalization."),
_tensor("Denominator", "Scalar", np.array([denominator], dtype=np.float64), "Actual left-to-right sum of active shifted terms."),
_tensor("LogS", "Scalar", np.array([log_s], dtype=np.float64), "Natural logarithm of Denominator."),
_tensor("LSE", "Scalar", np.array([lse], dtype=np.float64), "Saved max+LogS in binary64."),
_tensor("P", "Class", probabilities, "Terms/Denominator for active classes only, without clipping or padding."),
_tensor("NextRow", "Decision", np.array([next_row], dtype=np.int32), "Lowest compact index among highest computed logits."),
_tensor("NextID", "Decision", np.array([next_id], dtype=np.int32), "Public class ID gathered at NextRow."),
_tensor("NextProbability", "Decision", np.array([next_probability], dtype=np.float64), "Stored P gathered at the computed-logit winner."),
]
return dict(classIDs=ids.tolist(), logits=z.tolist(), max=maximum, shifted=shifted.tolist(), terms=terms.tolist(),
denominator=denominator, logS=log_s, lse=lse, probabilities=probabilities.tolist(),
nextRow=next_row, nextID=next_id, nextProbability=next_probability, tensors=tensors)
def compute_choice(state):
"""Full ordered IV45 record, including raw inactive metadata and every step."""
s = choice_state(state)
raw_z = np.array([s[f"z{c}"] for c in range(5)], dtype=np.float64)
class_ids = np.array(ALL_IDS[:s["V"]], dtype=np.int32)
trace = ChoiceTrace()
trace.add("setup", "Validate all raw logits before selecting active classes", "V in {3,4,5}; every raw z in [-40,40]; activeZ=rawZ[:V]",
"Inactive raw logits still validate and remain visible as metadata. This direct lesson has no text, target, loss, training, seed or sampling.",
s, dict(classCount=s["V"], rawLogitCount=5))
row = direct_distribution(raw_z[:s["V"]], class_ids, trace)
trace.add("finish", "Keep the distribution and greedy decision together", "nextID=classIDs[argmax computed activeZ]; nextProbability=P[nextRow]",
"The selected ID is a deterministic decision. Equal stored probabilities need not mean equal logits.",
dict(nextRow=row["nextRow"]), dict(nextID=row["nextID"], nextProbability=row["nextProbability"]))
outputs = dict(nextID=row["nextID"], nextProbability=row["nextProbability"], classCount=s["V"], logsumexp=row["lse"],
nextRow=row["nextRow"], max=row["max"], denominator=row["denominator"], logS=row["logS"], rawLogitCount=5)
for step in trace.steps:
outputs.update({f"{step['id']}_{key}": value for key, value in step["outputs"].items()})
tensors = [_tensor("RawZ", "ModelRow", raw_z, "All five validated editable raw logits, including inactive slots."), *row["tensors"]]
return dict(status="defined", outputs=outputs, steps=trace.steps, tensors=tensors)
def source_self_check():
"""DEFERRED helper checks; never calls any other file's self-check."""
assert __debug__, "Deferred checks require assertions enabled."
state = dict(DEFAULT_IV45)
trace = ChoiceTrace()
row = direct_distribution([1, 0, 0], [97, 98, 512], trace)
assert list(row) == ["classIDs", "logits", "max", "shifted", "terms", "denominator", "logS", "lse", "probabilities", "nextRow", "nextID", "nextProbability", "tensors"]
ndarray_row = direct_distribution(np.array([1, 0, 0], dtype=np.float64), np.array([97, 98, 512], dtype=np.int32), ChoiceTrace())
assert ndarray_row == row
assert direct_distribution((1, 0, 0), (97, 98, 512), ChoiceTrace()) == row
assert len(trace.steps) == 9 and trace.steps[0]["id"] == "choice_max"
denominator = math.e + 2
assert row["nextRow"] == 0 and row["nextID"] == 97
assert math.isclose(row["probabilities"][0], math.e / denominator, rel_tol=1e-14)
assert math.isclose(row["probabilities"][1], 1 / denominator, rel_tol=1e-14)
assert math.isclose(row["lse"], math.log(denominator), rel_tol=1e-14)
tied = direct_distribution([0, 0, 1, 1, 0], ALL_IDS, ChoiceTrace())
assert tied["nextRow"] == 2 and tied["nextID"] == 512
uniform = direct_distribution([0] * 5, ALL_IDS, ChoiceTrace())
assert uniform["probabilities"] == [0.2] * 5 and uniform["nextID"] == 97
rounded = direct_distribution([0, math.ulp(0.0), 0], ALL_IDS[:3], ChoiceTrace())
assert rounded["probabilities"] == [1 / 3] * 3 and rounded["nextID"] == 98
thin = direct_distribution([-40, 40, -40], ALL_IDS[:3], ChoiceTrace())
assert thin["probabilities"][0] > 0 and thin["probabilities"][2] > 0
derived_trace = ChoiceTrace()
shifted = direct_distribution([101, 100, 100], ALL_IDS[:3], derived_trace, "derived")
assert shifted["probabilities"] == row["probabilities"] and shifted["nextID"] == row["nextID"]
assert all(step["id"].startswith("derived_") for step in derived_trace.steps)
for patch, code in ((dict(V=True), "NONFINITE"), (dict(V=2), "INVALID_INPUT"),
(dict(V=3.5), "INVALID_INPUT"), (dict(z4=True), "NONFINITE"),
(dict(z4=41), "INVALID_INPUT"), (dict(z4=float("nan")), "NONFINITE"),
(dict(z4=10**1000), "NONFINITE")):
fault = guarded(compute_choice)({**state, **patch})
assert list(fault) == ["status", "code", "reason"] and fault["code"] == code
class Hostile(dict):
def __getitem__(self, key):
raise AssertionError("Custom indexing must not be read")
assert guarded(compute_choice)(Hostile(state))["code"] == "INVALID_INPUT"
class HostileList(list):
def __getitem__(self, key):
raise AssertionError("Custom indexing must not be read")
for logits, ids, code in (([1, 0, 0], HostileList([97, 98, 512]), "INVALID_INPUT"),
(HostileList([1, 0, 0]), [97, 98, 512], "INVALID_INPUT"),
([1, 0, 0], [97, 98, 256], "INVALID_INPUT"),
([1, 0, 0], [99, float("nan"), 512], "NONFINITE"),
([1, float("nan"), 0], None, "INVALID_INPUT"),
([1, 0, 0], [97, 98, 512, 256], "SHAPE_MISMATCH"),
(np.array([True, False, False]), ALL_IDS[:3], "INVALID_INPUT"),
([1, True, 0], ALL_IDS[:3], "NONFINITE"),
([1, float("inf"), 0], ALL_IDS[:3], "NONFINITE"),
([1e308, -1e308, 0], ALL_IDS[:3], "NONFINITE"),
([1, 0], [97, 98], "UNSUPPORTED_SIZE")):
try:
direct_distribution(logits, ids, ChoiceTrace(), "bad")
except NumericalFault as error:
assert error.code == code
else:
raise AssertionError("Invalid helper boundary was accepted")
for prefix in (None, "", 0, True):
rejected_trace = ChoiceTrace()
try:
direct_distribution(HostileList(), None, rejected_trace, prefix)
except NumericalFault as error:
assert error.code == "INVALID_INPUT" and "prefix" in str(error)
assert not rejected_trace.steps
else:
raise AssertionError("Prefix must validate before containers")
assert _tensor("F", "Class", np.array([1.0], dtype=np.float64), "check")["dtype"] == "float64"
assert _tensor("I", "Class", np.array([97], dtype=np.int32), "check")["dtype"] == "int32"
row["tensors"][0]["values"][0] = -1
row["probabilities"][0] = -1
trace.steps[0]["outputs"].clear()
assert direct_distribution([1, 0, 0], ALL_IDS[:3], ChoiceTrace())["tensors"][0]["values"] == [97, 98, 512]
assert state == dict(DEFAULT_IV45)
_JSON_INT = int
def run(derive, defaults):
"""Default / full replacement JSON / '-' stdin; never invokes self-checks."""
class ParseFault(ValueError):
"""Only locally owned JSON profile/conversion faults."""
def _members(pairs):
value = {}
for key, member in pairs:
if key in value:
raise ParseFault("Duplicate JSON object members are not allowed.")
value[key] = member
return value
def _constant(token):
raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")
def _integer(token):
if token == "-0":
return -0.0
try:
return _JSON_INT(token)
except ValueError as fault:
if type(fault) is not ValueError:
raise
raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from fault
parser = argparse.ArgumentParser(description=derive.__doc__)
parser.add_argument("state", nargs="?")
args = parser.parse_args()
if args.state is not None:
source = sys.stdin.read() if args.state == "-" else args.state
try:
state = json.loads(source, object_pairs_hook=_members,
parse_constant=_constant, parse_int=_integer)
except (json.JSONDecodeError, ParseFault) as error:
result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
else:
result = derive(state)
else:
result = derive(dict(defaults))
print(json.dumps(result, allow_nan=False, separators=(",", ":")))
Unchanged full decoder — code/python/p10/tiny_reference.py. forward_tiny gathers observed IDs, normalizes, projects, rotates Q/K, performs full causal attention, adds residuals, applies the FFN and reads out active logits. This supplies the separate complete reference path. Its objective and derivative functions also remain visible in the file; these cache lessons do not call them or train parameters. The loader temporarily supplies the intended component module for the FFN’s bare import, then restores the prior module binding.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""IV43 tiny decoder: actual NumPy arrays and scalar-ordered arithmetic.
Text -> learned BPE -> E gather -> LN1 -> Q/K/V -> Q/K RoPE -> causal
attention -> identity WO -> residual -> LN2 -> M3 ReLU FFN -> residual
-> U/bias logits -> stable conditional objective and readout derivatives.
The first token is given. No optimizer, embedding/full-block gradient,
pretrained model or trained capability is supplied. All execution DEFERRED.
Keep the original p06, p07 and p09 files at their relative locations. The
chapter displays this exact dependency closure, rather than a rewritten demo.
"""
import argparse
from functools import wraps
import importlib.util
import json
import math
from pathlib import Path
import sys
from types import MappingProxyType
import numpy as np
_ROOT = Path(__file__).resolve().parent.parent
def _load(name, path):
"""Resolve an explicit source file; never search cwd or sys.path for helpers."""
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise ImportError(f"Cannot load canonical dependency: {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
_component = _load("_iv43_component_reference", _ROOT / "p07" / "component_reference.py")
# The unchanged FFN imports this bare name. Force OUR canonical dependency,
# even when an unrelated module already occupies the name, then restore it.
_missing = object()
_previous_component = sys.modules.get("component_reference", _missing)
sys.modules["component_reference"] = _component
try:
_ffn = _load("_iv43_ffn_reference", _ROOT / "p07" / "ffn_reference.py")
finally:
if _previous_component is _missing:
del sys.modules["component_reference"]
else:
sys.modules["component_reference"] = _previous_component
del _previous_component, _missing
_head = _load("_iv43_head_reference", _ROOT / "p06" / "head_reference.py")
_bpe = _load("_iv43_bpe_reference", _ROOT / "p09" / "bpe_reference.py")
_token = _bpe._token # BPE itself loads this exact adjacent token file.
NumericalFault = _component.NumericalFault
_DEPENDENCY_FAULTS = (NumericalFault, _head.NumericalFault, _bpe.NumericalFault, _ffn.NumericalFault)
ALL_IDS = (97, 98, 512, 256, 257)
PARAMETER_DEFAULTS = MappingProxyType(dict(
e00=1, e01=0, e10=0, e11=1, e20=0, e21=0, e30=0.5, e31=0.5, e40=1, e41=1,
u00=1, u01=0, u02=0, u03=0, u04=0, u10=0, u11=1, u12=0, u13=0, u14=0,
b0=0, b1=0, b2=0, b3=0, b4=0,
))
NUMERIC_DEFAULTS = MappingProxyType(dict(merges=0, **PARAMETER_DEFAULTS))
DEFAULT_IV43 = MappingProxyType(dict(text="ab", **NUMERIC_DEFAULTS))
def finite(value, label):
"""Own numbers only: booleans, coercion and overflowing integers are faults."""
if type(value) not in (int, float):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
try:
value = float(value)
except (ValueError, OverflowError) as error:
raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
if not math.isfinite(value):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
return value
def _object(value, fields, label):
# Exact dict rejects inherited/overridden indexing without invoking a getter.
if type(value) is not dict:
raise NumericalFault("INVALID_INPUT", "Provide a plain object with exactly the named data fields.")
if any(type(key) is not str for key in value) or set(value) != set(fields):
raise NumericalFault("INVALID_INPUT", "Provide every own field and no extra or symbol fields, including inactive parameters.")
def numeric_parameters(state):
"""Check all26 numeric fields, including unused rows/columns, in raw order."""
_object(state, NUMERIC_DEFAULTS, "numeric parameters")
checked = {}
for key in NUMERIC_DEFAULTS:
value = finite(state[key], key)
low, high = (0, 2) if key == "merges" else (-4, 4) if key.startswith("b") else (-2, 2)
if key == "merges" and (not value.is_integer() or not low <= value <= high):
raise NumericalFault("INVALID_INPUT", "merges must be an integer from 0 to 2.")
if not low <= value <= high:
raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
checked[key] = int(value) if key == "merges" else value
return checked
def tiny_state(state):
"""String type first, then EVERY numeric field, then text semantics later."""
_object(state, DEFAULT_IV43, "state")
if type(state["text"]) is not str:
raise NumericalFault("INVALID_INPUT", "text must be an actual string, without coercion.")
return dict(text=state["text"], numeric=numeric_parameters({key: state[key] for key in NUMERIC_DEFAULTS}))
def guarded(derive):
@wraps(derive)
def call(state):
try:
return derive(state)
except _DEPENDENCY_FAULTS as error:
return dict(status="unavailable", code=error.code, reason=str(error))
except (OverflowError, FloatingPointError) as error:
return dict(status="unavailable", code="NONFINITE", reason=str(error))
return call
def _ids(values, active):
"""Validate original public IDs before narrowing to real int32 storage."""
if type(values) is np.ndarray:
if values.ndim != 1 or values.dtype.kind not in "iuf":
raise NumericalFault("INVALID_INPUT", "inputIDs must be a dense one-dimensional numeric array.")
entries = values.tolist()
elif type(values) in (list, tuple):
entries = values
else:
raise NumericalFault("INVALID_INPUT", "inputIDs must be an actual dense array.")
if len(entries) > 3:
raise NumericalFault("UNSUPPORTED_SIZE", "Numeric inputIDs must contain at most 3 observed tokens.")
if not entries:
raise NumericalFault("UNAVAILABLE", "Numeric forward requires at least one observed input token.")
result = []
for t, value in enumerate(entries):
if type(value) not in (int, float):
raise NumericalFault("INVALID_INPUT", f"inputIDs[{t}] must be an active public model ID.")
try:
value = float(value)
except (ValueError, OverflowError) as error:
raise NumericalFault("INVALID_INPUT", f"inputIDs[{t}] must be an active public model ID.") from error
if not math.isfinite(value) or not value.is_integer() or value not in active:
raise NumericalFault("INVALID_INPUT", f"inputIDs[{t}] must be an active public model ID.")
result.append(int(value))
return np.array(result, dtype=np.int32)
def _float_tensor(identifier, shape, axes, values, provenance):
"""Serialize an actual float64 array into detached row-major JSON storage."""
if type(values) is not np.ndarray or values.dtype != np.dtype(np.float64) or tuple(shape) != values.shape:
raise NumericalFault("SHAPE_MISMATCH", f"{identifier} requires actual float64 storage of the declared shape.")
return _component.tensor(identifier, shape, axes, values.reshape(-1).tolist(), provenance)
def _norm(name, x, trace):
"""Keep normalization statistics in real scalar steps, without extra tensors."""
T = x["shape"][1]
X = np.array(x["values"], dtype=np.float64).reshape(1, T, 2)
output = np.empty((1, T, 2), dtype=np.float64)
for t in range(T):
row = _component.feature_norm("layer", f"{name.lower()}_{t}", X[0, t].tolist(),
[1, 1], [0, 0], 1, trace)
output[0, t] = row["values"]
source = "X" if name == "LN1" else "R1"
return _float_tensor(name, [1, T, 2], ["B", "T", "D"], output,
f"Per-token feature layer norm of {source}; population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside sqrt.")
def _residual(name, prefix, left, right, trace):
result = _component.same_shape_add(name, left, right)
for t in range(result["shape"][1]):
for d in range(2):
index = 2 * t + d
trace.add(f"{prefix}_{t}_{d}", f"{name} residual [0,{t},{d}]", "value=left+right",
"Actual same-shape addition; no broadcasting or second numerical engine.",
dict(t=t, d=d, left=left["values"][index], right=right["values"][index]),
dict(value=result["values"][index]))
return result
def _rope(role, values, trace):
"""One adjacent Q/K pair, frequency1, angle=absolute token position radians."""
T = values.shape[2]
rotated = np.empty((1, 1, T, 2), dtype=np.float64)
angles, cosines, sines = (np.empty(T, dtype=np.float64) for _ in range(3))
for t in range(T):
frequency = 10000 ** 0
angle = finite(t * frequency, "RoPE angle")
cosine, sine = finite(math.cos(angle), "RoPE cosine"), finite(math.sin(angle), "RoPE sine")
x0, x1 = float(values[0, 0, t, 0]), float(values[0, 0, t, 1])
product0, product1 = finite(x0 * cosine, "RoPE x0*cos"), finite(x1 * sine, "RoPE x1*sin")
product2, product3 = finite(x0 * sine, "RoPE x0*sin"), finite(x1 * cosine, "RoPE x1*cos")
rotated0, rotated1 = finite(product0 - product1, "RoPE first coordinate"), finite(product2 + product3, "RoPE second coordinate")
rotated[0, 0, t] = [rotated0, rotated1]
angles[t], cosines[t], sines[t] = angle, cosine, sine
trace.add(f"rope_{role}_{t}", f"RoPE {role} token {t}",
"frequency=10000^0; angle=t*frequency; rotated0=x0*cos-x1*sin; rotated1=x0*sin+x1*cos",
"Rotate this single adjacent pair at absolute position t. Q and K rotate; V remains unrotated. Every product is saved.",
dict(t=t, x0=x0, x1=x1, base=10000, exponent=0),
dict(frequency=frequency, angle=angle, cos=cosine, sin=sine, product0=product0, product1=product1,
product2=product2, product3=product3, rotated0=rotated0, rotated1=rotated1))
return rotated, angles, cosines, sines
# Literal metadata adoption is local: unchanged helpers still supply all storage and steps.
_PROJECTION_PROVENANCE = {
"X": "Active token rows; D=2 input features always retained.",
"WQ": "Query columns packed by h*Dk+f from wq{d}{h}{f}.",
"WK": "Key columns packed by h*Dk+f from wk{d}{h}{f}.",
"WV": "Value columns packed by h*Dv+f from wv{d}{h}{f}.",
"QConcat": "XWQ; each packed coordinate has two products and one sum.",
"KConcat": "XWK; each packed coordinate has two products and one sum.",
"VConcat": "XWV; values are projected separately from queries and keys.",
"QSplit": "QConcat reshaped without changing flat order; feature=h*F+f.",
"QHeads": "QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.",
"KSplit": "KConcat reshaped without changing flat order; feature=h*F+f.",
"KHeads": "KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.",
"VSplit": "VConcat reshaped without changing flat order; feature=h*F+f.",
"VHeads": "VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.",
}
_ATTENTION_PROVENANCE = {
"raw": "Separate QHeads KHeads transpose products within every batch and head.",
"scores": "raw/sqrt(Dk); the two-product order matches IV25 for H1,Dk2.",
"allowed": "Causal and/or valid-key mask; shared validity across B and H; every query retained.",
"logits": "Finite score+shift, including forbidden cells; mask applied separately.",
"probabilities": "Stable allowed-key softmax for each B/H/query independently; forbidden probabilities exactly zero.",
"OHeads": "Actual per-head P times VHeads; every product and running sum is traced.",
}
_JOIN_PROVENANCE = {
"C": "OHeads permuted to token-major order then joined by c=h*Dv+f; values unchanged.",
"WO": "wo{h}{f}{d} packed in h,f,d order, preserving parameter identity.",
"Y": "Y=C WO, summing products in ascending joined-feature order from zero; no normalization.",
}
_FFN_PROVENANCE = {
"W1": "Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.",
"b1": "Shared hidden bias, added after the two products.",
"Z": "Hidden preactivations X W1+b1; no batch or token mixing.",
"Hidden": "ReLU(Z)=max(0,Z), before the second affine layer.",
"W2": "Shared hidden-to-output weights, f2{m}{d}.",
"b2": "Shared output bias, added after all three running sums.",
"F": "ReLU(X W1+b1) W2+b2, independently per token with shared parameters.",
}
def _attention(n1, trace):
"""Reuse project/attend/join kernels; explicitly override their old WO."""
T = n1["shape"][1]
s = dict(_head.OUTPUT_HEAD_DEFAULTS)
s.update(B=1, T=T, H=1, Dk=2, Dv=2, mode=1, shift=0)
for t in range(T):
for d in range(2):
s[f"x0{t}{d}"] = n1["values"][2 * t + d]
for prefix in ("wq", "wk", "wv"):
for d in range(2):
for f in range(2):
s[f"{prefix}{d}0{f}"] = int(d == f)
for f in range(2):
for d in range(2):
s[f"wo0{f}{d}"] = int(f == d)
child = _head.head_trace()
try:
projected = _head.project_heads(s, child)
for step in child.steps:
trace.add(f"heads_{step['id']}", step["label"], step["equation"],
step["explanation"], step["inputs"], step["outputs"])
q, angles, cosines, sines = _rope("Q", projected["QHeads"], trace)
k, _, _, _ = _rope("K", projected["KHeads"], trace)
rotated = {**projected, "QHeads": q, "KHeads": k}
child = _head.head_trace()
attended = _head.attend_heads(s, rotated, child)
joined = _head.join_heads(s, attended, child)
except _head.NumericalFault as error:
raise NumericalFault(error.code, str(error)) from error
for step in child.steps:
trace.add(f"heads_{step['id']}", step["label"], step["equation"],
step["explanation"], step["inputs"], step["outputs"])
tensors = [{**record, "id": f"Projection{record['id']}",
"provenance": _PROJECTION_PROVENANCE[record["id"]] + " Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated."}
for record in projected["tensors"]]
tensors.extend([
_float_tensor("RotatedQHeads", [1, 1, T, 2], ["B", "H", "T", "Dk"], q,
"Actual RoPE(ProjectionQHeads) supplied as attendHeads QHeads; original projection is retained separately."),
_float_tensor("RotatedKHeads", [1, 1, T, 2], ["B", "H", "T", "Dk"], k,
"Actual RoPE(ProjectionKHeads) supplied as attendHeads KHeads; original projection is retained separately."),
_float_tensor("RoPEAngles", [T], ["Position"], angles, "Absolute position t times the single-pair frequency1, in radians."),
_float_tensor("RoPECos", [T], ["Position"], cosines, "Stored cos(angle) used in the Q pair rotation; K uses the same angle."),
_float_tensor("RoPESin", [T], ["Position"], sines, "Stored sin(angle) used in the Q pair rotation; K uses the same angle."),
])
tensors.extend({**record, "id": f"Attention{record['id']}",
"provenance": _ATTENTION_PROVENANCE[record["id"]] + " QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads."}
for record in attended["tensors"])
tensors.extend({**record, "id": "AttentionOutput" if record["id"] == "Y" else f"Attention{record['id']}",
"provenance": _JOIN_PROVENANCE[record["id"]] + " Source is AttentionOHeads; active WO is explicitly identity2."}
for record in joined["tensors"])
return tensors[-1], tensors
def tiny_trace():
"""An explicit finite scalar accumulator; forward_tiny never discards one."""
return _component.component_trace()
def forward_tiny(numeric_state, input_ids, trace):
"""Observed-ID forward with the adopted T,V,classIDs,inputIDs,inputRows,rows,tensors.
Validate26 parameters first, then dense active public IDs, including EOS.
Real float64/int32/bool arrays back the computation; the public return is a
detached JSON snapshot with complete stable distributions, without targets.
"""
s = numeric_parameters(numeric_state)
V = 3 + s["merges"]
ids = _ids(input_ids, ALL_IDS[:V])
T = len(ids)
class_ids = np.array(ALL_IDS[:V], dtype=np.int32)
input_rows = np.array([ALL_IDS.index(int(identifier)) for identifier in ids], dtype=np.int32)
E = np.array([[s[f"e{r}{d}"] for d in range(2)] for r in range(5)], dtype=np.float64)
U = np.array([[s[f"u{d}{c}"] for c in range(5)] for d in range(2)], dtype=np.float64)
bias = np.array([s[f"b{c}"] for c in range(5)], dtype=np.float64)
X = np.empty((1, T, 2), dtype=np.float64)
for t, identifier in enumerate(ids):
row = int(input_rows[t])
X[0, t] = E[row]
trace.add(f"input_{t}", f"Gather embedding for observed token {t}", "inputRow=compactRow(inputID); X[0,t,d]=E[inputRow,d]",
"The full model has an ordinary EOS embedding row. This kernel does not stop on EOS.",
dict(t=t, inputID=int(identifier)), dict(inputRow=row, x0=float(X[0, t, 0]), x1=float(X[0, t, 1])))
tensors = [
_token.tensor("AllClassIDs", "ModelRow", np.array(ALL_IDS, dtype=np.int32), "Full compact model row map: a,b,EOS,ab,abab; public IDs are not storage offsets."),
_token.tensor("ClassIDs", "Class", class_ids, "Active prefix of the full model row map; V=3+merges."),
_float_tensor("E", [5, 2], ["ModelRow", "D"], E, "All ten validated editable embeddings, including EOS and inactive learned pieces."),
_float_tensor("U", [2, 5], ["D", "ModelRow"], U, "All ten validated editable readout weights; only the first V columns contribute logits."),
_float_tensor("Bias", [5], ["ModelRow"], bias, "All five validated editable biases; inactive columns have no objective dependency."),
_token.tensor("InputIDs", "Position", ids, "Observed public IDs supplied directly to the numeric kernel; active EOS is permitted."),
_token.tensor("InputRows", "Position", input_rows, "Compact model row gathered for each observed ID; never index by public ID512."),
_float_tensor("X", [1, T, 2], ["B", "T", "D"], X, "Actual gathered E rows; B=1, token-major storage and D=2."),
]
n1 = _norm("LN1", tensors[-1], trace)
attention, at = _attention(n1, trace)
r1 = _residual("R1", "residual1", tensors[-1], attention, trace)
n2 = _norm("LN2", r1, trace)
fs = dict(B=1, T=T,
f100=1, f101=0, f102=0, f110=0, f111=1, f112=0,
fb10=0, fb11=0, fb12=0,
f200=1, f201=0, f210=0, f211=1, f220=0, f221=0,
fb20=0, fb21=0)
ffn = _ffn.feed_forward(fs, n2, trace, "ffn")
y = _residual("Y", "residual2", r1, ffn["output"], trace)
ft = [{**record, "provenance": _FFN_PROVENANCE[record["id"]]} for record in ffn["tensors"]]
tensors.extend([n1, *at, r1, n2, *ft, y])
Y = np.array(y["values"], dtype=np.float64).reshape(1, T, 2)
logits = np.empty((T, V), dtype=np.float64)
rows = []
for t in range(T):
for c in range(V):
y0, y1, u0, u1, b = float(Y[0, t, 0]), float(Y[0, t, 1]), float(U[0, c]), float(U[1, c]), float(bias[c])
product0, product1 = finite(y0 * u0, "readout product0"), finite(y1 * u1, "readout product1")
summed = finite(product0 + product1, "readout sum")
value = finite(summed + b, "readout logit")
logits[t, c] = value
trace.add(f"readout_{t}_{c}", f"Readout row {t}, class {c}",
"product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias",
"Only the active compact class prefix contributes to logits; targets are not operands.",
dict(t=t, c=c, y0=y0, u0=u0, y1=y1, u1=u1, bias=b),
dict(product0=product0, product1=product1, sum=summed, logit=value))
rows.append(_class_row(logits[t], t, class_ids, trace))
tensors.extend([
_float_tensor("Logits", [T, V], ["Position", "Class"], logits, "Final Y times the active U prefix, then active Bias; targets are not operands."),
_float_tensor("Max", [T], ["Position"], np.array([row["max"] for row in rows], dtype=np.float64), "Maximum computed active class logit at each position."),
_float_tensor("Shifted", [T, V], ["Position", "Class"], np.array([row["shifted"] for row in rows], dtype=np.float64), "Computed class logit minus its saved row maximum."),
_float_tensor("Terms", [T, V], ["Position", "Class"], np.array([row["terms"] for row in rows], dtype=np.float64), "Actual exp(Shifted) before left-to-right class summation."),
_float_tensor("Denominator", [T], ["Position"], np.array([row["denominator"] for row in rows], dtype=np.float64), "Shifted exponential sum from zero in ascending compact class order."),
_float_tensor("LogS", [T], ["Position"], np.array([row["logS"] for row in rows], dtype=np.float64), "ln(Denominator), saved for factored NLL."),
_float_tensor("LSE", [T], ["Position"], np.array([row["lse"] for row in rows], dtype=np.float64), "Max+LogS; saved evidence, not subtracted from target logits to compute NLL."),
_float_tensor("P", [T, V], ["Position", "Class"], np.array([row["probabilities"] for row in rows], dtype=np.float64), "Terms/Denominator for real active classes only; no inactive-class probabilities."),
_token.tensor("NextRows", "Position", np.array([row["nextRow"] for row in rows], dtype=np.int32), "Highest computed logit; exact ties keep the smallest compact class."),
_token.tensor("NextIDs", "Position", np.array([row["nextID"] for row in rows], dtype=np.int32), "Public ID mapped from each computed-logit winner."),
_float_tensor("NextProbability", [T], ["Position"], np.array([row["nextProbability"] for row in rows], dtype=np.float64), "Stored class probability of the computed-logit winner; never fed back as an observed input."),
])
return json.loads(json.dumps(dict(T=T, V=V, classIDs=class_ids.tolist(), inputIDs=ids.tolist(),
inputRows=input_rows.tolist(), rows=rows, tensors=tensors), allow_nan=False))
def _tokenize(text, merges, trace):
"""Actual IV39 algorithm with the narrower IV43 text/model boundary.
Prepare encoders before copying any successful record. Size in UTF16 units
precedes surrogate validation, then actual UTF8 size, then model alphabet.
The unchanged24/32-byte helper limits remain unchanged in their own files.
"""
if _token.utf16_length(text) > 6:
raise NumericalFault("UNSUPPORTED_SIZE", "text: more than 6 UTF-16 units exceeds the 6-byte model input bound.")
encoding = _token.TokenTrace()
try:
corpus = _bpe.encode_bounded("abab", "corpus", "corpus", encoding)
source = _bpe.encode_bounded(text, "text", "source", encoding)
if len(source["bytes"]) > 6:
raise NumericalFault("UNSUPPORTED_SIZE", "text: the actual UTF-8 encoding exceeds 6 bytes.")
if any(character not in "ab" for character in text):
raise NumericalFault("UNAVAILABLE", "This toy model supports only raw a and b letters; no normalization, unknown token or truncation is applied.")
if not text:
raise NumericalFault("UNAVAILABLE", "Empty text has no observed first token and no conditional target.")
child = _token.TokenTrace()
child.add("setup", "Declare learned byte-pair encoding and both exact inputs",
"byte IDs=0..255; learned ID=256+rank; EOS=512; each text field<=24 UTF-8 bytes",
"The disclosed training corpus is always abab. Encode the separate exact target with learned ranks, then append EOS. No normalization, trimming, unknown token or truncation.",
dict(requestedMerges=merges, eos=1),
dict(corpusUnits=4, corpusScalars=4, utf16Units=_token.utf16_length(text),
scalarCount=len(source["codePoints"]), byteBound=_bpe.BPE_BYTE_BOUND,
mergeBase=_bpe.MERGE_BASE, mergeBound=_bpe.MERGE_BOUND, EOS=512))
child.steps.extend(encoding.steps)
tensors = []
for stem, encoded in (("Corpus", corpus), ("Source", source)):
for suffix, key, axis, provenance in (
("CodePoints", "codePoints", "Scalars", "Validated Unicode scalars in exact input order."),
("UTF16Offsets", "offsets", "Scalars", "Zero-based UTF-16 storage offset for each scalar."),
("UTF16Widths", "widths", "Scalars", "UTF-16 storage units consumed by each scalar."),
("ByteOffsets", "byteOffsets", "Scalars", "Zero-based UTF-8 byte offset for each scalar."),
("ByteWidths", "byteWidths", "Scalars", "Actual UTF-8 bytes emitted by each scalar."),
("Bytes", "bytes", "Bytes", "Manual UTF-8 encoding in source order, preserving all data."),
):
_bpe.save_tensor(tensors, f"{stem}{suffix}", axis, encoded[key], provenance)
trained = _bpe.train_bpe(corpus["bytes"], merges, child, tensors)
ids = _bpe.encode_bpe(source["bytes"], trained["rules"], 1, child, tensors)
corpus_decoded = _bpe.decode_bpe_ids(trained["ids"], trained["rules"], 0, "corpus", child)
decoded = _bpe.decode_bpe_ids(ids, trained["rules"], 1, "target", child)
corpus_equal = int(corpus_decoded["decoded"] == "abab")
equal = int(decoded["decoded"] == text)
if not corpus_equal or not equal:
raise NumericalFault("INVALID_INPUT", "Actual BPE reconstructions did not equal both original strings.")
child.add("roundtrip", "Compare both actual strict reconstructions with the original strings",
"corpusEqual=(corpusDecoded===corpus); equal=(targetDecoded===text)",
"Expand actual saved IDs, concatenate bytes, strictly reconstruct scalars, then compare complete strings.",
dict(corpusOriginalUnits=4, corpusDecodedUnits=_token.utf16_length(corpus_decoded["decoded"]),
corpusDecodedByteCount=len(corpus_decoded["bytes"]), originalUnits=_token.utf16_length(text),
decodedUnits=_token.utf16_length(decoded["decoded"]), decodedByteCount=len(decoded["bytes"])),
dict(corpusTokens=len(trained["ids"]), tokenCount=len(ids), corpusEqual=corpus_equal, equal=equal))
_bpe.save_tensor(tensors, "CorpusDecodedBytes", "Bytes", corpus_decoded["bytes"], "Actual final corpus ID expansions passed to strict UTF-8 decoding.")
_bpe.save_tensor(tensors, "TargetDecodedBytes", "Bytes", decoded["bytes"], "Actual final target ID expansions passed to strict UTF-8 decoding.")
except _bpe.NumericalFault as error:
raise NumericalFault(error.code, str(error)) from error
if len(ids) - 1 > 3:
raise NumericalFault("UNSUPPORTED_SIZE", "The actual BPE sequence exceeds 3 observed input positions; change text or merges explicitly.")
for step in child.steps:
trace.add(f"tokenizer_{step['id']}", step["label"], step["equation"],
step["explanation"], step["inputs"], step["outputs"])
tensors = [{**record, "id": f"Tokenizer{record['id']}"} for record in tensors]
expansions = {rule["id"]: rule["bytes"].tolist() for rule in trained["rules"]}
def expansion(identifier):
return [] if identifier == 512 else [identifier] if identifier <= 255 else expansions[identifier]
def labels(values):
return ["ID 512: EOS (explicit control), bytes []" if int(identifier) == 512 else
f"ID {int(identifier)}, bytes {_token.json_text(expansion(int(identifier)))}" for identifier in values]
texts = dict(
corpus="abab", input=text, corpusDecoded=corpus_decoded["decoded"], decoded=decoded["decoded"],
corpusLabels=labels(trained["ids"]), corpusExpansions=[_token.json_text(expansion(int(identifier))) for identifier in trained["ids"]],
targetLabels=labels(ids), targetExpansions=[_token.json_text(expansion(int(identifier))) for identifier in ids],
ruleLabels=[f"ID {rule['id']}, bytes {_token.json_text(rule['bytes'].tolist())}" for rule in trained["rules"]],
ruleExpansions=[_token.json_text(rule["bytes"].tolist()) for rule in trained["rules"]],
trainingStop="Zero merges requested: no training round or pair selection occurs." if merges == 0 else "Stopped early: fewer than two current training tokens remain." if len(trained["rules"]) < merges else "Requested merge budget completed.",
)
summary = dict(corpusBytes=len(corpus["bytes"]), byteCount=len(source["bytes"]), actualMerges=len(trained["rules"]),
tokenCount=len(ids), requestedMerges=merges, corpusTokens=len(trained["ids"]), eos=1,
byteBound=_bpe.BPE_BYTE_BOUND, vocabularyItems=256 + len(trained["rules"]) + 1,
corpusEqual=corpus_equal, equal=equal)
return dict(ids=ids, tensors=tensors, texts=texts, summary=summary)
def _class_row(logits, t, class_ids, trace):
"""Stable complete row before the next token's readout; strict-logit argmax."""
V = len(class_ids)
maximum_inputs = {f"z{c}": float(logits[c]) for c in range(V)}
maximum = max(maximum_inputs.values())
trace.add(f"class_{t}_max", f"Class maximum for prediction row {t}", "max=max(active logits)",
"Only active classes contribute. The maximum term exp(0)=1 prevents a zero normalizer.",
maximum_inputs, dict(max=maximum))
shifted, terms, probabilities = (np.empty(V, dtype=np.float64) for _ in range(3))
denominator, running = 0.0, {}
for c in range(V):
z = float(logits[c])
shift = finite(z - maximum, "class shifted logit")
term = finite(math.exp(shift), "class exponential")
shifted[c], terms[c] = shift, term
trace.add(f"class_{t}_exp_{c}", f"Class row {t}, exponential {c}", "shifted=logit-max; term=exp(shifted)",
"Save each actual shifted exponential; no epsilon, clipping or rounded display operand.",
dict(t=t, c=c, logit=z, max=maximum), dict(shifted=shift, term=term))
denominator = finite(denominator + term, "class denominator")
running[f"running{c}"] = denominator
log_s = finite(math.log(denominator), "class logS")
lse = finite(maximum + log_s, "class logsumexp")
trace.add(f"class_{t}_normalize", f"Class denominator and logsumexp for row {t}",
"running starts at 0; running_c=previous+term_c; denominator=last running; logS=ln(denominator); lse=max+logS",
"Terms accumulate left to right. The objective uses (max-targetLogit)+logS rather than subtraction of rounded LSE.",
{**{f"term{c}": float(terms[c]) for c in range(V)}, "max": maximum},
{**running, "denominator": denominator, "logS": log_s, "lse": lse})
for c in range(V):
term = float(terms[c])
probability = finite(term / denominator, "class probability")
probabilities[c] = probability
trace.add(f"class_{t}_probability_{c}", f"Class row {t}, probability {c}", "probability=term/denominator",
"This is an actual stored probability, never a rounded display value used as arithmetic input.",
dict(t=t, c=c, term=term, denominator=denominator), dict(probability=probability))
next_row = 0
for c in range(1, V):
if float(logits[c]) > float(logits[next_row]):
next_row = c
next_id, next_probability = int(class_ids[next_row]), float(probabilities[next_row])
trace.add(f"class_{t}_argmax", f"Computed-logit winner for row {t}", "argmax(logits); exact ties use smallest compact class",
"Probability rounding can make distinct logits appear tied. Compare computed logits; predictions are not observed teacher-forcing inputs.",
maximum_inputs, dict(nextRow=next_row, nextID=next_id, nextProbability=next_probability))
return dict(logits=logits.tolist(), max=maximum, shifted=shifted.tolist(), terms=terms.tolist(),
denominator=denominator, logS=log_s, lse=lse, probabilities=probabilities.tolist(),
nextRow=next_row, nextID=next_id, nextProbability=next_probability)
def _objective(forward, targets, trace):
"""Mean shifted-target NLL and ONLY the conditional readout derivatives."""
T, V, rows, class_ids = forward["T"], forward["V"], forward["rows"], forward["classIDs"]
Y = np.array(next(record["values"] for record in forward["tensors"] if record["id"] == "Y"), dtype=np.float64).reshape(1, T, 2)
target_rows = np.empty(T, dtype=np.int32)
nll, gaps, target_logits, target_probabilities = (np.empty(T, dtype=np.float64) for _ in range(4))
for t in range(T):
target_id = int(targets[t])
if target_id not in class_ids:
raise NumericalFault("INVALID_INPUT", "Every shifted target must be an active model class.")
c = class_ids.index(target_id)
target_rows[t] = c
trace.add(f"target_lookup_{t}", f"Map shifted target at position {t}", "targetRow=compactRow(sequence[t+1])",
"Teacher forcing keeps the observed input and its next target distinct. Final EOS contributes one loss.",
dict(t=t, targetID=target_id, V=V), dict(targetRow=c))
row = rows[t]
target_logit, maximum, log_s, probability = row["logits"][c], row["max"], row["logS"], row["probabilities"][c]
gaps[t] = finite(maximum - target_logit, "target gap")
nll[t] = finite(float(gaps[t]) + log_s, "target NLL")
target_logits[t], target_probabilities[t] = target_logit, probability
trace.add(f"loss_{t}", f"Shifted target loss at position {t}", "gap=max-targetLogit; nll=gap+logS",
"Use the saved stable operands. The first piece is given; every continuation through EOS has weight1.",
dict(t=t, targetID=target_id, targetRow=c, max=maximum, targetLogit=target_logit, logS=log_s, probability=probability),
dict(gap=float(gaps[t]), nll=float(nll[t])))
loss_sum = 0.0
for t in range(T):
previous = loss_sum
loss_sum = finite(previous + float(nll[t]), "loss sum")
trace.add(f"reduce_{t}", f"Accumulate target loss {t}", "lossSum=previousLossSum+nll",
"Accumulate every actual shifted target loss in ascending position order, including EOS.",
dict(t=t, previousLossSum=previous, nll=float(nll[t])), dict(lossSum=loss_sum))
mean_nll = finite(loss_sum / T, "mean NLL")
perplexity = finite(math.exp(mean_nll), "perplexity")
trace.add("reduction", "Mean conditional objective and perplexity", "validCount=T; meanNLL=lossSum/T; perplexity=exp(meanNLL)",
"Natural-log loss is in nats per shifted target. Tokenizer changes alter the events and conditioning.",
dict(T=T, lossSum=loss_sum), dict(validCount=T, lossSum=loss_sum, meanNLL=mean_nll, perplexity=perplexity))
d_logits = np.empty((T, V), dtype=np.float64)
for t in range(T):
for c in range(V):
probability, indicator = rows[t]["probabilities"][c], int(c == int(target_rows[t]))
difference = finite(probability - indicator, "probability minus target")
gradient = finite(difference / T, "mean logit derivative")
d_logits[t, c] = gradient
trace.add(f"gradient_{t}_{c}", f"Mean-loss logit derivative [{t},{c}]", "indicator=(c=targetRow)?1:0; difference=P-indicator; gradient=difference/T",
"The analytic sensitivity includes the mean-loss denominator; it is not a gradient check or update.",
dict(t=t, c=c, targetRow=int(target_rows[t]), probability=probability, T=T),
dict(indicator=indicator, difference=difference, gradient=gradient))
# Inactive raw columns have zero dependency, not fabricated active probabilities.
d_u = np.zeros((2, 5), dtype=np.float64)
d_bias = np.zeros(5, dtype=np.float64)
for d in range(2):
for c in range(V):
inputs, outputs, gradient = dict(d=d, c=c), {}, 0.0
for t in range(T):
feature, g = float(Y[0, t, d]), float(d_logits[t, c])
inputs[f"y{t}"], inputs[f"g{t}"] = feature, g
product = finite(feature * g, "readout gradient product")
gradient = finite(gradient + product, "readout gradient sum")
outputs[f"product{t}"], outputs[f"running{t}"] = product, gradient
outputs["gradient"] = gradient
d_u[d, c] = gradient
trace.add(f"readout_gradient_{d}_{c}", f"Readout weight derivative [{d},{c}]", "product_t=Y[t,d]*dLogits[t,c]; running starts at 0; gradient=sum_t product_t",
"Hold final decoder features fixed. Each product immediately enters the sum in ascending position order.", inputs, outputs)
for c in range(V):
inputs, outputs, gradient = dict(c=c), {}, 0.0
for t in range(T):
g = float(d_logits[t, c])
inputs[f"g{t}"] = g
gradient = finite(gradient + g, "bias gradient sum")
outputs[f"running{t}"] = gradient
outputs["gradient"] = gradient
d_bias[c] = gradient
trace.add(f"bias_gradient_{c}", f"Readout bias derivative [{c}]", "running starts at 0; gradient=sum_t dLogits[t,c]",
"Each active bias contributes directly at each position. Inactive raw columns have structural zero dependency.", inputs, outputs)
tensors = [
_token.tensor("TargetIDs", "Position", targets, "sequence[1:]; final EOS included exactly once as a scored continuation."),
_token.tensor("TargetRows", "Position", target_rows, "Active compact class of each observed shifted target."),
_float_tensor("TargetLogits", [T], ["Position"], target_logits, "Actual class logit gathered after computing the entire causal distribution."),
_float_tensor("TargetProbability", [T], ["Position"], target_probabilities, "Actual target class probability; never rounded before loss computation."),
_float_tensor("TargetGap", [T], ["Position"], gaps, "Saved max-targetLogit used in the factored NLL."),
_float_tensor("NLL", [T], ["Position"], nll, "TargetGap+LogS for every shifted target, including EOS."),
_float_tensor("dLogits", [T, V], ["Position", "Class"], d_logits, "(P-oneHot(target))/T for the actual mean objective."),
_float_tensor("dU", [2, 5], ["D", "ModelRow"], d_u, "Conditional readout gradient sum_t Y[t,d]*dLogits[t,c]; inactive raw class columns have structural zero dependency."),
_float_tensor("db", [5], ["ModelRow"], d_bias, "Conditional readout bias gradient sum_t dLogits[t,c]; inactive raw biases have structural zero dependency."),
]
return dict(validCount=T, lossSum=loss_sum, meanNLL=mean_nll, perplexity=perplexity, tensors=tensors)
_JSON_INT = int
def run(derive, defaults):
"""No args: default; one JSON argument: COMPLETE replacement; '-': stdin.
No query calls any self-check. Invalid data returns only status/code/reason.
No caller cwd supplies a helper; source loading above is file-relative.
"""
class ParseFault(ValueError):
"""Only locally owned JSON profile/conversion faults."""
def _members(pairs):
value = {}
for key, member in pairs:
if key in value:
raise ParseFault("Duplicate JSON object members are not allowed.")
value[key] = member
return value
def _constant(token):
raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")
def _integer(token):
if token == "-0":
return -0.0
try:
return _JSON_INT(token)
except ValueError as fault:
if type(fault) is not ValueError:
raise
raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from fault
parser = argparse.ArgumentParser(description=derive.__doc__)
parser.add_argument("state", nargs="?")
args = parser.parse_args()
if args.state is not None:
source = sys.stdin.read() if args.state == "-" else args.state
try:
state = json.loads(source, object_pairs_hook=_members,
parse_constant=_constant, parse_int=_integer)
except (json.JSONDecodeError, ParseFault) as error:
result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
else:
result = derive(state)
else:
result = derive(dict(defaults))
print(json.dumps(result, allow_nan=False, separators=(",", ":")))
def source_self_check():
"""DEFERRED explicit helper assertions; never called by import or query.
Source-authored anchors/metamorphics are not independent oracle authority.
Future V5 separately invokes this, the wrapper check and the old BPE check.
"""
assert __debug__, "Deferred checks require assertions enabled."
assert _ffn.NumericalFault is _component.NumericalFault
assert _ffn.tensor is _component.tensor
assert _ffn.finite is _component.finite
assert Path(_component.__file__).resolve() == _ROOT / "p07" / "component_reference.py"
assert Path(_ffn.__file__).resolve() == _ROOT / "p07" / "ffn_reference.py"
assert Path(_head.__file__).resolve() == _ROOT / "p06" / "head_reference.py"
assert Path(_bpe.__file__).resolve() == _ROOT / "p09" / "bpe_reference.py"
assert Path(_token.__file__).resolve() == _ROOT / "p09" / "token_reference.py"
assert len(DEFAULT_IV43) == 27 and len(NUMERIC_DEFAULTS) == 26
assert list(DEFAULT_IV43) == ["text", "merges", *PARAMETER_DEFAULTS]
assert list(tiny_state(dict(DEFAULT_IV43))) == ["text", "numeric"]
def rejects(call, code):
try:
call()
except NumericalFault as error:
assert error.code == code, (error.code, code)
else:
raise AssertionError("Invalid helper input was accepted")
def forward(parameters, ids):
return forward_tiny(parameters, ids, tiny_trace())
def saved(record, identifier):
return next(tensor for tensor in record["tensors"] if tensor["id"] == identifier)
s = dict(NUMERIC_DEFAULTS)
trace = tiny_trace()
f = forward_tiny(s, [97, 98], trace)
assert list(f) == ["T", "V", "classIDs", "inputIDs", "inputRows", "rows", "tensors"]
assert list(f["rows"][0]) == ["logits", "max", "shifted", "terms", "denominator", "logS", "lse", "probabilities", "nextRow", "nextID", "nextProbability"]
assert f["T"] == 2 and f["V"] == 3 and f["inputRows"] == [0, 1]
assert len(trace.steps) == 112 and len(f["tensors"]) == 57
assert saved(f, "E")["shape"] == [5, 2] and saved(f, "U")["shape"] == [2, 5]
assert saved(f, "Bias")["shape"] == [5]
assert saved(f, "InputIDs")["dtype"] == "int32" and _ids([97, 98], ALL_IDS).dtype == np.dtype(np.int32)
assert all(saved(f, name)["dtype"] == "float64" for name in ("E", "U", "Bias", "Y", "Logits", "P"))
for tensor in f["tensors"]:
assert list(tensor) == ["id", "shape", "axes", "dtype", "values", "provenance", "precision"]
assert tensor["precision"] == (0 if tensor["dtype"] == "int32" else 8)
# These constructors require real float64 storage before JSON projection.
rejects(lambda: _float_tensor("bad", [1], ["D"], np.array([1], dtype=np.int32), "wrong dtype"), "SHAPE_MISMATCH")
rejects(lambda: _float_tensor("bad", [2], ["D"], np.array([1], dtype=np.float64), "wrong shape"), "SHAPE_MISMATCH")
alpha = 1 / math.sqrt(5)
r = math.exp((2 * alpha * alpha / math.sqrt(2)) * (1 + math.cos(1)))
d = (r - 1) / (r + 1)
delta0, delta1 = 0.5 + alpha, 0.5 + alpha * d
rho0, rho1 = delta0 / math.sqrt(delta0 * delta0 + 1), delta1 / math.sqrt(delta1 * delta1 + 1)
expected = [[1 + alpha + rho0, -alpha], [-alpha * d, 1 + alpha * d + rho1]]
for t in range(2):
for coordinate in range(2):
assert math.isclose(saved(f, "Y")["values"][t * 2 + coordinate], expected[t][coordinate], rel_tol=1e-12, abs_tol=1e-14)
attention_p, allowed = saved(f, "Attentionprobabilities"), saved(f, "Attentionallowed")
assert allowed["dtype"] == "bool" and allowed["precision"] == 8 and allowed["values"] == [True, False, True, True]
assert attention_p["values"][:2] == [1, 0]
assert math.isclose(attention_p["values"][2], 1 / (1 + r), rel_tol=1e-12)
assert math.isclose(attention_p["values"][3], r / (1 + r), rel_tol=1e-12)
# Earlier causal features survive a later ID edit; forbidden raw scores need not.
later = forward(s, [97, 97])
assert saved(f, "Y")["values"][:2] == saved(later, "Y")["values"][:2]
assert f["rows"][0] == later["rows"][0]
eos_input = forward({**s, "e20": 1, "e21": -1}, [512])
assert eos_input["inputIDs"] == [512] and eos_input["inputRows"] == [2]
assert saved(eos_input, "X")["values"] == [1, -1]
assert forward(s, [97])["rows"][0] == f["rows"][0]
assert forward(s, [512, 97])["inputRows"] == [2, 0]
for merges, text, ids in ((0, "ab", [97, 98, 512]), (1, "ab", [256, 512]),
(2, "abab", [257, 512]), (1, "ababab", [256, 256, 256, 512]),
(2, "ababab", [257, 256, 512])):
checked = tiny_state({**DEFAULT_IV43, "text": text, "merges": merges})
tokenized = _tokenize(checked["text"], checked["numeric"]["merges"], tiny_trace())
assert tokenized["ids"].tolist() == ids and tokenized["ids"].dtype == np.dtype(np.int32)
for ids, code in (([], "UNAVAILABLE"), ([97] * 4, "UNSUPPORTED_SIZE"), ([256], "INVALID_INPUT"),
([True], "INVALID_INPUT"), (["97"], "INVALID_INPUT"), ([None], "INVALID_INPUT"),
([768], "INVALID_INPUT"), ([97.5], "INVALID_INPUT"),
([float("nan")], "INVALID_INPUT"), ([float("inf")], "INVALID_INPUT"), ([10**1000], "INVALID_INPUT")):
rejects(lambda: forward(s, ids), code)
rejects(lambda: forward(s, np.array([True])), "INVALID_INPUT")
rejects(lambda: forward(s, np.array([[97]])), "INVALID_INPUT")
rejects(lambda: forward(s, {0: 97}), "INVALID_INPUT")
for field, value, code in (("e40", 3, "INVALID_INPUT"), ("u04", True, "NONFINITE"),
("b4", 10**1000, "NONFINITE"), ("merges", 0.5, "INVALID_INPUT")):
rejects(lambda: forward({**s, field: value}, [97]), code)
rejects(lambda: forward({**s, "b4": float("nan")}, []), "NONFINITE")
rejects(lambda: numeric_parameters({**s, "extra": 1}), "INVALID_INPUT")
rejects(lambda: numeric_parameters({key: value for key, value in s.items() if key != "u04"}), "INVALID_INPUT")
class GetterDict(dict):
def __getitem__(self, key):
raise AssertionError("Custom getter must not execute")
rejects(lambda: tiny_state(GetterDict(DEFAULT_IV43)), "INVALID_INPUT")
rejects(lambda: tiny_state({**DEFAULT_IV43, "text": [], "e40": float("nan")}), "INVALID_INPUT")
for patch, code in (({"text": "a" * 7}, "UNSUPPORTED_SIZE"), ({"text": "\ud800"}, "INVALID_INPUT"),
({"text": "🦊🦊"}, "UNSUPPORTED_SIZE"), ({"text": "ééé"}, "UNAVAILABLE"),
({"text": "c"}, "UNAVAILABLE"), ({"text": ""}, "UNAVAILABLE"),
({"text": "ababab"}, "UNSUPPORTED_SIZE")):
checked = tiny_state({**DEFAULT_IV43, **patch})
rejects(lambda: _tokenize(checked["text"], checked["numeric"]["merges"], tiny_trace()), code)
rejects(lambda: tiny_state({**DEFAULT_IV43, "text": "\ud800", "b4": float("nan")}), "NONFINITE")
# Public records and the explicit trace are detached from state and later calls.
f["rows"][0]["probabilities"][0] = 99
saved(f, "Y")["values"][0] = 99
f["tensors"][0]["values"][0] = 0
trace.steps[0]["outputs"].clear()
again = forward(s, [97, 98])
assert saved(again, "Y")["values"][0] != 99
assert again["rows"][0]["probabilities"][0] != 99
assert again["inputIDs"] == [97, 98]
assert s == dict(NUMERIC_DEFAULTS)
def derive43(state):
"""Compose the owner-adopted complete ordered numerical/text snapshot."""
checked = tiny_state(state)
text, numeric = checked["text"], checked["numeric"]
token_trace = tiny_trace()
tokenized = _tokenize(text, numeric["merges"], token_trace)
sequence = tokenized["ids"]
inputs, targets = sequence[:-1].copy(), sequence[1:].copy()
T, V = len(inputs), 3 + numeric["merges"]
trace = tiny_trace()
trace.add("setup", "Validate all raw fields before interpreting the text",
"text<=6 UTF-8 bytes; fixed corpus=abab; eos=1; inputs=sequence[:-1]; targets=sequence[1:]",
"The first encoded piece is given. Score each continuation through EOS; no first-piece probability, cropping or learning update.",
numeric, dict(utf16Units=_token.utf16_length(text), byteBound=6, eos=1, corpusUnits=4))
for step in token_trace.steps:
trace.add(step["id"], step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
class_ids = np.array(ALL_IDS[:V], dtype=np.int32)
token_summary = tokenized["summary"]
trace.add("class_map", "Map tokenizer IDs to active compact model classes", "V=3+actualMerges; classIDs=prefix([97,98,512,256,257],V)",
"Tokenizer vocabularyItems=257+merges differs from the model's 3+merges active classes; public IDs never allocate513 rows.",
dict(actualMerges=token_summary["actualMerges"], vocabularyItems=token_summary["vocabularyItems"]),
{"classCount": V, **{f"id{c}": int(identifier) for c, identifier in enumerate(class_ids)}})
forward = forward_tiny(numeric, inputs, trace)
objective = _objective(forward, targets, trace)
trace.add("finish", "Keep the objective and conditional readout derivatives together",
"objective=mean shifted NLL; derivatives=dLogits,dU,db with decoder features fixed",
"All parameters are hand-set and untrained. No optimizer, embedding/full-block gradient or language-learning claim.",
dict(contextLength=T, classCount=V),
dict(validCount=T, lossSum=objective["lossSum"], meanNLL=objective["meanNLL"], perplexity=objective["perplexity"]))
last = forward["rows"][-1]
summary = dict(validCount=T, lossSum=objective["lossSum"], meanNLL=objective["meanNLL"], perplexity=objective["perplexity"],
classCount=V, actualMerges=numeric["merges"], contextLength=T,
B=1, D=2, H=1, Dk=2, Dv=2, hiddenWidth=3, byteBound=6,
nextRow=last["nextRow"], nextID=last["nextID"], nextProbability=last["nextProbability"],
**{f"tokenizer_{key}": value for key, value in token_summary.items()})
tensors = [*tokenized["tensors"], *forward["tensors"],
_token.tensor("SequenceIDs", "Sequence", sequence, "Actual ranked BPE result with one final EOS; the first piece is given."),
*objective["tensors"]]
texts = dict(input=text, decoded=tokenized["texts"]["decoded"],
objective="Conditional continuation through EOS given the first encoded piece; no probability for that first piece.",
gradientScope="Analytic readout U/bias derivatives with decoder features fixed; no embedding/full-block gradient, optimizer update or training.",
modelVocabulary=["0: a / ID97", "1: b / ID98", "2: EOS / ID512", "3: ab / ID256", "4: abab / ID257"],
**{f"tokenizer_{key}": value for key, value in tokenized["texts"].items()})
result = trace.result(summary, tensors)
result["texts"] = texts
# Python exposes ordinary detached JSON; TS additionally freezes its snapshot.
return json.loads(json.dumps(result, allow_nan=False, ensure_ascii=False))
if __name__ == "__main__":
run(guarded(derive43), DEFAULT_IV43)
Tokenizer composition — code/python/p09/iv39.py. derive_iv39 learns from the fixed corpus and applies the learned rules to the prompt, retaining actual tokenizer evidence. Prompt tokenization runs once with automatic EOS insertion off. A later ID append is not a request to tokenize the reconstructed characters again.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""IV-39 — Byte-Pair Encoding: A Full Merge Trace.
Train adjacent byte-ID pairs on a separate, literal training corpus. Count
ALL adjacent occurrences, including overlaps, choose the greatest count,
then the lexicographically smallest NUMERIC (left ID, right ID) on ties.
Replace matches left to right without overlap. Recount after every rule.
Encode the target with the learned rules in increasing rank, not by taking
the longest dictionary prefix. Only the target can receive explicit EOS512.
Hand default: corpus abab starts [97,98,97,98]. Counts ab2,ba1 select ab256,
so [256,256] becomes rule257=[97,98,97,98]. Target ababab becomes
[256,256,256] then [257,256]; expanding BOTH IDs reconstructs six bytes.
Corpus aaaa has three adjacent aa occurrences but only two replacements.
Corpus bbaa encounters bb,ba,aa once each; numeric order chooses the LAST
encountered aa=(97,97), producing [98,98,256], not insertion-order bb.
Corpus 'bc bc ab' learns bc256,bc-space257,ab258. In its third round
(97,98) beats pairs starting257 numerically, not by decimal string keys.
Target abc becomes [97,256]; greedy longest-prefix ab258 would differ.
All source is authored without imports, execution, fixtures generation or
runtime validation. Keep bpe_reference.py AND token_reference.py beside this
wrapper. File-relative loading supports an arbitrary caller working directory.
"""
import importlib.util
from pathlib import Path
_bpe_spec = importlib.util.spec_from_file_location(
"_p09_bpe_reference", Path(__file__).resolve().with_name("bpe_reference.py"))
_bpe = importlib.util.module_from_spec(_bpe_spec)
_bpe_spec.loader.exec_module(_bpe)
DEFAULT_IV39 = _bpe.DEFAULT_IV39
@_bpe._token.guarded
def derive_iv39(state):
"""Train a real corpus, encode a separate target, and decode both actual IDs."""
token = _bpe._token
s = _bpe.bpe_state(state)
encoding_trace = token.TokenTrace()
corpus = _bpe.encode_bounded(s["corpus"], "corpus", "corpus", encoding_trace)
source = _bpe.encode_bounded(s["text"], "text", "source", encoding_trace)
trace = token.TokenTrace()
corpus_units, units = token.utf16_length(s["corpus"]), token.utf16_length(s["text"])
trace.add("setup", "Declare learned byte-pair encoding and both exact inputs",
"byte IDs=0..255; learned ID=256+rank; EOS=512; each text field<=24 UTF-8 bytes",
"Validate every raw field before corpus then target Unicode semantics. Train on the corpus byte stream including spaces; encode the separate target using learned ranks. No normalization, word splitting, inferred EOS or pretrained vocabulary is used.",
dict(requestedMerges=s["merges"], eos=s["eos"]),
dict(corpusUnits=corpus_units, corpusScalars=len(corpus["codePoints"]), utf16Units=units,
scalarCount=len(source["codePoints"]), byteBound=_bpe.BYTE_BOUND,
mergeBase=_bpe.MERGE_BASE, mergeBound=_bpe.MERGE_BOUND, EOS=_bpe.EOS))
# Scalar records were prepared during validation; keep their actual order.
trace.steps.extend(encoding_trace.steps)
tensors = []
for stem, encoded in (("Corpus", corpus), ("Source", source)):
for suffix, key, axis, provenance in (
("CodePoints", "codePoints", "Scalars", "Validated Unicode scalars in exact input order."),
("UTF16Offsets", "offsets", "Scalars", "Zero-based UTF-16 storage offset for each scalar."),
("UTF16Widths", "widths", "Scalars", "UTF-16 storage units consumed by each scalar."),
("ByteOffsets", "byteOffsets", "Scalars", "Zero-based UTF-8 byte offset for each scalar."),
("ByteWidths", "byteWidths", "Scalars", "Actual UTF-8 bytes emitted by each scalar."),
("Bytes", "bytes", "Bytes", "Manual UTF-8 encoding in source order, preserving all data."),
):
_bpe.save_tensor(tensors, f"{stem}{suffix}", axis, encoded[key], provenance)
trained = _bpe.train_bpe(corpus["bytes"], s["merges"], trace, tensors)
ids = _bpe.encode_bpe(source["bytes"], trained["rules"], s["eos"], trace, tensors)
# Corpus is NEVER EOS-trained. Both inverse paths expand real saved IDs.
corpus_decoded = _bpe.decode_bpe_ids(trained["ids"], trained["rules"], 0, "corpus", trace)
target_decoded = _bpe.decode_bpe_ids(ids, trained["rules"], s["eos"], "target", trace)
corpus_equal = int(corpus_decoded["decoded"] == s["corpus"])
equal = int(target_decoded["decoded"] == s["text"])
if not (corpus_equal and equal):
raise _bpe.NumericalFault("INVALID_INPUT", "Actual BPE reconstructions did not equal both original strings.")
trace.add("roundtrip", "Compare both actual strict reconstructions with the original strings",
"corpusEqual=(corpusDecoded===corpus); equal=(targetDecoded===text)",
"Expand real corpus and target IDs separately, concatenate real bytes, strictly reconstruct Unicode scalars, and only then compare strings. Empty content reconstructs the empty string; optional target EOS emits no bytes.",
dict(corpusOriginalUnits=corpus_units, corpusDecodedUnits=token.utf16_length(corpus_decoded["decoded"]),
corpusDecodedByteCount=len(corpus_decoded["bytes"]), originalUnits=units,
decodedUnits=token.utf16_length(target_decoded["decoded"]), decodedByteCount=len(target_decoded["bytes"])),
dict(corpusTokens=len(trained["ids"]), tokenCount=len(ids), corpusEqual=corpus_equal, equal=equal))
_bpe.save_tensor(tensors, "CorpusDecodedBytes", "Bytes", corpus_decoded["bytes"],
"Actual final corpus ID expansions passed to strict UTF-8 decoding.")
_bpe.save_tensor(tensors, "TargetDecodedBytes", "Bytes", target_decoded["bytes"],
"Actual final target ID expansions passed to strict UTF-8 decoding.")
expansions = {rule["id"]: rule["bytes"].tolist() for rule in trained["rules"]}
def expansion(identifier):
return [] if identifier == _bpe.EOS else [identifier] if identifier <= 255 else expansions[identifier]
def labels(token_ids):
return ["ID 512: EOS (explicit control), bytes []" if int(identifier) == _bpe.EOS else
f"ID {int(identifier)}, bytes {token.json_text(expansion(int(identifier)))}" for identifier in token_ids]
def expansion_labels(token_ids):
return [token.json_text(expansion(int(identifier))) for identifier in token_ids]
summary = dict(corpusBytes=len(corpus["bytes"]), byteCount=len(source["bytes"]),
actualMerges=len(trained["rules"]), tokenCount=len(ids), requestedMerges=s["merges"],
corpusTokens=len(trained["ids"]), eos=s["eos"], byteBound=_bpe.BYTE_BOUND,
vocabularyItems=256 + len(trained["rules"]) + 1, corpusEqual=corpus_equal, equal=equal)
texts = dict(corpus=s["corpus"], input=s["text"], corpusDecoded=corpus_decoded["decoded"],
decoded=target_decoded["decoded"], corpusLabels=labels(trained["ids"]),
corpusExpansions=expansion_labels(trained["ids"]), targetLabels=labels(ids),
targetExpansions=expansion_labels(ids),
ruleLabels=[f"ID {rule['id']}, bytes {token.json_text(rule['bytes'].tolist())}" for rule in trained["rules"]],
ruleExpansions=[token.json_text(rule["bytes"].tolist()) for rule in trained["rules"]],
trainingStop="Zero merges requested: no training round or pair selection occurs." if s["merges"] == 0 else
"Stopped early: fewer than two current training tokens remain." if len(trained["rules"]) < s["merges"] else
"Requested merge budget completed.")
return trace.result(summary, tensors, texts)
def source_self_check():
"""Deferred hand-literal record checks; never part of the normal CLI path."""
assert __debug__, "Run later checks with assertions enabled."
_bpe.source_self_check()
result = derive_iv39(dict(DEFAULT_IV39))
assert list(result) == ["status", "outputs", "steps", "tensors", "texts"]
assert list(result["outputs"])[:11] == ["corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges", "corpusTokens", "eos", "byteBound", "vocabularyItems", "corpusEqual", "equal"]
assert [result["outputs"][key] for key in ("corpusBytes", "byteCount", "actualMerges", "tokenCount")] == [4, 6, 2, 2]
assert len(result["steps"]) == 44 and len(result["tensors"]) == 37
assert result["texts"]["corpusDecoded"] == "abab" and result["texts"]["decoded"] == "ababab"
assert result["texts"]["targetLabels"] == ["ID 257, bytes [97,98,97,98]", "ID 256, bytes [97,98]"]
# Tensor count:12source+1initial+10round+1corpus+3rules+2expansions+
# 1targetinitial+4targetpasses+1targetfinal+2decoded=37. No program counted it.
tensor_ids = [record["id"] for record in result["tensors"]]
for merges, eos, steps in ((2, 1, 46), (3, 0, 45), (3, 1, 47), (4, 0, 45), (4, 1, 47)):
case = derive_iv39(dict(corpus="abab", text="ababab", merges=merges, eos=eos))
assert len(case["steps"]) == steps
assert [record["id"] for record in case["tensors"]] == tensor_ids
for eos in (0, 1):
empty = derive_iv39(dict(corpus="", text="", merges=0, eos=eos))
assert empty["outputs"]["tokenCount"] == eos
assert len(empty["steps"]) == 2 + 2 * eos
assert empty["texts"]["decoded"] == empty["texts"]["corpusDecoded"] == ""
for patch, code in (
(dict(corpus="\ud800", merges=float("nan")), "NONFINITE"),
(dict(corpus="a" * 25, text="\ud800"), "UNSUPPORTED_SIZE"),
(dict(corpus="\ud800", text="a" * 25), "INVALID_INPUT"),
(dict(text="🦊" * 7), "UNSUPPORTED_SIZE"),
(dict(text="🦊" * 9), "UNSUPPORTED_SIZE"),
):
bad = derive_iv39({**DEFAULT_IV39, **patch})
assert list(bad) == ["status", "code", "reason"] and bad["code"] == code
if __name__ == "__main__":
# No args: defaults; one complete JSON state: replacement; '-': stdin JSON.
_bpe._token.run(derive_iv39, DEFAULT_IV39)
Learned rules and reverse expansion — code/python/p09/bpe_reference.py. train_bpe counts pairs and selects replacements using the declared tie order. encode_bpe applies ranked rules. decode_bpe_ids expands the actual supplied IDs with those rules and the explicit EOS policy. Distinct module instances can load this same source; the raw disclosure is by unique source file.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""IV-39: complete learned byte-pair encoding, authored without execution.
NumPy int32 arrays hold actual bytes, code points, offsets, IDs and rule
expansions. Python integers do scalar comparisons, counts and index arithmetic.
The unchanged token_reference.py supplies the manual UTF-8 codec and record
storage. No native codec supplies a production answer. A byte piece need not
be valid Unicode alone: concatenate all expansions before strict decoding.
"""
import importlib.util
from pathlib import Path
from types import MappingProxyType
import numpy as np
# File-relative loading works even when the caller has an unrelated cwd.
_token_spec = importlib.util.spec_from_file_location(
"_p09_bpe_token_reference", Path(__file__).resolve().with_name("token_reference.py"))
_token = importlib.util.module_from_spec(_token_spec)
_token_spec.loader.exec_module(_token)
NumericalFault = _token.NumericalFault
BPE_BYTE_BOUND = 24
BYTE_BOUND = BPE_BYTE_BOUND
MERGE_BASE = 256
MERGE_BOUND = 4
EOS = 512
DEFAULT_IV39 = MappingProxyType(dict(corpus="abab", text="ababab", merges=2, eos=0))
def data_object(value, fields, label):
"""Exact built-in mappings have own data entries, never property getters."""
if type(value) not in (dict, MappingProxyType):
raise NumericalFault("INVALID_INPUT", f"{label} must be a plain object.")
if any(type(key) is not str for key in value) or set(value) != set(fields):
raise NumericalFault("INVALID_INPUT", f"{label} must have exactly {', '.join(fields)} as own fields.")
def dense_data(values, limit, label, numeric=True):
"""Reject custom indexing BEFORE reading entries; never narrow invalid data."""
if type(values) is np.ndarray and numeric:
if values.ndim != 1 or values.dtype.kind not in "iuf":
raise NumericalFault("INVALID_INPUT", f"{label} must be a dense one-dimensional numeric array.")
elif type(values) not in (list, tuple):
raise NumericalFault("INVALID_INPUT", f"{label} must be an actual array.")
if len(values) > limit:
raise NumericalFault("UNSUPPORTED_SIZE", f"{label} exceeds {limit} entries.")
def budget(merges):
if type(merges) not in (int, float):
raise NumericalFault("NONFINITE", "merges must be an actual finite number.")
# The reused integer validator catches finiteness OverflowError on huge ints.
return _token.integer(merges, 0, MERGE_BOUND, "merges")
def eos_flag(eos):
_token._flag(eos)
return int(eos)
def bpe_state(state):
"""ALL raw strings/numbers precede corpus, then target Unicode semantics."""
data_object(state, DEFAULT_IV39, "state")
for key in ("corpus", "text"):
if type(state[key]) is not str:
raise NumericalFault("INVALID_INPUT", f"{key} must be an actual string, without coercion.")
merges = budget(state["merges"])
if type(state["eos"]) not in (int, float):
raise NumericalFault("NONFINITE", "eos must be an actual finite number.")
# Check finite before the flag domain, preserving NONFINITE error precedence.
eos = _token.integer(state["eos"], 0, 1, "eos")
return dict(corpus=state["corpus"], text=state["text"], merges=merges, eos=eos)
def encode_bounded(text, field, prefix, trace):
"""Early UTF-16 bound, all surrogate checks, then actual UTF-8 byte bound."""
if type(text) is not str:
raise NumericalFault("INVALID_INPUT", f"{field} must be an actual string, without coercion.")
if _token.utf16_length(text) > BYTE_BOUND:
raise NumericalFault("UNSUPPORTED_SIZE", f"{field}: more than 24 UTF-16 units necessarily exceeds this 24-byte field.")
reason = f"{field}: the actual UTF-8 encoding exceeds 24 bytes; shorten this field explicitly."
try:
encoded = _token.utf8_encode(text, prefix, trace)
except NumericalFault as error:
# Nine foxes hit the inherited32-byte bound before this24-byte postcheck.
if error.code == "UNSUPPORTED_SIZE":
raise NumericalFault("UNSUPPORTED_SIZE", reason) from error
raise
if len(encoded["bytes"]) > BYTE_BOUND:
raise NumericalFault("UNSUPPORTED_SIZE", reason)
return encoded
def bytes_input(values):
dense_data(values, BYTE_BOUND, "BPE bytes")
return _token.int_array(values, high=255, label="BPE bytes", limit=BYTE_BOUND)
def rule_table(rules):
"""Validate a lossless, acyclic rule namespace before expanding caller IDs."""
dense_data(rules, MERGE_BOUND, "BPE rules", numeric=False)
# Inspect every object/container first; no arbitrary mapping/index getter runs.
for rule in rules:
data_object(rule, ("id", "left", "right", "bytes"), "rule")
dense_data(rule["bytes"], BYTE_BOUND, "Rule bytes")
expansions, pairs = {}, set()
for rank, rule in enumerate(rules):
expected_id = MERGE_BASE + rank
identifier = int(_token.int_array([rule["id"]], high=259, label="Rule ID")[0])
if identifier != expected_id:
raise NumericalFault("INVALID_INPUT", f"Rule {rank} must have ID {expected_id}.")
operands = _token.int_array([rule["left"], rule["right"]], high=expected_id - 1, label="Rule operands")
left, right = int(operands[0]), int(operands[1])
# IDs between255 and this ID must already be present, never forward/cyclic.
if any(operand > 255 and operand not in expansions for operand in (left, right)):
raise NumericalFault("INVALID_INPUT", "Each rule operand must be a byte ID or an earlier merge ID.")
if (left, right) in pairs:
raise NumericalFault("INVALID_INPUT", "Duplicate BPE rule pairs are not allowed.")
pairs.add((left, right))
stored = _token.int_array(rule["bytes"], high=255, label="Rule bytes", limit=BYTE_BOUND)
left_bytes = np.array([left], dtype=np.int32) if left <= 255 else expansions[left]
right_bytes = np.array([right], dtype=np.int32) if right <= 255 else expansions[right]
expected = np.concatenate((left_bytes, right_bytes))
if len(expected) > BYTE_BOUND:
raise NumericalFault("UNSUPPORTED_SIZE", "A rule expansion exceeds 24 bytes.")
if len(expected) != len(stored) or any(int(a) != int(b) for a, b in zip(expected, stored)):
raise NumericalFault("INVALID_INPUT", "Rule bytes must equal the left expansion followed by the right expansion.")
expansions[identifier] = expected
return expansions
def save_tensor(tensors, identifier, axis, values, provenance):
"""Keep actual int32 storage; an empty stream has no fabricated tensor."""
if len(values):
tensors.append(_token.tensor(identifier, axis, values, provenance))
def replace_pass(ids, rule, rank, stage, trace, tensors):
"""Count positions in CURRENT input tokens, not original UTF-8 bytes."""
stem = f"{'Train' if stage == 'train' else 'Encode'}R{rank}"
save_tensor(tensors, f"{stem}Before", "Tokens", ids,
"Complete current token list before this nonoverlapping left-to-right pass.")
result, position = [], 0
while position < len(ids):
current_id = int(ids[position])
next_id = int(ids[position + 1]) if position + 1 < len(ids) else -1
matched = int(current_id == rule["left"] and next_id == rule["right"])
consumed = 2 if matched else 1
identifier = rule["id"] if matched else current_id
next_position = position + consumed
inputs = dict(rank=rank, position=position, inputLength=len(ids), left=rule["left"],
right=rule["right"], newID=rule["id"], currentID=current_id,
nextID=next_id, outputLength=len(result))
result.append(identifier)
trace.add(f"{stage}_replace_{rank}_{position}", f"{stage}: rank {rank}, current-token position {position}",
"matched=(currentID=left and nextID=right); emit matched?newID:currentID; consumed=matched?2:1; nextPosition=position+consumed",
"Positions index the current token list, not original bytes. A match consumes two tokens and emits one; a nonmatch copies one token. Advancing past both matched operands prevents overlapping replacements. The complete pass snapshots and position/consumed/nextPosition retain every scan; nextID -1 means no next token, never a token or padding item.",
inputs, dict(matched=matched, id=identifier, consumed=consumed,
nextPosition=next_position, outputLength=len(result)))
position = next_position
values = np.array(result, dtype=np.int32)
save_tensor(tensors, f"{stem}After", "Tokens", values,
"Complete actual output token list after this rank; no padding or truncation.")
return values
def train_bpe(values, merges, trace, tensors):
"""Count overlaps, select numeric ties, concatenate bytes, replace disjointly."""
merges = budget(merges)
ids = bytes_input(values).copy()
rules, expansions = [], {}
save_tensor(tensors, "TrainInitialIDs", "Tokens", ids,
"Initial training byte IDs, one ID for each actual corpus byte.")
for rank in range(merges):
if len(ids) < 2:
trace.add("train_stop", "Stop: fewer than two training tokens remain", "length<2 means no adjacent pair exists",
"This is one real early stop, not a fabricated merge. A zero requested budget does not enter training at all.",
dict(rank=rank, length=len(ids), requestedMerges=merges), dict(actualMerges=len(rules)))
break
counts = {}
# Advance by ONE here: unlike replacement, counting includes overlaps.
for position in range(len(ids) - 1):
left, right = int(ids[position]), int(ids[position + 1])
count_before = counts.get((left, right), 0)
counts[(left, right)] = count_before + 1
trace.add(f"train_count_{rank}_{position}", f"Count round {rank} pair at current-token position {position}",
"frequency(left,right)=previous frequency+1; next counting position=position+1",
"Count every adjacent occurrence, including overlaps. The table starts empty each round. In aaaa, aa occurs at positions 0, 1 and 2 even though replacement will consume only two disjoint pairs.",
dict(rank=rank, position=position, left=left, right=right, countBefore=count_before),
dict(countAfter=counts[(left, right)], distinctPairs=len(counts)))
# Sort NUMERIC tuples, never string keys or insertion order (bbaa anchor).
candidates = sorted(counts)
for suffix, entries, provenance in (
("Left", [pair[0] for pair in candidates], "Numeric tuple order: left ID, then right ID; aligned candidate columns."),
("Right", [pair[1] for pair in candidates], "Right ID in the same sorted candidate order."),
("Frequency", [counts[pair] for pair in candidates], "Actual adjacent-pair frequency, including overlapping occurrences."),
):
save_tensor(tensors, f"TrainR{rank}Candidate{suffix}", "Candidates",
np.array(entries, dtype=np.int32), provenance)
best = None
best_frequency = 0
for candidate_index, (left, right) in enumerate(candidates):
frequency = counts[(left, right)]
best_left, best_right = best if best is not None else (-1, -1)
inputs = dict(candidateIndex=candidate_index, left=left, right=right, frequency=frequency,
bestLeft=best_left, bestRight=best_right, bestFrequency=best_frequency)
frequency_greater = int(frequency > best_frequency)
frequency_equal = int(frequency == best_frequency)
lex_smaller = int(best is not None and (left, right) < best)
take = int(best is None or frequency_greater or (frequency_equal and lex_smaller))
if take:
best, best_frequency = (left, right), frequency
trace.add(f"train_compare_{rank}_{candidate_index}", f"Compare round {rank} candidate {candidate_index}",
"take=first candidate or greater frequency or (equal frequency and numerically smaller (left,right))",
"Compare integer IDs, left first and then right, not string keys or encounter order. Candidate columns use numeric tuple order. The first comparison uses best IDs -1 and frequency 0 as an explicit empty-best sentinel.",
inputs, dict(take=take, frequencyGreater=frequency_greater, frequencyEqual=frequency_equal,
lexSmaller=lex_smaller, bestLeft=best[0], bestRight=best[1], bestFrequency=best_frequency))
left, right = best
identifier = MERGE_BASE + rank
trace.add(f"train_select_{rank}", f"Select round {rank} winning pair",
"newID=256+rank; select greatest frequency, then smallest numeric pair",
"Frequency 1 is eligible. Requested merges are a budget; actual merges stop early only when no adjacent pair remains.",
dict(rank=rank, currentLength=len(ids), candidateCount=len(candidates)),
dict(id=identifier, left=left, right=right, frequency=best_frequency))
left_bytes = np.array([left], dtype=np.int32) if left <= 255 else expansions[left]
right_bytes = np.array([right], dtype=np.int32) if right <= 255 else expansions[right]
expansion = np.concatenate((left_bytes, right_bytes))
rule = dict(id=identifier, left=left, right=right, bytes=expansion)
inputs = dict(id=identifier, left=left, right=right, leftWidth=len(left_bytes), rightWidth=len(right_bytes))
inputs.update({f"leftByte{i}": int(byte) for i, byte in enumerate(left_bytes)})
inputs.update({f"rightByte{i}": int(byte) for i, byte in enumerate(right_bytes)})
outputs = dict(byteWidth=len(expansion))
outputs.update({f"byte{i}": int(byte) for i, byte in enumerate(expansion)})
trace.add(f"train_rule_{rank}", f"Build rule {rank} byte expansion", "new bytes=left bytes followed by right bytes",
"Both operands are bytes or earlier merge IDs. Their complete concatenation defines the new ID and cannot create a cycle. A piece may end inside a UTF-8 scalar, so its label uses ID and exact JSON bytes.",
inputs, outputs)
rules.append(rule)
expansions[identifier] = expansion.copy()
ids = replace_pass(ids, rule, rank, "train", trace, tensors)
save_tensor(tensors, "CorpusIDs", "Tokens", ids,
"Final learned corpus token IDs; corpus training never contains EOS.")
for identifier, key, provenance in (
("RuleIDs", "id", "Learned IDs in ascending rank, ID=256+rank."),
("RuleLeft", "left", "Left operand ID for each learned rank."),
("RuleRight", "right", "Right operand ID for each learned rank."),
):
save_tensor(tensors, identifier, "Rules", np.array([rule[key] for rule in rules], dtype=np.int32), provenance)
for rule in rules:
save_tensor(tensors, f"Rule{rule['id']}Bytes", "Bytes", rule["bytes"],
"Actual concatenated operand bytes; the piece alone need not be valid UTF-8.")
return dict(ids=ids, rules=rules)
def encode_bpe(values, rules, eos, trace, tensors):
"""Apply each learned rank once; only then append optional target EOS512.
A later rule emits a higher ID and leaves a replacement token between any
untouched neighbors, so it cannot create an earlier rule's lower-ID pair.
"""
rule_table(rules)
eos = eos_flag(eos)
ids = bytes_input(values).copy()
save_tensor(tensors, "EncodeInitialIDs", "Tokens", ids,
"Initial target byte IDs before any ranked application.")
for rank, rule in enumerate(rules):
# Public rule fields may be integral floats; scalar trace fields are ints.
actual = dict(id=int(rule["id"]), left=int(rule["left"]), right=int(rule["right"]))
ids = replace_pass(ids, actual, rank, "encode", trace, tensors)
ids = _token.append_eos(ids, eos, "target", trace)
save_tensor(tensors, "TargetIDs", "Tokens", ids,
"Final target token IDs after all learned ranks, then optional unique EOS tail.")
return ids
def decode_bpe_ids(values, rules, eos, prefix, trace):
"""Expand the ACTUAL validated IDs, then strictly reconstruct Unicode."""
expansions = rule_table(rules)
eos = eos_flag(eos)
dense_data(values, BYTE_BOUND + 1, "BPE token IDs")
ids = _token.int_array(values, high=EOS, label="BPE token IDs", limit=BYTE_BOUND + 1)
has_tail = len(ids) > 0 and int(ids[-1]) == EOS
content = ids[:-1] if has_tail else ids
if has_tail != (eos == 1) or any(int(value) == EOS for value in content):
raise NumericalFault("INVALID_INPUT", "EOS must occur exactly once at the tail when eos=1, and nowhere when eos=0.")
for stored in content:
identifier = int(stored)
if identifier > 255 and identifier not in expansions:
raise NumericalFault("INVALID_INPUT", f"Unknown or inactive BPE ID {identifier}.")
byte_values = []
for index, stored in enumerate(content):
identifier = int(stored)
expansion = [identifier] if identifier <= 255 else expansions[identifier].tolist()
byte_offset = len(byte_values)
byte_values.extend(expansion)
if len(byte_values) > BYTE_BOUND:
raise NumericalFault("UNSUPPORTED_SIZE", "Decoded BPE expansions exceed 24 bytes.")
outputs = dict(byteOffset=byte_offset, byteWidth=len(expansion))
outputs.update({f"byte{i}": byte for i, byte in enumerate(expansion)})
trace.add(f"{prefix}_expand_{index}", f"{prefix}: expand ID at token {index}", "ID → validated byte expansion",
"Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.",
dict(index=index, id=identifier), outputs)
if eos == 1:
trace.add(f"{prefix}_strip_eos", f"{prefix}: strip explicit tail EOS", "EOS emits no text bytes",
"The decoder has validated the unique required tail marker. Its empty expansion is a control convention, not a lost source character.",
dict(index=len(ids) - 1, id=EOS), dict(stripped=1))
actual_bytes = np.array(byte_values, dtype=np.int32)
return dict(bytes=actual_bytes, decoded=_token.utf8_decode(actual_bytes, prefix, trace))
def source_self_check():
"""Hand-derived deferred assertions: NEVER called by import or normal CLI.
The human resource hold forbids invoking this function now. These are
source checks for later owner validation, not generated expected answers.
"""
assert __debug__, "Run later checks with assertions enabled."
def rejects(call, code="INVALID_INPUT"):
try:
call()
except NumericalFault as error:
assert error.code == code, (error.code, code)
return error
raise AssertionError("Invalid boundary was accepted")
def train(values, merges):
trace, tensors = _token.TokenTrace(), []
result = train_bpe(values, merges, trace, tensors)
return result, trace, tensors
# Default: abab -> ab/ab -> abab; target ababab -> abab/ab.
trained, trace, tensors = train([97, 98, 97, 98], 2)
assert trained["ids"].tolist() == [257]
assert [(rule["id"], rule["left"], rule["right"]) for rule in trained["rules"]] == [(256, 97, 98), (257, 256, 256)]
assert [rule["bytes"].tolist() for rule in trained["rules"]] == [[97, 98], [97, 98, 97, 98]]
ids = encode_bpe([97, 98, 97, 98, 97, 98], trained["rules"], 1, trace, tensors)
assert ids.tolist() == [257, 256, 512]
assert decode_bpe_ids(trained["ids"], trained["rules"], 0, "corpus", trace)["decoded"] == "abab"
assert decode_bpe_ids(ids, trained["rules"], 1, "target", trace)["decoded"] == "ababab"
assert ids.dtype == np.dtype(np.int32) and trained["ids"].dtype == np.dtype(np.int32)
assert all(rule["bytes"].dtype == np.dtype(np.int32) for rule in trained["rules"])
assert all(record["dtype"] == "int32" and record["precision"] == 0 for record in tensors)
concat = next(step for step in trace.steps if step["id"] == "train_rule_1")
assert list(concat["inputs"]) == ["id", "left", "right", "leftWidth", "rightWidth", "leftByte0", "leftByte1", "rightByte0", "rightByte1"]
tail = next(step for step in trace.steps if step["id"] == "encode_replace_1_2")
assert tail["inputs"]["nextID"] == -1
assert tail["outputs"] == dict(matched=0, id=256, consumed=1, nextPosition=3, outputLength=2)
# Count overlaps3, replace disjointly2; every emitted token remains lossless.
overlap, overlap_trace, _ = train([97, 97, 97, 97], 1)
assert overlap["ids"].tolist() == [256, 256]
assert next(step for step in overlap_trace.steps if step["id"] == "train_count_0_2")["outputs"]["countAfter"] == 3
assert len([step for step in overlap_trace.steps if step["id"].startswith("train_replace_")]) == 2
last_tie, _, _ = train([98, 98, 97, 97], 1)
assert (last_tie["rules"][0]["left"], last_tie["rules"][0]["right"]) == (97, 97)
assert last_tie["ids"].tolist() == [98, 98, 256]
# Numeric97 precedes257; rank application differs from greedy prefix ab.
ranked, rank_trace, rank_tensors = train([98, 99, 32, 98, 99, 32, 97, 98], 3)
assert [(rule["left"], rule["right"]) for rule in ranked["rules"]] == [(98, 99), (256, 32), (97, 98)]
assert ranked["ids"].tolist() == [257, 257, 258]
assert encode_bpe([97, 98, 99], ranked["rules"], 0, rank_trace, rank_tensors).tolist() == [97, 256]
empty, empty_trace, empty_tensors = train([], 4)
assert not empty["rules"] and empty["ids"].tolist() == []
assert [step["id"] for step in empty_trace.steps] == ["train_stop"] and empty_tensors == []
_, zero_trace, _ = train([97, 98], 0)
assert zero_trace.steps == []
assert encode_bpe([], [], 1, _token.TokenTrace(), []).tolist() == [512]
# Malformed IDs/EOS/rules fail before any guessed/replacement decoding.
for values, eos in (([], 1), ([512], 0), ([512, 65], 1), ([65, 512, 512], 1), ([256], 0), ([384], 0), ([1024], 0), ([True], 0), ([10**1000], 0)):
rejects(lambda: decode_bpe_ids(values, [], eos, "target", _token.TokenTrace()))
rejects(lambda: decode_bpe_ids([65] * 25, [], 0, "target", _token.TokenTrace()), "UNSUPPORTED_SIZE")
for values in ([195], [192, 128], [237, 160, 128], [244, 144, 128, 128]):
rejects(lambda: decode_bpe_ids(values, [], 0, "target", _token.TokenTrace()))
assert decode_bpe_ids([239, 187, 191, 0], [], 0, "target", _token.TokenTrace())["decoded"] == "\ufeff\0"
for bad in (
[dict(id=257, left=97, right=98, bytes=[97, 98])],
[dict(id=256, left=256, right=98, bytes=[97, 98])],
[dict(id=256, left=97, right=98, bytes=[98, 97])],
[dict(id=256, left=97, right=98, bytes=[97, 98]), dict(id=257, left=97, right=98, bytes=[97, 98])],
):
rejects(lambda: rule_table(bad))
# Both 7fox/28byte postcheck and 9fox/36byte inherited32 rejection say24.
for text in ("🦊" * 7, "🦊" * 9):
error = rejects(lambda: encode_bounded(text, "corpus", "corpus", _token.TokenTrace()), "UNSUPPORTED_SIZE")
assert "24" in str(error) and "32" not in str(error)
rejects(lambda: encode_bounded("🦊" * 7 + "\ud800", "corpus", "corpus", _token.TokenTrace()))
rejects(lambda: bpe_state(dict(corpus=None, text="", merges=0, eos=float("nan"))))
rejects(lambda: bpe_state(dict(corpus="\ud800", text="", merges=float("nan"), eos=0)), "NONFINITE")
rejects(lambda: bpe_state(dict(corpus="", text="", merges=10**1000, eos=0)), "NONFINITE")
rejects(lambda: bpe_state(dict(corpus="", text="", merges=0, eos=10**1000)), "NONFINITE")
rejects(lambda: bpe_state(dict(corpus="", text="", merges=True, eos=0)), "NONFINITE")
rejects(lambda: bpe_state(dict(corpus="", text="", merges=0, eos=0, extra=0)))
rejects(lambda: bpe_state(dict(corpus="", text="", merges=0)))
class AccessorState:
@property
def corpus(self):
raise AssertionError("Getter must never run")
class AccessorList(list):
def __getitem__(self, index):
raise AssertionError("Custom indexing must never run")
rejects(lambda: bpe_state(AccessorState()))
rejects(lambda: decode_bpe_ids(AccessorList([65]), [], 0, "target", _token.TokenTrace()))
rejects(lambda: rule_table([dict(id=256, left=97, right=98, bytes=AccessorList([97, 98]))]))
Strict text codec — code/python/p09/token_reference.py. utf16_length, utf8_encode and utf8_decode distinguish code units, Unicode scalar values and bytes. A scalar value is a Unicode character number excluding the surrogate range. Invalid surrogates do not silently become replacement characters. Integer token evidence remains separate from floating neural features.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""Part IX: bounded integer tokenization, authored without execution.
NumPy int32 arrays store actual code points, offsets, bytes and IDs. Arithmetic
uses Python integers, so bit shifts never depend on NumPy scalar promotion.
UTF-8 is implemented below; no native codec supplies an encoded/decoded answer.
Empty streams, BOMs, noncharacters, spaces and NULs are ordinary valid data.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np
EOS = 512
BYTE_BOUND = 32
CHARACTER_BASE = 1024
IV37_DEFAULTS = MappingProxyType(dict(text="Aé🦊", eos=0))
IV38_DEFAULTS = MappingProxyType(dict(text="lower low", vocabLimit=8, eos=0))
# Fixed active-prefix dictionary: these pieces are authored, not trained.
SUBWORDS = (
(384, "low", (108, 111, 119)),
(385, "lower", (108, 111, 119, 101, 114)),
(386, "lowest", (108, 111, 119, 101, 115, 116)),
(387, "er", (101, 114)),
(388, "est", (101, 115, 116)),
(389, "ing", (105, 110, 103)),
(390, "a", (97,)),
(391, "ab", (97, 98)),
)
class NumericalFault(ValueError):
def __init__(self, code, reason):
super().__init__(reason)
self.code = code
def guarded(derive):
@wraps(derive)
def call(state):
try:
return derive(state)
except NumericalFault as error:
return dict(status="unavailable", code=error.code, reason=str(error))
return call
def integer(value, low, high, label):
"""Validate before conversion; Python bool is not a mathematical number here."""
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
try:
finite = math.isfinite(value)
except OverflowError:
finite = False
if not finite:
raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
if value < low or value > high or int(value) != value:
raise NumericalFault("INVALID_INPUT", f"{label} must be an integer from {low} to {high}.")
return int(value)
def scalar_valid(cp):
return 0 <= cp <= 0x10FFFF and not 0xD800 <= cp <= 0xDFFF
def utf16_units(cp):
"""Reconstruct the actual high/low units from a validated supplementary scalar."""
if cp <= 0xFFFF:
return [cp]
return [0xD800 + ((cp - 0x10000) >> 10), 0xDC00 + ((cp - 0x10000) & 1023)]
def utf16_length(text):
return sum(2 if ord(character) > 0xFFFF else 1 for character in text)
def text_state(state, chapter):
"""Exact raw fields and numeric domains precede ALL Unicode/size semantics."""
if type(chapter) is not int or chapter not in (37, 38):
raise NumericalFault("INVALID_INPUT", "Use token chapter 37 or 38.")
defaults = IV37_DEFAULTS if chapter == 37 else IV38_DEFAULTS
if type(state) not in (dict, MappingProxyType):
raise NumericalFault("INVALID_INPUT", "Provide a plain object with exactly the named fields.")
if set(state) != set(defaults):
raise NumericalFault("INVALID_INPUT", "Provide every own field and no extra or symbol fields.")
if type(state["text"]) is not str:
raise NumericalFault("INVALID_INPUT", "text must be an actual string, without coercion.")
result = dict(text=state["text"])
for key in defaults:
if key != "text":
if type(state[key]) not in (int, float):
raise NumericalFault("NONFINITE", f"{key} must be an actual finite number.")
result[key] = integer(state[key], 0, 8 if key == "vocabLimit" else 1, key)
return result
def int_array(values, low=0, high=0x7FFFFFFF, label="integer array", limit=BYTE_BOUND):
"""Check dense numeric storage BEFORE narrowing; integral-valued floats are legal."""
if type(values) is np.ndarray:
if values.ndim != 1 or values.dtype.kind not in "iuf":
raise NumericalFault("INVALID_INPUT", f"{label} must be a dense one-dimensional numeric array.")
elif type(values) not in (list, tuple):
raise NumericalFault("INVALID_INPUT", f"{label} must be an actual array.")
if len(values) > limit:
raise NumericalFault("UNSUPPORTED_SIZE", f"{label} exceeds {limit} entries.")
checked = []
for index, value in enumerate(values):
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
raise NumericalFault("INVALID_INPUT", f"{label}[{index}] must be an own integer from {low} to {high}.")
try:
finite = math.isfinite(value)
except OverflowError:
finite = False
if not finite or value < low or value > high or int(value) != value:
raise NumericalFault("INVALID_INPUT", f"{label}[{index}] must be an own integer from {low} to {high}.")
checked.append(int(value))
return np.array(checked, dtype=np.int32)
def utf8_encode(text, prefix="source", trace=None):
"""Scan valid scalars first; then split each into explicit UTF-8 payload groups."""
if trace is None:
trace = TokenTrace()
if type(text) is not str:
raise NumericalFault("INVALID_INPUT", "UTF-8 input must be an actual string.")
if utf16_length(text) > BYTE_BOUND:
raise NumericalFault("UNSUPPORTED_SIZE", "More than 32 UTF-16 units necessarily exceeds this 32-byte lab.")
code_points, offsets, widths = [], [], []
offset = 0
# Python strings store scalars directly; explicit surrogate values are invalid.
for character in text:
cp = ord(character)
if 0xD800 <= cp <= 0xDBFF:
raise NumericalFault("INVALID_INPUT", f"Unpaired high surrogate at UTF-16 offset {offset}.")
if 0xDC00 <= cp <= 0xDFFF:
raise NumericalFault("INVALID_INPUT", f"Unpaired low surrogate at UTF-16 offset {offset}.")
width = len(utf16_units(cp))
code_points.append(cp)
offsets.append(offset)
widths.append(width)
offset += width
byte_values, byte_offsets, byte_widths = [], [], []
for index, cp in enumerate(code_points):
if cp <= 0x7F:
expansion = [cp]
elif cp <= 0x7FF:
expansion = [0xC0 | (cp >> 6), 0x80 | (cp & 63)]
elif cp <= 0xFFFF:
expansion = [0xE0 | (cp >> 12), 0x80 | ((cp >> 6) & 63), 0x80 | (cp & 63)]
else:
expansion = [0xF0 | (cp >> 18), 0x80 | ((cp >> 12) & 63),
0x80 | ((cp >> 6) & 63), 0x80 | (cp & 63)]
units = utf16_units(cp)
inputs = dict(scalarIndex=index, utf16Offset=offsets[index], utf16Width=widths[index], codePoint=cp, unit0=units[0])
if len(units) == 2:
inputs["unit1"] = units[1]
outputs = dict(byteOffset=len(byte_values), byteWidth=len(expansion))
for j, byte in enumerate(expansion):
mask = (31 if len(expansion) == 2 else 15 if len(expansion) == 3 else 7) if j == 0 else 63
outputs[f"payload{j}"] = byte if len(expansion) == 1 else byte & mask
outputs.update({f"byte{j}": byte for j, byte in enumerate(expansion)})
trace.add(f"{prefix}_scalar_{index}", f"Encode scalar {index}: U+{cp:04X}",
"supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits",
"A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.",
inputs, outputs)
byte_offsets.append(len(byte_values))
byte_widths.append(len(expansion))
byte_values.extend(expansion)
if len(byte_values) > BYTE_BOUND:
raise NumericalFault("UNSUPPORTED_SIZE", "The actual UTF-8 encoding exceeds 32 bytes; shorten the input explicitly.")
return dict(bytes=int_array(byte_values, high=255, label="UTF-8 bytes"), codePoints=int_array(code_points),
offsets=int_array(offsets), widths=int_array(widths), byteOffsets=int_array(byte_offsets), byteWidths=int_array(byte_widths))
def utf8_decode(values, prefix="utf8", trace=None):
"""Remove prefixes, accumulate radix-64 digits, validate, then rebuild the text."""
if trace is None:
trace = TokenTrace()
values = int_array(values, high=255, label="UTF-8 bytes")
characters, offset = [], 0
while offset < len(values):
lead = int(values[offset])
width = 1 if lead <= 0x7F else 2 if 0xC2 <= lead <= 0xDF else 3 if 0xE0 <= lead <= 0xEF else 4 if 0xF0 <= lead <= 0xF4 else 0
if not width:
raise NumericalFault("INVALID_INPUT", f"Invalid UTF-8 lead at byte {offset}.")
if offset + width > len(values):
raise NumericalFault("INVALID_INPUT", f"Truncated UTF-8 sequence at byte {offset}.")
inputs = dict(scalarIndex=len(characters), byteOffset=offset, byteWidth=width)
outputs, cp = {}, 0
for j in range(width):
byte = int(values[offset + j])
if j > 0 and not 0x80 <= byte <= 0xBF:
raise NumericalFault("INVALID_INPUT", f"Invalid continuation byte at {offset + j}.")
inputs[f"byte{j}"] = byte
mask = (31 if width == 2 else 15 if width == 3 else 7) if j == 0 else 63
payload = byte if width == 1 else byte & mask
outputs[f"payload{j}"] = payload
cp = cp * 64 + payload
outputs[f"accumulator{j}"] = cp
minimum = 0 if width == 1 else 0x80 if width == 2 else 0x800 if width == 3 else 0x10000
if cp < minimum or not scalar_valid(cp):
raise NumericalFault("INVALID_INPUT", f"Overlong, surrogate or out-of-range scalar at byte {offset}.")
units = utf16_units(cp)
outputs.update(codePoint=cp, utf16Width=len(units))
outputs.update({f"unit{j}": unit for j, unit in enumerate(units)})
# chr uses the validated scalar; no source text is available to copy here.
characters.append(chr(cp))
trace.add(f"{prefix}_decode_{len(characters) - 1}", f"Decode UTF-8 scalar {len(characters) - 1}",
"accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar",
"Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.",
inputs, outputs)
offset += width
return "".join(characters)
def _flag(eos):
if type(eos) not in (int, float) or eos not in (0, 1):
raise NumericalFault("INVALID_INPUT", "eos must be numeric 0 or 1.")
def _vocabulary(limit):
try:
if type(limit) not in (int, float):
raise NumericalFault("INVALID_INPUT", "vocabLimit must be an integer from 0 to 8.")
return integer(limit, 0, 8, "vocabLimit")
except NumericalFault as error:
raise NumericalFault("INVALID_INPUT", "vocabLimit must be an integer from 0 to 8.") from error
def _strip_eos(ids, eos):
_flag(eos)
ids = int_array(ids, high=CHARACTER_BASE + 0x10FFFF, label="Token IDs", limit=BYTE_BOUND + 1)
has_tail = len(ids) > 0 and int(ids[-1]) == EOS
content = ids[:-1].copy() if has_tail else ids.copy()
if has_tail != (eos == 1) or any(int(value) == EOS for value in content):
raise NumericalFault("INVALID_INPUT", "EOS must occur exactly once at the tail when eos=1, and nowhere when eos=0.")
return ids, content
def append_eos(ids, eos, prefix, trace):
"""Return actual int32 storage with the optional reserved tail, never text matching."""
_flag(eos)
if eos == 1:
index = len(ids)
ids = np.concatenate((ids, np.array([EOS], dtype=np.int32)))
trace.add(f"{prefix}_eos", f"{prefix}: append explicit EOS", "id=512",
"Only this flag appends EOS; literal text such as <eos> remains ordinary input.",
dict(index=index, eos=eos), dict(id=EOS))
return ids
def _eos_record(ids, eos, prefix, trace):
if eos == 1:
trace.add(f"{prefix}_strip_eos", f"{prefix}: strip explicit tail EOS", "EOS emits no text bytes",
"The decoder has validated the whole ID stream and the required unique tail marker.",
dict(index=len(ids) - 1, id=EOS), dict(stripped=1))
def decode_byte_ids(ids, eos, prefix="byte", trace=None):
return _decode_pieces(ids, eos, 0, False, prefix, TokenTrace() if trace is None else trace)
def decode_subword_ids(ids, eos, limit, prefix="subword", trace=None):
limit = _vocabulary(limit)
return _decode_pieces(ids, eos, limit, True, prefix, TokenTrace() if trace is None else trace)
def _decode_pieces(ids, eos, limit, subwords, prefix, trace):
ids, content = _strip_eos(ids, eos)
active = {identifier: expansion for identifier, _, expansion in SUBWORDS[:limit]} if subwords else {}
byte_values = []
for index, stored in enumerate(content):
identifier = int(stored)
if identifier <= 255:
expansion = (identifier,)
elif identifier in active:
expansion = active[identifier]
else:
raise NumericalFault("INVALID_INPUT", f"Unknown or inactive {prefix} ID {identifier}.")
byte_offset = len(byte_values)
byte_values.extend(expansion)
if len(byte_values) > BYTE_BOUND:
raise NumericalFault("UNSUPPORTED_SIZE", "Decoded token expansions exceed 32 bytes.")
outputs = dict(byteOffset=byte_offset, byteWidth=len(expansion))
outputs.update({f"byte{j}": byte for j, byte in enumerate(expansion)})
trace.add(f"{prefix}_expand_{index}", f"{prefix}: expand ID at token {index}", "ID → declared byte expansion",
"Fallback byte IDs equal their byte value; active subword IDs expand to their full declared bytes. A single fallback byte may be only part of a Unicode scalar.",
dict(index=index, id=identifier), outputs)
_eos_record(ids, eos, prefix, trace)
values = int_array(byte_values, high=255, label="UTF-8 bytes")
return dict(bytes=values, decoded=utf8_decode(values, prefix, trace))
def decode_character_ids(ids, eos, prefix="char", trace=None):
if trace is None:
trace = TokenTrace()
ids, content = _strip_eos(ids, eos)
characters = []
for index, stored in enumerate(content):
identifier = int(stored)
cp = identifier - CHARACTER_BASE
if not scalar_valid(cp):
raise NumericalFault("INVALID_INPUT", f"Character ID {identifier} does not name a Unicode scalar.")
units = utf16_units(cp)
outputs = dict(codePoint=cp, utf16Width=len(units))
outputs.update({f"unit{j}": unit for j, unit in enumerate(units)})
characters.append(chr(cp))
trace.add(f"{prefix}_inverse_{index}", f"Character ID {index}: inverse mapping",
"codePoint=id−1024; reconstruct UTF-16 units",
"The scalar range excludes surrogate code points but includes noncharacters. The comparison vocabulary is algorithmic; no million-row matrix is allocated.",
dict(index=index, id=identifier), outputs)
_eos_record(ids, eos, prefix, trace)
decoded = "".join(characters)
# External ID streams obey the same text bound; this private trace is omitted.
utf8_encode(decoded)
return decoded
def greedy_ids(values, limit, trace):
"""Choose longest matching byte expansion, then lowest ID; no match keeps a byte."""
values = int_array(values, high=255, label="Greedy source bytes")
limit = _vocabulary(limit)
ids, offset = [], 0
while offset < len(values):
matches = []
for identifier, _, expansion in SUBWORDS[:limit]:
if offset + len(expansion) <= len(values) and all(int(values[offset + j]) == byte for j, byte in enumerate(expansion)):
matches.append((identifier, len(expansion)))
chosen, width = int(values[offset]), 1
if matches:
chosen, width = min(matches, key=lambda candidate: (-candidate[1], candidate[0]))
inputs = dict(byteOffset=offset, remaining=len(values) - offset, candidateMatches=len(matches))
for index, (identifier, match_width) in enumerate(matches):
inputs[f"candidate{index}ID"] = identifier
inputs[f"candidate{index}Width"] = match_width
trace.add(f"subword_decision_{len(ids)}", f"Choose subword at byte offset {offset}",
"choose longest matching active byte expansion; tie: lowest subword ID; no match: current byte",
"Matched candidates are listed in fixed vocabulary order. An active one-byte entry is preferred to fallback when it matches. Advance by the actual chosen byte width; spaces and unmatched Unicode bytes remain in the stream.",
inputs, dict(id=chosen, byteWidth=width, nextByteOffset=offset + width))
ids.append(chosen)
offset += width
return int_array(ids)
def json_text(value):
"""Match JSON string/array metadata without ASCII escaping or added spaces."""
return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
def byte_labels(ids):
return ["EOS (explicit control)" if int(value) == EOS else f"byte {int(value)}" for value in ids]
def byte_expansions(ids):
return [json_text([] if int(value) == EOS else [int(value)]) for value in ids]
def numbers(values):
return {key: integer(value, -0x80000000, 0x7FFFFFFF, key) for key, value in values.items()}
class TokenTrace:
def __init__(self):
self.steps = []
def add(self, identifier, label, equation, explanation, inputs, outputs):
inputs, outputs = numbers(inputs), numbers(outputs)
if len(self.steps) >= 512:
raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 operations are supported.")
self.steps.append(dict(id=identifier, label=label, equation=equation, explanation=explanation,
inputs=inputs, outputs=outputs))
def result(self, summary, tensors, texts):
# Include copied encoding steps too, after the signed first summary aliases.
outputs = numbers(summary)
for step in self.steps:
outputs.update({f"{step['id']}_{key}": value for key, value in step["outputs"].items()})
return dict(status="defined", outputs=outputs, steps=self.steps, tensors=tensors, texts=texts)
def tensor(identifier, axis, values, provenance):
"""Serialize actual nonempty int32 storage; empty streams yield no fake tensor."""
if type(values) is not np.ndarray or values.dtype != np.dtype(np.int32) or values.ndim != 1:
raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: require one-dimensional int32 storage.")
if not 1 <= len(values) <= 64:
raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: dimensions must be 1–64.")
if type(axis) is not str or not axis:
raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name the axis.")
return dict(id=identifier, shape=[len(values)], axes=[axis], dtype="int32", values=values.tolist(),
provenance=provenance, precision=0)
_JSON_INT = int
def run(derive, defaults):
"""No args: defaults; one JSON arg: full replacement; '-': JSON from stdin."""
class ParseFault(ValueError):
"""Only locally owned JSON profile/conversion faults."""
def _members(pairs):
value = {}
for key, member in pairs:
if key in value:
raise ParseFault("Duplicate JSON object members are not allowed.")
value[key] = member
return value
def _constant(token):
raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")
def _integer(token):
if token == "-0":
return -0.0
try:
return _JSON_INT(token)
except ValueError as fault:
if type(fault) is not ValueError:
raise
raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from fault
parser = argparse.ArgumentParser(description=derive.__doc__)
parser.add_argument("state", nargs="?")
args = parser.parse_args()
if args.state is not None:
source = sys.stdin.read() if args.state == "-" else args.state
try:
state = json.loads(source, object_pairs_hook=_members,
parse_constant=_constant, parse_int=_integer)
except (json.JSONDecodeError, ParseFault) as error:
result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
else:
result = derive(state)
else:
result = derive(dict(defaults))
print(json.dumps(result, allow_nan=False, separators=(",", ":")))
Feature-local normalization and residuals — code/python/p07/component_reference.py. feature_norm saves means, centered values, squared deviations, population variance and epsilon-inside-root division. same_shape_add checks matching named shapes before adding residual features. Neither operation mixes token positions.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""Part VII component kernels: real NumPy storage, explicit float operations.
Keep this file beside iv30.py and iv31.py. NumPy represents actual shaped arrays;
Python floats perform each product/addition/division separately in signed trace
order. No matmul, vector reduction, broadcast, fused multiply-add or hidden norm.
Authored under the resource hold: this source has NOT been executed or validated.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np
class NumericalFault(ValueError):
def __init__(self, code, reason):
super().__init__(reason)
self.code = code
def finite(value, label):
"""Reject booleans, numeric strings, complex numbers and nonfinite scalars."""
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
try:
value = float(value)
except (ValueError, OverflowError) as error:
raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
if not math.isfinite(value):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
return value
RESIDUAL_DEFAULTS = MappingProxyType(dict(
B=1, T=3,
x000=1, x001=0, x010=0, x011=1, x020=1, x021=1,
x100=1, x101=1, x110=-1, x111=0, x120=0, x121=2,
w00=0.5, w01=0, w10=0, w11=-0.5, b0=0, b1=0,
g000=1, g001=2, g010=1, g011=2, g020=1, g021=2,
g100=1, g101=2, g110=1, g111=2, g120=1, g121=2,
residual=1,
))
NORM_DEFAULTS = MappingProxyType(dict(
B=1, T=3,
x000=3, x001=1, x010=2, x011=2, x020=-1, x021=1,
x100=1, x101=-1, x110=0, x111=0, x120=-2, x121=3,
gamma0=1, gamma1=1, beta0=0, beta1=0, epsilon=3,
))
def component_state(state, stage):
"""Validate all 33/19 own fields, including inactive X/g, before selecting."""
if type(stage) is not int or stage not in (30, 31):
raise NumericalFault("INVALID_INPUT", "Use component stage 30 or 31.")
defaults = RESIDUAL_DEFAULTS if stage == 30 else NORM_DEFAULTS
if type(state) not in (dict, MappingProxyType):
raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
if set(state) != set(defaults):
raise NumericalFault("INVALID_INPUT", "Provide every own scalar field and no extra fields, including inactive slots.")
integer_bounds = dict(B=(1, 2), T=(1, 3), residual=(0, 1))
result = {}
for key in defaults:
value = finite(state[key], key)
low, high = integer_bounds.get(key, (1e-8, 4) if key == "epsilon" else (-4, 4))
if value < low or value > high:
raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
if key in integer_bounds and not value.is_integer():
raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
result[key] = int(value) if key in integer_bounds else value
return result
def guarded(derive):
@wraps(derive)
def call(state):
try:
return derive(state)
except NumericalFault as error:
return dict(status="unavailable", code=error.code, reason=str(error))
except (OverflowError, FloatingPointError) as error:
return dict(status="unavailable", code="NONFINITE", reason=str(error))
return call
def numbers(values):
return {key: finite(value, key) for key, value in values.items()}
class ComponentTrace:
def __init__(self):
self.outputs = {}
self.steps = []
def add(self, identifier, label, equation, explanation, inputs, values):
# Finite clones detach each saved operand/result from mutable arrays/state.
inputs, values = numbers(inputs), numbers(values)
if len(self.steps) >= 512:
raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 trace steps are supported.")
self.steps.append(dict(id=identifier, label=label, equation=equation,
explanation=explanation, inputs=inputs, outputs=values))
self.outputs.update({f"{identifier}_{key}": value for key, value in values.items()})
def result(self, summary, tensors):
# Aliases first, then ALL flattened step outputs in their insertion order.
return dict(status="defined", outputs=numbers({**summary, **self.outputs}),
steps=self.steps, tensors=tensors)
def component_trace():
return ComponentTrace()
def tensor(identifier, shape, axes, values, provenance):
"""Platform-style float64 boundary: explicit named shape and dense flat list."""
if type(shape) is not list or type(axes) is not list or not 1 <= len(shape) <= 4 or len(shape) != len(axes):
raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name each of 1–4 axes uniquely.")
if any(type(axis) is not str or not axis for axis in axes) or len(set(axes)) != len(axes):
raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: each axis needs a unique name.")
if any(type(d) is not int or not 1 <= d <= 64 for d in shape) or math.prod(shape) > 4096:
raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: dimensions 1–64 and at most 4096 elements required.")
if type(values) is not list or len(values) != math.prod(shape):
raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage does not match dimensions.")
flat = [finite(value, f"{identifier}[{n}]") for n, value in enumerate(values)]
return dict(id=identifier, shape=list(shape), axes=list(axes), dtype="float64",
values=flat, provenance=provenance, precision=8)
def same_shape_add(identifier, left, right):
"""Add validated float64 TensorRecords; equal element count is insufficient."""
checked = []
for n, record in enumerate((left, right)):
if type(record) not in (dict, MappingProxyType) or record.get("dtype") != "float64":
raise NumericalFault("INVALID_INPUT", f"{identifier}: operand {n} must be a float64 tensor.")
checked.append(tensor(record.get("id"), record.get("shape"), record.get("axes"),
record.get("values"), record.get("provenance")))
a, b = checked
if a["shape"] != b["shape"] or a["axes"] != b["axes"]:
raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: addition needs identical dimensions and named axes; no broadcasting.")
values = [finite(value + b["values"][n], f"{identifier}[{n}]") for n, value in enumerate(a["values"])]
return tensor(identifier, a["shape"], a["axes"], values,
f"Exact named-shape addition of {left['id']} and {right['id']}; no broadcasting.")
def feature_norm(kind, prefix, x, gamma, beta, epsilon, trace):
"""Normalize one width-two token; no chapter bounds on derived IV33 rows.
Inputs are dense lists, as in the TS kernel. Validate beta even for RMS,
then deliberately omit it from RMS arithmetic and feature trace inputs.
"""
if kind not in ("layer", "rms"):
raise NumericalFault("INVALID_INPUT", "Use layer or rms normalization.")
checked = []
for name, values in (("x", x), ("gamma", gamma), ("beta", beta)):
if type(values) is not list or len(values) != 2:
raise NumericalFault("SHAPE_MISMATCH", f"{name} needs exactly two dense features.")
checked.append([finite(value, f"{name}[{d}]") for d, value in enumerate(values)])
x, gamma, beta = checked
epsilon = finite(epsilon, "epsilon")
if epsilon <= 0:
raise NumericalFault("INVALID_INPUT", "epsilon must be strictly positive.")
statistics = {}
if kind == "layer":
# Population variance: two centered squares, then sum, then divide by 2.
statistics["sum"] = finite(x[0] + x[1], "feature sum")
statistics["mean"] = finite(statistics["sum"] / 2, "feature mean")
statistics["centered0"] = finite(x[0] - statistics["mean"], "centered0")
statistics["centered1"] = finite(x[1] - statistics["mean"], "centered1")
statistics["square0"] = finite(statistics["centered0"] * statistics["centered0"], "centered square0")
statistics["square1"] = finite(statistics["centered1"] * statistics["centered1"], "centered square1")
statistics["squareSum"] = finite(statistics["square0"] + statistics["square1"], "centered square sum")
statistics["variance"] = finite(statistics["squareSum"] / 2, "population variance")
statistics["variancePlusEpsilon"] = finite(statistics["variance"] + epsilon, "variance plus epsilon")
statistics["denominator"] = finite(math.sqrt(statistics["variancePlusEpsilon"]), "LN denominator")
source = [statistics["centered0"], statistics["centered1"]]
else:
# RMS uses original features, with neither mean subtraction nor beta.
statistics["square0"] = finite(x[0] * x[0], "square0")
statistics["square1"] = finite(x[1] * x[1], "square1")
statistics["squareSum"] = finite(statistics["square0"] + statistics["square1"], "square sum")
statistics["meanSquare"] = finite(statistics["squareSum"] / 2, "mean square")
statistics["meanSquarePlusEpsilon"] = finite(statistics["meanSquare"] + epsilon, "mean square plus epsilon")
statistics["denominator"] = finite(math.sqrt(statistics["meanSquarePlusEpsilon"]), "RMS denominator")
source = list(x)
trace.add(f"{prefix}_statistics", f"{prefix}: feature-only statistics",
"mean=(x0+x1)/2; variance=(centered0²+centered1²)/2; denominator=sqrt(variance+epsilon)" if kind == "layer" else
"meanSquare=(x0²+x1²)/2; denominator=sqrt(meanSquare+epsilon)",
"Only this token's two features contribute. Epsilon stays inside the square root.",
dict(x0=x[0], x1=x[1], epsilon=epsilon), statistics)
normalized, values = [], []
for d in range(2):
n = finite(source[d] / statistics["denominator"], "normalized feature")
scaled = finite(gamma[d] * n, "scaled feature")
value = finite(scaled + beta[d], "LN affine feature") if kind == "layer" else scaled
normalized.append(n)
values.append(value)
inputs = dict(d=d, source=source[d], denominator=statistics["denominator"], gamma=gamma[d])
if kind == "layer":
inputs["beta"] = beta[d]
trace.add(f"{prefix}_feature_{d}", f"{prefix}: affine feature {d}",
"normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta" if kind == "layer" else
"normalized=source/denominator; scaled=gamma*normalized; value=scaled",
"LayerNorm uses centered features and beta; scale-only RMS uses original features and no beta.",
inputs, dict(normalized=n, scaled=scaled, value=value))
return dict(values=values, normalized=normalized, statistics=statistics)
_JSON_INT = int
def run(derive, defaults):
"""No argument uses defaults; one JSON argument replaces all; '-' reads stdin."""
class ParseFault(ValueError):
"""Only locally owned JSON profile/conversion faults."""
def _members(pairs):
value = {}
for key, member in pairs:
if key in value:
raise ParseFault("Duplicate JSON object members are not allowed.")
value[key] = member
return value
def _constant(token):
raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")
def _integer(token):
if token == "-0":
return -0.0
try:
return _JSON_INT(token)
except ValueError as fault:
if type(fault) is not ValueError:
raise
raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from fault
parser = argparse.ArgumentParser(description=derive.__doc__)
parser.add_argument("state", nargs="?")
args = parser.parse_args()
if args.state is not None:
source = sys.stdin.read() if args.state == "-" else args.state
try:
state = json.loads(source, object_pairs_hook=_members,
parse_constant=_constant, parse_int=_integer)
except (json.JSONDecodeError, ParseFault) as error:
result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
else:
result = derive(state)
else:
result = derive(dict(defaults))
print(json.dumps(result, allow_nan=False, separators=(",", ":")))
Three-coordinate feed-forward network — code/python/p07/ffn_reference.py. feed_forward records hidden projection products, bias addition, each ReLU and the output contraction. Its zero third hidden coordinate is calculated, not dropped. Follow both feature sums back to the second residual Y.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""Part VII position-wise FFN: actual NumPy storage, explicit float order.
D=2 input features -> M=3 hidden features -> D=2 output features. Parameters
are shared across tokens/batches; arithmetic never sums over token positions.
NumPy stores shaped float64 arrays, but every arithmetic operation below uses
Python floats, with finite checks and saved operands/results. No BLAS reduction,
broadcast, fused multiply-add, residual, dropout or output softmax is hidden.
Source only: this program has not been imported, executed or validated.
"""
from types import MappingProxyType
import numpy as np
from component_reference import NORM_DEFAULTS, NumericalFault, finite, tensor
FFN_PARAMETERS = MappingProxyType(dict(
f100=1, f101=0, f102=1, f110=0, f111=1, f112=-1,
fb10=0, fb11=0, fb12=0,
f200=0.5, f201=0, f210=0, f211=-0.5, f220=0.25, f221=0.25,
fb20=0, fb21=0,
))
FFN_DEFAULTS = MappingProxyType(dict(
B=NORM_DEFAULTS["B"], T=NORM_DEFAULTS["T"],
**{key: value for key, value in NORM_DEFAULTS.items() if key.startswith("x")},
**FFN_PARAMETERS,
))
def ffn_state(state):
"""Validate all 31 exact own scalar fields, including inactive X slots."""
if type(state) not in (dict, MappingProxyType):
raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
if set(state) != set(FFN_DEFAULTS):
raise NumericalFault("INVALID_INPUT", "Provide every own scalar field and no extra fields, including inactive slots.")
result = {}
for key in FFN_DEFAULTS:
value = finite(state[key], key)
low, high = (1, 2) if key == "B" else (1, 3) if key == "T" else (-4, 4)
if value < low or value > high:
raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
if key in ("B", "T") and not value.is_integer():
raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
result[key] = int(value) if key in ("B", "T") else value
return result
def feed_forward(s, input_record, trace, prefix="ffn"):
"""Return seven stage tensors and aliases; the caller owns input_record.
This reusable kernel accepts finite derived inputs beyond raw [-4,4] bounds.
It requires exact [B,T,2] dimensions/axes and finite values for all parameters.
"""
dimensions = []
for key, maximum in (("B", 2), ("T", 3)):
value = finite(s.get(key), key)
if not value.is_integer() or not 1 <= value <= maximum:
raise NumericalFault("INVALID_INPUT", f"{key} must be an integer between 1 and {maximum}.")
dimensions.append(int(value))
B, T = dimensions
parameters = {key: finite(s.get(key), key) for key in FFN_PARAMETERS}
if type(input_record) not in (dict, MappingProxyType) or input_record.get("dtype") != "float64":
raise NumericalFault("INVALID_INPUT", "FFN input must be a float64 tensor.")
checked = tensor(input_record.get("id"), input_record.get("shape"), input_record.get("axes"),
input_record.get("values"), input_record.get("provenance"))
shape, axes = [B, T, 2], ["B", "T", "D"]
if checked["shape"] != shape or checked["axes"] != axes:
raise NumericalFault("SHAPE_MISMATCH", "FFN input needs exact [B,T,2] dimensions and B,T,D axes.")
# NumPy holds real shaped storage; scalar float reads prevent reordered reductions.
X = np.array(checked["values"], dtype=np.float64).reshape(shape)
W1, b1 = np.empty((2, 3), dtype=np.float64), np.empty(3, dtype=np.float64)
W2, b2 = np.empty((3, 2), dtype=np.float64), np.empty(2, dtype=np.float64)
for d in range(2):
for m in range(3):
W1[d, m] = parameters[f"f1{d}{m}"]
for m in range(3):
b1[m] = parameters[f"fb1{m}"]
for d in range(2):
W2[m, d] = parameters[f"f2{m}{d}"]
for d in range(2):
b2[d] = parameters[f"fb2{d}"]
hidden_shape, hidden_axes = [B, T, 3], ["B", "T", "HiddenFeature"]
Z, Hidden = np.empty(hidden_shape, dtype=np.float64), np.empty(hidden_shape, dtype=np.float64)
F = np.empty(shape, dtype=np.float64)
# Save ALL hidden affines before any activation, in ascending b/t/m order.
for b in range(B):
for t in range(T):
for m in range(3):
x0, x1 = float(X[b, t, 0]), float(X[b, t, 1])
w0, w1, bias = float(W1[0, m]), float(W1[1, m]), float(b1[m])
product0 = finite(x0 * w0, "FFN hidden product0")
product1 = finite(x1 * w1, "FFN hidden product1")
summed = finite(product0 + product1, "FFN hidden sum")
preactivation = finite(summed + bias, "FFN hidden preactivation")
Z[b, t, m] = preactivation
trace.add(f"{prefix}_hidden_{b}_{t}_{m}", f"Hidden affine [{b},{t},{m}]",
"product0=x0*w0; product1=x1*w1; sum=product0+product1; preactivation=sum+bias",
"The same input-to-hidden weights and bias are reused at every token; bias is added last.",
dict(b=b, t=t, m=m, x0=x0, x1=x1, w0=w0, w1=w1, bias=bias),
dict(product0=product0, product1=product1, sum=summed, preactivation=preactivation))
for b in range(B):
for t in range(T):
for m in range(3):
preactivation = float(Z[b, t, m])
activation = finite(max(0.0, preactivation), "FFN ReLU")
Hidden[b, t, m] = activation
trace.add(f"{prefix}_relu_{b}_{t}_{m}", f"ReLU [{b},{t},{m}]",
"activation=max(0,preactivation)",
"ReLU keeps positive values and maps negative values and zero to zero; it is not a softmax.",
dict(b=b, t=t, m=m, preactivation=preactivation), dict(activation=activation))
for b in range(B):
for t in range(T):
for d in range(2):
inputs, products, running = dict(b=b, t=t, d=d), {}, {}
summed = 0.0
# Each product is immediately accumulated from zero; bias follows all three.
for m in range(3):
h, w = float(Hidden[b, t, m]), float(W2[m, d])
inputs[f"h{m}"], inputs[f"w{m}"] = h, w
product = finite(h * w, "FFN output product")
products[f"product{m}"] = product
summed = finite(summed + product, "FFN output running sum")
running[f"running{m}"] = summed
bias = float(b2[d])
inputs["bias"] = bias
value = finite(summed + bias, "FFN output")
F[b, t, d] = value
trace.add(f"{prefix}_output_{b}_{t}_{d}", f"FFN output [{b},{t},{d}]",
"product_m=h_m*w_m; running starts at 0; running_m=previous+product_m; sum=running2; value=sum+bias",
"Three hidden features are contracted in ascending order. No token sum, residual or output softmax is added.",
inputs, {**products, **running, "sum": summed, "value": value})
aliases = {}
for name, values, width in (("pre", Z, 3), ("h", Hidden, 3), ("f", F, 2)):
for b in range(B):
for t in range(T):
for coordinate in range(width):
aliases[f"{name}{b}{t}{coordinate}"] = float(values[b, t, coordinate])
tensors = [
tensor("W1", [2, 3], ["D", "HiddenFeature"], W1.reshape(-1).tolist(), "Shared row weights from two input features to three hidden features."),
tensor("b1", [3], ["HiddenFeature"], b1.tolist(), "Shared hidden-feature biases, added after the two input products."),
tensor("Z", hidden_shape, hidden_axes, Z.reshape(-1).tolist(), "Hidden affine preactivations before ReLU."),
tensor("Hidden", hidden_shape, hidden_axes, Hidden.reshape(-1).tolist(), "ReLU applied separately to each preactivation, including zero -> zero."),
tensor("W2", [3, 2], ["HiddenFeature", "D"], W2.reshape(-1).tolist(), "Shared row weights from three hidden features back to two output features."),
tensor("b2", [2], ["D"], b2.tolist(), "Shared output-feature biases, added after the three hidden products."),
tensor("F", shape, axes, F.reshape(-1).tolist(), "Position-wise FFN output; each token uses the same parameters without token mixing."),
]
return dict(output=tensors[-1], tensors=tensors, aliases=aliases)
Projection and full attention primitives — code/python/p06/head_reference.py. project_heads supplies explicit Q/K/value projection and layout conversion. The full decoder uses attend_heads and join_heads; their coupled full-query/full-key layout is why the new cache module separately implements one-query attention and output projection. Reusing projections does not justify pretending an old square attention result was a cached row.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""Part VI: real NumPy head arrays with explicit Python-float arithmetic.
The stages are local: project_heads owns projections and layout, attend_heads
owns scores/probabilities/weighted values, join_heads owns concatenation and WO.
Chapter wrappers combine those records explicitly. No Part V helper is imported.
Keep this file beside iv27.py, iv28.py and iv29.py. Source authored under hold;
none of these numerical programs has been executed or runtime-validated.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np
class NumericalFault(ValueError):
def __init__(self, code, reason):
super().__init__(reason)
self.code = code
def finite(value, label):
"""Accept numerical scalars, never strings, booleans or nonfinite values."""
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
try:
value = float(value)
except (ValueError, OverflowError) as error:
raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
if not math.isfinite(value):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
return value
# Weight names mean input feature d, head h, feature f WITHIN that head.
_head_defaults = dict(
B=1, T=3, H=2, Dk=1, Dv=1,
x000=1, x001=0, x010=0, x011=1, x020=1, x021=1,
x100=1, x101=1, x110=-1, x111=0, x120=0, x121=2,
)
for _prefix in ("wq", "wk", "wv"):
for _d in range(2):
for _h in range(2):
for _f in range(2):
_head_defaults[f"{_prefix}{_d}{_h}{_f}"] = 1 if _d == (_h + _f) % 2 else 0
HEAD_DEFAULTS = MappingProxyType(_head_defaults)
ATTENTION_HEAD_DEFAULTS = MappingProxyType(dict(
**HEAD_DEFAULTS, mode=1, valid0=1, valid1=1, valid2=1, shift=0,
))
OUTPUT_HEAD_DEFAULTS = MappingProxyType(dict(
**ATTENTION_HEAD_DEFAULTS,
wo000=1, wo001=1, wo010=0.5, wo011=0,
wo100=1, wo101=-1, wo110=0, wo111=0.5,
))
del _head_defaults, _prefix, _d, _h, _f
def head_state(state, stage):
"""Validate exactly 41/46/54 fields BEFORE selecting any active slots."""
if type(stage) is not int or stage not in (27, 28, 29):
raise NumericalFault("INVALID_INPUT", "Use head stage 27, 28 or 29.")
defaults = {27: HEAD_DEFAULTS, 28: ATTENTION_HEAD_DEFAULTS, 29: OUTPUT_HEAD_DEFAULTS}[stage]
if type(state) not in (dict, MappingProxyType):
raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
if set(state) != set(defaults):
raise NumericalFault("INVALID_INPUT", "Provide every named scalar field and no extra fields, including inactive slots.")
integer_bounds = dict(B=(1, 2), T=(1, 3), H=(1, 2), Dk=(1, 2), Dv=(1, 2),
mode=(0, 3), valid0=(0, 1), valid1=(0, 1), valid2=(0, 1))
result = {}
for key in defaults:
value = finite(state[key], key)
low, high = integer_bounds.get(key, (-10000, 10000) if key == "shift" else (-4, 4))
if value < low or value > high:
raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
if key in integer_bounds and not value.is_integer():
raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
result[key] = int(value) if key in integer_bounds else value
return result
def guarded(derive):
@wraps(derive)
def call(state):
try:
return derive(state)
except NumericalFault as error:
return {"status": "unavailable", "code": error.code, "reason": str(error)}
except (OverflowError, FloatingPointError) as error:
return {"status": "unavailable", "code": "NONFINITE", "reason": str(error)}
return call
def numbers(values):
return {key: finite(value, key) for key, value in values.items()}
class HeadTrace:
def __init__(self):
self.outputs = {}
self.steps = []
def add(self, identifier, label, equation, explanation, inputs, values):
if len(self.steps) >= 512:
raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 trace steps are supported.")
# New finite dictionaries detach records from the caller's mutable state.
inputs, values = numbers(inputs), numbers(values)
self.outputs.update({f"{identifier}_{key}": value for key, value in values.items()})
self.steps.append(dict(id=identifier, label=label, equation=equation,
explanation=explanation, inputs=inputs, outputs=values))
def result(self, summary, tensors):
return dict(status="defined", outputs=numbers({**summary, **self.outputs}),
steps=self.steps, tensors=tensors)
def head_trace():
return HeadTrace()
def tensor(identifier, shape, axes, values, provenance):
if not 1 <= len(shape) <= 4 or len(shape) != len(axes) or len(set(axes)) != len(axes):
raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name each of 1–4 axes uniquely.")
if any(type(d) is not int or not 1 <= d <= 64 for d in shape) or math.prod(shape) > 4096:
raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: dimensions 1–64 and at most 4096 elements required.")
array = np.asarray(values)
if array.shape != tuple(shape):
raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage must match the named dimensions.")
boolean = array.dtype == np.dtype(np.bool_)
flat = [bool(value) for value in array.reshape(-1)] if boolean else [finite(value, identifier) for value in array.reshape(-1)]
return dict(id=identifier, shape=list(shape), axes=list(axes), dtype="bool" if boolean else "float64",
values=flat, provenance=provenance, precision=8)
def split_heads(identifier, values, B, T, H, F, features, trace):
"""Reshape [B,T,H*F] first; then separately permute axes (0,2,1,3)."""
for name, value, maximum in (("B", B, 2), ("T", T, 3), ("H", H, 2), ("F", F, 2), ("features", features, 4)):
value = finite(value, name)
if not value.is_integer() or not 1 <= value <= maximum:
raise NumericalFault("INVALID_INPUT", f"{name} must be an integer between 1 and {maximum}.")
B, T, H, F, features = int(B), int(T), int(H), int(F), int(features)
if features != H * F:
raise NumericalFault("SHAPE_MISMATCH", "Projection features must equal H*F; no feature may be discarded.")
if type(values) is not list or len(values) != B * T * features:
raise NumericalFault("SHAPE_MISMATCH", "Projection storage must be a dense array of B*T*features values.")
# Shape/storage errors precede traversal of any numerical element.
flat = [finite(value, f"{identifier}[{index}]") for index, value in enumerate(values)]
split = np.array(flat, dtype=np.float64).reshape((B, T, H, F))
trace.add(f"reshape_{identifier}", f"{identifier}: expose the head and within-head feature axes",
"[B,T,H*F] -> [B,T,H,F]; the flat value order is unchanged",
"A reshape changes only the coordinate description. It does not move a token or a head value.",
dict(B=B, T=T, H=H, F=F, features=features, elements=B*T*H*F), dict(elements=B*T*H*F))
# This declared permutation is a separate copy, not a disguised reshape.
heads = np.transpose(split, axes=(0, 2, 1, 3)).copy()
for b in range(B):
for h in range(H):
for t in range(T):
for f in range(F):
feature = h * F + f
source_offset = (b * T + t) * (H * F) + feature
destination_offset = ((b * H + h) * T + t) * F + f
source_value = float(split[b, t, h, f])
trace.add(f"permute_{identifier}_{b}_{h}_{t}_{f}", f"{identifier}[{b},{h},{t},{f}]: copy to head-major order",
"U[b,h,t,f]=R[b,t,h,f]; axes=(0,2,1,3)",
"The source and destination flat offsets differ in general; the indexed value is copied unchanged.",
dict(b=b, h=h, t=t, f=f, feature=feature, sourceOffset=source_offset,
destinationOffset=destination_offset, sourceValue=source_value),
dict(value=float(heads[b, h, t, f])))
feature_axis = "Dv" if identifier == "V" else "Dk"
tensors = [tensor(f"{identifier}Split", [B, T, H, F], ["B", "T", "H", feature_axis], split,
"Storage-preserving reshape of the concatenated projection; each feature is h*F+f."),
tensor(f"{identifier}Heads", [B, H, T, F], ["B", "H", "T", feature_axis], heads,
"Separate declared axis permutation (0,2,1,3) from token-major to head-major storage.")]
return dict(split=split, heads=heads, tensors=tensors)
def project_heads(s, trace):
"""Project Q,K,V in role/b/t/h/f order, then expose each head layout."""
B, T, H, Dk, Dv = (s[key] for key in ("B", "T", "H", "Dk", "Dv"))
X = np.empty((B, T, 2), dtype=np.float64)
for b in range(B):
for t in range(T):
for d in range(2):
X[b, t, d] = s[f"x{b}{t}{d}"]
trace.add("setup", "Validate all scalar inputs and select active dimensions",
"D=2; X[B,T,D]; WQ,WK[D,H*Dk]; WV[D,H*Dv]",
"Validate even inactive fields, then pack each named head/feature parameter. Both input rows remain active.",
s, dict(B=B, T=T, D=2, H=H, Dk=Dk, Dv=Dv))
stage = dict(X=X)
for name, prefix, width in (("Q", "wq", Dk), ("K", "wk", Dk), ("V", "wv", Dv)):
weights = np.empty((2, H * width), dtype=np.float64)
joined = np.empty((B, T, H * width), dtype=np.float64)
for d in range(2):
for h in range(H):
for f in range(width):
weights[d, h * width + f] = s[f"{prefix}{d}{h}{f}"]
for b in range(B):
for t in range(T):
for h in range(H):
for f in range(width):
x0, x1 = float(X[b, t, 0]), float(X[b, t, 1])
w0, w1 = float(weights[0, h * width + f]), float(weights[1, h * width + f])
product0 = finite(x0 * w0, "projection product0")
product1 = finite(x1 * w1, "projection product1")
value = finite(product0 + product1, "projection value")
joined[b, t, h * width + f] = value
trace.add(f"project_{name}_{b}_{t}_{h}_{f}", f"{name} token {b},{t}, head {h}, feature {f}",
"product0=x0*w0; product1=x1*w1; value=product0+product1",
"Multiply one input row by the column for this head and feature. The two products precede their sum.",
dict(b=b, t=t, h=h, f=f, x0=x0, x1=x1, w0=w0, w1=w1),
dict(product0=product0, product1=product1, value=value))
stage[f"W{name}"] = weights
stage[f"{name}Concat"] = joined
tensors = [tensor("X", [B, T, 2], ["B", "T", "D"], X, "Active input token rows; both input features are retained.")]
for name, width, axis in (("Q", Dk, "QueryFeature"), ("K", Dk, "KeyFeature"), ("V", Dv, "ValueFeature")):
tensors.append(tensor(f"W{name}", [2, H*width], ["D", axis], stage[f"W{name}"],
"Packed named weights: column h*F+f, retaining both input rows."))
for name, width, axis in (("Q", Dk, "QueryFeature"), ("K", Dk, "KeyFeature"), ("V", Dv, "ValueFeature")):
tensors.append(tensor(f"{name}Concat", [B, T, H*width], ["B", "T", axis], stage[f"{name}Concat"],
"Real two-product projections in token-major, packed-head feature order."))
aliases = {}
for name, width in (("Q", Dk), ("K", Dk), ("V", Dv)):
layout = split_heads(name, stage[f"{name}Concat"].reshape(-1).tolist(), B, T, H, width, H*width, trace)
stage[f"{name}Split"], stage[f"{name}Heads"] = layout["split"], layout["heads"]
tensors.extend(layout["tensors"])
for b in range(B):
for h in range(H):
for t in range(T):
for f in range(width):
aliases[f"{name.lower()}{b}{h}{t}{f}"] = float(layout["heads"][b, h, t, f])
return dict(X=stage["X"], WQ=stage["WQ"], WK=stage["WK"], WV=stage["WV"],
QConcat=stage["QConcat"], KConcat=stage["KConcat"], VConcat=stage["VConcat"],
QSplit=stage["QSplit"], QHeads=stage["QHeads"], KSplit=stage["KSplit"],
KHeads=stage["KHeads"], VSplit=stage["VSplit"], VHeads=stage["VHeads"],
aliases=aliases, tensors=tensors)
def stable_softmax(logits, allowed):
"""M1 operation order: allowed max, ascending terms/sum, then quotients."""
if type(logits) is not list or type(allowed) is not list or not 1 <= len(logits) <= 64 or len(logits) != len(allowed):
raise NumericalFault("SHAPE_MISMATCH", "A boolean allowed mask must match 1–64 logits.")
logits = [finite(value, f"logit {j}") for j, value in enumerate(logits)]
if any(type(value) is not bool for value in allowed):
raise NumericalFault("INVALID_INPUT", "Every mask entry must be boolean.")
candidates = [value for j, value in enumerate(logits) if allowed[j]]
if not candidates:
raise NumericalFault("FULLY_MASKED_ROW", "This query has no allowed keys; no probability distribution exists.")
maximum = max(candidates)
# Match Math.max zero ties without erasing an all-negative-zero maximum.
if maximum == 0.0 and any(value == 0.0 and math.copysign(1.0, value) > 0.0 for value in candidates):
maximum = 0.0
terms = []
for j, logit in enumerate(logits):
term = finite(math.exp(finite(logit - maximum, "shifted logit")), "softmax term") if allowed[j] else 0.0
terms.append(term)
denominator = 0.0
for term in terms:
denominator = finite(denominator + term, "softmax denominator")
probabilities = [finite(term / denominator, "softmax probability") for term in terms]
return dict(max=maximum, terms=terms, denominator=denominator, probabilities=probabilities)
def attend_heads(s, projected, trace):
"""Each b,h path scores, masks and mixes independently along the key axis."""
B, T, H, Dk, Dv = (s[key] for key in ("B", "T", "H", "Dk", "Dv"))
Q, K, V = projected["QHeads"], projected["KHeads"], projected["VHeads"]
shape = (B, H, T, T)
raw, scores = np.empty(shape, dtype=np.float64), np.empty(shape, dtype=np.float64)
aliases = {}
divisor = finite(math.sqrt(Dk), "score divisor")
for b in range(B):
for h in range(H):
for i in range(T):
for j in range(T):
q0, k0 = float(Q[b, h, i, 0]), float(K[b, h, j, 0])
inputs = dict(b=b, h=h, i=i, j=j, Dk=Dk, divisor=divisor, q0=q0, k0=k0)
product0 = finite(q0 * k0, "score product0")
values, dot = dict(product0=product0), product0
if Dk == 2:
q1, k1 = float(Q[b, h, i, 1]), float(K[b, h, j, 1])
inputs.update(q1=q1, k1=k1)
product1 = finite(q1 * k1, "score product1")
values["product1"] = product1
dot = finite(product0 + product1, "raw score")
scaled = finite(dot / divisor, "scaled score")
raw[b, h, i, j], scores[b, h, i, j] = dot, scaled
values.update(raw=dot, score=scaled)
aliases[f"raw{b}{h}{i}{j}"] = dot
aliases[f"score{b}{h}{i}{j}"] = scaled
trace.add(f"score_{b}_{h}_{i}_{j}", f"Batch {b}, head {h}: query {i} against key {j}",
"product0=q0*k0; raw=product0; score=raw/sqrt(Dk)" if Dk == 1 else
"product0=q0*k0; product1=q1*k1; raw=product0+product1; score=raw/sqrt(Dk)",
"Only matching features in this batch and head contribute. The divisor is the per-head key width.", inputs, values)
allowed = np.empty(shape, dtype=np.bool_)
logits, probabilities = np.empty(shape, dtype=np.float64), np.empty(shape, dtype=np.float64)
causal, padding = s["mode"] in (1, 3), s["mode"] in (2, 3)
for b in range(B):
for h in range(H):
for i in range(T):
inputs = dict(b=b, h=h, i=i, mode=s["mode"], shift=s["shift"])
row_logits, row_allowed = [], []
for j in range(T):
score = float(scores[b, h, i, j])
inputs[f"score{j}"] = score
permit = (not causal or j <= i) and (not padding or s[f"valid{j}"] == 1)
allowed[b, h, i, j] = permit
logit = finite(score + s["shift"], "shifted score")
logits[b, h, i, j] = logit
row_logits.append(logit)
row_allowed.append(permit)
for j in range(T):
inputs[f"allowed{j}"] = 1 if row_allowed[j] else 0
if not any(row_allowed):
raise NumericalFault("FULLY_MASKED_ROW", f"Batch {b}, head {h}, query {i} has no allowed keys; the entire result is unavailable.")
row = stable_softmax(row_logits, row_allowed)
values = dict(max=row["max"], denominator=row["denominator"])
for j in range(T):
if row_allowed[j]:
values[f"shifted{j}"] = finite(row_logits[j] - row["max"], "shifted logit")
for j in range(T):
values[f"term{j}"] = row["terms"][j]
for j in range(T):
p = row["probabilities"][j]
probabilities[b, h, i, j] = p
values[f"p{j}"] = p
aliases[f"p{b}{h}{i}{j}"] = p
trace.add(f"row_{b}_{h}_{i}", f"Batch {b}, head {h}: masked key softmax for query {i}",
"logit_j=score_j+shift; max=max(allowed logits); term_j=allowed_j?exp(logit_j-max):0; denominator=sum_j term_j; p_j=term_j/denominator",
"Normalize allowed keys only, in ascending key order. Queries remain; masks are shared across heads/batches. Forbidden probabilities are exactly zero; allowed exponential underflow is distinct.", inputs, values)
OHeads = np.empty((B, H, T, Dv), dtype=np.float64)
for b in range(B):
for h in range(H):
for i in range(T):
for f in range(Dv):
inputs, products, running = dict(b=b, h=h, i=i, f=f), {}, {}
value = 0.0
for j in range(T):
p, v = float(probabilities[b, h, i, j]), float(V[b, h, j, f])
inputs[f"p{j}"], inputs[f"v{j}"] = p, v
product = finite(p * v, "head value product")
products[f"product{j}"] = product
value = finite(value + product, "head value running sum")
running[f"running{j}"] = value
OHeads[b, h, i, f] = value
aliases[f"oh{b}{h}{i}{f}"] = value
trace.add(f"head_mix_{b}_{h}_{i}_{f}", f"Head output [{b},{h},{i},{f}]",
"product_j=p_j*v_j; running starts at 0; running_j=previous+product_j; value=last running sum",
"Use this head's actual probability row and value feature. Every key contributes its product, including masked 0*V, followed immediately by its running sum.",
inputs, {**products, **running, "value": value})
axes = ["B", "H", "Query", "Key"]
tensors = [tensor("raw", list(shape), axes, raw, "Per-head query-key products, summed before scaling."),
tensor("scores", list(shape), axes, scores, "Raw dot products divided by sqrt(Dk)."),
tensor("allowed", list(shape), axes, allowed, "Boolean allowed-key masks; validity is shared across B and H; queries remain."),
tensor("logits", list(shape), axes, logits, "Finite score+common shift for every key, including forbidden keys; no infinity sentinel."),
tensor("probabilities", list(shape), axes, probabilities, "Per-batch/head/query stable softmax along allowed keys only."),
tensor("OHeads", [B, H, T, Dv], ["B", "H", "Query", "Dv"], OHeads,
"Actual per-head weighted values: ascending key products and sequential sums from zero.")]
return dict(raw=raw, scores=scores, allowed=allowed, logits=logits, probabilities=probabilities,
OHeads=OHeads, aliases=aliases, tensors=tensors)
def join_heads(s, attended, trace):
"""Copy OHeads into C in head/feature order, then compute every C*WO term."""
B, T, H, Dv = (s[key] for key in ("B", "T", "H", "Dv"))
OHeads = attended["OHeads"]
C = np.empty((B, T, H*Dv), dtype=np.float64)
aliases = {}
for b in range(B):
for t in range(T):
for h in range(H):
for f in range(Dv):
c = h * Dv + f
source_offset = ((b * H + h) * T + t) * Dv + f
destination_offset = (b * T + t) * (H * Dv) + c
value = finite(OHeads[b, h, t, f], "head output to concatenate")
C[b, t, c] = value
aliases[f"c{b}{t}{c}"] = value
trace.add(f"concat_{b}_{t}_{h}_{f}", f"Joined feature [{b},{t},{c}] from head {h}, feature {f}",
"C[b,t,h*Dv+f]=OHeads[b,h,t,f]",
"Copy the actual head output unchanged; concatenation rearranges coordinates and never averages heads.",
dict(b=b, t=t, h=h, f=f, concatFeature=c, sourceOffset=source_offset,
destinationOffset=destination_offset, sourceValue=value), dict(value=value))
WO = np.empty((H*Dv, 2), dtype=np.float64)
for h in range(H):
for f in range(Dv):
for d in range(2):
WO[h*Dv+f, d] = s[f"wo{h}{f}{d}"]
Y = np.empty((B, T, 2), dtype=np.float64)
for b in range(B):
for t in range(T):
for d in range(2):
inputs, products, running = dict(b=b, t=t, d=d), {}, {}
value = 0.0
for c in range(H*Dv):
coordinate, weight = float(C[b, t, c]), float(WO[c, d])
inputs[f"c{c}"], inputs[f"w{c}"] = coordinate, weight
product = finite(coordinate * weight, "output projection product")
products[f"product{c}"] = product
value = finite(value + product, "output projection running sum")
running[f"running{c}"] = value
Y[b, t, d] = value
aliases[f"y{b}{t}{d}"] = value
trace.add(f"output_{b}_{t}_{d}", f"Output [{b},{t},{d}]: joined values times WO",
"product_c=c_c*w_c; running starts at 0; running_c=previous+product_c; value=last running sum",
"Pack WO rows by h*Dv+f, retaining parameter identity as Dv changes. Products and immediate running sums follow ascending joined features. Signed output is allowed; no output normalization is added.",
inputs, {**products, **running, "value": value})
tensors = [tensor("C", [B, T, H*Dv], ["B", "T", "JoinedValue"], C, "Head/within-head feature concatenation of actual OHeads, preserving each copied value."),
tensor("WO", [H*Dv, 2], ["JoinedValue", "D"], WO, "Named output parameters packed in head/feature row order h*Dv+f."),
tensor("Y", [B, T, 2], ["B", "T", "D"], Y, "C times WO via explicit scalar products and sequential running sums; no output softmax.")]
return dict(C=C, WO=WO, Y=Y, aliases=aliases, tensors=tensors)
_JSON_INT = int
def run(derive, defaults):
"""No argument uses defaults; JSON replaces all fields; '-' reads stdin."""
class ParseFault(ValueError):
"""Only locally owned JSON profile/conversion faults."""
def _members(pairs):
value = {}
for key, member in pairs:
if key in value:
raise ParseFault("Duplicate JSON object members are not allowed.")
value[key] = member
return value
def _constant(token):
raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")
def _integer(token):
if token == "-0":
return -0.0
try:
return _JSON_INT(token)
except ValueError as fault:
if type(fault) is not ValueError:
raise
raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from fault
parser = argparse.ArgumentParser(description=derive.__doc__)
parser.add_argument("state", nargs="?")
args = parser.parse_args()
if args.state is not None:
source = sys.stdin.read() if args.state == "-" else args.state
try:
state = json.loads(source, object_pairs_hook=_members,
parse_constant=_constant, parse_int=_integer)
except (json.JSONDecodeError, ParseFault) as error:
result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
else:
result = derive(state)
else:
result = derive(dict(defaults))
print(json.dumps(result, allow_nan=False, separators=(",", ":")))
Declared self-checks are separate later actions, not evidence supplied by displaying a file. In particular, the old IV-39 self-check calls its BPE self-check internally; those are not two independent explicit invocations. The independent oracle is separate from this canonical implementation. Its future assessment must examine the actual produced records rather than import the canonical calculation as its authority.
Recap and bridge
- Retain rotated past K and unrotated past V, together with the exact prefix and model identity.
- Compute a new Q/K/V row at absolute position N, then attend to all N+1 available keys.
- Causality supports reuse; finite metadata and freezing alone cannot certify arbitrary payloads.
- Compare actual operands and differences, not just the predicted ID or a presumed zero error.
Next, IV-49 places a genuine cached append beside a separate full-prefix calculation and distinguishes shared prefill work from each path’s new work.