Skip to content

lanes sampling: a keyed draw that cuts nothing by rank finds the sorted draw's token in one pass - #1337

Closed
ajensenwaud wants to merge 1 commit into
ashhart:mainfrom
ajensenwaud:lanes-sampler-no-sort
Closed

ajensenwaud wants to merge 1 commit into
ashhart:mainfrom
ajensenwaud:lanes-sampler-no-sort

Conversation

@ajensenwaud

Copy link
Copy Markdown
Contributor

What this changes

lanes.sampling.choose already selects only the top k candidates when 0 < top_k <= width / 2. In every other
case it still runs a stable std.mem.sort over the whole row: with top_k off, which is the server default
(top_k 0, top_p 1.0), and with top_k at or above the width. On a 200K-entry vocabulary that sort is most of the
cost of a host draw.

When neither top_k nor top_p cuts anything, choose now runs race (in core/lanes/sampling.zig). It is one
pass over the row in id order and returns exactly the token chooseOrdered would draw from the sorted order:

  • Same arithmetic. Each candidate gets the same keyed uniform, -log(-log(u)) and value / t, with
    t = max(temperature, 1e-6).
  • Same tie rule. A higher score wins. On an exactly equal score, the candidate the sort puts first wins (higher
    value, then the lower id).
  • Same min_p cut. The floor is max / t + ln(min_p), as chooseOrdered computes it. Every value / t at or
    above the floor is a prefix of the sorted order, so filtering in id order keeps the same set. When min_p keeps
    nothing, the result is the greedy first candidate, as the sorted loop returns order[0]. min_p on costs one
    extra max pass, still with no sort.
  • Skipped logs. Before taking the logs, a candidate whose noise provably cannot reach the lead's score is skipped.
    Such a candidate scores strictly below the lead, so skipping it changes no result. The proof: a uniform below
    exp(-exp(-(d - 0.5))) has Gumbel noise under d - 0.5, and with both scores within 1e6, rounding stays far
    inside that 0.5 margin.
  • Fallbacks to the unchanged sorted path:
    • temperature <= 0 or NaN (the greedy path is unchanged);
    • 0 < top_k < width;
    • 0 < top_p < 1;
    • any value / t that is not finite. This includes NaN and infinite logits, matching how selection.topK
      returns null for nonfinite rows.

The partial top-k path, chooseOrdered, sampling_selection.zig and the reference are unchanged.
keyBits/uniform are refactored to share keyBase/uniformOf; the operations and bits are the same.

This replaces the old patch 0060 (chooseAll/race). The Muse-specific f32 chooseRow entry is not part of this
PR.

Receipt

  • Environment: up/main 2ff0191 + this commit, Zig 0.17.0, x86_64 Linux host.
  • Exactness: the drawn token is identical by construction, and the tests check it against
    sampling_reference.choose (the full stable sort plus chooseOrdered). No bits change.
  • Decode speed: the same algorithm on the Muse Spark Open engine (202K vocabulary, two GB10s, 1 stream,
    temperature 1.0, top_k 0) took decode from 14.7 to 23.2 tok/s with its drafter and from 13.3 to 18.2 without it,
    same tokens. Device samplers are untouched. A cross-family A/B on Metal and CUDA is welcome.
  • Prompt speed before and after: n/a. Prompt processing does not draw.
  • Tests added (zig/src/core/lanes/sampling_race_test.zig, 94 lines, imported from sampling.zig's test block):
    • The draw equals the full-sort reference over 18,144 draws:
      • widths 1, 2, 3, 65, 1000 and 4096;
      • shapes: normal, quarter-step ties, flat ±0.0, wide (×40, which exercises the skip), huge (×1e303,
        overflowing at tiny temperatures, which exercises the fallback) and repeated ids;
      • temperatures from 1e-9 to inf;
      • min_p 0, 0.05, 0.5, 1, 1.5 and NaN;
      • top_p 0, 1, 1.5 and NaN;
      • top_k 0, width and maxInt(u32);
      • random seeds and positions.
    • One row draws the same token as the reference at 4,000 positions.
    • A draw with no rank cut allocates nothing (FailingAllocator with fail_index = 0). This fails before the
      change, when the sort allocated. A rank cut (top_k = width - 1), a top_p cut and a NaN row still sort,
      which shows up as OOM under the failing allocator.
    • Every skip bound's largest skipped uniform has Gumbel noise more than 0.4 under its gap.
    • The existing sampling_selection_test.zig draws (reference.choose vs choose over filters including
      top_k 0/maxInt and top_p 0/1) now also exercise the new path.
  • Lean check: python3 tools/zig/lean_check.py reports 435 problems on up/main and 435 on this branch, so there
    are 0 new findings, all inherited.
  • git diff --check: clean.
  • Tests run: zig test -lc zig/src/core/lanes/sampling.zig 14/14 passed (4 new); zig build test-cuda-host passed on a branch carrying this commit.
  • Not run: Metal; tests/lanes_units.zig's Python-golden draws.

Checklist

  • Every token still goes through the lane rounds. No serial path, and nothing that needs drafts off.
  • Drafted output equals "draft": false, a resumed prompt equals a fresh one, and concurrent equals solo. (The
    drawn token is unchanged for every key.)
  • No precision traded for speed. No bits change: same f64 arithmetic and libm calls per candidate.
  • A new or changed GPU kernel is registered with the kernel contract. (None.)
  • Prompt processing is no slower than the last release. (Not reached.)
  • The description says which platforms I ran, Metal M1 to M5 and CUDA, and which I could not. (x86_64 host; Metal not run.)
  • New tests fail before the change, pass after it, and skip cleanly without their dependency. (The allocation
    test is the before/after one.)
  • Comments and docstrings are one line. No measurements or history in the source.
  • No personal data, machine names, internal hosts or local paths. No AI attribution lines.

…ed draw's token in one pass over the row

With top_k off (or at least the row width) and top_p off, choose no longer sorts the whole vocabulary. One pass draws
the same Gumbel race in id order, a tied score going to the candidate the sort would put first; min_p keeps the same
prefix of the sorted order, and a candidate whose noise cannot reach the lead's score skips its logs. Nonfinite rows,
rank cuts and top_p cuts keep the full sort, and the partial top-k path is unchanged. Tests compare the draw with the
full-sort reference over widths, shapes with ties and duplicate ids, temperatures, filters and keys, and check that
the draw allocates nothing.
@kesslerio

Copy link
Copy Markdown

M5 Ultra Metal validation of head 12110e2b486e623e0237d37d714a820714bdf9ce, tracked in #1345. The unfiltered sampler speedup carries over to DeepSeek-V4.1 on Metal with matching full token hashes.

Case Baseline total tok/s Candidate total tok/s Ratio
greedy-code 119.2 119.4 1.00x
sampled-plain-code 38.1 58.7 1.54x
sampled-drafted-code 46.2 89.4 1.93x
sampled-concurrent-code 54.2 103.6 1.91x
sampled-prose 37.0 59.0 1.59x
filtered-control 49.8 49.6 0.99x

Environment: Apple M5 Ultra, 256 GiB, macOS 27.0 (26A425), Zig 0.17.0. Same BobClawblaw/DeepSeek-V4.1-Flash-1017-TensorFold-e2e3-p4-h8 checkpoint, revision 9012d3064675de44630c529f496e4961b30a73a4, with unchanged weights/tokenizer.

This is a validation backport, not a full build/test of the PR branch: baseline is the existing DeepSeek Metal engine 72a552ed09f5962379261e429552d83955cb37ad. Candidate changes only its shared sampler by copying five files byte-for-byte from this PR head: sampling.zig, sampling_race_test.zig, sampling_selection.zig, sampling_selection_test.zig, and sampling_reference.zig. This includes the upstream greedy/top-k selection helpers required by the PR sampler. No Metal kernel or model change.

Method: A0 baseline → B0 candidate → B1 candidate → A1 restored baseline, one resident model at a time. Two observations per cell per binary, three configured lanes, warm approximately 8k-token synthetic code/prose prompts, 256 output-token cap, thinking off, fixed seeds. Sampled requests use temperature 1, top-k 0, min-p 0, top-p 1; the filtered control uses top-p 0.95. Code task is a Python LRU implementation/tests; prose is an engineering update from fixed synthetic facts. Total decode counts output tokens minus the first token per request over the shared streamed-output window, averaged over two arms. These are short controlled fixtures, not coding-quality or capacity qualification.

Exactness: all eight cell/fixture groups have identical request payload SHA-256, full tensorfold.token_sha256, and completion lengths across all four arms: 32/32 measured replies matched. Unfiltered sampled code also matches across draft-off, draft-on and concurrent cases where paired. No top_k=20 shortcut was used. The greedy and filtered controls show no material speed change.

Checks run on the Mac:

  • zig test -lc zig/src/core/lanes/sampling.zig: 14 passed, 0 failed.
  • The new no-rank-cut allocation regression against the old sampler: fails with OutOfMemory, as expected before the change.
  • zig build native -j2 -Dcpu=native -Dversion=1.1.1 --summary all: exit 0.
  • git diff --check: clean.

Not run: full upstream host/golden/kernel suites, CUDA, other Apple chips, cold 2k/32k/64k prefill gates, or broad agent-quality evaluation. Prompt-processing arithmetic is unchanged, but I am not claiming a measured cold-prefill improvement. The original baseline was restored and verified afterward; this is not a production rollout.

@ashhart ashhart mentioned this pull request Oct 26, 2026
6 tasks done
@ashhart

ashhart commented Oct 26, 2026

Copy link
Copy Markdown
Owner

Landed on main in e929a71, thanks @ajensenwaud. We added 4577a1a on top: a host test that pins keyBits to main's original formula and compares choose with main's full sort + chooseOrdered over 483,840 sampler settings, including forced exact score ties, min_p floors, subnormals and values near the skip guard. It catches tie-order, key-order and guard-removal bugs the PR's own tests let through. Device check on M3 Ultras (Qwen3.8-27B, Nemotron), main vs this, sampled at temperature 1.0 with top_k 0 / top_p 1 and min_p 0 and 0.05: every token row identical, prefill flat.

@ajensenwaud

Copy link
Copy Markdown
Contributor Author

Thanks a lot.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants