← Inference From First Principles

Correctness, Determinism and Reproducibility

A cross-run comparison harness with a manifest, tested on a real model: repeatable bit for bit but not invariant to shape, what exact equality and numeric tolerance each say, how far a changed batch moves the tokens, and what it takes to make a seed mean the same thing in every batch.

A prompt run through a model on a GPU, twice, gave bit-for-bit identical logits: 48 prompts out of 48, in half precision and in single, within the tested same-process comparisons and for matching probes across three fresh processes; enabling the framework’s deterministic mode changed no recorded digest in this case. No run-to-run variation was detected in those controlled probes; that observation does not prove every operation on the machine deterministic. The same prompt padded by one position gave different logits for 48 prompts out of 48, with the per-prompt maximum logit difference about 0.05 at the median and about 0.09 at the extreme in half precision and 5e-5 to 1.4e-4 in single. The same prompt in a batch of 2, 8 or 32 did the same. And the same prompt at one fixed shape (a batch of 8, every prompt padded to 160 tokens) gave matching logit digests in 144 out of 144 tested neighbour/row comparisons. All of these are observations on the stated hardware, workload and software versions, not a cross-deployment guarantee.

That separates two properties that are usually spoken of as one. Repeatability, rerunning matched operations, inputs and shapes within the tested environment and getting the same bits, held in the configurations tested without enabling the extra deterministic setting. Batch or shape invariance, a request retaining the same numerical result when batch composition, padding and execution shapes change, did not hold in the tests. A dynamically scheduled service can change those shapes as load changes; that serving scenario was not itself benchmarked here. For greedy decoding in half precision it cost a few percent of sequences: 2 to 4 of 32 sequences of 256 tokens differed when the batch changed, and none in single precision. For the particular batch-wide library seeding procedure tested, it broke sequence identity: seeding the library’s generator with a request’s seed reproduced the request in 0 of 32 cases when the request was in a batch, because a batch-wide random stream does not preserve each request’s draw sequence when rows are regrouped; the experiment also seeded the whole batch using its first request, rather than supplying independent request generators. A stream per request, with execution at a fixed shape, reproduced 32 of 32, with matching per-step logit digests in the tested three regroupings, at the expense of padding dummy rows and pinning the shape.

The chapter’s plan asks for a cross-run output-comparison harness with a version, seed and machine manifest, a characterisation of exact equality against numeric tolerance, and a separate test of batch invariance. The chapter supplies those pieces for Qwen3-0.6B, on one GPU and one installed library stack; some manifest fields are caller supplied rather than automatically discovered. Cross-GPU, cross-driver and cross-library-version identity was not tested and remains NOT_RUN. A separate fp32 CPU-versus-GPU comparison was made, but it did not establish cross-GPU bitwise identity.

The question

“Reproducible” is not one binary property. This chapter distinguishes five questions and requires each experiment to name the relevant one; a result without its comparison conditions cannot support a meaningful repeatability claim.

  • Seeded repeatability: the same request, shapes and seed give the same output on the same system.
  • Deterministic algorithms: for the fixed inputs, environment and execution conditions covered by a kernel’s contract, it returns the same result on repeated calls; enabling deterministic algorithms is not a guarantee of batch invariance.
  • Batch and shape invariance: a request’s numerical result is preserved across changes in other batch members, row count, padding and relevant execution choices; these dimensions must be tested separately.
  • Numerical tolerance: outputs satisfy a specified elementwise or aggregate numerical acceptance rule, with its metric, threshold, comparison unit and denominator declared.
  • Semantic equivalence: two outputs that differ say the same thing.

These properties are related but not a simple ladder: deterministic fixed-shape kernels need not be shape-invariant; different logits may have the same greedy token; the same tokens do not certify semantic correctness. A bytewise difference between otherwise matched runs motivates an investigation of nondeterministic execution or missing configuration fields. A comparison with changed shape tests invariance, not run-to-run nondeterminism. The manifest records known factors but cannot prove there are no unrecorded factors.

Where this sits

Autoregressive Generation turned logits into tokens by sampling from a stream; here one independently advanced random stream per request is a way to preserve draws across regrouping. Quantization and Numerical Precision treated numerical precision, and this chapter measures what the precision of the logits does to tokens. Structured Outputs and Constrained Decoding’s constrained decoder should be tested for stable token choices at equal logical states, and Latency, Throughput and Time to First Token’s server batches requests in ways that change the shapes. Designing Meaningful Inference Benchmarks turns to benchmarks: numerical instability can change answers and reported accuracy even if every evaluation run is syntactically valid.

Where the starter was wrong

The starter’s batch_invariance calls a function for a batch of 1 and of 4, compares the first row, and calls the difference noise. But its function draws a fresh random input and a fresh random weight matrix on every call, so the two batch sizes compute with different matrices, and the starter reports invariant: false with a difference of 5.38 for a computation whose rows are independent of the batch. Its negative verdict cannot isolate batch dependence because it changed both the input and the weights. Its repeated seeded call checks only a narrow repeatability case, and its single absolute tolerance says nothing about model decisions or tail differences. Its manifest has the Python version, the torch version, the platform and the seed: it does not name the GPU, the driver, the CUDA version, the model or its revision, the dtype, the attention kernel, any numerics flag, the request or its batch. The starter’s script and tests remain untouched. The new harness separates the variables, compares saved logits and tokens, and records the conditions that make each comparison interpretable.

The harness

The manifest. Manifest holds 25 named fields in five groups: hardware (GPU and its compute capability, CPU and thread count, driver), software (Python, torch, CUDA runtime, cuDNN, transformers, numpy, operating system), model (name, model and tokenizer revisions, dtype, attention implementation), settings that change numerics (the framework’s deterministic-algorithms switch, the cuBLAS workspace variable, the reduced-precision-reduction flag, TF32) and request (seed, batch composition, padding, sampler). It rejects unknown field names, reports absent field names, and hashes the serialized values. It does not enforce completeness or reject blank/incorrect caller-supplied values; an identical hash therefore establishes only identical recorded metadata. collect_manifest discovers a subset (notably Python, torch, CUDA runtime, detected GPU and numerics flags); the caller must supply model details, driver, request seed, batch composition, padding and sampler when the collector cannot discover them. Record the actual tokenizer revision, not just the model revision.

comparability(a, b) is the part that matters. Two complete and identical manifests make a matched repeatability test possible; a numerical difference then indicates execution variation or an unrecorded input, not proof of a particular nondeterministic kernel. comparability also returns an unrecorded list, which must be empty before a strong claim. When manifests differ, comparability groups the differing keys under hardware, software, model, setting or request. If more than one factor changed, attribution requires an additional controlled experiment. In this chapter’s measurements, for example, the default and deterministic processes differ in exactly two fields, deterministic_algorithms and cublas_workspace_config, and the verdict identifies a setting-level difference; these runs cannot by themselves isolate the effect of the PyTorch switch from the cuBLAS workspace setting.

The comparison. compare_arrays reports exact numerical-value equality, how many elements differ, the largest and median absolute difference, the largest relative difference, and the distance in units in the last place, with whole-array pass/fail verdicts under six absolute tolerances from 1e-6 to 1e-1. Its exact_equal counts matching NaNs and regards +0 and -0 as equal; it also compares differently typed values after conversion to float64. Thus it is not a bytewise test. For matching dtype, shape and literal bytes, use digest together with the saved dtype/shape or compare the byte buffers directly. The digest uses a truncated SHA-256 representation: useful for these probes, not a substitute for a full artifact hash or a provenance record. top1_agreement, kl_divergence and margins compare what a model says as opposed to what its logits are; first_divergence locates the first differing token. digest hashes an array’s bytes so that runs in different processes can be compared without storing the logits.

A unit in the last place needs care for logits. Half precision has 10 bits of mantissa, so the spacing of representable numbers between 16 and 32 is 2⁻⁶ = 0.0156: a difference of 0.05 in a logit near 20 is three units. But a logit near zero has millions of representable numbers around it, and a small absolute difference crossing zero can span very many representable values, especially in single precision. The maximum ULP distance across 151,936 logits can therefore be dominated by low-magnitude or zero-crossing values rather than the top candidate, and so the harness reports median and p99 ULP distance and the maximum over reference logits with magnitude at least 0.5. The ULP diagnostic is defined only for matching floating dtypes and is not an acceptance criterion on its own.

The experiments. Qwen3-0.6B (revision c1899de289a04d12100db370d81485cdf75e47ca) in half and single precision on the RTX 2060 (driver 591.44, torch 2.6.0+cu124, transformers 5.17.0), the process pinned to the performance cores as in Latency, Throughput and Time to First Token. The prompts are 48 single order messages from Structured Outputs and Constrained Decoding’s generator, 62 to 94 tokens with the chat template, asking for a one-sentence summary. The greedy experiments suppress end-of-sequence termination to compare fixed output lengths; this is an experimental control, not normal stop-token behaviour in a serving API. Both model precision and the effective attention backend belong in the manifest.

Repeatability

Repeatability: same input, same output

The same call, repeated in one process, returned exactly equal last-position logits for all 48 matched prompt comparisons in each precision; the matching bytes/digests are a stronger check in the cross-process experiment. An explicit all-ones attention mask and no mask at all gave bitwise equal results (the results were identical; this alone does not demonstrate that the internal kernel path was identical). Repeating the masked run at the same padded shape also produced 48/48 identical comparisons.

Fresh processes were the sharper test. Three processes probed the same 12 individually run prompts (two probe passes, 24 digests) and 24 batched prompts (two passes, 48 digests), in half precision, recording a digest for each compared logit vector: a default process, another default process, and one with torch.use_deterministic_algorithms(True) and CUBLAS_WORKSPACE_CONFIG=:4096:8, the setting the cuBLAS documentation gives for deterministic results with several streams. The two default processes agreed in all 24 and all 48 digests. The deterministic process also agreed on all corresponding digests (24/24 individually probed and 48/48 batched). The framework’s documentation says that deterministic mode makes it use deterministic implementations where they exist and raise an error where they do not, and that this is often slower; the cuBLAS documentation says its routines are bit-for-bit reproducible from run to run on the same architecture and number of multiprocessors within one toolkit version, except in a few cases (several active streams, an atomics mode for some routines). This server has one stream, and the default was already repeatable. The mode changed no bit here and made the loop slower: the decode step was 31.2 and 30.3 ms (batch 1) and 30.1 and 28.8 ms (batch 8) in the two default processes, against 37.8 and 32.3 ms in deterministic mode, approximately 21–25% more for batch 1 and 7–12% more for batch 8 relative to the two default process measurements. These are comparisons between a very small number of unpaired timings, not repeated estimates of a stable performance penalty.

That is the answer for this configuration. It is not a general statement that the setting is useless: the cuBLAS page names conditions I did not create, and the documentation of both libraries gives no guarantee across releases or platforms, which I could not test. What the measurement establishes is the narrower point that the measured changes in output came from changed shapes or sampling arrangements, not from detected run-to-run variation at one fixed shape. Deterministic-algorithm mode was not shown to restore cross-shape identity.

Invariance to shape

Invariance to shape and precision

The first experiment ran each prompt alone and unpadded as the reference, and compared the same prompt padded by 1, 8 and 32 positions and inside batches of 2, 4, 8, 16 and 32 with random neighbours. Every measured changed-shape comparison differed from its reference in at least one logit in both precisions, across the configurations recorded in the first pass. Despite those numerical differences, the top-1 token agreed on all tested first-pass comparisons; this is not a claim about complete generated sequences. In half precision the median largest difference was 0.049 to 0.055 and the largest 0.078 to 0.094, three or four units at a logit’s scale; in single precision 5e-5 to 6e-5 and at most 1.4e-4.

That result did not say why. A possible confound was the attention-mask path, because the unpadded reference and the padded call need not execute identically. A second experiment compared an all-ones mask with no mask, repeated the same masked shape, and varied padding, row count and neighbours separately. The results narrow but do not uniquely identify the responsible kernels.

Comparison (48 prompts, last-position logits) Bitwise equal Largest difference, median / worst (half) (single)
no mask against an all-ones mask 48 of 48 0 0
the same call repeated 48 of 48 0 0
a masked run (padded by 1) repeated at that shape 48 of 48 0 0
padded by 2 rather than 1 0 of 48 0.050 / 0.078 5.0e-5 / 1.1e-4
padded by 8 rather than 1 0 of 48 0.051 / 0.086 4.6e-5 / 7.3e-5
padded by 32 rather than 1 0 of 48 0.054 / 0.070 5.2e-5 / 8.4e-5
in a batch of 2 (46 valid comparisons) 0 of 46 0.052 / 0.098 5.5e-5 / 8.7e-5
in a batch of 8 (43 valid comparisons) 0 of 43 0.055 / 0.094 5.7e-5 / 1.0e-4
in a batch of 32 0 of 48 0.052 / 0.113 6.2e-5 / 1.2e-4
one fixed shape (8 rows of 160 tokens), other neighbours and another row 144 of 144 0 0

The all-ones mask itself was not sufficient to change the tested outputs; this does not rule out other masking or attention-backend paths. At fixed shape, changing the content of the other rows was also insufficient: changing neighbours and moving the prompt to another row changed none of the tested logits in either precision. Changing padded length or row count reliably changed logits in these probes, even by one padding position. That establishes a shape dependence without identifying the exact library operation that caused it. The mechanism I believe is at work, though I did not inspect the kernels to confirm it, is that matrix multiplications and attention are launched with different tilings, and so different orders of summation, for different sizes, and floating-point addition is not associative; the PyTorch numerical-accuracy notes say that a batched mm need not be bitwise equal to the same product computed one element at a time, and the Thinking Machines post (an industry report, not peer-reviewed evidence for this implementation) argues that this batch non-invariance, and not atomic additions, is the main source of variation in a served model (its author reports, for a 235-billion-parameter model at temperature 0, 80 distinct completions in 1,000 requests, identical for the first 102 tokens). I label the mechanism a book hypothesis; the measurement above is the result.

The distinction is also central to Yuan et al. (NeurIPS 2025), who report configuration-dependent numerical and evaluation differences on other models and GPUs; their findings motivate broader qualification but do not validate the particular kernel mechanism hypothesized here.

Exact equality against numeric tolerance

The gate asks for the two to be characterised. Bytewise identity is a stricter reproducibility condition than numerical closeness. In these comparisons the changed configurations differed numerically, whereas the repeated fp32 reference matched. The harness’s exact_equal field must not be relabelled bitwise without a byte comparison. A tolerance is a weaker claim whose strength depends on the number chosen. The experiment reports both per-position acceptance (all 151,936 logits at a position meeting a threshold) and decision-level agreement, because a high acceptance percentage is not the same thing as a whole-run pass.

The reference was single precision on the GPU with the default attention, batch 1, decoding its own greedy continuation for 48 tokens. Each variant was then given that same text (teacher-forced, so that a diverging generated continuation cannot change subsequent inputs) and its logits compared with the reference’s at all 2,304 positions (48 prompts × 48 positions). The compared variants were the same configuration again; single precision in a batch of 8; single precision with the eager attention implementation; single precision on the CPU, which is the one cross-hardware comparison available; half precision; and half precision in a batch of 8.

Variant Positions exactly equal (numeric values) Largest logit difference: median, 99th pct, worst Positions within atol 1e-4 1e-3 1e-2 1e-1 Top-1 agreement KL (mean, worst)
fp32 again 100% 0, 0, 0 100% 100% 100% 100% 100% 0, 0
fp32, batch of 8 0% 4.7e-5, 1.1e-4, 2.9e-4 98.7% 100% 100% 100% 100% 3e-11, 6e-9
fp32, eager attention 0% 3.6e-5, 9.0e-5, 2.8e-4 99.1% 100% 100% 100% 100% 1e-11, 5e-9
fp32 on the CPU 0% 3.3e-5, 8.1e-5, 5.2e-4 99.5% 100% 100% 100% 100% 1e-11, 3e-9
fp16 0% 0.038, 0.080, 0.71 0% 0% 0% 99.7% 99.91% 8.8e-6, 5.1e-4
fp16, batch of 8 0% 0.037, 0.076, 0.15 0% 0% 0% 99.8% 99.96% 8.3e-6, 1.5e-3

What the columns say. Exact numerical equality separates matched repeated outputs from altered computations here but is not a literal bitwise test: the batch, the attention kernel and the CPU are all “different”. At an absolute tolerance of 1e-5, none of the altered fp32 variants passed every logit of a position; at 1e-3 all fp32 positions passed. For fp16, none of the positions passed 1e-2, and only 99.7–99.8% passed 0.1. Neither fp16 variant passed an all-positions, all-logits tolerance of 0.1. A threshold can reverse a per-position verdict without establishing bytewise reproducibility, semantic equivalence or end-to-end correctness. This is why neither a library’s tolerance nor this chapter’s threshold should be copied into a product specification without its decision criterion. It has to come from a requirement, and the requirement here is not about logits.

What the model does with the difference. Top-1 agreement and KL divergence quantify decision stability and distribution movement under the teacher-forced comparison. They do not tell us what actual independently sampled outputs will be under different random streams. All single-precision variants, including the CPU, agreed on the top token at every position, with KL below 6e-9. Half precision flipped the top token at 2 positions out of 2,304 (0.09%) and 1 in a batch of 8. The flipped positions had top-two reference margins no greater than 0.0125 (0.0141 for batch 8), versus a median margin of about 6.2. The margins make the sensitivity intelligible: if every candidate logit moves by at most epsilon, a reference top-two margin greater than 2 × epsilon guarantees the top remains unchanged. The helper flip_probability_bound(margin, noise) compares the margin with noise, not 2 × noise; it is therefore not a generally valid upper bound when noise is a per-logit absolute-error bound. The experiment’s observed flips are evidence, not a proof that the helper captures all possible flips. In the reference, 0.13% of positions had a margin under 0.01, 1.35% under 0.1, 6.2% under 0.5 and 13% under 1.0. The 0.08 figure from the table is a quantile of per-position maxima, not a uniform bound on every candidate; without a uniform bound, the 1–2% of positions with margins below 0.1 are a diagnostic subset, not an exhaustive at-risk set. The two unbatched fp16 flips were among the smallest margins observed, with only about three positions in 2,304 below 0.01.

The practical rule that follows is to choose the tolerance as a statement about the decision that the logits feed. A tolerance on logits is a proxy; the relevant boundary may be the chosen token, a tool call, a JSON constraint or a final answer. In greedy decoding a small perturbation can flip the winner only when its margin is small relative to the candidate-wise difference in perturbations; a larger margin gives protection only under a known uniform error bound.

From logits to tokens

Greedy decoding can amplify a near-tie: once the first selected token differs, all subsequent steps operate on different prefixes and need not reconverge. A logit comparison performed on one shared, teacher-forced continuation is therefore not a direct measurement of full free-running divergence. Each of 48 prompts was generated alone and in batches of 8 and 32, and two batches of 8 were compared under different neighbour groupings. Token positions are reported as in the saved experiment; the harness’s first_divergence function itself returns a zero-based index.

Comparison (identical sequences) Single precision Half precision
48 tokens, 48 prompts: batch of 8, in order 48 45 (diverged at tokens 23, 29, 45)
batch of 8, shuffled 48 45 (23, 35, 45)
batch of 32 48 43 (23, 24, 35, 43, 45)
batch of 8 versus differently grouped batch of 8 48 44 (24, 29, 35, 43)
256 tokens, 32 prompts: batch of 8, in order 32 30 (45, 197)
batch of 8, shuffled 32 28 (35, 45, 80, 199)
batch of 32 32 28 (24, 35, 43, 51)
batch of 8 versus differently grouped batch of 8 32 28 (35, 43, 197, 199)

In single precision no sequence diverged in the 320 reported pairwise comparisons (192 of 48 tokens and 128 of 256, about 42,000 generated tokens), although none of their logits was bitwise equal. In half precision 3 to 5 of 48, and 2 to 4 of 32, diverged. A rough illustration would treat the 2/2,304 first-step disagreements (0.09%) as an independent, stationary per-token hazard, giving about 4% divergence over 48 positions and 20% over 256. Those assumptions are not established: the 2,304 teacher-forced positions share prompts and errors, and free-running prefixes change after a flip. The observed divergences were roughly 6–10% for 48-token runs and 6–12% for the 256-token groups; the longer sequences diverged less than the estimate from two flips in 2,304 positions suggests, which a count that small cannot settle. First differences appeared between reported token positions 23 and 199. That range is descriptive for these fixed-length probes, not an estimated hazard distribution. This is the shape of the effect Thinking Machines reports at scale; the numbers here are for a small model with greedy decoding.

Seeds

Seeds: distinct streams, not aliased

A seed is only as good as the stream it seeds. In the measured model.generate() configuration, torch.manual_seed() controls a batch-wide RNG state rather than constructing an independently seeded stream for each request. Which draws a request receives can therefore change with row count and ordering. The experiment seeded each standalone request with its own seed, then seeded each eight-row batch with the first request’s seed. None of the 32 requests reproduced its 40-token standalone output in either precision. This establishes a failure of that batch-wide seeding and grouping procedure, but it does not compare two procedures in which the same independently seeded generator state is supplied for every request; therefore the result must not be attributed solely to an intrinsic property of all library sampling APIs.

A request needs its own stream. decode_batch draws each request’s randomness from a torch.Generator seeded by that request’s seed only, and samples by the Gumbel-max trick (the argmax of the logits over the temperature plus Gumbel noise from the request’s own uniform draws), which has the softmax law for ideal independent continuous Gumbel draws; the implemented finite-precision GPU generator was checked statistically in a small test against the expected frequencies and that activity on another request’s stream does not change a request’s draws. Removing shared RNG advancement leaves numerical shape changes, and potentially other unrecorded execution changes, as separate causes to test. The result, with 32 requests of 40 tokens, each compared with itself alone under the same regime, in groups of 8 in order and shuffled twice:

Regime (half precision) Identical to the request alone
generate(): standalone seed per request, first-request seed for each batch 0 of 32
per-request streams, natural shapes 30, 29, 30 of 32
per-request streams, fixed shape (every prompt padded to 160, 8 rows, dummy rows filling the batch) 32, 32, 32 of 32, matching recorded logit digests at every step
greedy, natural shapes 32, 30, 31 of 32
greedy, fixed shape 32, 32, 32, digests identical

In single precision every regime but the library’s was 32 of 32 in all three groupings. For the tested decoder, two controls were sufficient for matching output across three permutations of eight-row batches: a fresh request-specific generator state, and a fixed padded execution shape. This is not yet a proof for every sampling backend, context length, cache strategy or dynamic scheduler. The first removes the random draws’ dependence on the batch; the second removes the numerical one.

What the fixed shape costs and what it means. Forty tokens for one request took 1.37 s at natural shapes and 1.34 s at the fixed shape in half precision, 1.33 s with eight requests in it, and 1.16 s, 1.55 s and 1.60 s in single precision. In these few timing measurements on this small, launch-bound loop, the padded shape had a similar wall-clock cost to the natural shape for float16; this is not a statistically resolved performance equivalence; on a GPU-bound server it would be the waste of padding, which I did not measure. And the guarantee is narrow. A request is identical to itself in any batch at that shape. The reference is fixed-shape output, not necessarily the same output as natural-shape execution; fixed-shape reproducibility and algorithmic parity are distinct acceptance conditions. A real service must specify padding bucket, row count, sampler state, KV-cache representation and fallback policy, then verify that those conditions survive scheduling and streaming.

This is one way to the property. DeepSeek’s DeepInfer repository, at the commit pinned for this chapter, describes a batch-invariant mode (DEEPINFER_BATCH_INVARIANT=1, NVIDIA only; the repository lists one model on SM100 GPUs and Ascend NPUs) that makes results identical however requests are grouped, and deterministic sampling with a fixed per-sequence seed; the cited README does not quantify their cost for this hardware and workload. The Thinking Machines post reports kernels that keep a fixed reduction order for any shape, at a cost it gives as about 20% on a matrix multiplication and, in its end-to-end test, 42 s against 26 s (55 s before an improved attention kernel). Kernel-level batch-invariance and fixed-shape scheduling solve different parts of the problem. CoRun (August 2026 preprint) also investigates fixed-shape decode in a serving context, whereas Vosti (September 2026 preprint) explicitly specifies bitwise logit identity across scheduling and cache changes; both report results on other systems. This chapter implements a local fixed-shape control experiment, not those systems. Its evidence does not extend to changed prompt chunking, KV-cache reuse or multiple workers.

What the numbers do not show

One system. One GPU model, one driver/runtime combination, one installed PyTorch/Transformers stack, and one CPU platform. Whether the bits repeat across two GPUs of one model, across a driver update, or across a library upgrade is not measured: the cuBLAS documentation says its results are reproducible within one toolkit version on the same architecture and multiprocessor count and not across toolkit versions, and the framework’s says it promises neither across releases or platforms. The limited fp32 CPU-versus-GPU comparison gave different numerical logits at all 2,304 teacher-forced positions (up to 5.2e-4 in the worst per-position maximum) while retaining the top token at every position. That does not qualify all CPU types, GPU models or kernels.

A small model and short outputs. The effects at 600 million parameters, 48 to 256 tokens and greedy decoding are small; different model sizes, longer continuations or smaller logit margins might exhibit higher divergence rates, but the direction and magnitude were not tested here. Mixture-of-experts routing, speculative decoding, split prefill, tensor parallelism and cache eviction introduce additional shape and state transitions that this harness did not test. The NeurIPS 2025 study by Yuan et al. reports stronger configuration sensitivity in other models, but does not license extrapolating this chapter’s percentages.

Token identity is not semantic equivalence. I measured whether tokens differed, not whether the two answers meant the same. Two sequences that diverge at token 23 may say the same thing, and one that agrees for 100 tokens can diverge later. Semantic equivalence requires a task-specific comparison or independent evaluator, not a hash.

The mechanism is a hypothesis. That the shape-dependence comes from the order of summation in differently tiled kernels is consistent with the documentation and with the pattern of results, and was not established by profiling individual kernel tilings or reduction trees. The results support a changed-shape effect; they do not uniquely locate its source.

Unmeasured settings. TF32 and bfloat16 (the card has neither natively), the reduced-precision-reduction flag, multiple CUDA streams and interference from another process were not systematically varied. The card was shared with a desktop throughout, which is not the same as a controlled interference experiment. No CUDA graph capture, prefix-cache reuse, quantization or distributed execution was qualified.

Inference Lab increment

examples/ch39/repro_core.py adds Manifest, collect_manifest, manifest_diff and comparability, compare_arrays with Tolerance, ulp_distance, digest (a truncated SHA-256 of dtype/shape/bytes), top1_agreement, kl_divergence, margins, first_divergence and flip_probability_bound.

Implementation follow-up: add a dedicated literal-byte equality operation, include an explicit complete/missing gate for manifests, and correct flip_probability_bound for a per-logit epsilon assumption (or rename its argument to the proven pairwise perturbation bound). These are recommended code changes, not features already implemented.

examples/ch39/repro_lab.py adds the experiments invariance, invariance2, decode, tolerance, det_compare and fixed, and decode_batch and gumbel_choice, the batched decode with fixed shapes and per-request streams. Its generate() control seeds each eight-row batch with the first request’s seed, so comparisons with individually seeded runs should be interpreted under that exact procedure.

To rebuild the chapter’s summary from the existing measurement artifacts (without repeating GPU execution):

python research/ch39/build_results.py

To repeat one GPU experiment (device, packages, model weights and a reproducible environment required; the original full suite took about an hour on the reference machine):

python examples/ch39/repro_lab.py invariance2 --out research/ch39/measurements/invariance2.json

The rule this adds: record and validate a complete manifest, distinguish numerical value equality from byte identity, and compare only what the recorded conditions allow; separate repeating a run from not depending on the batch; choose a tolerance from the decision the logits feed, and read top-token agreement and margins beside it; give each request its own random stream; and if a request must return identical results under regrouping, either enforce and verify a fixed execution shape with request-owned random streams or qualify a stronger kernel/engine-level invariance contract. Test the policy under real scheduling before promising it in production.

What you should now be able to do

  • Name the five separate reproducibility properties and state the precise execution conditions required for each claim.
  • Build a manifest that says what a run ran on, and use it to say what a difference between two runs can be due to.
  • Distinguish bytewise identity from compare_arrays’ numerical equality; compare logits by absolute/relative error, ULP distance, positional tolerance and decision-level agreement.
  • Show repeatability across processes, and show that a deterministic-mode switch changed nothing and what it cost.
  • Show that a result depends on the shape of the computation and not on its neighbours, with a test that holds the shape fixed.
  • Link perturbation bounds and logit margins to greedy-token stability, and identify the untested independence assumptions behind any sequence-level divergence estimate.
  • Reproduce the measured fixed-shape, per-request-stream experiment and explain why it does not yet guarantee identity under arbitrary prompt chunking, KV-cache operations or deployment changes.

Key terms

  • Repeatability: matching repeated execution under fixed and sufficiently recorded model, software, hardware, shape and sampler conditions.

  • Batch invariance: a request’s output not depending on the shapes, the batch or the neighbours it ran with.

  • Deterministic algorithm: a kernel that returns the same result for the same inputs under the specified execution conditions; it need not be invariant to changes of tensor shape.

  • Tolerance: an explicit acceptance rule with a unit, metric, threshold and denominator (whole array, per position or final answer).

  • Unit in the last place: the spacing between neighbouring floating-point numbers at a value.

  • Margin: the gap between the top two logits at a position.

  • Manifest: the versioned record of known hardware, software, model, numeric settings and request conditions; missing fields weaken comparison claims.

  • Per-request stream: a random generator seeded by one request and used for no other.

  • Fixed-shape execution: normalizing row count and padded prompt length to specified shapes for the measured operations; this is not automatically equivalent to changing the kernels to be shape-invariant.

  • Byte identity versus numerical equality: equal raw tensor representations versus equal interpreted floating-point values; +0/-0 and differing NaN payloads illustrate why the two tests differ.

  • Per-logit error bound: a maximum change epsilon for every candidate; a top-two margin greater than 2 × epsilon protects the greedy winner when both reference and perturbed logits share the candidate set.

Reader exercises

  1. Repeat the shape experiment on a second GPU and a second PyTorch version. Record separate complete manifests and vary only one factor at a time; show which claims are no longer directly comparable.
  2. Inspect the kernels launched for padded lengths of 94 and 95 and find whether the matrix-multiplication tile or split changes; confirm or refute the hypothesis.
  3. Test several CUDA streams and a GPU shared with another process for run-to-run variation.
  4. Measure fixed-shape padding overhead for long prompts and batch 64, including prefill, decode, peak KV memory and per-request latency. Compare with a genuinely batch-invariant kernel implementation if one is available.
  5. Put a numerical-tolerance test for half precision on a decision other than the top token (for example, whether a constrained decode of Structured Outputs and Constrained Decoding produces the same record) and say which tolerance it needs.
  6. Count how often a divergence changes the meaning of an answer, by comparing the diverged sequences’ text with a judge of your choice.
  7. Require a complete manifest, full RNG state or counter offset, explicit request ordering and cache lineage. Write a test that refuses a repeatability verdict when any required field is missing, even if the recorded hashes match.
  8. Run the harness on a mixture-of-experts model and test routing/capacity variation separately from random-stream variation. Add a regression test showing that +0 and -0 pass numerical equality but fail a literal-byte comparison, and that a 0.1 fp16 per-position success rate under 100% is not a whole-run pass.

References

Evidence in this chapter

Claim Category
Repeated matched calls returned numerically identical logits for 48/48 prompts in both precisions; corresponding dtype/shape/byte digests matched in the three-process half-precision probes (24 individual and 48 batched comparisons) Book result (one GPU, driver and library version; finite tested probes)
The process with deterministic mode and a cuBLAS workspace setting returned the same tested digests as default; decode-step timings were 21–25% higher at batch 1 and 7–12% at batch 8 versus the two default process timings Book result (few unpaired process timings; two settings changed together)
Padding a prompt by one position, or batching it with others, changed the logits for 48 of 48 prompts by up to 0.09 (half) and 1.4e-4 (single); at one fixed shape, changing the neighbours and the row changed nothing in 144 of 144 Book result
An all-ones mask and no mask gave bitwise equal results Book result
Shape-dependent reduction order/tiling explains the observed changed-shape numerical differences Book hypothesis, motivated by documentation and external research; individual kernels were not inspected
All fp32 variants passed per-position atol 1e-3 and matched top-1 in the teacher-forced probe; the fp16 variants passed atol 0.1 at 99.7–99.8% of positions (not all), with 1–2 top-1 changes in 2,304 positions and reference margins up to 0.0141 Book result (per-position acceptance, not whole-array acceptance or end-to-end semantic equivalence)
Greedy decoding in half precision diverged from the run alone for 3 to 5 of 48 sequences of 48 tokens and 2 to 4 of 32 of 256; single precision for none Book result
The tested batch-wide generate() seed procedure reproduced 0/32 standalone sequences when regrouped; request-owned RNG streams plus fixed execution shape reproduced 32/32 under each tested grouping with matching per-step logit digests Book result (batch seeded using first request; fixed shapes only, no general provider guarantee)
Batch-invariant kernels cost about 20% in a matmul and 42 s against 26 s end to end; 80 distinct completions in 1,000 at temperature 0 Reported by the author of a vendor blog post; not reproduced
DeepInfer’s batch-invariant mode and deterministic sampling Reported by the README; not run
Cross-hardware, cross-driver and cross-version identity; several streams; TF32 and bfloat16; semantic equivalence of diverged outputs NOT_RUN
compare_arrays.exact_equal is a literal bitwise test NOT_ESTABLISHED: implementation checks numerical equality after float64 conversion (matching NaNs and signed zero count equal); byte identity requires a separate byte or digest check
flip_probability_bound correctly bounds all greedy flips under a per-logit absolute error epsilon NOT_ESTABLISHED: helper uses margin < epsilon; a sufficient top-token stability test requires margin > 2 epsilon when each logit may move independently by epsilon
Yuan et al., CoRun and Vosti results External peer-reviewed research (Yuan et al.) and preprints (CoRun/Vosti); not reproduced

Implementation status

  • Manuscript: content/books/inference/39-chapter.md
  • Runnable examples: examples/ch39/repro.py (original, unchanged), examples/ch39/repro_core.py (manifest, comparison, distances), examples/ch39/repro_lab.py (the experiments)
  • Tests: tests/test_ch39_repro.py (original), tests/test_ch39_repro_lab.py (24 tests: ULP distances, comparison verdicts and tolerances, NaNs and shape errors, KL, margins and first divergence, a limited margin/noise helper, digests, summation order, manifest comparability, the starter’s confounded invariance test, the Gumbel sampling frequency check, request-generator independence, and the batched decode loop against a tiny random Qwen3). The existing tests do not establish literal byte identity for signed zero/NaN payloads, complete-manifest enforcement, or a valid per-logit epsilon bound on all possible top-token flips
  • Evidence: research/ch39/sources.md, research/ch39/results.json, research/ch39/measurements/, research/ch39/build_results.py, research/evidence-register.md
  • Verification command: python -m unittest discover -s tests -v

The chapter is a draft with draft = false. It makes no claim of cross-GPU or cross-version determinism, independent reproduction of a serving engine’s invariance mode, or guaranteed byte identity beyond the tested digest comparisons. The proposed code corrections and prospective larger-system qualification are not yet implemented. Designing Meaningful Inference Benchmarks turns to benchmarks.