Repository navigation
lanes: the host GPU-rule sampler keeps its best 1,024 candidates in a bounded heap, not a full sort - #4744
Conversation
- The host sampler's full sort is the cost; ashhart#4744 keeps only the best 1,024 candidates with identical tokens.
|
CI result for |
|
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.
|
|
Thank you, @ashhart. The comparison you asked for, on a model that serves on current Model. Builds. A = Per run (a fresh server each, one client pass, one server at a time):
Requests (336 per pass), A against B, request by request:
All 64 grammar-routed replies are valid JSON or valid tool calls ( What this does not cover.
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])) |
|
Compared current main ( This family draws on the host: 16 seeded requests per pass ( 16/16 cases return identical token ids on both builds (950 ids per pass, 3,800 over the four passes), each reply's Commands: |
|
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.
|
93dbe31 to
0f0a7cb
Compare
…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.
0f0a7cb to
dc24b37
Compare
|
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. |
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.topCandsnow 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.7bd7081e06), one commit; it touchesgpu_rule.zig,gpu_full.zig,lanes.zig,gpu_top_test.zigand the changelog only.atc overlap --json: incomplete (pullFilesUnavailable, time limit); it lists conflicts with glm cuda: a GB10 holds the BF16 linears exactly in 12 bits a weight #3509 (one file) and lanes: host GPU draws select their candidates instead of sorting the whole row (#3396) #3455 (three files) without naming them, andatc whoon the three source files lists no pull request (also incomplete); the conflicts are probably the changelog [INFERENCE], unresolved.Checks on this head
93dbe31f40zig fmt --check build.zig zigclean;tools/pr_check.py --base upstream/main: 0 errors, 1 advisory (asks for--pr NUMBER).-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-host487 pass, 1 skip (includesgpu_full_testand the newgpu_top_test);test-lanes-topk-host5/5;test-dsv41-draft180/180;test-qwen27-draws-host6/6;test-flashnext-{constraint,draw,nonfinite,penalties,vision-contracts}-host12, 44, 38, 16, 15 pass;test-kimi-serving-host54/54;test-k328/28;test-flint-draft-host80/80;test-minimax-m3-metal-steps-host5/5;test-minimax-info-host1/1;test-llama-controls-host2/2;test-glm-samplingevery row PASS;tf-nemotron-sample-check(GPU, M4 Pro): 20 of 20 row groups match, "all draws match".spark2_5Metal engine, which reaches the changed code onmain): 672 of 672 seeded request pairs,mainagainstmainplus this branch, equal token ids, including full-vocabulary, wide top_k, structured-output and required-tool requests, at 1 and 4 streams (comment7126475411replies; commands and client in the comment below it).Receipt
topCands,rule.sampleandfull.planwith 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.gpu_ruleorgpu_full; no kernel, no new switch, no weights.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).7123893220; base7f4d175c3d, with this PR ateaa9e41a6a, T 0.7, seed 1234,--alone --serial,--parallel 4 --prompt-cache-gib 0, fresh server per block, quiet Mac;--aloneand--serialall 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.bench_concurrent --alone --serial --temperatures 0.7: 30/30 equal alone and 16/16 equal to"draft": falseon plain and DSpark, 0 unequal; greedychat_hashesunchanged.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.Checklist