[GH-ISSUE #127] DFlash2 on v1.1.0 with Maya-M on a RAM-bound desktop (RTX 3090 + RTX 3060): ten setups, one and two cards #41

Closed
opened 2026-10-29 21:19:35 +07:00 by bsakaguchi · 4 comments
Owner

Originally created by @sociolog on GitHub (Oct 12, 2026).
Original GitHub issue: https://github.com/mw00/project-maya/issues/127

Short version: on this machine the MTP block stays the better drafter. DFlash2 is correct (drafts are accepted 64-93% of
the time) but its verify window costs more than it saves: 2 cards 11.95-14.27 tok/s against 23.97 for the MTP block, and
1 card 14.57-14.74 against 19.01 for plain decode. Switching the window's RAM-tier experts from "all on the CPU" to the
calibrated CPU / PCIe plan (STRATA_GLM_WIN_ALLCPU=0) recovers about 19% on two cards, but not the gap. Posting this as
data for the 1-2 GPU tuning you mentioned; happy to measure anything you want varied.

The machine and the model

CPU / RAM Ryzen 9 5900X (12 cores, one NUMA node, SMT on), 128 GB DDR4; the engine measures 46 GB/s host reads
GPUs RTX 3090 24 GB (CUDA0), RTX 3060 12 GB (CUDA1); a Quadro RTX 4000 only drives displays (not used)
OS / toolchain Linux Mint (kernel 7.0), CUDA 12.8, v1.1.0 built from the tag, no local patches
Model Maya-M (112 GB), 245,760 context
Settings STRATA_GLM_SPLIT=28, RAM_RESIDENT=1 (RAM tier 47.8 + 38.6 GB pinned, ~86 GiB), KV_INT8=1, CPU_PLAN=012234567, MTP_KEEP=2, prefetch N=1 at fetch / 4 blocks / rank 2, PREFILL_MB=3072, TRUNK_KEEP_MAP=8888888888888888888888855555554444444444444448 (#103: keep 8 on layers 0-22, 5 on 23-29, 4 on 30-44, 8 on the last)
Drafter GLM-5.3-Flash-DFlash2-Q4_K_M.gguf, sha256 checked (f4158ffb...), passed as --dflash in the config's args

Method

One fresh start per row; then two warm API runs through the real server: a fresh 21K-token prompt (prefill), then 2,500
tokens decoded at 21K depth. Sampling is the installed one (T 1.0, top_p 0.95; so acceptance is of sampled tokens). Same
engine build, same config copy; only the drafting and the cards differ between rows. The SSD is never read (storage reads
are 0.00-0.17 GB in the first run, 0.00-0.03 GB after). Noise between two runs of one setup is about +-0.3 tok/s.

Results

Two cards (3090 + 3060, split 28/17)

drafting decode tok/s (run 1, run 2) prefill tok/s drafts accepted
MTP block (the default) 23.97 (23.77, 24.17) 764, 759 69.6% of 6,188 positions
DFlash2, default window 11.95 (11.73, 12.16) 765, 732 66.1% of 4,271
DFlash2, --spec 2 12.10 (12.17, 12.03) 767, 735 64.0% of 3,779
DFlash2, default window, STRATA_GLM_WIN_ALLCPU=0 14.16 (14.08, 14.25) 767, 699 64.7% of 4,312
DFlash2, --spec 2, STRATA_GLM_WIN_ALLCPU=0 14.27 (14.30, 14.24) 765, 686 65.4% of 3,746

One card (the 3090 alone, STRATA_GLM_SPLIT=0; no MTP block on one GPU, so the baseline is plain decode)

drafting decode tok/s (run 1, run 2) prefill tok/s drafts accepted
none (plain decode) 19.01 (19.01, 19.00) 629, 627 -
DFlash2, default window 14.74 (14.72, 14.76) 628, 616 90.0% of 2,254
DFlash2, --spec 2 14.57 (14.60, 14.54) 627, 616 93.2% of 1,814
DFlash2, default window, STRATA_GLM_WIN_ALLCPU=0 14.66 (14.42, 14.89) 626, 613 88.6% of 2,281

For reference, a third card (the RTX 4000, 4 layers, MTP block, RAM_HEADROOM_GB=16, auto split 0-29 / 30-40 / 41-44):
24.32 tok/s in the first run (the second run's decode line was not parsed by our harness; the engine's own per-token
counter reads about 24.3), prefill 692 and 646 tok/s, 71.6% of 6,157 positions accepted. Not DFlash2, just context for what
more VRAM buys on this box (+1.4% decode, about -12% prefill).

What the logs show

  • The drafter is right, the window is expensive. On one card 88-93% of the drafts are accepted, yet decode is 22-23%
    below plain decode. On two cards the accepted share is about that of the MTP block, and decode is half.
  • The window pass leans on the CPU lane. The log line glm dflash: a batched window's layer on both parts' CPU pools and
    the documented default (every RAM-tier expert of a window to the CPU) fit the numbers: about 86 GiB of the experts are
    RAM-resident here, a window of N tokens touches close to N different experts per layer, and the lane reads them from
    DDR4. The MTP block's one-draft check re-reads far fewer. The calibrated plan (WIN_ALLCPU=0) lifts two cards from
    11.95 to 14.16 (+19%), which supports this reading; it does not close the gap to 23.97.
  • The window length did not matter. --spec 2 (the token and one draft) is within noise of the default window in all
    three pairs; the two-card default already checks few drafts.
  • Prefill: the first run of every setup reads the same (2 cards 764-767, 1 card 626-629 tok/s). The second run of the
    2-card DFlash2 setups was lower (686-735 against 759 for the MTP block's second run); we did not investigate whether
    that is run-to-run spread or the drafter's state. The 1-card pairs are within 2%.

Not tried (so the table is not the last word)

STRATA_GLM_WIN_CPU, _WIN_STAGGER, _WIN_LANES, --spec-min-p / STRATA_GLM_DFLASH_MIN, DFlash2 on three cards (the
pipelined window, which is the case the release's +44% was measured on), and long-context or code-heavy prompts (all of
the above used one 21K document prompt, T 1.0). The first two-card number with the MTP block (23.97) is v1.1.0 on our
installed settings, so it can be reproduced by anyone with Maya-M.

Reproduce (stock v1.1.0, nothing else needed)

The variants differ from the installed Maya-M config only in these keys (maya-maya-m.json, "args" / "gpu" / "env"):

variant change
2 cards, MTP block none (the config as it is)
2 cards, DFlash2 "args": append "--dflash", "/path/GLM-5.3-Flash-DFlash2-Q4_K_M.gguf" (the file ./maya.sh --setup --draft dflash2 downloads)
2 cards, short window the same, plus "--spec", "2" in "args"
calibrated window plan the same, plus "STRATA_GLM_WIN_ALLCPU": "0" in "env"
1 card, plain "gpu": only the first card, "STRATA_GLM_SPLIT": "0" in "env", and STRATA_GLM_MTP_KEEP removed
1 card, DFlash2 the 1-card change plus the --dflash arguments

Measuring: start the server from the config, send one fresh prompt of about 21,000 tokens (prefill rate = prompt tokens over
the time to the first token), then, at that depth, request 2,500 more tokens and read the decode rate from the response or
from the engine log's glm stat: decode ... (N tok/s) lines; the drafts line is glm spec: N of M drafts accepted.
The one thing that is ours is the small client that does this (a 21K prompt, then 2,500 tokens, two runs, over the
OpenAI-compatible streaming API); it is attached below, python3 only, no packages.

speed_21k_api.py - the 21K client (python3 only)

Run it against the running server, once per start (the first request is a warm-up and is discarded):

python3 speed_21k_api.py --url http://localhost:9931 --label "2 cards, MTP" --no-append

It needs a text file prompt_src.txt next to it: the corpus it repeats three times (with section markers and a nonce
opening line, so no prompt cache can help) to make the ~21K-token prompt. Ours is the README.md of ggml-org/llama.cpp
(a copy from late August 2026, 26,000 bytes, about 7K tokens); any document of about that size works, but then the numbers
are not strictly comparable with ours. --no-append skips the log row it would otherwise append under ~/Local-AI/Logs.

#!/usr/bin/env python3
"""speed_21k_api.py — the warm 21K speed test, measured from OUTSIDE the engine (2026-09-19, Mile + Claude).

Why: llama-test-21k.sh reads prefill / decode speed from llama-server's own log, so it only works with
llama.cpp. This tool measures the same protocol over the OpenAI-compatible STREAMING API that every
engine offers (llama-server, oMLX, MTPLX, mlx_lm.server, …), so models and engines on the MacBook get
numbers that can be set beside each other — and beside the Linux rows. Not perfect: a reference.

Protocol (the same three requests and the same prompt texts as llama-test-21k.sh):
  1. 7K prompt, 300 tokens                      — warm-up, timings DISCARDED
  2. fresh ~21K prompt (3 corpus units + a nonce opening line so no prompt cache can help), 300 tokens
                                                — PREFILL of record = prompt tokens / time to the first token
  3. follow-up turn, 2,500 tokens at ~21K depth — DECODE of record = generated tokens / time after the first token

What the numbers mean, and their limits:
  - "time to the first token" includes the request's network + queue time and, on some engines, the first
    decode step; on a local server that is a few tens of ms against many seconds of prefill.
  - Phase 3 re-sends the whole conversation; an engine WITH a prompt cache only prefills the new turn, one
    WITHOUT re-reads all 21K. The tool reports phase 3's time to the first token so this is visible, but
    only phase 2 is the prefill number.
  - Token counts come from the API's `usage` (asked for with stream_options.include_usage). If an engine
    sends none, the tool falls back to the server's /tokenize (llama.cpp) and, failing that, to counting
    streamed chunks — the row is then marked "estimated".
  - Reasoning tokens count as generated tokens (they are decoded like any other).
  - Draft / MTP acceptance is engine-specific and NOT measured here; read it from the engine's log.

Usage:
  python3 speed_21k_api.py [--url http://localhost:9931] [--model NAME] [--label TEXT] [--api-key KEY]
                           [--units 3] [--gen 2500] [--no-append] [--temperature T]
  --url      base URL of the server WITHOUT /v1 (default http://localhost:9931; oMLX and MTPLX have their own port)
  --model    model id to send; default = the first id the server lists under /v1/models
  --label    free text for the row (engine, build, settings)
  --units    corpus units in the long prompt: 3 = ~21K (default), 9 = ~63K, 18 = ~126K
  --temperature  only if you want to override the server's / model's default sampler (default: not sent)
Output: a summary block, and one row appended to Logs/21K-API-TESTS.md next to the other test logs
(~/Local-AI/Logs on both machines; created if missing). Needs only python3 (no packages).
"""
import argparse, json, os, sys, time, urllib.error, urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.join(HERE, "prompt_src.txt")
LOGS = os.path.expanduser("~/Local-AI/Logs")
FOLLOW_UP = ("Now write a detailed, well-structured essay of about 2000 words analysing the design decisions "
             "described in this documentation: the trade-offs chosen, the alternatives rejected, the risks that "
             "remain, and what a maintainer should watch. Use headings and full paragraphs.")


def die(msg, code=1):
    print("ERROR: " + msg)
    sys.exit(code)


def http_json(url, payload=None, key=None, timeout=60):
    req = urllib.request.Request(url, data=json.dumps(payload).encode() if payload is not None else None,
                                 headers={"Content-Type": "application/json",
                                          **({"Authorization": "Bearer " + key} if key else {})})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.load(r)


def long_prompt(units):
    """Same text as make_long_prompt.sh N (the corpus repeated with section markers)."""
    src = open(SRC, encoding="utf-8", errors="replace").read()
    return "".join(src + "\n\n--- SECTION %d ---\n\n" % i for i in range(1, units + 1)), src


def count_tokens(base, text, key):
    """llama.cpp's /tokenize if the server has it, else None."""
    try:
        return len(http_json(base + "/tokenize", {"content": text}, key, timeout=120)["tokens"])
    except Exception:
        return None


TOP_K = None   # --top-k: sent with every request when given (the sampler test of 2026-10-11); default: not sent


def stream_chat(base, model, messages, max_tokens, key, temperature=None, timeout=7200):
    """One streamed chat request. Returns a dict with timings and token counts."""
    payload = {"model": model, "messages": messages, "max_tokens": max_tokens, "stream": True,
               "stream_options": {"include_usage": True}}
    if temperature is not None:
        payload["temperature"] = temperature
    if TOP_K is not None:
        payload["top_k"] = TOP_K
    req = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps(payload).encode(),
                                 headers={"Content-Type": "application/json", "Accept": "text/event-stream",
                                          **({"Authorization": "Bearer " + key} if key else {})})
    t0 = time.monotonic()
    t_first = t_last = None
    chunks = 0
    usage = None
    text_parts = []
    finish = None
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            for raw in r:
                line = raw.decode("utf-8", "replace").strip()
                if not line.startswith("data:"):
                    continue
                data = line[5:].strip()
                if data == "[DONE]":
                    break
                try:
                    ev = json.loads(data)
                except json.JSONDecodeError:
                    continue
                if ev.get("usage"):
                    usage = ev["usage"]
                for ch in ev.get("choices") or []:
                    d = ch.get("delta") or {}
                    piece = d.get("content") or d.get("reasoning_content") or d.get("reasoning") or ""
                    if piece:
                        now = time.monotonic()
                        if t_first is None:
                            t_first = now
                        t_last = now
                        chunks += 1
                        if d.get("content"):
                            text_parts.append(d["content"])
                    if ch.get("finish_reason"):
                        finish = ch["finish_reason"]
    except urllib.error.HTTPError as e:
        body = ""
        try:
            body = e.read().decode("utf-8", "replace")[:400]
        except Exception:
            pass
        die(f"the server answered HTTP {e.code} to the chat request: {body}")
    except (urllib.error.URLError, TimeoutError, OSError) as e:
        die(f"the chat request failed: {e}")
    t_end = time.monotonic()
    if t_first is None:
        die("the server streamed no text at all (no content and no reasoning deltas) — cannot time this engine "
            "through the streaming API. Check that it supports stream=true.")
    return {"ttft": t_first - t0, "gen_time": (t_last - t_first), "total": t_end - t0, "chunks": chunks,
            "usage": usage, "text": "".join(text_parts), "finish": finish}


def main():
    ap = argparse.ArgumentParser(description="Warm 21K speed test over the OpenAI-compatible streaming API.")
    ap.add_argument("--url", default="http://localhost:9931")
    ap.add_argument("--model")
    ap.add_argument("--label", default="")
    ap.add_argument("--api-key", default=os.environ.get("OPENAI_API_KEY") or None)
    ap.add_argument("--units", type=int, default=3)
    ap.add_argument("--gen", type=int, default=2500)
    ap.add_argument("--temperature", type=float)
    ap.add_argument("--top-k", type=int, help="send top_k with every request (default: not sent = the server's own)")
    ap.add_argument("--no-append", action="store_true")
    a = ap.parse_args()
    global TOP_K
    TOP_K = a.top_k
    if a.units < 1 or a.units > 40:
        die("--units must be between 1 and 40.", 2)
    if a.gen < 100:
        die("--gen must be at least 100 tokens, or the decode number means nothing.", 2)
    if not os.path.isfile(SRC):
        die(f"the fixed corpus is missing: {SRC}")
    base = a.url.rstrip("/")
    if base.endswith("/v1"):
        base = base[:-3]

    model = a.model
    if not model:
        try:
            model = http_json(base + "/v1/models", key=a.api_key, timeout=30)["data"][0]["id"]
        except Exception as e:
            die(f"could not read /v1/models at {base} ({e}) — is the server up, is --url right? Or pass --model.")
    text, src = long_prompt(a.units)
    depth = f"{a.units * 7}K"
    t_start = time.strftime("%Y-%m-%d %H:%M")
    print(f"Server: {base}   model: {model}   label: {a.label or '-'}")

    print("Phase 1/3: 7K warm-up (timings discarded) …", flush=True)
    stream_chat(base, model, [{"role": "user", "content": "Summarize the following documentation in about 10 sentences:\n\n" + src}],
                300, a.api_key, a.temperature)

    print(f"Phase 2/3: fresh {depth} prefill …", flush=True)
    nonce = time.strftime("Run %Y-%m-%d %H:%M:%S. ")
    msgs = [{"role": "user", "content": nonce + "You are reviewing a technical manual. Read all of it, then give a 10-sentence summary:\n\n" + text}]
    p2 = stream_chat(base, model, msgs, 300, a.api_key, a.temperature)
    estimated = False
    prompt_tok = (p2["usage"] or {}).get("prompt_tokens")
    if not prompt_tok:
        prompt_tok = count_tokens(base, msgs[0]["content"], a.api_key)
        estimated = True
    if not prompt_tok:
        prompt_tok = int(len(msgs[0]["content"]) / 3.7)      # rough: this corpus runs ~3.7 characters per token
    cached = ((p2["usage"] or {}).get("prompt_tokens_details") or {}).get("cached_tokens") or 0
    fresh = prompt_tok - cached
    prefill = fresh / p2["ttft"]
    gen2 = (p2["usage"] or {}).get("completion_tokens") or p2["chunks"]
    dec300 = (gen2 - 1) / p2["gen_time"] if p2["gen_time"] > 0 and gen2 > 1 else 0.0

    print(f"Phase 3/3: {a.gen} tokens at {depth} depth …", flush=True)
    reply = p2["text"] or "I have read the manual and can summarize or expand on it."
    conv = msgs + [{"role": "assistant", "content": reply}, {"role": "user", "content": FOLLOW_UP}]
    p3 = stream_chat(base, model, conv, a.gen, a.api_key, a.temperature)
    gen3 = (p3["usage"] or {}).get("completion_tokens")
    if not gen3:
        gen3 = p3["chunks"]
        estimated = True
    decode = (gen3 - 1) / p3["gen_time"] if p3["gen_time"] > 0 and gen3 > 1 else 0.0
    ms_tok = 1000.0 / decode if decode else 0.0
    short = gen3 < a.gen * 0.8
    mark = " (ESTIMATED token counts)" if estimated else ""

    print()
    print("=" * 76)
    print(f" {depth} API TEST  {t_start}   model {model}   {a.label}")
    print(f" prefill (fresh {depth})        : {prefill:8.2f} t/s over {fresh} fresh tokens, first token after {p2['ttft']:.2f} s"
          + (f"  ({cached} tokens came from a cache!)" if cached > 500 else "") + mark)
    print(f" decode  (@{depth}, {gen3} tokens): {decode:8.2f} t/s = {ms_tok:.2f} ms/tok"
          + ("   NOTE: the model stopped early, a short sample" if short else "") + mark)
    print(f" decode  (@{depth}, first {gen2}-token reply): {dec300:.2f} t/s")
    print(f" phase 3 first token after    : {p3['ttft']:.2f} s (small = the engine reused the {depth} prompt; large = it re-read it)")
    print("=" * 76)

    if not a.no_append:
        os.makedirs(LOGS, exist_ok=True)
        out = os.path.join(LOGS, "21K-API-TESTS.md")
        new = not os.path.exists(out)
        with open(out, "a", encoding="utf-8") as fh:
            if new:
                fh.write("# Speed tests over the streaming API (speed_21k_api.py) — 7K discard, fresh prefill, N tokens at depth\n\n"
                         "| date | host | url | model | label | depth | prefill t/s | fresh tokens | TTFT s | decode t/s | ms/tok | gen tokens | first-reply t/s | phase-3 TTFT s | notes |\n"
                         "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|\n")
            notes = "; ".join(x for x in ["estimated counts" if estimated else "", "stopped early" if short else "",
                                          f"{cached} cached" if cached > 500 else ""] if x)
            fh.write(f"| {t_start} | {os.uname().nodename} | {base} | {model} | {a.label} | {depth} | {prefill:.2f} | {fresh} | "
                     f"{p2['ttft']:.2f} | {decode:.2f} | {ms_tok:.2f} | {gen3} | {dec300:.2f} | {p3['ttft']:.2f} | {notes} |\n")
        print(f" appended to {out}")


if __name__ == "__main__":
    main()

Prepared with the help of Claude, an AI assistant by Anthropic.

bench-dflash2-2026-10-12.zip

Originally created by @sociolog on GitHub (Oct 12, 2026). Original GitHub issue: https://github.com/mw00/project-maya/issues/127 **Short version:** on this machine the MTP block stays the better drafter. DFlash2 is correct (drafts are accepted 64-93% of the time) but its verify window costs more than it saves: 2 cards 11.95-14.27 tok/s against 23.97 for the MTP block, and 1 card 14.57-14.74 against 19.01 for plain decode. Switching the window's RAM-tier experts from "all on the CPU" to the calibrated CPU / PCIe plan (`STRATA_GLM_WIN_ALLCPU=0`) recovers about 19% on two cards, but not the gap. Posting this as data for the 1-2 GPU tuning you mentioned; happy to measure anything you want varied. ### The machine and the model | | | |---|---| | CPU / RAM | Ryzen 9 5900X (12 cores, one NUMA node, SMT on), 128 GB DDR4; the engine measures 46 GB/s host reads | | GPUs | RTX 3090 24 GB (CUDA0), RTX 3060 12 GB (CUDA1); a Quadro RTX 4000 only drives displays (not used) | | OS / toolchain | Linux Mint (kernel 7.0), CUDA 12.8, v1.1.0 built from the tag, no local patches | | Model | Maya-M (112 GB), 245,760 context | | Settings | `STRATA_GLM_SPLIT=28`, `RAM_RESIDENT=1` (RAM tier 47.8 + 38.6 GB pinned, ~86 GiB), `KV_INT8=1`, `CPU_PLAN=012234567`, `MTP_KEEP=2`, prefetch N=1 at fetch / 4 blocks / rank 2, `PREFILL_MB=3072`, `TRUNK_KEEP_MAP=8888888888888888888888855555554444444444444448` (#103: keep 8 on layers 0-22, 5 on 23-29, 4 on 30-44, 8 on the last) | | Drafter | `GLM-5.3-Flash-DFlash2-Q4_K_M.gguf`, sha256 checked (`f4158ffb...`), passed as `--dflash` in the config's args | ### Method One fresh start per row; then two warm API runs through the real server: a fresh 21K-token prompt (prefill), then 2,500 tokens decoded at 21K depth. Sampling is the installed one (T 1.0, top_p 0.95; so acceptance is of sampled tokens). Same engine build, same config copy; only the drafting and the cards differ between rows. The SSD is never read (storage reads are 0.00-0.17 GB in the first run, 0.00-0.03 GB after). Noise between two runs of one setup is about +-0.3 tok/s. ### Results **Two cards (3090 + 3060, split 28/17)** | drafting | decode tok/s (run 1, run 2) | prefill tok/s | drafts accepted | |---|---|---|---| | MTP block (the default) | **23.97** (23.77, 24.17) | 764, 759 | 69.6% of 6,188 positions | | DFlash2, default window | 11.95 (11.73, 12.16) | 765, 732 | 66.1% of 4,271 | | DFlash2, `--spec 2` | 12.10 (12.17, 12.03) | 767, 735 | 64.0% of 3,779 | | DFlash2, default window, `STRATA_GLM_WIN_ALLCPU=0` | 14.16 (14.08, 14.25) | 767, 699 | 64.7% of 4,312 | | DFlash2, `--spec 2`, `STRATA_GLM_WIN_ALLCPU=0` | 14.27 (14.30, 14.24) | 765, 686 | 65.4% of 3,746 | **One card (the 3090 alone, `STRATA_GLM_SPLIT=0`; no MTP block on one GPU, so the baseline is plain decode)** | drafting | decode tok/s (run 1, run 2) | prefill tok/s | drafts accepted | |---|---|---|---| | none (plain decode) | **19.01** (19.01, 19.00) | 629, 627 | - | | DFlash2, default window | 14.74 (14.72, 14.76) | 628, 616 | 90.0% of 2,254 | | DFlash2, `--spec 2` | 14.57 (14.60, 14.54) | 627, 616 | 93.2% of 1,814 | | DFlash2, default window, `STRATA_GLM_WIN_ALLCPU=0` | 14.66 (14.42, 14.89) | 626, 613 | 88.6% of 2,281 | For reference, a third card (the RTX 4000, 4 layers, MTP block, `RAM_HEADROOM_GB=16`, auto split 0-29 / 30-40 / 41-44): 24.32 tok/s in the first run (the second run's decode line was not parsed by our harness; the engine's own per-token counter reads about 24.3), prefill 692 and 646 tok/s, 71.6% of 6,157 positions accepted. Not DFlash2, just context for what more VRAM buys on this box (+1.4% decode, about -12% prefill). ### What the logs show - **The drafter is right, the window is expensive.** On one card 88-93% of the drafts are accepted, yet decode is 22-23% below plain decode. On two cards the accepted share is about that of the MTP block, and decode is half. - **The window pass leans on the CPU lane.** The log line `glm dflash: a batched window's layer on both parts' CPU pools` and the documented default (every RAM-tier expert of a window to the CPU) fit the numbers: about 86 GiB of the experts are RAM-resident here, a window of N tokens touches close to N different experts per layer, and the lane reads them from DDR4. The MTP block's one-draft check re-reads far fewer. The calibrated plan (`WIN_ALLCPU=0`) lifts two cards from 11.95 to 14.16 (+19%), which supports this reading; it does not close the gap to 23.97. - **The window length did not matter.** `--spec 2` (the token and one draft) is within noise of the default window in all three pairs; the two-card default already checks few drafts. - **Prefill:** the first run of every setup reads the same (2 cards 764-767, 1 card 626-629 tok/s). The second run of the 2-card DFlash2 setups was lower (686-735 against 759 for the MTP block's second run); we did not investigate whether that is run-to-run spread or the drafter's state. The 1-card pairs are within 2%. ### Not tried (so the table is not the last word) `STRATA_GLM_WIN_CPU`, `_WIN_STAGGER`, `_WIN_LANES`, `--spec-min-p` / `STRATA_GLM_DFLASH_MIN`, DFlash2 on three cards (the pipelined window, which is the case the release's +44% was measured on), and long-context or code-heavy prompts (all of the above used one 21K document prompt, T 1.0). The first two-card number with the MTP block (23.97) is v1.1.0 on our installed settings, so it can be reproduced by anyone with Maya-M. ### Reproduce (stock v1.1.0, nothing else needed) The variants differ from the installed Maya-M config only in these keys (`maya-maya-m.json`, `"args"` / `"gpu"` / `"env"`): | variant | change | |---|---| | 2 cards, MTP block | none (the config as it is) | | 2 cards, DFlash2 | `"args"`: append `"--dflash", "/path/GLM-5.3-Flash-DFlash2-Q4_K_M.gguf"` (the file `./maya.sh --setup --draft dflash2` downloads) | | 2 cards, short window | the same, plus `"--spec", "2"` in `"args"` | | calibrated window plan | the same, plus `"STRATA_GLM_WIN_ALLCPU": "0"` in `"env"` | | 1 card, plain | `"gpu"`: only the first card, `"STRATA_GLM_SPLIT": "0"` in `"env"`, and `STRATA_GLM_MTP_KEEP` removed | | 1 card, DFlash2 | the 1-card change plus the `--dflash` arguments | Measuring: start the server from the config, send one fresh prompt of about 21,000 tokens (prefill rate = prompt tokens over the time to the first token), then, at that depth, request 2,500 more tokens and read the decode rate from the response or from the engine log's `glm stat: decode ... (N tok/s)` lines; the drafts line is `glm spec: N of M drafts accepted`. The one thing that is ours is the small client that does this (a 21K prompt, then 2,500 tokens, two runs, over the OpenAI-compatible streaming API); it is attached below, python3 only, no packages. <details> <summary>speed_21k_api.py - the 21K client (python3 only)</summary> Run it against the running server, once per start (the first request is a warm-up and is discarded): ``` python3 speed_21k_api.py --url http://localhost:9931 --label "2 cards, MTP" --no-append ``` It needs a text file `prompt_src.txt` next to it: the corpus it repeats three times (with section markers and a nonce opening line, so no prompt cache can help) to make the ~21K-token prompt. Ours is the `README.md` of ggml-org/llama.cpp (a copy from late August 2026, 26,000 bytes, about 7K tokens); any document of about that size works, but then the numbers are not strictly comparable with ours. `--no-append` skips the log row it would otherwise append under `~/Local-AI/Logs`. ```python #!/usr/bin/env python3 """speed_21k_api.py — the warm 21K speed test, measured from OUTSIDE the engine (2026-09-19, Mile + Claude). Why: llama-test-21k.sh reads prefill / decode speed from llama-server's own log, so it only works with llama.cpp. This tool measures the same protocol over the OpenAI-compatible STREAMING API that every engine offers (llama-server, oMLX, MTPLX, mlx_lm.server, …), so models and engines on the MacBook get numbers that can be set beside each other — and beside the Linux rows. Not perfect: a reference. Protocol (the same three requests and the same prompt texts as llama-test-21k.sh): 1. 7K prompt, 300 tokens — warm-up, timings DISCARDED 2. fresh ~21K prompt (3 corpus units + a nonce opening line so no prompt cache can help), 300 tokens — PREFILL of record = prompt tokens / time to the first token 3. follow-up turn, 2,500 tokens at ~21K depth — DECODE of record = generated tokens / time after the first token What the numbers mean, and their limits: - "time to the first token" includes the request's network + queue time and, on some engines, the first decode step; on a local server that is a few tens of ms against many seconds of prefill. - Phase 3 re-sends the whole conversation; an engine WITH a prompt cache only prefills the new turn, one WITHOUT re-reads all 21K. The tool reports phase 3's time to the first token so this is visible, but only phase 2 is the prefill number. - Token counts come from the API's `usage` (asked for with stream_options.include_usage). If an engine sends none, the tool falls back to the server's /tokenize (llama.cpp) and, failing that, to counting streamed chunks — the row is then marked "estimated". - Reasoning tokens count as generated tokens (they are decoded like any other). - Draft / MTP acceptance is engine-specific and NOT measured here; read it from the engine's log. Usage: python3 speed_21k_api.py [--url http://localhost:9931] [--model NAME] [--label TEXT] [--api-key KEY] [--units 3] [--gen 2500] [--no-append] [--temperature T] --url base URL of the server WITHOUT /v1 (default http://localhost:9931; oMLX and MTPLX have their own port) --model model id to send; default = the first id the server lists under /v1/models --label free text for the row (engine, build, settings) --units corpus units in the long prompt: 3 = ~21K (default), 9 = ~63K, 18 = ~126K --temperature only if you want to override the server's / model's default sampler (default: not sent) Output: a summary block, and one row appended to Logs/21K-API-TESTS.md next to the other test logs (~/Local-AI/Logs on both machines; created if missing). Needs only python3 (no packages). """ import argparse, json, os, sys, time, urllib.error, urllib.request HERE = os.path.dirname(os.path.abspath(__file__)) SRC = os.path.join(HERE, "prompt_src.txt") LOGS = os.path.expanduser("~/Local-AI/Logs") FOLLOW_UP = ("Now write a detailed, well-structured essay of about 2000 words analysing the design decisions " "described in this documentation: the trade-offs chosen, the alternatives rejected, the risks that " "remain, and what a maintainer should watch. Use headings and full paragraphs.") def die(msg, code=1): print("ERROR: " + msg) sys.exit(code) def http_json(url, payload=None, key=None, timeout=60): req = urllib.request.Request(url, data=json.dumps(payload).encode() if payload is not None else None, headers={"Content-Type": "application/json", **({"Authorization": "Bearer " + key} if key else {})}) with urllib.request.urlopen(req, timeout=timeout) as r: return json.load(r) def long_prompt(units): """Same text as make_long_prompt.sh N (the corpus repeated with section markers).""" src = open(SRC, encoding="utf-8", errors="replace").read() return "".join(src + "\n\n--- SECTION %d ---\n\n" % i for i in range(1, units + 1)), src def count_tokens(base, text, key): """llama.cpp's /tokenize if the server has it, else None.""" try: return len(http_json(base + "/tokenize", {"content": text}, key, timeout=120)["tokens"]) except Exception: return None TOP_K = None # --top-k: sent with every request when given (the sampler test of 2026-10-11); default: not sent def stream_chat(base, model, messages, max_tokens, key, temperature=None, timeout=7200): """One streamed chat request. Returns a dict with timings and token counts.""" payload = {"model": model, "messages": messages, "max_tokens": max_tokens, "stream": True, "stream_options": {"include_usage": True}} if temperature is not None: payload["temperature"] = temperature if TOP_K is not None: payload["top_k"] = TOP_K req = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps(payload).encode(), headers={"Content-Type": "application/json", "Accept": "text/event-stream", **({"Authorization": "Bearer " + key} if key else {})}) t0 = time.monotonic() t_first = t_last = None chunks = 0 usage = None text_parts = [] finish = None try: with urllib.request.urlopen(req, timeout=timeout) as r: for raw in r: line = raw.decode("utf-8", "replace").strip() if not line.startswith("data:"): continue data = line[5:].strip() if data == "[DONE]": break try: ev = json.loads(data) except json.JSONDecodeError: continue if ev.get("usage"): usage = ev["usage"] for ch in ev.get("choices") or []: d = ch.get("delta") or {} piece = d.get("content") or d.get("reasoning_content") or d.get("reasoning") or "" if piece: now = time.monotonic() if t_first is None: t_first = now t_last = now chunks += 1 if d.get("content"): text_parts.append(d["content"]) if ch.get("finish_reason"): finish = ch["finish_reason"] except urllib.error.HTTPError as e: body = "" try: body = e.read().decode("utf-8", "replace")[:400] except Exception: pass die(f"the server answered HTTP {e.code} to the chat request: {body}") except (urllib.error.URLError, TimeoutError, OSError) as e: die(f"the chat request failed: {e}") t_end = time.monotonic() if t_first is None: die("the server streamed no text at all (no content and no reasoning deltas) — cannot time this engine " "through the streaming API. Check that it supports stream=true.") return {"ttft": t_first - t0, "gen_time": (t_last - t_first), "total": t_end - t0, "chunks": chunks, "usage": usage, "text": "".join(text_parts), "finish": finish} def main(): ap = argparse.ArgumentParser(description="Warm 21K speed test over the OpenAI-compatible streaming API.") ap.add_argument("--url", default="http://localhost:9931") ap.add_argument("--model") ap.add_argument("--label", default="") ap.add_argument("--api-key", default=os.environ.get("OPENAI_API_KEY") or None) ap.add_argument("--units", type=int, default=3) ap.add_argument("--gen", type=int, default=2500) ap.add_argument("--temperature", type=float) ap.add_argument("--top-k", type=int, help="send top_k with every request (default: not sent = the server's own)") ap.add_argument("--no-append", action="store_true") a = ap.parse_args() global TOP_K TOP_K = a.top_k if a.units < 1 or a.units > 40: die("--units must be between 1 and 40.", 2) if a.gen < 100: die("--gen must be at least 100 tokens, or the decode number means nothing.", 2) if not os.path.isfile(SRC): die(f"the fixed corpus is missing: {SRC}") base = a.url.rstrip("/") if base.endswith("/v1"): base = base[:-3] model = a.model if not model: try: model = http_json(base + "/v1/models", key=a.api_key, timeout=30)["data"][0]["id"] except Exception as e: die(f"could not read /v1/models at {base} ({e}) — is the server up, is --url right? Or pass --model.") text, src = long_prompt(a.units) depth = f"{a.units * 7}K" t_start = time.strftime("%Y-%m-%d %H:%M") print(f"Server: {base} model: {model} label: {a.label or '-'}") print("Phase 1/3: 7K warm-up (timings discarded) …", flush=True) stream_chat(base, model, [{"role": "user", "content": "Summarize the following documentation in about 10 sentences:\n\n" + src}], 300, a.api_key, a.temperature) print(f"Phase 2/3: fresh {depth} prefill …", flush=True) nonce = time.strftime("Run %Y-%m-%d %H:%M:%S. ") msgs = [{"role": "user", "content": nonce + "You are reviewing a technical manual. Read all of it, then give a 10-sentence summary:\n\n" + text}] p2 = stream_chat(base, model, msgs, 300, a.api_key, a.temperature) estimated = False prompt_tok = (p2["usage"] or {}).get("prompt_tokens") if not prompt_tok: prompt_tok = count_tokens(base, msgs[0]["content"], a.api_key) estimated = True if not prompt_tok: prompt_tok = int(len(msgs[0]["content"]) / 3.7) # rough: this corpus runs ~3.7 characters per token cached = ((p2["usage"] or {}).get("prompt_tokens_details") or {}).get("cached_tokens") or 0 fresh = prompt_tok - cached prefill = fresh / p2["ttft"] gen2 = (p2["usage"] or {}).get("completion_tokens") or p2["chunks"] dec300 = (gen2 - 1) / p2["gen_time"] if p2["gen_time"] > 0 and gen2 > 1 else 0.0 print(f"Phase 3/3: {a.gen} tokens at {depth} depth …", flush=True) reply = p2["text"] or "I have read the manual and can summarize or expand on it." conv = msgs + [{"role": "assistant", "content": reply}, {"role": "user", "content": FOLLOW_UP}] p3 = stream_chat(base, model, conv, a.gen, a.api_key, a.temperature) gen3 = (p3["usage"] or {}).get("completion_tokens") if not gen3: gen3 = p3["chunks"] estimated = True decode = (gen3 - 1) / p3["gen_time"] if p3["gen_time"] > 0 and gen3 > 1 else 0.0 ms_tok = 1000.0 / decode if decode else 0.0 short = gen3 < a.gen * 0.8 mark = " (ESTIMATED token counts)" if estimated else "" print() print("=" * 76) print(f" {depth} API TEST {t_start} model {model} {a.label}") print(f" prefill (fresh {depth}) : {prefill:8.2f} t/s over {fresh} fresh tokens, first token after {p2['ttft']:.2f} s" + (f" ({cached} tokens came from a cache!)" if cached > 500 else "") + mark) print(f" decode (@{depth}, {gen3} tokens): {decode:8.2f} t/s = {ms_tok:.2f} ms/tok" + (" NOTE: the model stopped early, a short sample" if short else "") + mark) print(f" decode (@{depth}, first {gen2}-token reply): {dec300:.2f} t/s") print(f" phase 3 first token after : {p3['ttft']:.2f} s (small = the engine reused the {depth} prompt; large = it re-read it)") print("=" * 76) if not a.no_append: os.makedirs(LOGS, exist_ok=True) out = os.path.join(LOGS, "21K-API-TESTS.md") new = not os.path.exists(out) with open(out, "a", encoding="utf-8") as fh: if new: fh.write("# Speed tests over the streaming API (speed_21k_api.py) — 7K discard, fresh prefill, N tokens at depth\n\n" "| date | host | url | model | label | depth | prefill t/s | fresh tokens | TTFT s | decode t/s | ms/tok | gen tokens | first-reply t/s | phase-3 TTFT s | notes |\n" "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|\n") notes = "; ".join(x for x in ["estimated counts" if estimated else "", "stopped early" if short else "", f"{cached} cached" if cached > 500 else ""] if x) fh.write(f"| {t_start} | {os.uname().nodename} | {base} | {model} | {a.label} | {depth} | {prefill:.2f} | {fresh} | " f"{p2['ttft']:.2f} | {decode:.2f} | {ms_tok:.2f} | {gen3} | {dec300:.2f} | {p3['ttft']:.2f} | {notes} |\n") print(f" appended to {out}") if __name__ == "__main__": main() ``` </details> *Prepared with the help of Claude, an AI assistant by Anthropic.* [bench-dflash2-2026-10-12.zip](https://github.com/user-attachments/files/33321254/bench-dflash2-2026-10-12.zip)
Author
Owner

@mw00 commented on GitHub (Oct 12, 2026):

Thank you - ten setups on one and two cards is exactly the data we needed. It matches what we measured on Tesla V100s:
where most experts come from RAM, the verify window's extra routes cost more than the drafts save, and the MTP block
stays faster. v1.1.1 says so in the setup's drafting question and in the docs ("measure yours with --bench"); the MTP
block stays the default.

<!-- gh-comment-id:6119995588 --> @mw00 commented on GitHub (Oct 12, 2026): Thank you - ten setups on one and two cards is exactly the data we needed. It matches what we measured on Tesla V100s: where most experts come from RAM, the verify window's extra routes cost more than the drafts save, and the MTP block stays faster. v1.1.1 says so in the setup's drafting question and in the docs ("measure yours with `--bench`"); the MTP block stays the default.
Author
Owner

@mw00 commented on GitHub (Oct 12, 2026):

Following up on this in v1.1.3: DFlash2 is now checked on each PC. When the setup drafts with it - and once, at the first start after the update, for a config that already does - a speed calibration loads the model twice (without and with --dflash), reads a long document, writes about 1,500 sampled tokens of answers after a warm-up on each, and keeps DFlash2 only when its sustained decode is more than 5% faster than the MTP block's (one GPU: than no drafting). On a PC like yours it would keep the MTP block by itself. ./maya.sh --speed-calibration measures again; --draft dflash2 --no-speed-calibration keeps DFlash2 without it.

Your ten setups were the data that made the case for it - thank you.

<!-- gh-comment-id:6125778867 --> @mw00 commented on GitHub (Oct 12, 2026): Following up on this in [v1.1.3](https://github.com/mw00/project-maya/releases/tag/v1.1.3): DFlash2 is now checked on each PC. When the setup drafts with it - and once, at the first start after the update, for a config that already does - a **speed calibration** loads the model twice (without and with `--dflash`), reads a long document, writes about 1,500 sampled tokens of answers after a warm-up on each, and keeps DFlash2 only when its sustained decode is more than 5% faster than the MTP block's (one GPU: than no drafting). On a PC like yours it would keep the MTP block by itself. `./maya.sh --speed-calibration` measures again; `--draft dflash2 --no-speed-calibration` keeps DFlash2 without it. Your ten setups were the data that made the case for it - thank you.
Author
Owner

@mw00 commented on GitHub (Oct 12, 2026):

Closing, as v1.1.3's speed calibration (above) takes care of this on every PC.

<!-- gh-comment-id:6125943028 --> @mw00 commented on GitHub (Oct 12, 2026): Closing, as v1.1.3's speed calibration (above) takes care of this on every PC.
Author
Owner

@q8atnight commented on GitHub (Oct 14, 2026):

One more box for this thread's conclusion, from Maya's own speed calibration (v1.1.6, maya.speed_calibration(), copy config, 1,536 written tokens per drafter, the DFlash2 drafter fetched at the sha pinned in maya.py):

drafter sustained decode drafts accepted
MTP block 35.35 tok/s 85 %
DFlash2 22.48 tok/s 80 %

Maya kept mtp ("not faster on this PC"). Rig: 2x RTX 3090 24 GB NVLink (PCIe 4.0 x8 per card), Ryzen 9 3950X, 121 GB RAM, Maya-M with experts RAM-resident, 262K context, int8 KV, split 23. Same result as the issue: DFlash2 is correct but its verify window costs more than it saves on a RAM-resident desktop.

<!-- gh-comment-id:6158434985 --> @q8atnight commented on GitHub (Oct 14, 2026): One more box for this thread's conclusion, from Maya's own speed calibration (v1.1.6, `maya.speed_calibration()`, copy config, 1,536 written tokens per drafter, the DFlash2 drafter fetched at the sha pinned in `maya.py`): | drafter | sustained decode | drafts accepted | |---|---|---| | MTP block | 35.35 tok/s | 85 % | | DFlash2 | 22.48 tok/s | 80 % | Maya kept mtp ("not faster on this PC"). Rig: 2x RTX 3090 24 GB NVLink (PCIe 4.0 x8 per card), Ryzen 9 3950X, 121 GB RAM, Maya-M with experts RAM-resident, 262K context, int8 KV, split 23. Same result as the issue: DFlash2 is correct but its verify window costs more than it saves on a RAM-resident desktop.
Sign in to join this conversation.
No labels
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
mw00/project-maya#41
No description provided.