Repository navigation
fix(qwen35,server): HTTP daemon path generates content + prefix cache works + state reset between requests - #213
Merged
davide221 merged 6 commits intoMay 17, 2026
Conversation
Three coordinated fixes that take the harness probe from 0/14 -> 12/14 generation probes passing without touching the matrix bench path. 1. qwen35_backend: do_spec_decode read sg_.argmax_tokens on iteration 0 immediately after build_target_step rebuilt the graph but before ggml_backend_graph_compute. The tensor held uninitialized GPU memory; the garbage int32 streamed to the server pipe (sometimes negative, sometimes huge) and triggered an OverflowError inside HF tokenizer. Use cache_.last_tok (populated by prefill after compute) instead. 2. server: defensive 0 <= tok_id < vocab_size filter in _token_stream and _astream_tokens, after the -1 sentinel check. Stops any future out-of-range daemon output from crashing tokenizer.decode(). 3. server: thinking_enabled in the non-stream content path and the stream-path mode switch defaulted to True even though the prompt was rendered with enable_thinking=False. Spontaneous <think> from Qwen3.6 with low max_tokens was getting stripped into an empty reasoning_content, leaving message.content="". Default to _thinking_enabled(req.chat_template_kwargs) consistently; when thinking is off, keep the <think> tag in content. The matrix bench (bench_agent.py, bench_he.py) calls test_dflash with positional args and never hits server.py or the daemon's do_spec_decode path, so canonical numbers (DFlash SWE-2K median 52.36 tok/s, MTP D=3 median 50.31 tok/s) are unaffected. test_server.py grows two regressions for the vocab filter (56/56 pass). Harness: claude_code, codex, openwebui, openclaw, hermes, opencode now fully green; pi still fails on Qwen3.6 + max_tokens=32 producing immediate EOS for some prompts (model behavior, not server bug).
…prefill
The prefix-cache layer in server.py was correctly looking up snapshots
and issuing RESTORE commands, and the daemon was correctly logging
"ok N=24237 gen=128 prefix_len=18018 (RESTORE slot=1)". The bookkeeping
was right. But prefill on a "cache hit" still took the full cold-prefill
time — 22.5s for a 24K-token prompt with 18K of cached prefix.
The existing comment in restore_and_generate already documented the
intent:
// The prompt here is the diff (tokens beyond the snapshot)
committed = do_prefill(req.prompt, io, req.snap_pos, req.snap_slot);
…but the code passed the FULL prompt to do_prefill, whose loop runs
`for (int start = 0; start < prompt_len; ...)` and re-prefills every
token from KV position 0, ignoring the restored cache state. The
snapshot was loaded into the cache but then immediately overwritten.
Fix:
1. do_prefill gains a `kv_offset = 0` parameter. All position
computations (build_target_step kv_start, M-RoPE positions, FA
window start, causal-mask kv_pos, feature-mirror sync, committed
return value) now use `kv_pos = kv_offset + start` instead of
`start` alone.
2. When kv_offset > 0 the function skips migrate_prefill_cache — the
KV cache was already migrated when the snapshot was originally
taken, so re-migration would clobber the restored state.
3. restore_and_generate slices `req.prompt[snap_pos:]` into a delta
vector, sets `cache_.cur_pos = snap_pos`, and calls do_prefill
with that delta plus kv_offset=snap_pos.
Measured impact on Claude Code (24K-token system prompt, q4_0 KV,
budget=22, prefix-cache-slots=4):
Cold real-gen request: 22.3s prefill, 21.8 tok/s decode
Warm real-gen request: 5.7s prefill (~4× faster), 21.4 tok/s decode
Cold count_tokens probe: 9.2s prefill
Warm count_tokens probe: 0.1s prefill (~92× faster)
Output correctness preserved across all four runs (factorial,
reverse_string, etc. all produced real working Python). Decode rate
unchanged — prefix cache only affects prefill, exactly as designed.
After ~7 back-to-back bare-prompt requests the single-GPU daemon path entered a permanently-broken state: every subsequent request reported out=0 finish=stop, the model never recovered until daemon restart. This blocked ~3 of 7 harness clients from passing on probe 2 onwards (including pi, opencode chat.non_stream, claude_code anthropic.messages, codex responses.non_stream) and looked superficially like a "model emits immediate EOS for some prompts" quirk — but was actually a state leak across requests. Root cause: Qwen3.6's hybrid architecture has SSM layers that maintain persistent hidden state. layer_split_daemon_loop.cpp already calls reset_target_cache(shard.cache) between requests for the same reason. The single-GPU Qwen35Backend::generate() path never did. Each generate() call reused whatever SSM hidden state was left at the end of the previous request's decode. After enough requests the state drifted into a corruption basin where do_spec_decode generated only stop tokens (which the server's stop_ids filter dropped, yielding out=0 finish=stop). Fix: call reset_target_cache(cache_) at the top of Qwen35Backend:: generate(). The function zero-fills all stateful tensors (ssm_state, conv_state, rollback buffers) and resets cur_pos to 0, so every new bare-prompt request starts from a clean slate. restore_and_generate doesn't need it because restore_target_cache already overwrites the relevant cache tensors from the snapshot. Cost: ~10-50ms per request to zero-fill the cache. Negligible against ~100ms+ prefill + decode for any real prompt. Validated: 3 back-to-back harness probes against the same daemon, all 7/7 passing, zero out=0 across 57 generation requests. Pi (the one client we never unblocked) now fully green.
…ry is real Daemon's bare-prompt and RESTORE success path printed ok N=24237 gen=128 prefill_s=0.000 decode_s=0.000 decode_tok_s=128000000000.0 because GenerateResult.prefill_s/decode_s were never populated by Qwen35Backend::generate() or restore_and_generate(). The format-string math then printed nonsense (128 / 1e-9 = 1.28e11 tok/s). Time both phases with std::chrono::steady_clock, store on result, so the daemon log shows real numbers and downstream tools (server.py log parsers, bench-style metric scrapers) get truthful values.
dusterbloom
added a commit
to dusterbloom/lucebox-hub
that referenced
this pull request
May 17, 2026
…er.py End-to-end Multi-Token-Prediction speculation through the HTTP server, unlocking MTP for real coding agents (Claude Code, Codex, Hermes, OpenCode, OpenWebUI, OpenClaw, Pi). Previously MTP was only reachable through the file-mode `test_dflash --mtp-gguf --prompt-bin` harness, which spawns a fresh 16GB GGUF load per request (~10s startup) and can't drive interactive clients. ## Architecture Same daemon binary, same bare-prompt protocol. MTP is a STARTUP MODE selected by `--mtp-gguf` flag. test_dflash now dispatches: daemon_mode && mtp_gguf -> run_qwen35_daemon with MTP fields daemon_mode && !mtp_gguf -> existing DFlash daemon !daemon_mode && mtp_gguf -> existing file-mode harness (unchanged) ## Phase 1 — test_dflash.cpp dispatch Reordered the `if (mtp_gguf_path)` block in main() so daemon mode routes to `run_qwen35_daemon` populated with MTP args, instead of unconditionally entering `run_qwen36_mtp_harness`. File-mode bench path preserved. ## Phase 2 — Qwen35DaemonArgs + Qwen35Config carry MTP fields Added mtp_gguf_path, mtp_gamma, mtp_draft_source, mtp_draft_topk to both DaemonArgs (CLI plumbing) and Config (runtime). Copy through in run_qwen35_daemon. ## Phase 3 — Qwen35Backend optional MTP module Added `std::unique_ptr<mtp::Qwen36MtpModule> mtp_module_` member, `supports_mtp()`, `mtp()`, private `init_mtp_()` called from backend init when cfg_.mtp_gguf_path is set, and `warm_mtp_for_prompt_()` that mirrors run_qwen36_mtp_harness's post-prefill warm sequence. Relaxed the "qwen35 requires --draft" check when MTP is set (target serves both roles). Sized the decode cache for max(gamma+1, budget+1) in MTP mode. ## Phase 4 — generate() and restore_and_generate() branch to MTP Added `do_mtp_prefill_(prompt, all_prefill_hidden_out, kv_offset)`: chunked prefill via DFlashTarget::verify_batch with FULL_SEQ hidden capture so per-token hidden states are collected for warm_head_kv. Switches to LAST_ROW_ONLY after prefill so decode-side verifies only download one row. Added `do_mtp_decode_(committed, n_gen, out_tokens, io)`: emits the prefill argmax token, then drives MtpChainRunner with stream=true. Runner owns subsequent io.emit() calls including the -1 terminator. Logs `[mtp_decode] iters=N proposed=M accepted=K emitted=L accept_rate=R` per request for telemetry. Both `generate()` and `restore_and_generate()` branch on `supports_mtp()` to call the MTP prefill+decode pair instead of do_prefill+do_spec_decode when MTP is configured. Per-request `mtp_module_->reset_chain()` mirrors the SSM-state reset added in PR Luce-Org#213 for DFlash, so MTP also avoids the cumulative state-leak cascade under sustained load. ## Phase 5 — server.py wires --mtp-gguf through to spawn cmd Added CLI flags: --mtp-gguf, --mtp-gamma (default 3), --mtp-draft-source (default "chain"), --mtp-draft-topk (default 1). When --mtp-gguf is set: omits --draft (target serves as MTP head host), omits DFlash flags (--fast-rollback, --ddtree, --ddtree-budget), appends --mtp-gguf=... --gamma=... --draft-source ... to the daemon spawn. Force-disables prefix-cache and prefill-cache slots in MTP mode (RESTORE does not yet snapshot MTP head KV; follow-up PR will add MTP KV snapshots). ## Bug fix — qwen36_mtp.cpp hardcoded 8192 chain horizon Replaced `const int n_ctx = 8192;` with env-var override (DFLASH27B_MTP_CTX). Without this, real agentic prompts (Claude Code's 9-24K system prompts, OpenCode's 84K ctx) overflow MTP head KV and the daemon returns `err mtp_warm` -> 0 output tokens. Server.py now sets this from --max-ctx automatically. ## Measured impact Harness probe (3 back-to-back runs, 7 clients, 32K ctx, tq3_0 KV): DFlash mean decode: 22.0 tok/s (PR Luce-Org#213 baseline) MTP mean decode: 29.3 tok/s (+33%) MTP median: 29.6 tok/s MTP max: 50.6 tok/s out=0 cascade cells: 0 / 57 (reset_chain works under load) Claude Code real coding task (24K-token system prompt): prefill 24.7s, decode 4.2s for 153 tok = 35.8 tok/s (+63% vs DFlash) accept_rate=0.41 at gamma=3 Generated valid Heron's-formula function. Published Lucebox blog baselines for Qwen3.6 on RTX 3090: 22.6-29.6 tok/s across clients. Our MTP mean 29.3 / max 50.6 sits at or above the top of the published range. ## Known follow-ups (separate PR) 1. Pre-norm hidden capture path: warning fires once per process ("hidden_at_pos_pre_norm returned null"). Accept-rate degraded but functional. Fix would push accept from ~0.3 toward model-card ~0.83 recommended for gamma<=2. 2. Prefix-cache RESTORE in MTP mode: MTP head KV is not snapshotted by restore_target_cache, so the prefix-cache layer is force-off in MTP mode today. Adding MTP KV to PrefixSnapshot would unlock TTFT savings on repeated agent sessions (DFlash already gets 22s -> 6s on warm). 3. mtp_topk draft-source path is plumbed but not wired in do_mtp_decode_. The chain path is the production default per the matrix bench D=3 results.
5 of 8 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Five coordinated fixes (in three commits) take the harness probe from 0/14 → 14/14 generation probes, eliminate the previously-broken prefix-cache RESTORE, and fix a state-leak cascade that broke clients after ~7 back-to-back requests.
The bugs
qwen35_backend.cppcache_.last_tok(set by prefill after compute) instead of readingsg_.argmax_tokensGPU tensor beforeggml_backend_graph_compute.qwen35_backend.cpp+.hkv_offset = 0param; thread throughbuild_target_step, M-RoPE positions, FA window, mask, feature-mirror, snapshot guard; skip cache migration on resume.qwen35_backend.cppreq.prompt[snap_pos:]into delta + passkv_offset=snap_posso the daemon only prefills the fresh tokens (instead of re-prefilling the cached prefix from 0).qwen35_backend.cppreset_target_cache(cache_)at start of each bare-prompt request. SSM hidden state was carrying over between requests, corrupting decode after ~7 back-to-back calls. layer_split_daemon_loop.cpp already did this; single-GPU path didn't.server.pythinking_enableddefaults match prompt rendering.Measured impact
Harness probe — sustained-load reliability:
out=0cells across 57 requestsPer-client status after fixes (claude_code, codex, opencode, openwebui, pi, openclaw, hermes) — all green on real-text generation.
Prefix cache — Claude Code with 24K-token system prompt (q4_0 KV, budget=22, prefix-cache-slots=4):
Why bench didn't catch these
bench_agent.pyandbench_he.pycalltest_dflashwith positional CLI args (binary token I/O), bypassingserver.pyand the daemon entirely. Canonical numbers stand:These bugs all lived in the daemon HTTP path (
server.py→ daemon stdin/stdout →Qwen35Backend::generate/restore_and_generate/do_spec_decode). Real-agent integration is what surfaced them.Test plan
pytest dflash/scripts/test_server.py)harness/client_test_runner.py probe— 7/7 clients green on three back-to-back runsserver.pydaemon path