Repository navigation
cuda: TF_CUDA_SCHED, an opt-in host wait schedule for served CUDA models - #5165
Conversation
|
Thank you, @ZackSample. CHANGES REQUESTED at The parser and placement are correct on the shared registry and MOSS paths. Unset or blank returns before any scheduling call, each accepted word maps to the existing driver flag, and the call precedes primary-context initialization at One scope defect remains. Startup validates With The host parser checks do not establish driver delivery or output equality. The smallest subsequent device check should compare actual token IDs with the serial reference for every accepted word, plus one MOSS picture comparison on the two touched paths.
|
b6825f0 to
1189da4
Compare
|
Thanks @ZackSample for adding a clear, validated CUDA scheduling switch. The generic CUDA and MOSS paths apply it, but Qwen3, Qwen4 and the other special-family openers return before that call and create their own contexts, so a valid setting is silently ignored for those models; please apply it before each special family's primary-context initialization.
|
|
Thanks. Applied before every served primary-context creation, in b657da0 on top of your 1189da4:
Device checkEach arm is one fresh server with
The check fails unless every arm's outputs equal the unset arm's, and every set word appears in that server's
Not run
Checks on b657da0
The device check#!/usr/bin/env python3
"""TF_CUDA_SCHED device check: each word (and unset) on one server per arm; token IDs, picture bytes or audio bytes must
equal the unset arm's, and each set word must be logged by the server. Exits nonzero on any difference.
python3 device_check.py BINARY OUT {inkling|moss|drama} [words...]
"""
import base64, hashlib, http.client, json, os, subprocess, sys, threading, time
from pathlib import Path
HOME = Path.home()
PORT = 8891
TICK = os.sysconf("SC_CLK_TCK")
MODELS = {
"inkling": [str(HOME / "models/inkling-2-mini-derisked"), "--parallel", "4", "--context", "65536", "--no-drafts"],
"moss": [str(HOME / "models/moss-image-base"), "--name", "moss-image"],
"drama": [str(HOME / "models/drama-3-NVFP4-Pruned"), "--name", "drama-3"],
}
PROSE = "Write a calm, detailed walk through a coastal town at dawn: the harbour, the bakery, the fishing boats."
CODE = "Write a Python function that merges overlapping intervals, with a docstring and three test cases."
FOX = "A red fox standing in a misty birch grove at dawn, soft golden light through the trees, photorealistic, sharp detail in the fur."
SPEECH = "The lighthouse keeper climbed the stairs."
def post(path, body, timeout=900):
c = http.client.HTTPConnection("127.0.0.1", PORT, timeout=timeout)
c.request("POST", path, json.dumps(body).encode(), {"Content-Type": "application/json"})
r = c.getresponse(); raw = r.read(); c.close()
if r.status != 200:
raise SystemExit(f"{path} HTTP {r.status}: {raw[:300]!r}")
return raw
def chat(prompt):
body = {"messages": [{"role": "user", "content": prompt}], "max_tokens": 256, "temperature": 0, "draft": False, "return_token_ids": True}
ids = json.loads(post("/v1/chat/completions", body))["tensorfold"]["token_ids"]
return hashlib.sha256(json.dumps(ids).encode()).hexdigest()[:16] + f" ({len(ids)} ids)"
def work(model):
if model == "inkling":
out = {"prose x1": chat(PROSE), "code x1": chat(CODE)}
got = [None] * 4
ts = [threading.Thread(target=lambda i=i: got.__setitem__(i, chat(PROSE))) for i in range(4)]
for t in ts: t.start()
for t in ts: t.join()
out.update({f"prose x4 #{i}": g for i, g in enumerate(got)})
return out
if model == "moss":
b = {"model": "moss-image", "prompt": FOX, "size": "1024x1024", "steps": 8, "guidance": 1, "seed": 42, "response_format": "b64_json"}
return {"fox": hashlib.sha256(base64.b64decode(json.loads(post("/v1/images/generations", b))["data"][0]["b64_json"])).hexdigest()}
b = {"model": "drama-3", "input": SPEECH, "response_format": "wav", "seed": 7}
return {"speech": hashlib.sha256(post("/v1/audio/speech", b)).hexdigest()}
def cpu(pid):
f = open(f"/proc/{pid}/stat").read().rsplit(")", 1)[1].split()
return (int(f[11]) + int(f[12])) / TICK
def arm(binary, out, model, word):
log = out / f"{model}-{word}.log"
env = dict(os.environ, TF_CUDA_SCHED="" if word == "unset" else word)
p = subprocess.Popen([binary, "serve", "--host", "127.0.0.1", "--port", str(PORT), "--no-update-check", *MODELS[model]],
env=env, stdout=open(log, "w"), stderr=subprocess.STDOUT)
try:
for _ in range(300):
if p.poll() is not None:
raise SystemExit(f"{model} {word}: server exited\n" + log.read_text()[-2000:])
try:
c = http.client.HTTPConnection("127.0.0.1", PORT, timeout=2); c.request("GET", "/v1/models"); c.getresponse().read(); c.close(); break
except OSError:
time.sleep(3)
c0, t0 = cpu(p.pid), time.time()
r = work(model)
cores = round((cpu(p.pid) - c0) / (time.time() - t0), 2)
finally:
p.terminate(); p.wait()
logged = [l.split("cuda schedule: ", 1)[1].strip() for l in log.read_text().splitlines() if "cuda schedule: " in l]
rec = {"model": model, "word": word, "outputs": r, "server_cores": cores, "logged": logged}
print(json.dumps(rec), flush=True)
time.sleep(10)
return rec
def main():
binary, out, model = sys.argv[1], Path(sys.argv[2]), sys.argv[3]
words = sys.argv[4:] or ["unset", "auto", "spin", "yield", "blocking"]
out.mkdir(parents=True, exist_ok=True)
recs = [arm(binary, out, model, w) for w in words]
(out / f"{model}.json").write_text(json.dumps(recs, indent=1))
ref, bad = recs[0]["outputs"], []
for r in recs:
if r["outputs"] != ref:
bad.append(f"{r['word']}: outputs differ from {recs[0]['word']}")
want = [] if r["word"] == "unset" else [r["word"]]
if r["logged"][:1] != want:
bad.append(f"{r['word']}: server logged {r['logged']}")
if model == "inkling" and len({v for k, v in ref.items() if k.startswith("prose")}) != 1:
bad.append("inkling: a concurrent reply differs from the solo one")
print(f"{model}: " + ("PASS, every arm equals " + recs[0]["word"] if not bad else "FAIL\n " + "\n ".join(bad)), flush=True)
sys.exit(1 if bad else 0)
main() |
|
Thank you for extending the setting to each special family's primary-context path and for the detailed Inkling, MOSS, and Drama checks. The placement now covers the scope I asked about. One default-path regression remains in the two Please pass the After that, the remaining device coverage is Qwen3 and ZONOS3 through
|
|
Thanks. Fixed in d455dbf:
Checks on d455dbf
Device coverage for Qwen3, ZONOS3, Qwen4 and LFM2I'm going to leave these out. I don't have any of those checkpoints, and I won't download four model families to cover an opt-in switch. With the setting unset, those paths do the same as before: The device check script in my previous comment takes a model table, so anyone who has those checkpoints can add an entry and run it. I'm also happy for this to land with those four marked host-checked only, or for the PR to be narrowed to the families that were run on a device (shared CUDA open, MOSS, Drama), whichever you prefer. |
Unset keeps the driver's auto schedule, which spins one host core per server on a GB10. The setting is registered in platform/environment.zig (auto, spin, yield or blocking, refused by name otherwise) and applied to the primary context before the shared CUDA open and the MOSS image host create it.
Qwen3, Qwen4, LFM2, Drama and ZONOS3 open their own CUDA contexts before the shared open, so a valid TF_CUDA_SCHED was accepted and then ignored for them. Qwen4, LFM2 and Drama's device limit apply it on their own driver; Qwen3 and ZONOS3, whose engines open the driver inside their family modules, hold one with the setting until the engine's context starts.
…F_CUDA_SCHED is off An ordinal past c_int is refused (NoSuchCudaDevice) only when the setting is on, before a driver opens; unset and blank return null whatever the ordinal. The Qwen3 and ZONOS3 call sites pass the ordinal unchanged. Host regression for both.
d455dbf to
e0fe432
Compare
|
Thank you @ZackSample. 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. |
Five PR numbers were swapped between items (Idol #1787, TF_CUDA_SCHED #5165, TF_Q35_DFLASH_TRACE #5253, the DSpark draft head #5020, GLM draft head synthesis #4253; the Engram kernels #5087 and the router and row helpers #5099 described separately). 1.3.6 shipped sm_80/86/120/121, so sm_110 is the only new architecture. The #5456 workaround is 1.3.5 (1.3.6 is untested against it), the GB10 DFlash 2 cost is about 2%, and the confidential, draft-window and sharded-checkpoint wording now matches the code.
Five PR numbers were swapped between items (Idol #1787, TF_CUDA_SCHED #5165, TF_Q35_DFLASH_TRACE #5253, the DSpark draft head #5020, GLM draft head synthesis #4253; the Engram kernels #5087 and the router and row helpers #5099 described separately). 1.3.6 shipped sm_80/86/120/121, so sm_110 is the only new architecture. The #5456 workaround is 1.3.5 (1.3.6 is untested against it), the GB10 DFlash 2 cost is about 2%, and the confidential, draft-window and sharded-checkpoint wording now matches the code.
Five PR numbers were swapped between items (Idol #1787, TF_CUDA_SCHED #5165, TF_Q35_DFLASH_TRACE #5253, the DSpark draft head #5020, GLM draft head synthesis #4253; the Engram kernels #5087 and the router and row helpers #5099 described separately). 1.3.6 shipped sm_80/86/120/121, so sm_110 is the only new architecture. The #5456 workaround is 1.3.5 (1.3.6 is untested against it), the GB10 DFlash 2 cost is about 2%, and the confidential, draft-window and sharded-checkpoint wording now matches the code.
Five PR numbers were swapped between items (Idol #1787, TF_CUDA_SCHED #5165, TF_Q35_DFLASH_TRACE #5253, the DSpark draft head #5020, GLM draft head synthesis #4253; the Engram kernels #5087 and the router and row helpers #5099 described separately). 1.3.6 shipped sm_80/86/120/121, so sm_110 is the only new architecture. The #5456 workaround is 1.3.5 (1.3.6 is untested against it), the GB10 DFlash 2 cost is about 2%, and the confidential, draft-window and sharded-checkpoint wording now matches the code.
What this changes
Before, a CUDA server's host thread waits for its GPU with the driver's default
autoschedule. On a GB10, auto spins, so one host core stays at 100% for as long as the server is generating. After,TF_CUDA_SCHED=blocking(orspin/yield/auto) sets the schedule on the primary context before the shared CUDA open and the MOSS image host create it. Unset or blank keeps today's path, and any other value is refused by name at startup.TF_CUDA_HOST_WFEstays the change for those, and the two don't overlap.atc overlap --json: not run, since I don't use ATC. cuda: TF_CUDA_HOST_WFE, opt-in WFET waits for the RoCE proxy and GLM token readbacks #2922 is the open PR in the same area. Against it, the only shared files aredocs/environment.mdandzig/src/platform/environment.zig, as rows added to the same tables, so keeping both rows resolves them.Checks on this head
python3 tools/zig/lean_check.py, on the base and on this head: 152 and 152, 0 new (tools/pr_check.py --base origin/main: 0 errors, 4 inherited warnings).zig build test-environment-host test-env-defaults-host -Dfixed-cpu: 36 pass; 47 pass and 1 skip; 103 pass.TF_CUDA_SCHEDrow removed from the registry, both the registry test and the newcuda_schedule.zigtest fail (ABRT).zig build test test-golden -Dfixed-cpu: 922/922 steps, 13,842 of 13,947 tests pass and 105 skip.zig fmt --check build.zig zigandgit diff --checkpass.cuda). I have no wall power meter, so heat below is the host's hottest ACPI thermal zone, not watts.Receipt
native/cuda.zig, the MOSS image host, and the special families' own opens (Qwen3, Qwen4, LFM2, Drama, ZONOS3). DeepSeek V4.1 keeps its own existingTF_CUDA_SCHEDreader indev_arena.zig, which accepts the same four words.TF_CUDA_SCHED: unset by default; acceptsauto,spin,yieldorblocking; no profile row (no profile sets it).d3131544…).tools/bench_openai.py. It reports the same quantities: greedy, 512 tokens, median of three solo replies, and the aggregate over four concurrent replies.Inkling 2 Mini Derisked,
serve --parallel 4 --context 65536 --no-drafts, temperature 0. Each cell gives arm 1 / arm 3 (unset) and arm 2 / arm 4 (blocking).MOSS-Image, 1024², 8 steps, guidance 1, seed 42, five pictures per arm after a warm-up. Arm order: unset, blocking, unset, blocking.
What it costs: blocking is opt-in because it is not free on Inkling. Decode is about 2% slower at 1 and 4 streams, the first token 1–9 ms later on short prompts, and prompt processing unchanged. MOSS is 0.4% slower. What it buys is the spinning core: MOSS drops from one core to about none. Inkling on this engine drops to half a core, so a second host thread is still busy there, which this setting does not reach. The thermal zone was noisy between arms (arm 3 ran 8 °C warmer than arm 1 with the same setting), but every blocking arm ran cooler than the unset arm before it. On a different Inkling CUDA engine out of tree (#4441's lineage with its patches), the same switch cost 1–6% for about 6–8 °C, so the price depends on how often an engine waits; that is why this stays a choice, not a default.
The client used for the Inkling cells
Checklist
"draft": false, a resumed prompt equals a fresh one, and concurrent equals solo. (The change is host scheduling only. Drafts are off in these cells because main's Inkling CUDA engine has no drafter. Concurrent equals solo above.)--drafter, no slower than without it, greedy and sampled. Unset (the default) is main's path. Opting intoblockingcosts about 2% decode on Inkling, as measured above.