The neural notebook
← All chapters

IV-46 / Part XI · Autoregressive Inference

Temperature, Top-k and Nucleus Sampling

Follow temperature, score ranking, top-k and nucleus renormalization, then use an exact recorded seed draw to select a public token ID from the final distribution.

Review the ideas this chapter uses

A model can assign several possible next tokens positive probability. Always taking the largest score gives one kind of continuation; drawing from a distribution gives another. To understand that draw, we need to see which tokens remain eligible, how their probabilities change, and exactly where the random number lands.

Learning objective: Apply temperature and filtering in a declared order.

Compute it yourself

Temperature, Top-k and Nucleus Sampling

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

Complete results from this trace’s starting inputs

Starting inputs for these results
V
3
z0
1
z1
0
z2
0
z3
0
z4
0
temperature
1
topK
3
topP
1
seed
0
sampledID97
sampledProbability0.5761168847658291
candidateCount3
nextSeed1013904223

sampledID 97. sampledProbability 0.5761168847658291. candidateCount 3. nextSeed 1013904223. Validate all ten raw fields before sampling. Inactive logits validate too. The only RNG is the explicitly recorded Book III LCG; base greedy metadata is not the sampled choice.. classCount 3. rawLogitCount 5

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.

Inputs

V
3
z0
1
z1
0
z2
0
z3
0
z4
0
temperature
1
topK
3
topP
1
seed
0

Outputs

classCount
3
rawLogitCount
5

Three distributions, two orders, one recorded draw

Sampled a (ID97), compact class0, final policy probability 0.5761168847658291. 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.

All five validated raw slots, including inactive values: [1,0,0,0,0]. Only the active 3 entries enter the distribution.

Compact classes through all three distributions — actual saved values, without display rounding
Compact / public IDActual input logitScaled logitFull base PTop-k keep?Top-k PNucleus keep?Final policy PSelected?
0 / a ID97110.5761168847658291Yes0.5761168847658291Yes0.5761168847658291Yes
1 / b ID98000.21194155761708544Yes0.21194155761708544Yes0.21194155761708544No
2 / EOS ID512000.21194155761708544Yes0.21194155761708544Yes0.21194155761708544No

Selected class0: actual shift=0, exp(shift)=1, denominator=1.7357588823428847, logS=0.5514447139320511, LSE=1.551444713932051. BaseP, TopKP and FinalP describe different stages. Removed entries are exact zeros; no epsilon is added.

Score rank and actual nucleus visits — actual saved values, without display rounding
Score rankCompact / public IDComputed scaled scoreBase PTop-k running massNucleus beforeNucleus cumulativeCrossed threshold?Continue visit?
00 / ID9710.57611688476582910.576116884765829100.576116884765829101
11 / ID9800.211941557617085440.78805844238291460.57611688476582910.788058442382914601
22 / ID51200.2119415576170854410.7880584423829146110

Top-k mass=1, 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.5761168847658291,0.7880584423829146,1]. These sums use computed values; printed decimals never feed arithmetic.

Ascending public-ID CDF and exact selection predicates — actual saved values, without display rounding
CDF entryCompact / public IDFinal PBeforeActual cumulativePositive P?u < cumulative?First eligible take?
00 / ID970.576116884765829100.5761168847658291111
11 / ID980.211941557617085440.57611688476582910.7880584423829146110
22 / ID5120.211941557617085440.78805844238291461110

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
Complete sampler operations — actual saved values, without display rounding
Operation and equationExplanationActual inputsActual outputs
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=1
logit1=0
logit2=0
scaled0=1
scaled1=0
scaled2=0
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=1
z1=0
z2=0
max=1
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=1
max=1
shifted=0
term=1
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
max=1
shifted=-1
term=0.36787944117144233
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=1
shifted=-1
term=0.36787944117144233
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.36787944117144233
term2=0.36787944117144233
max=1
running0=1
running1=1.3678794411714423
running2=1.7357588823428847
denominator=1.7357588823428847
logS=0.5514447139320511
lse=1.551444713932051
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.7357588823428847
probability=0.5761168847658291
sample_base_probability_1

probability=term/S

This stored binary64 probability is displayed without feeding its formatting back into arithmetic.
c=1
term=0.36787944117144233
denominator=1.7357588823428847
probability=0.21194155761708544
sample_base_probability_2

probability=term/S

This stored binary64 probability is displayed without feeding its formatting back into arithmetic.
c=2
term=0.36787944117144233
denominator=1.7357588823428847
probability=0.21194155761708544
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=1
z1=0
z2=0
nextRow=0
nextID=97
nextProbability=0.5761168847658291
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=1
publicID0=97
scaled1=0
publicID1=98
scaled2=0
publicID2=512
compact0=0
publicID0=97
score0=1
compact1=1
publicID1=98
score1=0
compact2=2
publicID2=512
score2=0
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.5761168847658291
before0=0
compact1=1
publicID1=98
baseP1=0.21194155761708544
before1=0.5761168847658291
compact2=2
publicID2=512
baseP2=0.21194155761708544
before2=0.7880584423829146
keep0=1
running0=0.5761168847658291
keep1=1
running1=0.7880584423829146
keep2=1
running2=1
mass=1
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=1
baseP0=0.5761168847658291
keep0=1
baseP1=0.21194155761708544
keep1=1
baseP2=0.21194155761708544
keep2=1
topKP0=0.5761168847658291
topKP1=0.21194155761708544
topKP2=0.21194155761708544
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.5761168847658291
before0=0
compact1=1
publicID1=98
topKP1=0.21194155761708544
before1=0.5761168847658291
compact2=2
publicID2=512
topKP2=0.21194155761708544
before2=0.7880584423829146
running0=0.5761168847658291
keep0=1
crossed0=0
continue0=1
running1=0.7880584423829146
keep1=1
crossed1=0
continue1=1
running2=1
keep2=1
crossed2=1
continue2=0
candidateCount=3
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.5761168847658291
before0=0
compact1=1
topKP1=0.21194155761708544
before1=0.5761168847658291
compact2=2
topKP2=0.21194155761708544
before2=0.7880584423829146
running0=0.5761168847658291
running1=0.7880584423829146
running2=1
mass=1
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.5761168847658291
keep0=1
topKP1=0.21194155761708544
keep1=1
topKP2=0.21194155761708544
keep2=1
finalP0=0.5761168847658291
finalP1=0.21194155761708544
finalP2=0.21194155761708544
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.5761168847658291
before0=0
compact1=1
publicID1=98
probability1=0.21194155761708544
before1=0.5761168847658291
compact2=2
publicID2=512
probability2=0.21194155761708544
before2=0.7880584423829146
running0=0.5761168847658291
positive0=1
running1=0.7880584423829146
positive1=1
running2=1
positive2=1
positiveCount=3
lastPositive=2
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
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.5761168847658291
cumulative0=0.5761168847658291
compact1=1
probability1=0.21194155761708544
cumulative1=0.7880584423829146
compact2=2
probability2=0.21194155761708544
cumulative2=1
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.5761168847658291
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 tensor shapes and full precision

All computed outputs

sampledID
97
sampledProbability
0.5761168847658291
candidateCount
3
nextSeed
1013904223
classCount
3
sampledRow
0
selectedCDFIndex
0
positiveCount
3
fallback
0
drawCount
1
initialSeed
0
uniform
0.23606797284446657
temperature
1
topK
3
topP
1
baseGreedyRow
0
baseGreedyID
97
baseGreedyProbability
0.5761168847658291
max
1
denominator
1.7357588823428847
logS
0.5514447139320511
logsumexp
1.551444713932051
topKMass
1
finalMass
1
cdfTotal
1
rawLogitCount
5
setup_classCount
3
setup_rawLogitCount
5
sample_scale_scaled0
1
sample_scale_scaled1
0
sample_scale_scaled2
0
sample_base_max_max
1
sample_base_exp_0_shifted
0
sample_base_exp_0_term
1
sample_base_exp_1_shifted
-1
sample_base_exp_1_term
0.36787944117144233
sample_base_exp_2_shifted
-1
sample_base_exp_2_term
0.36787944117144233
sample_base_normalize_running0
1
sample_base_normalize_running1
1.3678794411714423
sample_base_normalize_running2
1.7357588823428847
sample_base_normalize_denominator
1.7357588823428847
sample_base_normalize_logS
0.5514447139320511
sample_base_normalize_lse
1.551444713932051
sample_base_probability_0_probability
0.5761168847658291
sample_base_probability_1_probability
0.21194155761708544
sample_base_probability_2_probability
0.21194155761708544
sample_base_argmax_nextRow
0
sample_base_argmax_nextID
97
sample_base_argmax_nextProbability
0.5761168847658291
sample_rank_compact0
0
sample_rank_publicID0
97
sample_rank_score0
1
sample_rank_compact1
1
sample_rank_publicID1
98
sample_rank_score1
0
sample_rank_compact2
2
sample_rank_publicID2
512
sample_rank_score2
0
sample_topk_mass_keep0
1
sample_topk_mass_running0
0.5761168847658291
sample_topk_mass_keep1
1
sample_topk_mass_running1
0.7880584423829146
sample_topk_mass_keep2
1
sample_topk_mass_running2
1
sample_topk_mass_mass
1
sample_topk_normalize_topKP0
0.5761168847658291
sample_topk_normalize_topKP1
0.21194155761708544
sample_topk_normalize_topKP2
0.21194155761708544
sample_nucleus_running0
0.5761168847658291
sample_nucleus_keep0
1
sample_nucleus_crossed0
0
sample_nucleus_continue0
1
sample_nucleus_running1
0.7880584423829146
sample_nucleus_keep1
1
sample_nucleus_crossed1
0
sample_nucleus_continue1
1
sample_nucleus_running2
1
sample_nucleus_keep2
1
sample_nucleus_crossed2
1
sample_nucleus_continue2
0
sample_nucleus_candidateCount
3
sample_final_mass_running0
0.5761168847658291
sample_final_mass_running1
0.7880584423829146
sample_final_mass_running2
1
sample_final_mass_mass
1
sample_final_normalize_finalP0
0.5761168847658291
sample_final_normalize_finalP1
0.21194155761708544
sample_final_normalize_finalP2
0.21194155761708544
sample_cdf_running0
0.5761168847658291
sample_cdf_positive0
1
sample_cdf_running1
0.7880584423829146
sample_cdf_positive1
1
sample_cdf_running2
1
sample_cdf_positive2
1
sample_cdf_positiveCount
3
sample_cdf_lastPositive
2
sample_rng_signedProduct
0
sample_rng_sum
1013904223
sample_rng_nextSeed
1013904223
sample_rng_uniform
0.23606797284446657
sample_rng_drawCount
1
sample_select_positive0
1
sample_select_below0
1
sample_select_take0
1
sample_select_positive1
1
sample_select_below1
1
sample_select_take1
0
sample_select_positive2
1
sample_select_below2
1
sample_select_take2
0
sample_select_fallback
0
sample_select_selectedCDFIndex
0
sample_select_sampledRow
0
sample_select_sampledID
97
sample_select_sampledProbability
0.5761168847658291
sample_select_candidateCount
3
finish_sampledID
97
finish_sampledProbability
0.5761168847658291
finish_candidateCount
3
finish_nextSeed
1013904223

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

RawZ

ModelRow=5 · float64 · display precision 8 · All five validated editable raw logits, including inactive slots.

Storage indexValue
01
10
20
30
40

InputLogits

Class=3 · float64 · display precision 8 · Validated actual sampler logits; derived logits are not clipped.

Storage indexValue
01
10
20

ScaledLogits

Class=3 · float64 · display precision 8 · Actual InputLogits/temperature in compact order.

Storage indexValue
01
10
20

BaseClassIDs

Class=3 · int32 · display precision 0 · 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.

Storage indexValue
097
198
2512

BaseZ

Class=3 · float64 · display precision 8 · Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Actual finite computed input logits; no derived-input clipping.

Storage indexValue
01
10
20

BaseShifted

Class=3 · float64 · display precision 8 · Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Z minus the saved active maximum.

Storage indexValue
00
1-1
2-1

BaseTerms

Class=3 · float64 · display precision 8 · Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Actual exp(Shifted), before normalization.

Storage indexValue
01
10.36787944117144233
20.36787944117144233

BaseDenominator

Scalar=1 · float64 · display precision 8 · Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Actual left-to-right sum of active shifted terms.

Storage indexValue
01.7357588823428847

BaseLogS

Scalar=1 · float64 · display precision 8 · Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Natural logarithm of Denominator.

Storage indexValue
00.5514447139320511

BaseLSE

Scalar=1 · float64 · display precision 8 · Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Saved max+LogS in binary64.

Storage indexValue
01.551444713932051

BaseP

Class=3 · float64 · display precision 8 · Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Terms/Denominator for active classes only, without clipping or padding.

Storage indexValue
00.5761168847658291
10.21194155761708544
20.21194155761708544

BaseNextRow

Decision=1 · int32 · display precision 0 · Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Lowest compact index among highest computed logits.

Storage indexValue
00

BaseNextID

Decision=1 · int32 · display precision 0 · Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Public class ID gathered at NextRow.

Storage indexValue
097

BaseNextProbability

Decision=1 · float64 · display precision 8 · Full scaled-logit base distribution; its Next metadata is greedy, not sampled. Stored P gathered at the computed-logit winner.

Storage indexValue
00.5761168847658291

RankCompact

Rank=3 · int32 · display precision 0 · Descending computed ScaledLogits; exact ties ascend public ID.

Storage indexValue
00
11
22

RankIDs

Rank=3 · int32 · display precision 0 · Public IDs gathered at RankCompact.

Storage indexValue
097
198
2512

TopKMask

Class=3 · int32 · display precision 0 · Complete active compact mask; first topK ranks are1.

Storage indexValue
01
11
21

TopKRunning

TopKRank=3 · float64 · display precision 8 · Actual baseP rank-order running sums from zero.

Storage indexValue
00.5761168847658291
10.7880584423829146
21

TopKMass

Scalar=1 · float64 · display precision 8 · Last actual TopKRunning value, required positive.

Storage indexValue
01

TopKP

Class=3 · float64 · display precision 8 · Kept BaseP/TopKMass; removed compact classes exact0.

Storage indexValue
00.5761168847658291
10.21194155761708544
20.21194155761708544

NucleusCompact

NucleusRank=3 · int32 · display precision 0 · Actual visited top-k rank prefix, including first crossing; topP1 visits all.

Storage indexValue
00
11
22

NucleusIDs

NucleusRank=3 · int32 · display precision 0 · Public IDs at actual visited nucleus ranks.

Storage indexValue
097
198
2512

NucleusBefore

NucleusRank=3 · float64 · display precision 8 · Actual cumulative operand before each visited TopKP addition.

Storage indexValue
00
10.5761168847658291
20.7880584423829146

NucleusRunning

NucleusRank=3 · float64 · display precision 8 · Actual cumulative TopKP in visited rank order.

Storage indexValue
00.5761168847658291
10.7880584423829146
21

NucleusCrossed

NucleusRank=3 · int32 · display precision 0 · Exact saved cumulative>=topP predicate for each visit.

Storage indexValue
00
10
21

NucleusContinue

NucleusRank=3 · int32 · display precision 0 · Actual next-visit decision, including topP===1 special policy.

Storage indexValue
01
11
20

FinalMask

Class=3 · int32 · display precision 0 · Complete active compact mask of actually visited nucleus entries.

Storage indexValue
01
11
21

FinalRunning

NucleusRank=3 · float64 · display precision 8 · Second actual kept TopKP mass accumulation in rank order, from zero.

Storage indexValue
00.5761168847658291
10.7880584423829146
21

FinalMass

Scalar=1 · float64 · display precision 8 · Last actual FinalRunning value, required positive.

Storage indexValue
01

FinalP

Class=3 · float64 · display precision 8 · Actual kept TopKP/FinalMass; all removed entries exact0.

Storage indexValue
00.5761168847658291
10.21194155761708544
20.21194155761708544

CDFCompact

CDFEntry=3 · int32 · display precision 0 · Retained compact indices sorted separately by ascending public ID.

Storage indexValue
00
11
22

CDFIDs

CDFEntry=3 · int32 · display precision 0 · Ascending public IDs, including retained zero-probability entries.

Storage indexValue
097
198
2512

CDFBefore

CDFEntry=3 · float64 · display precision 8 · Actual final-P cumulative operand before each public-order addition.

Storage indexValue
00
10.5761168847658291
20.7880584423829146

CDFRunning

CDFEntry=3 · float64 · display precision 8 · Actual public-order cumulative sum; last entry is not forced to1.

Storage indexValue
00.5761168847658291
10.7880584423829146
21

RNGState

StateEndpoint=2 · float64 · display precision 0 · Initial and next unsigned uint32 states stored exactly in float64, without int32 conversion.

Storage indexValue
00
11013904223

RNGArithmetic

IntegerOperand=3 · float64 · display precision 0 · Actual signed imul low32 product, increment and exact integer-valued sum in float64.

Storage indexValue
00
11013904223
21013904223

Uniform

Draw=1 · float64 · display precision 8 · Exact dyadic nextSeed/2^32, in [0,1); exactly one draw.

Storage indexValue
00.23606797284446657

SampledRow

Decision=1 · int32 · display precision 0 · Compact class selected from the actual final CDF and draw.

Storage indexValue
00

SampledID

Decision=1 · int32 · display precision 0 · Public ID at SampledRow; distinct from BaseNextID greedy metadata.

Storage indexValue
097

SampledProbability

Decision=1 · float64 · display precision 8 · Stored FinalP gathered at SampledRow, never the base greedy probability.

Storage indexValue
00.5761168847658291

Change a raw score, temperature, top-k, top-p or seed to recompute the real policy. Reset favors a97 from logits[1,0,0]. A one-candidate filter still advances the LCG once; its final probability1 differs from the original full-distribution probability. All five raw logits validate, including inactive slots. Top-k must not exceed active V.

Try V5, z2=z3=1, other logits0 and topK1 to see public256 beat512 in filtering. Try topP1 with z0=40, other active logits−40 and temperature.25: tiny positive raw-bound tails are retained. Inspect the actual saved values; library rounding can change boundary decisions across platforms. Input edits, reset and trace navigation clear answers; the class inspector only reads evidence.

Check your understanding

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

1. Which sequence defines this sampling policy, and what does temperature change?
2. The current record has V=3, topK=3, candidateCount=3. Which storage and normalization statement matches it?
3. Saved seed=0, nextSeed=1013904223, u=0.23606797284446657; retained public-ID CDF order=[97,98,512], cumulative=[0.5761168847658291,0.7880584423829146,1]. Which result and draw policy agree with this actual record?
4. Current computed scaled scores=[1,0,0]; ranked public IDs=[97,98,512]. At least one exact score tie is present. What order and selected-probability meaning does the record use?
5. Use V3 logits[0,0,-1], temperature1, topK2, topP1 and seed2782269413. The exact LCG draw is u=.5, finalP=[.5,.5,0], retained CDF=[.5,1]. Which ID is selected?

At reset the active scores are (1,0,0) for a, b and EOS. Temperature is1, top-k is3, top-p is1 and the seed is0. The exact real distribution is (e,1,1)/(e+2), where e=exp(1). Both filters retain all three tokens, and the first recorded uniform draw selects a/97. Being selected does not change a’s probability to1.

Change one raw score, temperature, top-k, top-p or seed, then follow the newly derived distribution and draw. Active compact sampling class to inspect reads a saved class without changing the graded answers. Calculation step selects a trace operation independently; its matching operation row is marked when present. Raw edits, Reset example and trace navigation clear grades. The live questions use the actual current record, including its retained maps and exact predicates, rather than whichever class you inspect.

Review IV-45 — From Logits to the Next Token for stable softmax and greedy selection. Book II’s VIII.10 — Reproducibility, random seeds, and nondeterminism explains reproducible random streams; VII.6 — Logits and softmax develops the probability normalization. Book III’s III-16 — Multiclass Classification and Softmax Regression connects logits to multiclass probabilities, and III-39 — Reproducibility and Numerical Reliability distinguishes numerical reliability from a reproducibility claim. Here the scores are editable direct inputs, not measurements or outputs of a trained model.

Give the arrays names before filtering

A token is an output piece named by a public integer ID. A logit is its real score before normalization. A class is one possible output item; a compact index is its address in the small array. The public ID’s size does not determine that address.

Public token names and compact storage addresses
Compact index cPublic IDPieceActive vocabulary
097aV=3,4,5
198bV=3,4,5
2512EOS, end of sequenceV=3,4,5
3256abV=4,5
4257ababV=5

V is the active class count, an integer3..5. Raw scores z0 through z4 form five stored entries; only the first V enter this distribution. All five still validate. Inactive classes have no active probability entry. By contrast, a class removed by a filter is still an active class with an exact zero in the filtered array.

A tensor is an array with named dimensions. Raw scores have shape [5]; active logits and each full probability or keep-mask vector have shape [V], one entry per Class. A keep-mask answers yes/no for every active class. A ranked list gives the compact address and public ID at each Rank, so ranking never silently renames the class axis. The CDF has its own sampling order, explained below. IDs and indices are integers; probabilities and scores use binary64 floating-point numbers. Formatting their digits is separate from calculation.

Temperature changes relative weights

Temperature, written τ (tau), is a positive divisor applied to every active logit:

sc=zc/τ.s_c=z_c/\tau.

Here c visits compact classes0 through V−1, z is the raw logit vector and s is the scaled vector. This chapter accepts τ in [1/4,4]. Smaller positive τ enlarges score differences; larger τ reduces them. It changes a decision distribution without changing any model weights. Temperature0 is rejected: it is not a request to divide by zero or secretly switch to greedy mode.

Stable softmax first finds the maximum m of the computed s values, then forms shifted values d, exponential weights w and a running sum S:

m=max⁡csc,dc=sc−m,wc=exp⁡(dc),S0=0,Sc+1=Sc+wc,Pc=wc/SV.m=\max_c s_c,\quad d_c=s_c-m,\quad w_c=\exp(d_c), \quad S_0=0,\quad S_{c+1}=S_c+w_c,\quad P_c=w_c/S_V.

The exponential exp(x)=eˣ is positive in exact real arithmetic. The denominator is accumulated in compact order, starting at0. Subtracting the same m from all scores cancels a common exponential factor, so it preserves the real distribution while avoiding unnecessarily large exponentials. At least one shifted value is0 and has weight1. The saved log-sum-exp is m+ln(S_V), where ln is the natural logarithm; it is normalization evidence, not a sampled ID.

P is the base distribution, before filtering. For two classes i,j, real probabilities satisfy P_i/P_j=exp((z_i−z_j)/τ). This explains temperature through an actual ratio rather than a promise about better text. Positive scaling preserves order in real arithmetic. Computed division can collapse a tiny difference: the smallest positive binary64 input divided by4 can round to0. The filter therefore ranks its actual computed s values.

Top-k, then top-p, with two real renormalizations

A rank orders candidates by decreasing computed scaled logit, breaking an exact score tie by increasing public ID. Do not sort printed probabilities, rounded labels or compact addresses. This rule deliberately differs from IV-45’s greedy rule, which retains the lowest compact index on a computed-logit tie.

Write r₀,r₁,… for the compact indices in ranked order. Integer top-k, k, keeps the first k ranked entries, where 1≤k≤V. It is a count, not a probability or a percentage. Add the stored base probabilities of those entries in rank order, starting at0, to obtain positive mass Mₖ. Divide each retained base probability by that mass:

Mk=∑j=0k−1Prj,Qc={Pc/Mkc retained by top-k,0otherwise.M_k=\sum_{j=0}^{k-1}P_{r_j},\qquad Q_c=\begin{cases}P_c/M_k&c\text{ retained by top-k},\\0&\text{otherwise}.\end{cases}

Q is the top-k distribution. The sum sign means the ordered additions just described; it does not authorize a library to reorder them. Renormalizing makes the retained probabilities relative to the smaller set. Simply zeroing removed entries would generally leave total mass below1.

Nucleus sampling, also called top-p, keeps a short leading portion of this same ranked top-k list. Its threshold p is a probability in (0,1]. Starting at0, accumulate Q in rank order and retain entries through the first one whose cumulative value is at least p, including that crossing token. Here p is a control, distinct from the vector P. If no earlier entry crosses, the retained list runs to its end. For p=1 the declared rule retains every top-k entry, even if rounded additions reach1 early. No smaller prefix is substituted.

Let N be the resulting retained set and Mₚ its mass, obtained by adding the retained Q entries in rank order. The final distribution R is

Mp=∑c∈Nrank orderQc,Rc={Qc/Mpc∈N,0c∉N.M_p=\sum_{c\in N}^{\text{rank order}}Q_c,\qquad R_c=\begin{cases}Q_c/M_p&c\in N,\\0&c\notin N.\end{cases}

The positive-support requirement is essential: there must be a retained entry with positive stored probability, and each normalizer must be positive. No epsilon, replacement distribution or invented token repairs an invalid set. The first ranked positive item is retained for a positive p. Some retained helper entries may have probability0 after genuine underflow; retained count and positive-support count need not mean the same thing.

Top-p is applied after top-k renormalization. For example, at reset choose k=2 and p=3/4. The retained base mass is (e+1)/(e+2), Q is (e/(e+1),1/(e+1),0), and its first cumulative value is below3/4 because e<3. The second entry crosses, so both remain. Applying p to the unrenormalized original probabilities would be a different algorithm.

The order can also change the actual retained set. With the same k=2 but p=2/3, e>2 gives e/(e+1)>2/3, so the renormalized first entry alone crosses. The original base e/(e+2) is below2/3 because e<4. Applying that threshold before top-k renormalization would therefore retain an extra token. These inequalities use exact real expressions, separate from each saved rounded calculation.

Work every filter stage of the default by hand

These are exact real expressions. The software saves each actual rounded division, exponential and addition; it does not replace those operations with this algebra.

At V=3, z=(1,0,0), τ=1, k=3, p=1, scaled logits are (1,0,0), maximum1, shifts (0,−1,−1) and weights (1,1/e,1/e). Define Z=e+2. The compact denominator is ((0+1)+1/e)+1/e=Z/e; base P is (e/Z,1/Z,1/Z).

The rank order is a, b, EOS: score1 first, then the score0 tie resolved by IDs98 before512. All three survive top-k. The complete intermediate arithmetic is:

Every default retained-mass and cumulative step, in exact real expressions
Rank; compact/publicBase PTop-k running massQ after full mass divisionTop-p running QKept at p=1; final R
0; 0/97e/Ze/Ze/Ze/Zyes; e/Z
1; 1/981/Z(e+1)/Z1/Z(e+1)/Zyes; 1/Z
2; 2/5121/Z(e+2)/Z=11/Z(e+2)/Z=1yes; 1/Z

The final kept-Q mass runs through e/Z, (e+1)/Z,1 again, so its real final value is1. Every final division still occurs. Software is not permitted to assume that the stored masses equal1 exactly or omit those operands. With k=1 instead, Mₖ=e/Z, Q=(1,0,0), Mₚ=1 and R=(1,0,0). Sampling still consumes one draw in that one-candidate case.

A CDF turns one uniform number into one ID

The recorded uniform draw u lies on the finite grid {0,1/2³²,…,(2³²−1)/2³²} in [0,1): it may be0 and cannot be1. This pseudorandom stream is deterministic from its seed; it is not a sequence of independent continuous random variables. A cumulative distribution function, or CDF, adds final probabilities in a declared order. Here that order is ascending public ID among retained entries, separate from score rank. Start C₀=0, add the actual saved R of each retained item, and select the first positive-probability entry with u < cumulative.

This assigns half-open intervals: an entry occupies [previous cumulative, new cumulative). Equality with its upper boundary belongs to the following interval. A retained zero has no interval width and cannot be selected. If finite summation leaves the final cumulative at or below u despite u<1, the policy selects the last positive entry and records the fallback; it does not silently change the last CDF value to1.

The last-positive rule is a defensive policy with an actual recorded flag. This chapter establishes no reachable positive-fallback fixture in the current V≤5, uint32-LCG domain. Inventing u=1 would violate the input stream, and forcing the last cumulative to1 would erase the arithmetic being taught.

For reset, score rank and public order happen to coincide. The intervals are a: [0,e/Z), b: [e/Z,(e+1)/Z), EOS: [(e+1)/Z,1). An exact reachable boundary example uses V=3, raw logits (0,0,−1), temperature1, k=2, p=1 and seed2782269413. The retained a/b base probabilities are the same stored positive number x. The ordered mass is x+x=2x exactly here, so both normalized values are exactly1/2; final mass1 leaves finalP=(1/2,1/2,0). The retained-entry CDF is [1/2,1], with no removed EOS candidate. This seed produces next state2147483648 and u=1/2, as derived below. The first entry fails u<1/2, the second passes u<1, so b/98 is selected. This is a manual exact-arithmetic anchor, not an executed fixture.

Reconstruct the seed arithmetic, without an opaque RNG

A seed is the integer starting state of a deterministic stream. The Book III linear congruential generator, abbreviated LCG, uses one update per sampling decision:

snext=(1664525sseed+1013904223) mod 4294967296,u=snext/4294967296.s_{\mathrm{next}}=(1664525s_{\mathrm{seed}}+1013904223)\bmod 4294967296, \qquad u=s_{\mathrm{next}}/4294967296.

Here s_seed is the RNG state, distinct from the scaled logits s; the word modulo means retain the nonnegative remainder after division. Its modulus is2³². The resulting u is a dyadic fraction, an integer divided by a power of2, represented exactly in binary64. This is a teaching generator, not a cryptographic source or NumPy-PCG equivalent. A finite grid and a deterministic recurrence do not imply that repeated runs have exact empirical frequencies equal to the categorical probabilities, or that successive draws are independent.

With seed0, the product is0, addition gives1013904223, and the remainder is1013904223. Thus u=1013904223/4294967296. Multiplying the numerator by3 gives3041712669, strictly less than4294967296; hence u<1/3. Since e>1, e/(e+2)>1/3. Therefore the first interval selects ID97, with final selection probability e/(e+2), candidate count3 and next seed1013904223.

TypeScript’s Math.imul retains the low32 product as a signed integer, then addition and >>>0 give the unsigned state. Python integer modulo gives the same unsigned transition. At maximal seed4294967295, the signed low product is−1664525; adding1013904223 gives1012239698, already unsigned. An unsigned state can exceed signed-int32 limits, so RNG-state evidence uses exactly integer-valued float64, not a wrapped signed-int32 token tensor. All integers through2³²−1 are exactly representable there. The stream is explicit evidence, not Math.random().

The boundary seed can also be established with integer arithmetic. With modulus M=4294967296 and multiplier a=1664525, 7306M=31379031064576 and 18851643a=31379031064575; their difference is1. Thus −18851643, or its unsigned representative4276115653, is the inverse multiplier modulo M. Direct multiplication gives 1664525·634785765+1013904223=1056617789390848=246013M, so seed634785765 produces next0 and u0. Adding M/2 to that seed gives2782269413; because the multiplier is odd, its next state shifts by M/2 to2147483648, producing u=1/2 exactly. Both this input seed and its next state exceed signed-int32 limits. This proof concerns exact integers and does not establish an RNG program result.

Two counterexamples to casual sorting

With V=5, z2=z3=1 and the other scores0, the top score is shared by EOS512 and ab256. Filtering ranks ab256 first, so k=1 samples ab. IV-45 greedy instead selects EOS512, because compact2 precedes compact3. Equal scores do not make these policies interchangeable.

With V=5 and all scores0, base P=(1/5,1/5,1/5,1/5,1/5). For k=3, the public-ID tie order retains97,98,256: compact indices0,1,3. The base retained mass runs1/5,2/5,3/5; Q in compact storage is (1/3,1/3,0,1/3,0). At p=1 all three remain. A compact-prefix implementation retaining0,1,2 would incorrectly include EOS512. Reading the maps prevents that mistake.

Follow the saved numerical record

The first four summaries are sampledID, sampledProbability, candidateCount and nextSeed. At reset their exact-real or integer hand values are97, e/(e+2),3 and1013904223. This is a numeric record with status,outputs,steps,tensors; it does not invent a text result. baseGreedyID and baseGreedyProbability describe the scaled-base helper’s greedy winner, separately from the final sampled ID and FinalP.

Follow sample_scale, the real sample_base_* operations, sample_rank, sample_topk_mass, sample_topk_normalize, sample_nucleus, sample_final_mass, sample_final_normalize, sample_cdf, sample_rng and sample_select. Each stage retains its actual operands, running values and decisions. setup and finish surround them. A single stage may save several coordinate calculations; it is not permission to discard their evidence.

In the tensor inspector, InputLogits and ScaledLogits have one value per active Class. BaseP, TopKP and FinalP show the three distributions in compact order. RankCompact and RankIDs map score rank; TopKRunning and TopKMass show its retained base mass. NucleusBefore, NucleusRunning, NucleusCrossed and NucleusContinue show every actual visit and its threshold predicates; FinalMask has all V keep decisions. FinalRunning and FinalMass show the second normalization’s actual mass. CDFCompact, CDFIDs, CDFBefore and CDFRunning use CDFEntry order, whose length is candidateCount rather than necessarily V. At the two-candidate half-open example they contain only a and b, not a padded EOS entry. RNGState, RNGArithmetic and Uniform expose the exact state endpoints, low product/increment/sum and dyadic draw. SampledRow, SampledID and SampledProbability gather the actual final decision. RawZ still retains all five validated raw scores.

By manual source count the sampler has19 steps at V3 and39 tensors; the chapter adds setup/finish and RawZ, giving21 steps and40 tensors. These are source inventory counts, not an executed measurement or numerical acceptance.

Thin tails, invalid inputs and the scope of reproducibility

All raw z values lie in [−40,40]; τ≥1/4 makes scaled values lie in [−160,160]. Shifted differences are at least−320. Their exponential tails remain positive and representable in binary64 under gradual underflow; printing0 does not justify clipping them. At p=1 they remain retained whenever top-k includes them, even if a leading rounded cumulative has reached1.

The reusable sampler accepts finite derived logits beyond slider bounds. For (0,−1000,−1000) at τ=1, the tail exponentials can underflow to actual stored0. Keeping a zero is permitted; selecting it or accepting an all-zero support is not. Overflowing intermediate arithmetic remains an error. No fallback manufactures a probability distribution from invalid arithmetic.

For a retained-zero example, use that helper with logits (−1000,0,0), temperature1, k=3, p=1 and seed634785765. When the first exponential underflows to0, final P is (0,1/2,1/2) and public-order CDF is (0,1/2,1). The derived u is exactly0: a has no positive interval, so the first selectable item is b/98. This helper example does not enlarge the raw chapter bounds.

The exact raw state has V, all five z fields, temperature, topK, topP and seed. It requires own data fields only, with no getters, missing/extra/symbol fields or coercion. Numeric validation follows that order: integer V3..5; all five bounded logits; τ in [1/4,4]; integer k1..V; 0<p≤1; integer seed0..4294967295. Zero k is not a disabled filter, and zero p or τ is invalid. Nonnumeric/nonfinite values give NONFINITE; finite domain violations give INVALID_INPUT. Valid inactive logits still validate. A failed edit has no new defined sample to present.

A fixed seed fixes the uniform stream. It does not guarantee identical floating-point branches across elementary-math libraries near a top-p or CDF boundary. The independent review strategy checks a conditional witness: independently bound the actual logits and stable probabilities, then treat those saved binary64 probabilities as exact operands for independently rounded mass additions, divisions and cumulative comparisons. It verifies the maps, first crossing, RNG and selected ID against that actual path. In generation it also reconstructs each prefix from previously verified emissions. It cannot accept a wrong ID by widening a probability tolerance, invent a subset within a loose error band, or impose one ideal-real path on every library.

Those numerical enclosures are conditional on the declared library-error premises, including the four-ulp elementary-function allowance, round-to-nearest binary64, gradual underflow and separate products/additions without fused contraction. An ulp is one spacing unit between neighboring representable values at the relevant magnitude. These premises must be checked in the validation environment; reading the source does not establish them.

The default derivation has a visible margin: u<1/3<P_a. Near-boundary cases need their actual records checked separately. Neither a hand proof nor source inspection is an executed oracle, parity test or browser check. Temperature and filtering offer explicit choice policies; they do not prove improved language quality, eliminate repetition or train a model.

Read the complete maintained Python calculation

The three disclosures below are raw imports of the actual maintained Python files. Preserve their relative locations. NumPy is the external numerical dependency; other imports use the standard library. Source display does not execute Python or establish parity. The chapter wrapper supports defaults, a complete replacement JSON state, and - for JSON on standard input. A partial object is invalid, not a patch merged with reset values.

1. Chapter entry — code/python/p11/iv46.py. derive_iv46 calls the guarded complete calculation, returning the numeric record or its typed unavailable reason. Its explicit leaf source_self_check is a separate declaration, not part of import or a normal query.

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.

"""IV46 canonical full ordered sampler record.

Keep sampling_reference.py and readonly choice_reference.py adjacent. Default,
complete replacement JSON and '-' stdin use the guarded derive, without checks.
No source in this packet has been imported, executed or runtime-validated.
"""
import importlib.util
from pathlib import Path
from types import MappingProxyType

_path = Path(__file__).resolve().with_name("sampling_reference.py")
_spec = importlib.util.spec_from_file_location("_p11_sampling_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_IV46 = MappingProxyType(dict(_helper.DEFAULT_IV46))


@_helper._choice.guarded
def derive_iv46(state):
    """Return the complete ordered sampler record; never repair partial state."""
    return _helper.compute_sampling(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_IV46)
    result = derive_iv46(state)
    assert list(result) == ["status", "outputs", "steps", "tensors"]
    assert list(result["outputs"])[:4] == ["sampledID", "sampledProbability", "candidateCount", "nextSeed"]
    assert result["outputs"]["sampledID"] == 97 and result["outputs"]["nextSeed"] == 1013904223
    assert len(DEFAULT_IV46) == 10
    assert len(result["steps"]) == 21 and len(result["tensors"]) == 40
    assert list(result["outputs"])[26:] == [f"{step['id']}_{key}" for step in result["steps"] for key in step["outputs"]]
    assert all(list(step) == ["id", "label", "equation", "explanation", "inputs", "outputs"] for step in result["steps"])
    for raw in ({}, None, [], {**state, "extra": 0}):
        rejected = derive_iv46(raw)
        assert list(rejected) == ["status", "code", "reason"] and rejected["code"] == "INVALID_INPUT"
    assert derive_iv46({**state, "z4": True})["code"] == "NONFINITE"
    assert derive_iv46({**state, "temperature": 0})["code"] == "INVALID_INPUT"
    result["outputs"].clear()
    result["tensors"][0]["values"][0] = -1
    repeated = derive_iv46(state)
    assert repeated["outputs"]["sampledID"] == 97 and state == dict(DEFAULT_IV46)
    assert repeated["tensors"][0]["values"] == [1, 0, 0, 0, 0]


if __name__ == "__main__":
    _helper._choice.run(derive_iv46, DEFAULT_IV46)

2. Actual sampling mechanics — code/python/p11/sampling_reference.py. sampling_state checks all ten fields; sampling_options first checks its explicit V, then every option. rng_step derives the signed low product and unsigned modulo transition using integers. sample_next validates the actual dense logits, divides each by temperature and calls the maintained stable distribution. Follow the NumPy float64 arrays through rank-ordered top-k mass, first-crossing top-p visits, the second mass division, public-order CDF and exact selection predicates. NumPy int32 stores IDs/maps/0-or-1 decisions; exactly integer-valued float64 stores unsigned RNG evidence. compute_sampling adds RawZ, setup, finish, summaries and every flattened actual step output, without replacing the real intermediates by ideal formulas.

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]

3. Reused stable full distribution — code/python/p11/choice_reference.py. direct_distribution retains its maximum, shifts, exponentials, ordered denominator, logS, LSE, all active probabilities and separate strict-logit greedy evidence. The sampler uses its actual probabilities; the helper’s greedy winner is not the sampled ID. Its ChoiceTrace stores real input/output operands, and _tensor serializes actual NumPy arrays into detached JSON metadata. No model/tokenizer import is needed just to obtain the fixed five-ID map.

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

Loaders resolve adjacent files from __file__, independently of the caller’s working directory. The exact IV46 closure is these three files; it does not secretly require an old inference wrapper. The wrapper, sampling helper and reused choice file each declare an explicit leaf source_self_check. None calls another check. Those three require deliberate invocation; imports and default/complete-JSON/stdin queries perform no implicit checking.

How to work with the graded checks

First predict from the current raw state. Then follow the scaled score, rank-to-compact/public maps, retained mass and cumulative values before choosing an answer in the lab. Keep base P, top-k Q and final R separate: a question about the selected probability requires the final saved distribution. For a seed question, work the integer transition before locating u in the CDF. For a tie question, name both the declared order and the public IDs. This procedure also applies after edits; the reset ID alone is not an explanation.

The lab’s five actual questions follow that progression:

  1. Which sequence defines this sampling policy, and what does temperature change? Divide by positive temperature, compute full stable P, rank, apply top-k and normalize, retain the first top-p crossing and normalize, then sample the public-ID CDF. Temperature changes scores, not weights. Neither printed probabilities nor a missing draw can replace these operations.
  2. Which storage and normalization statement matches the current V, topK and candidateCount? RawZ[5] retains inactive raw values; BaseP, TopKP and FinalP each retain V compact coordinates. TopKRunning has topK entries and CDFIDs has candidateCount retained entries. Read the actual two masses rather than assuming either equals1. Public ID512 does not allocate513 classes, and filtering does not turn compact addresses into new public IDs.
  3. Which result and draw policy agree with the saved seed, nextSeed, u and CDF? Read the current sampled ID and FinalP at its compact class. With fallback0, the first positive strict interval wins; if the actual flag is1, the answer instead follows the recorded last-positive policy. Do not manufacture that branch by inventing u=1. Every sampling decision consumes one draw, including candidateCount1, and unsigned state evidence remains exact integer-valued float64.
  4. What order and selected-probability meaning does the current record use? Compare actual scaled scores first; exact ties then use public IDs. The prompt distinguishes tied from all-distinct scores. FinalP[sampledRow] is the selected policy probability, separate from base greedy metadata. In the five-class EOS/ab tie, public256 wins filtering while compact2/EOS512 wins IV-45 greedy.
  5. At V3 logits (0,0,−1), temperature1, topK2, topP1 and seed2782269413, which ID is selected? The exact transition gives2147483648 and u=1/2. Equal retained probabilities give the actual two-entry CDF [1/2,1]. The first strict comparison fails at equality; b/98 wins the next interval. Removed EOS does not receive an invented CDF entry, and a retained zero would not win at u0.

Recap and bridge

  • Divide by positive temperature, compute base P, rank, keep top-k, renormalize, keep the top-p prefix and renormalize again.
  • Rank ties use public IDs; CDF order uses public IDs independently of score rank.
  • A strict CDF comparison assigns upper-boundary equality to the next positive interval.
  • One sampling decision consumes one explicit LCG draw, including a one-candidate distribution.
  • Fixed uniforms do not universalize floating-point decisions across libraries.

IV-47 feeds each selected nonterminal ID into the next actual model call, while making EOS, token budget and context stopping explicit.