Skip to content

prompt cache: with message starts, a repeating client's rewind state gets room in a full guarded store (#3617) - #5136

Merged
ashhart merged 2 commits into
ashhart:mainfrom
mrv777:prompt-cache-rewind-room
Nov 26, 2026
Merged

ashhart merged 2 commits into
ashhart:mainfrom
mrv777:prompt-cache-rewind-room

Conversation

@mrv777

@mrv777 mrv777 commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

What this changes

With TF_QWEN27_MESSAGE_STARTS=1, #4932 put the rewind state at the last user message's start: the state a new question with the same system prompt and tools resumes from (a voice assistant or agent asking short questions over one long fixed prompt). Under a reservation guard, which the lane host sets when it admits queued jobs, reserve evicted only to make room for the endpoint, and fitting admitted every other mark only into leftover room. So once other conversations filled the store, the rewind state was trimmed on every request and each new question re-read the whole prompt. Now, with message starts on, a repeating prompt's rewind state gets room right after the endpoint, and it never evicts another conversation's rewind state. A first-time prompt, and every plan with the switch unset, are as on main.

  • Repeating prompts only. Store.noteRewind keeps the last 16 rewind-prefix keys (active_rewind_key, already computed per lookup); a repeat moves to the newest slot. rewindPriority names the rewind state only when the key was among them, so a one-off conversation keeps main's plan and adds no pressure. clear() resets the ring.

  • No cycles between clients. The second reservation runs under a wrapper guard (KeepRewinds: exact, same promised) that protects whatever the outer guard needs plus every kept rewind state, so clients asking in turn cannot evict each other's rewind states. The endpoint reservation is unchanged.

  • fitting admits the rewind state right after the endpoint, before interior marks and ladder rungs; its three admit blocks now share one helper.

  • Why both rules. Without them it was worse than main: giving every request's rewind state priority made five clients asking in turn evict each other in a cycle (0% to 21% of prompt tokens reused across repeat runs, against main's 27% to 30%), and one-off conversations' rewind states pushed out a state main kept. With them, every cell below is at or above main.

  • Not included. Dropping the message_starts condition, since the same gap exists for any family's rewind state: every host suite passed that way, but on the device a follow-up turn with thinking on did worse than main, so it stays gated.

  • Known limits, both degrading to main's behavior: a state's rewind flag never clears, so stale rewind states of conversations that never return also stay protected from rewind reservations (endpoint reservations still evict them); and beginUser's retry after a refused restore runs the lookup again, which counts that prompt as a repeat (the lane host looks up once per job).

  • Docs. environment.md, the Qwen3.8-27B recipe and the ledger said message-start states "take only room the cache can already promise"; each now names this exception.

  • Issue: Refs Prompt cache: keep a state at every message start, in every family, by default (exact) #3617 (the Qwen3.8-27B Metal slice; fixes a gap in prompt cache: Qwen3.8-27B on Metal keeps states at message starts behind TF_QWEN27_MESSAGE_STARTS (#3617) #4932's opt-in; default-on is still step 4)

  • Stacked on: main

  • atc overlap --json (after rebasing on df3264725): CUDA (GB10): a lending-daemon source for the display carveout, opt-in #2762 conflicts on one file, docs/environment.md (neighbouring table rows); whichever lands second takes both. glm cuda: TF_GLM_COPY_SHARE=1 lets shared rounds' copies take the lone ramp, to a stream's share of the rows #3333 and qwen3_5 CUDA: split mixed-width DFlash/DSpine head batches #4439 clean; the rest unknown (ATC hit its pull request and time limits).

Checks on this head

  • Head commit: ae5b31eb6 (base df3264725)
  • Lean checker, python3 tools/zig/lean_check.py, on the base and on this head: base 164, head 164, 0 new (tools/zig/lean_new.py, the same checker on both). The 164 are inherited.
  • Tests run, with the command and pass, fail and skip counts (all -Dcpu=apple_m1):
    • zig build test-prompt-cache-host: 797 passed, 0 failed; 5 new tests in prompt_cache_message_starts_test.zig.
    • test-cache-store-host: 170 passed. test-message-starts-resume-host: 34 passed. test-qwen27-resume-host: 25 passed.
    • test-conversation-cache-host, test-cache-agent-host, test-cache-decay-host, test-cache-spares-host, test-cache-replay-host, test-cache-progress-host, test-qwen27-keep-host, test-request-starts-turns-host, test-qwen27-reply-cache-host: all pass.
    • New tests fail without the change. With rewindPriority returning null, "a full guarded store makes room…" and "a first-time prompt's rewind state takes only free room…" fail (795/797). Without KeepRewinds protecting rewind states, "never evicts another conversation's rewind state" fails (796/797). Treating every prompt as a repeat fails the first-time-prompt and ring tests (795/797). The queued-job test pins a property main already has.
    • zig fmt --check build.zig zig, git diff --check: clean
  • CI: pending on this push
  • Not run, and why: zig build test test-golden, since my only Mac serves a model (CONTRIBUTING); CI runs it. Chips other than the M5 Ultra. SenseNova-Loop: no looped checkpoint; message_starts stays 0 for it (prompt cache: Qwen3.8-27B on Metal keeps states at message starts behind TF_QWEN27_MESSAGE_STARTS (#3617) #4932's host test), so this change cannot reach it.

Receipt

  • Main against branch: the cells below, same machine, checkpoint and settings, one server start per cell, nothing else on the GPU.

  • Boxes it reaches: Qwen3.8-27B on Metal with TF_QWEN27_MESSAGE_STARTS=1, when a guarded lookup meets a full store and its prompt repeats a recent one. Unset, no plan changes on any family.

  • New switch? No. It changes what the existing TF_QWEN27_MESSAGE_STARTS=1 keeps.

  • Environment: main 8f11b41ba and this change on it (since rebased onto df3264725; the 11 commits between touch none of these files, and the host checks above ran on the rebased head). Zig 0.17.0 ReleaseFast. Mac Studio M5 Ultra, 64-core GPU, 96 GB, macOS 27.2. A Qwen3.8-27B fine-tune in MLX 4-bit (group 64), same architecture, local copy without a public revision; the change decides which states are kept, not any arithmetic. DFlash2 z-lab/Qwen3.8-27B-DFlash2 at 50307d4c. --parallel 2 --context 32768 --prompt-cache-gib 6 (3 where marked), TF_PROMPT_ROWS=512, TF_QWEN27_MESSAGE_STARTS=1, thinking off.

  • Paths and platforms the change reaches, which I ran and which I could not: the Qwen27 Metal lane host with DFlash2, greedy and seeded, 1 and 4 streams, on an M5 Ultra. Not run: M1 to M4.

  • Exactness: tools/bench_concurrent.py --tokens 256 --reps 3 --temperatures 0.7,0 --levels 1,4 --alone --serial on main and on this branch: every cell equal alone (3/3 at 1 stream, 12/12 at 4) and against "draft": false, 0 unequal, 0 failed, code and chat prompts, sampled (seed 1234) and greedy. All 240 token_sha256 values equal main's. In the scenario cells, every request the branch resumed returned the same token hash as main's fresh pass for it.

  • Main against this branch, same machine and checkpoint (seconds to first output, client-side; tool below):

    Cell main branch
    Five assistant clients, each with its own 4.1k-7.2k-token system prompt and six tools, asking new questions in turn, 4 rounds, 6 GiB 31,055 of 105,174 prompt tokens reused (29.5%); TTFT sum 53.2 s 40,882 reused (38.9%); 46.0 s
    One assistant, store full of one-off conversations (3 GiB, 6 others between rounds): its next question right after the last 0 cached; 3.20, 3.23 s 4,626 cached; 0.09, 0.09 s
    Same assistant, 6 GiB, 3 one-off conversations between each pair of questions 5 of 5 later requests resumed 5 of 5, same replies and timings
    Cold first request, 4,644 tokens 3.89-4.46 s 3.67-3.96 s

    Main's five-client figure varies between runs (28,182 and 31,055 tokens reused on two earlier runs); the branch gave 40,882 on both of its runs.

  • Decode speed before and after, from the bench_concurrent.py run above (256 tokens, DFlash2), tokens/s main / branch: greedy code 218.8 / 217.3 at 1 stream, 302.3 / 318.7 at 4; greedy chat 154.5 / 154.8, 238.1 / 237.5; sampled code 247.9 / 248.5, 297.2 / 300.4; sampled chat 135.5 / 135.6, 203.5 / 206.1. Level: the change does not reach decode.

  • Prompt speed before and after: the cold first request above. A cold pass keeps no states, so the change cannot reach it.

  • Licence of any new weights or drafter, or "n/a": n/a

Scenario tool: bench_new_question.py (stdlib Python, imports tools/bench_stream.py and bench_auth.py; exports counters and hashes only)
"""A new question after other conversations filled the prompt cache: does it resume at its system prompt?

Assistant pattern (voice assistant, agent): one long fixed system prompt plus tools, a short user message,
then a new short question with the same system prompt. Between the two, other conversations with their own
long prompts fill the store. Exports counters and hashes only (prompt_tokens, cached_tokens, ttft_s,
token_sha256), never prompt or reply text.
"""
import argparse
import json
import sys
import time
import urllib.request

sys.path.insert(0, sys.argv.pop(1) if len(sys.argv) > 1 and sys.argv[1].endswith("/tools") else ".")
import bench_stream  # noqa: E402
from bench_auth import read_api_key  # noqa: E402

TOOLS = [{"type": "function", "function": {"name": n, "description": d, "parameters": {"type": "object", "properties": {
    "target": {"type": "string", "description": "What to act on"}}, "required": ["target"]}}} for n, d in [
    ("get_weather", "Current weather and forecast for a place"), ("set_timer", "Start a named countdown timer"),
    ("control_device", "Turn a home device on or off or set its level"), ("calendar_events", "List upcoming calendar events"),
    ("web_search", "Search the web and return the top results"), ("camera_events", "Recent security camera detections")]]
QUESTIONS = ["What is the default port?", "How do I set an API key?", "What does --parallel do?",
             "Which models run on Metal?", "How do I stop the server?", "What is the context length flag?"]


def text(path: str, chars: int, offset: int = 0) -> str:
    with open(path, encoding="utf-8") as f:
        return f.read()[offset:offset + chars]


def ask(base, model, key, messages, tools, tokens, thinking):
    body = {"model": model, "messages": messages, "max_tokens": tokens, "temperature": 0, "ignore_eos": True,
            "stream": True, "stream_options": {"include_usage": True}, "chat_template_kwargs": {"enable_thinking": thinking}}
    if tools:
        body["tools"] = tools
    req = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps(body).encode(),
                                 headers={"Content-Type": "application/json", **({"Authorization": f"Bearer {key}"} if key else {})})
    sent = time.perf_counter()
    reply = bench_stream.Collector(sent)
    with urllib.request.urlopen(req, timeout=1800) as resp:
        reply.read(resp, None)
    observed = reply.evidence.finish(reply.usage, reply.runtime, reply.end == "done")
    first = reply.pieces[0][0] - sent if reply.pieces else None
    return {k: observed.get(k) for k in ("prompt_tokens", "cached_tokens", "tokens", "token_sha256")} | {"ttft_s": first, "complete": reply.end == "done"}


def reply_text(base, model, key, messages, tools, tokens, thinking):
    """One non-streamed turn; its visible reply (no reasoning) becomes history for the next turn."""
    body = {"model": model, "messages": messages, "max_tokens": tokens, "temperature": 0,
            "chat_template_kwargs": {"enable_thinking": thinking}, **({"tools": tools} if tools else {})}
    req = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps(body).encode(),
                                 headers={"Content-Type": "application/json", **({"Authorization": f"Bearer {key}"} if key else {})})
    with urllib.request.urlopen(req, timeout=1800) as resp:
        out = json.load(resp)
    return out["choices"][0]["message"].get("content") or "", out.get("usage", {})


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("base")
    p.add_argument("model")
    p.add_argument("--docs", required=True, help="directory of public text for the prompts (e.g. the repo's docs/)")
    p.add_argument("--system-chars", type=int, default=16000, help="system prompt size in characters (~4.3k tokens)")
    p.add_argument("--others", type=int, default=6, help="other conversations between the two questions")
    p.add_argument("--reps", type=int, default=3)
    p.add_argument("--tokens", type=int, default=64)
    p.add_argument("--thinking", action="store_true")
    p.add_argument("--follow-up", action="store_true", help="turn 2 continues turn 1 (reply in history) instead of a new question")
    p.add_argument("--clients", type=int, default=0, help="N assistant clients, each with its own fixed system prompt, asking new questions in turn")
    p.add_argument("--api-key-env")
    p.add_argument("--output")
    a = p.parse_args()
    key = read_api_key(p, a.api_key_env) if a.api_key_env else None
    system = text(f"{a.docs}/api.md", a.system_chars)
    others = [text(f"{a.docs}/{name}", a.system_chars) for name in ("environment.md", "optimization-ledger.md", "kernel-contract.md")]
    rows = []
    if a.clients:
        docs = ["api.md", "environment.md", "optimization-ledger.md", "kernel-contract.md", "recipes/SKILL.md", "atc/SKILL.md"]
        systems = [text(f"{a.docs}/{d}", a.system_chars) for d in docs[:a.clients]]
        for rep in range(a.reps):
            for c, system_c in enumerate(systems):
                q = {"role": "user", "content": QUESTIONS[(rep * a.clients + c) % len(QUESTIONS)] + f" (client {c}, turn {rep})"}
                r = ask(a.base, a.model, key, [{"role": "system", "content": system_c}, q], TOOLS, a.tokens, a.thinking)
                rows.append({"rep": rep, "client": c, **r})
                print(json.dumps({"rep": rep, "client": c, "prompt_tokens": r["prompt_tokens"], "cached_tokens": r["cached_tokens"],
                                  "ttft_s": round(r["ttft_s"] or 0, 2), "sha": (r["token_sha256"] or "")[:10]}), flush=True)
        if a.output:
            with open(a.output, "w") as f:
                json.dump(rows, f, indent=1)
        return
    for rep in range(a.reps):
        sys_msg = {"role": "system", "content": system}
        q1 = {"role": "user", "content": QUESTIONS[2 * rep % len(QUESTIONS)]}
        if a.follow_up:
            content, usage = reply_text(a.base, a.model, key, [sys_msg, q1], TOOLS, 512, a.thinking)
            first = {"prompt_tokens": usage.get("prompt_tokens"), "cached_tokens": (usage.get("prompt_tokens_details") or {}).get("cached_tokens"), "ttft_s": None}
            history = [sys_msg, q1, {"role": "assistant", "content": content}]
        else:
            first = ask(a.base, a.model, key, [sys_msg, q1], TOOLS, a.tokens, a.thinking)
            history = [sys_msg]
        for i in range(a.others):  # other conversations: different long prompts, so they share nothing with the assistant's
            other = others[i % len(others)] + f"\n\nConversation {rep}-{i}."
            ask(a.base, a.model, key, [{"role": "system", "content": other}, {"role": "user", "content": "Summarize."}], None, 8, False)
        second = ask(a.base, a.model, key, history + [{"role": "user", "content": QUESTIONS[(2 * rep + 1) % len(QUESTIONS)]}], TOOLS, a.tokens, a.thinking)
        rows.append({"rep": rep, "first": first, "new_question": second})
        print(json.dumps(rows[-1]), flush=True)
    if a.output:
        with open(a.output, "w") as f:
            json.dump(rows, f, indent=1)


if __name__ == "__main__":
    main()

Five clients: python3 bench_new_question.py tools http://127.0.0.1:8082 local-model --docs docs --clients 5 --reps 4. One assistant: --reps 3 --others 6 (3 GiB) and --reps 3 --others 3 (6 GiB).

Checklist

  • The title and description match the head commit, including the receipt and the stack.

  • New tests fail before the change, pass after it, and skip cleanly without their dependency.

  • Comments and docstrings are one line. No measurements or history in the source.

  • No personal data, machine names, internal hosts or local paths in the diff or its commits. No AI attribution lines.

  • Every token still goes through the lane rounds. No serial path, and nothing that needs drafts off.

  • Drafted output equals "draft": false, a resumed prompt equals a fresh one, and concurrent equals solo.

  • No precision traded for speed. If the bits change, the description says which sums change and why.

  • Decode and prompt processing are no slower than main at one stream and the widest admitted; with --drafter, no slower than without it, greedy and sampled

@ashhart

ashhart commented Nov 26, 2026

Copy link
Copy Markdown
Owner

Thank you, @mrv777.

The repeat-only 16-key history, first-time behavior, endpoint-first reservation and protection for queued jobs and other conversations' rewind states are confirmed. The branch merges cleanly on today's main. Switch-off behavior, saved-state formats and arithmetic are unchanged.

The supplied fail-before host tests cover the new reservation and guard decisions, and the reported replies remain token-identical. No additional GPU checkpoint run is needed for a cache-policy change that runs only on the host. SAFE TO LAND.

  • Synthena

mrv777 and others added 2 commits November 26, 2026 04:23
…gets room in a full guarded store (ashhart#3617)

Under TF_QWEN27_MESSAGE_STARTS=1 the rewind state sits at the last user message's start: the state a next
question with the same system prompt and tools resumes from. The guarded reservation made room for the endpoint
alone, so once other conversations filled the store the rewind state was always trimmed and every new question
re-read the whole prompt. Now, for a prompt whose rewind prefix came up in the last 16 lookups, the reservation
also evicts for the rewind state right after the endpoint, never taking another conversation's rewind state, and
fitting admits it next. A first-time prompt keeps main's plan, so one-off conversations add no pressure, and clients
asking in turn cannot evict each other's rewind states. Unset or 0 leaves every plan as on main.
@ashhart
ashhart force-pushed the prompt-cache-rewind-room branch from ae5b31e to 0e02cff Compare November 26, 2026 04:23
@ashhart
ashhart merged commit 4598f3b into ashhart:main Nov 26, 2026
2 of 12 checks passed
@ashhart

ashhart commented Nov 26, 2026

Copy link
Copy Markdown
Owner

Thank you @mrv777. 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.

ashhart added a commit to Bizuayeu/TensorFold that referenced this pull request Nov 26, 2026
ashhart added a commit that referenced this pull request Nov 26, 2026
@mrv777
mrv777 deleted the prompt-cache-rewind-room branch November 26, 2026 22:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants