IV-47 / Part XI · Autoregressive Inference
Complete Autoregressive Generation Trace
Trace two actual uncached model calls, their last-row conditional choices and exact seed draws, then distinguish emitted IDs, consumed inputs and EOS, budget or context stopping.
Review the ideas this chapter uses
Suppose the supplied prompt is a. Choosing another a produces aa; choosing a again produces aaa. What did the model actually process to make those two choices? This chapter joins the tokenizer, numerical forward calculation and explicit choice policy into one short loop whose input prefix is visible at every call.
Learning objective: Generate a short sequence with inspectable logits and deterministic RNG.
Complete Autoregressive Generation Trace
Generate at most two actual IDs with the same hand-set tiny decoder. Reset starts from a, processes[97] then[97,97], and retains the repeated logical result[97,97,97]. The final a is emitted but has not been processed by an extra model call. Choose greedy for zero RNG draws or seeded sampling to inspect every real filter and draw.
Use raw a/b letters only, at most six UTF-8 bytes and one to three actual BPE prompt tokens. Fixed corpus abab learns at most two merges. Empty text is UNAVAILABLE; longer contexts are reported, never cropped. All 33 raw fields validate, including sampling controls in greedy mode.
Full embedding E [5,2]
Full readout U [2,5]
Full readout biases [5]
Exact starting inputs for this saved calculation
generatedTokens 2. modelCalls 2. workTokens 3. finalSeed 1196435762. Validate every raw field, then tokenize the prompt exactly once. All 33 raw fields validate even in greedy mode. The real tokenizer, full-prefix forward kernel and strict reverse decoder retain their complete evidence.
Validate every raw field, then tokenize the prompt exactly once
strategy0 greedy or1 sampling; maxNew1..2; observed context<=3; fixed corpus abab, EOS off
All 33 raw fields validate even in greedy mode. The real tokenizer, full-prefix forward kernel and strict reverse decoder retain their complete evidence.
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
- strategy
- 1
- temperature
- 1
- topK
- 3
- topP
- 1
- seed
- 0
- maxNew
- 2
Saved outputs
- utf16Units
- 1
- byteBound
- 6
- promptTokenBound
- 3
- promptTokens
- 1
- classCount
- 3
Follow emitted IDs through the actual calls
Input "a" was tokenized once as [97]. Emitted IDs: [97,97]. Retained logical result: [97,97,97]. Strict reverse decoding produced "aaa" from actual bytes [97,97,97].
Stop reason: TOKEN_BUDGET, code2. After each append the order is EOS, then new-token budget, then whether another call would exceed three observed tokens. Model calls=2; total token rows recomputed=3; full raw score cells=5; generated IDs actually consumed by later calls=1.
Final processed prefix [97,97]; pending logical tail ID97 at slot2. That tail has no extra embedding gather, RoPE row, logits or probabilities computed from it. A three-token prompt may emit a fourth logical ID while only three inputs were processed. Repetition is allowed.
Sampling: temperature, full stable P, public-ID score ties, top-k, top-p, final normalization, ascending-public-ID CDF; one LCG draw per decision. First call is prefill; subsequent call is uncached full-prefix decode at absolute positions 0..T-1. cacheUsed=0, cacheEntries=0. Final seed=1196435762; actual RNG draw count=2.
| Call / phase | Observed input IDs | Selected last row | Logical output slot | Emitted public ID | Raw model P at selected row | Temperature-base P | Final sampling-policy P | Fed into a later call? | Work / cumulative work | Seed before → after | Stop code |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 / Prefill | [97] | 0 | 1 | a / ID97 | 0.8376116959343609 | 0.8376116959343609 | 0.837611695934361 | Yes | 1 / 1 | 0 → 1013904223 | 0 |
| 1 / Uncached decode | [97,97] | 1 | 2 | a / ID97 | 0.8376116959343609 | 0.8376116959343609 | 0.837611695934361 | No — final pending tail | 2 / 3 | 1013904223 → 1196435762 | 2 |
Raw model P comes from the actual unscaled last-row distribution at the selected compact class, even when sampling chooses a non-greedy class. The temperature-base distribution comes before filtering; final sampling-policy P comes after both filters. A greedy decision is deterministic but its raw model P need not be1. No sampled arrays, sampled probability or random draw is created in greedy mode.
Inspecting saved call0, observed position0, key0, compact class0. These selectors read immutable evidence and leave exercise answers unchanged.
Trace operation setup is selected above. Matching operation rows below are marked current; call/query/key/class inspection is independent.
Call0: full observed prefix at absolute positions0..0
B=1 batch, T=1 observed tokens, D=2 features, H=1 attention head, Dk=Dv=2, three FFN hidden features, V=3 active classes. Full E[5,2], U[2,5] and Bias[5] retain inactive parameters; model probability arrays are only [1,3]. Public IDs label compact rows.
| Absolute position | Input ID | Compact gather row | Strict-logit greedy ID | Its raw model P |
|---|---|---|---|---|
| 0 | a / ID97 | 0 | 97 | 0.8376116959343609 |
| Stage | Feature0 | Feature1 | Meaning |
|---|---|---|---|
| X | 1 | 0 | Actual compact embedding gather |
| LN1 | 0.4472135954999579 | -0.4472135954999579 | Feature-only layer norm of X |
| AttentionOutput | 0.4472135954999579 | -0.4472135954999579 | Causal value mixture and output projection |
| R1 | 1.4472135954999579 | -0.4472135954999579 | X plus AttentionOutput |
| LN2 | 0.6876854075163181 | -0.6876854075163181 | Feature-only layer norm of R1 |
| F | 0.6876854075163181 | 0 | Actual ReLU FFN output |
| Y | 2.134899003016276 | -0.4472135954999579 | R1 plus F |
Both layer norms use this row's two features, population variance and epsilon1 inside the square root, with gamma(1,1), beta(0,0). Residuals add identical named [B,T,D] shapes. No target, loss, gradient or parameter update is evaluated.
| Pair / absolute position | Unrotated pair | Angle | Cosine / sine | Actual rotated pair |
|---|---|---|---|---|
| Q / 0 | [0.4472135954999579,-0.4472135954999579] | 0 | 1 / 0 | [0.4472135954999579,-0.4472135954999579] |
| K / 0 | [0.4472135954999579,-0.4472135954999579] | 0 | 1 / 0 | [0.4472135954999579,-0.4472135954999579] |
| Key / public ID | Raw Q·K | Scaled score | Allowed? | Stored attention probability | Unrotated V pair |
|---|---|---|---|---|---|
| 0 / ID97 | 0.39999999999999997 | 0.28284271247461895 | true | 1 | [0.4472135954999579,-0.4472135954999579] |
Q and K rotate at their actual absolute positions; V stays unrotated. Scores divide by sqrt2. Future cells retain their real raw scores but have exactly zero attention probability. Attention weights are numerical mixture coefficients, not explanations of a trained model's reasoning.
| Hidden feature | Affine preactivation | ReLU activation |
|---|---|---|
| 0 | 0.6876854075163181 | 0.6876854075163181 |
| 1 | -0.6876854075163181 | 0 |
| 2 | 0 | 0 |
| Compact / public ID | Computed logit | Shifted logit | Exponential term | Raw model P |
|---|---|---|---|---|
| 0 / a ID97 | 2.134899003016276 | 0 | 1 | 0.8376116959343609 |
| 1 / b ID98 | -0.4472135954999579 | -2.582112598516234 | 0.0756140929478022 | 0.063335248630547 |
| 2 / EOS ID512 | 0 | -2.134899003016276 | 0.11825653332669596 | 0.09905305543509206 |
Saved model max=2.134899003016276, denominator=1.1938706262744982, logS=0.17720065589584005, LSE=2.312099658912116. Only the actual last computed row0 selects an emission at logical slot1; other rows remain genuine evidence, not extra decisions.
| Operation and equation | Explanation | Actual inputs | Actual outputs |
|---|---|---|---|
| call0_decision greedy: saved strict-logit argmax, zero draws; sampling: actual sampleNext on saved last-row logits, one draw | The raw model probability is gathered at the selected compact row of the actual unscaled last-row P. Sampling additionally saves the selected temperature-base and final-policy probabilities, which need not equal the raw model P. | callIndex=0 observedLength=1 lastRow=0 outputPosition=1 strategy=1 seedBefore=0 | selectedRow=0 selectedID=97 selectedModelProbability=0.8376116959343609 selectedTemperatureBaseProbability=0.8376116959343609 selectedSamplingProbability=0.837611695934361 seedAfter=1013904223 rngDrawCount=1 cacheUsed=0 cacheEntries=0 |
| call0_append ResultIDs append selectedID; stopCode=EOS?1:budget?2:nextContext>3?3:0 | A terminal emitted ID remains a pending logical output. It has no fabricated neural row. Only a continuing non-EOS ID becomes part of the next full-prefix input; tokenization is not repeated. | selectedID=97 EOS=512 outputPosition=1 maxNew=2 contextLimit=3 | generatedTokens=1 logicalResultTokenCount=2 stoppedEOS=0 budgetReached=0 contextExceeded=0 stopCode=0 continueLoop=1 |
Inspect every actual operation of this full-prefix neural call
| Operation and equation | Explanation | Actual inputs | Actual outputs |
|---|---|---|---|
| call0_input_0 inputRow=compactRow(inputID); X[0,t,:]=E[inputRow,:] | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: EOS is an ordinary available embedding row in this numeric kernel. There is no implicit stop rule or target lookup. | t=0 inputID=97 | inputRow=0 x0=1 x1=0 |
| call0_ln1_0_statistics sum=x0+x1; mean=sum/2; centered=x-mean; squareSum=centered0²+centered1²; variance=squareSum/2; denominator=sqrt(variance+epsilon) | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Only these two features contribute. Epsilon is inside the square root; no batch or token statistics are mixed. | x0=1 x1=0 epsilon=1 | sum=1 mean=0.5 centered0=0.5 centered1=-0.5 square0=0.25 square1=0.25 squareSum=0.5 variance=0.25 variancePlusEpsilon=1.25 denominator=1.118033988749895 |
| call0_ln1_0_feature_0 normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: The source is the saved centered feature. Gamma and beta may change output mean and variance. | d=0 source=0.5 denominator=1.118033988749895 gamma=1 beta=0 | normalized=0.4472135954999579 scaled=0.4472135954999579 value=0.4472135954999579 |
| call0_ln1_0_feature_1 normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: The source is the saved centered feature. Gamma and beta may change output mean and variance. | d=1 source=-0.5 denominator=1.118033988749895 gamma=1 beta=0 | normalized=-0.4472135954999579 scaled=-0.4472135954999579 value=-0.4472135954999579 |
| call0_heads_setup D=2; X[B,T,2]; WQ,WK[2,H*Dk]; WV[2,H*Dv] | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: All inactive fields remain finite and bounded. Parameter names identify input d, head h and feature f, so changing width never relabels a head’s weights. | B=1 T=1 H=1 Dk=2 Dv=2 x000=0.4472135954999579 x001=-0.4472135954999579 x010=0 x011=1 x020=1 x021=1 x100=1 x101=1 x110=-1 x111=0 x120=0 x121=2 wq000=1 wq001=0 wq010=0 wq011=1 wq100=0 wq101=1 wq110=1 wq111=0 wk000=1 wk001=0 wk010=0 wk011=1 wk100=0 wk101=1 wk110=1 wk111=0 wv000=1 wv001=0 wv010=0 wv011=1 wv100=0 wv101=1 wv110=1 wv111=0 mode=1 valid0=1 valid1=1 valid2=1 shift=0 wo000=1 wo001=0 wo010=0 wo011=1 wo100=1 wo101=-1 wo110=0 wo111=0.5 | B=1 T=1 D=2 H=1 Dk=2 Dv=2 |
| call0_heads_project_Q_0_0_0_0 product0=x0*w0; product1=x1*w1; value=product0+product1 | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: One token row times the packed column h*F+f, keeping both input-feature rows. Weights are hand-set; no bias, activation or learning is hidden. | b=0 t=0 h=0 f=0 x0=0.4472135954999579 x1=-0.4472135954999579 w0=1 w1=0 | product0=0.4472135954999579 product1=0 value=0.4472135954999579 |
| call0_heads_project_Q_0_0_0_1 product0=x0*w0; product1=x1*w1; value=product0+product1 | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: One token row times the packed column h*F+f, keeping both input-feature rows. Weights are hand-set; no bias, activation or learning is hidden. | b=0 t=0 h=0 f=1 x0=0.4472135954999579 x1=-0.4472135954999579 w0=0 w1=1 | product0=0 product1=-0.4472135954999579 value=-0.4472135954999579 |
| call0_heads_project_K_0_0_0_0 product0=x0*w0; product1=x1*w1; value=product0+product1 | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: One token row times the packed column h*F+f, keeping both input-feature rows. Weights are hand-set; no bias, activation or learning is hidden. | b=0 t=0 h=0 f=0 x0=0.4472135954999579 x1=-0.4472135954999579 w0=1 w1=0 | product0=0.4472135954999579 product1=0 value=0.4472135954999579 |
| call0_heads_project_K_0_0_0_1 product0=x0*w0; product1=x1*w1; value=product0+product1 | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: One token row times the packed column h*F+f, keeping both input-feature rows. Weights are hand-set; no bias, activation or learning is hidden. | b=0 t=0 h=0 f=1 x0=0.4472135954999579 x1=-0.4472135954999579 w0=0 w1=1 | product0=0 product1=-0.4472135954999579 value=-0.4472135954999579 |
| call0_heads_project_V_0_0_0_0 product0=x0*w0; product1=x1*w1; value=product0+product1 | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: One token row times the packed column h*F+f, keeping both input-feature rows. Weights are hand-set; no bias, activation or learning is hidden. | b=0 t=0 h=0 f=0 x0=0.4472135954999579 x1=-0.4472135954999579 w0=1 w1=0 | product0=0.4472135954999579 product1=0 value=0.4472135954999579 |
| call0_heads_project_V_0_0_0_1 product0=x0*w0; product1=x1*w1; value=product0+product1 | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: One token row times the packed column h*F+f, keeping both input-feature rows. Weights are hand-set; no bias, activation or learning is hidden. | b=0 t=0 h=0 f=1 x0=0.4472135954999579 x1=-0.4472135954999579 w0=0 w1=1 | product0=0 product1=-0.4472135954999579 value=-0.4472135954999579 |
| call0_heads_reshape_Q [B,T,H*F] → [B,T,H,F]; feature=h*F+f | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Reshaping preserves every flat value and its order. H counts attention heads; F counts features within each head. No projection feature is dropped. | B=1 T=1 H=1 F=2 features=2 elements=2 | elements=2 |
| call0_heads_permute_Q_0_0_0_0 axes [0,2,1,3]; destination[b,h,t,f]=source[b,t,h,f] | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Moving the head axis is a declared permutation, separate from reshape. The recorded offsets are actual row-major flat indices; this indexed value is copied unchanged. | b=0 h=0 t=0 f=0 feature=0 sourceOffset=0 destinationOffset=0 sourceValue=0.4472135954999579 | value=0.4472135954999579 |
| call0_heads_permute_Q_0_0_0_1 axes [0,2,1,3]; destination[b,h,t,f]=source[b,t,h,f] | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Moving the head axis is a declared permutation, separate from reshape. The recorded offsets are actual row-major flat indices; this indexed value is copied unchanged. | b=0 h=0 t=0 f=1 feature=1 sourceOffset=1 destinationOffset=1 sourceValue=-0.4472135954999579 | value=-0.4472135954999579 |
| call0_heads_reshape_K [B,T,H*F] → [B,T,H,F]; feature=h*F+f | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Reshaping preserves every flat value and its order. H counts attention heads; F counts features within each head. No projection feature is dropped. | B=1 T=1 H=1 F=2 features=2 elements=2 | elements=2 |
| call0_heads_permute_K_0_0_0_0 axes [0,2,1,3]; destination[b,h,t,f]=source[b,t,h,f] | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Moving the head axis is a declared permutation, separate from reshape. The recorded offsets are actual row-major flat indices; this indexed value is copied unchanged. | b=0 h=0 t=0 f=0 feature=0 sourceOffset=0 destinationOffset=0 sourceValue=0.4472135954999579 | value=0.4472135954999579 |
| call0_heads_permute_K_0_0_0_1 axes [0,2,1,3]; destination[b,h,t,f]=source[b,t,h,f] | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Moving the head axis is a declared permutation, separate from reshape. The recorded offsets are actual row-major flat indices; this indexed value is copied unchanged. | b=0 h=0 t=0 f=1 feature=1 sourceOffset=1 destinationOffset=1 sourceValue=-0.4472135954999579 | value=-0.4472135954999579 |
| call0_heads_reshape_V [B,T,H*F] → [B,T,H,F]; feature=h*F+f | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Reshaping preserves every flat value and its order. H counts attention heads; F counts features within each head. No projection feature is dropped. | B=1 T=1 H=1 F=2 features=2 elements=2 | elements=2 |
| call0_heads_permute_V_0_0_0_0 axes [0,2,1,3]; destination[b,h,t,f]=source[b,t,h,f] | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Moving the head axis is a declared permutation, separate from reshape. The recorded offsets are actual row-major flat indices; this indexed value is copied unchanged. | b=0 h=0 t=0 f=0 feature=0 sourceOffset=0 destinationOffset=0 sourceValue=0.4472135954999579 | value=0.4472135954999579 |
| call0_heads_permute_V_0_0_0_1 axes [0,2,1,3]; destination[b,h,t,f]=source[b,t,h,f] | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Moving the head axis is a declared permutation, separate from reshape. The recorded offsets are actual row-major flat indices; this indexed value is copied unchanged. | b=0 h=0 t=0 f=1 feature=1 sourceOffset=1 destinationOffset=1 sourceValue=-0.4472135954999579 | value=-0.4472135954999579 |
| call0_rope_Q_0 frequency=10000^0; angle=t*frequency; cos=cos(angle); sin=sin(angle); rotated0=x0*cos-x1*sin; rotated1=x0*sin+x1*cos | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: The only adjacent feature pair has frequency1 and angle t radians. Q and K rotate; V keeps its original projection. Every product and both final coordinates are saved. | 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 |
| call0_rope_K_0 frequency=10000^0; angle=t*frequency; cos=cos(angle); sin=sin(angle); rotated0=x0*cos-x1*sin; rotated1=x0*sin+x1*cos | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: The only adjacent feature pair has frequency1 and angle t radians. Q and K rotate; V keeps its original projection. Every product and both final coordinates are saved. | 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 |
| call0_heads_score_0_0_0_0 product0=q0*k0; product1=q1*k1; raw=product0+product1; score=raw/sqrt(Dk) | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Matching features are multiplied inside this batch and head only. Dk, not H or T or Dv, supplies the scaling width. Signed scores are not probabilities. | 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 |
| call0_heads_row_0_0_0 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 | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Each head has its own probabilities. Key validity is shared across batches and heads; queries remain. Forbidden terms are exactly zero, without an infinity sentinel or invented shifted value. Allowed terms can underflow; a large common shift can change low bits. | b=0 h=0 i=0 mode=1 shift=0 score0=0.28284271247461895 allowed0=1 | max=0.28284271247461895 denominator=1 shifted0=0 term0=1 p0=1 |
| call0_heads_head_mix_0_0_0_0 product_j=p_j*v_j; running starts at 0; running_j=previous+product_j; value=last running sum | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Use the real probability row and values in the same head and batch. Compute each product, then immediately accumulate in ascending key order, including actual zero times V for forbidden keys. No averaging across heads or extra division. | b=0 h=0 i=0 f=0 p0=1 v0=0.4472135954999579 | product0=0.4472135954999579 running0=0.4472135954999579 value=0.4472135954999579 |
| call0_heads_head_mix_0_0_0_1 product_j=p_j*v_j; running starts at 0; running_j=previous+product_j; value=last running sum | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Use the real probability row and values in the same head and batch. Compute each product, then immediately accumulate in ascending key order, including actual zero times V for forbidden keys. No averaging across heads or extra division. | b=0 h=0 i=0 f=1 p0=1 v0=-0.4472135954999579 | product0=-0.4472135954999579 running0=-0.4472135954999579 value=-0.4472135954999579 |
| call0_heads_concat_0_0_0_0 C[b,t,h*Dv+f]=OHeads[b,h,t,f] | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Copy one actual head output unchanged. Concatenate in head order then within-head feature order; never average heads or mix batches. | b=0 t=0 h=0 f=0 concatFeature=0 sourceOffset=0 destinationOffset=0 sourceValue=0.4472135954999579 | value=0.4472135954999579 |
| call0_heads_concat_0_0_0_1 C[b,t,h*Dv+f]=OHeads[b,h,t,f] | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Copy one actual head output unchanged. Concatenate in head order then within-head feature order; never average heads or mix batches. | b=0 t=0 h=0 f=1 concatFeature=1 sourceOffset=1 destinationOffset=1 sourceValue=-0.4472135954999579 | value=-0.4472135954999579 |
| call0_heads_output_0_0_0 product_c=C_c*WO[c,d]; running starts at 0; running_c=previous+product_c; Y=last running sum | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: WO rows preserve named head/feature identity when Dv changes. Every joined feature contributes one recorded product and running sum. Y may be signed; no output softmax, bias, residual, dropout or normalization is added. | 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 |
| call0_heads_output_0_0_1 product_c=C_c*WO[c,d]; running starts at 0; running_c=previous+product_c; Y=last running sum | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: WO rows preserve named head/feature identity when Dv changes. Every joined feature contributes one recorded product and running sum. Y may be signed; no output softmax, bias, residual, dropout or normalization is added. | 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 |
| call0_residual1_0_0 value=X+AttentionOutput | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Add identical named [B,T,D] shapes without broadcasting. The shortcut carries the original embedding. | t=0 d=0 left=1 right=0.4472135954999579 | value=1.4472135954999579 |
| call0_residual1_0_1 value=X+AttentionOutput | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Add identical named [B,T,D] shapes without broadcasting. The shortcut carries the original embedding. | t=0 d=1 left=0 right=-0.4472135954999579 | value=-0.4472135954999579 |
| call0_ln2_0_statistics sum=x0+x1; mean=sum/2; centered=x-mean; squareSum=centered0²+centered1²; variance=squareSum/2; denominator=sqrt(variance+epsilon) | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Only these two features contribute. Epsilon is inside the square root; no batch or token statistics are mixed. | x0=1.4472135954999579 x1=-0.4472135954999579 epsilon=1 | sum=1 mean=0.5 centered0=0.9472135954999579 centered1=-0.9472135954999579 square0=0.8972135954999578 square1=0.8972135954999578 squareSum=1.7944271909999157 variance=0.8972135954999578 variancePlusEpsilon=1.8972135954999578 denominator=1.3773937692250382 |
| call0_ln2_0_feature_0 normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: The source is the saved centered feature. Gamma and beta may change output mean and variance. | d=0 source=0.9472135954999579 denominator=1.3773937692250382 gamma=1 beta=0 | normalized=0.6876854075163181 scaled=0.6876854075163181 value=0.6876854075163181 |
| call0_ln2_0_feature_1 normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: The source is the saved centered feature. Gamma and beta may change output mean and variance. | d=1 source=-0.9472135954999579 denominator=1.3773937692250382 gamma=1 beta=0 | normalized=-0.6876854075163181 scaled=-0.6876854075163181 value=-0.6876854075163181 |
| call0_ffn_hidden_0_0_0 product0=x0*w0; product1=x1*w1; sum=product0+product1; preactivation=sum+bias | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: The same W1 and b1 apply separately to each token. Add bias after the two input products; no token sum occurs. | b=0 t=0 m=0 x0=0.6876854075163181 x1=-0.6876854075163181 w0=1 w1=0 bias=0 | product0=0.6876854075163181 product1=0 sum=0.6876854075163181 preactivation=0.6876854075163181 |
| call0_ffn_hidden_0_0_1 product0=x0*w0; product1=x1*w1; sum=product0+product1; preactivation=sum+bias | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: The same W1 and b1 apply separately to each token. Add bias after the two input products; no token sum occurs. | b=0 t=0 m=1 x0=0.6876854075163181 x1=-0.6876854075163181 w0=0 w1=1 bias=0 | product0=0 product1=-0.6876854075163181 sum=-0.6876854075163181 preactivation=-0.6876854075163181 |
| call0_ffn_hidden_0_0_2 product0=x0*w0; product1=x1*w1; sum=product0+product1; preactivation=sum+bias | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: The same W1 and b1 apply separately to each token. Add bias after the two input products; no token sum occurs. | b=0 t=0 m=2 x0=0.6876854075163181 x1=-0.6876854075163181 w0=0 w1=0 bias=0 | product0=0 product1=0 sum=0 preactivation=0 |
| call0_ffn_relu_0_0_0 activation=max(0,preactivation) | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself. | b=0 t=0 m=0 preactivation=0.6876854075163181 | activation=0.6876854075163181 |
| call0_ffn_relu_0_0_1 activation=max(0,preactivation) | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself. | b=0 t=0 m=1 preactivation=-0.6876854075163181 | activation=0 |
| call0_ffn_relu_0_0_2 activation=max(0,preactivation) | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself. | b=0 t=0 m=2 preactivation=0 | activation=0 |
| call0_ffn_output_0_0_0 product_m=h_m*w_m; running starts at 0; running_m=previous+product_m; sum=running2; value=sum+bias | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Multiply then immediately accumulate hidden features in ascending order 0,1,2. Add b2 last. Output may be signed; there is no softmax or residual inside the FFN. | 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 |
| call0_ffn_output_0_0_1 product_m=h_m*w_m; running starts at 0; running_m=previous+product_m; sum=running2; value=sum+bias | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Multiply then immediately accumulate hidden features in ascending order 0,1,2. Add b2 last. Output may be signed; there is no softmax or residual inside the FFN. | 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 |
| call0_residual2_0_0 value=R1+F | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: The FFN applies to each token separately; the real third hidden coordinate is computed with zero weights. | t=0 d=0 left=1.4472135954999579 right=0.6876854075163181 | value=2.134899003016276 |
| call0_residual2_0_1 value=R1+F | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: The FFN applies to each token separately; the real third hidden coordinate is computed with zero weights. | t=0 d=1 left=-0.4472135954999579 right=0 | value=-0.4472135954999579 |
| call0_readout_0_0 product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Final decoder features multiply only the active class columns. Bias is added last; targets are not operands. | 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 |
| call0_readout_0_1 product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Final decoder features multiply only the active class columns. Bias is added last; targets are not operands. | t=0 c=1 y0=2.134899003016276 u0=0 y1=-0.4472135954999579 u1=1 bias=0 | product0=0 product1=-0.4472135954999579 sum=-0.4472135954999579 logit=-0.4472135954999579 |
| call0_readout_0_2 product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Final decoder features multiply only the active class columns. Bias is added last; targets are not operands. | t=0 c=2 y0=2.134899003016276 u0=0 y1=-0.4472135954999579 u1=0 bias=0 | product0=0 product1=0 sum=0 logit=0 |
| call0_class_0_max max=max(active logits) | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: The maximum stabilizes exponentiation; every active class participates before the target is selected. | z0=2.134899003016276 z1=-0.4472135954999579 z2=0 | max=2.134899003016276 |
| call0_class_0_exp_0 shifted=logit-max; term=exp(shifted) | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: At least one term is exp(0)=1. No probability is clipped or rounded for this calculation. | t=0 c=0 logit=2.134899003016276 max=2.134899003016276 | shifted=0 term=1 |
| call0_class_0_exp_1 shifted=logit-max; term=exp(shifted) | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: At least one term is exp(0)=1. No probability is clipped or rounded for this calculation. | t=0 c=1 logit=-0.4472135954999579 max=2.134899003016276 | shifted=-2.582112598516234 term=0.0756140929478022 |
| call0_class_0_exp_2 shifted=logit-max; term=exp(shifted) | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: At least one term is exp(0)=1. No probability is clipped or rounded for this calculation. | t=0 c=2 logit=0 max=2.134899003016276 | shifted=-2.134899003016276 term=0.11825653332669596 |
| call0_class_0_normalize running starts at 0; running_c=previous+term_c; S=last running; logS=ln(S); LSE=max+logS | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Terms accumulate left to right in compact class order. NLL later uses the factored max-minus-target form, not subtraction of a rounded LSE. | 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 |
| call0_class_0_probability_0 probability=term/S | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: This is the stored binary64 probability for a real active class, before display formatting. | t=0 c=0 term=1 denominator=1.1938706262744982 | probability=0.8376116959343609 |
| call0_class_0_probability_1 probability=term/S | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: This is the stored binary64 probability for a real active class, before display formatting. | t=0 c=1 term=0.0756140929478022 denominator=1.1938706262744982 | probability=0.063335248630547 |
| call0_class_0_probability_2 probability=term/S | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: This is the stored binary64 probability for a real active class, before display formatting. | t=0 c=2 term=0.11825653332669596 denominator=1.1938706262744982 | probability=0.09905305543509206 |
| call0_class_0_argmax argmax computed logits; exact ties choose smallest compact class | Actual call0, absolute positions 0..0, no K/V reuse. Kernel explanation: Stored probabilities can appear tied even for different computed logits. This prediction is inspected, never fed back into teacher forcing. | z0=2.134899003016276 z1=-0.4472135954999579 z2=0 | nextRow=0 nextID=97 nextProbability=0.8376116959343609 |
| call0_decision greedy: saved strict-logit argmax, zero draws; sampling: actual sampleNext on saved last-row logits, one draw | The raw model probability is gathered at the selected compact row of the actual unscaled last-row P. Sampling additionally saves the selected temperature-base and final-policy probabilities, which need not equal the raw model P. | callIndex=0 observedLength=1 lastRow=0 outputPosition=1 strategy=1 seedBefore=0 | selectedRow=0 selectedID=97 selectedModelProbability=0.8376116959343609 selectedTemperatureBaseProbability=0.8376116959343609 selectedSamplingProbability=0.837611695934361 seedAfter=1013904223 rngDrawCount=1 cacheUsed=0 cacheEntries=0 |
| call0_append ResultIDs append selectedID; stopCode=EOS?1:budget?2:nextContext>3?3:0 | A terminal emitted ID remains a pending logical output. It has no fabricated neural row. Only a continuing non-EOS ID becomes part of the next full-prefix input; tokenization is not repeated. | selectedID=97 EOS=512 outputPosition=1 maxNew=2 contextLimit=3 | generatedTokens=1 logicalResultTokenCount=2 stoppedEOS=0 budgetReached=0 contextExceeded=0 stopCode=0 continueLoop=1 |
Three distributions, two orders, one recorded draw
Sampled a (ID97), compact class0, final policy probability 0.837611695934361. Retained entries=3; positive entries=3. Full scaled-distribution greedy evidence instead names ID97; it is a separate decision.
Temperature divides the actual logits before full stable normalization. Top-k ranks computed scaled scores, breaking exact ties by ascending public ID. Nucleus filtering then visits this ranked prefix through its first threshold crossing; p=1 retains every top-k entry. Selection uses a separately declared ascending-public-ID cumulative distribution.
Inspecting saved compact class0, public ID97. This selector reads the record and leaves exercise answers unchanged.
Trace operation setup is selected. Its matching saved-operation row below is marked current when present.
| Compact / public ID | Actual input logit | Scaled logit | Full base P | Top-k keep? | Top-k P | Nucleus keep? | Final policy P | Selected? |
|---|---|---|---|---|---|---|---|---|
| 0 / a ID97 | 2.134899003016276 | 2.134899003016276 | 0.8376116959343609 | Yes | 0.837611695934361 | Yes | 0.837611695934361 | Yes |
| 1 / b ID98 | -0.4472135954999579 | -0.4472135954999579 | 0.063335248630547 | Yes | 0.06333524863054701 | Yes | 0.06333524863054701 | No |
| 2 / EOS ID512 | 0 | 0 | 0.09905305543509206 | Yes | 0.09905305543509207 | Yes | 0.09905305543509207 | No |
Selected class0: actual shift=0, exp(shift)=1, denominator=1.1938706262744982, logS=0.17720065589584005, LSE=2.312099658912116. BaseP, TopKP and FinalP describe different stages. Removed entries are exact zeros; no epsilon is added.
| Score rank | Compact / public ID | Computed scaled score | Base P | Top-k running mass | Nucleus before | Nucleus cumulative | Crossed threshold? | Continue visit? |
|---|---|---|---|---|---|---|---|---|
| 0 | 0 / ID97 | 2.134899003016276 | 0.8376116959343609 | 0.8376116959343609 | 0 | 0.837611695934361 | 0 | 1 |
| 1 | 2 / ID512 | 0 | 0.09905305543509206 | 0.9366647513694529 | 0.837611695934361 | 0.936664751369453 | 0 | 1 |
| 2 | 1 / ID98 | -0.4472135954999579 | 0.063335248630547 | 0.9999999999999999 | 0.936664751369453 | 1 | 1 | 0 |
Top-k mass=0.9999999999999999, accumulated in score-rank order from stored BaseP. Nucleus mass=1, accumulated again in rank order from stored TopKP. Its actual running values are [0.837611695934361,0.936664751369453,1]. These sums use computed values; printed decimals never feed arithmetic.
| CDF entry | Compact / public ID | Final P | Before | Actual cumulative | Positive P? | u < cumulative? | First eligible take? |
|---|---|---|---|---|---|---|---|
| 0 | 0 / ID97 | 0.837611695934361 | 0 | 0.837611695934361 | 1 | 1 | 1 |
| 1 | 1 / ID98 | 0.06333524863054701 | 0.837611695934361 | 0.9009469445649081 | 1 | 1 | 0 |
| 2 | 2 / ID512 | 0.09905305543509207 | 0.9009469445649081 | 1.0000000000000002 | 1 | 1 | 0 |
LCG seed 0: signed low product 0 + increment 1013904223 = integer sum 1013904223; unsigned nextSeed 1013904223; u=0.23606797284446657. Draw count=1, including a one-candidate decision. RNGState is exact integer-valued float64 with precision0, so unsigned values above 2³¹−1 stay intact.
Actual fallback=0. Selection takes the first positive entry with u strictly below its saved cumulative value. Equality belongs to the following interval; zero-probability entries cannot win even at u=0. If a finite cumulative gap leaves no eligible interval, the declared defensive policy uses the last positive entry and records fallback1. The CDF is never silently forced to1.
Inspect every actual sampler operation and operand
| Operation and equation | Explanation | Actual inputs | Actual outputs |
|---|---|---|---|
| call0_sample_scale scaled_c=logit_c/temperature | All active operands and computed divisions are saved. Positive temperature is validated before arithmetic; no derived-logit clipping occurs. | temperature=1 logit0=2.134899003016276 logit1=-0.4472135954999579 logit2=0 | scaled0=2.134899003016276 scaled1=-0.4472135954999579 scaled2=0 |
| call0_sample_base_max max=max(z0,...,z[V-1]) | All active computed input logits participate. The maximum stabilizes exponentiation; it is not a rounded probability. | z0=2.134899003016276 z1=-0.4472135954999579 z2=0 | max=2.134899003016276 |
| call0_sample_base_exp_0 shifted=logit-max; term=exp(shifted) | No clipping, epsilon or display rounding feeds the distribution. Underflow is retained if a derived input reaches it. | c=0 logit=2.134899003016276 max=2.134899003016276 | shifted=0 term=1 |
| call0_sample_base_exp_1 shifted=logit-max; term=exp(shifted) | No clipping, epsilon or display rounding feeds the distribution. Underflow is retained if a derived input reaches it. | c=1 logit=-0.4472135954999579 max=2.134899003016276 | shifted=-2.582112598516234 term=0.0756140929478022 |
| call0_sample_base_exp_2 shifted=logit-max; term=exp(shifted) | No clipping, epsilon or display rounding feeds the distribution. Underflow is retained if a derived input reaches it. | c=2 logit=0 max=2.134899003016276 | shifted=-2.134899003016276 term=0.11825653332669596 |
| call0_sample_base_normalize running starts at 0; running_c=previous+term_c; logS=ln(S); LSE=max+logS | The denominator adds terms in ascending compact class order. Every actual running sum is saved. | 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 |
| call0_sample_base_probability_0 probability=term/S | This stored binary64 probability is displayed without feeding its formatting back into arithmetic. | c=0 term=1 denominator=1.1938706262744982 | probability=0.8376116959343609 |
| call0_sample_base_probability_1 probability=term/S | This stored binary64 probability is displayed without feeding its formatting back into arithmetic. | c=1 term=0.0756140929478022 denominator=1.1938706262744982 | probability=0.063335248630547 |
| call0_sample_base_probability_2 probability=term/S | This stored binary64 probability is displayed without feeding its formatting back into arithmetic. | c=2 term=0.11825653332669596 denominator=1.1938706262744982 | probability=0.09905305543509206 |
| call0_sample_base_argmax strict greater-than updates the winner; exact ties retain lowest compact index | Greedy choice uses the saved logits, never argmax of rounded or stored probabilities. Compact index order differs from ascending public ID order. | z0=2.134899003016276 z1=-0.4472135954999579 z2=0 | nextRow=0 nextID=97 nextProbability=0.8376116959343609 |
| call0_sample_rank descending computed scaled logit; exact score tie => ascending public token ID | This order intentionally differs from the base helper greedy metadata, whose ties retain the lowest compact index. No stored or formatted probability is sorted. | scaled0=2.134899003016276 publicID0=97 scaled1=-0.4472135954999579 publicID1=98 scaled2=0 publicID2=512 | compact0=0 publicID0=97 score0=2.134899003016276 compact1=2 publicID1=512 score1=0 compact2=1 publicID2=98 score2=-0.4472135954999579 |
| call0_sample_topk_mass mass starts at 0; in rank order mass=previous+baseP for each kept rank | The complete rank keep decisions are saved. Only retained terms enter the left-to-right sum; no epsilon or replacement class is added. | topK=3 compact0=0 publicID0=97 baseP0=0.8376116959343609 before0=0 compact1=2 publicID1=512 baseP1=0.09905305543509206 before1=0.8376116959343609 compact2=1 publicID2=98 baseP2=0.063335248630547 before2=0.9366647513694529 | keep0=1 running0=0.8376116959343609 keep1=1 running1=0.9366647513694529 keep2=1 running2=0.9999999999999999 mass=0.9999999999999999 |
| call0_sample_topk_normalize topKP_c=topKMask_c?baseP_c/topKMass:0 | Arrays retain every active compact class, including exact algorithmic zero for removed classes. | mass=0.9999999999999999 baseP0=0.8376116959343609 keep0=1 baseP1=0.063335248630547 keep1=1 baseP2=0.09905305543509206 keep2=1 | topKP0=0.837611695934361 topKP1=0.06333524863054701 topKP2=0.09905305543509207 |
| call0_sample_nucleus include each visited token; continue while cumulative<topP; topP===1 retains all topK | Every visited operand, running sum and keep/continue decision is real. At topP1 even a rounded prefix cumulative of1 cannot discard the remaining top-k tail. | topP=1 topK=3 compact0=0 publicID0=97 topKP0=0.837611695934361 before0=0 compact1=2 publicID1=512 topKP1=0.09905305543509207 before1=0.837611695934361 compact2=1 publicID2=98 topKP2=0.06333524863054701 before2=0.936664751369453 | running0=0.837611695934361 keep0=1 crossed0=0 continue0=1 running1=0.936664751369453 keep1=1 crossed1=0 continue1=1 running2=1 keep2=1 crossed2=1 continue2=0 candidateCount=3 |
| call0_sample_final_mass mass starts at 0; mass=previous+topKP for each nucleus entry | This second mass uses the saved top-k probabilities, not the original base probabilities or an ideal-real formula. | compact0=0 topKP0=0.837611695934361 before0=0 compact1=2 topKP1=0.09905305543509207 before1=0.837611695934361 compact2=1 topKP2=0.06333524863054701 before2=0.936664751369453 | running0=0.837611695934361 running1=0.936664751369453 running2=1 mass=1 |
| call0_sample_final_normalize finalP_c=finalMask_c?topKP_c/finalMass:0 | Kept entries may have actual zero probability after helper underflow. Removed entries are exact zero; positive support is checked before selection. | mass=1 topKP0=0.837611695934361 keep0=1 topKP1=0.06333524863054701 keep1=1 topKP2=0.09905305543509207 keep2=1 | finalP0=0.837611695934361 finalP1=0.06333524863054701 finalP2=0.09905305543509207 |
| call0_sample_cdf CDF starts at 0; cumulative_i=previous+finalP[public-order compact_i] | Every retained entry is present, including kept zero probabilities. The final cumulative is saved as computed, never forced to1. | compact0=0 publicID0=97 probability0=0.837611695934361 before0=0 compact1=1 publicID1=98 probability1=0.06333524863054701 before1=0.837611695934361 compact2=2 publicID2=512 probability2=0.09905305543509207 before2=0.9009469445649081 | running0=0.837611695934361 positive0=1 running1=0.9009469445649081 positive1=1 running2=1.0000000000000002 positive2=1 positiveCount=3 lastPositive=2 |
| call0_sample_rng signedProduct=imul(1664525,seed); sum=signedProduct+1013904223; nextSeed=sum>>>0; u=nextSeed/4294967296 | One draw is consumed even for a single candidate. Unsigned states and the integer sum use exact integer-valued binary64 evidence, never signed-int32 wrapping storage. | seed=0 multiplier=1664525 increment=1013904223 modulus=4294967296 | signedProduct=0 sum=1013904223 nextSeed=1013904223 uniform=0.23606797284446657 drawCount=1 |
| call0_sample_select first positive entry with u<cumulative; if none, use last positive entry and record fallback1 | Equality belongs to the following interval. Every exact predicate is saved. The fallback covers a finite summation gap; it does not alter any saved probability or CDF. | uniform=0.23606797284446657 compact0=0 probability0=0.837611695934361 cumulative0=0.837611695934361 compact1=1 probability1=0.06333524863054701 cumulative1=0.9009469445649081 compact2=2 probability2=0.09905305543509207 cumulative2=1.0000000000000002 | positive0=1 below0=1 take0=1 positive1=1 below1=1 take1=0 positive2=1 below2=1 take2=0 fallback=0 selectedCDFIndex=0 sampledRow=0 sampledID=97 sampledProbability=0.837611695934361 candidateCount=3 |
A seed fixes a finite 32-bit pseudorandom stream on the grid nextSeed/2³². It does not supply independent continuous uniforms or guarantee empirical frequencies. Binary64 division can collapse distinct tiny logits to an exact score tie; ranking follows the computed scaled scores. Elementary-library rounding near filter or CDF boundaries can change a token path across platforms. Temperature/filtering neither trains weights nor proves language quality.
Inspect real prompt BPE and final strict reconstruction
Fixed corpus "abab"; learned rules []. Zero merges requested: no training round or pair selection occurs. The old tokenizer's inner bound remains24 bytes; this lesson enforces raw6 bytes, merges0..2 and at most3 encoded prompt tokens. Appended IDs are never retokenized.
| Operation and equation | Explanation | Actual inputs | Actual outputs |
|---|---|---|---|
| tokenizer_setup byte IDs=0..255; learned ID=256+rank; EOS=512; each text field<=24 UTF-8 bytes | Validate every raw field before corpus then target Unicode semantics. Train on the corpus byte stream including spaces; encode the separate target using learned ranks. No normalization, word splitting, inferred EOS or pretrained vocabulary is used. | requestedMerges=0 eos=0 | corpusUnits=4 corpusScalars=4 utf16Units=1 scalarCount=1 byteBound=24 mergeBase=256 mergeBound=4 EOS=512 |
| tokenizer_corpus_scalar_0 supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits | A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs. | scalarIndex=0 utf16Offset=0 utf16Width=1 codePoint=97 unit0=97 | byteOffset=0 byteWidth=1 payload0=97 byte0=97 |
| tokenizer_corpus_scalar_1 supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits | A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs. | scalarIndex=1 utf16Offset=1 utf16Width=1 codePoint=98 unit0=98 | byteOffset=1 byteWidth=1 payload0=98 byte0=98 |
| tokenizer_corpus_scalar_2 supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits | A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs. | scalarIndex=2 utf16Offset=2 utf16Width=1 codePoint=97 unit0=97 | byteOffset=2 byteWidth=1 payload0=97 byte0=97 |
| tokenizer_corpus_scalar_3 supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits | A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs. | scalarIndex=3 utf16Offset=3 utf16Width=1 codePoint=98 unit0=98 | byteOffset=3 byteWidth=1 payload0=98 byte0=98 |
| tokenizer_source_scalar_0 supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits | A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs. | scalarIndex=0 utf16Offset=0 utf16Width=1 codePoint=97 unit0=97 | byteOffset=0 byteWidth=1 payload0=97 byte0=97 |
| tokenizer_corpus_expand_0 ID → validated byte expansion | Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used. | index=0 id=97 | byteOffset=0 byteWidth=1 byte0=97 |
| tokenizer_corpus_expand_1 ID → validated byte expansion | Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used. | index=1 id=98 | byteOffset=1 byteWidth=1 byte0=98 |
| tokenizer_corpus_expand_2 ID → validated byte expansion | Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used. | index=2 id=97 | byteOffset=2 byteWidth=1 byte0=97 |
| tokenizer_corpus_expand_3 ID → validated byte expansion | Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used. | index=3 id=98 | byteOffset=3 byteWidth=1 byte0=98 |
| tokenizer_corpus_decode_0 accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar | Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved. | scalarIndex=0 byteOffset=0 byteWidth=1 byte0=97 | payload0=97 accumulator0=97 codePoint=97 utf16Width=1 unit0=97 |
| tokenizer_corpus_decode_1 accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar | Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved. | scalarIndex=1 byteOffset=1 byteWidth=1 byte0=98 | payload0=98 accumulator0=98 codePoint=98 utf16Width=1 unit0=98 |
| tokenizer_corpus_decode_2 accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar | Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved. | scalarIndex=2 byteOffset=2 byteWidth=1 byte0=97 | payload0=97 accumulator0=97 codePoint=97 utf16Width=1 unit0=97 |
| tokenizer_corpus_decode_3 accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar | Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved. | scalarIndex=3 byteOffset=3 byteWidth=1 byte0=98 | payload0=98 accumulator0=98 codePoint=98 utf16Width=1 unit0=98 |
| tokenizer_target_expand_0 ID → validated byte expansion | Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used. | index=0 id=97 | byteOffset=0 byteWidth=1 byte0=97 |
| tokenizer_target_decode_0 accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar | Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved. | scalarIndex=0 byteOffset=0 byteWidth=1 byte0=97 | payload0=97 accumulator0=97 codePoint=97 utf16Width=1 unit0=97 |
| tokenizer_roundtrip corpusEqual=(corpusDecoded===corpus); equal=(targetDecoded===text) | Expand real corpus and target IDs separately, concatenate real bytes, strictly reconstruct Unicode scalars, and only then compare strings. Empty content reconstructs the empty string; optional target EOS emits no bytes. | corpusOriginalUnits=4 corpusDecodedUnits=4 corpusDecodedByteCount=4 originalUnits=1 decodedUnits=1 decodedByteCount=1 | corpusTokens=4 tokenCount=1 corpusEqual=1 equal=1 |
| result_expand_0 ID → validated byte expansion | Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used. | index=0 id=97 | byteOffset=0 byteWidth=1 byte0=97 |
| result_expand_1 ID → validated byte expansion | Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used. | index=1 id=97 | byteOffset=1 byteWidth=1 byte0=97 |
| result_expand_2 ID → validated byte expansion | Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used. | index=2 id=97 | byteOffset=2 byteWidth=1 byte0=97 |
| result_decode_0 accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar | Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved. | scalarIndex=0 byteOffset=0 byteWidth=1 byte0=97 | payload0=97 accumulator0=97 codePoint=97 utf16Width=1 unit0=97 |
| result_decode_1 accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar | Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved. | scalarIndex=1 byteOffset=1 byteWidth=1 byte0=97 | payload0=97 accumulator0=97 codePoint=97 utf16Width=1 unit0=97 |
| result_decode_2 accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar | Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved. | scalarIndex=2 byteOffset=2 byteWidth=1 byte0=97 | payload0=97 accumulator0=97 codePoint=97 utf16Width=1 unit0=97 |
A seed fixes the LCG stream. Elementary-library rounding near filter or CDF boundaries may change a valid token path; each actual saved path needs conditional-witness verification. Square root, trigonometry, exponential and logarithm values use approximate binary64 library operations. The full inspector retains every one of the57 tensors from each actual forward call and every sampler tensor when sampling occurs. These parameters are hand-set and untrained.
Inspect all stored values, text metadata and tensor storage
Every scalar output, including flattened operation outputs
Exact text evidence from the same record
These are the stored values, shown without display rounding. Each tensor names its axes, dtype and display precision. Empty arrays are omitted rather than padded.
TokenizerCorpusCodePoints
Scalars=4 · int32 · precision 0 · Prompt BPE with EOS off, once. 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 · Prompt BPE with EOS off, once. 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 · Prompt BPE with EOS off, once. 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 · Prompt BPE with EOS off, once. 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 · Prompt BPE with EOS off, once. 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 · Prompt BPE with EOS off, once. 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=1 · int32 · precision 0 · Prompt BPE with EOS off, once. Validated Unicode scalars in exact input order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
TokenizerSourceUTF16Offsets
Scalars=1 · int32 · precision 0 · Prompt BPE with EOS off, once. Zero-based UTF-16 storage offset for each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
TokenizerSourceUTF16Widths
Scalars=1 · int32 · precision 0 · Prompt BPE with EOS off, once. UTF-16 storage units consumed by each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
TokenizerSourceByteOffsets
Scalars=1 · int32 · precision 0 · Prompt BPE with EOS off, once. Zero-based UTF-8 byte offset for each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
TokenizerSourceByteWidths
Scalars=1 · int32 · precision 0 · Prompt BPE with EOS off, once. Actual UTF-8 bytes emitted by each scalar.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
TokenizerSourceBytes
Bytes=1 · int32 · precision 0 · Prompt BPE with EOS off, once. Manual UTF-8 encoding in source order, preserving all data.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
TokenizerTrainInitialIDs
Tokens=4 · int32 · precision 0 · Prompt BPE with EOS off, once. 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 · Prompt BPE with EOS off, once. 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=1 · int32 · precision 0 · Prompt BPE with EOS off, once. Initial target byte IDs before any ranked application.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
TokenizerTargetIDs
Tokens=1 · int32 · precision 0 · Prompt BPE with EOS off, once. Final target token IDs after all learned ranks, then optional unique EOS tail.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
TokenizerCorpusDecodedBytes
Bytes=4 · int32 · precision 0 · Prompt BPE with EOS off, once. 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=1 · int32 · precision 0 · Prompt BPE with EOS off, once. Actual final target ID expansions passed to strict UTF-8 decoding.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
Call0AllClassIDs
ModelRow=5 · int32 · precision 0 · Actual call0 prefill, absolute positions 0..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 |
Call0ClassIDs
Class=3 · int32 · precision 0 · Actual call0 prefill, absolute positions 0..0. Active prefix of the full model row map; V=3+merges.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
Call0E
ModelRow=5 × D=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0U
D=2 × ModelRow=5 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0Bias
ModelRow=5 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0InputIDs
Position=1 · int32 · precision 0 · Actual call0 prefill, absolute positions 0..0. Observed public IDs supplied directly to the numeric kernel; active EOS is permitted.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
Call0InputRows
Position=1 · int32 · precision 0 · Actual call0 prefill, absolute positions 0..0. Compact model row gathered for each observed ID; never index by public ID512.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
Call0X
B=1 × T=1 × D=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Actual gathered E rows; B=1, token-major storage and D=2.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
Call0LN1
B=1 × T=1 × D=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0ProjectionX
B=1 × T=1 × D=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0ProjectionWQ
D=2 × QueryFeature=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0ProjectionWK
D=2 × KeyFeature=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0ProjectionWV
D=2 × ValueFeature=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0ProjectionQConcat
B=1 × T=1 × QueryFeature=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0ProjectionKConcat
B=1 × T=1 × KeyFeature=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0ProjectionVConcat
B=1 × T=1 × ValueFeature=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0ProjectionQSplit
B=1 × T=1 × H=1 × Dk=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0ProjectionQHeads
B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0ProjectionKSplit
B=1 × T=1 × H=1 × Dk=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0ProjectionKHeads
B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0ProjectionVSplit
B=1 × T=1 × H=1 × Dv=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0ProjectionVHeads
B=1 × H=1 × T=1 × Dv=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0RotatedQHeads
B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Actual RoPE(ProjectionQHeads) supplied as attendHeads QHeads; original projection is retained separately.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
Call0RotatedKHeads
B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Actual RoPE(ProjectionKHeads) supplied as attendHeads KHeads; original projection is retained separately.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
Call0RoPEAngles
Position=1 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Absolute position t times the single-pair frequency1, in radians.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
Call0RoPECos
Position=1 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Stored cos(angle) used in the Q pair rotation; K uses the same angle.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
Call0RoPESin
Position=1 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Stored sin(angle) used in the Q pair rotation; K uses the same angle.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
Call0Attentionraw
B=1 × H=1 × Query=1 × Key=1 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0Attentionscores
B=1 × H=1 × Query=1 × Key=1 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0Attentionallowed
B=1 × H=1 × Query=1 × Key=1 · bool · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0Attentionlogits
B=1 × H=1 × Query=1 × Key=1 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Finite score+shift, including forbidden cells; mask applied separately. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.28284271247461895 |
Call0Attentionprobabilities
B=1 × H=1 × Query=1 × Key=1 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0AttentionOHeads
B=1 × H=1 × Query=1 × Dv=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0AttentionC
B=1 × T=1 × JoinedValue=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0AttentionWO
JoinedValue=2 × D=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0AttentionOutput
B=1 × T=1 × D=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0R1
B=1 × T=1 × D=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Exact named-shape addition of X and AttentionOutput; no broadcasting.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.4472135954999579 |
| 1 | -0.4472135954999579 |
Call0LN2
B=1 × T=1 × D=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0W1
D=2 × HiddenFeature=3 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0b1
HiddenFeature=3 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Shared hidden bias, added after the two products.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
Call0Z
B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Hidden preactivations X W1+b1; no batch or token mixing.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.6876854075163181 |
| 1 | -0.6876854075163181 |
| 2 | 0 |
Call0Hidden
B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. ReLU(Z)=max(0,Z), before the second affine layer.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.6876854075163181 |
| 1 | 0 |
| 2 | 0 |
Call0W2
HiddenFeature=3 × D=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0b2
D=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Shared output bias, added after all three running sums.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
Call0F
B=1 × T=1 × D=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. ReLU(X W1+b1) W2+b2, independently per token with shared parameters.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.6876854075163181 |
| 1 | 0 |
Call0Y
B=1 × T=1 × D=2 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Exact named-shape addition of R1 and F; no broadcasting.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.4472135954999579 |
Call0Logits
Position=1 × Class=3 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0Max
Position=1 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Maximum computed active class logit at each position.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
Call0Shifted
Position=1 × Class=3 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Computed class logit minus its saved row maximum.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | -2.582112598516234 |
| 2 | -2.134899003016276 |
Call0Terms
Position=1 × Class=3 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Actual exp(Shifted) before left-to-right class summation.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0.0756140929478022 |
| 2 | 0.11825653332669596 |
Call0Denominator
Position=1 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Shifted exponential sum from zero in ascending compact class order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.1938706262744982 |
Call0LogS
Position=1 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. ln(Denominator), saved for factored NLL.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.17720065589584005 |
Call0LSE
Position=1 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Max+LogS; saved evidence, not subtracted from target logits to compute NLL.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.312099658912116 |
Call0P
Position=1 × Class=3 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. 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 |
Call0NextRows
Position=1 · int32 · precision 0 · Actual call0 prefill, absolute positions 0..0. Highest computed logit; exact ties keep the smallest compact class.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
Call0NextIDs
Position=1 · int32 · precision 0 · Actual call0 prefill, absolute positions 0..0. Public ID mapped from each computed-logit winner.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
Call0NextProbability
Position=1 · float64 · precision 8 · Actual call0 prefill, absolute positions 0..0. Stored class probability of the computed-logit winner; never fed back as an observed input.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8376116959343609 |
Call0SampleInputLogits
Class=3 · float64 · precision 8 · Actual call0 last-row sampling. Validated actual sampler logits; derived logits are not clipped.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.4472135954999579 |
| 2 | 0 |
Call0SampleScaledLogits
Class=3 · float64 · precision 8 · Actual call0 last-row sampling. Actual InputLogits/temperature in compact order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.4472135954999579 |
| 2 | 0 |
Call0SampleBaseClassIDs
Class=3 · int32 · precision 0 · Actual call0 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Active compact prefix [97,98,512,256,257]; public IDs are labels, not offsets.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
Call0SampleBaseZ
Class=3 · float64 · precision 8 · Actual call0 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Actual finite computed input logits; no derived-input clipping.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.4472135954999579 |
| 2 | 0 |
Call0SampleBaseShifted
Class=3 · float64 · precision 8 · Actual call0 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Z minus the saved active maximum.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | -2.582112598516234 |
| 2 | -2.134899003016276 |
Call0SampleBaseTerms
Class=3 · float64 · precision 8 · Actual call0 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Actual exp(Shifted), before normalization.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0.0756140929478022 |
| 2 | 0.11825653332669596 |
Call0SampleBaseDenominator
Scalar=1 · float64 · precision 8 · Actual call0 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Actual left-to-right sum of active shifted terms.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.1938706262744982 |
Call0SampleBaseLogS
Scalar=1 · float64 · precision 8 · Actual call0 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Natural logarithm of Denominator.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.17720065589584005 |
Call0SampleBaseLSE
Scalar=1 · float64 · precision 8 · Actual call0 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Saved max+LogS in binary64.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.312099658912116 |
Call0SampleBaseP
Class=3 · float64 · precision 8 · Actual call0 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Terms/Denominator for active classes only, without clipping or padding.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8376116959343609 |
| 1 | 0.063335248630547 |
| 2 | 0.09905305543509206 |
Call0SampleBaseNextRow
Decision=1 · int32 · precision 0 · Actual call0 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Lowest compact index among highest computed logits.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
Call0SampleBaseNextID
Decision=1 · int32 · precision 0 · Actual call0 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Public class ID gathered at NextRow.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
Call0SampleBaseNextProbability
Decision=1 · float64 · precision 8 · Actual call0 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Stored P gathered at the computed-logit winner.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8376116959343609 |
Call0SampleRankCompact
Rank=3 · int32 · precision 0 · Actual call0 last-row sampling. Descending computed ScaledLogits; exact ties ascend public ID.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 2 |
| 2 | 1 |
Call0SampleRankIDs
Rank=3 · int32 · precision 0 · Actual call0 last-row sampling. Public IDs gathered at RankCompact.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 512 |
| 2 | 98 |
Call0SampleTopKMask
Class=3 · int32 · precision 0 · Actual call0 last-row sampling. Complete active compact mask; first topK ranks are1.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
Call0SampleTopKRunning
TopKRank=3 · float64 · precision 8 · Actual call0 last-row sampling. Actual baseP rank-order running sums from zero.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8376116959343609 |
| 1 | 0.9366647513694529 |
| 2 | 0.9999999999999999 |
Call0SampleTopKMass
Scalar=1 · float64 · precision 8 · Actual call0 last-row sampling. Last actual TopKRunning value, required positive.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.9999999999999999 |
Call0SampleTopKP
Class=3 · float64 · precision 8 · Actual call0 last-row sampling. Kept BaseP/TopKMass; removed compact classes exact0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.837611695934361 |
| 1 | 0.06333524863054701 |
| 2 | 0.09905305543509207 |
Call0SampleNucleusCompact
NucleusRank=3 · int32 · precision 0 · Actual call0 last-row sampling. Actual visited top-k rank prefix, including first crossing; topP1 visits all.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 2 |
| 2 | 1 |
Call0SampleNucleusIDs
NucleusRank=3 · int32 · precision 0 · Actual call0 last-row sampling. Public IDs at actual visited nucleus ranks.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 512 |
| 2 | 98 |
Call0SampleNucleusBefore
NucleusRank=3 · float64 · precision 8 · Actual call0 last-row sampling. Actual cumulative operand before each visited TopKP addition.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0.837611695934361 |
| 2 | 0.936664751369453 |
Call0SampleNucleusRunning
NucleusRank=3 · float64 · precision 8 · Actual call0 last-row sampling. Actual cumulative TopKP in visited rank order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.837611695934361 |
| 1 | 0.936664751369453 |
| 2 | 1 |
Call0SampleNucleusCrossed
NucleusRank=3 · int32 · precision 0 · Actual call0 last-row sampling. Exact saved cumulative>=topP predicate for each visit.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 1 |
Call0SampleNucleusContinue
NucleusRank=3 · int32 · precision 0 · Actual call0 last-row sampling. Actual next-visit decision, including topP===1 special policy.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 0 |
Call0SampleFinalMask
Class=3 · int32 · precision 0 · Actual call0 last-row sampling. Complete active compact mask of actually visited nucleus entries.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
Call0SampleFinalRunning
NucleusRank=3 · float64 · precision 8 · Actual call0 last-row sampling. Second actual kept TopKP mass accumulation in rank order, from zero.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.837611695934361 |
| 1 | 0.936664751369453 |
| 2 | 1 |
Call0SampleFinalMass
Scalar=1 · float64 · precision 8 · Actual call0 last-row sampling. Last actual FinalRunning value, required positive.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
Call0SampleFinalP
Class=3 · float64 · precision 8 · Actual call0 last-row sampling. Actual kept TopKP/FinalMass; all removed entries exact0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.837611695934361 |
| 1 | 0.06333524863054701 |
| 2 | 0.09905305543509207 |
Call0SampleCDFCompact
CDFEntry=3 · int32 · precision 0 · Actual call0 last-row sampling. Retained compact indices sorted separately by ascending public ID.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
Call0SampleCDFIDs
CDFEntry=3 · int32 · precision 0 · Actual call0 last-row sampling. Ascending public IDs, including retained zero-probability entries.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
Call0SampleCDFBefore
CDFEntry=3 · float64 · precision 8 · Actual call0 last-row sampling. Actual final-P cumulative operand before each public-order addition.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0.837611695934361 |
| 2 | 0.9009469445649081 |
Call0SampleCDFRunning
CDFEntry=3 · float64 · precision 8 · Actual call0 last-row sampling. Actual public-order cumulative sum; last entry is not forced to1.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.837611695934361 |
| 1 | 0.9009469445649081 |
| 2 | 1.0000000000000002 |
Call0SampleRNGState
StateEndpoint=2 · float64 · precision 0 · Actual call0 last-row sampling. Initial and next unsigned uint32 states stored exactly in float64, without int32 conversion.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1013904223 |
Call0SampleRNGArithmetic
IntegerOperand=3 · float64 · precision 0 · Actual call0 last-row sampling. Actual signed imul low32 product, increment and exact integer-valued sum in float64.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1013904223 |
| 2 | 1013904223 |
Call0SampleUniform
Draw=1 · float64 · precision 8 · Actual call0 last-row sampling. Exact dyadic nextSeed/2^32, in [0,1); exactly one draw.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.23606797284446657 |
Call0SampleSampledRow
Decision=1 · int32 · precision 0 · Actual call0 last-row sampling. Compact class selected from the actual final CDF and draw.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
Call0SampleSampledID
Decision=1 · int32 · precision 0 · Actual call0 last-row sampling. Public ID at SampledRow; distinct from BaseNextID greedy metadata.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
Call0SampleSampledProbability
Decision=1 · float64 · precision 8 · Actual call0 last-row sampling. Stored FinalP gathered at SampledRow, never the base greedy probability.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.837611695934361 |
Call1AllClassIDs
ModelRow=5 · int32 · precision 0 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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 |
Call1ClassIDs
Class=3 · int32 · precision 0 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Active prefix of the full model row map; V=3+merges.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
Call1E
ModelRow=5 × D=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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 |
Call1U
D=2 × ModelRow=5 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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 |
Call1Bias
ModelRow=5 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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 |
Call1InputIDs
Position=2 · int32 · precision 0 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Observed public IDs supplied directly to the numeric kernel; active EOS is permitted.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 97 |
Call1InputRows
Position=2 · int32 · precision 0 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Compact model row gathered for each observed ID; never index by public ID512.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
Call1X
B=1 × T=2 × D=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Actual gathered E rows; B=1, token-major storage and D=2.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
Call1LN1
B=1 × T=2 × D=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Per-token feature layer norm of X; population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside sqrt.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | 0.4472135954999579 |
| 3 | -0.4472135954999579 |
Call1ProjectionX
B=1 × T=2 × D=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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 |
Call1ProjectionWQ
D=2 × QueryFeature=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Query columns packed by h*Dk+f from wq{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
Call1ProjectionWK
D=2 × KeyFeature=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Key columns packed by h*Dk+f from wk{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
Call1ProjectionWV
D=2 × ValueFeature=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Value columns packed by h*Dv+f from wv{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
Call1ProjectionQConcat
B=1 × T=2 × QueryFeature=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. XWQ; each packed coordinate has two products and one sum. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | 0.4472135954999579 |
| 3 | -0.4472135954999579 |
Call1ProjectionKConcat
B=1 × T=2 × KeyFeature=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. XWK; each packed coordinate has two products and one sum. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | 0.4472135954999579 |
| 3 | -0.4472135954999579 |
Call1ProjectionVConcat
B=1 × T=2 × ValueFeature=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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 |
Call1ProjectionQSplit
B=1 × T=2 × H=1 × Dk=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. QConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | 0.4472135954999579 |
| 3 | -0.4472135954999579 |
Call1ProjectionQHeads
B=1 × H=1 × T=2 × Dk=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | 0.4472135954999579 |
| 3 | -0.4472135954999579 |
Call1ProjectionKSplit
B=1 × T=2 × H=1 × Dk=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. KConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | 0.4472135954999579 |
| 3 | -0.4472135954999579 |
Call1ProjectionKHeads
B=1 × H=1 × T=2 × Dk=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | 0.4472135954999579 |
| 3 | -0.4472135954999579 |
Call1ProjectionVSplit
B=1 × T=2 × H=1 × Dv=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. VConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | 0.4472135954999579 |
| 3 | -0.4472135954999579 |
Call1ProjectionVHeads
B=1 × H=1 × T=2 × Dv=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | 0.4472135954999579 |
| 3 | -0.4472135954999579 |
Call1RotatedQHeads
B=1 × H=1 × T=2 × Dk=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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 |
Call1RotatedKHeads
B=1 × H=1 × T=2 × Dk=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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 |
Call1RoPEAngles
Position=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Absolute position t times the single-pair frequency1, in radians.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
Call1RoPECos
Position=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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 |
Call1RoPESin
Position=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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 |
Call1Attentionraw
B=1 × H=1 × Query=2 × Key=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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 |
Call1Attentionscores
B=1 × H=1 × Query=2 × Key=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. raw/sqrt(Dk); the two-product order matches IV25 for H1,Dk2. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.28284271247461895 |
| 1 | 0.1528205697480359 |
| 2 | 0.1528205697480359 |
| 3 | 0.28284271247461906 |
Call1Attentionallowed
B=1 × H=1 × Query=2 × Key=2 · bool · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Causal and/or valid-key mask; shared validity across B and H; every query retained. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.
| Zero-based storage index | Stored value |
|---|---|
| 0 | true |
| 1 | false |
| 2 | true |
| 3 | true |
Call1Attentionlogits
B=1 × H=1 × Query=2 × Key=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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 |
Call1Attentionprobabilities
B=1 × H=1 × Query=2 × Key=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Stable allowed-key softmax for each B/H/query independently; forbidden probabilities exactly zero. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0.46754018125753244 |
| 3 | 0.5324598187424676 |
Call1AttentionOHeads
B=1 × H=1 × Query=2 × Dv=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Actual per-head P times VHeads; every product and running sum is traced. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | 0.447213595499958 |
| 3 | -0.447213595499958 |
Call1AttentionC
B=1 × T=2 × JoinedValue=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. OHeads permuted to token-major order then joined by c=h*Dv+f; values unchanged. Source is AttentionOHeads; active WO is explicitly identity2.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | 0.447213595499958 |
| 3 | -0.447213595499958 |
Call1AttentionWO
JoinedValue=2 × D=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. wo{h}{f}{d} packed in h,f,d order, preserving parameter identity. Source is AttentionOHeads; active WO is explicitly identity2.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
Call1AttentionOutput
B=1 × T=2 × D=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Y=C WO, summing products in ascending joined-feature order from zero; no normalization. Source is AttentionOHeads; active WO is explicitly identity2.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | 0.447213595499958 |
| 3 | -0.447213595499958 |
Call1R1
B=1 × T=2 × D=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Exact named-shape addition of X and AttentionOutput; no broadcasting.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.4472135954999579 |
| 1 | -0.4472135954999579 |
| 2 | 1.4472135954999579 |
| 3 | -0.447213595499958 |
Call1LN2
B=1 × T=2 × D=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Per-token feature layer norm of R1; population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside sqrt.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.6876854075163181 |
| 1 | -0.6876854075163181 |
| 2 | 0.6876854075163181 |
| 3 | -0.6876854075163181 |
Call1W1
D=2 × HiddenFeature=3 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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 |
Call1b1
HiddenFeature=3 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Shared hidden bias, added after the two products.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
Call1Z
B=1 × T=2 × HiddenFeature=3 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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.6876854075163181 |
| 4 | -0.6876854075163181 |
| 5 | 0 |
Call1Hidden
B=1 × T=2 × HiddenFeature=3 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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.6876854075163181 |
| 4 | 0 |
| 5 | 0 |
Call1W2
HiddenFeature=3 × D=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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 |
Call1b2
D=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Shared output bias, added after all three running sums.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
Call1F
B=1 × T=2 × D=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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.6876854075163181 |
| 3 | 0 |
Call1Y
B=1 × T=2 × D=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Exact named-shape addition of R1 and F; no broadcasting.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.4472135954999579 |
| 2 | 2.134899003016276 |
| 3 | -0.447213595499958 |
Call1Logits
Position=2 × Class=3 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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 | 2.134899003016276 |
| 4 | -0.447213595499958 |
| 5 | 0 |
Call1Max
Position=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Maximum computed active class logit at each position.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | 2.134899003016276 |
Call1Shifted
Position=2 × Class=3 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Computed class logit minus its saved row maximum.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | -2.582112598516234 |
| 2 | -2.134899003016276 |
| 3 | 0 |
| 4 | -2.582112598516234 |
| 5 | -2.134899003016276 |
Call1Terms
Position=2 × Class=3 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Actual exp(Shifted) before left-to-right class summation.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0.0756140929478022 |
| 2 | 0.11825653332669596 |
| 3 | 1 |
| 4 | 0.0756140929478022 |
| 5 | 0.11825653332669596 |
Call1Denominator
Position=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Shifted exponential sum from zero in ascending compact class order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.1938706262744982 |
| 1 | 1.1938706262744982 |
Call1LogS
Position=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. ln(Denominator), saved for factored NLL.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.17720065589584005 |
| 1 | 0.17720065589584005 |
Call1LSE
Position=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Max+LogS; saved evidence, not subtracted from target logits to compute NLL.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.312099658912116 |
| 1 | 2.312099658912116 |
Call1P
Position=2 × Class=3 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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.8376116959343609 |
| 4 | 0.063335248630547 |
| 5 | 0.09905305543509206 |
Call1NextRows
Position=2 · int32 · precision 0 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Highest computed logit; exact ties keep the smallest compact class.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
Call1NextIDs
Position=2 · int32 · precision 0 · Actual call1 uncached full-prefix decode, absolute positions 0..1. Public ID mapped from each computed-logit winner.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 97 |
Call1NextProbability
Position=2 · float64 · precision 8 · Actual call1 uncached full-prefix decode, absolute positions 0..1. 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.8376116959343609 |
Call1SampleInputLogits
Class=3 · float64 · precision 8 · Actual call1 last-row sampling. Validated actual sampler logits; derived logits are not clipped.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.447213595499958 |
| 2 | 0 |
Call1SampleScaledLogits
Class=3 · float64 · precision 8 · Actual call1 last-row sampling. Actual InputLogits/temperature in compact order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.447213595499958 |
| 2 | 0 |
Call1SampleBaseClassIDs
Class=3 · int32 · precision 0 · Actual call1 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Active compact prefix [97,98,512,256,257]; public IDs are labels, not offsets.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
Call1SampleBaseZ
Class=3 · float64 · precision 8 · Actual call1 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Actual finite computed input logits; no derived-input clipping.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.134899003016276 |
| 1 | -0.447213595499958 |
| 2 | 0 |
Call1SampleBaseShifted
Class=3 · float64 · precision 8 · Actual call1 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Z minus the saved active maximum.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | -2.582112598516234 |
| 2 | -2.134899003016276 |
Call1SampleBaseTerms
Class=3 · float64 · precision 8 · Actual call1 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Actual exp(Shifted), before normalization.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0.0756140929478022 |
| 2 | 0.11825653332669596 |
Call1SampleBaseDenominator
Scalar=1 · float64 · precision 8 · Actual call1 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Actual left-to-right sum of active shifted terms.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1.1938706262744982 |
Call1SampleBaseLogS
Scalar=1 · float64 · precision 8 · Actual call1 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Natural logarithm of Denominator.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.17720065589584005 |
Call1SampleBaseLSE
Scalar=1 · float64 · precision 8 · Actual call1 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Saved max+LogS in binary64.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2.312099658912116 |
Call1SampleBaseP
Class=3 · float64 · precision 8 · Actual call1 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Terms/Denominator for active classes only, without clipping or padding.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8376116959343609 |
| 1 | 0.063335248630547 |
| 2 | 0.09905305543509206 |
Call1SampleBaseNextRow
Decision=1 · int32 · precision 0 · Actual call1 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Lowest compact index among highest computed logits.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
Call1SampleBaseNextID
Decision=1 · int32 · precision 0 · Actual call1 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Public class ID gathered at NextRow.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
Call1SampleBaseNextProbability
Decision=1 · float64 · precision 8 · Actual call1 last-row sampling. Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Stored P gathered at the computed-logit winner.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8376116959343609 |
Call1SampleRankCompact
Rank=3 · int32 · precision 0 · Actual call1 last-row sampling. Descending computed ScaledLogits; exact ties ascend public ID.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 2 |
| 2 | 1 |
Call1SampleRankIDs
Rank=3 · int32 · precision 0 · Actual call1 last-row sampling. Public IDs gathered at RankCompact.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 512 |
| 2 | 98 |
Call1SampleTopKMask
Class=3 · int32 · precision 0 · Actual call1 last-row sampling. Complete active compact mask; first topK ranks are1.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
Call1SampleTopKRunning
TopKRank=3 · float64 · precision 8 · Actual call1 last-row sampling. Actual baseP rank-order running sums from zero.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8376116959343609 |
| 1 | 0.9366647513694529 |
| 2 | 0.9999999999999999 |
Call1SampleTopKMass
Scalar=1 · float64 · precision 8 · Actual call1 last-row sampling. Last actual TopKRunning value, required positive.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.9999999999999999 |
Call1SampleTopKP
Class=3 · float64 · precision 8 · Actual call1 last-row sampling. Kept BaseP/TopKMass; removed compact classes exact0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.837611695934361 |
| 1 | 0.06333524863054701 |
| 2 | 0.09905305543509207 |
Call1SampleNucleusCompact
NucleusRank=3 · int32 · precision 0 · Actual call1 last-row sampling. Actual visited top-k rank prefix, including first crossing; topP1 visits all.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 2 |
| 2 | 1 |
Call1SampleNucleusIDs
NucleusRank=3 · int32 · precision 0 · Actual call1 last-row sampling. Public IDs at actual visited nucleus ranks.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 512 |
| 2 | 98 |
Call1SampleNucleusBefore
NucleusRank=3 · float64 · precision 8 · Actual call1 last-row sampling. Actual cumulative operand before each visited TopKP addition.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0.837611695934361 |
| 2 | 0.936664751369453 |
Call1SampleNucleusRunning
NucleusRank=3 · float64 · precision 8 · Actual call1 last-row sampling. Actual cumulative TopKP in visited rank order.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.837611695934361 |
| 1 | 0.936664751369453 |
| 2 | 1 |
Call1SampleNucleusCrossed
NucleusRank=3 · int32 · precision 0 · Actual call1 last-row sampling. Exact saved cumulative>=topP predicate for each visit.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 1 |
Call1SampleNucleusContinue
NucleusRank=3 · int32 · precision 0 · Actual call1 last-row sampling. Actual next-visit decision, including topP===1 special policy.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 0 |
Call1SampleFinalMask
Class=3 · int32 · precision 0 · Actual call1 last-row sampling. Complete active compact mask of actually visited nucleus entries.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
Call1SampleFinalRunning
NucleusRank=3 · float64 · precision 8 · Actual call1 last-row sampling. Second actual kept TopKP mass accumulation in rank order, from zero.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.837611695934361 |
| 1 | 0.936664751369453 |
| 2 | 1 |
Call1SampleFinalMass
Scalar=1 · float64 · precision 8 · Actual call1 last-row sampling. Last actual FinalRunning value, required positive.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
Call1SampleFinalP
Class=3 · float64 · precision 8 · Actual call1 last-row sampling. Actual kept TopKP/FinalMass; all removed entries exact0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.837611695934361 |
| 1 | 0.06333524863054701 |
| 2 | 0.09905305543509207 |
Call1SampleCDFCompact
CDFEntry=3 · int32 · precision 0 · Actual call1 last-row sampling. Retained compact indices sorted separately by ascending public ID.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
Call1SampleCDFIDs
CDFEntry=3 · int32 · precision 0 · Actual call1 last-row sampling. Ascending public IDs, including retained zero-probability entries.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
Call1SampleCDFBefore
CDFEntry=3 · float64 · precision 8 · Actual call1 last-row sampling. Actual final-P cumulative operand before each public-order addition.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0.837611695934361 |
| 2 | 0.9009469445649081 |
Call1SampleCDFRunning
CDFEntry=3 · float64 · precision 8 · Actual call1 last-row sampling. Actual public-order cumulative sum; last entry is not forced to1.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.837611695934361 |
| 1 | 0.9009469445649081 |
| 2 | 1.0000000000000002 |
Call1SampleRNGState
StateEndpoint=2 · float64 · precision 0 · Actual call1 last-row sampling. Initial and next unsigned uint32 states stored exactly in float64, without int32 conversion.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1013904223 |
| 1 | 1196435762 |
Call1SampleRNGArithmetic
IntegerOperand=3 · float64 · precision 0 · Actual call1 last-row sampling. Actual signed imul low32 product, increment and exact integer-valued sum in float64.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 182531539 |
| 1 | 1013904223 |
| 2 | 1196435762 |
Call1SampleUniform
Draw=1 · float64 · precision 8 · Actual call1 last-row sampling. Exact dyadic nextSeed/2^32, in [0,1); exactly one draw.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.278566908556968 |
Call1SampleSampledRow
Decision=1 · int32 · precision 0 · Actual call1 last-row sampling. Compact class selected from the actual final CDF and draw.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
Call1SampleSampledID
Decision=1 · int32 · precision 0 · Actual call1 last-row sampling. Public ID at SampledRow; distinct from BaseNextID greedy metadata.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
Call1SampleSampledProbability
Decision=1 · float64 · precision 8 · Actual call1 last-row sampling. Stored FinalP gathered at SampledRow, never the base greedy probability.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.837611695934361 |
PromptIDs
PromptPosition=1 · int32 · precision 0 · Actual EOS-off BPE prompt, tokenized exactly once.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
GeneratedIDs
Emission=2 · int32 · precision 0 · Actual emitted public IDs in decision order, including a stopping EOS if present.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 97 |
ResultIDs
LogicalPosition=3 · int32 · precision 0 · Exact prompt IDs followed by actual emissions; no retokenization.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 97 |
| 2 | 97 |
ConsumedGenerated
Emission=2 · int32 · precision 0 · 1 only if this generated ID was actually fed into a subsequent forward call; terminal tail remains0.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 0 |
ObservedIDs
ObservedPosition=2 · int32 · precision 0 · Exact prefix processed by the final actual forward call; excludes the terminal emitted tail.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 97 |
CallLengths
ModelCall=2 · int32 · precision 0 · Actual number of observed token rows in each full-prefix call.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 2 |
CallLastRows
ModelCall=2 · int32 · precision 0 · Actual last computed row used for each decision.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 1 |
OutputPositions
Emission=2 · int32 · precision 0 · Absolute logical output slot selected by each last-row decision; terminal slot has no computed row.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 2 |
SelectedRows
Emission=2 · int32 · precision 0 · Actual selected compact class for each emission.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0 |
| 1 | 0 |
SelectedModelProbabilities
Emission=2 · float64 · precision 8 · Actual unscaled last-row model P gathered at each selected compact class, including sampled non-greedy choices.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8376116959343609 |
| 1 | 0.8376116959343609 |
SelectedTemperatureBaseProbabilities
Emission=2 · float64 · precision 8 · Selected compact-class probabilities from the actual full temperature-scaled base distribution, before filtering.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.8376116959343609 |
| 1 | 0.8376116959343609 |
SelectedSamplingProbabilities
Emission=2 · float64 · precision 8 · Actual FinalP gathered at each selected compact class; sampling-policy probability, separate from raw model P.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 0.837611695934361 |
| 1 | 0.837611695934361 |
WorkRunning
ModelCall=2 · int32 · precision 0 · Actual cumulative number of token rows recomputed, including old-prefix rows.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 3 |
ScoreRunning
ModelCall=2 · int32 · precision 0 · Actual cumulative full T*T raw query/key score cells, including future masked cells.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 1 |
| 1 | 5 |
PendingID
PendingTail=1 · int32 · precision 0 · Final emitted logical ID, not processed by an extra neural call.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
PendingPosition
PendingTail=1 · int32 · precision 0 · Logical slot of final unprocessed emitted ID; not a fabricated forward position.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 2 |
ResultBytes
Bytes=3 · int32 · precision 0 · Actual learned-piece expansions passed to the strict reverse decoder; stopping EOS emits no bytes.
| Zero-based storage index | Stored value |
|---|---|
| 0 | 97 |
| 1 | 97 |
| 2 | 97 |
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 aaa with merges0 and maxNew2: a non-EOS first choice can emit a fourth logical ID, then context capacity stops another call. Try a strong EOS bias: the marker stops before it is ever fed back. maxNew1 checks the emission budget after EOS and before context. Repetition is permitted, and absolute positions always start at0 for the retained prefix.
These are hand-set, untrained weights. The finite32bit LCG is a deterministic pseudorandom stream; elementary-library rounding near a filter/CDF boundary can change a valid path across platforms. Input edits, reset and trace navigation clear grades; independent record inspectors leave them unchanged.
At reset, sampling uses temperature1, top-k3, top-p1, seed0 and a two-token generation budget. The actual call inputs are [97] and then [97,97]. The emitted IDs are [97,97], decoding to aa; together with the prompt, logical result IDs are [97,97,97], decoding to aaa. The final third a has been emitted but has not been processed by another model call.
Use Actual model call to inspect, Observed position / attention query, Attention key position and Active compact model class to inspect saved evidence. Only executed calls appear, and indices clamp to actual current shapes. In sampling mode the additional Active compact sampling class to inspect reads that call’s last-row sampler independently of the model-row inspector. These selectors preserve graded answers. Calculation step selects trace evidence independently; raw input edits, Reset example and trace navigation clear grades. Changing an inspector does not change which final row actually emitted a token.
Review IV-44 — Prefill and Single-Token Decode for prefill, absolute positions and uncached recomputation; IV-45 — From Logits to the Next Token for greedy choice; and IV-46 — Temperature, Top-k and Nucleus Sampling for the complete seeded sampling policy. Book II’s II.9 — Matrix × vector and II.10 — Matrix × matrix as composition explain the products and shapes below, while VIII.10 — Reproducibility, random seeds, and nondeterminism explains reproducible streams. Book III’s III-16 — Multiclass Classification and Softmax Regression reviews class probabilities and III-39 — Reproducibility and Numerical Reliability numerical reliability. The composed forward calculations in III-40 — From Linear Model to Artificial Neuron and III-41 — Composition and Learned Representations prepare the same distinction used here: calculating with disclosed fixed weights is not training them.
Four different things to count
Autoregressive generation means choosing a new item conditional on the already observed prefix, then using that item in a later prefix if the loop continues. A prompt is the initial supplied text. A token is a piece with an integer public ID. Byte-pair encoding, or BPE, learns and applies explicit piece-combination rules. Prompt tokenization occurs once with the fixed training corpus abab, merges0..2 and automatic EOS insertion off.
Prefill is the first model call on the actual prompt IDs. A later decode call here recomputes the entire observed prefix. A key/value cache, or KV cache, would reuse saved attention keys and values; this implementation has none. Both cache-used and cache-entry counts remain0. There is no eviction or hidden sliding window.
Keep four lists or counts separate. Observed IDs enter an executed forward call. Generated IDs are actual choices emitted by this loop. Logical result IDs contain the original prompt followed by those emissions. Work tokens count all input rows recomputed across calls. A newly emitted token need not already be a consumed model input.
| Actual call | Observed IDs; positions | Last row used for choice | Emission; next RNG state | Work rows | Logical result after append |
|---|---|---|---|---|---|
| Prefill | [97]; [0] | row0, conditional on a | a/97; 1013904223 | 1 | [97,97] |
| Uncached decode | [97,97]; [0,1] | row1, conditional on aa | a/97; 1196435762 | 2 | [97,97,97] |
Thus model calls=2, generated tokens=2, work tokens=1+2=3, newly generated IDs consumed by later calls=1, and logical result token count=3. The stop is the token budget. There is no third call on [97,97,97], no output row for the final pending a, and no third RNG draw. Attention score-cell work is1²+2²=5 for the two saved full matrices; this is a source-level operation count, not measured time or a claim about production speed.
The pending a still has a saved probability as the token selected after aa. That probability comes from row1 of the second call. What is absent is a new forward row that treats this final a as an input and predicts a token after aaa. A probability of an emitted token and a probability row computed from that token are different evidence.
Name the vocabulary, parameters and shapes
The fixed compact map is [97,98,512,256,257], meaning a, b, EOS, ab, abab. EOS means end of sequence, an explicit terminal marker here. Compact indices are0..4; public ID512 addresses compact row2 rather than requiring513 rows. With m merges, active vocabulary count V=3+m takes the first V entries of that map. The m used here is a merge count, distinct from a maximum in softmax.
An embedding gathers a feature row for an input ID. The full embedding matrix E has five rows and two feature columns. At reset its rows are (1,0), (0,1), (0,0), (1/2,1/2), (1,1). The readout converts final feature rows into class scores with U’s two rows (1,0,0,0,0) and (0,1,0,0,0), then adds the zero bias vector. These are hand-set untrained parameters. All ten E entries, ten U entries and five biases are stored and validated, including inactive values.
Control names follow those indices: e30 is embedding row3, feature0; u12 is readout feature1, compact class2; b2 is the bias for that same class, EOS512. merges controls actual BPE rules and hence the active prefix V. Editing a public ID’s embedding changes its gathered feature row; it does not change the token’s byte expansion or use the public integer as a feature.
A tensor is an array with named dimensions. Let T denote the current call’s actual observed-token count. Batch count B=1, feature width D=2, head count H=1, query/key width Dk=2, value width Dv=2 and hidden FFN width3 are fixed. Here T is a token count, not temperature; temperature is τ.
| Quantity | Shape; named axes | Meaning |
|---|---|---|
| E; U; bias | [5,2]; [2,5]; [5] | ModelRow×D embeddings, D×ModelRow readout, ModelRow biases |
| Input IDs; gathered rows | [T]; Position | Public names and compact storage addresses |
| X, LN1, R1, LN2, F, Y | [1,T,2]; B,T,D | Gathered, normalized, residual and final features |
| Q, K, value heads | [1,1,T,2]; B,H,T,Dk or Dv | Queries, keys and features to mix |
| Attention scores, mask, weights | [1,1,T,T]; B,H,Query,Key | Comparisons, permissions and normalized mixing weights |
| FFN hidden features | [1,T,3]; B,T,HiddenFeature | Three computed hidden coordinates |
| Logits; base probabilities | [T,V]; Position,Class | Every actual row, active classes only |
| Sampling scores, masks, probabilities | [V]; Class | Choice evidence for the final computed row only |
A query compares the current position with keys at allowed positions; values supply the features mixed by those comparisons. One head performs one such mixture. An attention weight is a probability over key positions; a class probability is over possible next-token classes. They are different arrays even when their dimensions are small. A causal mask permits key j only when j≤i for query i. Masked attention probabilities are exactly0; the full raw score matrix can still contain forbidden comparisons.
A residual adds a branch’s input features back to its transformed features. Layer normalization centers and rescales features within each token. A feed-forward network, or FFN, transforms features within that same row. These operations do not mix a future token into an earlier query. Feature-last rows [T,2] multiplied by U’s active columns [2,V] give [T,V]; this explicitly transposes the storage viewpoint of the earlier books’ mathematical column vectors. An ID is a label, not a scalar feature multiplied by U.
Derive the full one-a forward call
The following hand calculation uses exact real arithmetic. The trace must retain the actual scalar products, sums and library functions; simplified identities are explanations, not replacements for saved computed operands.
Gather a/97 to obtain X=(1,0). For a two-feature row x=(x₀,x₁), the fixed normalization uses
μ is the mean, v the population variance and d is feature0 or1. The constant1 inside the root is epsilon. Fixed scale γ=(1,1) and offset β=(0,0) then leave n unchanged. For X=(1,0), μ=1/2, centered features (1/2,−1/2), squared deviations (1/4,1/4), variance1/4 and root√5/2. Define α=1/√5, so LN1=(α,−α).
Q, K and value projections are identity matrices. Each projected first coordinate is α·1+(−α)·0=α; the second is α·0+(−α)·1=−α. RoPE, rotary positional encoding, rotates Q and K at absolute position t through t radians:
The only pair has frequency1; t=0 uses cos0=1 and sin0=0, retaining (α,−α). Values are not rotated. The only dot product is α·α+(−α)·(−α)=2α². Divide by√Dk=√2 and define g=2α²/√2. There is one allowed key. Subtract maximum g, exponentiate0 to1, add starting at0, then divide1/1: attention weight1. Weighted value coordinates are 0+1·α=α and 0+1·(−α)=−α. Identity output projection preserves them.
The first residual is R1=(1+α,−α). Its mean is1/2. Define Δ=1/2+α; centered features are (Δ,−Δ), the sum of squared deviations is2Δ² and the variance isΔ². Define ρ=Δ/√(Δ²+1), giving LN2=(ρ,−ρ).
The fixed FFN weights have rows (1,0,0),(0,1,0) in W1 of shape [2,3], and (1,0),(0,1),(0,0) in W2 of shape [3,2]; both biases are0. Thus the three preactivations are (ρ,−ρ,0). ReLU keeps a positive value, replaces a negative value by0 and maps0 to0, so hidden features are (ρ,0,0). Output sums are ((0+ρ·1)+0·0)+0·0=ρ and ((0+ρ·0)+0·1)+0·0=0. The third coordinate is computed, not omitted.
The second residual gives Y=(1+α+ρ,−α). Write A=1+α+ρ. Readout class a is A·1+(−α)·0+0=A; b is A·0+(−α)·1+0=−α; EOS is A·0+(−α)·0+0=0. Therefore the logits are (A,−α,0). Since A>0, subtract maximum A to obtain (0,−α−A,−A). With h=exp(−α−A) and j=exp(−A), the compact running denominator is1,1+h,(1+h)+j, starting at0. The whole real class row is
P is conditioned on the actual supplied prefix a. Both h and j lie strictly between0 and1, so S<3 and P_a=1/S>1/3. The first seed draw is 1013904223/4294967296<1/3; sampling selects a. No token score has been trained to make that happen.
Derive the second call rather than assuming repetition
After the first nonterminal emission, the next observed IDs are [97,97]. Gathering and both local normalizations repeat the same feature calculations for each row, with positions0 and1. RoPE supplies q₀=k₀=(α,−α) and
The two diagonal dot sums are2α². Either off-diagonal dot sum simplifies to2α²cos1. After division by√2 the ideal full score matrix has rows (g,g cos1) and (g cos1,g). The row0/key1 comparison is forbidden. Its masked weight is0, so row0’s attention weights are (1,0) and its mixed value remains (α,−α).
For the last row, maximum g gives shifted terms (exp(g(cos1−1)),1). Define q=exp(g(cos1−1)); its ordered denominator is (0+q)+1=q+1. Attention weights are (q/(q+1),1/(q+1)). Both unrotated values are (α,−α), so the first mixed coordinate is
and the second is its negative. This is why, in exact real arithmetic, both rows have the same R1, Δ, ρ, FFN output, Y and logits (A,−α,0) derived above. Software still computes both products and additions; rounded weights need not sum to exactly1, and the stored rows need not be bitwise identical to this simplification or to each other.
The second selection uses row1 from the actual call on aa. At τ=1,k=3,p=1, all three class candidates survive. Their score rank is a, EOS, b, since A>0>−α. Their public-ID CDF order is a, b, EOS. The ideal-real ranked base mass runs 1/S, (1+j)/S,1. Top-k Q equals P in reals, top-p1 keeps all three, and the final kept-Q mass runs through the same ranked values before the final division. The actual trace saves every computed stage even when its real simplification is identity. CDF cumulatives in public order are 1/S, (1+h)/S,1.
The LCG’s second full product plus increment is
Hence the next state is1196435762. Its numerator multiplied by3 is3589307286<4294967296, so this uniform is also below1/3. Since the last row’s ideal P_a>1/3, the second choice is a. These inequalities establish the hand example’s separated real decisions; independent numerical bounds must also bind the actual computed rows. They are not observed runtime outputs.
Every emission has a raw model conditional probability: gather P from that actual forward call’s final row at the compact class actually selected. For the first default a this means the row conditional on prefix a; for the second it means the row conditional on prefix aa. Sampling may choose a non-greedy class, so the greedy winner’s NextProbability cannot supply this value. The class map must be the actual forward map. This is not a marginal probability for a anywhere in a string, and an old or independently inspected row cannot replace the current final row.
In sampling mode there is also a sampling-policy probability, gathered from the actual sampler FinalP at that same selected class. It can differ from the raw model P because temperature and filters change the distribution. Even the sampler’s temperature-scaled full-vocabulary base P is distinct from the unscaled forward P. At reset all three have the same exact-real expression1/S, but their actual saved computations still remain separate evidence. In greedy mode preserve the chosen class’s raw model P; do not overwrite it with1 or invent a sampledProbability, sampling array or draw. The deterministic choice rule and the model’s probability are different statements.
The fixed-seed LCG run is deterministic and each draw belongs to the finite grid of integer multiples of2⁻³² below1. These policy probabilities do not establish independent continuous random draws, exact empirical frequencies over a run, or language quality.
A non-greedy emission separates the three probabilities
Set every E entry to0, all biases0 except b1=1, temperature2, top-k2, top-p1, seed634785765 and maxNew1. Leave the other reset parameters unchanged. Every hidden row and Y is0, so the raw model logits are (0,1,0). The greedy winner is b/98, with raw model probability e/(e+2). Temperature division gives (0,1/2,0). Write f=exp(1/2)=√e. Its full temperature-base distribution is (1,f,1)/(f+2). Ranking keeps b then a, since a97 precedes EOS512 on the score0 tie. Their base mass is (f+1)/(f+2); top-k renormalization and top-p1 give the real final distribution (1,f,0)/(f+1).
The exact seed preimage from IV-46 produces u0. Public CDF order begins with a, whose positive interval therefore wins, even though b had the greatest raw logit. The selected compact class is0. For this same emitted a conditional on the current prefix, raw model P is 1/(e+2), temperature-base P is 1/(f+2), and final sampling-policy P is 1/(f+1). The greedy winner’s e/(e+2) is a different class’s probability and must not be copied as a’s model P. These are exact-real derivations; each corresponding saved floating computation must remain its own actual evidence.
The loop’s order decides what exists
Before each forward call, require an observed prefix of at most3 IDs. Compute all its rows, choose from its final row, append exactly that public ID, then evaluate stopping in this order:
- EOS: stop immediately if the emitted ID is512.
- Token budget: otherwise stop if the number emitted has reached
maxNew, which is1 or2. - Context cap: otherwise stop if feeding the extended prefix into another call would exceed3 observed IDs.
Only if continuing does the emitted non-EOS ID enter the next forward call. Absolute positions are always0..T−1; a new API call does not reset the appended token’s position to0. Repetitions are allowed. There is no repetition penalty or hidden forced alternate token.
For an EOS example, set every E entry to0, keep the other reset readout values, and set EOS bias b2=4 while other biases are0. Every hidden row and Y is0; the class logits are (0,0,4). Under greedy strategy, EOS uniquely wins. Under sampling with k=1, only EOS remains and it is selected with final-policy probability1, still consuming one draw. Its raw model probability remains exp(4)/(exp(4)+2), strictly below1; greedy determinism also leaves that model probability unchanged. With maxNew=2 this is one call and one emission; EOS wins before considering a second call. No EOS embedding is gathered, no second-call tensor is created, and strict decoding strips the terminal marker. With maxNew=1, EOS still has precedence over the simultaneously exhausted budget.
For the context example, use raw text aaa, merges0 and greedy reset parameters. The actual prompt has3 IDs. Every value row is the same a embedding’s normalized value; causal mixtures preserve it in exact real arithmetic, so the dominant a readout remains the hand expectation. One call may emit a logical fourth ID. At maxNew=2, the loop stops for context because another call would need four observed IDs. It never processes T=4. At maxNew=1, the same append stops for budget first. The output may contain four logical IDs while the last one has no Y, logits, P, RoPE or attention row. A logical append slot is not evidence of an executed model position.
Greedy strategy0 selects the saved greatest computed logit with IV-45’s lowest-compact-index tie rule. It uses zero RNG draws and leaves the seed unchanged. It does not create pretend temperature/filter/CDF/RNG arrays for that decision. Sampling strategy1 executes IV-46’s actual policy and advances once per emission, including k=1. Each sampling emission keeps both its raw forward P at the selected class and its final sampling-policy probability. A greedy-winner probability is not a substitute when sampling selects a different class. Sampling fields still validate in greedy mode.
Preserve token boundaries and decode the result strictly
The next input prefix is assembled from actual IDs, never by decoding text and retokenizing it. With two learned merges, the rules combine a,b to256 and then256,256 to257. A prompt ab becomes [256]. If a policy emits256, the next prefix is [256,256], decoding to abab; freshly tokenizing those characters would give [257], a different model input and work count.
After stopping, the strict decoder expands the final logical IDs with the actual learned rules, removes EOS only when EOS actually stopped the run, reconstructs UTF-8 bytes and decodes valid Unicode scalars. At reset [97,97,97] expands one byte97 per ID and gives bytes [97,97,97], hence aaa. This is reconstruction from real ID expansions, not a hard-coded returned word. The prompt remains part of the decoded logical result.
With all E entries and biases0, all final features and logits are0, giving uniform base class probabilities. Greedy ties select compact0; sampling still follows its seed and filters. Neither repeated a nor a changed continuation establishes learned language ability. No targets, loss, derivatives, parameter updates or training process are part of this loop.
Read the actual calls and their probability evidence
The first four summaries are generatedTokens, modelCalls, workTokens, finalSeed: reset gives2,2,3,1196435762 by the hand derivation. The root is status,outputs,steps,tensors,texts. stopReason is EOS, TOKEN_BUDGET or CONTEXT_LIMIT; numeric stopCode is1,2 or3 respectively. It is0 only at a continuing append. pendingID and pendingPosition identify the final logical emission without asserting another neural row.
Call0InputIDs and, only when executed, Call1InputIDs show actual call inputs. Their complete forward tensors include Call0Y, Call0Logits, Call0P and the corresponding Call1 tensors. For call j, inspect call{j}_decision and its actual lastRow input, then selectedRow and selectedID outputs. call0SelectedModelProbability and any call1SelectedModelProbability are gathered from those actual unscaled forward P rows. SelectedModelProbabilities has shape [modelCalls], axis Emission. It retains a raw model probability for every emission, even a sampled non-greedy class.
Only sampling adds call0SelectedTemperatureBaseProbability and call0SelectedSamplingProbability, with corresponding call1 fields only for an executed second call. Tensors SelectedTemperatureBaseProbabilities and SelectedSamplingProbabilities have that same Emission shape. The final-emission aliases are selectedModelProbability and, sampling only, selectedTemperatureBaseProbability and selectedSamplingProbability. They are different sources, not interchangeable copies of a greedy winner. For a sampling call j, the full helper evidence is prefixed Call{j}Sample: its BaseP is temperature-scaled, while FinalP is post-filter. Greedy has none of those sampling arrays or sampling-only aliases.
PromptIDs, GeneratedIDs, ResultIDs and ObservedIDs distinguish the four lists discussed above. At reset they are [97], [97,97], [97,97,97] and [97,97]. ConsumedGenerated is [1,0], CallLengths is [1,2], CallLastRows is [0,1], OutputPositions is [1,2], WorkRunning is [1,3] and ScoreRunning is [1,5]. The one-entry PendingID and PendingPosition identify97 at logical position2. ResultBytes comes from actual strict expansion. No absent call1 field or pending neural probability is filled with zero.
The full trace retains tokenizer_*, then each actual call0_*/call1_* forward and optional sampling operation, its decision and append, actual result_* strict decoding, and finish. Source counting gives236 default sampling steps/227 tensors or198 greedy steps/147 tensors for the same real default path. The maximum source bound is436 steps: forward311, sampler46, prompt55, decoder18 and outer6. The conservative signed bound476 is also below480 and the trace cap512. These counts explain complete retention; none is runtime evidence.
Input limits and honest numerical evidence
The raw state contains text, the original26 numeric tiny-model fields, then strategy, temperature, topK, topP, seed and maxNew. String type is checked first; all numeric fields validate in their original order before Unicode or prompt-domain semantics. Strategy must be integer0 or1; τ∈[1/4,4], integer k1..V, 0<p≤1, integer seed0..4294967295, integer maxNew1..2. E/U entries lie in [−2,2], biases in [−4,4], and merges is integer0..2. Invalid inactive parameters or sampling controls invalidate even a greedy or EOS-stopping state. No coercion, extra fields or accessors are accepted.
The prompt is raw a/b text, at most6 UTF-8 bytes, with no trimming or normalization. Validation checks more than6 UTF-16 units before malformed surrogates, then actual byte length, then alphabet and finally empty text. Empty text is UNAVAILABLE. Actual BPE must produce1..3 prompt IDs; a longer prefix is UNSUPPORTED_SIZE and is never cropped. This is a new three-token prompt boundary, not a hidden relaxation of IV-44’s two-token prompt helper.
Each executed forward retains all57 real tensor records and all primitive steps. Prompt BPE, actual choices, RNG operations, append/stop decisions and final strict decoding remain evidence too. An absent call or greedy sampling branch has no fabricated arrays to inspect. Row-work counts and score-cell counts describe this bounded uncached program, not benchmarks. The two-call worst case uses lengths2 and3, not two calls of length3: a length3 observed prefix can only emit once before context stopping. No trace truncation is justified by calling a pending tail an unobserved row.
An independent conditional witness checks this actual path: independently tokenize the prompt, verify the current observed-prefix forward record, bind the choice logits to its actual final row, verify the filter arithmetic and exact RNG, then append the verified emission. Repeat only if the declared stop policy permits it. It must also check copies, aliases, shapes, orders, absent branches and final decoding. A fixed seed guarantees the integer uniform stream; it does not guarantee one universal floating-point token path near probability boundaries across elementary libraries. A different ID cannot be hidden inside a larger numeric tolerance.
The numerical bounds assume the declared four-ulp elementary-library allowance, nearest binary64 rounding, gradual underflow and unfused products/additions. An ulp is a spacing unit between adjacent representable values at the relevant magnitude. These are explicit conditions for the independent enclosures, not measured properties of an environment checked in this chapter.
The algebra above is an independent manual derivation, not an executed numerical acceptance check. The ordinary finite-precision operation order, transcendental bounds, actual UI, Python parity and full witness validators require separate runtime evidence. IV-08 and IV-25 remain source-protected, not runtime-frozen.
Read the actual Python loop and its complete local closure
All eleven panels below import the maintained source files as raw text. Keep their relative directories intact. NumPy is the external numerical dependency; the loaders and command-line handling use Python’s standard library. The wrapper supports defaults, one complete replacement JSON state and - for JSON on standard input. Missing fields are errors, not a partial update merged with reset values. Displaying this source does not run it or establish numerical parity.
1. Chapter wrapper — code/python/p11/iv47.py. derive_iv47 returns the complete guarded generation record, including texts. Invalid inputs produce the typed unavailable triple instead of a stale successful trace. The wrapper’s source_self_check is an explicit leaf.
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.
"""IV47 canonical full ordered generation record.
Preserve the disclosed eleven-file relative closure. No-argument default,
complete replacement JSON and '-' stdin never invoke any self-check.
All checks and execution remain UNRUN under the hard resource hold.
"""
import importlib.util
from pathlib import Path
from types import MappingProxyType
_path = Path(__file__).resolve().with_name("generation_reference.py")
_spec = importlib.util.spec_from_file_location("_p11_generation_reference", _path)
if _spec is None or _spec.loader is None:
raise ImportError(f"Cannot load canonical dependency: {_path}")
_helper = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_helper)
DEFAULT_IV47 = MappingProxyType(dict(_helper.DEFAULT_IV47))
@_helper.guarded
def derive_iv47(state):
"""Return the full actual bounded-generation record, including real texts."""
return _helper.generation_record(state)
def source_self_check():
"""DEFERRED wrapper-only leaf assertions; invokes no other self-check."""
assert __debug__, "Deferred checks require assertions enabled."
assert Path(_helper.__file__).resolve() == _path
state = dict(DEFAULT_IV47)
result = derive_iv47(state)
assert list(result) == ["status", "outputs", "steps", "tensors", "texts"]
assert list(result["outputs"])[:4] == ["generatedTokens", "modelCalls", "workTokens", "finalSeed"]
assert [result["outputs"][key] for key in ("generatedTokens", "modelCalls", "workTokens", "finalSeed")] == [2, 2, 3, 1196435762]
assert result["texts"]["decoded"] == "aaa"
assert len(DEFAULT_IV47) == 33
for raw in ({}, None, [], {**state, "extra": 0}):
rejected = derive_iv47(raw)
assert list(rejected) == ["status", "code", "reason"] and rejected["code"] == "INVALID_INPUT"
assert derive_iv47({**state, "strategy": 0, "seed": True})["code"] == "NONFINITE"
assert derive_iv47({**state, "text": "\ud800", "maxNew": 0})["code"] == "INVALID_INPUT"
result["outputs"].clear()
result["texts"]["decoded"] = "changed"
repeated = derive_iv47(state)
assert repeated["texts"]["decoded"] == "aaa" and state == dict(DEFAULT_IV47)
if __name__ == "__main__":
_helper._tiny.run(derive_iv47, DEFAULT_IV47)
2. Bounded loop — code/python/p11/generation_reference.py. generation_state validates all33 raw fields. generation_prompt enforces the new three-token bound, obtains actual IV39 prompt evidence once and preserves the original raw text. _tokenizer_rules reconstructs the actual learned rules. generation_record calls forward_tiny on each real observed prefix, chooses from its last row, gathers raw model P at the selected class and, sampling only, saves its temperature-base and final-policy probabilities. Follow the append, stop and continuation branches before the strict final decoder. The returned record keeps complete actual operands,57 tensors per call and detached texts; no final emitted ID receives a fictional forward call.
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.
"""Bounded uncached IV47 generation, canonical NumPy source under the hold.
Tokenize once through actual IV39; reuse actual forward_tiny on observed IDs;
append a real sampled/greedy public ID; stop before a fourth input is processed.
Complete records follow the owner-adopted actual inventory.
"""
from functools import wraps
import importlib.util
import json
from pathlib import Path
from types import MappingProxyType
import numpy as np
_ROOT = Path(__file__).resolve().parent.parent
def _load(name, path):
"""Resolve the exact disclosed source independently of cwd and sys.path."""
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise ImportError(f"Cannot load canonical dependency: {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
_sampling = _load("_iv47_sampling_reference", Path(__file__).resolve().with_name("sampling_reference.py"))
_tiny = _load("_iv47_tiny_reference", _ROOT / "p10" / "tiny_reference.py")
_iv39 = _load("_iv47_iv39", _ROOT / "p09" / "iv39.py")
_bpe, _token = _iv39._bpe, _iv39._bpe._token
NumericalFault = _tiny.NumericalFault
# Tiny and IV39 load separate codec instances; sampling loads its own choice.
_DEPENDENCY_FAULTS = (*_tiny._DEPENDENCY_FAULTS, _bpe.NumericalFault, _sampling.NumericalFault)
NUMERIC_DEFAULTS = _tiny.NUMERIC_DEFAULTS
DEFAULT_IV47 = MappingProxyType(dict(text="a", **NUMERIC_DEFAULTS, strategy=1,
temperature=1, topK=3, topP=1, seed=0, maxNew=2))
STOP_EOS, STOP_TOKEN_BUDGET, STOP_CONTEXT_LIMIT = 1, 2, 3
STOP_REASONS = {STOP_EOS: "EOS", STOP_TOKEN_BUDGET: "TOKEN_BUDGET", STOP_CONTEXT_LIMIT: "CONTEXT_LIMIT"}
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 generation_state(state):
"""String type, all26 numeric fields, then all six generation controls."""
_tiny._object(state, DEFAULT_IV47, "state")
if type(state["text"]) is not str:
raise NumericalFault("INVALID_INPUT", "text must be an actual string, without coercion.")
numeric = _tiny.numeric_parameters({key: state[key] for key in NUMERIC_DEFAULTS})
strategy = _tiny.finite(state["strategy"], "strategy")
if not strategy.is_integer() or strategy not in (0, 1):
raise NumericalFault("INVALID_INPUT", "strategy must be 0 (greedy) or 1 (sampling).")
options = _sampling.sampling_options({key: state[key] for key in _sampling.OPTION_FIELDS}, 3 + numeric["merges"])
max_new = _tiny.finite(state["maxNew"], "maxNew")
if not max_new.is_integer() or not 1 <= max_new <= 2:
raise NumericalFault("INVALID_INPUT", "maxNew must be an integer from 1 to 2.")
return dict(text=state["text"], numeric=numeric, strategy=int(strategy), **options, maxNew=int(max_new))
def generation_prompt(text, merges):
"""Actual learned EOS-off BPE with the NEW three-observed-token boundary.
The manual encoder precheck validates Unicode/byte length only. IV39 supplies
every saved training, encoding, rule, reconstruction and text record once.
"""
if type(text) is not str:
raise NumericalFault("INVALID_INPUT", "text must be an actual string, without coercion.")
merges = _tiny.finite(merges, "merges")
if not merges.is_integer() or not 0 <= merges <= 2:
raise NumericalFault("INVALID_INPUT", "merges must be an integer from 0 to 2.")
merges = int(merges)
if _token.utf16_length(text) > 6:
raise NumericalFault("UNSUPPORTED_SIZE", "text: more than 6 UTF-16 units exceeds the 6-byte input bound.")
encoded = _token.utf8_encode(text)
if len(encoded["bytes"]) > 6:
raise NumericalFault("UNSUPPORTED_SIZE", "text: the actual UTF-8 encoding exceeds 6 bytes.")
if any(character not in "ab" for character in text):
raise NumericalFault("UNAVAILABLE", "This toy model supports only raw a and b letters, without normalization or truncation.")
if not text:
raise NumericalFault("UNAVAILABLE", "Empty text has no observed prompt token.")
prompt = _iv39.derive_iv39(dict(corpus="abab", text=text, merges=merges, eos=0))
if prompt["status"] != "defined":
raise NumericalFault(prompt["code"], prompt["reason"])
ids = np.array(next(record["values"] for record in prompt["tensors"] if record["id"] == "TargetIDs"), dtype=np.int32)
if len(ids) > 3:
raise NumericalFault("UNSUPPORTED_SIZE", "The actual BPE prompt exceeds 3 tokens; change text or merges explicitly.")
return prompt, ids
def _tokenizer_rules(prompt):
"""Reconstruct only the actual learned rules saved by readonly IV39."""
tensors = {record["id"]: record for record in prompt["tensors"]}
if "RuleIDs" not in tensors:
return []
rules = [dict(id=identifier, left=tensors["RuleLeft"]["values"][rank], right=tensors["RuleRight"]["values"][rank],
bytes=np.array(tensors[f"Rule{identifier}Bytes"]["values"], dtype=np.int32))
for rank, identifier in enumerate(tensors["RuleIDs"]["values"])]
_bpe.rule_table(rules)
return rules
def generation_record(state):
"""Complete actual bounded-generation record; NumPy computes every value.
All57 forward tensors survive each actual call. A final emitted logical ID
is pending, without a fabricated model row. The selected raw model P and
optional sampling probabilities remain different, exact copied operands.
"""
s = generation_state(state)
numeric, strategy, V = s["numeric"], s["strategy"], 3 + s["numeric"]["merges"]
prompt, prompt_ids = generation_prompt(s["text"], numeric["merges"])
trace = _tiny.tiny_trace()
trace.add("setup", "Validate every raw field, then tokenize the prompt exactly once", "strategy0 greedy or1 sampling; maxNew1..2; observed context<=3; fixed corpus abab, EOS off",
"All 33 raw fields validate even in greedy mode. The real tokenizer, full-prefix forward kernel and strict reverse decoder retain their complete evidence.",
{**numeric, **{key: s[key] for key in ("strategy", "temperature", "topK", "topP", "seed", "maxNew")}},
dict(utf16Units=_token.utf16_length(s["text"]), byteBound=6, promptTokenBound=3, promptTokens=len(prompt_ids), classCount=V))
for step in prompt["steps"]:
trace.add(f"tokenizer_{step['id']}", step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
tensors = [{**record, "id": f"Tokenizer{record['id']}", "provenance": f"Prompt BPE with EOS off, once. {record['provenance']}"}
for record in prompt["tensors"]]
emitted, logical_ids, consumed_generated = [], prompt_ids.tolist(), []
lengths, last_rows, positions, selected_rows = [], [], [], []
model_probabilities, temperature_probabilities, sampling_probabilities = [], [], []
work_running, score_running, call_summary = [], [], {}
observed = prompt_ids.copy()
seed, model_calls, work_tokens, score_cells, draws, consumed, stop_code = s["seed"], 0, 0, 0, 0, 0, 0
for call_index in range(s["maxNew"]):
if not 1 <= len(observed) <= 3:
raise NumericalFault("UNSUPPORTED_SIZE", "Each actual forward requires one to three observed IDs.")
prefix, stem = f"call{call_index}", f"Call{call_index}"
saved = _tiny.tiny_trace()
forward = _tiny.forward_tiny(numeric, observed, saved)
for step in saved.steps:
trace.add(f"{prefix}_{step['id']}", f"{'Prefill' if call_index == 0 else 'Uncached decode'}: {step['label']}", step["equation"],
f"Actual call{call_index}, absolute positions 0..{forward['T'] - 1}, no K/V reuse. Kernel explanation: {step['explanation']}", step["inputs"], step["outputs"])
tensors.extend({**record, "id": f"{stem}{record['id']}",
"provenance": f"Actual call{call_index} {'prefill' if call_index == 0 else 'uncached full-prefix decode'}, absolute positions 0..{forward['T'] - 1}. {record['provenance']}"}
for record in forward["tensors"])
model_calls += 1
work_tokens += forward["T"]
score_cells += forward["T"] * forward["T"]
if call_index > 0:
consumed += 1
consumed_generated[call_index - 1] = 1
last_row = forward["T"] - 1
last, position, previous_seed = forward["rows"][last_row], len(logical_ids), seed
selected_row, selected_id = last["nextRow"], last["nextID"]
sampling_summary, sampling_outputs = {}, {}
if strategy == 1:
options = {key: s[key] for key in _sampling.OPTION_FIELDS}
options["seed"] = seed
sample = _sampling.sample_next(last["logits"], options, trace, f"{prefix}_sample")
selected_row, selected_id = sample["sampledRow"], sample["sampledID"]
sampling_probability = sample["sampledProbability"]
temperature_probability = sample["base"]["probabilities"][selected_row]
sampling_probabilities.append(sampling_probability)
temperature_probabilities.append(temperature_probability)
sampling_summary.update({f"{prefix}SelectedSamplingProbability": sampling_probability,
f"{prefix}SelectedTemperatureBaseProbability": temperature_probability})
sampling_outputs.update(selectedTemperatureBaseProbability=temperature_probability, selectedSamplingProbability=sampling_probability)
seed = sample["rng"]["nextSeed"]
draws += sample["rng"]["drawCount"]
sampling_summary.update({f"{prefix}Uniform": sample["rng"]["uniform"], f"{prefix}CandidateCount": sample["candidateCount"], f"{prefix}Fallback": sample["fallback"]})
tensors.extend({**record, "id": f"{stem}Sample{record['id']}", "provenance": f"Actual call{call_index} last-row sampling. {record['provenance']}"}
for record in sample["tensors"])
model_probability = last["probabilities"][selected_row]
trace.add(f"{prefix}_decision", "Choose from the last row of this actual observed-prefix call", "greedy: saved strict-logit argmax, zero draws; sampling: actual sampleNext on saved last-row logits, one draw",
"The raw model probability is gathered at the selected compact row of the actual unscaled last-row P. Sampling additionally saves the selected temperature-base and final-policy probabilities, which need not equal the raw model P.",
dict(callIndex=call_index, observedLength=forward["T"], lastRow=last_row, outputPosition=position, strategy=strategy, seedBefore=previous_seed),
dict(selectedRow=selected_row, selectedID=selected_id, selectedModelProbability=model_probability, **sampling_outputs,
seedAfter=seed, rngDrawCount=draws, cacheUsed=0, cacheEntries=0))
logical_ids.append(selected_id)
emitted.append(selected_id)
consumed_generated.append(0)
stopped_eos = int(selected_id == 512)
budget_reached = int(len(emitted) >= s["maxNew"])
context_exceeded = int(len(logical_ids) > 3)
stop_code = STOP_EOS if stopped_eos else STOP_TOKEN_BUDGET if budget_reached else STOP_CONTEXT_LIMIT if context_exceeded else 0
trace.add(f"{prefix}_append", "Append one actual ID, then apply EOS → budget → context precedence", "ResultIDs append selectedID; stopCode=EOS?1:budget?2:nextContext>3?3:0",
"A terminal emitted ID remains a pending logical output. It has no fabricated neural row. Only a continuing non-EOS ID becomes part of the next full-prefix input; tokenization is not repeated.",
dict(selectedID=selected_id, EOS=512, outputPosition=position, maxNew=s["maxNew"], contextLimit=3),
dict(generatedTokens=len(emitted), logicalResultTokenCount=len(logical_ids), stoppedEOS=stopped_eos, budgetReached=budget_reached,
contextExceeded=context_exceeded, stopCode=stop_code, continueLoop=int(stop_code == 0)))
lengths.append(forward["T"])
last_rows.append(last_row)
positions.append(position)
selected_rows.append(selected_row)
model_probabilities.append(model_probability)
work_running.append(work_tokens)
score_running.append(score_cells)
call_summary.update({f"{prefix}WorkTokens": forward["T"], f"{prefix}ScoreCells": forward["T"] * forward["T"], f"{prefix}LastRow": last_row,
f"{prefix}OutputPosition": position, f"{prefix}SelectedRow": selected_row, f"{prefix}SelectedID": selected_id,
f"{prefix}SelectedModelProbability": model_probability, f"{prefix}SeedBefore": previous_seed, f"{prefix}SeedAfter": seed,
f"{prefix}StopCode": stop_code, **sampling_summary})
if stop_code:
break
observed = np.array(logical_ids, dtype=np.int32)
stopped_eos, stopped_budget, stopped_context = int(stop_code == 1), int(stop_code == 2), int(stop_code == 3)
result_ids, generated_ids = np.array(logical_ids, dtype=np.int32), np.array(emitted, dtype=np.int32)
reverse = _token.TokenTrace()
reconstructed = _bpe.decode_bpe_ids(result_ids, _tokenizer_rules(prompt), stopped_eos, "result", reverse)
result_bytes = reconstructed["bytes"]
if len(result_bytes) > 14:
raise NumericalFault("UNSUPPORTED_SIZE", "Result expansions exceed the declared 14-byte bound.")
for step in reverse.steps:
trace.add(step["id"], step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
def integer(identifier, axis, values, provenance):
return _token.tensor(identifier, axis, np.array(values, dtype=np.int32), provenance)
def floating(identifier, values, provenance):
return _tiny._float_tensor(identifier, [model_calls], ["Emission"], np.array(values, dtype=np.float64), provenance)
tensors.extend([
integer("PromptIDs", "PromptPosition", prompt_ids, "Actual EOS-off BPE prompt, tokenized exactly once."),
integer("GeneratedIDs", "Emission", generated_ids, "Actual emitted public IDs in decision order, including a stopping EOS if present."),
integer("ResultIDs", "LogicalPosition", result_ids, "Exact prompt IDs followed by actual emissions; no retokenization."),
integer("ConsumedGenerated", "Emission", consumed_generated, "1 only if this generated ID was actually fed into a subsequent forward call; terminal tail remains0."),
integer("ObservedIDs", "ObservedPosition", observed, "Exact prefix processed by the final actual forward call; excludes the terminal emitted tail."),
integer("CallLengths", "ModelCall", lengths, "Actual number of observed token rows in each full-prefix call."),
integer("CallLastRows", "ModelCall", last_rows, "Actual last computed row used for each decision."),
integer("OutputPositions", "Emission", positions, "Absolute logical output slot selected by each last-row decision; terminal slot has no computed row."),
integer("SelectedRows", "Emission", selected_rows, "Actual selected compact class for each emission."),
floating("SelectedModelProbabilities", model_probabilities, "Actual unscaled last-row model P gathered at each selected compact class, including sampled non-greedy choices."),
])
if strategy == 1:
tensors.extend([
floating("SelectedTemperatureBaseProbabilities", temperature_probabilities, "Selected compact-class probabilities from the actual full temperature-scaled base distribution, before filtering."),
floating("SelectedSamplingProbabilities", sampling_probabilities, "Actual FinalP gathered at each selected compact class; sampling-policy probability, separate from raw model P."),
])
tensors.extend([
integer("WorkRunning", "ModelCall", work_running, "Actual cumulative number of token rows recomputed, including old-prefix rows."),
integer("ScoreRunning", "ModelCall", score_running, "Actual cumulative full T*T raw query/key score cells, including future masked cells."),
integer("PendingID", "PendingTail", [emitted[-1]], "Final emitted logical ID, not processed by an extra neural call."),
integer("PendingPosition", "PendingTail", [len(logical_ids) - 1], "Logical slot of final unprocessed emitted ID; not a fabricated forward position."),
integer("ResultBytes", "Bytes", result_bytes, "Actual learned-piece expansions passed to the strict reverse decoder; stopping EOS emits no bytes."),
])
trace.add("finish", "Keep logical emissions, consumed novel IDs and recomputed work distinct", "generatedTokens=modelCalls; newTokensConsumed=modelCalls-1; final emitted tail is pending",
"At most two decisions and a three-observed-token context. All actual forward tensors and steps are retained, with no target, loss, gradient, training or cache operation.",
dict(promptTokens=len(prompt_ids), maxNew=s["maxNew"], strategy=strategy, initialSeed=s["seed"]),
dict(generatedTokens=len(emitted), modelCalls=model_calls, workTokens=work_tokens, finalSeed=seed, newTokensConsumed=consumed,
rngDrawCount=draws, logicalResultTokenCount=len(logical_ids), stopCode=stop_code, resultByteCount=len(result_bytes)))
summary = dict(generatedTokens=len(emitted), modelCalls=model_calls, workTokens=work_tokens, finalSeed=seed,
promptTokens=len(prompt_ids), newTokensConsumed=consumed, generatedCount=len(emitted), logicalResultTokenCount=len(logical_ids),
cacheUsed=0, cacheEntries=0, stoppedEOS=stopped_eos, stopCode=stop_code, stoppedContext=stopped_context, stoppedBudget=stopped_budget,
currentObservedLength=len(observed), rngDrawCount=draws, scoreCells=score_cells, pendingTail=1, pendingID=emitted[-1], pendingPosition=len(logical_ids) - 1,
selectedID=emitted[-1], selectedModelProbability=model_probabilities[-1])
if strategy == 1:
summary.update(selectedTemperatureBaseProbability=temperature_probabilities[-1], selectedSamplingProbability=sampling_probabilities[-1])
summary.update(classCount=V, actualMerges=numeric["merges"], strategy=strategy, temperature=s["temperature"], topK=s["topK"], topP=s["topP"], initialSeed=s["seed"], maxNew=s["maxNew"],
B=1, D=2, H=1, Dk=2, Dv=2, hiddenWidth=3, byteBound=6, contextLimit=3, resultByteCount=len(result_bytes))
summary.update(call_summary)
tokenizer_names = ("corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges", "corpusTokens", "eos", "byteBound", "vocabularyItems", "corpusEqual", "equal")
summary.update({f"tokenizer_{key}": prompt["outputs"][key] for key in tokenizer_names})
result = trace.result(summary, tensors)
result["texts"] = dict(input=s["text"], decoded=reconstructed["decoded"],
strategy="Greedy: highest actual unscaled computed logit; exact ties retain lowest compact class; zero RNG draws." if strategy == 0 else "Sampling: temperature, full stable P, public-ID score ties, top-k, top-p, final normalization, ascending-public-ID CDF; one LCG draw per decision.",
stopReason=STOP_REASONS[stop_code],
stopPolicy="After appending: EOS first, then maxNew budget, then whether another full-prefix call would exceed three observed tokens.",
pendingPolicy="The final emitted ID is logical output only. It is not fed through an extra forward call, RoPE position, embedding gather or readout.",
cachePolicy="First call is prefill; subsequent call is uncached full-prefix decode at absolute positions 0..T-1. cacheUsed=0, cacheEntries=0.",
platformPolicy="A seed fixes the LCG stream. Elementary-library rounding near filter or CDF boundaries may change a valid token path; each actual saved path needs conditional-witness verification.",
modelVocabulary=["0: a / ID97", "1: b / ID98", "2: EOS / ID512", "3: ab / ID256 (merges>=1)", "4: abab / ID257 (merges=2)"],
**{f"tokenizer_{key}": value for key, value in prompt["texts"].items()})
return json.loads(json.dumps(result, allow_nan=False, ensure_ascii=False))
def source_self_check():
"""DEFERRED leaf assertions; invokes no other file's self-check."""
assert __debug__, "Deferred checks require assertions enabled."
assert Path(_tiny.__file__).resolve() == _ROOT / "p10" / "tiny_reference.py"
assert Path(_iv39.__file__).resolve() == _ROOT / "p09" / "iv39.py"
assert Path(_sampling.__file__).resolve() == Path(__file__).resolve().with_name("sampling_reference.py")
assert _tiny._ffn.NumericalFault is _tiny._component.NumericalFault
assert len(DEFAULT_IV47) == 33 and list(DEFAULT_IV47) == ["text", *NUMERIC_DEFAULTS, "strategy", "temperature", "topK", "topP", "seed", "maxNew"]
state = dict(DEFAULT_IV47)
result = generation_record(state)
tensors = {record["id"]: record for record in result["tensors"]}
assert list(result) == ["status", "outputs", "steps", "tensors", "texts"]
assert tensors["PromptIDs"]["values"] == [97] and tensors["GeneratedIDs"]["values"] == [97, 97]
assert tensors["ResultIDs"]["values"] == [97, 97, 97] and result["texts"]["decoded"] == "aaa"
assert tensors["Call0InputIDs"]["values"] == [97] and tensors["Call1InputIDs"]["values"] == [97, 97]
assert tensors["ConsumedGenerated"]["values"] == [1, 0] and tensors["ObservedIDs"]["values"] == [97, 97]
assert tensors["OutputPositions"]["values"] == [1, 2] and tensors["CallLengths"]["values"] == [1, 2]
assert len(result["steps"]) == 236 and len(result["tensors"]) == 227
assert [result["outputs"][key] for key in ("generatedTokens", "modelCalls", "workTokens", "finalSeed", "newTokensConsumed", "rngDrawCount", "scoreCells")] == [2, 2, 3, 1196435762, 1, 2, 5]
assert result["texts"]["stopReason"] == "TOKEN_BUDGET" and tensors["PendingPosition"]["values"] == [2]
greedy = generation_record({**state, "strategy": 0})
assert len(greedy["steps"]) == 198 and len(greedy["tensors"]) == 147
assert greedy["outputs"]["rngDrawCount"] == 0 and greedy["outputs"]["finalSeed"] == 0
assert not any("_sample_" in step["id"] for step in greedy["steps"])
assert not any("Sample" in record["id"] or record["id"].startswith("SelectedTemperature") for record in greedy["tensors"])
assert "selectedSamplingProbability" not in greedy["outputs"] and "selectedTemperatureBaseProbability" not in greedy["outputs"]
context = generation_record({**state, "text": "aaa", "strategy": 0})
assert context["outputs"]["modelCalls"] == 1 and context["outputs"]["logicalResultTokenCount"] == 4 and context["texts"]["stopReason"] == "CONTEXT_LIMIT"
budget = generation_record({**state, "text": "aaa", "strategy": 0, "maxNew": 1})
assert budget["texts"]["stopReason"] == "TOKEN_BUDGET"
eos = generation_record({**state, "strategy": 0, "b2": 4, **{f"u{d}{c}": 0 for d in range(2) for c in range(5)}})
assert eos["outputs"]["modelCalls"] == 1 and eos["outputs"]["newTokensConsumed"] == 0 and eos["texts"]["decoded"] == "a"
assert eos["texts"]["stopReason"] == "EOS" and not any(record["id"].startswith("Call1") for record in eos["tensors"])
fixed = generation_record({**state, "text": "ab", "merges": 2, "strategy": 0, "maxNew": 1, "b3": 4,
**{f"u{d}{c}": 0 for d in range(2) for c in range(5)}})
fixed_tensors = {record["id"]: record for record in fixed["tensors"]}
assert fixed_tensors["PromptIDs"]["values"] == [256] and fixed_tensors["ResultIDs"]["values"] == [256, 256] and fixed["texts"]["decoded"] == "abab"
distinct = generation_record({**state, **{f"e{r}{d}": 0 for r in range(5) for d in range(2)}, "b1": 1, "b2": -1, "temperature": 2, "topK": 2, "maxNew": 1})
t = {record["id"]: record for record in distinct["tensors"]}
assert distinct["outputs"]["selectedID"] == 97 and t["Call0NextIDs"]["values"] == [98]
assert distinct["outputs"]["selectedModelProbability"] == t["Call0P"]["values"][0]
assert distinct["outputs"]["selectedModelProbability"] != t["Call0NextProbability"]["values"][0]
assert distinct["outputs"]["selectedModelProbability"] < distinct["outputs"]["selectedTemperatureBaseProbability"] < distinct["outputs"]["selectedSamplingProbability"]
assert distinct["outputs"]["selectedSamplingProbability"] == t["Call0SampleFinalP"]["values"][0]
for patch, code in ((dict(text=[]), "INVALID_INPUT"), (dict(text="\ud800", seed=True), "NONFINITE"), (dict(text=""), "UNAVAILABLE"),
(dict(text="a" * 7), "UNSUPPORTED_SIZE"), (dict(text="\ud800"), "INVALID_INPUT"), (dict(text="🦊🦊"), "UNSUPPORTED_SIZE"),
(dict(text="c"), "UNAVAILABLE"), (dict(text="aaaa"), "UNSUPPORTED_SIZE"),
(dict(strategy=0, temperature=0), "INVALID_INPUT"), (dict(strategy=0, b4=True), "NONFINITE")):
rejected = guarded(generation_record)({**state, **patch})
assert list(rejected) == ["status", "code", "reason"] and rejected["code"] == code
for text, merges, code in (([], float("nan"), "INVALID_INPUT"), ("\ud800", True, "NONFINITE"), ("\ud800", 3, "INVALID_INPUT"), ("a", 0.5, "INVALID_INPUT")):
try:
generation_prompt(text, merges)
except _DEPENDENCY_FAULTS as error:
assert error.code == code
else:
raise AssertionError("Direct prompt helper accepted invalid input")
prompt, ids = generation_prompt("aaa", 0)
assert ids.dtype == np.dtype(np.int32) and ids.tolist() == [97, 97, 97] and prompt["outputs"]["eos"] == 0
for fault in _DEPENDENCY_FAULTS:
def raises(unused):
raise fault("INVALID_INPUT", "declared fault-family check")
assert guarded(raises)({})["code"] == "INVALID_INPUT"
result["outputs"].clear()
tensors["Call0P"]["values"][0] = -1
again = generation_record(state)
assert again["outputs"]["generatedTokens"] == 2 and state == dict(DEFAULT_IV47)
3. Sampling mechanics — code/python/p11/sampling_reference.py. sample_next receives that call’s actual last-row logits and current seed. It computes temperature division, full stable base P, public-ID tie ranking, top-k and top-p masses and divisions, public-order CDF, exact LCG and half-open predicates. rng_step returns the actual next state; a single-candidate decision still advances it. This helper is not called in greedy mode.
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.
"""Canonical NumPy sampler mechanics for IV46/47, authored under the hold.
All scalar arithmetic is binary64 in the displayed order; arrays use real
float64/int32 storage. The readonly choice helper supplies the full stable
base distribution. No random-choice API or implicit self-check is used.
Full records follow the owner-adopted actual A inventory.
"""
import importlib.util
import json
from pathlib import Path
from types import MappingProxyType
import numpy as np
_path = Path(__file__).resolve().with_name("choice_reference.py")
_spec = importlib.util.spec_from_file_location("_p11_sampling_choice", _path)
if _spec is None or _spec.loader is None:
raise ImportError(f"Cannot load canonical dependency: {_path}")
_choice = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_choice)
NumericalFault = _choice.NumericalFault
finite = _choice.finite
ALL_IDS = _choice.ALL_IDS
DEFAULT_IV46 = MappingProxyType(dict(V=3, z0=1, z1=0, z2=0, z3=0, z4=0,
temperature=1, topK=3, topP=1, seed=0))
OPTION_FIELDS = ("temperature", "topK", "topP", "seed")
def sampling_options(options, V):
"""Exact built-in own fields, all domains in their signed raw order."""
V = finite(V, "V")
if not V.is_integer() or not 3 <= V <= 5:
raise NumericalFault("INVALID_INPUT", "V must be an integer from 3 to 5.")
V = int(V)
if type(options) is not dict or any(type(key) is not str for key in options) or set(options) != set(OPTION_FIELDS):
raise NumericalFault("INVALID_INPUT", "options requires exactly temperature,topK,topP,seed.")
result = {}
for key in OPTION_FIELDS:
value = finite(options[key], key)
valid = (0.25 <= value <= 4 if key == "temperature" else
value.is_integer() and 1 <= value <= V if key == "topK" else
0 < value <= 1 if key == "topP" else
value.is_integer() and 0 <= value <= 4294967295)
if not valid:
raise NumericalFault("INVALID_INPUT", f"{key} is outside its sampling domain.")
result[key] = int(value) if key in ("topK", "seed") else value
return result
def sampling_state(state):
if type(state) is not dict or any(type(key) is not str for key in state) or set(state) != set(DEFAULT_IV46):
raise NumericalFault("INVALID_INPUT", "Provide every IV46 own field and no extras.")
logits = _choice.choice_state({key: state[key] for key in _choice.DEFAULT_IV45})
options = sampling_options({key: state[key] for key in OPTION_FIELDS}, logits["V"])
return {**logits, **options}
def rng_step(seed):
"""Exact Book III LCG; integer modulo models Math.imul then unsigned cast."""
numeric = finite(seed, "seed")
if not numeric.is_integer() or not 0 <= numeric <= 4294967295:
raise NumericalFault("INVALID_INPUT", "seed must be an unsigned 32-bit integer.")
initial = int(numeric)
low_unsigned = (1664525 * initial) % 4294967296
signed_low = low_unsigned if low_unsigned < 2147483648 else low_unsigned - 4294967296
increment = 1013904223
summed = signed_low + increment
next_seed = summed % 4294967296
uniform = next_seed / 4294967296
return dict(seed=initial, signedProduct=signed_low, increment=increment,
sum=summed, nextSeed=next_seed, uniform=uniform, drawCount=1)
def sample_next(logits, options, trace, prefix="sample"):
"""Actual stable filtering and one exact LCG draw, with full ordered evidence.
Prefix, original array descriptor/length, options and domains precede all
logit reads. Derived logits have no raw slider clipping. Every probability
is computed here by Python, never borrowed from a TypeScript witness.
"""
if type(prefix) is not str or not prefix:
raise NumericalFault("INVALID_INPUT", "prefix must be an actual nonempty string.")
_choice._dense(logits, "logits")
V = len(logits)
s = sampling_options(options, V)
entries = logits.tolist() if type(logits) is np.ndarray else logits
z = np.array([finite(value, f"logits[{c}]") for c, value in enumerate(entries)], dtype=np.float64)
ids = np.array(ALL_IDS[:V], dtype=np.int32)
scaled = np.empty(V, dtype=np.float64)
for c in range(V):
scaled[c] = finite(float(z[c]) / s["temperature"], "temperature-scaled logit")
trace.add(f"{prefix}_scale", "Divide every active computed logit by temperature", "scaled_c=logit_c/temperature",
"All active operands and computed divisions are saved. Positive temperature is validated before arithmetic; no derived-logit clipping occurs.",
{"temperature": s["temperature"], **{f"logit{c}": float(z[c]) for c in range(V)}},
{f"scaled{c}": float(scaled[c]) for c in range(V)})
base = _choice.direct_distribution(scaled, ids, trace, f"{prefix}_base")
base_p = np.array(base["probabilities"], dtype=np.float64)
rank = np.array(sorted(range(V), key=lambda c: (-float(scaled[c]), int(ids[c]))), dtype=np.int32)
rank_ids = ids[rank].copy()
inputs, outputs = {}, {}
for c in range(V):
inputs.update({f"scaled{c}": float(scaled[c]), f"publicID{c}": int(ids[c])})
for r, stored in enumerate(rank):
c = int(stored)
outputs.update({f"compact{r}": c, f"publicID{r}": int(ids[c]), f"score{r}": float(scaled[c])})
trace.add(f"{prefix}_rank", "Rank computed scaled scores, breaking ties by public ID", "descending computed scaled logit; exact score tie => ascending public token ID",
"This order intentionally differs from the base helper greedy metadata, whose ties retain the lowest compact index. No stored or formatted probability is sorted.", inputs, outputs)
top_k_mask = np.zeros(V, dtype=np.int32)
top_k_running = np.empty(s["topK"], dtype=np.float64)
top_k_mass, inputs, outputs = 0.0, dict(topK=s["topK"]), {}
for r, stored in enumerate(rank):
c, keep = int(stored), int(r < s["topK"])
top_k_mask[c] = keep
probability = float(base_p[c])
inputs.update({f"compact{r}": c, f"publicID{r}": int(ids[c]), f"baseP{r}": probability})
outputs[f"keep{r}"] = keep
if keep:
inputs[f"before{r}"] = top_k_mass
top_k_mass = finite(top_k_mass + probability, "top-k mass")
top_k_running[r] = top_k_mass
outputs[f"running{r}"] = top_k_mass
if top_k_mass <= 0:
raise NumericalFault("UNAVAILABLE", "The top-k retained base probability mass must be positive.")
outputs["mass"] = top_k_mass
trace.add(f"{prefix}_topk_mass", "Keep top-k ranks and add their stored base probabilities", "mass starts at 0; in rank order mass=previous+baseP for each kept rank",
"The complete rank keep decisions are saved. Only retained terms enter the left-to-right sum; no epsilon or replacement class is added.", inputs, outputs)
top_k_p = np.zeros(V, dtype=np.float64)
inputs, outputs = dict(mass=top_k_mass), {}
for c in range(V):
top_k_p[c] = finite(float(base_p[c]) / top_k_mass, "top-k probability") if top_k_mask[c] else 0.0
inputs.update({f"baseP{c}": float(base_p[c]), f"keep{c}": int(top_k_mask[c])})
outputs[f"topKP{c}"] = float(top_k_p[c])
trace.add(f"{prefix}_topk_normalize", "Renormalize top-k and retain exact removed zeros", "topKP_c=topKMask_c?baseP_c/topKMass:0",
"Arrays retain every active compact class, including exact algorithmic zero for removed classes.", inputs, outputs)
final_mask = np.zeros(V, dtype=np.int32)
nucleus_before, nucleus_running = (np.empty(s["topK"], dtype=np.float64) for _ in range(2))
nucleus_crossed, nucleus_continue = (np.empty(s["topK"], dtype=np.int32) for _ in range(2))
cumulative, candidate_count = 0.0, 0
inputs, outputs = dict(topP=s["topP"], topK=s["topK"]), {}
for r in range(s["topK"]):
c, before = int(rank[r]), cumulative
cumulative = finite(before + float(top_k_p[c]), "nucleus cumulative")
crossed = int(cumulative >= s["topP"])
again = int(r + 1 < s["topK"] and (s["topP"] == 1 or not crossed))
nucleus_before[r], nucleus_running[r] = before, cumulative
nucleus_crossed[r], nucleus_continue[r] = crossed, again
final_mask[c] = 1
inputs.update({f"compact{r}": c, f"publicID{r}": int(ids[c]), f"topKP{r}": float(top_k_p[c]), f"before{r}": before})
outputs.update({f"running{r}": cumulative, f"keep{r}": 1, f"crossed{r}": crossed, f"continue{r}": again})
candidate_count += 1
if not again:
break
nucleus = rank[:candidate_count].copy()
nucleus_ids = ids[nucleus].copy()
nucleus_before, nucleus_running = nucleus_before[:candidate_count].copy(), nucleus_running[:candidate_count].copy()
nucleus_crossed, nucleus_continue = nucleus_crossed[:candidate_count].copy(), nucleus_continue[:candidate_count].copy()
outputs["candidateCount"] = candidate_count
trace.add(f"{prefix}_nucleus", "Visit ranked top-k entries through the first top-p crossing", "include each visited token; continue while cumulative<topP; topP===1 retains all topK",
"Every visited operand, running sum and keep/continue decision is real. At topP1 even a rounded prefix cumulative of1 cannot discard the remaining top-k tail.", inputs, outputs)
final_mass, inputs, outputs = 0.0, {}, {}
final_running = np.empty(candidate_count, dtype=np.float64)
for r, stored in enumerate(nucleus):
c = int(stored)
inputs.update({f"compact{r}": c, f"topKP{r}": float(top_k_p[c]), f"before{r}": final_mass})
final_mass = finite(final_mass + float(top_k_p[c]), "nucleus mass")
final_running[r] = final_mass
outputs[f"running{r}"] = final_mass
if final_mass <= 0:
raise NumericalFault("UNAVAILABLE", "The nucleus retained top-k probability mass must be positive.")
outputs["mass"] = final_mass
trace.add(f"{prefix}_final_mass", "Sum the actual kept top-k probabilities again in rank order", "mass starts at 0; mass=previous+topKP for each nucleus entry",
"This second mass uses the saved top-k probabilities, not the original base probabilities or an ideal-real formula.", inputs, outputs)
final_p = np.zeros(V, dtype=np.float64)
inputs, outputs = dict(mass=final_mass), {}
for c in range(V):
final_p[c] = finite(float(top_k_p[c]) / final_mass, "final sampling probability") if final_mask[c] else 0.0
inputs.update({f"topKP{c}": float(top_k_p[c]), f"keep{c}": int(final_mask[c])})
outputs[f"finalP{c}"] = float(final_p[c])
trace.add(f"{prefix}_final_normalize", "Normalize the nucleus into the final sampling distribution", "finalP_c=finalMask_c?topKP_c/finalMass:0",
"Kept entries may have actual zero probability after helper underflow. Removed entries are exact zero; positive support is checked before selection.", inputs, outputs)
cdf_compact = np.array(sorted((int(c) for c in nucleus), key=lambda c: int(ids[c])), dtype=np.int32)
cdf_ids = ids[cdf_compact].copy()
cdf_before, cdf_running = (np.empty(candidate_count, dtype=np.float64) for _ in range(2))
total, positive_count, last_positive = 0.0, 0, -1
inputs, outputs = {}, {}
for i, stored in enumerate(cdf_compact):
c, probability = int(stored), float(final_p[int(stored)])
cdf_before[i] = total
inputs.update({f"compact{i}": c, f"publicID{i}": int(ids[c]), f"probability{i}": probability, f"before{i}": total})
total = finite(total + probability, "CDF cumulative")
cdf_running[i] = total
outputs[f"running{i}"] = total
if probability > 0:
positive_count += 1
last_positive = i
outputs[f"positive{i}"] = int(probability > 0)
if last_positive < 0:
raise NumericalFault("UNAVAILABLE", "Sampling requires positive support.")
outputs.update(positiveCount=positive_count, lastPositive=last_positive)
trace.add(f"{prefix}_cdf", "Build a separately ordered CDF by ascending public ID", "CDF starts at 0; cumulative_i=previous+finalP[public-order compact_i]",
"Every retained entry is present, including kept zero probabilities. The final cumulative is saved as computed, never forced to1.", inputs, outputs)
rng = rng_step(s["seed"])
trace.add(f"{prefix}_rng", "Advance the Book III unsigned 32-bit LCG exactly once", "signedProduct=imul(1664525,seed); sum=signedProduct+1013904223; nextSeed=sum>>>0; u=nextSeed/4294967296",
"One draw is consumed even for a single candidate. Unsigned states and the integer sum use exact integer-valued binary64 evidence, never signed-int32 wrapping storage.",
dict(seed=rng["seed"], multiplier=1664525, increment=rng["increment"], modulus=4294967296),
{key: rng[key] for key in ("signedProduct", "sum", "nextSeed", "uniform", "drawCount")})
selected_index, inputs, outputs = -1, dict(uniform=rng["uniform"]), {}
for i, stored in enumerate(cdf_compact):
c = int(stored)
probability, cumulative = float(final_p[c]), float(cdf_running[i])
positive, below = int(probability > 0), int(rng["uniform"] < cumulative)
take = int(selected_index < 0 and positive and below)
inputs.update({f"compact{i}": c, f"probability{i}": probability, f"cumulative{i}": cumulative})
outputs.update({f"positive{i}": positive, f"below{i}": below, f"take{i}": take})
if take:
selected_index = i
fallback = int(selected_index < 0)
if fallback:
selected_index = last_positive
sampled_row = int(cdf_compact[selected_index])
sampled_id, sampled_probability = int(ids[sampled_row]), float(final_p[sampled_row])
outputs.update(fallback=fallback, selectedCDFIndex=selected_index, sampledRow=sampled_row,
sampledID=sampled_id, sampledProbability=sampled_probability, candidateCount=candidate_count)
trace.add(f"{prefix}_select", "Select the first positive half-open CDF interval", "first positive entry with u<cumulative; if none, use last positive entry and record fallback1",
"Equality belongs to the following interval. Every exact predicate is saved. The fallback covers a finite summation gap; it does not alter any saved probability or CDF.", inputs, outputs)
def f(identifier, axis, values, provenance):
return _choice._tensor(identifier, axis, np.array(values, dtype=np.float64), provenance)
def integer(identifier, axis, values, provenance):
return _choice._tensor(identifier, axis, np.array(values, dtype=np.int32), provenance)
tensors = [
f("InputLogits", "Class", z, "Validated actual sampler logits; derived logits are not clipped."),
f("ScaledLogits", "Class", scaled, "Actual InputLogits/temperature in compact order."),
*({**record, "id": f"Base{record['id']}", "provenance": f"Full scaled-logit base distribution; its Next metadata is greedy, not sampled. {record['provenance']}"} for record in base["tensors"]),
integer("RankCompact", "Rank", rank, "Descending computed ScaledLogits; exact ties ascend public ID."),
integer("RankIDs", "Rank", rank_ids, "Public IDs gathered at RankCompact."),
integer("TopKMask", "Class", top_k_mask, "Complete active compact mask; first topK ranks are1."),
f("TopKRunning", "TopKRank", top_k_running, "Actual baseP rank-order running sums from zero."),
f("TopKMass", "Scalar", [top_k_mass], "Last actual TopKRunning value, required positive."),
f("TopKP", "Class", top_k_p, "Kept BaseP/TopKMass; removed compact classes exact0."),
integer("NucleusCompact", "NucleusRank", nucleus, "Actual visited top-k rank prefix, including first crossing; topP1 visits all."),
integer("NucleusIDs", "NucleusRank", nucleus_ids, "Public IDs at actual visited nucleus ranks."),
f("NucleusBefore", "NucleusRank", nucleus_before, "Actual cumulative operand before each visited TopKP addition."),
f("NucleusRunning", "NucleusRank", nucleus_running, "Actual cumulative TopKP in visited rank order."),
integer("NucleusCrossed", "NucleusRank", nucleus_crossed, "Exact saved cumulative>=topP predicate for each visit."),
integer("NucleusContinue", "NucleusRank", nucleus_continue, "Actual next-visit decision, including topP===1 special policy."),
integer("FinalMask", "Class", final_mask, "Complete active compact mask of actually visited nucleus entries."),
f("FinalRunning", "NucleusRank", final_running, "Second actual kept TopKP mass accumulation in rank order, from zero."),
f("FinalMass", "Scalar", [final_mass], "Last actual FinalRunning value, required positive."),
f("FinalP", "Class", final_p, "Actual kept TopKP/FinalMass; all removed entries exact0."),
integer("CDFCompact", "CDFEntry", cdf_compact, "Retained compact indices sorted separately by ascending public ID."),
integer("CDFIDs", "CDFEntry", cdf_ids, "Ascending public IDs, including retained zero-probability entries."),
f("CDFBefore", "CDFEntry", cdf_before, "Actual final-P cumulative operand before each public-order addition."),
f("CDFRunning", "CDFEntry", cdf_running, "Actual public-order cumulative sum; last entry is not forced to1."),
{**f("RNGState", "StateEndpoint", [rng["seed"], rng["nextSeed"]], "Initial and next unsigned uint32 states stored exactly in float64, without int32 conversion."), "precision": 0},
{**f("RNGArithmetic", "IntegerOperand", [rng["signedProduct"], rng["increment"], rng["sum"]], "Actual signed imul low32 product, increment and exact integer-valued sum in float64."), "precision": 0},
f("Uniform", "Draw", [rng["uniform"]], "Exact dyadic nextSeed/2^32, in [0,1); exactly one draw."),
integer("SampledRow", "Decision", [sampled_row], "Compact class selected from the actual final CDF and draw."),
integer("SampledID", "Decision", [sampled_id], "Public ID at SampledRow; distinct from BaseNextID greedy metadata."),
f("SampledProbability", "Decision", [sampled_probability], "Stored FinalP gathered at SampledRow, never the base greedy probability."),
]
result = dict(classIDs=ids.tolist(), logits=z.tolist(), scaled=scaled.tolist(), base=base,
rankCompact=rank.tolist(), rankIDs=rank_ids.tolist(), topKMask=top_k_mask.tolist(), topKRunning=top_k_running.tolist(), topKMass=top_k_mass, topKP=top_k_p.tolist(),
nucleusCompact=nucleus.tolist(), nucleusIDs=nucleus_ids.tolist(), nucleusBefore=nucleus_before.tolist(), nucleusRunning=nucleus_running.tolist(),
nucleusCrossed=nucleus_crossed.tolist(), nucleusContinue=nucleus_continue.tolist(), finalMask=final_mask.tolist(), finalRunning=final_running.tolist(), finalMass=final_mass,
finalP=final_p.tolist(), cdfCompact=cdf_compact.tolist(), cdfIDs=cdf_ids.tolist(), cdfBefore=cdf_before.tolist(), cdfRunning=cdf_running.tolist(), rng=rng,
selectedCDFIndex=selected_index, sampledRow=sampled_row, sampledID=sampled_id, sampledProbability=sampled_probability, candidateCount=candidate_count,
positiveCount=positive_count, fallback=fallback, tensors=tensors)
return json.loads(json.dumps(result, allow_nan=False))
def compute_sampling(state):
"""Full ordered IV46 chapter record following the adopted actual inventory."""
s = sampling_state(state)
raw_z = np.array([s[f"z{c}"] for c in range(5)], dtype=np.float64)
trace = _choice.ChoiceTrace()
trace.add("setup", "Validate all ten raw fields before sampling", "V3..5; all five raw z in [-40,40]; temperature .25..4; topK1..V; 0<topP<=1; seed uint32",
"Inactive logits validate too. The only RNG is the explicitly recorded Book III LCG; base greedy metadata is not the sampled choice.",
s, dict(classCount=s["V"], rawLogitCount=5))
sample = sample_next(raw_z[:s["V"]], {key: s[key] for key in OPTION_FIELDS}, trace)
trace.add("finish", "Keep the sampled decision separate from base greedy evidence", "sampledProbability=FinalP[sampledRow]; nextSeed=one LCG transition",
"The complete base, top-k, nucleus, CDF and RNG records remain available. A single candidate still consumes exactly one draw.",
dict(sampledRow=sample["sampledRow"], selectedCDFIndex=sample["selectedCDFIndex"]),
dict(sampledID=sample["sampledID"], sampledProbability=sample["sampledProbability"], candidateCount=sample["candidateCount"], nextSeed=sample["rng"]["nextSeed"]))
base, rng = sample["base"], sample["rng"]
outputs = dict(sampledID=sample["sampledID"], sampledProbability=sample["sampledProbability"], candidateCount=sample["candidateCount"], nextSeed=rng["nextSeed"],
classCount=s["V"], sampledRow=sample["sampledRow"], selectedCDFIndex=sample["selectedCDFIndex"], positiveCount=sample["positiveCount"], fallback=sample["fallback"],
drawCount=rng["drawCount"], initialSeed=s["seed"], uniform=rng["uniform"], temperature=s["temperature"], topK=s["topK"], topP=s["topP"],
baseGreedyRow=base["nextRow"], baseGreedyID=base["nextID"], baseGreedyProbability=base["nextProbability"],
max=base["max"], denominator=base["denominator"], logS=base["logS"], logsumexp=base["lse"],
topKMass=sample["topKMass"], finalMass=sample["finalMass"], cdfTotal=sample["cdfRunning"][-1], rawLogitCount=5)
for step in trace.steps:
outputs.update({f"{step['id']}_{key}": value for key, value in step["outputs"].items()})
return dict(status="defined", outputs=outputs, steps=trace.steps,
tensors=[_choice._tensor("RawZ", "ModelRow", raw_z, "All five validated editable raw logits, including inactive slots."), *sample["tensors"]])
def source_self_check():
"""DEFERRED explicit leaf assertions; never run on import or normal query."""
assert __debug__, "Deferred checks require assertions enabled."
assert Path(_choice.__file__).resolve() == _path
assert rng_step(0)["nextSeed"] == 1013904223
assert rng_step(1013904223)["nextSeed"] == 1196435762
edge = rng_step(4294967295)
assert edge["signedProduct"] == -1664525 and edge["nextSeed"] == 1012239698
options = dict(temperature=1, topK=3, topP=1, seed=0)
row = sample_next([1, 0, 0], options, _choice.ChoiceTrace())
assert row["sampledID"] == 97 and row["candidateCount"] == 3 and row["rng"]["drawCount"] == 1
one = sample_next([1, 0, 0], {**options, "topK": 1}, _choice.ChoiceTrace())
assert one["sampledProbability"] == 1 and one["rng"]["nextSeed"] == 1013904223
tied = sample_next([0, 0, 1, 1, 0], {**options, "topK": 1}, _choice.ChoiceTrace())
assert tied["sampledID"] == 256 and tied["base"]["nextID"] == 512
uniform = sample_next([0] * 5, options, _choice.ChoiceTrace())
assert uniform["rankCompact"] == [0, 1, 3, 4, 2] and uniform["topKMask"] == [1, 1, 0, 1, 0]
thin = sample_next([40, -40, -40], {**options, "temperature": 0.25}, _choice.ChoiceTrace())
assert thin["candidateCount"] == 3 and all(p > 0 for p in thin["finalP"])
underflow = sample_next([0, -1000, -1000], options, _choice.ChoiceTrace())
assert underflow["finalP"] == [1, 0, 0] and underflow["positiveCount"] == 1
collapsed = sample_next([0, float.fromhex("0x0.0000000000001p-1022"), 0], {**options, "temperature": 4}, _choice.ChoiceTrace())
assert collapsed["scaled"] == [0, 0, 0] and collapsed["rankCompact"] == [0, 1, 2]
half_options = {**options, "topK": 2, "seed": 2782269413}
half = sample_next([0, 0, -1], half_options, _choice.ChoiceTrace())
assert half["rng"]["nextSeed"] == 2147483648 and half["rng"]["uniform"] == 0.5
assert half["finalP"] == [0.5, 0.5, 0] and half["cdfRunning"] == [0.5, 1]
assert half["sampledID"] == 98 and half["fallback"] == 0
zero = sample_next([-1000, 0, 0], {**options, "seed": 634785765}, _choice.ChoiceTrace())
assert zero["rng"]["nextSeed"] == 0 and zero["rng"]["uniform"] == 0
assert zero["finalP"] == [0, 0.5, 0.5] and zero["sampledID"] == 98 and zero["fallback"] == 0
for raw, opts, prefix, code in (([], {}, "", "INVALID_INPUT"), ([], {}, "s", "UNSUPPORTED_SIZE"),
([float("nan"), 0, 0], {**options, "temperature": 0}, "s", "INVALID_INPUT"),
([1, True, 0], options, "s", "NONFINITE"),
([1e308, -1e308, 0], {**options, "temperature": 0.25}, "s", "NONFINITE")):
try:
sample_next(raw, opts, _choice.ChoiceTrace(), prefix)
except NumericalFault as error:
assert error.code == code
else:
raise AssertionError("Invalid sampler boundary was accepted")
for V, code in ((float("nan"), "NONFINITE"), (float("inf"), "NONFINITE"), (True, "NONFINITE"),
(2, "INVALID_INPUT"), (3.5, "INVALID_INPUT")):
try:
sampling_options({}, V)
except NumericalFault as error:
assert error.code == code and "V" in str(error)
else:
raise AssertionError("Invalid direct options V was accepted")
class HostileList(list):
def __getitem__(self, key):
raise AssertionError("Custom array indexing must not be invoked")
try:
sample_next(HostileList([1, 0, 0]), options, _choice.ChoiceTrace())
except NumericalFault as error:
assert error.code == "INVALID_INPUT"
else:
raise AssertionError("Sampler accepted a hostile container")
class HostileDict(dict):
def __getitem__(self, key):
raise AssertionError("Custom mapping indexing must not be invoked")
for raw in (HostileDict(options), {}, {**options, "extra": 0}):
try:
sampling_options(raw, 3)
except NumericalFault as error:
assert error.code == "INVALID_INPUT"
else:
raise AssertionError("Sampler accepted invalid own options")
trace = _choice.ChoiceTrace()
saved = sample_next([1, 0, 0], options, trace)
assert list(saved) == ["classIDs", "logits", "scaled", "base", "rankCompact", "rankIDs", "topKMask", "topKRunning", "topKMass", "topKP",
"nucleusCompact", "nucleusIDs", "nucleusBefore", "nucleusRunning", "nucleusCrossed", "nucleusContinue", "finalMask", "finalRunning", "finalMass", "finalP",
"cdfCompact", "cdfIDs", "cdfBefore", "cdfRunning", "rng", "selectedCDFIndex", "sampledRow", "sampledID", "sampledProbability", "candidateCount", "positiveCount", "fallback", "tensors"]
assert list(saved["rng"]) == ["seed", "signedProduct", "increment", "sum", "nextSeed", "uniform", "drawCount"]
assert len(trace.steps) == 19 and len(saved["tensors"]) == 39
assert [step["id"] for step in trace.steps] == ["sample_scale", "sample_base_max", "sample_base_exp_0", "sample_base_exp_1", "sample_base_exp_2", "sample_base_normalize",
"sample_base_probability_0", "sample_base_probability_1", "sample_base_probability_2", "sample_base_argmax", "sample_rank", "sample_topk_mass",
"sample_topk_normalize", "sample_nucleus", "sample_final_mass", "sample_final_normalize", "sample_cdf", "sample_rng", "sample_select"]
assert saved["nucleusContinue"] == [1, 1, 0]
for tensor in half["tensors"]:
assert list(tensor) == ["id", "shape", "axes", "dtype", "values", "provenance", "precision"]
rng_tensor = next(tensor for tensor in half["tensors"] if tensor["id"] == "RNGState")
assert rng_tensor["dtype"] == "float64" and rng_tensor["precision"] == 0 and rng_tensor["values"] == [2782269413, 2147483648]
assert all(tensor["dtype"] == "int32" for tensor in saved["tensors"] if tensor["id"] in ("RankCompact", "RankIDs", "TopKMask", "FinalMask", "SampledRow", "SampledID"))
boundary = sample_next([0, 0, -1], {**options, "topP": 0.5, "topK": 2}, _choice.ChoiceTrace())
assert boundary["candidateCount"] == 1 and boundary["finalP"] == [1, 0, 0] and boundary["nucleusCrossed"] == [1]
before = saved["base"]["tensors"][0]["values"].copy()
saved["tensors"][2]["values"][0] = -1
assert saved["base"]["tensors"][0]["values"] == before
assert sample_next([1, 0, 0], options, _choice.ChoiceTrace())["classIDs"] == [97, 98, 512]
4. Full scaled-base distribution — code/python/p11/choice_reference.py. direct_distribution records max, each shifted exponential, compact-order sum, logS, LSE and probabilities. Its own greedy metadata is a separate decision at scaled logits. Neither its greedy NextProbability nor the unscaled forward winner can replace model P at a sampled non-greedy class.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""Direct logits -> stable probabilities -> strict-logit greedy choice.
NumPy float64/int32 arrays are the actual storage. Scalar binary64 arithmetic
preserves exp, left-to-right denominator and division order. No neural/tokenizer
import is needed for the literal five-ID model contract. Full ordered chapter
records follow the owner-adopted A inventory. All execution remains DEFERRED.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np
ALL_IDS = (97, 98, 512, 256, 257)
DEFAULT_IV45 = MappingProxyType(dict(V=3, z0=1, z1=0, z2=0, z3=0, z4=0))
class NumericalFault(ValueError):
def __init__(self, code, reason):
super().__init__(reason)
self.code = code
def finite(value, label):
"""No coercion, bools, custom scalar conversions, infinities or NaNs."""
if type(value) not in (int, float):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
try:
value = float(value)
except (OverflowError, ValueError) as error:
raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
if not math.isfinite(value):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
return value
def choice_state(state):
"""Validate all six own fields in raw order, including inactive logits."""
if type(state) is not dict:
raise NumericalFault("INVALID_INPUT", "Provide a plain object with exactly V,z0,z1,z2,z3,z4.")
if any(type(key) is not str for key in state) or set(state) != set(DEFAULT_IV45):
raise NumericalFault("INVALID_INPUT", "Provide every own field and no extra or symbol fields, including inactive logits.")
checked = {}
for key in DEFAULT_IV45:
value = finite(state[key], key)
if key == "V":
if not value.is_integer() or not 3 <= value <= 5:
raise NumericalFault("INVALID_INPUT", "V must be an integer from 3 to 5.")
checked[key] = int(value)
else:
if not -40 <= value <= 40:
raise NumericalFault("INVALID_INPUT", f"{key} must be between -40 and 40.")
checked[key] = value
return checked
def guarded(derive):
@wraps(derive)
def call(state):
try:
return derive(state)
except NumericalFault as error:
return dict(status="unavailable", code=error.code, reason=str(error))
except (OverflowError, FloatingPointError) as error:
return dict(status="unavailable", code="NONFINITE", reason=str(error))
return call
class ChoiceTrace:
"""Finite detached scalar records; no implicit invocation of self-checks."""
def __init__(self):
self.steps = []
def add(self, identifier, label, equation, explanation, inputs, outputs):
if len(self.steps) >= 512:
raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 operations are supported.")
self.steps.append(dict(id=identifier, label=label, equation=equation, explanation=explanation,
inputs={key: finite(value, key) for key, value in inputs.items()},
outputs={key: finite(value, key) for key, value in outputs.items()}))
def _dense(values, label):
"""Inspect both containers before either helper operand is read."""
if type(values) is np.ndarray:
if values.ndim != 1 or values.dtype.kind not in "iuf":
raise NumericalFault("INVALID_INPUT", f"{label} must be a dense one-dimensional numeric array.")
elif type(values) not in (list, tuple):
raise NumericalFault("INVALID_INPUT", f"{label} must be an actual dense array.")
if not 3 <= len(values) <= 5:
raise NumericalFault("UNSUPPORTED_SIZE", f"{label} must have 3 to 5 entries.")
def _tensor(identifier, axis, values, provenance):
"""Serialize actual internal float64/int32 vectors into detached metadata."""
if type(values) is not np.ndarray or values.ndim != 1 or values.dtype not in (np.dtype(np.float64), np.dtype(np.int32)):
raise NumericalFault("SHAPE_MISMATCH", f"{identifier} requires actual float64/int32 vector storage.")
if not 1 <= len(values) <= 5:
raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier} requires 1 to 5 entries.")
flat = values.tolist()
for value in flat:
finite(value, identifier)
integer = values.dtype == np.dtype(np.int32)
return dict(id=identifier, shape=[len(flat)], axes=[axis], dtype="int32" if integer else "float64",
values=flat, provenance=provenance, precision=0 if integer else 8)
def direct_distribution(logits, class_ids, trace, prefix="choice"):
"""Dynamic V3..5 distribution; no slider bound on finite derived logits.
Prefix precedes both container guards; both descriptors precede entries.
Highest computed input logit wins; ties keep the lowest compact index.
"""
if type(prefix) is not str or not prefix:
raise NumericalFault("INVALID_INPUT", "prefix must be an actual nonempty string.")
_dense(logits, "logits")
_dense(class_ids, "classIDs")
if len(logits) != len(class_ids):
raise NumericalFault("SHAPE_MISMATCH", "logits and classIDs must have equal lengths.")
raw_z = logits.tolist() if type(logits) is np.ndarray else logits
raw_ids = class_ids.tolist() if type(class_ids) is np.ndarray else class_ids
V = len(raw_z)
z = np.array([finite(value, f"logits[{c}]") for c, value in enumerate(raw_z)], dtype=np.float64)
numeric_ids = [finite(value, f"classIDs[{c}]") for c, value in enumerate(raw_ids)]
checked_ids = []
for c, identifier in enumerate(numeric_ids):
if not identifier.is_integer() or identifier != ALL_IDS[c]:
raise NumericalFault("INVALID_INPUT", "classIDs must be the active prefix of [97,98,512,256,257].")
checked_ids.append(int(identifier))
ids = np.array(checked_ids, dtype=np.int32)
maximum_inputs = {f"z{c}": float(z[c]) for c in range(V)}
maximum = max(maximum_inputs.values())
trace.add(f"{prefix}_max", "Find the maximum active computed logit", "max=max(z0,...,z[V-1])",
"All active computed input logits participate. The maximum stabilizes exponentiation; it is not a rounded probability.",
maximum_inputs, dict(max=maximum))
shifted, terms, probabilities = (np.empty(V, dtype=np.float64) for _ in range(3))
denominator, running = 0.0, {}
for c in range(V):
logit = float(z[c])
shift = finite(logit - maximum, "shifted logit")
term = finite(math.exp(shift), "shifted exponential")
shifted[c], terms[c] = shift, term
trace.add(f"{prefix}_exp_{c}", f"Exponentiate active class {c}", "shifted=logit-max; term=exp(shifted)",
"No clipping, epsilon or display rounding feeds the distribution. Underflow is retained if a derived input reaches it.",
dict(c=c, logit=logit, max=maximum), dict(shifted=shift, term=term))
denominator = finite(denominator + term, "denominator")
running[f"running{c}"] = denominator
if denominator <= 0:
raise NumericalFault("UNAVAILABLE", "The shifted exponential denominator must be positive.")
log_s = finite(math.log(denominator), "logS")
lse = finite(maximum + log_s, "logsumexp")
trace.add(f"{prefix}_normalize", "Accumulate terms and compute logsumexp",
"running starts at 0; running_c=previous+term_c; logS=ln(S); LSE=max+logS",
"The denominator adds terms in ascending compact class order. Every actual running sum is saved.",
{**{f"term{c}": float(terms[c]) for c in range(V)}, "max": maximum},
{**running, "denominator": denominator, "logS": log_s, "lse": lse})
for c in range(V):
term = float(terms[c])
probability = finite(term / denominator, "probability")
probabilities[c] = probability
trace.add(f"{prefix}_probability_{c}", f"Normalize active class {c}", "probability=term/S",
"This stored binary64 probability is displayed without feeding its formatting back into arithmetic.",
dict(c=c, term=term, denominator=denominator), dict(probability=probability))
next_row = 0
for c in range(1, V):
if float(z[c]) > float(z[next_row]):
next_row = c
next_id, next_probability = int(ids[next_row]), float(probabilities[next_row])
trace.add(f"{prefix}_argmax", "Choose the highest computed input logit",
"strict greater-than updates the winner; exact ties retain lowest compact index",
"Greedy choice uses the saved logits, never argmax of rounded or stored probabilities. Compact index order differs from ascending public ID order.",
maximum_inputs, dict(nextRow=next_row, nextID=next_id, nextProbability=next_probability))
tensors = [
_tensor("ClassIDs", "Class", ids, "Active compact prefix [97,98,512,256,257]; public IDs are labels, not offsets."),
_tensor("Z", "Class", z, "Actual finite computed input logits; no derived-input clipping."),
_tensor("Shifted", "Class", shifted, "Z minus the saved active maximum."),
_tensor("Terms", "Class", terms, "Actual exp(Shifted), before normalization."),
_tensor("Denominator", "Scalar", np.array([denominator], dtype=np.float64), "Actual left-to-right sum of active shifted terms."),
_tensor("LogS", "Scalar", np.array([log_s], dtype=np.float64), "Natural logarithm of Denominator."),
_tensor("LSE", "Scalar", np.array([lse], dtype=np.float64), "Saved max+LogS in binary64."),
_tensor("P", "Class", probabilities, "Terms/Denominator for active classes only, without clipping or padding."),
_tensor("NextRow", "Decision", np.array([next_row], dtype=np.int32), "Lowest compact index among highest computed logits."),
_tensor("NextID", "Decision", np.array([next_id], dtype=np.int32), "Public class ID gathered at NextRow."),
_tensor("NextProbability", "Decision", np.array([next_probability], dtype=np.float64), "Stored P gathered at the computed-logit winner."),
]
return dict(classIDs=ids.tolist(), logits=z.tolist(), max=maximum, shifted=shifted.tolist(), terms=terms.tolist(),
denominator=denominator, logS=log_s, lse=lse, probabilities=probabilities.tolist(),
nextRow=next_row, nextID=next_id, nextProbability=next_probability, tensors=tensors)
def compute_choice(state):
"""Full ordered IV45 record, including raw inactive metadata and every step."""
s = choice_state(state)
raw_z = np.array([s[f"z{c}"] for c in range(5)], dtype=np.float64)
class_ids = np.array(ALL_IDS[:s["V"]], dtype=np.int32)
trace = ChoiceTrace()
trace.add("setup", "Validate all raw logits before selecting active classes", "V in {3,4,5}; every raw z in [-40,40]; activeZ=rawZ[:V]",
"Inactive raw logits still validate and remain visible as metadata. This direct lesson has no text, target, loss, training, seed or sampling.",
s, dict(classCount=s["V"], rawLogitCount=5))
row = direct_distribution(raw_z[:s["V"]], class_ids, trace)
trace.add("finish", "Keep the distribution and greedy decision together", "nextID=classIDs[argmax computed activeZ]; nextProbability=P[nextRow]",
"The selected ID is a deterministic decision. Equal stored probabilities need not mean equal logits.",
dict(nextRow=row["nextRow"]), dict(nextID=row["nextID"], nextProbability=row["nextProbability"]))
outputs = dict(nextID=row["nextID"], nextProbability=row["nextProbability"], classCount=s["V"], logsumexp=row["lse"],
nextRow=row["nextRow"], max=row["max"], denominator=row["denominator"], logS=row["logS"], rawLogitCount=5)
for step in trace.steps:
outputs.update({f"{step['id']}_{key}": value for key, value in step["outputs"].items()})
tensors = [_tensor("RawZ", "ModelRow", raw_z, "All five validated editable raw logits, including inactive slots."), *row["tensors"]]
return dict(status="defined", outputs=outputs, steps=trace.steps, tensors=tensors)
def source_self_check():
"""DEFERRED helper checks; never calls any other file's self-check."""
assert __debug__, "Deferred checks require assertions enabled."
state = dict(DEFAULT_IV45)
trace = ChoiceTrace()
row = direct_distribution([1, 0, 0], [97, 98, 512], trace)
assert list(row) == ["classIDs", "logits", "max", "shifted", "terms", "denominator", "logS", "lse", "probabilities", "nextRow", "nextID", "nextProbability", "tensors"]
ndarray_row = direct_distribution(np.array([1, 0, 0], dtype=np.float64), np.array([97, 98, 512], dtype=np.int32), ChoiceTrace())
assert ndarray_row == row
assert direct_distribution((1, 0, 0), (97, 98, 512), ChoiceTrace()) == row
assert len(trace.steps) == 9 and trace.steps[0]["id"] == "choice_max"
denominator = math.e + 2
assert row["nextRow"] == 0 and row["nextID"] == 97
assert math.isclose(row["probabilities"][0], math.e / denominator, rel_tol=1e-14)
assert math.isclose(row["probabilities"][1], 1 / denominator, rel_tol=1e-14)
assert math.isclose(row["lse"], math.log(denominator), rel_tol=1e-14)
tied = direct_distribution([0, 0, 1, 1, 0], ALL_IDS, ChoiceTrace())
assert tied["nextRow"] == 2 and tied["nextID"] == 512
uniform = direct_distribution([0] * 5, ALL_IDS, ChoiceTrace())
assert uniform["probabilities"] == [0.2] * 5 and uniform["nextID"] == 97
rounded = direct_distribution([0, math.ulp(0.0), 0], ALL_IDS[:3], ChoiceTrace())
assert rounded["probabilities"] == [1 / 3] * 3 and rounded["nextID"] == 98
thin = direct_distribution([-40, 40, -40], ALL_IDS[:3], ChoiceTrace())
assert thin["probabilities"][0] > 0 and thin["probabilities"][2] > 0
derived_trace = ChoiceTrace()
shifted = direct_distribution([101, 100, 100], ALL_IDS[:3], derived_trace, "derived")
assert shifted["probabilities"] == row["probabilities"] and shifted["nextID"] == row["nextID"]
assert all(step["id"].startswith("derived_") for step in derived_trace.steps)
for patch, code in ((dict(V=True), "NONFINITE"), (dict(V=2), "INVALID_INPUT"),
(dict(V=3.5), "INVALID_INPUT"), (dict(z4=True), "NONFINITE"),
(dict(z4=41), "INVALID_INPUT"), (dict(z4=float("nan")), "NONFINITE"),
(dict(z4=10**1000), "NONFINITE")):
fault = guarded(compute_choice)({**state, **patch})
assert list(fault) == ["status", "code", "reason"] and fault["code"] == code
class Hostile(dict):
def __getitem__(self, key):
raise AssertionError("Custom indexing must not be read")
assert guarded(compute_choice)(Hostile(state))["code"] == "INVALID_INPUT"
class HostileList(list):
def __getitem__(self, key):
raise AssertionError("Custom indexing must not be read")
for logits, ids, code in (([1, 0, 0], HostileList([97, 98, 512]), "INVALID_INPUT"),
(HostileList([1, 0, 0]), [97, 98, 512], "INVALID_INPUT"),
([1, 0, 0], [97, 98, 256], "INVALID_INPUT"),
([1, 0, 0], [99, float("nan"), 512], "NONFINITE"),
([1, float("nan"), 0], None, "INVALID_INPUT"),
([1, 0, 0], [97, 98, 512, 256], "SHAPE_MISMATCH"),
(np.array([True, False, False]), ALL_IDS[:3], "INVALID_INPUT"),
([1, True, 0], ALL_IDS[:3], "NONFINITE"),
([1, float("inf"), 0], ALL_IDS[:3], "NONFINITE"),
([1e308, -1e308, 0], ALL_IDS[:3], "NONFINITE"),
([1, 0], [97, 98], "UNSUPPORTED_SIZE")):
try:
direct_distribution(logits, ids, ChoiceTrace(), "bad")
except NumericalFault as error:
assert error.code == code
else:
raise AssertionError("Invalid helper boundary was accepted")
for prefix in (None, "", 0, True):
rejected_trace = ChoiceTrace()
try:
direct_distribution(HostileList(), None, rejected_trace, prefix)
except NumericalFault as error:
assert error.code == "INVALID_INPUT" and "prefix" in str(error)
assert not rejected_trace.steps
else:
raise AssertionError("Prefix must validate before containers")
assert _tensor("F", "Class", np.array([1.0], dtype=np.float64), "check")["dtype"] == "float64"
assert _tensor("I", "Class", np.array([97], dtype=np.int32), "check")["dtype"] == "int32"
row["tensors"][0]["values"][0] = -1
row["probabilities"][0] = -1
trace.steps[0]["outputs"].clear()
assert direct_distribution([1, 0, 0], ALL_IDS[:3], ChoiceTrace())["tensors"][0]["values"] == [97, 98, 512]
assert state == dict(DEFAULT_IV45)
_JSON_INT = int
def run(derive, defaults):
"""Default / full replacement JSON / '-' stdin; never invokes self-checks."""
class ParseFault(ValueError):
"""Only locally owned JSON profile/conversion faults."""
def _members(pairs):
value = {}
for key, member in pairs:
if key in value:
raise ParseFault("Duplicate JSON object members are not allowed.")
value[key] = member
return value
def _constant(token):
raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")
def _integer(token):
if token == "-0":
return -0.0
try:
return _JSON_INT(token)
except ValueError as fault:
if type(fault) is not ValueError:
raise
raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from fault
parser = argparse.ArgumentParser(description=derive.__doc__)
parser.add_argument("state", nargs="?")
args = parser.parse_args()
if args.state is not None:
source = sys.stdin.read() if args.state == "-" else args.state
try:
state = json.loads(source, object_pairs_hook=_members,
parse_constant=_constant, parse_int=_integer)
except (json.JSONDecodeError, ParseFault) as error:
result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
else:
result = derive(state)
else:
result = derive(dict(defaults))
print(json.dumps(result, allow_nan=False, separators=(",", ":")))
5. Same numerical decoder — code/python/p10/tiny_reference.py. forward_tiny gathers actual IDs and computes layer normalization, Q/K/value projections, absolute-position RoPE, causal attention, residuals, the second normalization, three-coordinate FFN and readout. _class_row computes every actual class probability row. The file also contains IV-43 objective code, but this generation path calls the ID-based forward directly, without targets, loss or derivatives. Real NumPy float64/int32/bool arrays back the full tensor evidence.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""IV43 tiny decoder: actual NumPy arrays and scalar-ordered arithmetic.
Text -> learned BPE -> E gather -> LN1 -> Q/K/V -> Q/K RoPE -> causal
attention -> identity WO -> residual -> LN2 -> M3 ReLU FFN -> residual
-> U/bias logits -> stable conditional objective and readout derivatives.
The first token is given. No optimizer, embedding/full-block gradient,
pretrained model or trained capability is supplied. All execution DEFERRED.
Keep the original p06, p07 and p09 files at their relative locations. The
chapter displays this exact dependency closure, rather than a rewritten demo.
"""
import argparse
from functools import wraps
import importlib.util
import json
import math
from pathlib import Path
import sys
from types import MappingProxyType
import numpy as np
_ROOT = Path(__file__).resolve().parent.parent
def _load(name, path):
"""Resolve an explicit source file; never search cwd or sys.path for helpers."""
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise ImportError(f"Cannot load canonical dependency: {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
_component = _load("_iv43_component_reference", _ROOT / "p07" / "component_reference.py")
# The unchanged FFN imports this bare name. Force OUR canonical dependency,
# even when an unrelated module already occupies the name, then restore it.
_missing = object()
_previous_component = sys.modules.get("component_reference", _missing)
sys.modules["component_reference"] = _component
try:
_ffn = _load("_iv43_ffn_reference", _ROOT / "p07" / "ffn_reference.py")
finally:
if _previous_component is _missing:
del sys.modules["component_reference"]
else:
sys.modules["component_reference"] = _previous_component
del _previous_component, _missing
_head = _load("_iv43_head_reference", _ROOT / "p06" / "head_reference.py")
_bpe = _load("_iv43_bpe_reference", _ROOT / "p09" / "bpe_reference.py")
_token = _bpe._token # BPE itself loads this exact adjacent token file.
NumericalFault = _component.NumericalFault
_DEPENDENCY_FAULTS = (NumericalFault, _head.NumericalFault, _bpe.NumericalFault, _ffn.NumericalFault)
ALL_IDS = (97, 98, 512, 256, 257)
PARAMETER_DEFAULTS = MappingProxyType(dict(
e00=1, e01=0, e10=0, e11=1, e20=0, e21=0, e30=0.5, e31=0.5, e40=1, e41=1,
u00=1, u01=0, u02=0, u03=0, u04=0, u10=0, u11=1, u12=0, u13=0, u14=0,
b0=0, b1=0, b2=0, b3=0, b4=0,
))
NUMERIC_DEFAULTS = MappingProxyType(dict(merges=0, **PARAMETER_DEFAULTS))
DEFAULT_IV43 = MappingProxyType(dict(text="ab", **NUMERIC_DEFAULTS))
def finite(value, label):
"""Own numbers only: booleans, coercion and overflowing integers are faults."""
if type(value) not in (int, float):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
try:
value = float(value)
except (ValueError, OverflowError) as error:
raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
if not math.isfinite(value):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
return value
def _object(value, fields, label):
# Exact dict rejects inherited/overridden indexing without invoking a getter.
if type(value) is not dict:
raise NumericalFault("INVALID_INPUT", "Provide a plain object with exactly the named data fields.")
if any(type(key) is not str for key in value) or set(value) != set(fields):
raise NumericalFault("INVALID_INPUT", "Provide every own field and no extra or symbol fields, including inactive parameters.")
def numeric_parameters(state):
"""Check all26 numeric fields, including unused rows/columns, in raw order."""
_object(state, NUMERIC_DEFAULTS, "numeric parameters")
checked = {}
for key in NUMERIC_DEFAULTS:
value = finite(state[key], key)
low, high = (0, 2) if key == "merges" else (-4, 4) if key.startswith("b") else (-2, 2)
if key == "merges" and (not value.is_integer() or not low <= value <= high):
raise NumericalFault("INVALID_INPUT", "merges must be an integer from 0 to 2.")
if not low <= value <= high:
raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
checked[key] = int(value) if key == "merges" else value
return checked
def tiny_state(state):
"""String type first, then EVERY numeric field, then text semantics later."""
_object(state, DEFAULT_IV43, "state")
if type(state["text"]) is not str:
raise NumericalFault("INVALID_INPUT", "text must be an actual string, without coercion.")
return dict(text=state["text"], numeric=numeric_parameters({key: state[key] for key in NUMERIC_DEFAULTS}))
def guarded(derive):
@wraps(derive)
def call(state):
try:
return derive(state)
except _DEPENDENCY_FAULTS as error:
return dict(status="unavailable", code=error.code, reason=str(error))
except (OverflowError, FloatingPointError) as error:
return dict(status="unavailable", code="NONFINITE", reason=str(error))
return call
def _ids(values, active):
"""Validate original public IDs before narrowing to real int32 storage."""
if type(values) is np.ndarray:
if values.ndim != 1 or values.dtype.kind not in "iuf":
raise NumericalFault("INVALID_INPUT", "inputIDs must be a dense one-dimensional numeric array.")
entries = values.tolist()
elif type(values) in (list, tuple):
entries = values
else:
raise NumericalFault("INVALID_INPUT", "inputIDs must be an actual dense array.")
if len(entries) > 3:
raise NumericalFault("UNSUPPORTED_SIZE", "Numeric inputIDs must contain at most 3 observed tokens.")
if not entries:
raise NumericalFault("UNAVAILABLE", "Numeric forward requires at least one observed input token.")
result = []
for t, value in enumerate(entries):
if type(value) not in (int, float):
raise NumericalFault("INVALID_INPUT", f"inputIDs[{t}] must be an active public model ID.")
try:
value = float(value)
except (ValueError, OverflowError) as error:
raise NumericalFault("INVALID_INPUT", f"inputIDs[{t}] must be an active public model ID.") from error
if not math.isfinite(value) or not value.is_integer() or value not in active:
raise NumericalFault("INVALID_INPUT", f"inputIDs[{t}] must be an active public model ID.")
result.append(int(value))
return np.array(result, dtype=np.int32)
def _float_tensor(identifier, shape, axes, values, provenance):
"""Serialize an actual float64 array into detached row-major JSON storage."""
if type(values) is not np.ndarray or values.dtype != np.dtype(np.float64) or tuple(shape) != values.shape:
raise NumericalFault("SHAPE_MISMATCH", f"{identifier} requires actual float64 storage of the declared shape.")
return _component.tensor(identifier, shape, axes, values.reshape(-1).tolist(), provenance)
def _norm(name, x, trace):
"""Keep normalization statistics in real scalar steps, without extra tensors."""
T = x["shape"][1]
X = np.array(x["values"], dtype=np.float64).reshape(1, T, 2)
output = np.empty((1, T, 2), dtype=np.float64)
for t in range(T):
row = _component.feature_norm("layer", f"{name.lower()}_{t}", X[0, t].tolist(),
[1, 1], [0, 0], 1, trace)
output[0, t] = row["values"]
source = "X" if name == "LN1" else "R1"
return _float_tensor(name, [1, T, 2], ["B", "T", "D"], output,
f"Per-token feature layer norm of {source}; population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside sqrt.")
def _residual(name, prefix, left, right, trace):
result = _component.same_shape_add(name, left, right)
for t in range(result["shape"][1]):
for d in range(2):
index = 2 * t + d
trace.add(f"{prefix}_{t}_{d}", f"{name} residual [0,{t},{d}]", "value=left+right",
"Actual same-shape addition; no broadcasting or second numerical engine.",
dict(t=t, d=d, left=left["values"][index], right=right["values"][index]),
dict(value=result["values"][index]))
return result
def _rope(role, values, trace):
"""One adjacent Q/K pair, frequency1, angle=absolute token position radians."""
T = values.shape[2]
rotated = np.empty((1, 1, T, 2), dtype=np.float64)
angles, cosines, sines = (np.empty(T, dtype=np.float64) for _ in range(3))
for t in range(T):
frequency = 10000 ** 0
angle = finite(t * frequency, "RoPE angle")
cosine, sine = finite(math.cos(angle), "RoPE cosine"), finite(math.sin(angle), "RoPE sine")
x0, x1 = float(values[0, 0, t, 0]), float(values[0, 0, t, 1])
product0, product1 = finite(x0 * cosine, "RoPE x0*cos"), finite(x1 * sine, "RoPE x1*sin")
product2, product3 = finite(x0 * sine, "RoPE x0*sin"), finite(x1 * cosine, "RoPE x1*cos")
rotated0, rotated1 = finite(product0 - product1, "RoPE first coordinate"), finite(product2 + product3, "RoPE second coordinate")
rotated[0, 0, t] = [rotated0, rotated1]
angles[t], cosines[t], sines[t] = angle, cosine, sine
trace.add(f"rope_{role}_{t}", f"RoPE {role} token {t}",
"frequency=10000^0; angle=t*frequency; rotated0=x0*cos-x1*sin; rotated1=x0*sin+x1*cos",
"Rotate this single adjacent pair at absolute position t. Q and K rotate; V remains unrotated. Every product is saved.",
dict(t=t, x0=x0, x1=x1, base=10000, exponent=0),
dict(frequency=frequency, angle=angle, cos=cosine, sin=sine, product0=product0, product1=product1,
product2=product2, product3=product3, rotated0=rotated0, rotated1=rotated1))
return rotated, angles, cosines, sines
# Literal metadata adoption is local: unchanged helpers still supply all storage and steps.
_PROJECTION_PROVENANCE = {
"X": "Active token rows; D=2 input features always retained.",
"WQ": "Query columns packed by h*Dk+f from wq{d}{h}{f}.",
"WK": "Key columns packed by h*Dk+f from wk{d}{h}{f}.",
"WV": "Value columns packed by h*Dv+f from wv{d}{h}{f}.",
"QConcat": "XWQ; each packed coordinate has two products and one sum.",
"KConcat": "XWK; each packed coordinate has two products and one sum.",
"VConcat": "XWV; values are projected separately from queries and keys.",
"QSplit": "QConcat reshaped without changing flat order; feature=h*F+f.",
"QHeads": "QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.",
"KSplit": "KConcat reshaped without changing flat order; feature=h*F+f.",
"KHeads": "KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.",
"VSplit": "VConcat reshaped without changing flat order; feature=h*F+f.",
"VHeads": "VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.",
}
_ATTENTION_PROVENANCE = {
"raw": "Separate QHeads KHeads transpose products within every batch and head.",
"scores": "raw/sqrt(Dk); the two-product order matches IV25 for H1,Dk2.",
"allowed": "Causal and/or valid-key mask; shared validity across B and H; every query retained.",
"logits": "Finite score+shift, including forbidden cells; mask applied separately.",
"probabilities": "Stable allowed-key softmax for each B/H/query independently; forbidden probabilities exactly zero.",
"OHeads": "Actual per-head P times VHeads; every product and running sum is traced.",
}
_JOIN_PROVENANCE = {
"C": "OHeads permuted to token-major order then joined by c=h*Dv+f; values unchanged.",
"WO": "wo{h}{f}{d} packed in h,f,d order, preserving parameter identity.",
"Y": "Y=C WO, summing products in ascending joined-feature order from zero; no normalization.",
}
_FFN_PROVENANCE = {
"W1": "Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.",
"b1": "Shared hidden bias, added after the two products.",
"Z": "Hidden preactivations X W1+b1; no batch or token mixing.",
"Hidden": "ReLU(Z)=max(0,Z), before the second affine layer.",
"W2": "Shared hidden-to-output weights, f2{m}{d}.",
"b2": "Shared output bias, added after all three running sums.",
"F": "ReLU(X W1+b1) W2+b2, independently per token with shared parameters.",
}
def _attention(n1, trace):
"""Reuse project/attend/join kernels; explicitly override their old WO."""
T = n1["shape"][1]
s = dict(_head.OUTPUT_HEAD_DEFAULTS)
s.update(B=1, T=T, H=1, Dk=2, Dv=2, mode=1, shift=0)
for t in range(T):
for d in range(2):
s[f"x0{t}{d}"] = n1["values"][2 * t + d]
for prefix in ("wq", "wk", "wv"):
for d in range(2):
for f in range(2):
s[f"{prefix}{d}0{f}"] = int(d == f)
for f in range(2):
for d in range(2):
s[f"wo0{f}{d}"] = int(f == d)
child = _head.head_trace()
try:
projected = _head.project_heads(s, child)
for step in child.steps:
trace.add(f"heads_{step['id']}", step["label"], step["equation"],
step["explanation"], step["inputs"], step["outputs"])
q, angles, cosines, sines = _rope("Q", projected["QHeads"], trace)
k, _, _, _ = _rope("K", projected["KHeads"], trace)
rotated = {**projected, "QHeads": q, "KHeads": k}
child = _head.head_trace()
attended = _head.attend_heads(s, rotated, child)
joined = _head.join_heads(s, attended, child)
except _head.NumericalFault as error:
raise NumericalFault(error.code, str(error)) from error
for step in child.steps:
trace.add(f"heads_{step['id']}", step["label"], step["equation"],
step["explanation"], step["inputs"], step["outputs"])
tensors = [{**record, "id": f"Projection{record['id']}",
"provenance": _PROJECTION_PROVENANCE[record["id"]] + " Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated."}
for record in projected["tensors"]]
tensors.extend([
_float_tensor("RotatedQHeads", [1, 1, T, 2], ["B", "H", "T", "Dk"], q,
"Actual RoPE(ProjectionQHeads) supplied as attendHeads QHeads; original projection is retained separately."),
_float_tensor("RotatedKHeads", [1, 1, T, 2], ["B", "H", "T", "Dk"], k,
"Actual RoPE(ProjectionKHeads) supplied as attendHeads KHeads; original projection is retained separately."),
_float_tensor("RoPEAngles", [T], ["Position"], angles, "Absolute position t times the single-pair frequency1, in radians."),
_float_tensor("RoPECos", [T], ["Position"], cosines, "Stored cos(angle) used in the Q pair rotation; K uses the same angle."),
_float_tensor("RoPESin", [T], ["Position"], sines, "Stored sin(angle) used in the Q pair rotation; K uses the same angle."),
])
tensors.extend({**record, "id": f"Attention{record['id']}",
"provenance": _ATTENTION_PROVENANCE[record["id"]] + " QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads."}
for record in attended["tensors"])
tensors.extend({**record, "id": "AttentionOutput" if record["id"] == "Y" else f"Attention{record['id']}",
"provenance": _JOIN_PROVENANCE[record["id"]] + " Source is AttentionOHeads; active WO is explicitly identity2."}
for record in joined["tensors"])
return tensors[-1], tensors
def tiny_trace():
"""An explicit finite scalar accumulator; forward_tiny never discards one."""
return _component.component_trace()
def forward_tiny(numeric_state, input_ids, trace):
"""Observed-ID forward with the adopted T,V,classIDs,inputIDs,inputRows,rows,tensors.
Validate26 parameters first, then dense active public IDs, including EOS.
Real float64/int32/bool arrays back the computation; the public return is a
detached JSON snapshot with complete stable distributions, without targets.
"""
s = numeric_parameters(numeric_state)
V = 3 + s["merges"]
ids = _ids(input_ids, ALL_IDS[:V])
T = len(ids)
class_ids = np.array(ALL_IDS[:V], dtype=np.int32)
input_rows = np.array([ALL_IDS.index(int(identifier)) for identifier in ids], dtype=np.int32)
E = np.array([[s[f"e{r}{d}"] for d in range(2)] for r in range(5)], dtype=np.float64)
U = np.array([[s[f"u{d}{c}"] for c in range(5)] for d in range(2)], dtype=np.float64)
bias = np.array([s[f"b{c}"] for c in range(5)], dtype=np.float64)
X = np.empty((1, T, 2), dtype=np.float64)
for t, identifier in enumerate(ids):
row = int(input_rows[t])
X[0, t] = E[row]
trace.add(f"input_{t}", f"Gather embedding for observed token {t}", "inputRow=compactRow(inputID); X[0,t,d]=E[inputRow,d]",
"The full model has an ordinary EOS embedding row. This kernel does not stop on EOS.",
dict(t=t, inputID=int(identifier)), dict(inputRow=row, x0=float(X[0, t, 0]), x1=float(X[0, t, 1])))
tensors = [
_token.tensor("AllClassIDs", "ModelRow", np.array(ALL_IDS, dtype=np.int32), "Full compact model row map: a,b,EOS,ab,abab; public IDs are not storage offsets."),
_token.tensor("ClassIDs", "Class", class_ids, "Active prefix of the full model row map; V=3+merges."),
_float_tensor("E", [5, 2], ["ModelRow", "D"], E, "All ten validated editable embeddings, including EOS and inactive learned pieces."),
_float_tensor("U", [2, 5], ["D", "ModelRow"], U, "All ten validated editable readout weights; only the first V columns contribute logits."),
_float_tensor("Bias", [5], ["ModelRow"], bias, "All five validated editable biases; inactive columns have no objective dependency."),
_token.tensor("InputIDs", "Position", ids, "Observed public IDs supplied directly to the numeric kernel; active EOS is permitted."),
_token.tensor("InputRows", "Position", input_rows, "Compact model row gathered for each observed ID; never index by public ID512."),
_float_tensor("X", [1, T, 2], ["B", "T", "D"], X, "Actual gathered E rows; B=1, token-major storage and D=2."),
]
n1 = _norm("LN1", tensors[-1], trace)
attention, at = _attention(n1, trace)
r1 = _residual("R1", "residual1", tensors[-1], attention, trace)
n2 = _norm("LN2", r1, trace)
fs = dict(B=1, T=T,
f100=1, f101=0, f102=0, f110=0, f111=1, f112=0,
fb10=0, fb11=0, fb12=0,
f200=1, f201=0, f210=0, f211=1, f220=0, f221=0,
fb20=0, fb21=0)
ffn = _ffn.feed_forward(fs, n2, trace, "ffn")
y = _residual("Y", "residual2", r1, ffn["output"], trace)
ft = [{**record, "provenance": _FFN_PROVENANCE[record["id"]]} for record in ffn["tensors"]]
tensors.extend([n1, *at, r1, n2, *ft, y])
Y = np.array(y["values"], dtype=np.float64).reshape(1, T, 2)
logits = np.empty((T, V), dtype=np.float64)
rows = []
for t in range(T):
for c in range(V):
y0, y1, u0, u1, b = float(Y[0, t, 0]), float(Y[0, t, 1]), float(U[0, c]), float(U[1, c]), float(bias[c])
product0, product1 = finite(y0 * u0, "readout product0"), finite(y1 * u1, "readout product1")
summed = finite(product0 + product1, "readout sum")
value = finite(summed + b, "readout logit")
logits[t, c] = value
trace.add(f"readout_{t}_{c}", f"Readout row {t}, class {c}",
"product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias",
"Only the active compact class prefix contributes to logits; targets are not operands.",
dict(t=t, c=c, y0=y0, u0=u0, y1=y1, u1=u1, bias=b),
dict(product0=product0, product1=product1, sum=summed, logit=value))
rows.append(_class_row(logits[t], t, class_ids, trace))
tensors.extend([
_float_tensor("Logits", [T, V], ["Position", "Class"], logits, "Final Y times the active U prefix, then active Bias; targets are not operands."),
_float_tensor("Max", [T], ["Position"], np.array([row["max"] for row in rows], dtype=np.float64), "Maximum computed active class logit at each position."),
_float_tensor("Shifted", [T, V], ["Position", "Class"], np.array([row["shifted"] for row in rows], dtype=np.float64), "Computed class logit minus its saved row maximum."),
_float_tensor("Terms", [T, V], ["Position", "Class"], np.array([row["terms"] for row in rows], dtype=np.float64), "Actual exp(Shifted) before left-to-right class summation."),
_float_tensor("Denominator", [T], ["Position"], np.array([row["denominator"] for row in rows], dtype=np.float64), "Shifted exponential sum from zero in ascending compact class order."),
_float_tensor("LogS", [T], ["Position"], np.array([row["logS"] for row in rows], dtype=np.float64), "ln(Denominator), saved for factored NLL."),
_float_tensor("LSE", [T], ["Position"], np.array([row["lse"] for row in rows], dtype=np.float64), "Max+LogS; saved evidence, not subtracted from target logits to compute NLL."),
_float_tensor("P", [T, V], ["Position", "Class"], np.array([row["probabilities"] for row in rows], dtype=np.float64), "Terms/Denominator for real active classes only; no inactive-class probabilities."),
_token.tensor("NextRows", "Position", np.array([row["nextRow"] for row in rows], dtype=np.int32), "Highest computed logit; exact ties keep the smallest compact class."),
_token.tensor("NextIDs", "Position", np.array([row["nextID"] for row in rows], dtype=np.int32), "Public ID mapped from each computed-logit winner."),
_float_tensor("NextProbability", [T], ["Position"], np.array([row["nextProbability"] for row in rows], dtype=np.float64), "Stored class probability of the computed-logit winner; never fed back as an observed input."),
])
return json.loads(json.dumps(dict(T=T, V=V, classIDs=class_ids.tolist(), inputIDs=ids.tolist(),
inputRows=input_rows.tolist(), rows=rows, tensors=tensors), allow_nan=False))
def _tokenize(text, merges, trace):
"""Actual IV39 algorithm with the narrower IV43 text/model boundary.
Prepare encoders before copying any successful record. Size in UTF16 units
precedes surrogate validation, then actual UTF8 size, then model alphabet.
The unchanged24/32-byte helper limits remain unchanged in their own files.
"""
if _token.utf16_length(text) > 6:
raise NumericalFault("UNSUPPORTED_SIZE", "text: more than 6 UTF-16 units exceeds the 6-byte model input bound.")
encoding = _token.TokenTrace()
try:
corpus = _bpe.encode_bounded("abab", "corpus", "corpus", encoding)
source = _bpe.encode_bounded(text, "text", "source", encoding)
if len(source["bytes"]) > 6:
raise NumericalFault("UNSUPPORTED_SIZE", "text: the actual UTF-8 encoding exceeds 6 bytes.")
if any(character not in "ab" for character in text):
raise NumericalFault("UNAVAILABLE", "This toy model supports only raw a and b letters; no normalization, unknown token or truncation is applied.")
if not text:
raise NumericalFault("UNAVAILABLE", "Empty text has no observed first token and no conditional target.")
child = _token.TokenTrace()
child.add("setup", "Declare learned byte-pair encoding and both exact inputs",
"byte IDs=0..255; learned ID=256+rank; EOS=512; each text field<=24 UTF-8 bytes",
"The disclosed training corpus is always abab. Encode the separate exact target with learned ranks, then append EOS. No normalization, trimming, unknown token or truncation.",
dict(requestedMerges=merges, eos=1),
dict(corpusUnits=4, corpusScalars=4, utf16Units=_token.utf16_length(text),
scalarCount=len(source["codePoints"]), byteBound=_bpe.BPE_BYTE_BOUND,
mergeBase=_bpe.MERGE_BASE, mergeBound=_bpe.MERGE_BOUND, EOS=512))
child.steps.extend(encoding.steps)
tensors = []
for stem, encoded in (("Corpus", corpus), ("Source", source)):
for suffix, key, axis, provenance in (
("CodePoints", "codePoints", "Scalars", "Validated Unicode scalars in exact input order."),
("UTF16Offsets", "offsets", "Scalars", "Zero-based UTF-16 storage offset for each scalar."),
("UTF16Widths", "widths", "Scalars", "UTF-16 storage units consumed by each scalar."),
("ByteOffsets", "byteOffsets", "Scalars", "Zero-based UTF-8 byte offset for each scalar."),
("ByteWidths", "byteWidths", "Scalars", "Actual UTF-8 bytes emitted by each scalar."),
("Bytes", "bytes", "Bytes", "Manual UTF-8 encoding in source order, preserving all data."),
):
_bpe.save_tensor(tensors, f"{stem}{suffix}", axis, encoded[key], provenance)
trained = _bpe.train_bpe(corpus["bytes"], merges, child, tensors)
ids = _bpe.encode_bpe(source["bytes"], trained["rules"], 1, child, tensors)
corpus_decoded = _bpe.decode_bpe_ids(trained["ids"], trained["rules"], 0, "corpus", child)
decoded = _bpe.decode_bpe_ids(ids, trained["rules"], 1, "target", child)
corpus_equal = int(corpus_decoded["decoded"] == "abab")
equal = int(decoded["decoded"] == text)
if not corpus_equal or not equal:
raise NumericalFault("INVALID_INPUT", "Actual BPE reconstructions did not equal both original strings.")
child.add("roundtrip", "Compare both actual strict reconstructions with the original strings",
"corpusEqual=(corpusDecoded===corpus); equal=(targetDecoded===text)",
"Expand actual saved IDs, concatenate bytes, strictly reconstruct scalars, then compare complete strings.",
dict(corpusOriginalUnits=4, corpusDecodedUnits=_token.utf16_length(corpus_decoded["decoded"]),
corpusDecodedByteCount=len(corpus_decoded["bytes"]), originalUnits=_token.utf16_length(text),
decodedUnits=_token.utf16_length(decoded["decoded"]), decodedByteCount=len(decoded["bytes"])),
dict(corpusTokens=len(trained["ids"]), tokenCount=len(ids), corpusEqual=corpus_equal, equal=equal))
_bpe.save_tensor(tensors, "CorpusDecodedBytes", "Bytes", corpus_decoded["bytes"], "Actual final corpus ID expansions passed to strict UTF-8 decoding.")
_bpe.save_tensor(tensors, "TargetDecodedBytes", "Bytes", decoded["bytes"], "Actual final target ID expansions passed to strict UTF-8 decoding.")
except _bpe.NumericalFault as error:
raise NumericalFault(error.code, str(error)) from error
if len(ids) - 1 > 3:
raise NumericalFault("UNSUPPORTED_SIZE", "The actual BPE sequence exceeds 3 observed input positions; change text or merges explicitly.")
for step in child.steps:
trace.add(f"tokenizer_{step['id']}", step["label"], step["equation"],
step["explanation"], step["inputs"], step["outputs"])
tensors = [{**record, "id": f"Tokenizer{record['id']}"} for record in tensors]
expansions = {rule["id"]: rule["bytes"].tolist() for rule in trained["rules"]}
def expansion(identifier):
return [] if identifier == 512 else [identifier] if identifier <= 255 else expansions[identifier]
def labels(values):
return ["ID 512: EOS (explicit control), bytes []" if int(identifier) == 512 else
f"ID {int(identifier)}, bytes {_token.json_text(expansion(int(identifier)))}" for identifier in values]
texts = dict(
corpus="abab", input=text, corpusDecoded=corpus_decoded["decoded"], decoded=decoded["decoded"],
corpusLabels=labels(trained["ids"]), corpusExpansions=[_token.json_text(expansion(int(identifier))) for identifier in trained["ids"]],
targetLabels=labels(ids), targetExpansions=[_token.json_text(expansion(int(identifier))) for identifier in ids],
ruleLabels=[f"ID {rule['id']}, bytes {_token.json_text(rule['bytes'].tolist())}" for rule in trained["rules"]],
ruleExpansions=[_token.json_text(rule["bytes"].tolist()) for rule in trained["rules"]],
trainingStop="Zero merges requested: no training round or pair selection occurs." if merges == 0 else "Stopped early: fewer than two current training tokens remain." if len(trained["rules"]) < merges else "Requested merge budget completed.",
)
summary = dict(corpusBytes=len(corpus["bytes"]), byteCount=len(source["bytes"]), actualMerges=len(trained["rules"]),
tokenCount=len(ids), requestedMerges=merges, corpusTokens=len(trained["ids"]), eos=1,
byteBound=_bpe.BPE_BYTE_BOUND, vocabularyItems=256 + len(trained["rules"]) + 1,
corpusEqual=corpus_equal, equal=equal)
return dict(ids=ids, tensors=tensors, texts=texts, summary=summary)
def _class_row(logits, t, class_ids, trace):
"""Stable complete row before the next token's readout; strict-logit argmax."""
V = len(class_ids)
maximum_inputs = {f"z{c}": float(logits[c]) for c in range(V)}
maximum = max(maximum_inputs.values())
trace.add(f"class_{t}_max", f"Class maximum for prediction row {t}", "max=max(active logits)",
"Only active classes contribute. The maximum term exp(0)=1 prevents a zero normalizer.",
maximum_inputs, dict(max=maximum))
shifted, terms, probabilities = (np.empty(V, dtype=np.float64) for _ in range(3))
denominator, running = 0.0, {}
for c in range(V):
z = float(logits[c])
shift = finite(z - maximum, "class shifted logit")
term = finite(math.exp(shift), "class exponential")
shifted[c], terms[c] = shift, term
trace.add(f"class_{t}_exp_{c}", f"Class row {t}, exponential {c}", "shifted=logit-max; term=exp(shifted)",
"Save each actual shifted exponential; no epsilon, clipping or rounded display operand.",
dict(t=t, c=c, logit=z, max=maximum), dict(shifted=shift, term=term))
denominator = finite(denominator + term, "class denominator")
running[f"running{c}"] = denominator
log_s = finite(math.log(denominator), "class logS")
lse = finite(maximum + log_s, "class logsumexp")
trace.add(f"class_{t}_normalize", f"Class denominator and logsumexp for row {t}",
"running starts at 0; running_c=previous+term_c; denominator=last running; logS=ln(denominator); lse=max+logS",
"Terms accumulate left to right. The objective uses (max-targetLogit)+logS rather than subtraction of rounded LSE.",
{**{f"term{c}": float(terms[c]) for c in range(V)}, "max": maximum},
{**running, "denominator": denominator, "logS": log_s, "lse": lse})
for c in range(V):
term = float(terms[c])
probability = finite(term / denominator, "class probability")
probabilities[c] = probability
trace.add(f"class_{t}_probability_{c}", f"Class row {t}, probability {c}", "probability=term/denominator",
"This is an actual stored probability, never a rounded display value used as arithmetic input.",
dict(t=t, c=c, term=term, denominator=denominator), dict(probability=probability))
next_row = 0
for c in range(1, V):
if float(logits[c]) > float(logits[next_row]):
next_row = c
next_id, next_probability = int(class_ids[next_row]), float(probabilities[next_row])
trace.add(f"class_{t}_argmax", f"Computed-logit winner for row {t}", "argmax(logits); exact ties use smallest compact class",
"Probability rounding can make distinct logits appear tied. Compare computed logits; predictions are not observed teacher-forcing inputs.",
maximum_inputs, dict(nextRow=next_row, nextID=next_id, nextProbability=next_probability))
return dict(logits=logits.tolist(), max=maximum, shifted=shifted.tolist(), terms=terms.tolist(),
denominator=denominator, logS=log_s, lse=lse, probabilities=probabilities.tolist(),
nextRow=next_row, nextID=next_id, nextProbability=next_probability)
def _objective(forward, targets, trace):
"""Mean shifted-target NLL and ONLY the conditional readout derivatives."""
T, V, rows, class_ids = forward["T"], forward["V"], forward["rows"], forward["classIDs"]
Y = np.array(next(record["values"] for record in forward["tensors"] if record["id"] == "Y"), dtype=np.float64).reshape(1, T, 2)
target_rows = np.empty(T, dtype=np.int32)
nll, gaps, target_logits, target_probabilities = (np.empty(T, dtype=np.float64) for _ in range(4))
for t in range(T):
target_id = int(targets[t])
if target_id not in class_ids:
raise NumericalFault("INVALID_INPUT", "Every shifted target must be an active model class.")
c = class_ids.index(target_id)
target_rows[t] = c
trace.add(f"target_lookup_{t}", f"Map shifted target at position {t}", "targetRow=compactRow(sequence[t+1])",
"Teacher forcing keeps the observed input and its next target distinct. Final EOS contributes one loss.",
dict(t=t, targetID=target_id, V=V), dict(targetRow=c))
row = rows[t]
target_logit, maximum, log_s, probability = row["logits"][c], row["max"], row["logS"], row["probabilities"][c]
gaps[t] = finite(maximum - target_logit, "target gap")
nll[t] = finite(float(gaps[t]) + log_s, "target NLL")
target_logits[t], target_probabilities[t] = target_logit, probability
trace.add(f"loss_{t}", f"Shifted target loss at position {t}", "gap=max-targetLogit; nll=gap+logS",
"Use the saved stable operands. The first piece is given; every continuation through EOS has weight1.",
dict(t=t, targetID=target_id, targetRow=c, max=maximum, targetLogit=target_logit, logS=log_s, probability=probability),
dict(gap=float(gaps[t]), nll=float(nll[t])))
loss_sum = 0.0
for t in range(T):
previous = loss_sum
loss_sum = finite(previous + float(nll[t]), "loss sum")
trace.add(f"reduce_{t}", f"Accumulate target loss {t}", "lossSum=previousLossSum+nll",
"Accumulate every actual shifted target loss in ascending position order, including EOS.",
dict(t=t, previousLossSum=previous, nll=float(nll[t])), dict(lossSum=loss_sum))
mean_nll = finite(loss_sum / T, "mean NLL")
perplexity = finite(math.exp(mean_nll), "perplexity")
trace.add("reduction", "Mean conditional objective and perplexity", "validCount=T; meanNLL=lossSum/T; perplexity=exp(meanNLL)",
"Natural-log loss is in nats per shifted target. Tokenizer changes alter the events and conditioning.",
dict(T=T, lossSum=loss_sum), dict(validCount=T, lossSum=loss_sum, meanNLL=mean_nll, perplexity=perplexity))
d_logits = np.empty((T, V), dtype=np.float64)
for t in range(T):
for c in range(V):
probability, indicator = rows[t]["probabilities"][c], int(c == int(target_rows[t]))
difference = finite(probability - indicator, "probability minus target")
gradient = finite(difference / T, "mean logit derivative")
d_logits[t, c] = gradient
trace.add(f"gradient_{t}_{c}", f"Mean-loss logit derivative [{t},{c}]", "indicator=(c=targetRow)?1:0; difference=P-indicator; gradient=difference/T",
"The analytic sensitivity includes the mean-loss denominator; it is not a gradient check or update.",
dict(t=t, c=c, targetRow=int(target_rows[t]), probability=probability, T=T),
dict(indicator=indicator, difference=difference, gradient=gradient))
# Inactive raw columns have zero dependency, not fabricated active probabilities.
d_u = np.zeros((2, 5), dtype=np.float64)
d_bias = np.zeros(5, dtype=np.float64)
for d in range(2):
for c in range(V):
inputs, outputs, gradient = dict(d=d, c=c), {}, 0.0
for t in range(T):
feature, g = float(Y[0, t, d]), float(d_logits[t, c])
inputs[f"y{t}"], inputs[f"g{t}"] = feature, g
product = finite(feature * g, "readout gradient product")
gradient = finite(gradient + product, "readout gradient sum")
outputs[f"product{t}"], outputs[f"running{t}"] = product, gradient
outputs["gradient"] = gradient
d_u[d, c] = gradient
trace.add(f"readout_gradient_{d}_{c}", f"Readout weight derivative [{d},{c}]", "product_t=Y[t,d]*dLogits[t,c]; running starts at 0; gradient=sum_t product_t",
"Hold final decoder features fixed. Each product immediately enters the sum in ascending position order.", inputs, outputs)
for c in range(V):
inputs, outputs, gradient = dict(c=c), {}, 0.0
for t in range(T):
g = float(d_logits[t, c])
inputs[f"g{t}"] = g
gradient = finite(gradient + g, "bias gradient sum")
outputs[f"running{t}"] = gradient
outputs["gradient"] = gradient
d_bias[c] = gradient
trace.add(f"bias_gradient_{c}", f"Readout bias derivative [{c}]", "running starts at 0; gradient=sum_t dLogits[t,c]",
"Each active bias contributes directly at each position. Inactive raw columns have structural zero dependency.", inputs, outputs)
tensors = [
_token.tensor("TargetIDs", "Position", targets, "sequence[1:]; final EOS included exactly once as a scored continuation."),
_token.tensor("TargetRows", "Position", target_rows, "Active compact class of each observed shifted target."),
_float_tensor("TargetLogits", [T], ["Position"], target_logits, "Actual class logit gathered after computing the entire causal distribution."),
_float_tensor("TargetProbability", [T], ["Position"], target_probabilities, "Actual target class probability; never rounded before loss computation."),
_float_tensor("TargetGap", [T], ["Position"], gaps, "Saved max-targetLogit used in the factored NLL."),
_float_tensor("NLL", [T], ["Position"], nll, "TargetGap+LogS for every shifted target, including EOS."),
_float_tensor("dLogits", [T, V], ["Position", "Class"], d_logits, "(P-oneHot(target))/T for the actual mean objective."),
_float_tensor("dU", [2, 5], ["D", "ModelRow"], d_u, "Conditional readout gradient sum_t Y[t,d]*dLogits[t,c]; inactive raw class columns have structural zero dependency."),
_float_tensor("db", [5], ["ModelRow"], d_bias, "Conditional readout bias gradient sum_t dLogits[t,c]; inactive raw biases have structural zero dependency."),
]
return dict(validCount=T, lossSum=loss_sum, meanNLL=mean_nll, perplexity=perplexity, tensors=tensors)
_JSON_INT = int
def run(derive, defaults):
"""No args: default; one JSON argument: COMPLETE replacement; '-': stdin.
No query calls any self-check. Invalid data returns only status/code/reason.
No caller cwd supplies a helper; source loading above is file-relative.
"""
class ParseFault(ValueError):
"""Only locally owned JSON profile/conversion faults."""
def _members(pairs):
value = {}
for key, member in pairs:
if key in value:
raise ParseFault("Duplicate JSON object members are not allowed.")
value[key] = member
return value
def _constant(token):
raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")
def _integer(token):
if token == "-0":
return -0.0
try:
return _JSON_INT(token)
except ValueError as fault:
if type(fault) is not ValueError:
raise
raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from fault
parser = argparse.ArgumentParser(description=derive.__doc__)
parser.add_argument("state", nargs="?")
args = parser.parse_args()
if args.state is not None:
source = sys.stdin.read() if args.state == "-" else args.state
try:
state = json.loads(source, object_pairs_hook=_members,
parse_constant=_constant, parse_int=_integer)
except (json.JSONDecodeError, ParseFault) as error:
result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
else:
result = derive(state)
else:
result = derive(dict(defaults))
print(json.dumps(result, allow_nan=False, separators=(",", ":")))
def source_self_check():
"""DEFERRED explicit helper assertions; never called by import or query.
Source-authored anchors/metamorphics are not independent oracle authority.
Future V5 separately invokes this, the wrapper check and the old BPE check.
"""
assert __debug__, "Deferred checks require assertions enabled."
assert _ffn.NumericalFault is _component.NumericalFault
assert _ffn.tensor is _component.tensor
assert _ffn.finite is _component.finite
assert Path(_component.__file__).resolve() == _ROOT / "p07" / "component_reference.py"
assert Path(_ffn.__file__).resolve() == _ROOT / "p07" / "ffn_reference.py"
assert Path(_head.__file__).resolve() == _ROOT / "p06" / "head_reference.py"
assert Path(_bpe.__file__).resolve() == _ROOT / "p09" / "bpe_reference.py"
assert Path(_token.__file__).resolve() == _ROOT / "p09" / "token_reference.py"
assert len(DEFAULT_IV43) == 27 and len(NUMERIC_DEFAULTS) == 26
assert list(DEFAULT_IV43) == ["text", "merges", *PARAMETER_DEFAULTS]
assert list(tiny_state(dict(DEFAULT_IV43))) == ["text", "numeric"]
def rejects(call, code):
try:
call()
except NumericalFault as error:
assert error.code == code, (error.code, code)
else:
raise AssertionError("Invalid helper input was accepted")
def forward(parameters, ids):
return forward_tiny(parameters, ids, tiny_trace())
def saved(record, identifier):
return next(tensor for tensor in record["tensors"] if tensor["id"] == identifier)
s = dict(NUMERIC_DEFAULTS)
trace = tiny_trace()
f = forward_tiny(s, [97, 98], trace)
assert list(f) == ["T", "V", "classIDs", "inputIDs", "inputRows", "rows", "tensors"]
assert list(f["rows"][0]) == ["logits", "max", "shifted", "terms", "denominator", "logS", "lse", "probabilities", "nextRow", "nextID", "nextProbability"]
assert f["T"] == 2 and f["V"] == 3 and f["inputRows"] == [0, 1]
assert len(trace.steps) == 112 and len(f["tensors"]) == 57
assert saved(f, "E")["shape"] == [5, 2] and saved(f, "U")["shape"] == [2, 5]
assert saved(f, "Bias")["shape"] == [5]
assert saved(f, "InputIDs")["dtype"] == "int32" and _ids([97, 98], ALL_IDS).dtype == np.dtype(np.int32)
assert all(saved(f, name)["dtype"] == "float64" for name in ("E", "U", "Bias", "Y", "Logits", "P"))
for tensor in f["tensors"]:
assert list(tensor) == ["id", "shape", "axes", "dtype", "values", "provenance", "precision"]
assert tensor["precision"] == (0 if tensor["dtype"] == "int32" else 8)
# These constructors require real float64 storage before JSON projection.
rejects(lambda: _float_tensor("bad", [1], ["D"], np.array([1], dtype=np.int32), "wrong dtype"), "SHAPE_MISMATCH")
rejects(lambda: _float_tensor("bad", [2], ["D"], np.array([1], dtype=np.float64), "wrong shape"), "SHAPE_MISMATCH")
alpha = 1 / math.sqrt(5)
r = math.exp((2 * alpha * alpha / math.sqrt(2)) * (1 + math.cos(1)))
d = (r - 1) / (r + 1)
delta0, delta1 = 0.5 + alpha, 0.5 + alpha * d
rho0, rho1 = delta0 / math.sqrt(delta0 * delta0 + 1), delta1 / math.sqrt(delta1 * delta1 + 1)
expected = [[1 + alpha + rho0, -alpha], [-alpha * d, 1 + alpha * d + rho1]]
for t in range(2):
for coordinate in range(2):
assert math.isclose(saved(f, "Y")["values"][t * 2 + coordinate], expected[t][coordinate], rel_tol=1e-12, abs_tol=1e-14)
attention_p, allowed = saved(f, "Attentionprobabilities"), saved(f, "Attentionallowed")
assert allowed["dtype"] == "bool" and allowed["precision"] == 8 and allowed["values"] == [True, False, True, True]
assert attention_p["values"][:2] == [1, 0]
assert math.isclose(attention_p["values"][2], 1 / (1 + r), rel_tol=1e-12)
assert math.isclose(attention_p["values"][3], r / (1 + r), rel_tol=1e-12)
# Earlier causal features survive a later ID edit; forbidden raw scores need not.
later = forward(s, [97, 97])
assert saved(f, "Y")["values"][:2] == saved(later, "Y")["values"][:2]
assert f["rows"][0] == later["rows"][0]
eos_input = forward({**s, "e20": 1, "e21": -1}, [512])
assert eos_input["inputIDs"] == [512] and eos_input["inputRows"] == [2]
assert saved(eos_input, "X")["values"] == [1, -1]
assert forward(s, [97])["rows"][0] == f["rows"][0]
assert forward(s, [512, 97])["inputRows"] == [2, 0]
for merges, text, ids in ((0, "ab", [97, 98, 512]), (1, "ab", [256, 512]),
(2, "abab", [257, 512]), (1, "ababab", [256, 256, 256, 512]),
(2, "ababab", [257, 256, 512])):
checked = tiny_state({**DEFAULT_IV43, "text": text, "merges": merges})
tokenized = _tokenize(checked["text"], checked["numeric"]["merges"], tiny_trace())
assert tokenized["ids"].tolist() == ids and tokenized["ids"].dtype == np.dtype(np.int32)
for ids, code in (([], "UNAVAILABLE"), ([97] * 4, "UNSUPPORTED_SIZE"), ([256], "INVALID_INPUT"),
([True], "INVALID_INPUT"), (["97"], "INVALID_INPUT"), ([None], "INVALID_INPUT"),
([768], "INVALID_INPUT"), ([97.5], "INVALID_INPUT"),
([float("nan")], "INVALID_INPUT"), ([float("inf")], "INVALID_INPUT"), ([10**1000], "INVALID_INPUT")):
rejects(lambda: forward(s, ids), code)
rejects(lambda: forward(s, np.array([True])), "INVALID_INPUT")
rejects(lambda: forward(s, np.array([[97]])), "INVALID_INPUT")
rejects(lambda: forward(s, {0: 97}), "INVALID_INPUT")
for field, value, code in (("e40", 3, "INVALID_INPUT"), ("u04", True, "NONFINITE"),
("b4", 10**1000, "NONFINITE"), ("merges", 0.5, "INVALID_INPUT")):
rejects(lambda: forward({**s, field: value}, [97]), code)
rejects(lambda: forward({**s, "b4": float("nan")}, []), "NONFINITE")
rejects(lambda: numeric_parameters({**s, "extra": 1}), "INVALID_INPUT")
rejects(lambda: numeric_parameters({key: value for key, value in s.items() if key != "u04"}), "INVALID_INPUT")
class GetterDict(dict):
def __getitem__(self, key):
raise AssertionError("Custom getter must not execute")
rejects(lambda: tiny_state(GetterDict(DEFAULT_IV43)), "INVALID_INPUT")
rejects(lambda: tiny_state({**DEFAULT_IV43, "text": [], "e40": float("nan")}), "INVALID_INPUT")
for patch, code in (({"text": "a" * 7}, "UNSUPPORTED_SIZE"), ({"text": "\ud800"}, "INVALID_INPUT"),
({"text": "🦊🦊"}, "UNSUPPORTED_SIZE"), ({"text": "ééé"}, "UNAVAILABLE"),
({"text": "c"}, "UNAVAILABLE"), ({"text": ""}, "UNAVAILABLE"),
({"text": "ababab"}, "UNSUPPORTED_SIZE")):
checked = tiny_state({**DEFAULT_IV43, **patch})
rejects(lambda: _tokenize(checked["text"], checked["numeric"]["merges"], tiny_trace()), code)
rejects(lambda: tiny_state({**DEFAULT_IV43, "text": "\ud800", "b4": float("nan")}), "NONFINITE")
# Public records and the explicit trace are detached from state and later calls.
f["rows"][0]["probabilities"][0] = 99
saved(f, "Y")["values"][0] = 99
f["tensors"][0]["values"][0] = 0
trace.steps[0]["outputs"].clear()
again = forward(s, [97, 98])
assert saved(again, "Y")["values"][0] != 99
assert again["rows"][0]["probabilities"][0] != 99
assert again["inputIDs"] == [97, 98]
assert s == dict(NUMERIC_DEFAULTS)
def derive43(state):
"""Compose the owner-adopted complete ordered numerical/text snapshot."""
checked = tiny_state(state)
text, numeric = checked["text"], checked["numeric"]
token_trace = tiny_trace()
tokenized = _tokenize(text, numeric["merges"], token_trace)
sequence = tokenized["ids"]
inputs, targets = sequence[:-1].copy(), sequence[1:].copy()
T, V = len(inputs), 3 + numeric["merges"]
trace = tiny_trace()
trace.add("setup", "Validate all raw fields before interpreting the text",
"text<=6 UTF-8 bytes; fixed corpus=abab; eos=1; inputs=sequence[:-1]; targets=sequence[1:]",
"The first encoded piece is given. Score each continuation through EOS; no first-piece probability, cropping or learning update.",
numeric, dict(utf16Units=_token.utf16_length(text), byteBound=6, eos=1, corpusUnits=4))
for step in token_trace.steps:
trace.add(step["id"], step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
class_ids = np.array(ALL_IDS[:V], dtype=np.int32)
token_summary = tokenized["summary"]
trace.add("class_map", "Map tokenizer IDs to active compact model classes", "V=3+actualMerges; classIDs=prefix([97,98,512,256,257],V)",
"Tokenizer vocabularyItems=257+merges differs from the model's 3+merges active classes; public IDs never allocate513 rows.",
dict(actualMerges=token_summary["actualMerges"], vocabularyItems=token_summary["vocabularyItems"]),
{"classCount": V, **{f"id{c}": int(identifier) for c, identifier in enumerate(class_ids)}})
forward = forward_tiny(numeric, inputs, trace)
objective = _objective(forward, targets, trace)
trace.add("finish", "Keep the objective and conditional readout derivatives together",
"objective=mean shifted NLL; derivatives=dLogits,dU,db with decoder features fixed",
"All parameters are hand-set and untrained. No optimizer, embedding/full-block gradient or language-learning claim.",
dict(contextLength=T, classCount=V),
dict(validCount=T, lossSum=objective["lossSum"], meanNLL=objective["meanNLL"], perplexity=objective["perplexity"]))
last = forward["rows"][-1]
summary = dict(validCount=T, lossSum=objective["lossSum"], meanNLL=objective["meanNLL"], perplexity=objective["perplexity"],
classCount=V, actualMerges=numeric["merges"], contextLength=T,
B=1, D=2, H=1, Dk=2, Dv=2, hiddenWidth=3, byteBound=6,
nextRow=last["nextRow"], nextID=last["nextID"], nextProbability=last["nextProbability"],
**{f"tokenizer_{key}": value for key, value in token_summary.items()})
tensors = [*tokenized["tensors"], *forward["tensors"],
_token.tensor("SequenceIDs", "Sequence", sequence, "Actual ranked BPE result with one final EOS; the first piece is given."),
*objective["tensors"]]
texts = dict(input=text, decoded=tokenized["texts"]["decoded"],
objective="Conditional continuation through EOS given the first encoded piece; no probability for that first piece.",
gradientScope="Analytic readout U/bias derivatives with decoder features fixed; no embedding/full-block gradient, optimizer update or training.",
modelVocabulary=["0: a / ID97", "1: b / ID98", "2: EOS / ID512", "3: ab / ID256", "4: abab / ID257"],
**{f"tokenizer_{key}": value for key, value in tokenized["texts"].items()})
result = trace.result(summary, tensors)
result["texts"] = texts
# Python exposes ordinary detached JSON; TS additionally freezes its snapshot.
return json.loads(json.dumps(result, allow_nan=False, ensure_ascii=False))
if __name__ == "__main__":
run(guarded(derive43), DEFAULT_IV43)
6. Actual prompt BPE composition — code/python/p09/iv39.py. derive_iv39 trains on fixed abab, applies requested merges to the separate prompt, and retains both real reconstructions with EOS off. This supplies the prompt IDs and rules; it is never called again on decoded characters after an emission.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""IV-39 — Byte-Pair Encoding: A Full Merge Trace.
Train adjacent byte-ID pairs on a separate, literal training corpus. Count
ALL adjacent occurrences, including overlaps, choose the greatest count,
then the lexicographically smallest NUMERIC (left ID, right ID) on ties.
Replace matches left to right without overlap. Recount after every rule.
Encode the target with the learned rules in increasing rank, not by taking
the longest dictionary prefix. Only the target can receive explicit EOS512.
Hand default: corpus abab starts [97,98,97,98]. Counts ab2,ba1 select ab256,
so [256,256] becomes rule257=[97,98,97,98]. Target ababab becomes
[256,256,256] then [257,256]; expanding BOTH IDs reconstructs six bytes.
Corpus aaaa has three adjacent aa occurrences but only two replacements.
Corpus bbaa encounters bb,ba,aa once each; numeric order chooses the LAST
encountered aa=(97,97), producing [98,98,256], not insertion-order bb.
Corpus 'bc bc ab' learns bc256,bc-space257,ab258. In its third round
(97,98) beats pairs starting257 numerically, not by decimal string keys.
Target abc becomes [97,256]; greedy longest-prefix ab258 would differ.
All source is authored without imports, execution, fixtures generation or
runtime validation. Keep bpe_reference.py AND token_reference.py beside this
wrapper. File-relative loading supports an arbitrary caller working directory.
"""
import importlib.util
from pathlib import Path
_bpe_spec = importlib.util.spec_from_file_location(
"_p09_bpe_reference", Path(__file__).resolve().with_name("bpe_reference.py"))
_bpe = importlib.util.module_from_spec(_bpe_spec)
_bpe_spec.loader.exec_module(_bpe)
DEFAULT_IV39 = _bpe.DEFAULT_IV39
@_bpe._token.guarded
def derive_iv39(state):
"""Train a real corpus, encode a separate target, and decode both actual IDs."""
token = _bpe._token
s = _bpe.bpe_state(state)
encoding_trace = token.TokenTrace()
corpus = _bpe.encode_bounded(s["corpus"], "corpus", "corpus", encoding_trace)
source = _bpe.encode_bounded(s["text"], "text", "source", encoding_trace)
trace = token.TokenTrace()
corpus_units, units = token.utf16_length(s["corpus"]), token.utf16_length(s["text"])
trace.add("setup", "Declare learned byte-pair encoding and both exact inputs",
"byte IDs=0..255; learned ID=256+rank; EOS=512; each text field<=24 UTF-8 bytes",
"Validate every raw field before corpus then target Unicode semantics. Train on the corpus byte stream including spaces; encode the separate target using learned ranks. No normalization, word splitting, inferred EOS or pretrained vocabulary is used.",
dict(requestedMerges=s["merges"], eos=s["eos"]),
dict(corpusUnits=corpus_units, corpusScalars=len(corpus["codePoints"]), utf16Units=units,
scalarCount=len(source["codePoints"]), byteBound=_bpe.BYTE_BOUND,
mergeBase=_bpe.MERGE_BASE, mergeBound=_bpe.MERGE_BOUND, EOS=_bpe.EOS))
# Scalar records were prepared during validation; keep their actual order.
trace.steps.extend(encoding_trace.steps)
tensors = []
for stem, encoded in (("Corpus", corpus), ("Source", source)):
for suffix, key, axis, provenance in (
("CodePoints", "codePoints", "Scalars", "Validated Unicode scalars in exact input order."),
("UTF16Offsets", "offsets", "Scalars", "Zero-based UTF-16 storage offset for each scalar."),
("UTF16Widths", "widths", "Scalars", "UTF-16 storage units consumed by each scalar."),
("ByteOffsets", "byteOffsets", "Scalars", "Zero-based UTF-8 byte offset for each scalar."),
("ByteWidths", "byteWidths", "Scalars", "Actual UTF-8 bytes emitted by each scalar."),
("Bytes", "bytes", "Bytes", "Manual UTF-8 encoding in source order, preserving all data."),
):
_bpe.save_tensor(tensors, f"{stem}{suffix}", axis, encoded[key], provenance)
trained = _bpe.train_bpe(corpus["bytes"], s["merges"], trace, tensors)
ids = _bpe.encode_bpe(source["bytes"], trained["rules"], s["eos"], trace, tensors)
# Corpus is NEVER EOS-trained. Both inverse paths expand real saved IDs.
corpus_decoded = _bpe.decode_bpe_ids(trained["ids"], trained["rules"], 0, "corpus", trace)
target_decoded = _bpe.decode_bpe_ids(ids, trained["rules"], s["eos"], "target", trace)
corpus_equal = int(corpus_decoded["decoded"] == s["corpus"])
equal = int(target_decoded["decoded"] == s["text"])
if not (corpus_equal and equal):
raise _bpe.NumericalFault("INVALID_INPUT", "Actual BPE reconstructions did not equal both original strings.")
trace.add("roundtrip", "Compare both actual strict reconstructions with the original strings",
"corpusEqual=(corpusDecoded===corpus); equal=(targetDecoded===text)",
"Expand real corpus and target IDs separately, concatenate real bytes, strictly reconstruct Unicode scalars, and only then compare strings. Empty content reconstructs the empty string; optional target EOS emits no bytes.",
dict(corpusOriginalUnits=corpus_units, corpusDecodedUnits=token.utf16_length(corpus_decoded["decoded"]),
corpusDecodedByteCount=len(corpus_decoded["bytes"]), originalUnits=units,
decodedUnits=token.utf16_length(target_decoded["decoded"]), decodedByteCount=len(target_decoded["bytes"])),
dict(corpusTokens=len(trained["ids"]), tokenCount=len(ids), corpusEqual=corpus_equal, equal=equal))
_bpe.save_tensor(tensors, "CorpusDecodedBytes", "Bytes", corpus_decoded["bytes"],
"Actual final corpus ID expansions passed to strict UTF-8 decoding.")
_bpe.save_tensor(tensors, "TargetDecodedBytes", "Bytes", target_decoded["bytes"],
"Actual final target ID expansions passed to strict UTF-8 decoding.")
expansions = {rule["id"]: rule["bytes"].tolist() for rule in trained["rules"]}
def expansion(identifier):
return [] if identifier == _bpe.EOS else [identifier] if identifier <= 255 else expansions[identifier]
def labels(token_ids):
return ["ID 512: EOS (explicit control), bytes []" if int(identifier) == _bpe.EOS else
f"ID {int(identifier)}, bytes {token.json_text(expansion(int(identifier)))}" for identifier in token_ids]
def expansion_labels(token_ids):
return [token.json_text(expansion(int(identifier))) for identifier in token_ids]
summary = dict(corpusBytes=len(corpus["bytes"]), byteCount=len(source["bytes"]),
actualMerges=len(trained["rules"]), tokenCount=len(ids), requestedMerges=s["merges"],
corpusTokens=len(trained["ids"]), eos=s["eos"], byteBound=_bpe.BYTE_BOUND,
vocabularyItems=256 + len(trained["rules"]) + 1, corpusEqual=corpus_equal, equal=equal)
texts = dict(corpus=s["corpus"], input=s["text"], corpusDecoded=corpus_decoded["decoded"],
decoded=target_decoded["decoded"], corpusLabels=labels(trained["ids"]),
corpusExpansions=expansion_labels(trained["ids"]), targetLabels=labels(ids),
targetExpansions=expansion_labels(ids),
ruleLabels=[f"ID {rule['id']}, bytes {token.json_text(rule['bytes'].tolist())}" for rule in trained["rules"]],
ruleExpansions=[token.json_text(rule["bytes"].tolist()) for rule in trained["rules"]],
trainingStop="Zero merges requested: no training round or pair selection occurs." if s["merges"] == 0 else
"Stopped early: fewer than two current training tokens remain." if len(trained["rules"]) < s["merges"] else
"Requested merge budget completed.")
return trace.result(summary, tensors, texts)
def source_self_check():
"""Deferred hand-literal record checks; never part of the normal CLI path."""
assert __debug__, "Run later checks with assertions enabled."
_bpe.source_self_check()
result = derive_iv39(dict(DEFAULT_IV39))
assert list(result) == ["status", "outputs", "steps", "tensors", "texts"]
assert list(result["outputs"])[:11] == ["corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges", "corpusTokens", "eos", "byteBound", "vocabularyItems", "corpusEqual", "equal"]
assert [result["outputs"][key] for key in ("corpusBytes", "byteCount", "actualMerges", "tokenCount")] == [4, 6, 2, 2]
assert len(result["steps"]) == 44 and len(result["tensors"]) == 37
assert result["texts"]["corpusDecoded"] == "abab" and result["texts"]["decoded"] == "ababab"
assert result["texts"]["targetLabels"] == ["ID 257, bytes [97,98,97,98]", "ID 256, bytes [97,98]"]
# Tensor count:12source+1initial+10round+1corpus+3rules+2expansions+
# 1targetinitial+4targetpasses+1targetfinal+2decoded=37. No program counted it.
tensor_ids = [record["id"] for record in result["tensors"]]
for merges, eos, steps in ((2, 1, 46), (3, 0, 45), (3, 1, 47), (4, 0, 45), (4, 1, 47)):
case = derive_iv39(dict(corpus="abab", text="ababab", merges=merges, eos=eos))
assert len(case["steps"]) == steps
assert [record["id"] for record in case["tensors"]] == tensor_ids
for eos in (0, 1):
empty = derive_iv39(dict(corpus="", text="", merges=0, eos=eos))
assert empty["outputs"]["tokenCount"] == eos
assert len(empty["steps"]) == 2 + 2 * eos
assert empty["texts"]["decoded"] == empty["texts"]["corpusDecoded"] == ""
for patch, code in (
(dict(corpus="\ud800", merges=float("nan")), "NONFINITE"),
(dict(corpus="a" * 25, text="\ud800"), "UNSUPPORTED_SIZE"),
(dict(corpus="\ud800", text="a" * 25), "INVALID_INPUT"),
(dict(text="🦊" * 7), "UNSUPPORTED_SIZE"),
(dict(text="🦊" * 9), "UNSUPPORTED_SIZE"),
):
bad = derive_iv39({**DEFAULT_IV39, **patch})
assert list(bad) == ["status", "code", "reason"] and bad["code"] == code
if __name__ == "__main__":
# No args: defaults; one complete JSON state: replacement; '-': stdin JSON.
_bpe._token.run(derive_iv39, DEFAULT_IV39)
7. Learned rules and strict inverse — code/python/p09/bpe_reference.py. train_bpe counts pairs, resolves the declared numeric ties and replaces disjoint occurrences. encode_bpe applies rules in rank order. decode_bpe_ids expands the actual final IDs using those rules and strips EOS only when instructed by the actual EOS stop. Read this code to distinguish appending [256,256] from freshly tokenizing abab.
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]))]))
8. Strict Unicode/UTF-8 codec — code/python/p09/token_reference.py. utf16_length, utf8_encode and utf8_decode keep UTF-16 storage units, Unicode scalars and emitted bytes distinct. Malformed scalars are rejected rather than silently normalized or replaced. Integer token/byte storage stays separate from neural features.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""Part IX: bounded integer tokenization, authored without execution.
NumPy int32 arrays store actual code points, offsets, bytes and IDs. Arithmetic
uses Python integers, so bit shifts never depend on NumPy scalar promotion.
UTF-8 is implemented below; no native codec supplies an encoded/decoded answer.
Empty streams, BOMs, noncharacters, spaces and NULs are ordinary valid data.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np
EOS = 512
BYTE_BOUND = 32
CHARACTER_BASE = 1024
IV37_DEFAULTS = MappingProxyType(dict(text="Aé🦊", eos=0))
IV38_DEFAULTS = MappingProxyType(dict(text="lower low", vocabLimit=8, eos=0))
# Fixed active-prefix dictionary: these pieces are authored, not trained.
SUBWORDS = (
(384, "low", (108, 111, 119)),
(385, "lower", (108, 111, 119, 101, 114)),
(386, "lowest", (108, 111, 119, 101, 115, 116)),
(387, "er", (101, 114)),
(388, "est", (101, 115, 116)),
(389, "ing", (105, 110, 103)),
(390, "a", (97,)),
(391, "ab", (97, 98)),
)
class NumericalFault(ValueError):
def __init__(self, code, reason):
super().__init__(reason)
self.code = code
def guarded(derive):
@wraps(derive)
def call(state):
try:
return derive(state)
except NumericalFault as error:
return dict(status="unavailable", code=error.code, reason=str(error))
return call
def integer(value, low, high, label):
"""Validate before conversion; Python bool is not a mathematical number here."""
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
try:
finite = math.isfinite(value)
except OverflowError:
finite = False
if not finite:
raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
if value < low or value > high or int(value) != value:
raise NumericalFault("INVALID_INPUT", f"{label} must be an integer from {low} to {high}.")
return int(value)
def scalar_valid(cp):
return 0 <= cp <= 0x10FFFF and not 0xD800 <= cp <= 0xDFFF
def utf16_units(cp):
"""Reconstruct the actual high/low units from a validated supplementary scalar."""
if cp <= 0xFFFF:
return [cp]
return [0xD800 + ((cp - 0x10000) >> 10), 0xDC00 + ((cp - 0x10000) & 1023)]
def utf16_length(text):
return sum(2 if ord(character) > 0xFFFF else 1 for character in text)
def text_state(state, chapter):
"""Exact raw fields and numeric domains precede ALL Unicode/size semantics."""
if type(chapter) is not int or chapter not in (37, 38):
raise NumericalFault("INVALID_INPUT", "Use token chapter 37 or 38.")
defaults = IV37_DEFAULTS if chapter == 37 else IV38_DEFAULTS
if type(state) not in (dict, MappingProxyType):
raise NumericalFault("INVALID_INPUT", "Provide a plain object with exactly the named fields.")
if set(state) != set(defaults):
raise NumericalFault("INVALID_INPUT", "Provide every own field and no extra or symbol fields.")
if type(state["text"]) is not str:
raise NumericalFault("INVALID_INPUT", "text must be an actual string, without coercion.")
result = dict(text=state["text"])
for key in defaults:
if key != "text":
if type(state[key]) not in (int, float):
raise NumericalFault("NONFINITE", f"{key} must be an actual finite number.")
result[key] = integer(state[key], 0, 8 if key == "vocabLimit" else 1, key)
return result
def int_array(values, low=0, high=0x7FFFFFFF, label="integer array", limit=BYTE_BOUND):
"""Check dense numeric storage BEFORE narrowing; integral-valued floats are legal."""
if type(values) is np.ndarray:
if values.ndim != 1 or values.dtype.kind not in "iuf":
raise NumericalFault("INVALID_INPUT", f"{label} must be a dense one-dimensional numeric array.")
elif type(values) not in (list, tuple):
raise NumericalFault("INVALID_INPUT", f"{label} must be an actual array.")
if len(values) > limit:
raise NumericalFault("UNSUPPORTED_SIZE", f"{label} exceeds {limit} entries.")
checked = []
for index, value in enumerate(values):
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
raise NumericalFault("INVALID_INPUT", f"{label}[{index}] must be an own integer from {low} to {high}.")
try:
finite = math.isfinite(value)
except OverflowError:
finite = False
if not finite or value < low or value > high or int(value) != value:
raise NumericalFault("INVALID_INPUT", f"{label}[{index}] must be an own integer from {low} to {high}.")
checked.append(int(value))
return np.array(checked, dtype=np.int32)
def utf8_encode(text, prefix="source", trace=None):
"""Scan valid scalars first; then split each into explicit UTF-8 payload groups."""
if trace is None:
trace = TokenTrace()
if type(text) is not str:
raise NumericalFault("INVALID_INPUT", "UTF-8 input must be an actual string.")
if utf16_length(text) > BYTE_BOUND:
raise NumericalFault("UNSUPPORTED_SIZE", "More than 32 UTF-16 units necessarily exceeds this 32-byte lab.")
code_points, offsets, widths = [], [], []
offset = 0
# Python strings store scalars directly; explicit surrogate values are invalid.
for character in text:
cp = ord(character)
if 0xD800 <= cp <= 0xDBFF:
raise NumericalFault("INVALID_INPUT", f"Unpaired high surrogate at UTF-16 offset {offset}.")
if 0xDC00 <= cp <= 0xDFFF:
raise NumericalFault("INVALID_INPUT", f"Unpaired low surrogate at UTF-16 offset {offset}.")
width = len(utf16_units(cp))
code_points.append(cp)
offsets.append(offset)
widths.append(width)
offset += width
byte_values, byte_offsets, byte_widths = [], [], []
for index, cp in enumerate(code_points):
if cp <= 0x7F:
expansion = [cp]
elif cp <= 0x7FF:
expansion = [0xC0 | (cp >> 6), 0x80 | (cp & 63)]
elif cp <= 0xFFFF:
expansion = [0xE0 | (cp >> 12), 0x80 | ((cp >> 6) & 63), 0x80 | (cp & 63)]
else:
expansion = [0xF0 | (cp >> 18), 0x80 | ((cp >> 12) & 63),
0x80 | ((cp >> 6) & 63), 0x80 | (cp & 63)]
units = utf16_units(cp)
inputs = dict(scalarIndex=index, utf16Offset=offsets[index], utf16Width=widths[index], codePoint=cp, unit0=units[0])
if len(units) == 2:
inputs["unit1"] = units[1]
outputs = dict(byteOffset=len(byte_values), byteWidth=len(expansion))
for j, byte in enumerate(expansion):
mask = (31 if len(expansion) == 2 else 15 if len(expansion) == 3 else 7) if j == 0 else 63
outputs[f"payload{j}"] = byte if len(expansion) == 1 else byte & mask
outputs.update({f"byte{j}": byte for j, byte in enumerate(expansion)})
trace.add(f"{prefix}_scalar_{index}", f"Encode scalar {index}: U+{cp:04X}",
"supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits",
"A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.",
inputs, outputs)
byte_offsets.append(len(byte_values))
byte_widths.append(len(expansion))
byte_values.extend(expansion)
if len(byte_values) > BYTE_BOUND:
raise NumericalFault("UNSUPPORTED_SIZE", "The actual UTF-8 encoding exceeds 32 bytes; shorten the input explicitly.")
return dict(bytes=int_array(byte_values, high=255, label="UTF-8 bytes"), codePoints=int_array(code_points),
offsets=int_array(offsets), widths=int_array(widths), byteOffsets=int_array(byte_offsets), byteWidths=int_array(byte_widths))
def utf8_decode(values, prefix="utf8", trace=None):
"""Remove prefixes, accumulate radix-64 digits, validate, then rebuild the text."""
if trace is None:
trace = TokenTrace()
values = int_array(values, high=255, label="UTF-8 bytes")
characters, offset = [], 0
while offset < len(values):
lead = int(values[offset])
width = 1 if lead <= 0x7F else 2 if 0xC2 <= lead <= 0xDF else 3 if 0xE0 <= lead <= 0xEF else 4 if 0xF0 <= lead <= 0xF4 else 0
if not width:
raise NumericalFault("INVALID_INPUT", f"Invalid UTF-8 lead at byte {offset}.")
if offset + width > len(values):
raise NumericalFault("INVALID_INPUT", f"Truncated UTF-8 sequence at byte {offset}.")
inputs = dict(scalarIndex=len(characters), byteOffset=offset, byteWidth=width)
outputs, cp = {}, 0
for j in range(width):
byte = int(values[offset + j])
if j > 0 and not 0x80 <= byte <= 0xBF:
raise NumericalFault("INVALID_INPUT", f"Invalid continuation byte at {offset + j}.")
inputs[f"byte{j}"] = byte
mask = (31 if width == 2 else 15 if width == 3 else 7) if j == 0 else 63
payload = byte if width == 1 else byte & mask
outputs[f"payload{j}"] = payload
cp = cp * 64 + payload
outputs[f"accumulator{j}"] = cp
minimum = 0 if width == 1 else 0x80 if width == 2 else 0x800 if width == 3 else 0x10000
if cp < minimum or not scalar_valid(cp):
raise NumericalFault("INVALID_INPUT", f"Overlong, surrogate or out-of-range scalar at byte {offset}.")
units = utf16_units(cp)
outputs.update(codePoint=cp, utf16Width=len(units))
outputs.update({f"unit{j}": unit for j, unit in enumerate(units)})
# chr uses the validated scalar; no source text is available to copy here.
characters.append(chr(cp))
trace.add(f"{prefix}_decode_{len(characters) - 1}", f"Decode UTF-8 scalar {len(characters) - 1}",
"accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar",
"Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.",
inputs, outputs)
offset += width
return "".join(characters)
def _flag(eos):
if type(eos) not in (int, float) or eos not in (0, 1):
raise NumericalFault("INVALID_INPUT", "eos must be numeric 0 or 1.")
def _vocabulary(limit):
try:
if type(limit) not in (int, float):
raise NumericalFault("INVALID_INPUT", "vocabLimit must be an integer from 0 to 8.")
return integer(limit, 0, 8, "vocabLimit")
except NumericalFault as error:
raise NumericalFault("INVALID_INPUT", "vocabLimit must be an integer from 0 to 8.") from error
def _strip_eos(ids, eos):
_flag(eos)
ids = int_array(ids, high=CHARACTER_BASE + 0x10FFFF, label="Token IDs", limit=BYTE_BOUND + 1)
has_tail = len(ids) > 0 and int(ids[-1]) == EOS
content = ids[:-1].copy() if has_tail else ids.copy()
if has_tail != (eos == 1) or any(int(value) == EOS for value in content):
raise NumericalFault("INVALID_INPUT", "EOS must occur exactly once at the tail when eos=1, and nowhere when eos=0.")
return ids, content
def append_eos(ids, eos, prefix, trace):
"""Return actual int32 storage with the optional reserved tail, never text matching."""
_flag(eos)
if eos == 1:
index = len(ids)
ids = np.concatenate((ids, np.array([EOS], dtype=np.int32)))
trace.add(f"{prefix}_eos", f"{prefix}: append explicit EOS", "id=512",
"Only this flag appends EOS; literal text such as <eos> remains ordinary input.",
dict(index=index, eos=eos), dict(id=EOS))
return ids
def _eos_record(ids, eos, prefix, trace):
if eos == 1:
trace.add(f"{prefix}_strip_eos", f"{prefix}: strip explicit tail EOS", "EOS emits no text bytes",
"The decoder has validated the whole ID stream and the required unique tail marker.",
dict(index=len(ids) - 1, id=EOS), dict(stripped=1))
def decode_byte_ids(ids, eos, prefix="byte", trace=None):
return _decode_pieces(ids, eos, 0, False, prefix, TokenTrace() if trace is None else trace)
def decode_subword_ids(ids, eos, limit, prefix="subword", trace=None):
limit = _vocabulary(limit)
return _decode_pieces(ids, eos, limit, True, prefix, TokenTrace() if trace is None else trace)
def _decode_pieces(ids, eos, limit, subwords, prefix, trace):
ids, content = _strip_eos(ids, eos)
active = {identifier: expansion for identifier, _, expansion in SUBWORDS[:limit]} if subwords else {}
byte_values = []
for index, stored in enumerate(content):
identifier = int(stored)
if identifier <= 255:
expansion = (identifier,)
elif identifier in active:
expansion = active[identifier]
else:
raise NumericalFault("INVALID_INPUT", f"Unknown or inactive {prefix} ID {identifier}.")
byte_offset = len(byte_values)
byte_values.extend(expansion)
if len(byte_values) > BYTE_BOUND:
raise NumericalFault("UNSUPPORTED_SIZE", "Decoded token expansions exceed 32 bytes.")
outputs = dict(byteOffset=byte_offset, byteWidth=len(expansion))
outputs.update({f"byte{j}": byte for j, byte in enumerate(expansion)})
trace.add(f"{prefix}_expand_{index}", f"{prefix}: expand ID at token {index}", "ID → declared byte expansion",
"Fallback byte IDs equal their byte value; active subword IDs expand to their full declared bytes. A single fallback byte may be only part of a Unicode scalar.",
dict(index=index, id=identifier), outputs)
_eos_record(ids, eos, prefix, trace)
values = int_array(byte_values, high=255, label="UTF-8 bytes")
return dict(bytes=values, decoded=utf8_decode(values, prefix, trace))
def decode_character_ids(ids, eos, prefix="char", trace=None):
if trace is None:
trace = TokenTrace()
ids, content = _strip_eos(ids, eos)
characters = []
for index, stored in enumerate(content):
identifier = int(stored)
cp = identifier - CHARACTER_BASE
if not scalar_valid(cp):
raise NumericalFault("INVALID_INPUT", f"Character ID {identifier} does not name a Unicode scalar.")
units = utf16_units(cp)
outputs = dict(codePoint=cp, utf16Width=len(units))
outputs.update({f"unit{j}": unit for j, unit in enumerate(units)})
characters.append(chr(cp))
trace.add(f"{prefix}_inverse_{index}", f"Character ID {index}: inverse mapping",
"codePoint=id−1024; reconstruct UTF-16 units",
"The scalar range excludes surrogate code points but includes noncharacters. The comparison vocabulary is algorithmic; no million-row matrix is allocated.",
dict(index=index, id=identifier), outputs)
_eos_record(ids, eos, prefix, trace)
decoded = "".join(characters)
# External ID streams obey the same text bound; this private trace is omitted.
utf8_encode(decoded)
return decoded
def greedy_ids(values, limit, trace):
"""Choose longest matching byte expansion, then lowest ID; no match keeps a byte."""
values = int_array(values, high=255, label="Greedy source bytes")
limit = _vocabulary(limit)
ids, offset = [], 0
while offset < len(values):
matches = []
for identifier, _, expansion in SUBWORDS[:limit]:
if offset + len(expansion) <= len(values) and all(int(values[offset + j]) == byte for j, byte in enumerate(expansion)):
matches.append((identifier, len(expansion)))
chosen, width = int(values[offset]), 1
if matches:
chosen, width = min(matches, key=lambda candidate: (-candidate[1], candidate[0]))
inputs = dict(byteOffset=offset, remaining=len(values) - offset, candidateMatches=len(matches))
for index, (identifier, match_width) in enumerate(matches):
inputs[f"candidate{index}ID"] = identifier
inputs[f"candidate{index}Width"] = match_width
trace.add(f"subword_decision_{len(ids)}", f"Choose subword at byte offset {offset}",
"choose longest matching active byte expansion; tie: lowest subword ID; no match: current byte",
"Matched candidates are listed in fixed vocabulary order. An active one-byte entry is preferred to fallback when it matches. Advance by the actual chosen byte width; spaces and unmatched Unicode bytes remain in the stream.",
inputs, dict(id=chosen, byteWidth=width, nextByteOffset=offset + width))
ids.append(chosen)
offset += width
return int_array(ids)
def json_text(value):
"""Match JSON string/array metadata without ASCII escaping or added spaces."""
return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
def byte_labels(ids):
return ["EOS (explicit control)" if int(value) == EOS else f"byte {int(value)}" for value in ids]
def byte_expansions(ids):
return [json_text([] if int(value) == EOS else [int(value)]) for value in ids]
def numbers(values):
return {key: integer(value, -0x80000000, 0x7FFFFFFF, key) for key, value in values.items()}
class TokenTrace:
def __init__(self):
self.steps = []
def add(self, identifier, label, equation, explanation, inputs, outputs):
inputs, outputs = numbers(inputs), numbers(outputs)
if len(self.steps) >= 512:
raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 operations are supported.")
self.steps.append(dict(id=identifier, label=label, equation=equation, explanation=explanation,
inputs=inputs, outputs=outputs))
def result(self, summary, tensors, texts):
# Include copied encoding steps too, after the signed first summary aliases.
outputs = numbers(summary)
for step in self.steps:
outputs.update({f"{step['id']}_{key}": value for key, value in step["outputs"].items()})
return dict(status="defined", outputs=outputs, steps=self.steps, tensors=tensors, texts=texts)
def tensor(identifier, axis, values, provenance):
"""Serialize actual nonempty int32 storage; empty streams yield no fake tensor."""
if type(values) is not np.ndarray or values.dtype != np.dtype(np.int32) or values.ndim != 1:
raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: require one-dimensional int32 storage.")
if not 1 <= len(values) <= 64:
raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: dimensions must be 1–64.")
if type(axis) is not str or not axis:
raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name the axis.")
return dict(id=identifier, shape=[len(values)], axes=[axis], dtype="int32", values=values.tolist(),
provenance=provenance, precision=0)
_JSON_INT = int
def run(derive, defaults):
"""No args: defaults; one JSON arg: full replacement; '-': JSON from stdin."""
class ParseFault(ValueError):
"""Only locally owned JSON profile/conversion faults."""
def _members(pairs):
value = {}
for key, member in pairs:
if key in value:
raise ParseFault("Duplicate JSON object members are not allowed.")
value[key] = member
return value
def _constant(token):
raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")
def _integer(token):
if token == "-0":
return -0.0
try:
return _JSON_INT(token)
except ValueError as fault:
if type(fault) is not ValueError:
raise
raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from fault
parser = argparse.ArgumentParser(description=derive.__doc__)
parser.add_argument("state", nargs="?")
args = parser.parse_args()
if args.state is not None:
source = sys.stdin.read() if args.state == "-" else args.state
try:
state = json.loads(source, object_pairs_hook=_members,
parse_constant=_constant, parse_int=_integer)
except (json.JSONDecodeError, ParseFault) as error:
result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
else:
result = derive(state)
else:
result = derive(dict(defaults))
print(json.dumps(result, allow_nan=False, separators=(",", ":")))
9. Head operations — code/python/p06/head_reference.py. project_heads computes all projection products and explicit layout changes, attend_heads retains raw scores, permissions, allowed-only normalization and value mixtures, and join_heads assembles the head with its output projection. The tiny caller supplies its actual identity projections and fixed one-head shape; the helper’s separate default is not a hidden generation configuration.
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=(",", ":")))
10. Normalization and residuals — code/python/p07/component_reference.py. feature_norm saves means, centered squares, population variance and epsilon-inside-root division. same_shape_add validates matching dimensions before residual addition. These operations are local to feature rows, so they do not introduce a future-token dependency.
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=(",", ":")))
11. Actual FFN — code/python/p07/ffn_reference.py. feed_forward computes all hidden products, biases, ReLUs and output sums in the stated order. The hand example’s third hidden zero is a genuine computed coordinate, not an omitted branch or a fourth token.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""Part VII position-wise FFN: actual NumPy storage, explicit float order.
D=2 input features -> M=3 hidden features -> D=2 output features. Parameters
are shared across tokens/batches; arithmetic never sums over token positions.
NumPy stores shaped float64 arrays, but every arithmetic operation below uses
Python floats, with finite checks and saved operands/results. No BLAS reduction,
broadcast, fused multiply-add, residual, dropout or output softmax is hidden.
Source only: this program has not been imported, executed or validated.
"""
from types import MappingProxyType
import numpy as np
from component_reference import NORM_DEFAULTS, NumericalFault, finite, tensor
FFN_PARAMETERS = MappingProxyType(dict(
f100=1, f101=0, f102=1, f110=0, f111=1, f112=-1,
fb10=0, fb11=0, fb12=0,
f200=0.5, f201=0, f210=0, f211=-0.5, f220=0.25, f221=0.25,
fb20=0, fb21=0,
))
FFN_DEFAULTS = MappingProxyType(dict(
B=NORM_DEFAULTS["B"], T=NORM_DEFAULTS["T"],
**{key: value for key, value in NORM_DEFAULTS.items() if key.startswith("x")},
**FFN_PARAMETERS,
))
def ffn_state(state):
"""Validate all 31 exact own scalar fields, including inactive X slots."""
if type(state) not in (dict, MappingProxyType):
raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
if set(state) != set(FFN_DEFAULTS):
raise NumericalFault("INVALID_INPUT", "Provide every own scalar field and no extra fields, including inactive slots.")
result = {}
for key in FFN_DEFAULTS:
value = finite(state[key], key)
low, high = (1, 2) if key == "B" else (1, 3) if key == "T" else (-4, 4)
if value < low or value > high:
raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
if key in ("B", "T") and not value.is_integer():
raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
result[key] = int(value) if key in ("B", "T") else value
return result
def feed_forward(s, input_record, trace, prefix="ffn"):
"""Return seven stage tensors and aliases; the caller owns input_record.
This reusable kernel accepts finite derived inputs beyond raw [-4,4] bounds.
It requires exact [B,T,2] dimensions/axes and finite values for all parameters.
"""
dimensions = []
for key, maximum in (("B", 2), ("T", 3)):
value = finite(s.get(key), key)
if not value.is_integer() or not 1 <= value <= maximum:
raise NumericalFault("INVALID_INPUT", f"{key} must be an integer between 1 and {maximum}.")
dimensions.append(int(value))
B, T = dimensions
parameters = {key: finite(s.get(key), key) for key in FFN_PARAMETERS}
if type(input_record) not in (dict, MappingProxyType) or input_record.get("dtype") != "float64":
raise NumericalFault("INVALID_INPUT", "FFN input must be a float64 tensor.")
checked = tensor(input_record.get("id"), input_record.get("shape"), input_record.get("axes"),
input_record.get("values"), input_record.get("provenance"))
shape, axes = [B, T, 2], ["B", "T", "D"]
if checked["shape"] != shape or checked["axes"] != axes:
raise NumericalFault("SHAPE_MISMATCH", "FFN input needs exact [B,T,2] dimensions and B,T,D axes.")
# NumPy holds real shaped storage; scalar float reads prevent reordered reductions.
X = np.array(checked["values"], dtype=np.float64).reshape(shape)
W1, b1 = np.empty((2, 3), dtype=np.float64), np.empty(3, dtype=np.float64)
W2, b2 = np.empty((3, 2), dtype=np.float64), np.empty(2, dtype=np.float64)
for d in range(2):
for m in range(3):
W1[d, m] = parameters[f"f1{d}{m}"]
for m in range(3):
b1[m] = parameters[f"fb1{m}"]
for d in range(2):
W2[m, d] = parameters[f"f2{m}{d}"]
for d in range(2):
b2[d] = parameters[f"fb2{d}"]
hidden_shape, hidden_axes = [B, T, 3], ["B", "T", "HiddenFeature"]
Z, Hidden = np.empty(hidden_shape, dtype=np.float64), np.empty(hidden_shape, dtype=np.float64)
F = np.empty(shape, dtype=np.float64)
# Save ALL hidden affines before any activation, in ascending b/t/m order.
for b in range(B):
for t in range(T):
for m in range(3):
x0, x1 = float(X[b, t, 0]), float(X[b, t, 1])
w0, w1, bias = float(W1[0, m]), float(W1[1, m]), float(b1[m])
product0 = finite(x0 * w0, "FFN hidden product0")
product1 = finite(x1 * w1, "FFN hidden product1")
summed = finite(product0 + product1, "FFN hidden sum")
preactivation = finite(summed + bias, "FFN hidden preactivation")
Z[b, t, m] = preactivation
trace.add(f"{prefix}_hidden_{b}_{t}_{m}", f"Hidden affine [{b},{t},{m}]",
"product0=x0*w0; product1=x1*w1; sum=product0+product1; preactivation=sum+bias",
"The same input-to-hidden weights and bias are reused at every token; bias is added last.",
dict(b=b, t=t, m=m, x0=x0, x1=x1, w0=w0, w1=w1, bias=bias),
dict(product0=product0, product1=product1, sum=summed, preactivation=preactivation))
for b in range(B):
for t in range(T):
for m in range(3):
preactivation = float(Z[b, t, m])
activation = finite(max(0.0, preactivation), "FFN ReLU")
Hidden[b, t, m] = activation
trace.add(f"{prefix}_relu_{b}_{t}_{m}", f"ReLU [{b},{t},{m}]",
"activation=max(0,preactivation)",
"ReLU keeps positive values and maps negative values and zero to zero; it is not a softmax.",
dict(b=b, t=t, m=m, preactivation=preactivation), dict(activation=activation))
for b in range(B):
for t in range(T):
for d in range(2):
inputs, products, running = dict(b=b, t=t, d=d), {}, {}
summed = 0.0
# Each product is immediately accumulated from zero; bias follows all three.
for m in range(3):
h, w = float(Hidden[b, t, m]), float(W2[m, d])
inputs[f"h{m}"], inputs[f"w{m}"] = h, w
product = finite(h * w, "FFN output product")
products[f"product{m}"] = product
summed = finite(summed + product, "FFN output running sum")
running[f"running{m}"] = summed
bias = float(b2[d])
inputs["bias"] = bias
value = finite(summed + bias, "FFN output")
F[b, t, d] = value
trace.add(f"{prefix}_output_{b}_{t}_{d}", f"FFN output [{b},{t},{d}]",
"product_m=h_m*w_m; running starts at 0; running_m=previous+product_m; sum=running2; value=sum+bias",
"Three hidden features are contracted in ascending order. No token sum, residual or output softmax is added.",
inputs, {**products, **running, "sum": summed, "value": value})
aliases = {}
for name, values, width in (("pre", Z, 3), ("h", Hidden, 3), ("f", F, 2)):
for b in range(B):
for t in range(T):
for coordinate in range(width):
aliases[f"{name}{b}{t}{coordinate}"] = float(values[b, t, coordinate])
tensors = [
tensor("W1", [2, 3], ["D", "HiddenFeature"], W1.reshape(-1).tolist(), "Shared row weights from two input features to three hidden features."),
tensor("b1", [3], ["HiddenFeature"], b1.tolist(), "Shared hidden-feature biases, added after the two input products."),
tensor("Z", hidden_shape, hidden_axes, Z.reshape(-1).tolist(), "Hidden affine preactivations before ReLU."),
tensor("Hidden", hidden_shape, hidden_axes, Hidden.reshape(-1).tolist(), "ReLU applied separately to each preactivation, including zero -> zero."),
tensor("W2", [3, 2], ["HiddenFeature", "D"], W2.reshape(-1).tolist(), "Shared row weights from three hidden features back to two output features."),
tensor("b2", [2], ["D"], b2.tolist(), "Shared output-feature biases, added after the three hidden products."),
tensor("F", shape, axes, F.reshape(-1).tolist(), "Position-wise FFN output; each token uses the same parameters without token mixing."),
]
return dict(output=tensors[-1], tensors=tensors, aliases=aliases)
All new loaders resolve from their own __file__; they do not depend on an unrelated current-directory helper. The reused tiny loader temporarily binds its actual component module while loading the unchanged FFN, then restores any previous binding. The guarded boundary handles the separately loaded numerical-fault families, including the tokenizer and sampler. Python records are detached JSON containers; the TypeScript snapshot additionally freezes its copies.
Seven files in this IV47 closure declare source_self_check: wrapper, generation, sampling, choice, tiny, IV39 and BPE. Only the existing IV39 check calls another file’s check, its BPE check. Thus a deliberate plan has six explicit calls plus that one nested edge, without separately invoking a duplicate BPE module’s check. Across IV46/47 together, IV46 adds one wrapper leaf: eight declaring files, seven explicit calls plus the same nested BPE check. Token/head/component/FFN declare none. No check runs on import or normal queries; declared calls are not execution results.
How to reason through the graded checks
For a current-state question, start from the actual prompt IDs rather than character count. List each executed call’s observed IDs and final row, then distinguish selected ID, logical append and later consumed input. Add the call lengths to obtain work; count draws only in sampling strategy. Apply EOS before budget before context when more than one stop condition seems possible. For a transfer question, change the stated input and derive the new branch; do not invent a call just to fill a table or assume that a final emitted token was already processed. When a question asks about probability, distinguish raw forward P at the selected class, temperature-scaled base P and final-policy P. Read the requested value for the current prefix, not a remembered default decimal.
The five actual lab questions use these mechanisms:
- What makes this an actual autoregressive generation loop? Each real call uses the currently observed ID prefix; only its final row chooses one emitted ID. Append it, check stopping and continue only when allowed. Tokenize the prompt once, preserve IDs and absolute positions, and leave the last emission pending. No prewritten output string or mandatory extra call supplies the mechanism.
- Which counts match the actual call lengths, generated IDs and consumed-generated flags? One call emits one ID. Sum
CallLengthsforworkTokens; readConsumedGeneratedfor which earlier emissions entered later calls. Reset has two calls/emissions, work3 and one newly consumed ID. Final pending output and old-prefix recomputation explain why these are different counts; they do not imply an invisible cache or measured latency. - Which interpretation of the selected probabilities is valid? Sampling’s raw model P comes from the actual unscaled last row at the selected class, separately from that class’s temperature-base and final-policy P. Borrowing a different greedy winner’s probability is wrong. The greedy branch instead preserves its real model P, leaves the seed unchanged and creates no sampled probability or RNG evidence. A deterministic or one-candidate choice does not overwrite model P with1.
- Which stopping interpretation matches the current reason and pending ID? In the EOS branch, the marker remains logical output but decoding strips it and no later call gathers it. In the context branch, an emitted logical fourth ID remains pending because processing four observed inputs is forbidden. In the budget branch, budget stops before a possible context reason, while EOS would have won first. No branch secretly crops, resets positions or invents a pending row’s Y/logits/P.
- With text=ab, merges2, greedy, maxNew2, every U=0, b3=4 and every other bias−4, which result preserves token boundaries? The prompt is
[256]. Readout ignores Y because U=0, so actual class3/public256 has score4 and every other active class score−4 at every call. Greedy therefore emits256 twice: calls process[256]then[256,256], and retained result[256,256,256]decodes toababab. The final256 remains pending, zero draws are consumed, and no retokenization merges the existing IDs into257 or converts repetition into EOS.
Recap and bridge
- Each choice belongs to the actual final computed row conditional on its observed prefix.
- Reset calls on a and aa emit aa and reconstruct aaa, using two draws and three work rows.
- Only the first generated a is consumed by a later call; the last emission remains pending.
- EOS precedes budget, which precedes context; a logical fourth ID does not imply a T=4 call.
- This loop recomputes full prefixes with zero cache entries and allows repetitions.
Part XII introduces reusable keys and values and asks when a cached calculation agrees with this explicit uncached reference.