Skip to content

Test MLX token sampling: temperature, top-k and top-p

If the same logits suddenly produce repetitive answers after a change to the sampling code, do not retrain the model just yet. Changing the order of temperature scaling, candidate filtering, or renormalization changes the output distribution. When running MLX inference on a cloud Mac, separate the sampler from the model and test it with a small vocabulary. An answer that “looks reasonable” is not evidence that the sampler passes.

Define the contract

Start with a one-dimensional array of logits for the final position of a single sequence, where each array index is a token ID. Process batched inputs row by row; never sort across the batch axis. This article fixes the order as follows: validate the inputs, handle zero temperature, apply Top-K, perform temperature scaling and softmax, then apply Top-P and renormalize.

In exact arithmetic, changing the order of Top-K and temperature scaling does not affect the ranking. Top-P, however, must use the probabilities after temperature scaling. If Top-K comes first, the denominator for Top-P is based on the filtered candidate set. You cannot keep using probabilities calculated over the full vocabulary.

Top-P retains the first token that brings the cumulative probability to or above the threshold. Removing this “threshold-crossing token” can leave the candidate set empty and systematically narrows the sampling range.

Break all score ties by ascending token ID. Allow negative infinity to represent masked positions, but reject NaN, positive infinity, and inputs in which every position is masked. At zero temperature, select greedily without consuming the random source.

Build a reference implementation

In a separate Python environment, save the following as sampling_check.py. This is an auditable CPU reference, not a high-throughput sampling implementation. It returns candidate IDs and probabilities so that you can compare intermediate stages rather than seeing only the final token.

import math
import random

def distribution(logits, temperature=1.0, top_k=None, top_p=1.0):
    values = [float(v) for v in logits]
    if not values or any(math.isnan(v) or v == math.inf for v in values):
        raise ValueError("Invalid logits")
    if not math.isfinite(temperature) or temperature < 0:
        raise ValueError("Invalid temperature")
    if not math.isfinite(top_p) or not 0 < top_p <= 1:
        raise ValueError("Invalid top_p")
    if top_k is not None and (
        type(top_k) is not int or top_k < 1
    ):
        raise ValueError("Invalid top_k")
    ids = [i for i, v in enumerate(values) if math.isfinite(v)]
    if not ids:
        raise ValueError("No valid candidates")
    ids.sort(key=lambda i: (-values[i], i))
    if temperature == 0:
        return [ids[0]], [1.0]
    if top_k is not None:
        ids = ids[:top_k]
    peak = values[ids[0]]
    weights = [math.exp((values[i] - peak) / temperature) for i in ids]
    total = math.fsum(weights)
    probs = [w / total for w in weights]
    end = len(ids)
    if top_p < 1:
        for j in range(len(ids)):
            if math.fsum(probs[:j + 1]) >= top_p:
                end = j + 1
                break
    ids, probs = ids[:end], probs[:end]
    mass = math.fsum(probs)
    return ids, [p / mass for p in probs]

def draw(ids, probs, rng):
    u = rng.random()
    if not 0 <= u < 1:
        raise ValueError("Invalid draw")
    cumulative = 0.0
    for token, probability in zip(ids, probs):
        cumulative += probability
        if u < cumulative:
            return token
    return ids[-1]

Subtracting the maximum score before dividing by temperature avoids exponentiating large positive values directly. When Top-P equals one, the code explicitly retains every candidate with a finite logit, preventing accumulated rounding error from cutting the list short. Extremely small weights can still underflow to zero, so remaining in the candidate set does not guarantee an observable chance of being selected.

Test the boundaries

Append these assertions to the file, then run python sampling_check.py. Exiting without an exception means only that these fixtures passed; any new rule still needs its own test cases. First check equality using exactly representable half probabilities, then use a three-entry distribution to test threshold crossing.

ids, probs = distribution([0.0, 0.0], top_p=0.5)
assert ids == [0] and probs == [1.0]

logits = [math.log(0.5), math.log(0.3), math.log(0.2)]
ids, probs = distribution(logits, top_p=0.6)
assert ids == [0, 1]
assert math.isclose(probs[0], 0.625, abs_tol=1e-12)

assert distribution([2.0, 2.0], temperature=0)[0] == [0]
assert distribution([-math.inf, 0.0], top_k=9)[0] == [1]
assert distribution([0.0, 0.0, 0.0], top_k=2)[0] == [0, 1]

for invalid in ([math.nan], [math.inf], [-math.inf]):
    try:
        distribution(invalid)
    except ValueError:
        pass
    else:
        raise AssertionError("Invalid input accepted")

class FixedDraw:
    def random(self):
        return 0.625

assert draw(ids, probs, FixedDraw()) == 1
left = random.Random(17)
right = random.Random(17)
assert [draw(ids, probs, left) for _ in range(20)] == [
    draw(ids, probs, right) for _ in range(20)
]

When the fixed draw lands exactly on the first entry’s cumulative probability, it must select the second entry: sampling intervals include the left endpoint and exclude the right. Do not try to verify this equality case by increasing the number of random draws. A finite experiment may never hit the boundary.

Add negative test cases

Also add tests requiring exceptions for empty input, negative temperature, zero Top-K, zero Top-P, and Top-P greater than one. When Top-K exceeds the number of valid tokens, retain all valid candidates without an out-of-bounds error. A failed test must block the task; do not fall back to the unfiltered distribution and continue generating.

Connect to MLX inference

Use a small tensor in an environment with MLX installed, evaluating it before converting it to a host-side list. With a real model, likewise extract only the final position rather than copying the entire context to the CPU.

import mlx.core as mx

logits = mx.array([2.0, 1.0, -float("inf")], dtype=mx.float32)
mx.eval(logits)
ids, probs = distribution(logits.tolist(), top_k=2, top_p=0.9)
assert ids == [0, 1]
assert math.isclose(math.fsum(probs), 1.0, abs_tol=1e-12)

Add a test-only inspection interface to the sampler under test. Export the filtered IDs and probabilities, and compare each against the reference. IDs must match; set probability tolerances according to the numerical precision used. Do not use floating-point accumulation error as a reason to add the same loose offset to every threshold.

A fixed seed constrains results only within the same random-number implementation. If the CPU reference and device use different random algorithms, you cannot require token-by-token agreement. A more reliable debugging order is to compare candidate sets, normalized probabilities, and fixed draws, then finish with frequency checks across repeated samples.

Retain the evidence

For every acceptance run, save the script, dependency versions, numerical precision, and failing cases. Logging candidate IDs, the probability sum, and parameters is enough; real prompts and full outputs do not need to enter the logs. Give each request an independent random source so concurrent requests do not consume one another’s random state, leaving serial execution reproducible but parallel execution prone to drift.

Reconnect the sampler to the generation loop only after acceptance testing. Also verify that the end-of-sequence token is not incorrectly masked and that the maximum generation length is always enforced. Evaluate sampling correctness separately from answer quality: the former establishes that the implementation follows the distribution contract; the latter addresses task performance. With this separation, changes after an inference-environment switch can be traced to a specific stage instead of prompting another round of guesswork about whether the model has degraded.

Frequently asked questions

Does top-p retain the token that crosses the threshold?

Under this contract, yes. Keep the shortest prefix whose cumulative probability reaches or exceeds p, then renormalize it. Stop at that token when the cumulative probability equals p as well.

What should happen at zero temperature?

Validate the input, then return the highest-scoring token directly. Break ties by the smaller token ID. Do not divide by temperature or consume random state.

Will the same seed make MLX and the oracle match token for token?

Not necessarily. Random algorithms and floating-point reduction order can differ. Compare candidate IDs and probabilities first, and inject fixed draws to test selection boundaries.

Rent a Mac for your project

Dedicated physical Mac mini, not a virtual machine. Choose a daily, weekly, monthly, or quarterly rental. It stops when your term ends unless you renew. Export your project files and logs before your rental ends.

Choose a plan

Start for your project, stop when you're done

Choose a dedicated physical Mac mini and rent it by the day, week, month, or quarter.