Phase 04/Measure and tune/Correctness, numerics and regression evals
PHASE 04 · Measure and tune

Correctness, numerics and regression evals

0%
10 h7 subtopics3 lessons · 1 required
In plain English

Making a model faster usually means changing how it does arithmetic, with smaller number formats, fused operations, different kernels or new hardware. Each change nudges the model's answers a tiny bit, and enough tiny nudges add up to a model that is quietly worse. Correctness engineering is the habit of measuring those nudges before shipping. Think of a pharmacy that switches to a cheaper pill press. The pills look identical, so the only way to know they still work is to assay a sample from every batch against a reference. Here the reference is the model's output in full precision, the assay is a set of statistical comparisons of its predictions, and the gate is a rule that blocks a release when the drift crosses a threshold you chose on purpose rather than by accident.

Why it matters

Performance teams at Anthropic and Cerebras treat correctness as part of performance because a 20 percent faster kernel that changes 2 percent of answers is a regression, not a win. Numerical comparison harnesses, golden output tests and determinism checks are what let you change precision, kernels or hardware every week without a slow-motion quality collapse.

Hiring signal

Anthropic's Inference System Dynamics team owns "the correctness evaluation pipeline that validates model output quality across hardware platforms, numerics, and serving configurations" and expects engineers to root-cause a numerical divergence between two platforms to a specific kernel change; Cerebras asks for validation and regression infrastructure covering numerical accuracy, precision changes, quantization and determinism.

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Compute KL divergence, top-1 agreement and top-k overlap between two models' next-token distributions over a prompt set and interpret the numbers.
  • Build a regression harness that compares FP32, BF16 and INT4 variants of a model and fails on a threshold you justify from measured noise.
  • Detect a deliberately injected quantization bug with the harness and localize it to a layer.
  • Design golden-output tests across engines that tolerate benign floating-point divergence while catching real regressions.
  • Measure batch-invariance and run-to-run determinism and explain where nondeterminism enters an inference stack.

Key concepts

Reference (golden) outputs
Logits, logprobs or generated tokens from a trusted configuration, usually FP32 on a known engine, stored with the prompts and versions that produced them.
KL divergence of next-token distributions
KL(p_ref || p_test) averaged over positions; a scalar for how much the test configuration's predictions drift from the reference, in nats.
Top-1 agreement and top-k overlap
Fraction of positions where the argmax matches, and the mean Jaccard overlap of the top-k sets; cheap signals that correlate with user-visible changes.
Greedy divergence position
The first token at which two greedy generations differ; after it, comparisons are meaningless because the contexts differ.
Teacher-forced comparison
Feeding both configurations the same reference tokens so every position is comparable, avoiding divergence cascades.
Noise floor
The spread of your metric between two runs that should be identical (different seeds, batch compositions or hardware); thresholds must sit above it.
Batch invariance
Whether a request's logits depend on which other requests shared its batch; broken by reduction-order changes in GEMM and attention kernels.
Determinism
Identical outputs for identical inputs across runs; requires fixed seeds, deterministic kernels and batch-invariant reductions.
Task evals versus numerics evals
Downstream accuracy (GSM8K, MMLU) is slow and noisy; numerical comparisons are fast and sensitive; a release gate needs both at different stages.

Subtopics

  1. 1. What can change the numbers

    Precision casts, fused versus unfused kernels, accumulation order, attention backends, quantization, tensor-parallel splits, hardware; each shifts logits by a characteristic amount.

  2. 2. Comparison metrics

    Per-position KL, max-abs and relative logit error, top-1 agreement, top-k overlap, log-prob of reference tokens; what each catches and misses.

  3. 3. Building a numerics harness

    Prompt set design, teacher forcing on reference tokens, storing golden logits compactly, computing metrics per layer and per position, reporting distributions not means.

  4. 4. Setting thresholds and gates

    Measure the noise floor with identical configurations, pick thresholds with margin, inject known regressions to verify the gate fires, review false-positive rates.

  5. 5. Golden-output tests across engines

    Comparing transformers, vLLM and SGLang greedy outputs, allowing benign divergence at near-ties, using logprobs from the API, versioning the goldens.

  6. 6. Determinism and batch invariance

    Sources of nondeterminism (atomics, split-K, dynamic batching), measuring batch invariance, deterministic kernel modes and their cost.

  7. 7. Investigating a regression

    Bisect across layers with hooks, across kernels with backend flags, across commits with the harness; define the acceptance threshold going forward.

Resources

documentation
article
repo
  • lm-evaluation-harness ↗
    The standard task-eval harness; use it to see how slow and noisy downstream evals are compared with numerics checks.
  • vLLM tests directory ↗
    Read tests/models for how a production engine compares its outputs against transformers.
paper

Hands-on lessons

L1

Build a numerics regression harness and catch a seeded bug

CPU · your Macscript180 minrequired

Goal · numerics_check.py that compares FP32, BF16 and INT4 variants of Qwen2.5-0.5B (or GPT-2) with KL and top-k metrics, applies a justified threshold, and flags an injected quantization regression.

  1. 1Load Qwen/Qwen2.5-0.5B-Instruct (or gpt2) in float32 and build a prompt set of 100 varied prompts of 64-256 tokens; generate 32 greedy tokens per prompt with the FP32 model and save prompt plus continuation as the reference token sequences.
  2. 2Write compare(model_ref, model_test, sequences) that teacher-forces each sequence through both models and records per-position KL(p_ref || p_test), top-1 agreement and top-5 Jaccard overlap.
  3. 3Create the BF16 variant with model.to(torch.bfloat16) and run compare; report mean and p99 KL, top-1 agreement and top-5 overlap.
  4. 4Create the INT4 variant by applying your per-group(128) weight quantizer from p4-quantization-l1 to every linear layer and run compare.
  5. 5Measure the noise floor by comparing FP32 against FP32 with sequences processed one at a time versus in padded batches of 8; set your gate thresholds at least 3x above the measured floor and write down the reasoning.
  6. 6Inject a regression into the INT4 variant, for example quantizing one middle MLP layer per-tensor instead of per-group, or truncating instead of rounding in one layer; rerun compare and confirm the gate fires.
  7. 7Add a per-layer bisection mode that quantizes layers one at a time and reports which single layer moves mean KL the most; confirm it points at the layer you broke.
  8. 8Write a short results table and a paragraph on which metric caught the bug first and why.
Deliverable
numerics_check.py, a saved reference set, the results table for BF16, INT4 clean and INT4 seeded, and the paragraph.
Check
BF16 mean KL is under 0.02 nats with top-1 agreement above 95 percent; the seeded regression raises INT4 mean KL by at least 3x over clean INT4 and trips your gate; the bisection names the layer you modified.
L2

Golden-output tests across transformers and vLLM

Colab T4 · freeexperiment120 minoptional

Goal · A pytest suite that compares vLLM greedy outputs and logprobs against transformers goldens for 50 prompts and distinguishes benign near-tie divergence from real regressions.

  1. 1On CPU (or in Colab) generate 32 greedy tokens for 50 prompts with transformers in float32 for Qwen2.5-0.5B-Instruct and save tokens plus top-5 logprobs per position as goldens in a JSON file with model revision and library versions.
  2. 2In Colab start vllm serve Qwen/Qwen2.5-0.5B-Instruct --dtype half and request the same prompts with temperature 0, max_tokens 32, logprobs 5.
  3. 3For each prompt find the first divergence position; at that position record the golden top-1/top-2 logprob gap.
  4. 4Write test_goldens.py that asserts token agreement for positions before the first divergence and asserts that every divergence happens where the golden top-1/top-2 gap is under 0.5 nats; report the fraction of prompts that diverge within 32 tokens.
  5. 5Simulate a regression by rerunning vLLM with --quantization fp8 (or a GPTQ or AWQ checkpoint of the same model) and show which assertions fail and how the divergence distribution shifts.
  6. 6Write a paragraph on how you would version and refresh goldens when the reference model or engine is upgraded.
Deliverable
goldens.json, test_goldens.py, the pytest output for the FP16 and quantized runs and the paragraph.
Check
At least 80 percent of divergences in the FP16 run occur at positions where the golden top-1/top-2 gap is under 0.5 nats; the quantized run produces a measurably higher divergence rate that your tests report.
Fallback
Replace vLLM with the same transformers model cast to float16 or bfloat16 on CPU; the test structure and the near-tie analysis are identical.
L3

Measure batch invariance and determinism

CPU · your Macexperiment60 minoptional

Goal · A measurement of how much a request's logits change depending on which other requests share its batch, in FP32 and BF16, and whether greedy tokens change.

  1. 1Load Qwen2.5-0.5B-Instruct (or gpt2) and pick 8 prompts of different lengths; run prompt 1 alone and record its last-position logits.
  2. 2Run prompt 1 padded in a batch with the other 7 (attention mask set correctly) and record the same logits; compute max-abs and relative difference, in FP32 and in BF16.
  3. 3Repeat the single run 5 times with the same seed and confirm whether results are bit-identical on your machine.
  4. 4Vary batch size 2, 4, 8 and plot max-abs logit difference versus batch size for both dtypes.
  5. 5Check whether the greedy next token ever changes for any of the 8 prompts across batch compositions; count the cases.
  6. 6Write three sentences relating what you saw to reduction order in GEMM kernels and to what a serving engine with dynamic batching implies for reproducibility.
Deliverable
A notebook with the difference table, the plot and the sentences.
Check
You report max-abs logit differences for FP32 and BF16 and the BF16 figure is larger; repeated single runs are bit-identical or you identify the nondeterministic op.

Build your own

Build your own numerics regression harness

PythonCPU · your Mac~8 h

A golden-logit harness with KL and top-k agreement gates that catches seeded bugs in a model implementation and runs on every push.

The real thing: github.com/vllm-project/vllm/blob/main/tests/models/utils.py ↗

How you know a stage passes

Write tests/test_harness.py first. The harness under test compares a candidate model (your Phase-1 GPT-2 engine, transformers GPT-2 in another dtype, or a deliberately broken model) against golden outputs from transformers GPT-2 fp32 on 20 fixed prompts. Each stage adds a test that either checks a metric against a hand-computed value, or injects a specific bug and asserts the gate fires with exit code 1. `numerics golden|run|inject` is the CLI. Run `pytest -q`; a stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/7
  1. 01generate and fingerprint goldens
    `numerics golden` saves, for 20 prompts, the top-10 logprobs at every position, the full-vocab logits at the last position and the 32 greedy continuation tokens, with a manifest of model id, tokenizer hash, torch version and seed.
    test · Running the command twice produces byte-identical golden files; the manifest has every field and the loader refuses a golden file whose model id does not match the candidate's.
  2. 02the metrics
    Max abs logit difference, mean KL(golden || candidate) over the full vocab, top-1 agreement, top-10 Jaccard overlap and first-divergence position of the greedy continuation, each a pure function with its own unit test.
    test · Candidate equal to golden gives KL 0.0, agreement 1.0 and divergence position -1; a uniform-random candidate gives top-1 agreement below 0.01; KL of two hand-built 3-way distributions equals the value you compute by hand to 1e-9.
  3. 03tiered gates
    A gates.yaml defines thresholds per tier (fp32, bf16, int8) for every metric, and `numerics run --tier T` exits 0 or 1 and prints a table of metric, value, threshold, pass.
    test · transformers GPT-2 in bf16 on CPU passes the bf16 tier and fails the fp32 tier; your Phase-1 engine in fp32 passes the fp32 tier; exit codes are asserted by the test.
  4. 04seeded bug injection
    `numerics inject <bug>` monkeypatches one of five bugs into the candidate: dropped final-layer bias, position ids off by one at decode, softmax computed in fp16 without the scale, one transposed weight, causal mask off by one.
    test · Each of the five bugs trips at least one fp32-tier gate; the test writes a matrix of bug versus metric and asserts that at least one bug is caught by KL while top-1 agreement stays above 0.98, showing why token agreement alone is not enough.
  5. 05determinism and batch invariance
    The harness runs each prompt alone and padded inside a batch of 8, and runs the same input three times, reporting max logit differences for both.
    test · Repeated single runs are bit-identical in fp32 or the harness names the first op whose output differs; the batch-versus-alone difference is reported for fp32 and bf16 and the bf16 figure is larger.
  6. 06candidates behind one interface
    An adapter interface (load, logits(input_ids), greedy(input_ids, n)) with implementations for transformers, your Phase-1 engine and, on Colab, vLLM through its offline API.
    test · `numerics run --candidate phase1 --golden hf --tier fp32` passes; the README table lists each candidate against each tier with the measured KL and agreement.
  7. 07run it on every push
    A GitHub Actions workflow runs the fp32 tier on CPU with cached goldens and publishes a JUnit XML report.
    test · The workflow passes on a clean clone; a branch that injects one bug turns the job red, and the README links both runs.

Knowledge check

QWhy compare models with teacher forcing instead of comparing their free-running generations?

Once two generations diverge at one token their contexts differ and later tokens are not comparable; teacher forcing feeds both the same reference tokens so every position is a fair comparison.

QA BF16 build shows 97 percent top-1 agreement with FP32. Is it broken?

Not necessarily; most disagreements happen at near-ties where the top two tokens have almost equal probability, so check the KL and the logprob gap at the disagreement positions before judging.

QHow do you choose a threshold for a numerics gate?

Measure the noise floor by comparing configurations that should be identical (different batch compositions, seeds or hardware of the same type), set the threshold with margin above it, then verify the gate fires on injected regressions.

QWhat makes an inference engine non-batch-invariant?

Kernels whose reduction order or tiling depends on batch size (split-K GEMM, attention with different block strategies), so the same request produces slightly different floating-point results in different batches.

QWhy keep both numerical comparisons and downstream task evals in a release pipeline?

Numerical checks are fast and sensitive and run on every change, but they cannot say whether a drift matters; task evals measure what users see but are slow and noisy, so they gate less frequently.

Completion

  • All 7 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 harness saved, the seeded regression is caught and localized, and the thresholds are justified in writing.
  • Can list five sources of numerical divergence in an inference stack and the metric that would catch each.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →