IV-43 / Part X · Language Modeling
End-to-End Tiny Language-Model Objective
Follow real BPE tokens through embeddings, a causal rotary decoder, stable shifted loss and readout gradients, with complete exact hand examples and editable parameters.
Suppose we are given the letter a and then observe b, followed by the end of the text. How much probability does a small neural network assign to those two observed continuations? Earlier lessons examined pieces of this question separately. Here we join the actual tokenizer, embeddings, causal Transformer block and loss into one calculation whose intermediate numbers remain visible.
Learning objective: Connect token IDs, embeddings, causal block, logits, and shifted loss.
End-to-End Tiny Language-Model Objective
Type a short sequence of a and b to follow real BPE pieces through an embedding, a causal decoder block, class probabilities and a shifted next-token objective. These are hand-set, untrained parameters. The input bound is six UTF-8 bytes and the encoded observed context must fit one to three positions; empty text has no conditional target and is UNAVAILABLE.
Use only raw a/b letters, at most six UTF-8 bytes. Empty text is UNAVAILABLE because there is no observed first piece. Actual BPE input context must contain one to three positions; merges can compress some strings. Nothing is trimmed, normalized or cropped. This hand-set network is untrained.
Full embedding E [5,2]
Full readout U [2,5]
Full readout biases [5]
Exact starting inputs for this saved calculation
validCount 2. lossSum 4.690896604589282. meanNLL 2.345448302294641. perplexity 10.437951036223197. Validate all raw fields before interpreting the text. The first encoded piece is given. Every continuation through EOS is scored; no first-piece probability, cropping or learning update is invented.
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. Every continuation through EOS is scored; no first-piece probability, cropping or learning update is invented.
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
- 2
- byteBound
- 6
- eos
- 1
- corpusUnits
- 4
Follow one observed position through the entire decoder
The raw input is "ab"; strict BPE decoding reconstructed "ab". The fixed training corpus is "abab". A token is an ID naming a byte piece; an embedding supplies its two features. A logit is a class score before normalization. A target is the next observed ID whose probability is scored.
- BPE pieces and one final EOS → observed inputs and shifted targets.
- E gather → feature layer norm → Q/K/V projections → position rotations of Q/K.
- Causal attention → identity output projection → first residual → second layer norm.
- Three-coordinate ReLU FFN → second residual Y → active readout logits and probabilities.
- Target NLL → mean and perplexity → conditional readout derivatives.
Here B=1 batch, D=2 features, H=1 attention head, Dk=Dv=2 head features and T=2 positions. Model active class count V=3 differs from tokenizer vocabulary size 257. Raw E[5,2], U[2,5] and Bias[5] keep the full map; only the active class prefix gets logits/probabilities.
| Position t | Observed input | Compact embedding row | Next observed target | Target compact class | Saved NLL |
|---|---|---|---|---|---|
| 0 | a (ID97) | 0 | b (ID98) | 1 | 2.7593132544120738 |
| 1 | b (ID98) | 1 | EOS (ID512) | 2 | 1.9315833501772082 |
The first piece a (ID97) is given. Every printed target is scored, including final EOS. The saved last-row prediction is b (ID98) with probability 0.7234156524931242; teacher forcing still uses the observed sequence.
Inspecting observed position 0, key 0 and compact class 0. These selectors only inspect the same saved record; the five questions use its starting inputs.
Trace operation setup is selected above. Its matching row is marked current below when that operation belongs to this inspection. Trace and inspection selectors are independent.
Two features, with every residual preserved
| Saved stage | Feature 0 | Feature 1 | Meaning |
|---|---|---|---|
| X | 1 | 0 | Embedding gathered from the observed ID |
| LN1 | 0.4472135954999579 | -0.4472135954999579 | Feature normalization before attention |
| AttentionOutput | 0.4472135954999579 | -0.4472135954999579 | Actual causal P times unrotated V, then identity WO |
| R1 | 1.4472135954999579 | -0.4472135954999579 | X plus attention output |
| LN2 | 0.6876854075163181 | -0.6876854075163181 | Feature normalization of R1 |
| F | 0.6876854075163181 | 0 | Actual FFN output |
| Y | 2.134899003016276 | -0.4472135954999579 | R1 plus F; the readout input |
Inspect both layer norms and both residual additions for this position
Each layer norm uses only this token's two features: population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside the square root. It does not mix positions or batch items. Residual additions require the same named [B,T,D] shape.
| Saved operation | Actual operands | Actual results |
|---|---|---|
| ln1_0_statistics | x0=1 x1=0 epsilon=1 | sum=1 mean=0.5 centered0=0.5 centered1=-0.5 square0=0.25 square1=0.25 squareSum=0.5 variance=0.25 variancePlusEpsilon=1.25 denominator=1.118033988749895 |
| ln1_0_feature_0 | d=0 source=0.5 denominator=1.118033988749895 gamma=1 beta=0 | normalized=0.4472135954999579 scaled=0.4472135954999579 value=0.4472135954999579 |
| ln1_0_feature_1 | d=1 source=-0.5 denominator=1.118033988749895 gamma=1 beta=0 | normalized=-0.4472135954999579 scaled=-0.4472135954999579 value=-0.4472135954999579 |
| residual1_0_0 | t=0 d=0 left=1 right=0.4472135954999579 | value=1.4472135954999579 |
| residual1_0_1 | t=0 d=1 left=0 right=-0.4472135954999579 | value=-0.4472135954999579 |
| ln2_0_statistics | x0=1.4472135954999579 x1=-0.4472135954999579 epsilon=1 | sum=1 mean=0.5 centered0=0.9472135954999579 centered1=-0.9472135954999579 square0=0.8972135954999578 square1=0.8972135954999578 squareSum=1.7944271909999157 variance=0.8972135954999578 variancePlusEpsilon=1.8972135954999578 denominator=1.3773937692250382 |
| ln2_0_feature_0 | d=0 source=0.9472135954999579 denominator=1.3773937692250382 gamma=1 beta=0 | normalized=0.6876854075163181 scaled=0.6876854075163181 value=0.6876854075163181 |
| ln2_0_feature_1 | d=1 source=-0.9472135954999579 denominator=1.3773937692250382 gamma=1 beta=0 | normalized=-0.6876854075163181 scaled=-0.6876854075163181 value=-0.6876854075163181 |
| residual2_0_0 | t=0 d=0 left=1.4472135954999579 right=0.6876854075163181 | value=2.134899003016276 |
| residual2_0_1 | t=0 d=1 left=-0.4472135954999579 right=0 | value=-0.4472135954999579 |
Position rotates matching Q/K feature pairs
| Pair | Absolute position | Original feature 0 | Original feature 1 | Angle in radians | cos(angle) | sin(angle) | Rotated feature 0 | Rotated feature 1 |
|---|---|---|---|---|---|---|---|---|
| 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 single pair's frequency is1, so angle=t radians. Original projections remain separately inspectable. Attention receives the rotated Q/K arrays and unrotated ProjectionVHeads; V is not a rotated pair.
Inspect all four rotation products and both saved sums
| Saved operation | Actual operands | Actual results |
|---|---|---|
| rope_Q_0 | t=0 x0=0.4472135954999579 x1=-0.4472135954999579 base=10000 exponent=0 | frequency=1 angle=0 cos=1 sin=0 product0=0.4472135954999579 product1=0 product2=0 product3=-0.4472135954999579 rotated0=0.4472135954999579 rotated1=-0.4472135954999579 |
| rope_K_0 | t=0 x0=0.4472135954999579 x1=-0.4472135954999579 base=10000 exponent=0 | frequency=1 angle=0 cos=1 sin=0 product0=0.4472135954999579 product1=0 product2=0 product3=-0.4472135954999579 rotated0=0.4472135954999579 rotated1=-0.4472135954999579 |
Causal attention admits only keys at or before the query
| Key j / observed ID | Raw rotated dot | Scaled score | Allowed j<=i | Stored probability | Unrotated V feature 0 | Unrotated V feature 1 |
|---|---|---|---|---|---|---|
| 0 / a (ID97) | 0.39999999999999997 | 0.28284271247461895 | true | 1 | 0.4472135954999579 | -0.4472135954999579 |
| 1 / b (ID98) | -0.2161209223472559 | -0.1528205697480359 | false | 0 | -0.4472135954999579 | 0.4472135954999579 |
A forbidden future key may have a real raw score, but the mask removes it before the row maximum, exponentiation and weighted mixture. Its stored probability is exactly zero. Changing a later numeric input cannot affect earlier Y/logits/probabilities with IDs and positions held fixed. Editing characters can change BPE segmentation, so a character prefix is a different question.
Inspect the selected score, stable key normalization and both value mixtures
| Saved operation | Actual operands | Actual results |
|---|---|---|
| heads_score_0_0_0_0 | b=0 h=0 i=0 j=0 Dk=2 divisor=1.4142135623730951 q0=0.4472135954999579 k0=0.4472135954999579 q1=-0.4472135954999579 k1=-0.4472135954999579 | product0=0.19999999999999998 product1=0.19999999999999998 raw=0.39999999999999997 score=0.28284271247461895 |
| heads_row_0_0_0 | b=0 h=0 i=0 mode=1 shift=0 score0=0.28284271247461895 score1=-0.1528205697480359 allowed0=1 allowed1=0 | max=0.28284271247461895 denominator=1 shifted0=0 term0=1 term1=0 p0=1 p1=0 |
| heads_head_mix_0_0_0_0 | b=0 h=0 i=0 f=0 p0=1 v0=0.4472135954999579 p1=0 v1=-0.4472135954999579 | product0=0.4472135954999579 product1=0 running0=0.4472135954999579 running1=0.4472135954999579 value=0.4472135954999579 |
| heads_head_mix_0_0_0_1 | b=0 h=0 i=0 f=1 p0=1 v0=-0.4472135954999579 p1=0 v1=0.4472135954999579 | product0=-0.4472135954999579 product1=0 running0=-0.4472135954999579 running1=-0.4472135954999579 value=-0.4472135954999579 |
| heads_output_0_0_0 | b=0 t=0 d=0 c0=0.4472135954999579 w0=1 c1=-0.4472135954999579 w1=0 | product0=0.4472135954999579 product1=0 running0=0.4472135954999579 running1=0.4472135954999579 value=0.4472135954999579 |
| heads_output_0_0_1 | b=0 t=0 d=1 c0=0.4472135954999579 w0=0 c1=-0.4472135954999579 w1=1 | product0=0 product1=-0.4472135954999579 running0=0 running1=-0.4472135954999579 value=-0.4472135954999579 |
The FFN computes three real hidden coordinates
| Hidden coordinate m | Affine preactivation Z | ReLU activation |
|---|---|---|
| 0 | 0.6876854075163181 | 0.6876854075163181 |
| 1 | -0.6876854075163181 | 0 |
| 2 | 0 | 0 |
W1 has rows (1,0,0)/(0,1,0), W2 has rows (1,0)/(0,1)/(0,0), and both biases are zero. Coordinate2 therefore computes zero from actual fixed weights; it is not padding. ReLU keeps positive preactivations and replaces nonpositive ones with zero. No derivative through its zero cusp is claimed.
Inspect the FFN's affine products, ReLU and running output sums
| Saved operation | Actual operands | Actual results |
|---|---|---|
| ffn_hidden_0_0_0 | b=0 t=0 m=0 x0=0.6876854075163181 x1=-0.6876854075163181 w0=1 w1=0 bias=0 | product0=0.6876854075163181 product1=0 sum=0.6876854075163181 preactivation=0.6876854075163181 |
| ffn_hidden_0_0_1 | b=0 t=0 m=1 x0=0.6876854075163181 x1=-0.6876854075163181 w0=0 w1=1 bias=0 | product0=0 product1=-0.6876854075163181 sum=-0.6876854075163181 preactivation=-0.6876854075163181 |
| ffn_hidden_0_0_2 | b=0 t=0 m=2 x0=0.6876854075163181 x1=-0.6876854075163181 w0=0 w1=0 bias=0 | product0=0 product1=0 sum=0 preactivation=0 |
| ffn_relu_0_0_0 | b=0 t=0 m=0 preactivation=0.6876854075163181 | activation=0.6876854075163181 |
| ffn_relu_0_0_1 | b=0 t=0 m=1 preactivation=-0.6876854075163181 | activation=0 |
| ffn_relu_0_0_2 | b=0 t=0 m=2 preactivation=0 | activation=0 |
| ffn_output_0_0_0 | b=0 t=0 d=0 h0=0.6876854075163181 w0=1 h1=0 w1=0 h2=0 w2=0 bias=0 | product0=0.6876854075163181 product1=0 product2=0 running0=0.6876854075163181 running1=0.6876854075163181 running2=0.6876854075163181 sum=0.6876854075163181 value=0.6876854075163181 |
| ffn_output_0_0_1 | b=0 t=0 d=1 h0=0.6876854075163181 w0=0 h1=0 w1=1 h2=0 w2=0 bias=0 | product0=0 product1=0 product2=0 running0=0 running1=0 running2=0 sum=0 value=0 |
Final features become active class scores and a target loss
Selected readout readout_0_0: feature products 2.134899003016276 and 0 sum to 2.134899003016276, then bias 0 gives logit 2.134899003016276.
| Compact class / public ID | Logit | Shifted | exp(shifted) | Probability | Observed target? | d meanNLL / d logit |
|---|---|---|---|---|---|---|
| 0 / a (ID97) | 2.134899003016276 | 0 | 1 | 0.8376116959343609 | No | 0.41880584796718046 |
| 1 / b (ID98) | -0.4472135954999579 | -2.582112598516234 | 0.0756140929478022 | 0.063335248630547 | Yes | -0.4683323756847265 |
| 2 / EOS (ID512) | 0 | -2.134899003016276 | 0.11825653332669596 | 0.09905305543509206 | No | 0.04952652771754603 |
Maximum=2.134899003016276; denominator S=1.1938706262744982; ln(S)=0.17720065589584005; saved LSE=2.312099658912116. Computed logits select a (ID97) with stored probability 0.8376116959343609; exact logit ties select the smallest compact class. Rounded probabilities can appear tied even when logits differ.
The observed target is b (ID98), compact row 1. Saved gap 2.582112598516234 plus logS 0.17720065589584005 gives NLL 2.7593132544120738 nats. Total lossSum=4.690896604589282 over 2 scored targets gives meanNLL=2.345448302294641 and perplexity=10.437951036223197.
The chosen class's saved logit derivative is (P−oneHot)/T: indicator 0, probability-minus-indicator 0.8376116959343609, derivative 0.41880584796718046. A derivative measures sensitivity; it is not a learning step or an independent numerical check.
Inspect this class's readout, stable normalization, target and mean reduction
| Saved operation | Actual operands | Actual results |
|---|---|---|
| readout_0_0 | t=0 c=0 y0=2.134899003016276 u0=1 y1=-0.4472135954999579 u1=0 bias=0 | product0=2.134899003016276 product1=0 sum=2.134899003016276 logit=2.134899003016276 |
| class_0_max | z0=2.134899003016276 z1=-0.4472135954999579 z2=0 | max=2.134899003016276 |
| class_0_exp_0 | t=0 c=0 logit=2.134899003016276 max=2.134899003016276 | shifted=0 term=1 |
| class_0_normalize | term0=1 term1=0.0756140929478022 term2=0.11825653332669596 max=2.134899003016276 | running0=1 running1=1.0756140929478022 running2=1.1938706262744982 denominator=1.1938706262744982 logS=0.17720065589584005 lse=2.312099658912116 |
| class_0_probability_0 | t=0 c=0 term=1 denominator=1.1938706262744982 | probability=0.8376116959343609 |
| class_0_argmax | z0=2.134899003016276 z1=-0.4472135954999579 z2=0 | nextRow=0 nextID=97 nextProbability=0.8376116959343609 |
| target_lookup_0 | t=0 targetID=98 V=3 | targetRow=1 |
| loss_0 | t=0 targetID=98 targetRow=1 max=2.134899003016276 targetLogit=-0.4472135954999579 logS=0.17720065589584005 probability=0.063335248630547 | gap=2.582112598516234 nll=2.7593132544120738 |
| reduce_0 | t=0 previousLossSum=0 nll=2.7593132544120738 | lossSum=2.7593132544120738 |
| reduce_1 | t=1 previousLossSum=2.7593132544120738 nll=1.9315833501772082 | lossSum=4.690896604589282 |
| reduction | T=2 lossSum=4.690896604589282 | validCount=2 lossSum=4.690896604589282 meanNLL=2.345448302294641 perplexity=10.437951036223197 |
| gradient_0_0 | t=0 c=0 targetRow=1 probability=0.8376116959343609 T=2 | indicator=0 difference=0.8376116959343609 gradient=0.41880584796718046 |
Readout gradients match all raw U and bias entries
| Full model row / ID | Dependency | dU[0,c] | dU[1,c] | db[c] |
|---|---|---|---|---|
| 0 / a (ID97) | Active class contraction | 0.8877944751077725 | -0.08144875060272931 | 0.4846387417681431 |
| 1 / b (ID98) | Active class contraction | -1.0345319576788132 | 0.7910027992351697 | -0.1066245494381644 |
| 2 / EOS (ID512) | Active class contraction | 0.14673748257104066 | -0.7095540486324403 | -0.3780141923299787 |
| 3 / ab (ID256) | Inactive raw column: structural zero | 0 | 0 | 0 |
| 4 / abab (ID257) | Inactive raw column: structural zero | 0 | 0 | 0 |
These are conditional readout derivatives dU[2,5] and db[5], with final features Y held fixed. Inactive raw columns have zero dependency; they do not become extra classes with fake probabilities. Gradients through E, layer norms, RoPE, attention and the FFN are outside this calculation. All parameters remain hand-set and untrained.
Inspect the selected active class's real gradient products and position sums
| Saved operation | Actual operands | Actual results |
|---|---|---|
| readout_gradient_0_0 | d=0 c=0 y0=2.134899003016276 g0=0.41880584796718046 y1=-0.0959051290352784 g1=0.06583289380096262 | product0=0.8941081872825196 running0=0.8941081872825196 product1=-0.0063137121747471 running1=0.8877944751077725 gradient=0.8877944751077725 |
| readout_gradient_1_0 | d=1 c=0 y0=-0.4472135954999579 g0=0.41880584796718046 y1=1.6078120278761694 g1=0.06583289380096262 | product0=-0.18729566908581152 running0=-0.18729566908581152 product1=0.10584691848308221 running1=-0.08144875060272931 gradient=-0.08144875060272931 |
| bias_gradient_0 | c=0 g0=0.41880584796718046 g1=0.06583289380096262 | running0=0.41880584796718046 running1=0.4846387417681431 gradient=0.4846387417681431 |
Inspect tokenizer rules, expansions and actual saved token operations
Rules: []. Target pieces: ["ID 97, bytes [97]","ID 98, bytes [98]","ID 512: EOS (explicit control), bytes []"]. Expansions: ["[97]","[98]","[]"]. Zero merges requested: no training round or pair selection occurs.
The outer model permits six bytes and at most two merges. Original tokenizer helper evidence retains its inner24-byte/mergeBound4 limits; those larger helper limits do not widen this chapter's input boundary.
| Saved operation | Actual operands | Actual results |
|---|---|---|
| tokenizer_setup | requestedMerges=0 eos=1 | corpusUnits=4 corpusScalars=4 utf16Units=2 scalarCount=2 byteBound=24 mergeBase=256 mergeBound=4 EOS=512 |
| tokenizer_corpus_scalar_0 | scalarIndex=0 utf16Offset=0 utf16Width=1 codePoint=97 unit0=97 | byteOffset=0 byteWidth=1 payload0=97 byte0=97 |
| tokenizer_corpus_scalar_1 | scalarIndex=1 utf16Offset=1 utf16Width=1 codePoint=98 unit0=98 | byteOffset=1 byteWidth=1 payload0=98 byte0=98 |
| tokenizer_corpus_scalar_2 | scalarIndex=2 utf16Offset=2 utf16Width=1 codePoint=97 unit0=97 | byteOffset=2 byteWidth=1 payload0=97 byte0=97 |
| tokenizer_corpus_scalar_3 | scalarIndex=3 utf16Offset=3 utf16Width=1 codePoint=98 unit0=98 | byteOffset=3 byteWidth=1 payload0=98 byte0=98 |
| tokenizer_source_scalar_0 | scalarIndex=0 utf16Offset=0 utf16Width=1 codePoint=97 unit0=97 | byteOffset=0 byteWidth=1 payload0=97 byte0=97 |
| tokenizer_source_scalar_1 | scalarIndex=1 utf16Offset=1 utf16Width=1 codePoint=98 unit0=98 | byteOffset=1 byteWidth=1 payload0=98 byte0=98 |
| tokenizer_target_eos | index=2 eos=1 | id=512 |
| tokenizer_corpus_expand_0 | index=0 id=97 | byteOffset=0 byteWidth=1 byte0=97 |
| tokenizer_corpus_expand_1 | index=1 id=98 | byteOffset=1 byteWidth=1 byte0=98 |
| tokenizer_corpus_expand_2 | index=2 id=97 | byteOffset=2 byteWidth=1 byte0=97 |
| tokenizer_corpus_expand_3 | index=3 id=98 | byteOffset=3 byteWidth=1 byte0=98 |
| tokenizer_corpus_decode_0 | scalarIndex=0 byteOffset=0 byteWidth=1 byte0=97 | payload0=97 accumulator0=97 codePoint=97 utf16Width=1 unit0=97 |
| tokenizer_corpus_decode_1 | scalarIndex=1 byteOffset=1 byteWidth=1 byte0=98 | payload0=98 accumulator0=98 codePoint=98 utf16Width=1 unit0=98 |
| tokenizer_corpus_decode_2 | scalarIndex=2 byteOffset=2 byteWidth=1 byte0=97 | payload0=97 accumulator0=97 codePoint=97 utf16Width=1 unit0=97 |
| tokenizer_corpus_decode_3 | scalarIndex=3 byteOffset=3 byteWidth=1 byte0=98 | payload0=98 accumulator0=98 codePoint=98 utf16Width=1 unit0=98 |
| tokenizer_target_expand_0 | index=0 id=97 | byteOffset=0 byteWidth=1 byte0=97 |
| tokenizer_target_expand_1 | index=1 id=98 | byteOffset=1 byteWidth=1 byte0=98 |
| tokenizer_target_strip_eos | index=2 id=512 | stripped=1 |
| tokenizer_target_decode_0 | scalarIndex=0 byteOffset=0 byteWidth=1 byte0=97 | payload0=97 accumulator0=97 codePoint=97 utf16Width=1 unit0=97 |
| tokenizer_target_decode_1 | scalarIndex=1 byteOffset=1 byteWidth=1 byte0=98 | payload0=98 accumulator0=98 codePoint=98 utf16Width=1 unit0=98 |
| tokenizer_roundtrip | corpusOriginalUnits=4 corpusDecodedUnits=4 corpusDecodedByteCount=4 originalUnits=2 decodedUnits=2 decodedByteCount=2 | corpusTokens=4 tokenCount=3 corpusEqual=1 equal=1 |
All tables index the same detached numerical result. The full inspector below retains every tensor, named axis, dtype, precision and provenance; each trace step retains actual operands and intermediate arithmetic. Floating square roots, trigonometry, exponentials and logarithms are approximations. Perplexities across different tokenizations are not directly comparable.
Inspect all stored values, text metadata and tensor storage
Every scalar output, including flattened operation outputs
Exact text evidence from the same record
These are the stored values, shown without display rounding. Each tensor names its axes, dtype and display precision. Empty arrays are omitted rather than padded.
TokenizerCorpusCodePoints
Scalars=4 · int32 · precision 0 · Validated Unicode scalars in exact input order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
| 3 | 98 |
TokenizerCorpusUTF16Offsets
Scalars=4 · int32 · precision 0 · Zero-based UTF-16 storage offset for each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
TokenizerCorpusUTF16Widths
Scalars=4 · int32 · precision 0 · UTF-16 storage units consumed by each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
TokenizerCorpusByteOffsets
Scalars=4 · int32 · precision 0 · Zero-based UTF-8 byte offset for each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
TokenizerCorpusByteWidths
Scalars=4 · int32 · precision 0 · Actual UTF-8 bytes emitted by each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
TokenizerCorpusBytes
Bytes=4 · int32 · precision 0 · Manual UTF-8 encoding in source order, preserving all data.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
| 3 | 98 |
TokenizerSourceCodePoints
Scalars=2 · int32 · precision 0 · Validated Unicode scalars in exact input order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
TokenizerSourceUTF16Offsets
Scalars=2 · int32 · precision 0 · Zero-based UTF-16 storage offset for each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
TokenizerSourceUTF16Widths
Scalars=2 · int32 · precision 0 · UTF-16 storage units consumed by each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
TokenizerSourceByteOffsets
Scalars=2 · int32 · precision 0 · Zero-based UTF-8 byte offset for each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
TokenizerSourceByteWidths
Scalars=2 · int32 · precision 0 · Actual UTF-8 bytes emitted by each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
TokenizerSourceBytes
Bytes=2 · int32 · precision 0 · Manual UTF-8 encoding in source order, preserving all data.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
TokenizerTrainInitialIDs
Tokens=4 · int32 · precision 0 · 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 |
TokenizerCorpusIDs
Tokens=4 · int32 · precision 0 · Final learned corpus token IDs; corpus training never contains EOS.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 97 |
| 3 | 98 |
TokenizerEncodeInitialIDs
Tokens=2 · int32 · precision 0 · Initial target byte IDs before any ranked application.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
TokenizerTargetIDs
Tokens=3 · int32 · precision 0 · Final target token IDs after all learned ranks, then optional unique EOS tail.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
TokenizerCorpusDecodedBytes
Bytes=4 · int32 · precision 0 · 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 |
TokenizerTargetDecodedBytes
Bytes=2 · int32 · precision 0 · Actual final target ID expansions passed to strict UTF-8 decoding.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
AllClassIDs
ModelRow=5 · int32 · precision 0 · 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 |
ClassIDs
Class=3 · int32 · precision 0 · Active prefix of the full model row map; V=3+merges.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
E
ModelRow=5 × D=2 · float64 · precision 8 · 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 |
U
D=2 × ModelRow=5 · float64 · precision 8 · 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 |
Bias
ModelRow=5 · float64 · precision 8 · 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 |
InputIDs
Position=2 · int32 · precision 0 · Observed public IDs supplied directly to the numeric kernel; active EOS is permitted.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
InputRows
Position=2 · int32 · precision 0 · Compact model row gathered for each observed ID; never index by public ID512.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
X
B=1 × T=2 × D=2 · float64 · precision 8 · 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 |
LN1
B=1 × T=2 × D=2 · float64 · precision 8 · 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 |
ProjectionX
B=1 × T=2 × D=2 · float64 · precision 8 · 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 |
ProjectionWQ
D=2 × QueryFeature=2 · float64 · precision 8 · 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 |
ProjectionWK
D=2 × KeyFeature=2 · float64 · precision 8 · 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 |
ProjectionWV
D=2 × ValueFeature=2 · float64 · precision 8 · 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 |
ProjectionQConcat
B=1 × T=2 × QueryFeature=2 · float64 · precision 8 · 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 |
ProjectionKConcat
B=1 × T=2 × KeyFeature=2 · float64 · precision 8 · 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 |
ProjectionVConcat
B=1 × T=2 × ValueFeature=2 · float64 · precision 8 · 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 |
ProjectionQSplit
B=1 × T=2 × H=1 × Dk=2 · float64 · precision 8 · 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 |
ProjectionQHeads
B=1 × H=1 × T=2 × Dk=2 · float64 · precision 8 · 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 |
ProjectionKSplit
B=1 × T=2 × H=1 × Dk=2 · float64 · precision 8 · 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 |
ProjectionKHeads
B=1 × H=1 × T=2 × Dk=2 · float64 · precision 8 · 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 |
ProjectionVSplit
B=1 × T=2 × H=1 × Dv=2 · float64 · precision 8 · 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 |
ProjectionVHeads
B=1 × H=1 × T=2 × Dv=2 · float64 · precision 8 · 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 |
RotatedQHeads
B=1 × H=1 × T=2 × Dk=2 · float64 · precision 8 · 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 |
RotatedKHeads
B=1 × H=1 × T=2 × Dk=2 · float64 · precision 8 · 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 |
RoPEAngles
Position=2 · float64 · precision 8 · Absolute position t times the single-pair frequency1, in radians.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
RoPECos
Position=2 · float64 · precision 8 · 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 |
RoPESin
Position=2 · float64 · precision 8 · 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 |
Attentionraw
B=1 × H=1 × Query=2 × Key=2 · float64 · precision 8 · 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.2161209223472559 |
| 3 | 0.4000000000000001 |
Attentionscores
B=1 × H=1 × Query=2 × Key=2 · float64 · precision 8 · 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.1528205697480359 |
| 3 | 0.28284271247461906 |
Attentionallowed
B=1 × H=1 × Query=2 × Key=2 · bool · precision 8 · 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 | true |
| 3 | true |
Attentionlogits
B=1 × H=1 × Query=2 × Key=2 · float64 · precision 8 · 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.1528205697480359 |
| 3 | 0.28284271247461906 |
Attentionprobabilities
B=1 × H=1 × Query=2 × Key=2 · float64 · precision 8 · 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.3927748060431144 |
| 3 | 0.6072251939568857 |
AttentionOHeads
B=1 × H=1 × Query=2 × Dv=2 · float64 · precision 8 · 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 |
AttentionC
B=1 × T=2 × JoinedValue=2 · float64 · precision 8 · 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 |
AttentionWO
JoinedValue=2 × D=2 · float64 · precision 8 · 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 |
AttentionOutput
B=1 × T=2 × D=2 · float64 · precision 8 · 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 |
R1
B=1 × T=2 × D=2 · float64 · precision 8 · 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 |
LN2
B=1 × T=2 × D=2 · float64 · precision 8 · 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 |
W1
D=2 × HiddenFeature=3 · float64 · precision 8 · 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 |
b1
HiddenFeature=3 · float64 · precision 8 · Shared hidden bias, added after the two products.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
Z
B=1 × T=2 × HiddenFeature=3 · float64 · precision 8 · 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 |
Hidden
B=1 × T=2 × HiddenFeature=3 · float64 · precision 8 · 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 |
W2
HiddenFeature=3 × D=2 · float64 · precision 8 · 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 |
b2
D=2 · float64 · precision 8 · Shared output bias, added after all three running sums.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
F
B=1 × T=2 × D=2 · float64 · precision 8 · 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 |
Y
B=1 × T=2 × D=2 · float64 · precision 8 · 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 |
Logits
Position=2 × Class=3 · float64 · precision 8 · 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 |
Max
Position=2 · float64 · precision 8 · Maximum computed active class logit at each position.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | 1.6078120278761694 |
Shifted
Position=2 × Class=3 · float64 · precision 8 · 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 |
Terms
Position=2 × Class=3 · float64 · precision 8 · 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 |
Denominator
Position=2 · float64 · precision 8 · Shifted exponential sum from zero in ascending compact class order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.1938706262744982 |
| 1 | 1.3823311626637835 |
LogS
Position=2 · float64 · precision 8 · ln(Denominator), saved for factored NLL.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.17720065589584005 |
| 1 | 0.3237713223010388 |
LSE
Position=2 · float64 · precision 8 · Max+LogS; saved evidence, not subtracted from target logits to compute NLL.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.312099658912116 |
| 1 | 1.9315833501772082 |
P
Position=2 × Class=3 · float64 · precision 8 · 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 |
NextRows
Position=2 · int32 · precision 0 · Highest computed logit; exact ties keep the smallest compact class.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
NextIDs
Position=2 · int32 · precision 0 · Public ID mapped from each computed-logit winner.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
NextProbability
Position=2 · float64 · precision 8 · 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 |
SequenceIDs
Sequence=3 · int32 · precision 0 · Actual ranked BPE result with one final EOS; the first piece is given.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
TargetIDs
Position=2 · int32 · precision 0 · sequence[1:]; final EOS included exactly once as a scored continuation.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 98 |
| 1 | 512 |
TargetRows
Position=2 · int32 · precision 0 · Active compact class of each observed shifted target.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 2 |
TargetLogits
Position=2 · float64 · precision 8 · Actual class logit gathered after computing the entire causal distribution.
| Zero-based storage index | Stored value |
|---|---|
| 0 | -0.4472135954999579 |
| 1 | 0 |
TargetProbability
Position=2 · float64 · precision 8 · Actual target class probability; never rounded before loss computation.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.063335248630547 |
| 1 | 0.14491855990495064 |
TargetGap
Position=2 · float64 · precision 8 · Saved max-targetLogit used in the factored NLL.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.582112598516234 |
| 1 | 1.6078120278761694 |
NLL
Position=2 · float64 · precision 8 · TargetGap+LogS for every shifted target, including EOS.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.7593132544120738 |
| 1 | 1.9315833501772082 |
dLogits
Position=2 × Class=3 · float64 · precision 8 · (P-oneHot(target))/T for the actual mean objective.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.41880584796718046 |
| 1 | -0.4683323756847265 |
| 2 | 0.04952652771754603 |
| 3 | 0.06583289380096262 |
| 4 | 0.3617078262465621 |
| 5 | -0.4275407200475247 |
dU
D=2 × ModelRow=5 · float64 · precision 8 · Conditional readout gradient sum_t Y[t,d]*dLogits[t,c]; inactive raw class columns have structural zero dependency.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8877944751077725 |
| 1 | -1.0345319576788132 |
| 2 | 0.14673748257104066 |
| 3 | 0 |
| 4 | 0 |
| 5 | -0.08144875060272931 |
| 6 | 0.7910027992351697 |
| 7 | -0.7095540486324403 |
| 8 | 0 |
| 9 | 0 |
db
ModelRow=5 · float64 · precision 8 · Conditional readout bias gradient sum_t dLogits[t,c]; inactive raw biases have structural zero dependency.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4846387417681431 |
| 1 | -0.1066245494381644 |
| 2 | -0.3780141923299787 |
| 3 | 0 |
| 4 | 0 |
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 text ab with merges0, then merges1: the observed first piece changes from a to ab. Try ababab with merges1 to inspect three positions, or merges2 to inspect two. The same six letters exceed context capacity with merges0; bbbbbb still exceeds it with merges2 because the fixed corpus learned no bb merge.
All 25 real parameters remain editable and validated, including unused EOS/inactive rows. The full model map includes EOS as an ordinary possible numeric input; this chapter wrapper uses it only as its final target. Readout derivatives hold the decoder features fixed. They do not differentiate the embeddings or block and do not perform training.
Begin with reset text ab and zero merges. Inspect the two input rows and their two targets before changing anything. Then change only e20, the first coordinate of the EOS embedding: the saved parameter changes, but this objective’s numerical predictions and loss should remain unchanged. Later we will explain both this unused row and why an invalid value in it must still be rejected.
Use the lab’s three inspection selectors to choose an Observed position / attention query to inspect, an Attention key position to inspect, and an Active compact readout class to inspect. They only select saved evidence and preserve graded answers. The separate Calculation step control moves through actual arithmetic and clears answers. Input edits and Reset example restore the trace cursor and clear grades; an independent inspection choice may remain selected if it still fits the current shape. Open a parameter disclosure to edit an embedding, readout weight or bias; every field still validates when its disclosure is closed.
All text, weights and biases are disclosed teaching examples. The tokenizer learns a merge table from the fixed toy corpus abab; the neural weights are hand-set and untrained. A training objective is a number that training would try to reduce. Calculating it, and even calculating some derivatives, does not update any parameter or establish learned language ability.
Review IV-33 — A Complete Transformer Block for the pre-normalization block, IV-36 — Rotary Position Embeddings (RoPE) for rotary positions, IV-39 — Byte-Pair Encoding: A Full Merge Trace for actual BPE, and IV-42 — Cross-Entropy, NLL and Perplexity for stable loss. For the older foundations, Book II’s II.9 — Matrix × vector and II.10 — Matrix × matrix as composition explain matrix multiplication; Book III’s III-16 — Multiclass Classification and Softmax Regression explains softmax classification and III-05 — Parameters, Hyperparameters, Loss and Optimization distinguishes parameters, loss and optimization. The earlier neuron and composition lessons, III-40 — From Linear Model to Artificial Neuron and III-41 — Composition and Learned Representations, provide useful forward-calculation background; this chapter adds the tokenized causal objective rather than claiming those forward examples trained a model.
First make the prediction events explicit
A token is a piece represented by an integer ID, a name rather than a measured magnitude. Byte-pair encoding (BPE) repeatedly combines selected adjacent pieces. Here it learns from the fixed corpus abab, counts adjacent byte-ID pairs, breaks equal counts by numeric pair order, replaces disjoint occurrences, and applies the learned rules in rank order to the editable text. Its strict decoder reconstructs the original text. No guessed token sequence replaces that procedure.
With no merges, ab becomes byte IDs [97,98]; appending EOS, the end-of-sequence token, gives [97,98,512]. Shift this one sequence by one place:
| Position t | Observed input ID | Observed next target ID | Compact target class |
|---|---|---|---|
| 0 | 97, a | 98, b | 1 |
| 1 | 98, b | 512, EOS | 2 |
The input list is the full sequence without its last item; the target list is the same sequence without its first item. Thus T=2 prediction events. Teacher forcing means position 1 receives the observed b, even if position 0’s largest score favors a. The first a is given, so we score the conditional continuation b then EOS. There is no probability term for that first a and no claim to compute the unconditional probability of raw text.
The model uses this compact row map:
| Compact row or class c | Public ID | Piece | Default embedding row |
|---|---|---|---|
| 0 | 97 | a | (1,0) |
| 1 | 98 | b | (0,1) |
| 2 | 512 | EOS | (0,0) |
| 3 | 256 | ab | (1/2,1/2) |
| 4 | 257 | abab | (1,1) |
With k learned merges, the active classes are the first V=3+k rows. k is 0, 1 or 2. Public ID512 maps to compact row2; it does not require 513 embedding rows. The tokenizer’s vocabulary has 257+k entries, including bytes unavailable in this tiny neural model. That tokenizer count differs from the model’s active class count V. At reset only a, b and EOS are active; one merge adds ab, and two add abab as well.
EOS has a real embedding row. This full model stores E with shape [5,2], including EOS and both possible merged pieces. The text wrapper’s final EOS is always a target and is excluded from inputs, so its embedding is unused in this objective. The separate numerical forward kernel can accept an active EOS among observed input IDs; stopping generation is a separate policy. The restricted two-row embeddings in IV-40/41 do not define this full model’s interface.
Read the shapes before following the arithmetic
An embedding looks up a token’s row of learned or hand-set features. A tensor is an array with named axes; its shape lists the length of each axis. Our batch contains one sequence (B=1), each token has two features (D=2), and the context contains T=1 to 3 input tokens. An attention head is one independently computed set of query/key/value comparisons. Here H=1, with two query/key features Dk=2 and two value features Dv=2.
| Quantity | Shape; axes | What its entries mean |
|---|---|---|
| E | [5,2]; ModelRow, D | Editable token feature rows |
| InputIDs, TargetIDs | [T]; Position | Public IDs after the one-place shift |
| X, LN1, R1, LN2, F, Y | [1,T,2]; B, T, D | Token features at successive block stages |
| Q, K, value head arrays | [1,1,T,2]; B, H, T, Dk or Dv | Projected features, with Q/K also rotated |
| Attention scores and weights | [1,1,T,T]; B, H, Query, Key | One comparison or mixing weight per query/key pair |
| FFN hidden array | [1,T,3]; B, T, HiddenFeature | Three actual hidden coordinates, M=3 |
| Stored U | [2,5]; D, ModelRow | All editable readout columns; only the first V predict |
| Stored Bias | [5]; ModelRow | All editable biases; only the first V enter logits |
| Logits; class probabilities P | [T,V]; Position, Class | Active class scores and probabilities |
| NLL; dLogits | [T]; [T,V]; Position and Position, Class | Target losses and active logit derivatives |
| Stored dU; stored db | [2,5]; [5]; D, ModelRow and ModelRow | Readout derivatives matching every raw U/bias entry; inactive columns have structural zero dependency |
The displayed U and Bias retain every raw column, including inactive ones. For arithmetic, take U’s first V columns (shape [2,V]) and Bias’s first V entries (shape [V]); these are active prefixes, not additional promised tensor records. Position is the length-T prediction axis, while Class is the length-V active-class axis. The stored dU and db match the full raw parameter shapes; only their first V columns or entries require contractions. Their remaining zeros report no dependency on this objective, without adding inactive softmax classes.
The active output matrix maps a two-feature row to V class scores: [T,2] times [2,V] gives [T,V]. We omit the size-one batch axis only at this readout. Earlier books often wrote a single example as a column vector with weights on the left. Here examples occupy rows and feature-last weights multiply on the right; the shapes explain that change of notation.
There are 27 raw fields: text, integer merges, ten E entries, ten U entries and five biases. e30 means embedding row3/feature 0; u12 means feature 1/class 2; b2 is class 2’s offset. E and U entries range from −2 to2; biases from −4 to4. Reset U has rows (1,0,0,0,0) and (0,1,0,0,0), with all biases0. Inactive rows/columns remain valid raw parameters; they do not receive invented active probabilities.
The following are fixed, not additional learned controls: both feature normalizations use scale gamma=(1,1), offset beta=(0,0), and epsilon 1 inside the square root. Q, K and value projections and the attention output projection are identity matrices, each of shape [2,2]. Each normalization has its own two-entry gamma and beta vectors; their fixed values happen to agree. There is no dropout, padding, attention-score shift or extra block. Only keys j≤i are allowed for query i.
A complete default, from lookup through normalization
We use exact expressions to make the entire example reproducible by hand. They describe real arithmetic; a computer’s square root, trigonometric functions, exp and ln produce floating-point approximations. No evaluated decimal results are asserted here.
Gathering E rows 0 and 1 gives X rows (1,0) and (0,1). Layer normalization treats each token independently: average its two features, subtract that average, compute the population variance (divide by2), then divide centered features by the square root of variance plus epsilon. It does not average across tokens.
For a row (x0,x1), define
Here d is feature 0 or1, μx is this row’s mean, vx its variance, and nd its normalized feature. Multiplication by gamma 1 and addition of beta 0 leave nd unchanged. For each default row, μx=1/2, centered squares are 1/4 and 1/4, vx=(1/4+1/4)/2=1/4, and the denominator is √(5/4)=√5/2. Let α=1/√5. LN1 therefore has rows (α,−α) and (−α,α).
Why normalize? It gives the attention branch a controlled feature scale while the residual path will retain X itself. Epsilon1 is deliberately large enough for this hand example and prevents division by zero for equal features. It changes the result; omitting it would turn these coordinates into ±1 instead of ±α.
Projection, rotary positions, scores and the causal mask
A query supplies the features used to compare the current token; a key supplies the features it is compared with; a value supplies features that attention mixes. The projections use the same LN1 input but are separate matrix operations. Identity weights mean, for row (n0,n1), output coordinate 0 is n0·1+n1·0=n0 and coordinate 1 is n0·0+n1·1=n1. Thus original Q, K and value rows all equal LN1. Splitting the single head and permuting from token-major to head-major storage preserves these indexed values.
Rotary positional encoding (RoPE) rotates the adjacent Q/K feature pair through angle t radians at absolute position t. The sole pair’s frequency is 1. For a pair (v0,v1), write
At t=0, cos0=1 and sin0=0, so rotated Q0 and K0 remain (α,−α). Put c=cos1 and s=sin1. At t=1, original (−α,α) becomes
Each output first forms its two products, then subtracts or adds them. Values are not rotated. The inspector retains original projections separately from the rotated Q/K arrays actually supplied to attention. Position enters comparisons through those rotations; it is not an extra feature appended to X.
For query i and key j, multiply matching rotated features, add both products and divide by √Dk=√2. The dot product measures feature agreement; dividing by the square root of the comparison width controls how its scale grows with that width. It does not make scores sum to one: softmax does that later. Let g=2α²/√2. All four default comparisons are
| i,j | Raw two-product dot sum | Scaled score | Allowed? |
|---|---|---|---|
| 0,0 | α·α+(−α)·(−α)=2α² | g | yes |
| 0,1 | α·[−α(c+s)]+(−α)·[α(c−s)]=−2α²c | −gc | no |
| 1,0 | [−α(c+s)]·α+[α(c−s)]·(−α)=−2α²c | −gc | yes |
| 1,1 | [−α(c+s)]²+[α(c−s)]²=2α² | g | yes |
The last identity uses c²+s²=1 in exact real arithmetic. Raw forbidden scores are recorded evidence, but they do not enter the allowed maximum or exponential normalization. Otherwise even a weight later set to 0 could leave a future-dependent denominator.
An attention softmax subtracts the largest allowed score m, exponentiates allowed differences, stores forbidden terms as exact 0, sums terms in key order and divides. For row0, m=g, terms (1,0), denominator (0+1)+0=1, weights (1,0). For row1, m=g and terms (exp(−g(c+1)),1). Define r=exp(g(1+c)); those terms are (1/r,1), their ordered sum is (0+1/r)+1, and the weights are
A is the attention matrix, distinct from the upcoming class probabilities P. Every query has its own key, so this fixed causal mask never leaves a query without an allowed key. Attention weights describe this mixing operation; they do not establish an explanation of reasoning.
Mix values, keep the residual and apply the real FFN
Each attention output coordinate starts at 0 and adds weight times value in key order. Row0 feature 0 is 0+1·α+0·(−α)=α; feature 1 is 0+1·(−α)+0·α=−α. For row 1 define δ=(r−1)/(r+1). Since cos1 is positive, r>1 and δ>0; this also fixes the signs of the default normalized features used by ReLU below. Its two sums are
The single head is concatenated and multiplied by identity WO, so AttentionOutput has rows (α,−α) and (−αδ,αδ). A residual adds a branch’s output to its input coordinate by coordinate. The first residual R1=X+AttentionOutput is therefore
Both rows still have mean 1/2. Let Δ0=1/2+α and Δ1=1/2+αδ. Row0’s centered features are (Δ0,−Δ0), squared-feature sum2Δ0², varianceΔ0² and denominator√(Δ0²+1). Row1 has centered features (−Δ1,Δ1), varianceΔ1² and denominator√(Δ1²+1). Define ρ0=Δ0/√(Δ0²+1) and ρ1=Δ1/√(Δ1²+1). LN2 rows are (ρ0,−ρ0) and (−ρ1,ρ1).
The feed-forward network (FFN) transforms each row independently, using a three-coordinate hidden layer. Its fixed matrices and biases are
Here b1 and b2 with subscripts on the fixed FFN are vectors; they are different from the editable output-class fields b1 and b2. Multiplication [T,2] by W1 [2,3] gives three preactivations per token. ReLU replaces each negative preactivation with 0 and retains each nonnegative one. This nonlinearity makes the transformation depend on which features are positive; without an intervening nonlinearity, two affine maps could be combined into one. It mixes features within a token, not information across positions.
For input (n0,n1), the preactivations are (n0·1+n1·0+0,n0·0+n1·1+0,n0·0+n1·0+0)=(n0,n1,0). The third 0 is a real computed hidden coordinate with fixed zero weights, not a padded token. Default row0 becomes (ρ0,0,0) after ReLU; row1 becomes (0,ρ1,0). W2 then forms first coordinate h0·1+h1·0+h2·0+0 and second h0·0+h1·1+h2·0+0. FFN outputs F are (ρ0,0) and (0,ρ1).
The second residual Y=R1+F completes the block:
No target has entered this block. The mask makes earlier contextual features independent of later input IDs when tokenization, parameters and absolute positions are held fixed.
Turn those features into every probability and target loss
A readout converts final features into class scores, called logits. For position t and active class c (now a class index, rather than the earlier local abbreviation c=cos1),
The computation stores product0, product1, their sum, then the bias addition. At reset, a’s column (1,0) returns feature 0, b’s column (0,1) returns feature 1, and EOS’s (0,0) with bias 0 returns 0. Abbreviate a0=1+α+ρ0, a1=−αδ and a2=1+αδ+ρ1. These three symbols name final feature values, not tokens. Logit rows are (a0,−α,0) and (a1,a2,0); their largest scores are respectively a0 and a2.
For a row, let m be its maximum over all active classes, v its shifted exponential terms and S their denominator. Class probabilities P and NLL ℓ are
τ is this row’s compact target class. ln is the natural logarithm; exp is its inverse, the exponential function. Negative log-likelihood (NLL) penalizes low probability of the observed target. One-hot cross-entropy gives the same value because only that target class contributes. The trace also retains log-sum-exp m+lnS, but forms NLL in the factored gap-plus-log order above. It never takes ln of a rounded displayed probability.
Here is the entire stable default class calculation:
| Row; target | Maximum; shifts | Exponential terms in class order | Sequential denominator | All class probabilities | Target NLL |
|---|---|---|---|---|---|
| 0; b/class1 | a0; (0,−α−a0,−a0) | (1,exp(−α−a0),exp(−a0)) | S0=((0+1)+exp(−α−a0))+exp(−a0) | (1/S0,exp(−α−a0)/S0,exp(−a0)/S0) | ℓ0=(a0+α)+lnS0 |
| 1; EOS/class 2 | a2; (a1−a2,0,−a2) | (exp(a1−a2),1,exp(−a2)) | S1=((0+exp(a1−a2))+1)+exp(−a2) | (exp(a1−a2)/S1,1/S1,exp(−a2)/S1) | ℓ1=a2+lnS1 |
Every target counts. Thus validCount=2, lossSum=(0+ℓ0)+ℓ1, meanNLL=(ℓ0+ℓ1)/2, and perplexity=exp(meanNLL). Write Z0=exp(a0)+exp(−α)+1 and Z1=exp(a1)+exp(a2)+1. In exact real arithmetic the continuation likelihood is [exp(−α)/Z0]·[1/Z1], ℓ0=lnZ0+α, ℓ1=lnZ1, and
The stable route computes the same real quantity without exponentiating large unshifted scores. Perplexity is the reciprocal geometric mean of the two target probabilities, not accuracy or exp of the loss sum. Argmax, the largest-score choice, is selected from actual computed logits; exact score ties choose the smallest compact class. Rounded printed probabilities can appear tied even when their underlying logits differ.
What gradients are actually provided?
A gradient records how a small parameter change affects a scalar objective. Hold the final features Y, token IDs and targets fixed, and differentiate this mean NLL with respect to the readout only. Define G=dLogits and the indicator I(t,c), equal to 1 if c is position t’s target class and 0 otherwise:
Why does probability appear in the derivative? For one row, write ℓ=ln(Σ exp(zc))−zτ before differentiating. The derivative of the log of the sum with respect to zc is exp(zc)/Σ exp(zj)=Pc; the derivative of the target score is the indicator I(t,c). Their difference is Pc−I(t,c). The stable shifted calculation evaluates this same real function.
The factor 1/T comes from averaging T target losses. Each U entry contributes to a logit multiplied by the corresponding Y feature, which explains that product in dU. Each bias is added directly, which explains db’s unweighted sum. Parameter sharing across tokens explains why both derivatives sum over positions.
At default T=2, the complete G rows are (P00/2,(P01−1)/2,P02/2) and (P10/2,P11/2,(P12−1)/2), where Ptc names row t/class c of the class table above. For each active class c, all readout cells are
Products and running sums are saved in position order. Inactive U/bias columns have structural zero dependency on this objective, without being extra softmax classes. These are conditional readout derivatives. There is no computed gradient for E, attention, normalization, rotary positions or the FFN, and no optimizer step. At a ReLU preactivation of 0 a full-block derivative would additionally need an explicit subgradient convention; that issue does not invalidate this smooth readout calculation with Y fixed.
Work the compressed examples all the way through
Set text ab, merges 1, and keep all numerical parameters at reset. The learned merge maps a,b to ID256. The full sequence is [256,512], input [256], target [512], T=1 and V=4. E row 3 gives X=(1/2,1/2). Its mean is1/2, centered coordinates 0, variance 0, denominator√(0+1)=1, so LN1=(0,0). Identity projections and position0 rotation retain zeros. The one allowed attention score is 0; maximum 0 gives exp0=1, denominator 1 and attention weight 1. Its value is zero, hence AttentionOutput=(0,0).
R1=(1/2,1/2)+(0,0)=(1/2,1/2). LN2 again has zero centered coordinates and output (0,0). All three FFN preactivations, ReLU outputs and both output coordinates are 0. The second residual therefore leaves Y=(1/2,1/2). The readout now has four active classes: logits (1/2,1/2,0,0). Maximum 1/2 gives shifts (0,0,−1/2,−1/2), terms (1,1,exp(−1/2),exp(−1/2)) and sequential sum S=(((0+1)+1)+exp(−1/2))+exp(−1/2).
Let Z=2exp(1/2)+2. The full probabilities are (exp(1/2)/Z,exp(1/2)/Z,1/Z,1/Z). EOS is class 2, so NLL=(1/2−0)+lnS=lnZ, count 1, sum=mean=lnZ and perplexityZ. The extra ab output class contributes a real denominator term even though the observed target is EOS. G is P minus (0,0,1,0); db=G and both dU feature rows equal G/2. These are the full conditional readout derivatives for this example.
Now set text abab, merges 2, with reset parameters. First a,b merges to 256; the second rule combines256,256 to 257. Sequence [257,512] gives T=1,V=5, X=(1,1). Both normalizations and attention/FFN branches again output zeros by the same mean/centering steps, while residuals retain Y=(1,1). Logits are (1,1,0,0,0), maximum 1, shifts (0,0,−1,−1,−1), terms (1,1,exp(−1),exp(−1),exp(−1)), and S=((((0+1)+1)+exp(−1))+exp(−1))+exp(−1).
Put Z=2exp(1)+3 for this second example. P is (exp(1)/Z,exp(1)/Z,1/Z,1/Z,1/Z); EOS NLL=1+lnS=lnZ, meanlnZ and perplexityZ. Here G=P−(0,0,1,0,0), db=G and both dU rows equal G. These examples show why zero normalized features do not imply zero final features: the residual still carries the constant input.
Do not compare these perplexities as evidence of improved neural learning. Compression changes the first given piece, the active classes and the number of scored targets. It has not updated a neural weight. It can even make the entire content one given token so that the only scored event is EOS.
Try limits that test the explanation
Set every E entry to 0 and keep all biases0; U can be any valid value. Both branches and residuals now produce Y=0. Every active logit is0, each shifted term 1, S=V and P=1/V. Every NLL is lnV, meanlnV and perplexityV. Active dU is exactly0 because each derivative multiplies a zero feature. db need not be 0: for the default b and EOS targets at V=3 it is (1/3,−1/6,−1/6). Equal probabilities do not make the target-dependent gradient disappear.
A different constant embedding (q,q) with any valid q produces zero normalized branches but retains Y=(q,q) through residuals. Its logits depend on U and bias and need not be uniform. This is the distinction between “normalization centers a constant row to zero” and “the whole residual block erases a constant row.”
At reset, changing valid e20 or e21 alters saved E metadata but leaves this wrapper’s Y, logits and loss unchanged: EOS is not an input. Likewise inactive row 3/4 embeddings and inactive U/bias columns do not affect this zero-merge objective. Compare dependent numerical quantities, not the entire record, which honestly preserves changed inputs. An out-of-range inactive value must still make the whole state unavailable.
To reason about causality, hold parameters, positions and an input-ID prefix fixed, then change a later input ID in the numerical kernel. Earlier Y/logits/class probabilities must remain unchanged. A raw score against a forbidden future key can change; it is excluded from normalization. Changing raw text under BPE is a different experiment: it may resegment the token prefix, so character-prefix equality alone does not prove the earlier numerical inputs stayed fixed.
Invalid input is a visible result, not a repaired example
The toy model accepts only raw a/b text, at most 6 UTF-8 bytes, and T=1 to 3 actual input tokens after BPE. It preserves the draft: no trim, normalization, unknown-token substitution or context cropping. Empty text has no conditional target and gives UNAVAILABLE; no mean 0 or perplexity 1 is invented. Unsupported alphabet such as ac gives UNAVAILABLE. Text aaaa at zero merges fits the byte bound but has four input tokens and gives UNSUPPORTED_SIZE. Six letters such as ababab exceed context without merges; after the first merge they become three ab pieces and fit. Compression changes actual context length, not a cosmetic counter.
Boundary order matters. The whole state first needs exactly the declared own fields and an actual string. All numeric fields then validate in declared order, including inactive ones. For text semantics, more than 6 UTF-16 code units gives UNSUPPORTED_SIZE first; strict UTF-8 encoding then rejects an unpaired surrogate as INVALID_INPUT; the actual 6-byte bound precedes the toy alphabet check; tokenized context size is checked without truncation. UTF-16 code units and UTF-8 bytes are different units even though ordinary a/b has one of each. Nonfinite parameters or values outside the stated ranges cannot leave an old successful result displayed.
In exact real arithmetic a normalized two-feature coordinate has magnitude below 1 because epsilon 1 is positive. Identity value/output projections and convex attention mixing keep each branch coordinate below 1. Since |X|≤2, |R1|<3; the fixed FFN has each output below 1; hence |Y|<4. Two readout products with |U|≤2 and a bias of magnitude≤4 give |logit|≤20, and NLL≤40+ln5. Mean NLL and its exponential remain finite in this bounded lesson. These real bounds do not make ideal sqrt/trig identities exactly representable: later numerical checks must include floating-point and library uncertainty.
Read the maintained Python and its entire local dependency closure
The following seven disclosures show actual maintained files through raw-source imports. They require NumPy and the Python standard library and must retain their relative repository locations. Displaying source is not evidence of execution or parity validation.
1. Chapter wrapper — code/python/p10/iv43.py. This is the chapter entry point and complete-state command-line interface. A supplied JSON state replaces defaults rather than silently filling missing fields; - reads JSON from standard input. Read the wrapper’s comments and the tiny helper together.
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 — End-to-End Tiny Language-Model Objective, canonical NumPy wrapper.
Given the first actual learned BPE piece, score every continuation through EOS.
The explicit dependency closure is tiny_reference.py plus the unchanged p09
bpe/token, p06 head and p07 component/FFN sources. Copy the relative directory
structure when running from another location. All loaders use __file__.
The five-row E[5,2] and five-column raw U[2,5] are hand-set, editable parameters.
A full causal decoder computes features; analytic derivatives cover the full raw
readout U/bias shapes at FIXED features (inactive columns have zero dependency).
No parameter update or learned capability is claimed. Different tokenizers define different conditional events and PPL units.
Source-authored under the FluxGeo hold; all execution/validation is DEFERRED.
"""
import importlib.util
import math
from pathlib import Path
from types import MappingProxyType
_spec = importlib.util.spec_from_file_location(
"_p10_tiny_reference", Path(__file__).resolve().with_name("tiny_reference.py"))
if _spec is None or _spec.loader is None:
raise ImportError("Cannot load adjacent canonical tiny_reference.py.")
_helper = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_helper)
DEFAULT_IV43 = MappingProxyType(dict(_helper.DEFAULT_IV43))
@_helper.guarded
def derive_iv43(state):
"""Compute the real tiny decoder, conditional objective and readout gradients."""
return _helper.derive43(state)
def source_self_check():
"""DEFERRED explicit wrapper check; never invoked by import or CLI query.
Future V5 separately calls tiny_reference.source_self_check and the old
BPE helper check once each; this wrapper does not silently call either.
"""
assert __debug__, "Deferred checks require assertions enabled."
s = dict(DEFAULT_IV43)
result = derive_iv43(s)
assert list(result) == ["status", "outputs", "steps", "tensors", "texts"]
summary_names = ["validCount", "lossSum", "meanNLL", "perplexity", "classCount", "actualMerges", "contextLength",
"B", "D", "H", "Dk", "Dv", "hiddenWidth", "byteBound", "nextRow", "nextID", "nextProbability",
"tokenizer_corpusBytes", "tokenizer_byteCount", "tokenizer_actualMerges", "tokenizer_tokenCount",
"tokenizer_requestedMerges", "tokenizer_corpusTokens", "tokenizer_eos", "tokenizer_byteBound",
"tokenizer_vocabularyItems", "tokenizer_corpusEqual", "tokenizer_equal"]
assert list(result["outputs"])[:28] == summary_names
assert list(result["outputs"])[28:] == [f"{step['id']}_{key}" for step in result["steps"] for key in step["outputs"]]
assert len(result["steps"]) == 159 and len(result["tensors"]) == 85
assert result["outputs"]["byteBound"] == 6 and result["outputs"]["tokenizer_byteBound"] == 24
token_setup = next(step for step in result["steps"] if step["id"] == "tokenizer_setup")
assert token_setup["outputs"]["mergeBound"] == 4
for step in result["steps"]:
assert list(step) == ["id", "label", "equation", "explanation", "inputs", "outputs"]
assert all(step[key] for key in ("label", "equation", "explanation"))
assert all(type(value) in (int, float) and math.isfinite(value) for fields in (step["inputs"], step["outputs"]) for value in fields.values())
contraction = next(step for step in result["steps"] if step["id"] == "readout_gradient_0_0")
assert list(contraction["outputs"]) == ["product0", "running0", "product1", "running1", "gradient"]
for identifier, shape in (("E", [5, 2]), ("U", [2, 5]), ("Bias", [5]), ("dU", [2, 5]), ("db", [5])):
assert next(t for t in result["tensors"] if t["id"] == identifier)["shape"] == shape
raw_du = next(t for t in result["tensors"] if t["id"] == "dU")["values"]
raw_db = next(t for t in result["tensors"] if t["id"] == "db")["values"]
assert [raw_du[i] for i in (3, 4, 8, 9)] == [0, 0, 0, 0] and raw_db[3:] == [0, 0]
assert list(result["texts"]) == ["input", "decoded", "objective", "gradientScope", "modelVocabulary",
"tokenizer_corpus", "tokenizer_input", "tokenizer_corpusDecoded", "tokenizer_decoded",
"tokenizer_corpusLabels", "tokenizer_corpusExpansions", "tokenizer_targetLabels", "tokenizer_targetExpansions",
"tokenizer_ruleLabels", "tokenizer_ruleExpansions", "tokenizer_trainingStop"]
assert result["outputs"]["validCount"] == 2
assert result["texts"]["input"] == "ab"
# Exact-real transfer anchors, compared as approximations after libm rounding.
for text, merges, expected in (("ab", 1, 2 * math.exp(0.5) + 2), ("abab", 2, 2 * math.e + 3)):
transfer = derive_iv43({**s, "text": text, "merges": merges})
assert transfer["outputs"]["validCount"] == 1
assert len(transfer["tensors"]) == (96 if merges == 1 else 104)
assert math.isclose(transfer["outputs"]["perplexity"], expected, rel_tol=1e-12)
assert math.isclose(transfer["outputs"]["meanNLL"], math.log(expected), rel_tol=1e-12)
single = derive_iv43({**s, "text": "a"})
assert single["outputs"]["validCount"] == 1 and single["outputs"]["classCount"] == 3
zero = {key: 0 for key in s if key.startswith("e")}
uniform = derive_iv43({**s, **zero})
assert math.isclose(uniform["outputs"]["perplexity"], 3, rel_tol=1e-12)
assert all(value == 0 for value in next(t for t in uniform["tensors"] if t["id"] == "dU")["values"])
unused = derive_iv43({**s, "e20": 2, "e21": -2, "u04": 2, "u14": -2, "b4": 4})
for key in ("validCount", "lossSum", "meanNLL", "perplexity"):
assert unused["outputs"][key] == result["outputs"][key]
for patch, code in (({"text": ""}, "UNAVAILABLE"), ({"text": "c"}, "UNAVAILABLE"),
({"text": "a" * 7}, "UNSUPPORTED_SIZE"), ({"text": "\ud800"}, "INVALID_INPUT"),
({"text": "ababab"}, "UNSUPPORTED_SIZE"), ({"e40": 3}, "INVALID_INPUT"),
({"u04": True}, "NONFINITE"), ({"b4": 10**1000}, "NONFINITE"),
({"text": "\ud800", "b4": float("inf")}, "NONFINITE"),
({"text": [], "merges": float("nan")}, "INVALID_INPUT")):
fault = derive_iv43({**s, **patch})
assert list(fault) == ["status", "code", "reason"] and fault["code"] == code
assert derive_iv43({})["code"] == "INVALID_INPUT"
assert derive_iv43({**s, "extra": 0})["code"] == "INVALID_INPUT"
# Saved outputs are ordinary detached JSON; mutating them cannot alter defaults.
result["outputs"]["meanNLL"] = -1
result["steps"][0]["outputs"].clear()
result["tensors"][0]["values"][0] = -1
assert derive_iv43(s)["outputs"]["meanNLL"] >= 0
assert s == dict(DEFAULT_IV43)
if __name__ == "__main__":
_helper.run(derive_iv43, DEFAULT_IV43)
2. Full numerical composition — code/python/p10/tiny_reference.py. Start with the complete raw defaults and validation, then follow the text wrapper into BPE and the separate ID-based forward computation. Track gather → LN1 → projections → Q/K rotation → causal attention → WO → R1 → LN2 → FFN → Y, then the class readout, shifted losses and readout derivatives. Real NumPy arrays store numerical tensors; detached ordinary containers describe the result.
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)
3. Actual learned BPE — code/python/p09/bpe_reference.py. This source owns pair counting, numeric tie order, disjoint replacements, ranked target application and expansion. The corpus is the disclosed abab; it is not a pretrained tokenizer.
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]))]))
4. Actual strict codec — code/python/p09/token_reference.py. Follow scalar validation, UTF-8 byte construction and strict decoding before treating a text token as an ID. This helper supplies integer token evidence; it is not used as an integer-only container for neural arithmetic.
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=(",", ":")))
5. Actual head computation — code/python/p06/head_reference.py. project_heads, attend_heads and join_heads implement the separate scalar products, layout changes, allowed-key softmax, value products/running sums and output projection. The composition explicitly supplies identity WO; the older helper’s default WO is a different teaching example.
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=(",", ":")))
6. Actual normalization and residual primitives — code/python/p07/component_reference.py. feature_norm supplies each mean, centered square, population variance and epsilon-inside-root division. same_shape_add requires equal shapes before adding residual coordinates. Follow the trace’s actual float precision rather than reading these values as token integers.
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=(",", ":")))
7. Actual three-coordinate FFN — code/python/p07/ffn_reference.py. feed_forward computes all three hidden affine coordinates, their ReLUs and both output coordinates from the fixed matrices shown above.
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)
The local loaders resolve paths from each file’s __file__. The unchanged FFN’s bare component_reference import is explicitly bound to the intended canonical module while loading and its previous binding is restored afterward. This prevents an unrelated working-directory module from supplying the numerical primitive. The closure needs no earlier p10a affine predictor, full-block wrapper or private rotary module. Declared self-checks and command-line examples are not automatic evidence of correctness.
Use the five graded checks to explain the mechanism
The lab contains exactly five questions. They refer to this saved starting state; moving through its trace does not turn a later inspected operation into a different training example. An input edit, reset or trace selection clears previous answers so feedback cannot belong to an older calculation.
- Causal inputs and later targets. Explain which observed prefix can enter the block before logits exist. The target selects a loss from an already computed distribution; it does not supply the answer to attention.
- Compact shapes in the current state. Read the current T and V, then distinguish the full E/U/Bias parameter storage from the active logit matrix. Public ID512 is a label mapped to row2, not a demand for 513 rows.
- The live factored objective. Read the actual first saved gap, logS and NLL. With one target, its loss is already the mean; with several, sum every target loss and divide by their count. In both branches include EOS and exponentiate the mean for perplexity.
- An unused EOS embedding. Predict what changes when valid e20/e21 change. Raw parameter evidence changes, while this wrapper’s dependent features, probabilities, losses and readout derivatives remain the same. A numeric call that actually observes EOS has a different dependency.
- A compressed transfer and its limit. Recompute ab with one merge. Centered branches vanish, the residual retains Y=(1/2,1/2), and the only target is EOS with real-arithmetic perplexity2exp(1/2)+2. Explain why changing the given first piece, vocabulary and scored events prevents a direct claim of better learning.
Every option in the live questions receives a corrective explanation after selection. For the third question, compare its displayed numbers with the saved trace rather than memorizing the default. For the transfer question, keep the parameters at reset so the stated constant-vector calculation applies.
Recap and bridge
- Tokenization determines the actual observed input/target pairs; the first piece is given and final EOS is counted.
- The causal block computes features through every normalization, rotation, attention product, residual and FFN stage before a target is scored.
- Stable class softmax gives actual target NLL; the mean divides by T and perplexity exponentiates that mean.
- Readout gradients hold Y fixed. No parameters are updated, and compression is not neural learning.
The next chapter, IV-44, distinguishes processing an observed prompt from computing one subsequent decode step. Its numerical input is an existing token-ID prefix; this chapter’s separate forward kernel makes that distinction possible without re-tokenizing generated IDs.