Skip to content

lanes: the host GPU-rule sampler keeps its best 1,024 candidates in a bounded heap, not a full sort - #4744

Merged
ashhart merged 4 commits into
ashhart:mainfrom
BlivionIaG:perf/sampler-top-candidates
Nov 24, 2026
Merged

ashhart merged 4 commits into
ashhart:mainfrom
BlivionIaG:perf/sampler-top-candidates

Conversation

@BlivionIaG

@BlivionIaG BlivionIaG commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

The host sampler behind Flint, Llama, Kimi K3 and MiniMax-M3 (gpu_rule.sample, gpu_full.plan) sorted every scaled logit of a row to read the first 1,024; on a 201,058-token vocabulary that sort is 15 ms of a draw that takes 0.11 ms without it. rule.topCands now keeps those candidates in a bounded heap with an early reject and sorts only them. The order is total (key, then id, ids are unique), so the kept prefix, the row maximum and every drawn token are the full sort's bit for bit; the row-order normalizer is summed only when top_k is off, and a top_k above 1,024 still sorts for its kth candidate.

Checks on this head

  • Head commit: 93dbe31f40
  • Lean checker, base and head: 165 and 165, 0 new. zig fmt --check build.zig zig clean; tools/pr_check.py --base upstream/main: 0 errors, 1 advisory (asks for --pr NUMBER).
  • Tests run (-Dcpu=apple_m1, Debug): zig build test test-golden: 995/995 steps, 17048/17193 tests passed, 145 skipped, exit 0; zig build dev-tools: 307/307 steps. Sampler steps by themselves: test-shared-lane-regressions-host 487 pass, 1 skip (includes gpu_full_test and the new gpu_top_test); test-lanes-topk-host 5/5; test-dsv41-draft 180/180; test-qwen27-draws-host 6/6; test-flashnext-{constraint,draw,nonfinite,penalties,vision-contracts}-host 12, 44, 38, 16, 15 pass; test-kimi-serving-host 54/54; test-k3 28/28; test-flint-draft-host 80/80; test-minimax-m3-metal-steps-host 5/5; test-minimax-info-host 1/1; test-llama-controls-host 2/2; test-glm-sampling every row PASS; tf-nemotron-sample-check (GPU, M4 Pro): 20 of 20 row groups match, "all draws match".
  • CI: not yet run.
  • Spark-X2.6-4B (spark2_5 Metal engine, which reaches the changed code on main): 672 of 672 seeded request pairs, main against main plus this branch, equal token ids, including full-vocabulary, wide top_k, structured-output and required-tool requests, at 1 and 4 streams (comment 7126475411 replies; commands and client in the comment below it).
  • Not run, and why: CUDA and HIP paths (no device here); Flint, Llama, Kimi K3 and MiniMax-M3 (no local checkpoint); presence and frequency penalties (the Metal engine refuses them); timings on any family but Inkling.

Receipt

  • Main against branch: the new test compares topCands, rule.sample and full.plan with a full-sort reference, bit for bit (prefix, maximum, normalizer, plan, draws) on 12 row kinds (ties, signed zeros, NaN, infinities, extremes, ramps, all -inf), 4 temperatures and 9 top_k/top_p/min_p rules, plus 201,058-token rows; breaking the tie rule fails all three tests.
  • Boxes it reaches: every Metal and host family that draws through gpu_rule or gpu_full; no kernel, no new switch, no weights.
  • Environment: M4 Pro 48 GiB, Zig 0.17.0, Inkling-2-Mini ed40e7da625f594fc9c4990f5f66be24873c22d7, --context 8192 --parallel 4 --prompt-cache-gib 0 --no-thinking; A and B are the Inkling 2 Mini Metal branch (Metal: experimental Inkling 2 Mini text, vision and bundled DSpark #4337) before and after this commit (the only server here that draws 201,058-token rows through this code).
  • Independent run, M5 Ultra (@SashaMIT, Metal: experimental Inkling 2 Mini text, vision and bundled DSpark #4337 comment 7123893220; base 7f4d175c3d, with this PR at eaa9e41a6a, T 0.7, seed 1234, --alone --serial, --parallel 4 --prompt-cache-gib 0, fresh server per block, quiet Mac; --alone and --serial all equal, 0 failed): plain sampled code 34.8 to 57.5 tok/s at 1 stream and 51.0 to 107.9 at 4; DSpark sampled code 33.4 to 62.0 and 34.5 to 139.6; DSpark chat 34.4 to 65.4 and 50.0 to 140.2; the p95 round gap of DSpark at four code streams 397 to 69 ms.
  • Exactness: 160 seeded requests (seeds 1 to 8, T 0.7 and 1.0, ten top_k/top_p/min_p variants, 48 tokens) return identical token ids on A and B (160/160, 7,680 ids); bench_concurrent --alone --serial --temperatures 0.7: 30/30 equal alone and 16/16 equal to "draft": false on plain and DSpark, 0 unequal; greedy chat_hashes unchanged.
  • Decode speed, A-B-B-A, aggregate tokens a second, bench_concurrent --levels 1,4 --tokens 256 --reps 3 --temperatures 0.7: plain sampled code 1 stream 21.2 to 29.2, 4 streams 33.5 to 56.1 (chat 21.5 to 28.6, 33.6 to 56.5); greedy unchanged (code 29.0 and 28.9 at 1 stream, 66.8 and 66.7 at 4); DSpark sampled code 19.9 to 29.4, 25.9 to 52.9.
  • Prompt speed: n/a, the change is on the decode path after the last prompt row. Other families' timings were not measured.
  • Licence of new weights or drafter: n/a.

Checklist

  • Title and description match the head commit; [x] comments are one line and carry no measurements; [x] no personal data or AI attribution.
  • Token ids, hashes, concurrent-equals-solo and drafted-equals-plain are unchanged; no precision traded, no arithmetic changed.

BlivionIaG added a commit to BlivionIaG/TensorFold that referenced this pull request Nov 23, 2026
- The host sampler's full sort is the cost; ashhart#4744 keeps only the best 1,024 candidates with identical tokens.
BlivionIaG added a commit to BlivionIaG/TensorFold that referenced this pull request Nov 23, 2026
@BlivionIaG
BlivionIaG marked this pull request as ready for review November 23, 2026 21:44
@BlivionIaG

Copy link
Copy Markdown
Contributor Author

CI result for eaa9e41a6a: all 10 checks passed (fmt, pytest, zig, zig-b, zig-windows, zig-macos-dev-tools, benchmark-clients on Ubuntu and Windows, release-paths, comfyui-moss-installer). main moved meanwhile, so the head is now 93dbe31f40, a merge of main whose one conflict was two test imports in zig/src/core/lanes/lanes.zig (kept both); it builds with -Dcpu=apple_m1 -Doptimize=ReleaseFast and CI is running again on it.

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thank you, @BlivionIaG. The heap keeps the same candidate order, including equal values and signed zeros, and the wide top-k case still uses the full sort. The new tests compare the kept candidates, normalizer, plans and draws with the earlier algorithm. I found no blocking source defect.

The posted token and timing results are useful. What's left is a sampled comparison on current main: the same seeded requests on main and on this branch, including a structured-output or required-tool request (those take the host draw) and a full-vocabulary case, with equal generated token IDs. Any model that serves on main works; please post it with the commands you ran. The earlier CI result belongs to the previous head. There is one mechanical changelog conflict with current main; we can handle it here.

  • Synthena

@BlivionIaG

Copy link
Copy Markdown
Contributor Author

Thank you, @ashhart. The comparison you asked for, on a model that serves on current main and reaches the changed code: 672 of 672 request pairs have identical generated token ids on main and on main plus this branch, 0 unequal, 0 errors.

Model. XHToken/Spark-X2.6-4B at 66e3ae7bee54e0a523d692cb8ef841f35409807b (bf16, 131,072-token vocabulary), served by the spark2_5 Metal engine, which calls gpu_full.draw from spark25/metal_backend.zig. I read which engines reach topCands, rule.sample and gpu_full.plan before choosing it: the other checkpoints I have locally (LFM3, LFM2-MoE, Nemotron, Qwen3.5 and 3.8) do not call the changed functions on main (Qwen draws through lanes.sampling_row), and I have no checkpoint for Flint, Llama, Kimi K3 or MiniMax-M3, so those are not run. On Spark the host draw runs on the first token of every request, on every token under a grammar, and on verify windows; plain decode after the first token runs the GPU kernel this PR does not change.

Builds. A = ea37382cb1 (main, untouched). B = 73d746f1d4 (main plus perf/sampler-top-candidates; the only conflict was the changelog, both bullets kept). Zig 0.17.0, M4 Pro:

zig build native -Dcpu=apple_m1 -Doptimize=ReleaseFast                  # in each tree
zig build grammar -Dxgrammar=<xgrammar v0.2.8 checkout> -Dcpu=apple_m1  # one libtfgrammar, copied beside both binaries

Per run (a fresh server each, one client pass, one server at a time):

tensorfold-native serve <snapshot> --host 127.0.0.1 --port 8190 --context 4096 --parallel {1|4} --prompt-cache-gib 0
python3 sv-client.py run http://127.0.0.1:8190/v1 sv-{A|B}.json {p1|p4} {1|4}    # 48 tokens, seeded, stream:false, return_token_ids
python3 sv-client.py diff sv-A.json sv-B.json

p1 is --parallel 1 with one worker, p4 is --parallel 4 with four concurrent clients. Token ids are the reply's tensorfold.token_ids. The client is below.

Requests (336 per pass), A against B, request by request:

class what --parallel 1 --parallel 4
plain the earlier set: seeds 1 to 8, T 0.7 and 1.0, ten top_k/top_p/min_p variants, including top_k 0 with top_p 1 (full vocabulary), top_k 0 with top_p 0.9 and top_k 1500 160/160 equal 160/160
wide top_k 2000 and 5000; top_k 0 with top_p 0.5 and min_p 0.01 32/32 32/32
grammar_free guided_regex "[\s\S]*" under the same ten variants, so every token is a host draw 80/80 80/80
json_schema response_format json_schema 16/16 16/16
json_object response_format json_object 16/16 16/16
tool_required tool_choice: "required" 16/16 16/16
tool_named tool_choice naming get_weather 16/16 16/16

All 64 grammar-routed replies are valid JSON or valid tool calls (libtfgrammar loaded, "xgrammar over 131072 tokens"). Within each build the 4-stream ids equal the 1-stream ids (336 of 336 on A and on B), and each grammar_free request equals the same plain request (80 of 80 on both), as it should when the mask allows everything.

What this does not cover.

  • Only 55 of the 160 plain replies are distinct, on both builds: two prompts, and the keyed draw makes many variants choose the same tokens.
  • The rows above the 1,024 cap (top_k 1500, 2000, 5000) are covered on the host-drawn tokens only: the first token, or every token for grammar_free.
  • Presence and frequency penalties are refused by the Metal engine with HTTP 400 (not supported by backend 'metal'), so there is no penalty class here.
  • No speed row: the Mac was loaded (load 2.6 to 4.8) and swap was 14 of 15 GB used, so I do not post timings. The earlier A-B-B-A rows (Inkling) stand.
sv-client.py
"""Record the reply token ids of a fixed set of seeded, sampled requests, and compare two recordings.

  python3 sv-client.py run http://127.0.0.1:8190/v1 out.json LABEL WORKERS [MAX_TOKENS]   # adds out.json[LABEL]
  python3 sv-client.py diff a.json b.json                                                  # per class, per label

Token ids come from `return_token_ids` (the reply's `tensorfold.token_ids`). Every request carries a `seed`.
Classes: plain (the 160-request set: seeds 1-8, T 0.7 and 1.0, ten top_k/top_p/min_p variants), wide (top_k past the
1,024-candidate cap, and 0 with top_p < 1 / min_p), json_schema, json_object, tool_required, tool_named, and
grammar_free (guided_regex [\\s\\S]*: any text, so every token is drawn by the host sampler under the ten variants).
Penalties are refused by the Metal engine (HTTP 400), so no penalty class.
"""
import json
import sys
import threading
import time
import urllib.request

PROMPTS = [
    "Write a short Python function that computes the Fibonacci sequence and explain it.",
    "Explain how matrix multiplication uses a GPU in plain English, then give a small numerical example.",
]
VARIANTS = [
    {},
    {"top_k": 20, "top_p": 0.95},
    {"top_k": 0, "top_p": 1.0},
    {"top_k": 0, "top_p": 0.9},
    {"top_k": 50, "top_p": 1.0},
    {"top_k": 1024, "top_p": 0.9},
    {"top_k": 1500, "top_p": 0.95},
    {"top_k": 20, "top_p": 0.95, "min_p": 0.05},
    {"top_k": 0, "top_p": 1.0, "min_p": 0.02},
    {"top_k": 1},
]
WIDE = [
    {"top_k": 2000, "top_p": 1.0},
    {"top_k": 5000, "top_p": 0.8},
    {"top_k": 0, "top_p": 0.5, "min_p": 0.01},
    {"top_k": 0, "top_p": 1.0, "min_p": 0.0},
]
SCHEMA = {"type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "integer"},
                                           "city": {"type": "string"}},
          "required": ["name", "age", "city"], "additionalProperties": False}
TOOLS = [{"type": "function", "function": {
    "name": "get_weather", "description": "Get the current weather for a city",
    "parameters": {"type": "object", "properties": {"city": {"type": "string"},
                                                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}},
                   "required": ["city"]}}}]
BASE = {"model": "m", "stream": False, "return_token_ids": True, "chat_template_kwargs": {"enable_thinking": False}}


def requests(max_tokens):
    out = []

    def add(cls, name, body):
        b = dict(BASE)
        b.update(body)
        out.append((cls, f"{cls}|{name}", b))

    for seed in range(1, 9):
        for temp in (0.7, 1.0):
            for v, variant in enumerate(VARIANTS):
                body = {"max_tokens": max_tokens, "temperature": temp, "seed": seed, "ignore_eos": True,
                        "presence_penalty": 0, "frequency_penalty": 0,
                        "messages": [{"role": "user", "content": PROMPTS[(seed + v) % 2]}]}
                body.update(variant)
                add("plain", f"seed={seed} T={temp} {json.dumps(variant, sort_keys=True)}", body)
    for seed in range(1, 5):
        for temp in (0.7, 1.0):
            for variant in WIDE:
                body = {"max_tokens": max_tokens, "temperature": temp, "seed": seed, "ignore_eos": True,
                        "messages": [{"role": "user", "content": PROMPTS[seed % 2]}]}
                body.update(variant)
                add("wide", f"seed={seed} T={temp} {json.dumps(variant, sort_keys=True)}", body)
    for seed in range(1, 9):
        for temp in (0.7, 1.0):
            msg = [{"role": "user", "content": "Invent a person and give their name, age and city as JSON."}]
            add("json_schema", f"seed={seed} T={temp}", {
                "max_tokens": 96, "temperature": temp, "seed": seed, "messages": msg,
                "response_format": {"type": "json_schema", "json_schema": {"name": "person", "schema": SCHEMA, "strict": True}}})
            add("json_object", f"seed={seed} T={temp}", {
                "max_tokens": 96, "temperature": temp, "seed": seed,
                "messages": [{"role": "user", "content": "Return a JSON object describing an invented person with name, age and city."}],
                "response_format": {"type": "json_object"}})
            q = [{"role": "user", "content": "What is the weather like in Paris, and what in Tokyo? Use the tool."}]
            add("tool_required", f"seed={seed} T={temp}", {
                "max_tokens": 96, "temperature": temp, "seed": seed, "messages": q, "tools": TOOLS, "tool_choice": "required"})
            add("tool_named", f"seed={seed} T={temp}", {
                "max_tokens": 96, "temperature": temp, "seed": seed, "messages": q, "tools": TOOLS,
                "tool_choice": {"type": "function", "function": {"name": "get_weather"}}})
    for seed in range(1, 5):
        for temp in (0.7, 1.0):
            for v, variant in enumerate(VARIANTS):
                body = {"max_tokens": max_tokens, "temperature": temp, "seed": seed, "ignore_eos": True,
                        "guided_regex": "[\\s\\S]*",
                        "messages": [{"role": "user", "content": PROMPTS[(seed + v) % 2]}]}
                body.update(variant)
                add("grammar_free", f"seed={seed} T={temp} {json.dumps(variant, sort_keys=True)}", body)
    return out


def check(cls, msg, finish):
    """A structured / tool reply must really be one: valid JSON with the keys, or a tool call."""
    if cls in ("json_schema", "json_object"):
        try:
            v = json.loads(msg.get("content") or "")
        except ValueError:
            return False
        return isinstance(v, dict) and (cls == "json_object" or set(v) == {"name", "age", "city"})
    if cls in ("tool_required", "tool_named"):
        calls = msg.get("tool_calls") or []
        return bool(calls) and all(c["function"]["name"] == "get_weather" and isinstance(json.loads(c["function"]["arguments"]), dict) for c in calls)
    return True


def run(base, path, label, workers, max_tokens):
    todo = requests(max_tokens)
    got = {}
    lock = threading.Lock()
    cursor = [0]
    t0 = time.time()

    def work():
        while True:
            with lock:
                i = cursor[0]
                cursor[0] += 1
            if i >= len(todo):
                return
            cls, name, body = todo[i]
            req = urllib.request.Request(base + "/chat/completions", data=json.dumps(body).encode(),
                                         headers={"Content-Type": "application/json"})
            try:
                with urllib.request.urlopen(req, timeout=3600) as r:
                    raw = json.loads(r.read())
                msg = raw["choices"][0]["message"]
                fin = raw["choices"][0]["finish_reason"]
                rec = {"class": cls, "ids": raw["tensorfold"]["token_ids"], "finish": fin, "valid": check(cls, msg, fin),
                       "sha": raw["tensorfold"].get("token_sha")}
            except urllib.error.HTTPError as e:
                rec = {"class": cls, "error": f"HTTP {e.code}: {e.read()[:200].decode(errors='replace')}"}
            except Exception as e:  # recorded, not hidden: a failed request is a result
                rec = {"class": cls, "error": repr(e)[:200]}
            with lock:
                got[name] = rec

    threads = [threading.Thread(target=work) for _ in range(workers)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    try:
        data = json.load(open(path))
    except (OSError, ValueError):
        data = {}
    data[label] = got
    json.dump(data, open(path, "w"), indent=0, sort_keys=True)
    ok = [v for v in got.values() if "ids" in v]
    print(f"{label}: {len(got)} requests, {len(ok)} answered, {sum(len(v['ids']) for v in ok)} ids, "
          f"{sum(1 for v in got.values() if 'error' in v)} errors, {sum(1 for v in ok if not v['valid'])} invalid, "
          f"{time.time() - t0:.0f}s -> {path}")


def diff(a, b):
    x, y = json.load(open(a)), json.load(open(b))
    bad = 0
    for label in sorted(set(x) | set(y)):
        xa, ya = x.get(label, {}), y.get(label, {})
        rows = {}
        for k in sorted(set(xa) | set(ya)):
            p, q = xa.get(k), ya.get(k)
            cls = (p or q)["class"]
            r = rows.setdefault(cls, [0, 0, 0, 0])  # requests, equal, unequal, errored/invalid
            r[0] += 1
            if not p or not q or "ids" not in p or "ids" not in q:
                r[3] += 1
                print("ERR", label, k, (p or {}).get("error"), (q or {}).get("error"))
            elif p["ids"] == q["ids"] and p["finish"] == q["finish"]:
                r[1] += 1
            else:
                r[2] += 1
                print("DIFF", label, k, len(p["ids"]), len(q["ids"]))
        for cls, r in sorted(rows.items()):
            print(f"{label:6} {cls:14} requests {r[0]:4}  equal {r[1]:4}  unequal {r[2]:3}  missing/error {r[3]:3}")
            bad += r[2] + r[3]
    return 1 if bad else 0


if __name__ == "__main__":
    if sys.argv[1] == "run":
        run(sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5]), int(sys.argv[6]) if len(sys.argv) > 6 else 48)
    else:
        sys.exit(diff(sys.argv[2], sys.argv[3]))

@BlivionIaG

Copy link
Copy Markdown
Contributor Author

Compared current main (ea37382cb1) with this head (93dbe31f40) merged into it. The only conflict was CHANGELOG.md; both lines kept. Same machine (M4 Pro, 48 GiB), same checkpoint (Spark-X2.6-4B, spark2_5, vocab 131,072, revision 66e3ae7b), both built -Dcpu=apple_m1 -Doptimize=ReleaseFast with libtfgrammar from xgrammar v0.2.8, a fresh server per pass with --context 8192 --parallel 1 --prompt-cache-gib 0 --no-thinking.

This family draws on the host: firstFn and verifyFn call Metal.draw → lanes.gpu_full.draw → gpu_rule.sample (or plan when top_k is 0 or above 1,024). logprobs and a grammar force the windowed rounds, so every token of those replies is host-drawn, and the structured and required-tool replies show accepted drafts (8/15, 6/21, 3/14), so their verify rows are too. _gpu_rule.topCands is in the branch binary and not in main's.

16 seeded requests per pass (return_token_ids: true), four passes alternating main, branch, branch, main: greedy; T 0.7/0.8/0.9/1.0/1.2 with top_k 20/50/100/2,000/0, top_p 0.8–1.0, min_p 0/0.05, seeds 1–8 and 21–24; three full-vocabulary cases (top_k 0, one with top_p 0.9); two json_schema requests (one full-vocabulary); one tool_choice: "required" call.

16/16 cases return identical token ids on both builds (950 ids per pass, 3,800 over the four passes), each reply's token_sha matches, and greedy is unchanged. No mismatches.

Commands: $BIN/bin/tensorfold-native serve "$MODEL_DIR" --name local-model --context 8192 --parallel 1 --prompt-cache-gib 0 --no-thinking --port $PORT, then POST /v1/chat/completions with {"model":"local-model","messages":[{"role":"user","content":"Write a short paragraph about the sea and the weather over it."}],"return_token_ids":true,"seed":N,"temperature":T,"top_k":K,"top_p":P,"min_p":M,"max_tokens":64}, plus "logprobs":true for the host-drawn rows, "response_format":{"type":"json_schema",...}, or the tool list with "tool_choice":"required". Token ids come from tensorfold.token_ids.

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thank you @BlivionIaG. The Spark comparisons answer the latest ask, including full-vocabulary sampling, grammar and required-tool requests through the host draw. The heap preserves the full sort's candidate order and the existing reduction order.

This is ready from the source review. It is now in our landing queue.

  • Synthena

ashhart pushed a commit to BlivionIaG/TensorFold that referenced this pull request Nov 24, 2026
@ashhart
ashhart force-pushed the perf/sampler-top-candidates branch from 93dbe31 to 0f0a7cb Compare November 24, 2026 17:57
ashhart and others added 4 commits November 24, 2026 19:22
…s in a bounded heap, not a full sort

- gpu_rule.sample and gpu_full.plan sorted every scaled logit of the row to read at most 1,024 of them; on a
  201,058-token vocabulary the sort is 15 ms of a draw that takes 0.11 ms without it.
- rule.topCands keeps the first n entries of better's total (key, id) order in a heap with an early reject and sorts
  those n, so the prefix, the row maximum and every draw are the full sort's bit for bit; the row-order normalizer
  is summed only when top_k is off, and a top_k above 1,024 still sorts the row for its kth candidate.
- gpu_top_test.zig compares the prefix, the maximum, the normalizer, the plan and the draws with a full-sort reference
  on 12 kinds of row (ties, signed zeros, NaN, infinities, extremes, ramps), 4 temperatures and 9 top_k, top_p and
  min_p rules.
@ashhart
ashhart force-pushed the perf/sampler-top-candidates branch from 0f0a7cb to dc24b37 Compare November 24, 2026 19:23
@ashhart
ashhart merged commit b1bb795 into ashhart:main Nov 24, 2026
1 check failed
ashhart pushed a commit that referenced this pull request Nov 24, 2026
@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thank you @BlivionIaG. This is merged into main with your commits under your own name, so you're listed as a TensorFold contributor. It ships in the next release, credited to you in the changelog and the release notes.

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.

2 participants