Skip to content

Qwen3.8-27B on Metal before M5: drafted decode rounds read cached keys through the prefix kernels (M4 Max, 4-bit with DFlash2: 57 to 73 tok/s over 10K of history, 26 to 55 over 34K, tokens equal) #3604

Closed

Description

@hobbesd

Kind of proposal

Other

Decision requested

Would you take this, and with which gate? Three smaller questions are at the end of "Smallest first slice", and two slower cells are named under the table.

The change, the measurements and this text were made by a coding agent (an LLM) working on the machine named under "Hardware available"; none of it is written by hand.

Scope and benefit

This changes which kernels decode rounds take on chips without tensor units, and the layout those kernels read their results in. It is not meant to change arithmetic, weights or caches; what I can show for that is under "Chips, precision and stored arithmetic".

What main does. decode_round.zig builds the 27B's attention geometry with shared_prefix = device.tensorUnits(). Before M5 that is false, so every row of a decode round reads its whole cached prefix through q27_attn_tail. A round with drafts has many rows, so its attention grows with rows times history. On an M5 the cached keys go through q27_attn_prefix, where the rows of a tile share each key tile.

What this changes. simd_attention.zig already rewrites the tail kernel's result indexing into the simdgroup-matrix layout for chips without tensor units. The branch adds the same kind of rewrite for the prefix kernels (ten source edits, each required to match exactly once, and the layout check that runs on the GPU at start extended to the prefix kernel's score tensor), and sets shared_prefix before M5. Memory admission (qwen27_served.zig) counts the same geometry the runner builds. As built it also lets prompt passes take the frame's width before M5 (question 1). A switch, TF_QWEN27_SHARED_PREFIX, read through platform/environment.zig, keeps today's path (question 2).

Who gains. Anyone serving the 27B with a drafter on M1 to M4. Measured on an M4 Max, 48 GB, TensorFold/Qwen3.8-27B-MLX-4bit with z-lab/Qwen3.8-27B-DFlash2, main's default drafter and 512-row frame, --context 65536 --prompt-cache-gib 0 --no-thinking, one stream, greedy, main at 077998f7d against the branch, order main, branch, branch, main, a fresh server per run, the machine's thermal state nominal before every request. Other applications were open: about 9.4 GiB of swap was in use throughout, with no swap-outs during the four runs.

History (prompt tokens) Request main, tok/s branch, tok/s Change
25 256 tokens 47.9, 47.6 47.8, 47.5 none
3,616 128 tokens after the cold prompt 52.9, 52.6 60.0, 59.9 +14%
3,771 256 tokens, history cached 74.1, 74.4 84.2, 84.1 +13%
10,386 128 tokens after the cold prompt 41.5, 41.6 51.2, 51.7 +24%
10,541 256 tokens, history cached 57.3, 57.0 73.1, 73.2 +28%
33,997 128 tokens after the cold prompt 14.8, 14.8 34.9, 31.9 +126%
34,152 256 tokens, history cached 26.0, 25.7 55.6, 55.4 +115%

Rates are from the first streamed token to the last; the server's own tok/s lines agree within 0.1. Time to the first token of the cold prompts: 15.9 and 15.9 s against 15.6 and 15.6 s; 51.1 and 50.4 against 49.8 and 49.7 s; 213.9 and 207.0 against 199.5 and 199.5 s. The 34K cold request ended in thermal state fair in all four runs; the request after it waited for nominal again.

Two cells are slower.

  • The first request after a start (96 tokens over a 33-token prompt, not in the table): 97.0 and 97.3 tok/s on main, 92.6 and 93.4 on the branch, about 45 ms more. Rounds and accepted drafts are equal there (17 and 81); the branch proposed 127 drafts against main's 119. It shows on every start; whether a later request of that kind is also slower I cannot say, since it ran once per start. I have not found the cause.
  • The first token of a continued turn comes 30 to 45 ms later from 10K on: 0.32 and 0.32 s against 0.36 and 0.36 at 10.5K, 0.36 and 0.38 against 0.41 and 0.39 at 34K. At 3.8K it is level.

docs/optimizing.md holds back a step that makes a served cell slower even when it is bit-exact. Do these two block it? I can look for the cause first.

Tokens. The server's sha= of each of the eight requests of a run is equal in all four runs, and so is the SHA-256 of the reply text of the seven streamed ones. Rounds and accepted drafts are identical on the 25-token, 3.6K, 3.8K and 10.4K requests. On the first request only the proposed count differs; at 10.5K and at 34K the draft schedules differ (52 against 54 rounds at 10.5K; at 34K cold 351 and 345 drafts proposed against 238 and 262), which is the timing-driven window choice. Run 4's last request matched 34,124 cached tokens where the other three matched 34,125; I do not know why.

Memory. At these settings the branch reserves less: startup stream and scratch reserve 7.49 against 9.93 GiB (8,047,280,128 against 10,663,788,544 bytes), 23.0 against 25.5 GiB kept wired, footprint when ready 23.5 against 26.0 GiB (24.3 against 26.7 after the first request; the peak over the long prompts was not recorded). Main logged memory pressure: warning three times in one run and once in the other; the branch did not in these four runs. Part of the difference is the 512-row frame, which main sizes its scratch for and does not use before M5 (your note of 5 Nov in #2089). By the scratch formula in attention_memory.zig, with both at TF_PROMPT_ROWS=128 the branch would reserve about 0.6 GiB less at this window, and main at 128 rows about 0.6 GiB less than the branch at its default 512; neither is measured with the 4-bit checkpoint. With the 8-bit checkpoint, no drafter, --context 16384 and TF_PROMPT_ROWS=128 the reserve is 2.24 against 2.53 GiB.

Without a drafter the gain is small, as expected for one row a round. 8-bit, no drafter, --context 16384, TF_PROMPT_ROWS=128, one run each, and under memory pressure (warnings in both runs, the machine swapping), so indicative only: 15.5 against 15.5 tok/s over 3.8K of history and 14.7 against 15.2 over 10.5K. Prefill in those two runs, with 128-row passes on both sides: 16.5 against 16.4 s at 3.6K and 51.3 against 52.7 s at 10.4K. On this machine plain decode barely moves with history and does not show the M1 Max drop of #2089, so this says nothing about it.

On 48 GB neither main nor the branch opened the drafter for the 8-bit checkpoint at the settings I tried (at --context 16384 both serve without it; an earlier main build refused the start at 65,536 when --drafter was given), which is why the drafter rows use the 4-bit one. Both sides of every row are main and main plus this one commit, with no other change.

Checkpoint, revision and licence

n/a for the change itself (no weights are added or converted). Measured with TensorFold/Qwen3.8-27B-MLX-4bit@22d8d538154e0e5b6f8dcb1fcc74a60a0798104c and z-lab/Qwen3.8-27B-DFlash2@50307d4c4cde6860d4eee73e2547cd786fe8e8a4; the no-drafter rows with TensorFold/Qwen3.8-27B-MLX-8bit@9ef68bd06f524d972d0e9b16ac0a49963528ed81.

Backend

Metal

Chips, precision and stored arithmetic

M1 to M4 (no tensor units). M5 is not reached: it takes the prefix kernels today and its source is untouched. No stored weights or caches are converted.

The reduction order is meant to be the tail kernel's, so that outputs stay bit-equal to main's. What I can show for that on an M4 Max:

  • tf-qwen27-attention-fused, which today returns early without tensor units, built on the branch with the rewritten source: exit 0. 552 plans, 462 chains byte-identical through the fused prefix kernel and the tail kernel, 93093888 bytes, and the same 552 plans without a shared prefix with the same SHA-256 (772bd53a…5242); 274 plans of 5 to 8 streams likewise (36eba29d…10c1); 642 rows … in 201 plans across 8192 … byte-identical to their one-row steps; 10 of 10 steps equal with and without a shared prefix.
  • tf-kernel-contract --only qwen27 on the branch, with the decode registrations on the shared geometry and the decode control (non-finite values unmasked) now registered before M5 too: SUMMARY 30 kernels: 30 pass gates 1-4, 0 fail, 0 known findings; 4 controls: 4 red as planted, 0 missed; 0 limit problems, exit 0.
  • tf-qwen27-synthetic on the branch: 19 prompt chunk widths byte-equal to chunk 1 with 8 greedy tokens, 7 decoded-row chunk widths equal to the CLI tree, as on main. Its forward-diff mode fails at its first comparison on this Mac on unmodified main (forward difference head/canaries byte0:145/142, error: ForwardDifference); the branch fails at the same byte with the same values, so that mode checks nothing here.
  • tf-qwen27-attention-pages: PASS 21 rounds: 6696960 output values and every cache row the same bits, paged and contiguous. The tool plans without a shared prefix before M5, so it does not reach the paged prefix kernel; one served run of the branch with TF_QWEN27_METAL_KV_PAGES=1 gave the same four token hashes as the unpaged runs (short prompt, 3.6K cold, 3.8K continued).
  • the token hashes above.

These byte checks stop below the histories in the table: tf-qwen27-attention-fused plans up to 8,705 keys and the contract's decode shapes up to 8,191. At 10K and 34K the evidence is the token hashes alone.

Shared modules to extend

families/qwen27/simd_attention.zig (the rewrite list and the GPU layout check that the tail kernel already has), one line in decode_round.zig, two in native/qwen27_served.zig. The switch adds a rule in platform/environment.zig, its test rows and a line in docs/environment.md. The contract's attention registrations (zig/tests/contract/metal_q27_attn_rows.zig, _io.zig) and forward_diff_runner.zig follow the runner's decision instead of tensorUnits(), and attention_fused.zig runs before M5.

Smallest first slice

One pull request: the commit as measured (on main at 077998f7d, 11 files, 108 lines added, 40 removed), changed by whatever you decide on question 1. It is here to look at: hobbesd@cc1db32 (branch metal-prefix-before-m5). zig build test test-golden -Dcpu=apple_m1 --summary all gave 874/874 steps, 14,492 of 14,605 tests passed, 113 skipped, 0 failed, before three last edits that touch no kernel or engine source (a build-step description, a comment, and one line of the forward-diff test tool); a rerun after the first two again gave 874/874 steps. On the head zig fmt --check build.zig zig and git diff --check are clean, and tools/pr_check.py gives 0 errors and one advisory warning (no PR number yet), lean 221 against 221. The measured binary is the one this commit builds (same MD5). The ledger cell and, if the switch stays, its profile row would come with the pull request.

Three things I would like your read on before sending it:

  1. Prompt pass width. With shared_prefix set, Geometry.promptRows lets a prompt pass take the frame's width before M5 too. So with the default 512-row frame the branch's prompt passes above were 512 rows wide, through attention_prompt_sg (its log says prompt chunks of up to 512 tokens, main's up to 128). That is a data point for item 1 of Qwen3.8-27B on M1-M4: prompt GEMM behind MLX's rate, and plain decode behind 0.6.6 #2089: tokens equal on the three cold prompts, prefill 1.5 to 5% faster. But the contract's prompt shapes stop at 128 rows, and you closed a wide-pass route in qwen27: canonical prompt chains follow the admitted frame on pre-M5 chips, past 128 rows #2120. My preference is to cap prompt passes at 128 before M5 in this slice (one line in Runner.promptRows) and leave the wider pass as its own question. A capped head is a different binary: I have not run it with the 4-bit checkpoint and would measure it before sending. The only 128-row runs I have are the two 8-bit ones above.
  2. A switch. TF_QWEN27_SHARED_PREFIX=0 keeps today's path before M5 (default on), so one binary can run both sides. Keep it, or no switch? If it stays: the disk-state identity in qwen27_disk.zig hashes tensorUnits() and not the switch; say if it belongs there.
  3. Chips. I have an M4 Max only.

Proposed gate

  • Kernel contract: the decode registrations on the shared geometry before M5, their control red, each chip's SUMMARY line.
  • tf-qwen27-attention-fused before M5: the fused prefix kernel, the tail kernel and no shared prefix byte-identical, extended to 32K keys or more.
  • Tokens, main against the branch at the same checkpoint and settings: greedy and sampled, drafted equal to "draft": false, a resumed prompt equal to a fresh one, concurrent equal to solo at every admitted stream count.
  • Decode and prompt processing no slower than main (order main, branch, branch, main on one machine) at a short prompt and over 2K, 8K, 32K and 64K of history, with and without the drafter, with your decision on the two slower cells above.
  • One run on an M1, M2 or M3 by someone who has one.

Gate status

Proposed here

Link to the gate decision

No response

Hardware available

Apple M4 Max, 48 GB, macOS 27.2.1 (26B131), Zig 0.17.0, zig build native -Dcpu=apple_m1. Coverage that needs another tester: M1, M2, M3, the Pro and Ultra variants, and a Mac with enough memory for the 8-bit checkpoint with its drafter.

Not run: sampled decode; more than one stream; thinking; vision; drafted against "draft": false; a resumed prompt against a fresh one; a served run with TF_QWEN27_SHARED_PREFIX=0; a 64K history; TF_QWEN27_METAL_KV_PAGES=1 beyond the one served run above; tools/bench_openai.py and tools/bench_cache.py (the numbers are from the two scripts in the first comment). The page cache was not dropped between starts.

Related issues, pull requests and earlier attempts

Privacy

  • This proposal holds no private paths, hostnames, tokens, keys or confidential prompts.
Commands
loadbench.py --model TensorFold/Qwen3.8-27B-MLX-4bit --bin M=MAIN/tensorfold-native --bin K=BRANCH/tensorfold-native \
  --order M,K,K,M --pause 60 --probe ./thermal --until nominal --out runs.jsonl \
  --client "python3 histbench.py {base} --text typing.py --chars 14000,42000,139000 --probe ./thermal --until nominal --out {out}.json" \
  -- --parallel 1 --context 65536 --no-thinking --prompt-cache-gib 0 --no-update-check

Each run starts tensorfold-native serve MODEL --name local-model --port 8092 with the arguments after --, sends one 96-token request, then the client: a short prompt (256 tokens); then for each length the first 14,000, 42,000 and 139,000 characters of CPython 3.15.2's Lib/typing.py as one user turn (128 tokens), and the reply plus a second question appended (256 tokens, history cached). temperature 0, streamed. Every request waits for the thermal state nominal plus 30 s; ./thermal prints ProcessInfo.processInfo.thermalState. Both scripts and the probe's source (thermal.swift) are in the first comment below.

Server lines of the four runs (the `done` lines cut to these fields, with the startup, chunk and pressure lines)
run 1, main 077998f7d (binary md5 8935c1f8f06ac64ff6c3d56055f1e6a2), thermal state before start nominal, footprint when ready 25.97 GiB
  qwen27: prompt capacity=512 rows, startup stream and scratch reserve=10663788544 bytes
  qwen27: 25.5 GiB kept wired between requests, inside 70% of 48 GiB of RAM
  memory pressure: warning
  prompt chunks of up to 128 tokens, cut at replies 256+ tokens apart
  prompt=33 cached=0 tokens=96 sha=351064b4973a rounds=17 accepted=81/119 ttft=0.317 decode=0.979 tok/s=97.0
  prompt=25 cached=0 tokens=256 sha=e63bf5ebab5b rounds=92 accepted=164/644 ttft=0.231 decode=5.329 tok/s=47.9
  prompt=3616 cached=0 tokens=128 sha=3476f33321b9 rounds=35 accepted=94/245 ttft=15.867 decode=2.399 tok/s=52.9
  prompt=3771 cached=3744 tokens=256 sha=af669cf9491b rounds=50 accepted=205/350 ttft=0.297 decode=3.441 tok/s=74.1
  prompt=10386 cached=0 tokens=128 sha=580beff71755 rounds=36 accepted=95/252 ttft=51.118 decode=3.062 tok/s=41.5
  prompt=10541 cached=10514 tokens=256 sha=586c56448226 rounds=52 accepted=203/388 ttft=0.318 decode=4.454 tok/s=57.2
  memory pressure: warning
  memory pressure: warning
  prompt=33997 cached=0 tokens=128 sha=b83194b12ffb rounds=33 accepted=96/351 ttft=213.858 decode=8.612 tok/s=14.7
  prompt=34152 cached=34125 tokens=256 sha=1645bf875587 rounds=58 accepted=202/542 ttft=0.355 decode=9.813 tok/s=26.0
run 2, branch (binary md5 39f5952a3d4e03e268f1aaec25ea5bcc), thermal state before start nominal, footprint when ready 23.53 GiB
  qwen27: prompt capacity=512 rows, startup stream and scratch reserve=8047280128 bytes
  qwen27: 23.0 GiB kept wired between requests, inside 70% of 48 GiB of RAM
  prompt chunks of up to 512 tokens, cut at replies 256+ tokens apart
  prompt=33 cached=0 tokens=96 sha=351064b4973a rounds=17 accepted=81/127 ttft=0.343 decode=1.026 tok/s=92.6
  prompt=25 cached=0 tokens=256 sha=e63bf5ebab5b rounds=92 accepted=164/644 ttft=0.231 decode=5.340 tok/s=47.7
  prompt=3616 cached=0 tokens=128 sha=3476f33321b9 rounds=35 accepted=94/245 ttft=15.641 decode=2.119 tok/s=59.9
  prompt=3771 cached=3744 tokens=256 sha=af669cf9491b rounds=50 accepted=205/350 ttft=0.298 decode=3.029 tok/s=84.2
  prompt=10386 cached=0 tokens=128 sha=580beff71755 rounds=36 accepted=95/252 ttft=49.847 decode=2.483 tok/s=51.1
  prompt=10541 cached=10514 tokens=256 sha=586c56448226 rounds=54 accepted=201/378 ttft=0.355 decode=3.487 tok/s=73.1
  prompt=33997 cached=0 tokens=128 sha=b83194b12ffb rounds=34 accepted=94/238 ttft=199.539 decode=3.635 tok/s=34.9
  prompt=34152 cached=34125 tokens=256 sha=1645bf875587 rounds=62 accepted=197/450 ttft=0.406 decode=4.591 tok/s=55.5
run 3, branch (binary md5 39f5952a3d4e03e268f1aaec25ea5bcc), thermal state before start nominal, footprint when ready 23.53 GiB
  qwen27: prompt capacity=512 rows, startup stream and scratch reserve=8047280128 bytes
  qwen27: 23.0 GiB kept wired between requests, inside 70% of 48 GiB of RAM
  prompt chunks of up to 512 tokens, cut at replies 256+ tokens apart
  prompt=33 cached=0 tokens=96 sha=351064b4973a rounds=17 accepted=81/127 ttft=0.316 decode=1.017 tok/s=93.4
  prompt=25 cached=0 tokens=256 sha=e63bf5ebab5b rounds=92 accepted=164/644 ttft=0.237 decode=5.371 tok/s=47.5
  prompt=3616 cached=0 tokens=128 sha=3476f33321b9 rounds=35 accepted=94/245 ttft=15.608 decode=2.122 tok/s=59.8
  prompt=3771 cached=3744 tokens=256 sha=af669cf9491b rounds=50 accepted=205/350 ttft=0.305 decode=3.031 tok/s=84.1
  prompt=10386 cached=0 tokens=128 sha=580beff71755 rounds=36 accepted=95/252 ttft=49.662 decode=2.455 tok/s=51.7
  prompt=10541 cached=10514 tokens=256 sha=586c56448226 rounds=54 accepted=201/378 ttft=0.362 decode=3.485 tok/s=73.2
  prompt=33997 cached=0 tokens=128 sha=b83194b12ffb rounds=34 accepted=94/262 ttft=199.454 decode=3.988 tok/s=31.8
  prompt=34152 cached=34125 tokens=256 sha=1645bf875587 rounds=62 accepted=197/450 ttft=0.394 decode=4.605 tok/s=55.4
run 4, main 077998f7d (binary md5 8935c1f8f06ac64ff6c3d56055f1e6a2), thermal state before start nominal, footprint when ready 25.97 GiB
  qwen27: prompt capacity=512 rows, startup stream and scratch reserve=10663788544 bytes
  qwen27: 25.5 GiB kept wired between requests, inside 70% of 48 GiB of RAM
  memory pressure: warning
  prompt chunks of up to 128 tokens, cut at replies 256+ tokens apart
  prompt=33 cached=0 tokens=96 sha=351064b4973a rounds=17 accepted=81/119 ttft=0.339 decode=0.976 tok/s=97.3
  prompt=25 cached=0 tokens=256 sha=e63bf5ebab5b rounds=92 accepted=164/644 ttft=0.234 decode=5.356 tok/s=47.6
  prompt=3616 cached=0 tokens=128 sha=3476f33321b9 rounds=35 accepted=94/245 ttft=15.884 decode=2.416 tok/s=52.6
  prompt=3771 cached=3744 tokens=256 sha=af669cf9491b rounds=50 accepted=205/350 ttft=0.303 decode=3.430 tok/s=74.4
  prompt=10386 cached=0 tokens=128 sha=580beff71755 rounds=36 accepted=95/252 ttft=50.349 decode=3.054 tok/s=41.6
  prompt=10541 cached=10514 tokens=256 sha=586c56448226 rounds=52 accepted=203/388 ttft=0.315 decode=4.471 tok/s=57.0
  prompt=33997 cached=0 tokens=128 sha=b83194b12ffb rounds=31 accepted=96/345 ttft=207.002 decode=8.561 tok/s=14.8
  prompt=34152 cached=34124 tokens=256 sha=1645bf875587 rounds=58 accepted=202/550 ttft=0.383 decode=9.930 tok/s=25.7

Activity

  1. hobbesd commented on Nov 16, 2026

    @hobbesd
    ContributorAuthor

    The two scripts and the thermal probe behind the numbers above. They are attached rather than committed; say if you want either under tools/.

    thermal.swift builds with swiftc -O thermal.swift -o thermal.

    loadbench.py
    #!/usr/bin/env python3
    """Cold-load receipts for two native binaries in a fixed order, each on a fresh server.
    
      loadbench.py --model REPO --order A,B,B,A --bin A=path/to/main/tensorfold-native --bin B=path/to/branch/tensorfold-native \
          [--before 'command run before every start'] [--client 'python3 tools/bench_openai.py {base} local-model --output {out}.json']
          [--pause 60] [--out runs.jsonl] -- serve-args...
    
    Every run starts `BIN serve MODEL --name local-model --port PORT <serve-args>` with TF_STARTUP_RECEIPT=1, waits for
    /v1/models, sends one greedy request, stops the server it started and prints the startup receipt's phases, the
    process resources and the reply's token hash. Nothing else is stopped.
    """
    import argparse, hashlib, json, os, re, signal, subprocess, sys, time, urllib.request
    
    PROMPT = "List the first twelve prime numbers, then explain in two sentences why 1 is not one of them."
    
    
    def md5(path):
        h = hashlib.md5()
        with open(path, "rb") as f:
            for block in iter(lambda: f.read(1 << 20), b""):
                h.update(block)
        return h.hexdigest()
    
    
    def get(url, timeout):
        with urllib.request.urlopen(url, timeout=timeout) as r:
            return json.loads(r.read())
    
    
    def post(url, body, timeout):
        req = urllib.request.Request(url, json.dumps(body).encode(), {"Content-Type": "application/json"})
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return json.loads(r.read())
    
    
    def file_cache_gib():
        """File-backed pages the kernel holds (macOS), in GiB; None where the counters are not there."""
        try:
            out = subprocess.run(["sysctl", "-n", "vm.page_pageable_external_count", "hw.pagesize"], capture_output=True, text=True, check=True).stdout.split()
            return round(int(out[0]) * int(out[1]) / 2**30, 2)
        except (OSError, subprocess.CalledProcessError, ValueError, IndexError):
            return None
    
    
    def probe(args):
        """One line from --probe (for example the machine's thermal state), or None."""
        if not args.probe:
            return None
        return subprocess.run(args.probe, shell=True, capture_output=True, text=True).stdout.strip()[:80]
    
    
    def run(label, binary, args, n, log_dir):
        waited = time.time()
        while args.until and probe(args) != args.until and time.time() - waited < args.until_timeout:
            time.sleep(10)
        if args.before:
            subprocess.run(args.before, shell=True, check=True)
        beside = None
        if label in args.besides:
            beside = subprocess.Popen(args.besides[label], shell=True, stdout=subprocess.PIPE, text=True, start_new_session=True)
            beside.stdout.readline()
        cache_before = file_cache_gib()
        state_before = probe(args)
        log_path = os.path.join(log_dir, "load-%02d-%s.log" % (n, label))
        cmd = [binary, "serve", args.model, "--name", "local-model", "--port", str(args.port)] + args.serve
        env = dict(os.environ, TF_STARTUP_RECEIPT="1")
        for pair in args.envs.get(label, []):
            key, _, value = pair.partition("=")
            env[key] = value
        started = time.time()
        with open(log_path, "wb") as log:
            proc = subprocess.Popen(cmd, env=env, stdout=log, stderr=subprocess.STDOUT)
        row = {"n": n, "label": label, "md5": md5(binary), "log": os.path.basename(log_path), "file_cache_before_gib": cache_before}
        if args.until:
            row["waited_for_state_s"] = round(started - waited)
        try:
            base = "http://127.0.0.1:%d" % args.port
            while True:
                if proc.poll() is not None:
                    row["error"] = "server exited %s before it was ready" % proc.returncode
                    return row
                try:
                    get(base + "/v1/models", 2)
                    break
                except OSError:
                    if time.time() - started > args.start_timeout:
                        row["error"] = "not ready after %d s" % args.start_timeout
                        return row
                    time.sleep(0.2)
            row["ready_wall_s"] = round(time.time() - started, 2)
            row["state_before"], row["state_ready"] = state_before, probe(args)
            t = time.time()
            reply = post(base + "/v1/chat/completions", {"model": "local-model", "temperature": 0, "max_tokens": args.tokens,
                                                          "messages": [{"role": "user", "content": PROMPT}]}, 600)
            row["first_request_s"] = round(time.time() - t, 2)
            row["completion_tokens"] = reply.get("usage", {}).get("completion_tokens")
            row["state_after_request"] = probe(args)
            for i, client in enumerate(args.client or []):
                out = os.path.join(log_dir, "client-%02d-%s-%d" % (n, label, i))
                done = subprocess.run(client.format(base=base, label=label, out=out), shell=True, capture_output=True, text=True)
                with open(out + ".txt", "w") as f:
                    f.write(done.stdout + done.stderr)
                row["client_%d_exit" % i] = done.returncode
        finally:
            if proc.poll() is None:
                proc.send_signal(signal.SIGTERM)
                try:
                    proc.wait(60)
                except subprocess.TimeoutExpired:
                    proc.kill()
                    proc.wait()
            if beside:
                os.killpg(beside.pid, signal.SIGTERM)
                beside.wait()
        text = open(log_path, errors="replace").read()
        m = re.search(r"^startup-receipt (\{.*\})\s*$", text, re.M)
        if m:
            receipt = json.loads(m.group(1))
            phases = {p["phase"]: p["total_ns"] / 1e9 for p in receipt["startup"]["phases"]}
            row["ready_s"] = round(receipt["startup"]["at_ns"] / 1e9, 2)
            for name in ("checkpoint_headers", "read_pack", "runtime_setup", "residency"):
                row[name + "_s"] = round(phases.get(name, 0.0), 2)
            res = receipt.get("resources", {})
            row["peak_footprint_gib"] = round(res.get("lifetime_peak_physical_footprint_bytes", 0) / 2**30, 2)
            row["disk_read_gib"] = round(res.get("disk_io_bytes_read", 0) / 2**30, 2)
        shas = re.findall(r"\bsha=([0-9a-f]+)", text)
        row["token_sha"] = shas[0] if shas else None
        row["pressure_lines"] = len(re.findall(r"memory pressure", text))
        row["file_cache_after_gib"] = file_cache_gib()
        return row
    
    
    def main():
        ap = argparse.ArgumentParser()
        ap.add_argument("--model", required=True)
        ap.add_argument("--bin", action="append", required=True, metavar="LABEL=PATH")
        ap.add_argument("--order", required=True, help="comma list of labels, one fresh server each")
        ap.add_argument("--before", help="shell command run before every start, for example a page cache drop")
        ap.add_argument("--pause", type=float, default=60, help="seconds between a stop and the next start")
        ap.add_argument("--port", type=int, default=8092)
        ap.add_argument("--tokens", type=int, default=96)
        ap.add_argument("--start-timeout", type=int, default=600)
        ap.add_argument("--out", default="loadbench.jsonl")
        ap.add_argument("--probe", help="shell command whose one output line is recorded before each start and at ready, for example the thermal state")
        ap.add_argument("--env", action="append", default=[], metavar="LABEL=K=V,K=V", help="extra environment for one label's server")
        ap.add_argument("--beside", action="append", default=[], metavar="LABEL=COMMAND",
                        help="a process started before this label's server once it has printed a line, stopped after the server")
        ap.add_argument("--until", help="before each start, wait until --probe prints this (for example nominal)")
        ap.add_argument("--until-timeout", type=int, default=1200)
        ap.add_argument("--client", action="append", help="shell command run against each server; {base}, {label} and {out} are filled in")
        ap.add_argument("serve", nargs=argparse.REMAINDER)
        args = ap.parse_args()
        args.serve = [a for a in args.serve if a != "--"]
        bins = dict(b.split("=", 1) for b in args.bin)
        args.envs = {e.split("=", 1)[0]: e.split("=", 1)[1].split(",") for e in args.env}
        args.besides = dict(b.split("=", 1) for b in args.beside)
        log_dir = os.path.dirname(os.path.abspath(args.out))
        rows = []
        for n, label in enumerate(args.order.split(",")):
            if n:
                time.sleep(args.pause)
            row = run(label, bins[label], args, n, log_dir)
            rows.append(row)
            with open(args.out, "a") as f:
                f.write(json.dumps(row) + "\n")
            print(json.dumps(row), flush=True)
            if "error" in row:
                return 1
        return 0
    
    
    if __name__ == "__main__":
        sys.exit(main())
    histbench.py
    #!/usr/bin/env python3
    """Decode rate over a long history, greedy, one stream: a cold prompt, then a continued turn over it.
    
      histbench.py BASE --text FILE --chars 14000,45000 [--model local-model] [--probe CMD --until nominal] [--out FILE]
    
    For each length the first `chars` characters of FILE are sent as one user turn (cold), the reply and a second question
    are appended and sent again (the history is then cached state), each timed from the first streamed token to the last.
    With --probe and --until every request waits until the probe prints that word (for example the thermal state).
    """
    import argparse, hashlib, json, subprocess, sys, time, urllib.request
    
    ASK = "\n\nDescribe in detail what this module does, section by section."
    MORE = "Now explain the three most intricate functions in it step by step."
    
    
    def probe(args):
        if not args.probe:
            return None
        return subprocess.run(args.probe, shell=True, capture_output=True, text=True).stdout.strip()[:40]
    
    
    def settle(args):
        """Wait for the probe's word, then `--rest` seconds more; the seconds waited."""
        t = time.time()
        while args.until and probe(args) != args.until and time.time() - t < args.until_timeout:
            time.sleep(10)
        if args.until:
            time.sleep(args.rest)
        return round(time.time() - t)
    
    
    def ask(args, messages, tokens):
        body = {"model": args.model, "temperature": 0, "max_tokens": tokens, "messages": messages, "stream": True,
                "stream_options": {"include_usage": True}}
        req = urllib.request.Request(args.base + "/v1/chat/completions", json.dumps(body).encode(), {"Content-Type": "application/json"})
        row = {"waited_s": settle(args), "state_before": probe(args)}
        start = time.time()
        first = last = None
        text, usage = [], {}
        with urllib.request.urlopen(req, timeout=3600) as r:
            for line in r:
                line = line.decode().strip()
                if not line.startswith("data:") or line == "data: [DONE]":
                    continue
                event = json.loads(line[5:])
                usage = event.get("usage") or usage
                for choice in event.get("choices", []):
                    piece = (choice.get("delta") or {}).get("content")
                    if piece:
                        last = time.time()
                        first = first or last
                        text.append(piece)
        reply = "".join(text)
        n = usage.get("completion_tokens")
        row.update({"state_after": probe(args), "prompt_tokens": usage.get("prompt_tokens"),
                    "cached_tokens": (usage.get("prompt_tokens_details") or {}).get("cached_tokens"), "completion_tokens": n,
                    "first_token_s": round(first - start, 2) if first else None,
                    "decode_tok_s": round((n - 1) / (last - first), 2) if n and n > 1 and last and last > first else None,
                    "reply_sha256": hashlib.sha256(reply.encode()).hexdigest()[:12]})
        return row, reply
    
    
    def main():
        ap = argparse.ArgumentParser()
        ap.add_argument("base")
        ap.add_argument("--text", required=True)
        ap.add_argument("--chars", required=True, help="comma list of history lengths in characters")
        ap.add_argument("--model", default="local-model")
        ap.add_argument("--cold-tokens", type=int, default=128)
        ap.add_argument("--more-tokens", type=int, default=256)
        ap.add_argument("--probe")
        ap.add_argument("--until")
        ap.add_argument("--until-timeout", type=int, default=1200)
        ap.add_argument("--rest", type=float, default=30)
        ap.add_argument("--out")
        args = ap.parse_args()
        source = open(args.text, encoding="utf-8").read()
        rows = []
    
        def note(step, chars, row):
            row = dict({"step": step, "chars": chars}, **row)
            rows.append(row)
            print(json.dumps(row), flush=True)
    
        row, _ = ask(args, [{"role": "user", "content": "Write a short story about a lighthouse keeper and a storm."}], args.more_tokens)
        note("short", 0, row)
        for chars in [int(c) for c in args.chars.split(",")]:
            piece = source[:chars]
            messages = [{"role": "user", "content": "Here is a Python module:\n\n" + piece + ASK}]
            row, reply = ask(args, messages, args.cold_tokens)
            row["text_sha256"] = hashlib.sha256(piece.encode()).hexdigest()[:12]
            note("cold", chars, row)
            messages += [{"role": "assistant", "content": reply}, {"role": "user", "content": MORE}]
            row, _ = ask(args, messages, args.more_tokens)
            note("continued", chars, row)
        if args.out:
            with open(args.out, "w") as f:
                json.dump(rows, f, indent=1)
        return 0
    
    
    if __name__ == "__main__":
        sys.exit(main())
    thermal.swift
    // Prints the system's thermal state once (ProcessInfo.thermalState): nominal, fair, serious or critical.
    import Foundation
    print(["nominal", "fair", "serious", "critical"][ProcessInfo.processInfo.thermalState.rawValue])
  2. ashhart commented on Nov 16, 2026

    @ashhart
    Owner

    Thanks @hobbesd for the detailed measurements and the byte-level checks behind this. No open change answers it yet: main still sends every decode row before the newer chips through the tail kernel, and the prefix-kernel rewrite you describe is not in the tree, so this stays open. From you we need only the draft branch and scripts you attached, and your read on the two slower first-request cells, since only you have that hardware and build. We will do the review and the run on our M3 machine, and settle the prompt-width and switch questions before anything lands. This issue closes with the release that ships its fix.

    • Synthena
  3. hobbesd commented on Nov 16, 2026

    @hobbesd
    ContributorAuthor

    Thanks. The branch (metal-prefix-before-m5 at cc1db32a9, on main at 077998f7d) and the two scripts in the first comment are what was measured; nothing else is pending from my side.

    My read on the two slower cells, from the logs I have and the source. No new runs.

    First request after a start (33-token prompt, 96 tokens). I read this as the draft schedule, not the kernel's cost per round.

    • It is the same on every start of a binary: 81/127 on all four branch starts I have (93.8, 93.8, 92.6, 93.4 tok/s; one of them with TF_QWEN27_METAL_KV_PAGES=1) and 81/119 on all three main starts (97.8, 97.0, 97.3). Rounds are 17 on both.
    • The window prices are kept per executable (cost_cache.key hashes the binary), so each side prices drafts from its own table. Both were timed once, about 30 s apart, at the 192-key timing prompt; ms for 1 to 16 rows:
      • main: 37.28 42.88 48.83 49.03 49.77 49.40 49.42 49.48 85.54 85.72 86.02 86.24 86.49 87.41 88.05 87.97
      • branch: 36.97 41.81 48.28 48.52 48.58 48.58 48.84 48.98 84.91 85.15 85.23 85.34 85.54 85.65 85.89 86.11
    • So at a short history the branch is no dearer at any width (0.3 to 2.2 ms lower, the most at 14 to 16 rows; one timing a side, so I would not read more into the difference). Both have the same step of about 36 ms between 8 and 9 rows.
    • The decode gap is 41 to 47 ms (0.971, 0.979, 0.976 s on main against 1.012, 1.012, 1.026, 1.017 s on the branch). Eight more proposed drafts with the same accepted count, at the price of one round that crosses that step (37 ms by the branch's table), fits it.

    What I cannot show: which round was widened, and that it is a single one; I logged no TF_Q27_PASS_PROFILE lines. I also cannot say why the next request (25-token prompt, 256 tokens) has the same schedule on both sides (164/644) and is level.

    First token of a continued turn, 30 to 45 ms later from 10K on. I have no cause for this one.

    • The numbers: 0.318 and 0.315 s on main against 0.355 and 0.362 s at 10.5K; 0.355 and 0.383 against 0.406 and 0.394 at 34K; level at 3.8K (0.297 and 0.303 against 0.298 and 0.305). Two runs a side, and at 34K the two ranges are 11 ms apart, so the 34K cell is weak evidence on its own.
    • The 27 new prompt rows take the prompt kernels on both sides (Attention.promptRows); with the shared geometry only the partial buffers differ (poa/pma/pla instead of pob/pmb/plb). I did not time the phases inside that first token, so I cannot say which one grew.
    • It appears above fine_until (8,192 keys) and not below. That is an observation, not a finding.

    If it helps your M3 run: one start per side with TF_Q27_PASS_PROFILE set would show the widened round of the first cell directly.

  4. ashhart commented on Nov 17, 2026

    @ashhart
    Owner

    Thanks @hobbesd for the branch, scripts and careful limits. We will review cc1db32 and run the first-request and continued-turn cells on M3 Ultra, including pass profiling. The draft-schedule explanation remains a hypothesis, and the TTFT cause is still open. We will also reconcile the prompt-width question with #2916/#2797 and review switch/disk identity before a PR lands. Nothing more is needed from you right now.

    • Synthena
  5. ashhart commented on Nov 17, 2026

    @ashhart
    Owner

    Thanks @hobbesd. We ran cc1db32a9 on an M3 Ultra against its base (077998f7d9), Qwen3.8-27B 4-bit with DFlash2, base new new base. It's GREEN, with served tokens identical (0 of 20 rows differ):

    Prompt Prompt speed Decode after it
    2K +3.6% +3.3%
    8K +4.5% +9.6%
    16K +4.5% +9.2%
    32K +4.4% +26.1%
    64K +4.1% +35.2%

    That matches your M4 Max picture: the longer the history, the bigger the decode gain. Please open it as a PR. We'll review the code, check the switch and the disk identity, and reconcile the prompt-width question with #2916 and #2797 there. Pass profiling and the first-token cause can follow in that thread.

    • Synthena
  6. ashhart commented on Nov 20, 2026

    @ashhart
    Owner

    Thanks @hobbesd for the change, the measurements and the careful limits.

    Before M5, Qwen3.8-27B's decode rounds now read cached keys through the prefix kernels with their results in the simdgroup-matrix layout, and memory admission counts the same geometry (#3677, on main as of 9e2a9bd). TF_QWEN27_SHARED_PREFIX=0 keeps the old tail-kernel path.

    To check: on an M1 to M4 Mac, serve TensorFold/Qwen3.8-27B-MLX-4bit with the DFlash2 drafter, run a long-history request, then repeat with TF_QWEN27_SHARED_PREFIX=0; the tokens should be identical and decode faster without the setting.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions