Skip to content

perf(sampling): softmax-free Gumbel-max categorical sampling kernel - #970

Merged
inureyes merged 8 commits into
mainfrom
feature/issue-900-gumbel-max-sampling
Jul 30, 2026
Merged

inureyes merged 8 commits into
mainfrom
feature/issue-900-gumbel-max-sampling

Conversation

@inureyes

@inureyes inureyes commented Jul 30, 2026 •

Copy link
Copy Markdown
Member

Summary

The fused sampler ended in mlx::core::random::categorical, which normalises over the whole vocabulary (32K-152K entries) once per token per row. The Gumbel-max identity removes that pass: adding i.i.d. Gumbel(0,1) noise to logits / temperature and taking the argmax draws exactly from softmax(logits / temperature), so the sampling step collapses to a single index-carrying max reduction with no softmax and no sort. This lands the kernel for the no-filter path, which is the simplest case and the one that validates the plumbing (dual-backend JIT strings, per-row RNG, batch-wide launch, statistical parity harness) before the rejection-based top-k/top-p work in #901.

What changed

  • src/lib/mlx-cpp/turbo/sampling.{h,cpp} (new): the launcher and both JIT strings, following the dual-source pattern in paged_attention.cpp. One threadgroup of 256 threads handles one (row, split) pair; each thread owns 4 consecutive vocabulary entries per sweep and keeps a running (value, index) maximum, then a halving-tree reduction over threadgroup memory merges them. Noise is Philox-4x32-10 generated in-kernel and keyed on (row, element), so element i of row r always draws philox(key, {i >> 2, 0, r, 0})[i & 3] regardless of thread count or split count.
  • src/lib/mlxcel-core/cpp/mlx_cxx_bridge.cpp: fused_sample is refactored into fused_sample_impl(..., allow_gumbel). The public fused_sample passes the resolved gate; the new fused_sample_categorical pins allow_gumbel = false and is the pre-change reference path, which is what lets the microbenchmark A/B both arms and the tests compare them inside one process. New entry points gumbel_max_sample, sampling_gumbel_available, and gumbel_sample_num_splits, all exposed through the cxx bridge.
  • src/lib/mlxcel-core/src/sampling.rs: batched_sample dispatches the whole batch through one batched_fused_sample call when every row shares a fused-eligible scalar config (new uniform_fused_batch_params helper), which on the no-filter path is a single batch-wide kernel launch with grid.z = B instead of the per-row slice/sample/eval/readback loop. Any divergent or penalty-carrying row falls back to the existing loop.
  • src/lib/mlxcel-core/src/sampling_gumbel_tests.rs (new): the statistical suite, described under Test plan.
  • tests/sampling_gumbel_kill_switch.rs (new): the MLXCEL_SAMPLING_GUMBEL=0 test, in its own binary because the C++ gate resolves the env var into a process-static.
  • examples/gumbel_sampling_microbench.rs (new): the sampling-step microbenchmark over vocab {32K, 64K, 152K} x batch {1, 4, 8}.
  • CHANGELOG.md, docs/environment-variables.md, docs/architecture.md: the RNG stream change, the new env switch, and a corrected description of what now lives under src/lib/mlx-cpp/turbo/.

Design notes

RNG derivation. Each call draws one Philox key from mlx::core::random::bits(Shape{2}, 4), which consumes MLX's default thread-local key sequence, the same stream random::categorical consumes. So ffi::random_seed still reproduces a run exactly, and one sampling call advances the shared state exactly once, the same way one categorical call does. The counter carries the (row, element-group) pair, so every element of every row gets an independent stream from that one key, with no per-element RNG state and no [B, V] uniform buffer materialised.

Split heuristic and launch-shape invariance. A [1, 152064] decode row is one reduction; without splitting, a batch-1 launch would occupy a single GPU core while the rest idle. gumbel_num_splits therefore spreads a small batch across up to 64 cooperating threadgroups (targeting 64 resident threadgroups overall) and collapses to 1 once the batch already fills the machine, in which case there is no second reduction pass at all. This is only safe because the noise is a pure function of (key, row, element): the sampled index is provably identical under any split count, which gumbel_sample_index_does_not_depend_on_the_launch_split pins directly by comparing row 0 across a 32-split and a 1-split launch at the same seed.

Gating. The kernel is used when temperature > 0 and none of top-k / top-p / min-p narrows the support, on a 2-D f32/f16/bf16 input, on a GPU default device with Metal or CUDA available. Greedy stays on argmax. Masked entries need no special handling: -inf / T is -inf and -inf + finite_gumbel is -inf, so a masked token can never win the argmax while any finite logit remains. That is why the uniform is built on the open interval (0, 1): a u of exactly 0 or 1 makes the Gumbel infinite, which would both hand that element the argmax unconditionally and produce a NaN against a -inf logit. Commit f48e388f fixes a real instance of that (the 24-bit spelling ties 2^24 - 1 + 0.5f up to 2^24 in f32 and lands on u == 1.0, roughly one uniformly-random token per 110 decode steps at a 152K vocabulary) and adds the regression test that catches it.

Behavior change, please read

Sampled token streams differ at equal seeds. Gumbel-max and categorical consume the shared MLX key sequence differently, so a fixed seed no longer reproduces a stream recorded before this change on the no-filter stochastic path. The distribution is unchanged, which is what the chi-square suite establishes, and greedy decoding is byte-identical. Runs remain fully reproducible going forward (same seed, same backend, same stream). MLXCEL_SAMPLING_GUMBEL=0 restores the exact previous path for anyone who needs to reproduce an older stream. Noted in CHANGELOG.md under Unreleased/Changed and in the docs/environment-variables.md row.

Test plan

All run on Apple Silicon (M1 Ultra, Metal), against the final tree:

  • cargo test --release -p mlxcel-core --lib --features metal,accelerate sampling_gumbel_tests:: gives 14 passed, 0 failed, 0.68s
  • cargo test --release -p mlxcel-core --lib --features metal,accelerate sampling:: gives 54 passed, 0 failed, 0.44s (the pre-existing sampling suite, no regression)
  • cargo test --release --features metal,accelerate --test sampling_gumbel_kill_switch gives 1 passed, 0 failed, 0.07s
  • cargo clippy --release -p mlxcel-core --lib --tests --features metal,accelerate -- -D warnings gives no warnings
  • cargo check --release --features metal,accelerate --example gumbel_sampling_microbench gives clean
  • rustfmt --edition 2024 --check on every touched Rust file, clean
  • python3 scripts/ci/check_cross_repo_refs.py, exit 0 (every #900 is a same-repo reference)

What the committed statistical tests actually draw. DEFAULT_SAMPLE_COUNT is 1000000 draws per goodness-of-fit test, overridable with MLXCEL_TEST_GUMBEL_SAMPLES. That is the committed default, not an opt-in and not an #[ignore]d variant: the whole module runs in well under a second because draws are accumulated 16384 rows per launch off one staged logits buffer. Shapes covered at temperature 1.0: peaked, flat, bimodal, -inf-masked (vocab 64 to 96), and a 4096-entry vocabulary that exercises the strided multi-sweep read loop. Temperature scaling is tested at 0.5 and 1.5 against the exact softmax at that temperature, on the bimodal shape (dividing the peaked shape by 0.5 leaves one cell above p = 0.99999 and nothing else testable, so it would have constrained almost nothing).

Acceptance threshold. Cells with probability exactly zero are asserted to draw zero samples and then excluded, since a zero-expectation cell has no chi-square term. The rest are sorted by probability and pooled greedily until each bin's expected count reaches 10, the standard fix for the sparse tail of a peaked distribution, with the trailing remainder folded into the last bin. The statistic is compared against the Wilson-Hilferty critical value at upper-tail p = 1e-6, so a correct implementation is expected to fail roughly once in a million runs per test. The threshold is computed in the test from the realised degrees of freedom rather than hard-coded from a table.

Other properties pinned. Masked tokens are never sampled at temperatures 0.5 / 1.0 / 1.5 while every surviving token is; the Gumbel noise never leaves its finite range (a separate hard-failure test, because a rare degenerate noise value perturbs an empirical frequency far below chi-square's resolution); a fixed seed reproduces an 8-launch token stream; the sampled index is invariant to the split count; fused_sample with no filter reproduces gumbel_max_sample exactly and does not reproduce fused_sample_categorical; all four filtered configurations (top-k, top-p, min-p, and all three together) stay bit-identical to the categorical path; greedy via temperature == 0 and via top_k == 1 both match argmax exactly; and with MLXCEL_SAMPLING_GUMBEL=0 the no-filter path reproduces fused_sample_categorical bit-for-bit and does not reproduce the kernel's stream.

What is NOT validated here, and where to look

  • The CUDA JIT string is unvalidated. This host is Apple Silicon with no CUDA hardware and no nvcc, so GUMBEL_MAX_SAMPLE_CUDA_SOURCE has never been compiled or run. It is written to be structurally parallel to the Metal source (same thread mapping, same Philox derivation, same halving-tree reduction, __umulhi for mulhi and logf for log), and the file says so at the declaration. It needs a GB10-class host before anyone should trust it.
  • No benchmark numbers. The microbenchmark is written but deliberately not run in this unit, because measurement is serialized elsewhere to avoid GPU contention from concurrent work. docs/benchmark_results/gumbel-sampling-<hw>-<date>.md is therefore absent rather than filled with numbers nobody took. The harness prints a table and accepts --csv PATH. No end-to-end decode throughput was measured either, so the issue's "no regression at batch 1, measurable improvement at batch 4" outcome is still open.
  • Watch for a contiguity copy during measurement. The launch requests a row-contiguous input. Decode never pays for it (slice_last_logits on the [B, 1, V] decode shape is already contiguous), but a batched first-token sample off a [B, S, V] prefill output with S > 1 and B > 1 is strided and costs one [B, V] copy. Documented at the declaration in sampling.h.
  • XTC is not gated in C++, by design. The issue's task 3 lists XTC alongside top-k/top-p/min-p, but the same task also states that XTC stays an untouched upstream pre-step, and fused_sample has no XTC parameter to gate on. XTC's entire effect is a -inf logit mask, which the kernel reproduces exactly, so sampling an XTC-filtered row through Gumbel-max is mathematically identical to sampling it through categorical. gumbel_sample_never_selects_masked_tokens and gumbel_sample_matches_softmax_with_masked_entries cover exactly that case, and config_supports_fused_batch still refuses XTC rows in the batched fast path as before. Gating on XTC instead would mean threading a flag through fused_sample and its six call sites; flagging the choice here so it is visible rather than silent.
  • The repository working-contract file is gitignored in this tree, so this kernel could not be added to its "re-validate after an MLX pin bump" checklist alongside sparse_v_sdpa and the delegated SDPA launchers. It belongs there: it is a runtime-JIT path that a breaking MLX API change could silently regress, and sampling_gumbel_tests:: is the check to run.

Closes #900

inureyes added 7 commits July 31, 2026 00:00
The fused sampler ends in `mlx::core::random::categorical`, which normalises over the whole vocabulary (32K-152K entries) once per token per row. The Gumbel-max identity removes that pass: adding i.i.d. Gumbel(0,1) noise to `logits / temperature` and taking the argmax draws exactly from `softmax(logits / temperature)`, so the sampling step collapses to one index-carrying max reduction with no softmax and no sort.

`src/lib/mlx-cpp/turbo/sampling.{h,cpp}` holds the launcher and both JIT strings, following the dual-source pattern in `paged_attention.cpp`. Noise is generated in-kernel by a stateless counter-based Philox-4x32-10 CBRNG keyed on `(row, element)`, so the sampled index is invariant to the launch shape; that is what lets the launcher split a row across up to 64 cooperating threadgroups (keeping a batch-1 launch wide) without perturbing the token stream. The Philox key itself is drawn from MLX's own thread-local key sequence, the same stream `categorical` consumes, so `ffi::random_seed` still reproduces a run exactly.

`fused_sample` routes to the kernel when temperature > 0 and no top-k / top-p / min-p filter narrows the support; greedy stays on `argmax`, and every filtered configuration keeps the existing graph path untouched. Token bias and XTC are upstream logit pre-steps that leave `-inf` masks, which the kernel reproduces exactly (a `-inf` entry stays `-inf` after the divide and the finite Gumbel add), so they need no gate. `MLXCEL_SAMPLING_GUMBEL=0` restores `categorical`, and the new `fused_sample_categorical` entry point exposes the pre-change path in-process for A/B benchmarking and parity tests.

`batched_sample` now dispatches the whole batch in one `batched_fused_sample` call when every row shares a fused-eligible scalar config, which on the no-filter path is a single batch-wide kernel launch (grid.z = B) instead of a per-row loop.

Sampled streams differ from the pre-change `categorical` streams at equal seeds: this is a different RNG consumer, not a different distribution. Greedy (temperature 0) output is unchanged.

Work in progress: statistical correctness tests, the sampling microbenchmark, and the CHANGELOG / env-var documentation follow in later commits.

Refs #900
The Gumbel-max kernel replaces `random::categorical` with a distributionally equivalent draw, not a bit-identical one, so correctness has to be established by goodness of fit rather than by comparison against a golden stream.

`src/lib/mlxcel-core/src/sampling_gumbel_tests.rs` runs a chi-square test of the empirical token frequencies against exact f64 softmax probabilities on peaked, flat, bimodal, `-inf`-masked, and large-vocabulary logits, at temperatures 0.5, 1.0, and 1.5. Cells whose probability is exactly zero are asserted to draw zero samples and then excluded; the rest are pooled by ascending probability until each bin's expected count reaches 10, which keeps the asymptotic approximation valid on a peaked tail. The threshold is the Wilson-Hilferty critical value at upper-tail p = 1e-6, so a correct implementation is expected to fail about once in a million runs per test. The draw count is `MLXCEL_TEST_GUMBEL_SAMPLES` (default 262144).

The same file pins that masked tokens are never selected at any temperature, that a fixed seed reproduces a whole token stream, that a row's sampled id does not move when the split heuristic changes the launch shape, that `fused_sample` reaches the kernel exactly when no filter is set, that every filtered configuration stays bit-identical to the categorical path, and that greedy (both `temperature == 0` and `top_k == 1`) matches `argmax`.

`tests/sampling_gumbel_kill_switch.rs` covers `MLXCEL_SAMPLING_GUMBEL=0`. The C++ gate resolves the variable into a process-static, so the test owns its own binary and holds exactly one test, which sets the variable before anything can resolve the static; it then asserts the no-filter path reproduces `fused_sample_categorical` bit-for-bit and does not reproduce the kernel's stream.

`examples/gumbel_sampling_microbench.rs` measures the sampling step alone across vocab {32K, 64K, 152K} x batch {1, 4, 8}, comparing the categorical baseline against the kernel by median-of-N with the GPU synchronized inside the timed region.

Documents the RNG stream change in `CHANGELOG.md` and the new `MLXCEL_SAMPLING_GUMBEL` switch in `docs/environment-variables.md`.

Refs #900
…tests

Both JIT sources selected the Philox output word by indexing a four-element thread-local array. The enclosing loop has a constant trip count but an early exit, which can stop the compiler from unrolling it; without the unroll the index is dynamic and the array falls out of registers into backing memory on both back-ends. Replaced with a ternary chain, which is register-resident either way.

Raises the committed goodness-of-fit draw count to 1000000 per test (the figure the issue asks for), overridable through MLXCEL_TEST_GUMBEL_SAMPLES, and caps rows-per-launch by total elements so a large-vocabulary shape does not stage a multi-hundred-megabyte buffer.

Switches the temperature-scaling test from the peaked shape to the bimodal one. Dividing an already sharp peak by 0.5 leaves a single cell above p = 0.99999 and nothing else above the pooling floor, so the test would have collapsed to two bins and constrained almost nothing; the bimodal shape keeps tens of cells testable at both 0.5 and 1.5.

Records the microbenchmark's memory mode (warm) and why warm is the representative mode for a sampling step, per the docs/benchmarks.md requirement that every recorded result state its mode.

Refs #900
… index

`src/lib/mlx-cpp/turbo/` no longer holds only TurboQuant kernels: paged-attention decode and now Gumbel-max sampling live there too, and each carries a Metal source plus a runtime-selected CUDA counterpart. The architecture bullet said "TurboQuant Metal kernels", which is no longer what a reader will find in that directory.

Also records where the Gumbel-max launcher's row-contiguity requirement can cost a copy (a `[B, S, V]` prefill output sampled at `S > 1` and `B > 1`) and why decode never pays it, so a future reader does not have to re-derive the stride analysis from `slice_last_logits`.

Refs #900
The kernel built its uniform as `((float)(word >> 8) + 0.5f) * 2^-24`, intending an open interval. It is not open at the top. For the single value `word >> 8 == 2^24-1` the addend lands on 16777215.5, which needs 25 mantissa bits; f32 in that binade has an ulp of 1, so it ties and rounds to 16777216, and `u` becomes exactly 1.0. Then `-log(-log(1.0))` is `-log(-0.0)`, which is positive infinity, and that element wins the argmax regardless of its logit.

The failure probability is 2^-24 per element, so it scales with the vocabulary: over a 152K-entry row that is roughly one uniformly-random token every 110 decode steps, which is a real output-quality defect rather than a theoretical corner. Against a `-inf` logit the candidate becomes NaN instead, which the comparison rejects, so the masking guarantee was never at risk.

Fixed by taking 23 bits instead of 24. An integer below 2^23 has an f32 ulp of at most 0.5, so `x + 0.5f` is exact for every value the expression can produce, and `u` is provably in `[2^-24, 1 - 2^-24]`. The noise range narrows from about [-2.9, 17.3] to [-2.9, 16.6]; the Gumbel tail mass outside that is 6e-8, which is far below anything the sampler resolves.

Adds `gumbel_noise_stays_inside_its_finite_range`, which the chi-square suite could not have caught: a stray sample every 2^-24 element draws perturbs an empirical frequency far below chi-square's resolution (the 64-entry tests saw about four such draws in a million and passed comfortably). The new test separates the logits by 100, which exceeds the entire finite noise range, so the argmax is unambiguous and a single wrong token is a hard failure. Over a 4096-entry vocabulary a million draws is 4.1e9 element draws, which at the old spelling would have hit the degenerate value about 244 times.

Refs #900
House style avoids em dashes in prose; the four in the test module's summary list are replaced with colons. No behavior or test logic changes.

Refs #900
`clippy::unusual_byte_groupings` rejects hex literals whose underscore groups are unequal, which the `0x5EED_900`-style seeds were. Padded to even 4-digit groups. Seed values change, which is immaterial: every test that uses them asserts a relation between two runs at the same seed, never a specific token id.

Refs #900
@inureyes inureyes added type:performance Performance improvements priority:high High priority area:inference Generation, sampling, decoding (incl. speculative, DRY) status:review Under review labels Jul 30, 2026
Adds the performance-validation report issue #900 requires. Op-level sampling is faster at every point of the vocab {32K, 64K, 152K} by batch {1, 4, 8} matrix, from 1.13x to 1.40x, and end-to-end decode at batch 1 on Qwen2.5-0.5B-Instruct-4bit is 361.8 tok/s against a 353.6 tok/s baseline, so the no-regression requirement is met with a 2.3 percent gain.

The shape of the op-level result is the substantive part. Baseline cost rises with both vocabulary and batch, 523.62us to 687.92us, because it normalizes over the vocabulary per row, while the Gumbel path stays between 429.50us and 491.79us across a 4.6x range of vocabulary and an 8x range of batch. Removing the vocabulary-sized work is what the issue set out to do, and it is why the advantage grows with batch rather than shrinking.

Records two shortfalls rather than reconciling them. The issue predicted at least 2x at batch 4 and above; the measured range there is 1.18x to 1.40x, real and consistent but short of the estimate. End-to-end at batch 4 was not measured at all, because `mlxcel generate` has no batch flag and it needs the server with concurrent clients, so that outcome stays open. CUDA remains uncompiled and unrun.
@inureyes inureyes added status:done Completed and removed status:review Under review labels Jul 30, 2026
@inureyes
inureyes merged commit 3f1387b into main Jul 30, 2026
4 checks passed
@inureyes
inureyes deleted the feature/issue-900-gumbel-max-sampling branch August 4, 2026 12:08
@inureyes inureyes self-assigned this Aug 31, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…ablup#970)

## Summary

The fused sampler ended in `mlx::core::random::categorical`, which normalises over the whole vocabulary (32K-152K entries) once per token per row. The Gumbel-max identity removes that pass: adding i.i.d. Gumbel(0,1) noise to `logits / temperature` and taking the argmax draws exactly from `softmax(logits / temperature)`, so the sampling step collapses to a single index-carrying max reduction with no softmax and no sort. This lands the kernel for the no-filter path, which is the simplest case and the one that validates the plumbing (dual-backend JIT strings, per-row RNG, batch-wide launch, statistical parity harness) before the rejection-based top-k/top-p work in lablup#901.

## What changed

- `src/lib/mlx-cpp/turbo/sampling.{h,cpp}` (new): the launcher and both JIT strings, following the dual-source pattern in `paged_attention.cpp`. One threadgroup of 256 threads handles one `(row, split)` pair; each thread owns 4 consecutive vocabulary entries per sweep and keeps a running `(value, index)` maximum, then a halving-tree reduction over threadgroup memory merges them. Noise is Philox-4x32-10 generated in-kernel and keyed on `(row, element)`, so element `i` of row `r` always draws `philox(key, {i >> 2, 0, r, 0})[i & 3]` regardless of thread count or split count.
- `src/lib/mlxcel-core/cpp/mlx_cxx_bridge.cpp`: `fused_sample` is refactored into `fused_sample_impl(..., allow_gumbel)`. The public `fused_sample` passes the resolved gate; the new `fused_sample_categorical` pins `allow_gumbel = false` and is the pre-change reference path, which is what lets the microbenchmark A/B both arms and the tests compare them inside one process. New entry points `gumbel_max_sample`, `sampling_gumbel_available`, and `gumbel_sample_num_splits`, all exposed through the cxx bridge.
- `src/lib/mlxcel-core/src/sampling.rs`: `batched_sample` dispatches the whole batch through one `batched_fused_sample` call when every row shares a fused-eligible scalar config (new `uniform_fused_batch_params` helper), which on the no-filter path is a single batch-wide kernel launch with `grid.z = B` instead of the per-row slice/sample/eval/readback loop. Any divergent or penalty-carrying row falls back to the existing loop.
- `src/lib/mlxcel-core/src/sampling_gumbel_tests.rs` (new): the statistical suite, described under Test plan.
- `tests/sampling_gumbel_kill_switch.rs` (new): the `MLXCEL_SAMPLING_GUMBEL=0` test, in its own binary because the C++ gate resolves the env var into a process-static.
- `examples/gumbel_sampling_microbench.rs` (new): the sampling-step microbenchmark over vocab {32K, 64K, 152K} x batch {1, 4, 8}.
- `CHANGELOG.md`, `docs/environment-variables.md`, `docs/architecture.md`: the RNG stream change, the new env switch, and a corrected description of what now lives under `src/lib/mlx-cpp/turbo/`.

## Design notes

**RNG derivation.** Each call draws one Philox key from `mlx::core::random::bits(Shape{2}, 4)`, which consumes MLX's default thread-local key sequence, the same stream `random::categorical` consumes. So `ffi::random_seed` still reproduces a run exactly, and one sampling call advances the shared state exactly once, the same way one `categorical` call does. The counter carries the `(row, element-group)` pair, so every element of every row gets an independent stream from that one key, with no per-element RNG state and no `[B, V]` uniform buffer materialised.

**Split heuristic and launch-shape invariance.** A `[1, 152064]` decode row is one reduction; without splitting, a batch-1 launch would occupy a single GPU core while the rest idle. `gumbel_num_splits` therefore spreads a small batch across up to 64 cooperating threadgroups (targeting 64 resident threadgroups overall) and collapses to 1 once the batch already fills the machine, in which case there is no second reduction pass at all. This is only safe because the noise is a pure function of `(key, row, element)`: the sampled index is provably identical under any split count, which `gumbel_sample_index_does_not_depend_on_the_launch_split` pins directly by comparing row 0 across a 32-split and a 1-split launch at the same seed.

**Gating.** The kernel is used when `temperature > 0` and none of top-k / top-p / min-p narrows the support, on a 2-D f32/f16/bf16 input, on a GPU default device with Metal or CUDA available. Greedy stays on `argmax`. Masked entries need no special handling: `-inf / T` is `-inf` and `-inf + finite_gumbel` is `-inf`, so a masked token can never win the argmax while any finite logit remains. That is why the uniform is built on the open interval `(0, 1)`: a `u` of exactly 0 or 1 makes the Gumbel infinite, which would both hand that element the argmax unconditionally and produce a NaN against a `-inf` logit. Commit `f48e388f` fixes a real instance of that (the 24-bit spelling ties `2^24 - 1 + 0.5f` up to `2^24` in f32 and lands on `u == 1.0`, roughly one uniformly-random token per 110 decode steps at a 152K vocabulary) and adds the regression test that catches it.

## Behavior change, please read

**Sampled token streams differ at equal seeds.** Gumbel-max and `categorical` consume the shared MLX key sequence differently, so a fixed seed no longer reproduces a stream recorded before this change on the no-filter stochastic path. The distribution is unchanged, which is what the chi-square suite establishes, and greedy decoding is byte-identical. Runs remain fully reproducible going forward (same seed, same backend, same stream). `MLXCEL_SAMPLING_GUMBEL=0` restores the exact previous path for anyone who needs to reproduce an older stream. Noted in `CHANGELOG.md` under Unreleased/Changed and in the `docs/environment-variables.md` row.

## Test plan

All run on Apple Silicon (M1 Ultra, Metal), against the final tree:

- [x] `cargo test --release -p mlxcel-core --lib --features metal,accelerate sampling_gumbel_tests::` gives 14 passed, 0 failed, 0.68s
- [x] `cargo test --release -p mlxcel-core --lib --features metal,accelerate sampling::` gives 54 passed, 0 failed, 0.44s (the pre-existing sampling suite, no regression)
- [x] `cargo test --release --features metal,accelerate --test sampling_gumbel_kill_switch` gives 1 passed, 0 failed, 0.07s
- [x] `cargo clippy --release -p mlxcel-core --lib --tests --features metal,accelerate -- -D warnings` gives no warnings
- [x] `cargo check --release --features metal,accelerate --example gumbel_sampling_microbench` gives clean
- [x] `rustfmt --edition 2024 --check` on every touched Rust file, clean
- [x] `python3 scripts/ci/check_cross_repo_refs.py`, exit 0 (every `lablup#900` is a same-repo reference)

**What the committed statistical tests actually draw.** `DEFAULT_SAMPLE_COUNT` is 1000000 draws per goodness-of-fit test, overridable with `MLXCEL_TEST_GUMBEL_SAMPLES`. That is the committed default, not an opt-in and not an `#[ignore]`d variant: the whole module runs in well under a second because draws are accumulated 16384 rows per launch off one staged logits buffer. Shapes covered at temperature 1.0: peaked, flat, bimodal, `-inf`-masked (vocab 64 to 96), and a 4096-entry vocabulary that exercises the strided multi-sweep read loop. Temperature scaling is tested at 0.5 and 1.5 against the exact softmax at that temperature, on the bimodal shape (dividing the peaked shape by 0.5 leaves one cell above p = 0.99999 and nothing else testable, so it would have constrained almost nothing).

**Acceptance threshold.** Cells with probability exactly zero are asserted to draw zero samples and then excluded, since a zero-expectation cell has no chi-square term. The rest are sorted by probability and pooled greedily until each bin's expected count reaches 10, the standard fix for the sparse tail of a peaked distribution, with the trailing remainder folded into the last bin. The statistic is compared against the Wilson-Hilferty critical value at upper-tail p = 1e-6, so a correct implementation is expected to fail roughly once in a million runs per test. The threshold is computed in the test from the realised degrees of freedom rather than hard-coded from a table.

**Other properties pinned.** Masked tokens are never sampled at temperatures 0.5 / 1.0 / 1.5 while every surviving token is; the Gumbel noise never leaves its finite range (a separate hard-failure test, because a rare degenerate noise value perturbs an empirical frequency far below chi-square's resolution); a fixed seed reproduces an 8-launch token stream; the sampled index is invariant to the split count; `fused_sample` with no filter reproduces `gumbel_max_sample` exactly and does not reproduce `fused_sample_categorical`; all four filtered configurations (top-k, top-p, min-p, and all three together) stay bit-identical to the categorical path; greedy via `temperature == 0` and via `top_k == 1` both match `argmax` exactly; and with `MLXCEL_SAMPLING_GUMBEL=0` the no-filter path reproduces `fused_sample_categorical` bit-for-bit and does not reproduce the kernel's stream.

## What is NOT validated here, and where to look

- **The CUDA JIT string is unvalidated.** This host is Apple Silicon with no CUDA hardware and no `nvcc`, so `GUMBEL_MAX_SAMPLE_CUDA_SOURCE` has never been compiled or run. It is written to be structurally parallel to the Metal source (same thread mapping, same Philox derivation, same halving-tree reduction, `__umulhi` for `mulhi` and `logf` for `log`), and the file says so at the declaration. It needs a GB10-class host before anyone should trust it.
- **No benchmark numbers.** The microbenchmark is written but deliberately not run in this unit, because measurement is serialized elsewhere to avoid GPU contention from concurrent work. `docs/benchmark_results/gumbel-sampling-<hw>-<date>.md` is therefore absent rather than filled with numbers nobody took. The harness prints a table and accepts `--csv PATH`. No end-to-end decode throughput was measured either, so the issue's "no regression at batch 1, measurable improvement at batch 4" outcome is still open.
- **Watch for a contiguity copy during measurement.** The launch requests a row-contiguous input. Decode never pays for it (`slice_last_logits` on the `[B, 1, V]` decode shape is already contiguous), but a batched first-token sample off a `[B, S, V]` prefill output with `S > 1` and `B > 1` is strided and costs one `[B, V]` copy. Documented at the declaration in `sampling.h`.
- **XTC is not gated in C++, by design.** The issue's task 3 lists XTC alongside top-k/top-p/min-p, but the same task also states that XTC stays an untouched upstream pre-step, and `fused_sample` has no XTC parameter to gate on. XTC's entire effect is a `-inf` logit mask, which the kernel reproduces exactly, so sampling an XTC-filtered row through Gumbel-max is mathematically identical to sampling it through `categorical`. `gumbel_sample_never_selects_masked_tokens` and `gumbel_sample_matches_softmax_with_masked_entries` cover exactly that case, and `config_supports_fused_batch` still refuses XTC rows in the batched fast path as before. Gating on XTC instead would mean threading a flag through `fused_sample` and its six call sites; flagging the choice here so it is visible rather than silent.
- **The repository working-contract file is gitignored in this tree**, so this kernel could not be added to its "re-validate after an MLX pin bump" checklist alongside `sparse_v_sdpa` and the delegated SDPA launchers. It belongs there: it is a runtime-JIT path that a breaking MLX API change could silently regress, and `sampling_gumbel_tests::` is the check to run.

Closes lablup#900
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) priority:high High priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Softmax-free GPU sampling: Gumbel-max categorical sampling kernel

1 participant