Skip to content

perf(prefix-cache): exact Qwen snapshot cuts, generated-turn checkpoints, zero-copy restore - #792

Merged
davide221 merged 6 commits into
mainfrom
perf/prefix-cache-exact-reuse
Sep 30, 2026
Merged

davide221 merged 6 commits into
mainfrom
perf/prefix-cache-exact-reuse

Conversation

@davide221

@davide221 davide221 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Why

Measured on lucebox7 (R9700 behind a PCIe Gen3 x4 root port, Qwen3.8-27B UD-IQ4_XS + DFlash2, qualified launcher flags) with an engine-side trace of every request's prompt and generated tokens:

  • Qwen saved an inline snapshot at the start of the 512-token prefill chunk holding the requested cut, about 256 tokens short on average, and saved nothing when a turn added fewer than 512 tokens (short system prompts were never cached).
  • In an agent loop every turn re-prefilled the model's previous tool-call turn although the next request renders exactly those tokens.
  • Each turn copied a full snapshot to host RAM and back over the x4 link: about 0.55 s to save and 0.45 s to restore at 30-36K tokens.

Change

  • Exact cuts. Qwen starts a prefill chunk at every restore point, the contract DeepSeek already follows, so a snapshot lands on the chat boundary and a restore still reproduces a cold prefill. Between restore points chunks keep to the 512 grid; no chunk in the middle of a prompt is shorter than 16 tokens (a 2-token chunk produced NaN logits, reproduced deterministically). The rule is qwen35_prefill_chunk_tokens(), unit tested. The generation prompt's own boundary starts a chunk only when the request snapshots there.
  • Attention span padding. Masked prefill attention pads its KV span to a multiple of 256 for chunks of at least 32 tokens. Other spans fall back to the generic tile kernel on RDNA4 at head size 256: with a prefill-shaped mask at 33K tokens it is 7.6x further from the CPU reference (2.8e-3 vs 3.7e-4, over the test's own tolerance) and a cold 28K prefill is 12.5% slower. test_fattn_mma256 misses this because its mask puts the queries at the start of the span. This also moves the last prefill chunk of every prompt on main off the tile kernel.
  • Generated-turn checkpoints. After a tool-call turn the server keeps the post-generation state as a checkpoint of prompt plus generated tokens, as far as the next request renders the turn with the same tokens (tool memory replays it exactly for OpenAI Chat Completions and Responses clients). New ModelBackend::snapshot_save_deferred(): Qwen keeps that state live and copies it out only before other work would overwrite it; restoring the snapshot the live state already holds copies nothing. Qwen3.5-MoE opts out (its own generation entry points).
  • Fewer copies. An agent turn continued from a generated-turn checkpoint takes its own snapshot only when the deepest other checkpoint is 2048 tokens behind.
  • Robustness. A lookup skips entries whose snapshot is gone and tries the next one instead of prefilling the whole prompt; a consumed deferred snapshot drops its entry; the empty spec-decode retry prefills the prompt when the snapshot was consumed.
  • Docs: PREFIX_CACHE.md, the Agent Turn Cache section of API.md; --agent-turn-cache now only adds the idle-time replay for turns the next request renders differently.

Results (lucebox7)

main this PR
29K-token tool loop, OpenAI client, 7 requests (2 runs each) 47.5 s 42.0 s
prefill per small agent turn at 29K 440-1490 ms 276-350 ms
cold 28K prefill (cache on) 32.0-33.2 s 31.9-32.5 s
restore of a 30-36K checkpoint ~450 ms ~10 ms (live)
  • Exactness: a greedy 6-turn tool loop is byte-identical between live restore, deferred-then-copied restore and copy restore; an 8-turn chat's cached answer is byte-identical to a cold prefill of the same prompt. A turn restored from a generated-turn checkpoint uses decode-time KV, so it is not bit-identical to re-prefilling that turn (outputs equivalent).
  • Stability: no decode error in the last 16 Claude Code sessions; the deterministic replay of the session that produced the NaN passes.
  • Unit tests: chunk planning, generated-turn save (match, mismatch, live position past the match), stale-entry lookup, agent-continuation throttle, consumed-snapshot retry.

Limits

  • The copy savings apply to the single-sequence worker; concurrent paged serving is unchanged.
  • Generated-turn checkpoints need the next request to render the turn with the same tokens. Claude Code gets them once Anthropic replies are registered in tool memory, which should ship with sampling defaults for Qwen3.8 (see fix(server): convert Anthropic tool_use and tool_result blocks #791).
  • DeepSeek V4: no regression in a 6-turn tool loop (byte-identical to main), but its generated-turn checkpoint never matched there; not investigated yet.

Review in cubic

/v1/messages kept only text blocks. An assistant turn of tool_use blocks
rendered empty, and so did a user turn of tool_result blocks, so the model
never saw its own call or its result and Claude Code re-issued the same
first tool call forever.

- tool_use ids go through tool memory like OpenAI tool_calls; ids the server
  no longer remembers fall back to the Qwen template's <tool_call> rendering.
- Each tool_result becomes a tool message (string or text-block content);
  the user's own text in that turn follows them.
- Claude Code ends every request with a system note, so a request "ends with
  a tool result" when the last message other than a system note is one. The
  agent-turn prefix snapshot (#775) depends on it.
…nts, zero-copy restore

- Qwen starts a prefill chunk at every restore point, as DeepSeek does, so a
  snapshot lands on the chat boundary it was requested at instead of the
  512-token chunk start before it, and a restore still reproduces a cold
  prefill. Between restore points chunks keep to the 512 grid, and no chunk
  in the middle of a prompt is shorter than 16 tokens (a 2-token chunk gave
  NaN logits on the R9700). The rule is qwen35_prefill_chunk_tokens().
- Masked prefill attention pads its KV span to a multiple of 256 for chunks
  of at least 32 tokens. Other spans fall back to the generic tile kernel on
  RDNA4 at head size 256: 12.5% slower and 7.6x further from the CPU
  reference at 33K tokens.
- After a tool-call turn the server keeps the state the generation left as a
  checkpoint of prompt plus generated tokens, as far as the next request
  renders that turn with the same tokens. The backend may keep it live
  (snapshot_save_deferred) and copy it out only before other work would
  overwrite the live state; restoring the snapshot the live state holds
  copies nothing. Qwen3.5 dense implements both; Qwen3.5-MoE opts out.
- An agent turn continued from such a checkpoint takes its own snapshot only
  every 2048 tokens of growth: the next request continues it the same way.
- A lookup skips entries whose snapshot is gone instead of prefilling the
  whole prompt, and a consumed deferred snapshot drops its entry. The empty
  spec-decode retry prefills the prompt when the snapshot was consumed.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 14 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread server/src/qwen35/prefill_helpers.h Resolved
Comment thread server/src/common/model_backend.h Resolved
Comment thread server/src/server/http_server.cpp Resolved
Comment thread server/src/server/http_server.cpp Resolved
Comment thread server/src/server/server_main.cpp Resolved
Comment thread server/docs/PREFIX_CACHE.md Resolved
Comment thread server/src/server/http_server.h Resolved
Comment thread server/test/test_server_unit.cpp Resolved
- Qwen prefill raises LUCE_PREFILL_UBATCH to the 16-token chunk minimum.
- The empty spec-decode retry that prefills the prompt reports no restored
  prefix.
- Generated-turn checkpoints are always deferred; the disk cache's shutdown
  save copies a deferred snapshot out first (snapshot_flush_deferred()).
- The throttle test covers a continued turn far from any other checkpoint.
- Wording of the help text, a header comment and PREFIX_CACHE.md.
@davide221

Copy link
Copy Markdown
Contributor Author

@cubic-dev-ai review

@cubic-dev-ai

cubic-dev-ai Bot commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

@cubic-dev-ai review

@davide221 I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 14 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread server/src/qwen35/qwen35_backend.h Resolved
Comment thread server/src/qwen35/qwen35_backend.cpp Resolved
Comment thread server/test/test_server_unit.cpp Resolved
Comment thread server/test/test_server_unit.cpp Resolved
- Qwen reports its 64-token minimum first chunk after a restore as the
  snapshot granularity, so the cache no longer reserves a cut the chunk
  planner cannot save exactly.
- A restore that fails validation no longer consumes the live
  generated-turn checkpoint; it is consumed only once prefill or decode
  changes the live state.
- Tests: the generated-turn save keeps the request's own inline snapshot
  at capacity; clearer comment in the consumed-snapshot lookup test.
@davide221

Copy link
Copy Markdown
Contributor Author

@cubic-dev-ai review

@cubic-dev-ai

cubic-dev-ai Bot commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

@cubic-dev-ai review

@davide221 I have started the AI code review. It will take a few minutes to complete.

@davide221
davide221 changed the base branch from fix/anthropic-tool-blocks to main September 30, 2026 21:39

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread server/src/qwen35/qwen35_backend.cpp Resolved
Comment thread server/test/test_server_unit.cpp Resolved
Comment thread server/docs/PREFIX_CACHE.md Resolved
…pshot copy

- The prefill chunk constants (512 grid, 16-token minimum, 64-token lead
  after an off-grid restore) live in prefill_helpers.h, used by do_prefill,
  snapshot_granularity and the chunk-planning test alike.
- snapshot_save into the slot a deferred snapshot holds keeps the copy
  materialization already made instead of copying twice.
- PREFIX_CACHE.md: the 16-token minimum does not apply to the prompt's last
  chunk.
@davide221

Copy link
Copy Markdown
Contributor Author

@cubic-dev-ai review

@cubic-dev-ai

cubic-dev-ai Bot commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

@cubic-dev-ai review

@davide221 I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 14 files

Re-trigger cubic

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.

1 participant