Skip to content

fix(qwen35,server): HTTP daemon path generates content + prefix cache works + state reset between requests - #213

Merged
davide221 merged 6 commits into
Luce-Org:mainfrom
dusterbloom:fix/qwen35-server-http-content
May 17, 2026
Merged

davide221 merged 6 commits into
Luce-Org:mainfrom
dusterbloom:fix/qwen35-server-http-content

Conversation

@dusterbloom

@dusterbloom dusterbloom commented May 17, 2026 •

Copy link
Copy Markdown
Collaborator

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

# Layer File Fix
1 C++ daemon (do_spec_decode) qwen35_backend.cpp Use cache_.last_tok (set by prefill after compute) instead of reading sg_.argmax_tokens GPU tensor before ggml_backend_graph_compute.
2 C++ daemon (do_prefill) qwen35_backend.cpp + .h Add kv_offset = 0 param; thread through build_target_step, M-RoPE positions, FA window, mask, feature-mirror, snapshot guard; skip cache migration on resume.
3 C++ daemon (restore_and_generate) qwen35_backend.cpp Slice req.prompt[snap_pos:] into delta + pass kv_offset=snap_pos so the daemon only prefills the fresh tokens (instead of re-prefilling the cached prefix from 0).
4 C++ daemon (generate) qwen35_backend.cpp Call reset_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.
5 Server defense + thinking server.py Vocab-range filter on tok_id stream + thinking_enabled defaults match prompt rendering.

Measured impact

Harness probe — sustained-load reliability:

Run Before After
Probe 1 (fresh daemon) 0-4 / 7 clients 7 / 7
Probe 2 (back-to-back) 0 / 7 (cascade) 7 / 7
Probe 3 (back-to-back) 0 / 7 (cascade) 7 / 7
out=0 cells across 57 requests ~50% 0

Per-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):

Metric Cold Warm Speedup
Real-gen prefill 22.3s 5.7s ~4×
count_tokens probe prefill 9.2s 0.1s ~92×
Decode rate 21.8 tok/s 21.4 tok/s unchanged (prefill-only feature, as designed)

Why bench didn't catch these

bench_agent.py and bench_he.py call test_dflash with positional CLI args (binary token I/O), bypassing server.py and the daemon entirely. Canonical numbers stand:

  • DFlash SWE-2K median 52.36 tok/s (1.73×)
  • MTP D=3 median 50.31 tok/s (1.57×)

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

  • 56/56 server tests pass (pytest dflash/scripts/test_server.py)
  • harness/client_test_runner.py probe — 7/7 clients green on three back-to-back runs
  • Claude Code end-to-end: real Fibonacci/factorial/string-reverse functions generated, 20-22 tok/s decode
  • Hermes end-to-end: real code generated, 23 tok/s decode
  • Cold/warm Claude Code A/B: prefix cache reduces TTFT from 22s → 6s on repeat requests
  • No matrix bench regression (different code path)
  • (separate PR) Wire MTP into server.py daemon path

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).

@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 3 files

Re-trigger cubic

…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.
@dusterbloom dusterbloom changed the title fix(qwen35,server): make HTTP daemon path generate real content fix(qwen35,server): HTTP daemon path generates content + prefix cache actually skips prefill May 17, 2026
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.
@dusterbloom dusterbloom changed the title fix(qwen35,server): HTTP daemon path generates content + prefix cache actually skips prefill fix(qwen35,server): HTTP daemon path generates content + prefix cache works + state reset between requests May 17, 2026
dusterbloom and others added 3 commits May 18, 2026 00:03
…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.
@davide221
davide221 merged commit 7b781b8 into Luce-Org:main May 17, 2026
2 checks passed
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