Skip to content

server : fall back to full prompt re-processing when memory rollback fails - #28007

Open
IvanAndreychikov wants to merge 1 commit into
ggml-org:masterfrom
IvanAndreychikov:fix/recurrent-rollback-reprocess
Open

IvanAndreychikov wants to merge 1 commit into
ggml-org:masterfrom
IvanAndreychikov:fix/recurrent-rollback-reprocess

Conversation

@IvanAndreychikov

Copy link
Copy Markdown

Recurrent memories (e.g. hybrid models) can refuse to remove tokens when the rollback exceeds the recurrent snapshot ring. The result of the removal was ignored, which either aborted the process via common_context_seq_rm, or left the slot with a stale recurrent state and a truncated token list.

Check the seq_rm result and, on failure, clear the sequence and re-process the full prompt.

Fixes #27931

Overview

On hybrid models with recurrent state (e.g. qwen3_5_moe: Gated DeltaNet layers + attention), llama_memory_recurrent::seq_rm refuses a partial rollback when the rollback distance exceeds the recurrent snapshot ring (n_rs_seq, 0 by default). At the server prompt-processing site the boolean result of slot.mem.seq_rm(slot.id, p0, -1) was discarded:

  • common_memory::seq_rm routes through common_context_seq_rm, which calls GGML_ABORT on the refusal, so the server process dies (fail-fast, 0xc0000409 on Windows).
  • When the refusal is not surfaced, the KV cache and the recurrent memory disagree with the truncated token list: the slot continues on a stale recurrent state (silent quality degradation, the find_slot: non-consecutive token position warning storm) and with some batch geometries the process eventually crashes.

Note that llama_memory_hybrid::seq_rm short-circuits: when the recurrent part refuses, the KV part is not truncated either, so after a refusal the whole cached prefix is unusable. A full re-process is the only sound fallback.

This PR checks the seq_rm result at the prompt truncation site and, on failure, clears the sequence (seq_rm(seq_id, -1, -1), which recurrent memories always support) and resets the cached token list, so the slot re-processes the full prompt. This mirrors the existing "forcing full prompt re-processing" policy the server already applies for SWA/hybrid memories. The draft context is covered as well when speculative decoding is enabled.

Additional information

  • Testing: existing server suites pass (built on current master, CUDA): test_basic (7), test_completion (38), test_chat_completion + test_ctx_shift (57), test_slot_save + test_speculative (17), test_stream + test_kv_keep_only_active + test_ignore_eos + test_tokenize + test_infill (17). Total 136 passed, 0 failed.
  • Manual validation with a 35B qwen3_5_moe hybrid + mmproj model on 2 GPUs (--split-mode tensor), which is the configuration that reproduces the abort/stale state: multi-turn chat with alternating text/image turns, prompt-prefix divergence (edited history), identical-prompt retries and slot save/restore all complete without crashes and without non-consecutive token position warnings. Before the change the same workload deterministically aborted the server.
  • A minimal CI repro is not practical: it requires a hybrid recurrent model with an mmproj projector (multi-GB), so no new test was added; happy to add one if maintainers can point at a suitable tiny model.
  • Reproduction details and analysis: Eval bug: llama-server crashes (stack overflow / access violation) on hybrid recurrent models (qwen3_5_moe) with mmproj vision when alternating text and image turns #27931.

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: YES - I used an AI coding agent (opencode with GLM) to analyze the crash and prepare the fix; the change was reviewed and submitted by me (see Assisted-by: in the commit)

…fails

Recurrent memories (e.g. hybrid models) can refuse to remove tokens when
the rollback exceeds the recurrent snapshot ring. The result of the removal
was ignored, which either aborted the process via common_context_seq_rm, or
left the slot with a stale recurrent state and a truncated token list.

Check the seq_rm result and, on failure, clear the sequence and re-process
the full prompt.

Assisted-by: opencode (GLM)
@IvanAndreychikov
IvanAndreychikov requested a review from a team as a code owner August 30, 2026 07:29
@ferer2013

Copy link
Copy Markdown

Production evidence in support of this PR - we run exactly this pathology at scale.

Environment (all measured)

Symptoms at production scale

W find_slot: non-consecutive token position 4 after 4 for sequence 0 with 512 new tokens
W find_slot: non-consecutive token position 4 after 4 for sequence 0 with 512 new tokens
W find_slot: non-consecutive token position 4 after 4 for sequence 0 with 452 new tokens
W find_slot: non-consecutive token position 134 after 4 for sequence 0 with 24 new tokens
I slot print_timing: id 0 | task 262832 | prompt processing, n_tokens = 8160, progress = 1.00, t = 7.22 s / 1130.21 tokens per second

Impact

  • Stability: tens of thousands of pages in single-slot production, ZERO crashes. 30-minute dual-slot stress run (--parallel 2, 1,561 requests, real page images): all HTTP 200, zero crashes, zero CUDA errors / GGML_ABORT, no quality regression (CJK ratio 81-85%, output length 74-88% of single-slot baseline).
  • Cost: GPU0 utilization mean ~91%, peak 99% on a single serial OCR worker. We infer - flagged as inference, not directly measured - that the 5-6 x 512-token find_slot retries per page burn roughly 20-40% of per-page GPU time.

Ask: please review/merge this PR - our production config sits exactly on this pathology. We will upgrade to the first official nightly containing it and post before/after warning counts (expectation: storm goes to zero, GPU headroom returns). Full 178 MB log or time-bounded excerpts available on request.

@SgfKrc

SgfKrc commented Nov 8, 2026 •

Copy link
Copy Markdown

I've been carrying this fix in my downstream fork and have two things to report: your mechanism analysis is spot on, and the recovery path needs one more step to actually match the title.

Mechanism. Confirmed on a clean upstream build (f477f79) with qwen35-2b (hybrid arch), pure text, no server — just llama_decode + llama_memory_seq_rm:

eval 30 tokens → llama_n_rs_seq(ctx) == 0

llama_memory_seq_rm(mem, 0, 20, -1) → false

seq_pos_min/max → 29/29 (unchanged, KV not truncated)

replay tokens [20,30) → rc = -1, "inconsistent sequence positions ... X = 29, Y = 20"

Control: seq_rm(mem, 0, -1, -1) returns true and resets pos to -1, so the memory isn't wedged. The false really is the recurrent half refusing and taking the attention truncation down with it, exactly as you described.

The missing step. In the hunk, slot.prompt.tokens.keep_first(0); empties the token list, and the code then falls through expecting the prompt to be re-processed from scratch. But the prompt processing loop doesn't refill slot.prompt.tokens from the task — that only happens in launch_slot_with_task. So the next iteration processes an empty prompt and generates from position 0. That's worse than the 500 it replaces: the client gets a 200 with a response that has nothing to do with the request.

What we ended up with in the fork:

if (!slot.mem.seq_rm(slot.id, p0, -1)) {
SLT_WRN(slot, "memory could not roll back to pos %d - clearing the "
"sequence and re-processing the full prompt\n", (int) p0);
slot.prompt_clear(); // mem.seq_rm(id, -1, -1) + prompt.clear()
slot.prompt.tokens = server_tokens(slot.task->tokens.get_tokens(),
slot.task->tokens.has_mtmd);
return; // this iteration does nothing; the next one starts at pos 0
}

The return matters too: falling through with a freshly repopulated token list lands in the middle of the loop that assumes n_past is consistent with the list it just built.

Testing note (not a bug in your patch, but it cost me an hour). When I first made the forced-failure injection refuse every partial seq_rm — including the no-op case where p0 > pos_max — the degraded caller retried at the same position forever: five iterations, then a timeout. Worth making sure the recovery path isn't reachable when the delete was a no-op to begin with.

Related. #31656 reports the same short-circuit from the common_context_seq_rm abort path in post_decode, so this looks like one mechanism with two visible outcomes. Happy to attach the repro (~40 lines, no server, no model-specific code) to #31656 as well.

SgfKrc added a commit to SgfKrc/llama.cpp that referenced this pull request Nov 12, 2026
一个 llama_context 成为「分段链」的驱动者:本地 head 跑前 N 层、输出 pre-norm hidden,
后续段(本地 `split_stages` 或远程 `split_remotes`)消费 hidden 继续算,最后一段出 logits。
llama-server 的 slot 管理、prompt cache、seq_rm 通过聚合 memory 看到整条链,不需要知道段
在哪台机器上。目标是让 llama.cpp 在分段形态下具备它整模时的能力。

================================================================
一、分段加载与链驱动
================================================================

- layer_range 从 `LLAMA_LAYER_RANGE` 环境变量提升到 `llama_model_params.split_layer_lo/hi`
  (配 `--split-layer-range`),同一进程才能加载多个不同层范围的模型;环境变量降级为兜底。
- hidden 传递走标准 embedding 路径(`embeddings_pre_norm` + `get_embeddings_ith`),不是
  MTP 的 nextn 通道——后者在没有 nextn 层的 context 上打开会让图索要一块从未规划过的缓冲,
  实测单 context 也直接 `GGML_ASSERT(buffer)`。
- relay 段没有 `tok_embd` 时不再无条件构建 `GET_ROWS`:那一行被 `ggml_build_forward_order`
  强制入图,只看分支选择不够。
- 聚合 memory(`llama_memory_split`)广播 seq_rm / seq_cp / seq_keep / seq_add / seq_div /
  clear,`seq_pos_*` 问链首,`can_shift` 恒 false,state 带段数与每段长度按段切片。
- 「这一段是 relay 还是 tail」改成显式声明:`split-stage --role relay|tail` 必填,
  `llama_model_n_layer_src()` 带出源 trunk 深度。原来用 `layer_hi >= llama_model_n_layer()`
  判断,而后者返回的是**本段**层数(加载器已把 block_count 覆盖成 hi-lo),于是那个比较
  只要 lo >= 0 就恒真——远程 relay 段从来没工作过,它返回 logits 而不是 hidden,客户端
  看到空 hidden 就保持 carrier 不变,静默算错。
- `llama_split_attach` 返回 int32_t 并做衔接校验:段必须铺满源模型、逐段首尾相接、末段到
  trunk、head 不能已经是尾段、段不能来自另一个源模型。失败返回 -1 且不改变已有链。

================================================================
二、远程段
================================================================

- 协议(`src/llama-split-proto.h`)定长头 + 位置 + hidden;`PROTO_VER` = 3。
- `src/llama-split-net.*`:两端共用的 socket 层(短写/短读/关闭/WSAStartup 只此一份),
  connect 后设 120 s 的 SO_RCVTIMEO/SNDTIMEO——没有失败边界的连接是静默零吞吐的来源。
- `src/llama-split-remote.*`:TCP 客户端。错误语义三分:`seq_rm` 失败(传输或对端拒绝)
  一律先打段号+endpoint+seq+范围再让 `common_context_seq_rm` 的 abort 发生,因为 KV 错开
  之后每个后续 token 的 hidden 都是错的且不可检测;`decode` 失败是请求级 -3;`clear` 没有
  错误通道,记 `remote_failure` 让后续 decode 直接 -3。
- 远程段进聚合 memory:`seq_rm`/`clear` 分派到协议;`seq_pos_*` 仍问 head——位置由
  `decode_split` 逐 token 原样下发保证,是构造不变式。
- `llama-server --split-remote host:port`(可重复,与 `--split-tail-range` 互斥);
  `split-stage --host`(默认仍 loopback)。
- M-RoPE 位置全量下发:`split_expand_pos()` 按 `llama_batch_allocr::init` 的规则算出 head
  真正用的位置(token 项 `[p,p,p,0]`、embedding 项原样),远程链把 4 个 section 都发过去。
  之前下游拿到的是 `[p,0,0,0]`,位置 0 上恰好相同,所以所有 1-token 的逐位对比都通过,
  `p > 0` 就分叉。

================================================================
三、checkpoint 复用
================================================================

server 的前缀复用靠 context checkpoint,而 checkpoint 就是 state 导出。远程链的
`state_seq_*` 原先返回 0,于是每轮都从头重算。

- `state_seq_write/read_data` 以前用成员 `memory` 而不是 `get_memory()`,链的 checkpoint
  只含 head 段;tail 的 recurrent cell 停在恢复前的位置,于是下一轮 `seq_rm(p0,-1)` 在
  tail 上变成回滚上百个位置、`n_rs_seq` 是 0 → 拒绝 → abort。修好后 `-np 2` 从「第 3 个
  请求必死」变成 10/10 存活。
- 协议加 `OP_STATE_SAVE`/`OP_STATE_LOAD`,`llama_memory_split::state_write/read` 把远程段
  的 blob 拼进来(远端段写在 head 之前:恢复时先远端后 head,head 是回答 pos_min/max 的一方;
  save 失败时本地零写入)。server 侧零改动。
- 两条不变式:**save 时所有段 pos_max 必须相等**(不等说明链已错开,拒绝把错开固化进
  checkpoint);**restore 时每段 pos_max 必须 ≥ 快照位置**(-1 = 被清空/重启过,stage 在
  应用之前就拒绝)。后者的方向和直觉相反——恢复永远发生在链已往前走之后。
- 只放行 PARTIAL_ONLY(checkpoint 档):qwen35 没有 SWA,这一档里一个 KV cell 都没有,
  只有 recurrent state(每 8 层段 6.422 MiB),KV 由恢复后紧跟的 `seq_rm` 裁到同一位置。
  全量 state(含 KV)仍返回 0 并 WARN,server 干净回退重算。

实测:3103 token 历史的 chat 第一轮 19847 ms,第二轮只解 38 个新 token、714 ms。

================================================================
四、投机
================================================================

MTP:之前是**启动失败**不是效果差——`spec_init` 用 head 的 model 建 draft,而 head 段
`nextn_keep = 0`、model 里没有 MTP 层,`ctx_type=MTP` 直接 return nullptr。改用 tail 的
model/context。上游 impl 的 `process()` 把 target batch 的 token id 逐行转成 draft 输入,
而链上 tail 收到的是 hidden 行,链模式跳过 catch-up、只取 `t_h_nextn` 的行。

DFlash:8 个 `target_layers` 天然分布在两段(head 的 2/7/12/17/23/28、tail 的 33/38),
spec target 建在 head(词表在那里),tail 的两个 tap 是进程内读。`target_layer_ids` 映射成
`(ctx, local_lid)`,没加访问器——head 的 `n_layer()` 就是 tail 起点。

远程链的投机明确不做:stage 只回 1 行 logits,验证要 k+1 行;一行 248320×4B ≈ 993 KB,
k=3 一帧约 4 MB,1 Gbps 上 3–4 s,比本地算还慢。瓶颈是带宽与公共协议,不是延迟。

**当前硬件上投机在链上是亏的**:2B 链 k=2 在代码负载 0.87×、混合 0.69×、纯中文 0.63×
(接受率 46.9%/27.0%/19.4%);DFlash 在 35B 上 k=3 只有 1.12×、k=15 0.46×。所以链上默认
不开投机。开发期一度记过 1.33×,那是一个模型复读的退化 prompt 上的数。

================================================================
五、两处自己引入的回归(最终复审抓出来的)
================================================================

**`LLAMA_LAYER_RANGE` 环境变量入口被误杀。** 上一轮为「单独给层范围要拒绝」加的检查用
`params.split_layer_hi != n_layer_src` 判断,而走环境变量时 `params.split_layer_hi == -1` ——
于是 `LLAMA_LAYER_RANGE=0:24`(与整模完全等价的配置)被拒,错误信息还打印 `-1:-1`。env 与
flag 是同一事实的两种入口,检查只该问「模型最终加载了哪一段」:新增
`llama_model_layer_range()` 读生效后的范围,参数侧用「params 优先、env 兜底」的解析。

**remote tail 的 logits 图缓冲没跟着修。** 本地 tail 从 `n_batch × n_vocab` 改成
`n_seq_max*(1+n_max)` 之后,`split-stage` 那边还写着「Leave the output-row limits at their
defaults」,于是 remote tail 仍按 `-b 2048` 预留 `[n_vocab, 2048]` 的图输出节点。实测同一个
248k 词表的 tail:`sched_reserve: CPU compute buffer size` **2052.10 MiB → 240.09 MiB**,
省 1812 MiB/段——而它每帧只回 1 行。

另外八条:同一个 output flag 被写两次(非末段的值实际是 false,全靠 relay 是 embeddings
上下文兜住);carrier 宽度用 `hparams.n_embd` 而 head 导出的是 `n_embd_out()`(两个 qwen35
模型三者恰好相等所以没暴露,现在建链时校验);一次瞬时 `clear` 失败让远程链永久 500(改成
下一次 clear 成功即重新信任);checkpoint 的 size 查询与 write 之间的窗口会让 `update_tgt`
`GGML_ABORT`(存储路径改成「这一轮不复用」——但**投机回滚那三处保留致命退出**,因为那里空
blob 会被 `load_tgt()` 当成「无需恢复」,静默继续比 abort 更糟);`split_attach` 对 stage 自身
cparams 只 WARN(改拒绝);loader 的「skipped MiB」恒为 0(`size_data` 重算之后这个差值不再
成立,改成按源 weight 去重的三段式:loaded / mapped lazily / not created);注释把机制归错
函数;一处死代码;`--split-rs-seq` 的 `std::stoul` 无上界(`-1` 会变成 4294967295)。

================================================================
六、上游门槛:ABI、语言、可移植性
================================================================

三次独立复审里,最后一层意见不再是「会不会算错」,而是「这是一份能合进上游的 PR 吗」。
这一轮把那一层清掉了:

**公共结构体不再中间插字段。** `llama_model_params` 的 `split_layer_lo/hi` 移到 struct
末尾,`llama_context_params` 的 `embeddings_pre_norm` 移到 bool 块末尾——并顺手把
`kv_unified` 那两行被切开的续行注释接回去(它们原先读起来像是在描述 `embeddings_pre_norm`)。
中间插字段会改变其后所有字段的偏移,而这两个结构体都是**位置初始化**的:编译能过、值会
静默错位。核对用了三重手段——静态解析 `llama.h` 的字段顺序与两个 `*_default_params` 的
`/*.field =*/` 列表逐项对齐;运行期 ABI 探针断言 19+39 个字段的默认值与 `offsetof` 关系
(并对照「旧 dll + 新结构体」确实串位,反过来印证 `--clean-first` 的必要性);跨版本用改动
前的旧二进制跑 baseline,logits 与 hidden 逐字相同(argmax=3709)。

**`src/` 下的中文注释改成英文。** 61 行(`slim-arc-prefetch.h` 35 + `.cpp` 18 +
`qwen35moe.cpp` 8),保留 `[QLH-SPLIT]`/`[C-scheme]`/`[DFLASH-01]` 前缀与全部技术信息。
剩下 20 行中文是上游既有的——`llama-chat.cpp` 的 chat template 占位符、`llama-vocab.cpp`
的 CJK 分词正则,与 `e0f142d` 版本逐字节相同。`common/`、`tools/`、`tests/` 里的中文保留:
那些不在上游 PR 范围内,且这个项目的中文文档是刻意的。

**测试不再硬编码本机路径。** 三个测试改成「`argv[1]` 或 `QLH_SPLIT_MODEL`,缺失则打印
一行 SKIP 并 exit 0」。顺带发现并修了一个更要紧的问题:`tests/split-smoke.exe` 原先不在
cmake 目标里、靠手工 `cl` 编译,`verify.sh` 用的是那份旧二进制——结构体一改序,它与 dll 的
布局必然不一致,而组 1 的逐位对比会照常「通过」。现在它和其他测试一样由 cmake 构建。

================================================================
七、并发与输出
================================================================

- 分段链支持 `-np > 1`:server 的 `can_batch_with()` 允许两个 slot 进同一 batch,而
  `decode_split` 原先只取每行第一个 seq_id。现在每行保留真实 seq 集合
  (`llama_batch_ext_add_seq` 本来就是公开 API),位置各归各行。`-np 4` 四个并发请求的
  输出与串行逐字节相同。
- tail 段的 logits 缓冲从 `n_batch × n_vocab` 改成按角色分设:head 保持派生自 n_batch
  (它每 token 都要一行 hidden),tail 设成 `n_seq_max*(1+n_max)`。实测 `-ub 2048` 时
  1710.76 MiB → 3.79 MiB。下限 `n_seq_max` 不可省——`output_reserve` 先把上界抬到
  `n_seq_max()` 再断言。

================================================================
八、三种「能起来但算错」的配置,现在都在启动时拒绝
================================================================

分段链最坏的失败方式是**启动成功、返回 200、内容是错的**,因为 snake 一条错配的链不会有任何
异常。这一轮把这类形状一口气收掉:

**单独跑一个尾段范围。** `llama-server --split-layer-range 20:24`(24 层模型,不给
`--split-tail-range`/`--split-remote`)会正常加载、返回 200——前 20 层根本没算。它的参数形态
与 server 自己加载 tail 段时**逐字段相同**(`common_init_from_params` 里 `split_layer_lo=20`、
`hi=24`、`split_tail_lo=-1`),所以只能靠「这个进程是怎么拿到这个范围的」区分:`common_params`
里加一个内部 bool,server 组 tail 时置真,别处一律为假。`0:20`(缺尾巴)与 `20:24`(缺头)
现在各给一条点名缺哪几层的消息,并给出两种正确写法。

**本地链的 head 不从第 0 层开始。** `--split-layer-range 8:20 --split-tail-range 20:24` 的
tile 8..24 连续、又到末层,其余校验全过——但前 8 层从没算过,head 连 `tok_embd` 都没载
(`needs_tok_embd()==false`),实测启动、200、**纯乱码**。`split_attach` 现在校验 head 的
`layer_lo == 0`,与远程路径已有的那条对称,`split-smoke` 的 `[F]` 组加了反例。
`llama.h` 的 API 注释同步写上这条契约。

**远程链 + `-np > 1`。** 这条之前是「库里有拒绝、但 server 路径根本走不到」——`server_prepare_params`
在更早的地方就用另一条消息拒了。两条消息现在都改成语义明确的版本,并记录这个决定:远程链
单序列是**设计决定**而不是缺口(技术上约 105 行:每行 `seq_id` 过协议、client/stage 逐行传递,
checkpoint 本就 per-seq),理由是远程链解决「一台机器装不下」或「借用算力」而不是多租户,
真要并发就**起多个 server、各带一条链**——单条链上任何一段出问题会拖垮所有 seq。

================================================================
九、一次网络抖动曾经杀掉整个 server
================================================================

跨机实测(本机 head + ROG tail,35B 未降级)暴露了一个 loopback 上永远看不到的形状:
用 `NtSuspendProcess` 挂起 stage 之后,`/health` 在那 120 s 里**一直回 200**,而 head 在
`seq_rm` 失败后 `GGML_ABORT` —— **整个进程退出,所有 slot 一起**,此后端口直接拒绝连接。
文档当时写的是「把永久卡住变成一次普通请求失败」,实测证伪。

abort 的理由原本是对的(KV 错开后每个后续 token 都是错的且不可检测),错的是承载它的东西。
现在改成:远端操作失败 → 置 `remote_failure`(链已不可信)→ **不 abort**,返回值交给 caller;
`common_context_seq_rm` 查到链已死就 flush 日志、打两行 ERROR、return。安全性没有放松——
`decode_split` 在算任何东西之前就查这个状态并返回 `-3`,后续每个请求都失败,**绝不会假装成功**。
变的只有谁承担后果:从「进程死」变成「这条链死、server 活着、返回明确错误」。

1. **同一类的第二处**(实测才发现,真实路径上先炸的其实是它):槽里有缓存前缀时请求先走
   checkpoint 恢复,远端 `state_load` 超时 → `failed to restore context checkpoint` → 同样 abort。
   现在恢复失败且链已死时回退整段重算,后续 `seq_rm`/`decode` 带着原因失败成 500;本地链和
   draft 的恢复失败仍 abort。
2. **链死后不再向 stage 要状态**:`state_size`/`state_write`/`state_read` 对死链直接拒绝,
   把一次失败请求从「120 s + 再等 120 s」压到 120.0 s。
3. **链死之后 `seq_rm` 不再碰网络**(否则每个后续请求都要再等 120 s),实测第二个请求 **0.01 s** 失败。
4. **`/health?deep=1`**:浅 `/health` 语义一字未变(那是存活性,链路抖一下就摘机器比不摘更糟);
   显式问 deep 才走链路——链已死快速 503,链活才真的发一个 1-token 请求。服务忙时返回
   `200 {"deep":"busy"}` 并明说「链没有被验证」,不替编排器做摘机器的决定。探针是真请求且
   `cache_prompt=false`,所以**不适合轮询**(代价在缓存不在时间),这两处都写进了注释。

端到端验收新增 `build-split/verify_chain_death.py`(真 `NtSuspendProcess`、真 120 s 超时):
27 项全过——挂起后请求 500 但 head 存活、后续请求 0.01 s 失败、deep 探测 503、日志里没有
`GGML_ABORT`、只重启 stage 不自愈(仍 500)、重启 head 后重建成功。

### 还没做的自愈

现在链死之后进程活着、每个请求明确失败,但**恢复仍然要重启 server**。自愈 = 重连 + 清空 +
让 server 重置 slot 的 `n_past`,四件缺一不可——因为重连后远端 KV 是空的,而 server 还记着
旧位置,不重置就会从旧位置接着算,**自愈本身会变成新的静默错源**。

另外投机路径还有三处 abort(抓 speculative checkpoint / draft ctx 的 `seq_rm`),触发条件是
「开投机 + head 没给 `--split-rs-seq` + 远端掉线」三者同时成立。这轮只在注释里记录了条件和
「为什么不能像 `seq_rm` 那样一行改掉」(没有 blob 就无法 rewind 已验证的 token,缺的是 unwind),
留待下一轮。

================================================================
十、自愈:断了的链能自己接回来
================================================================

上一轮做到「链死、进程活、请求明确失败」,但恢复要重启 server。这一轮把恢复补上。

**做法**:`remote_failure` 非空时,在 `decode_split` 的最开头(在 head 自己 decode **之前**,
否则 head 刚算出来的 KV 会被随后的 clear 抹掉)判断这次 batch 是否每个 seq 都从位置 0 开始;
是则尝试重建——逐个 `reconnect()`(有界 connect,1.5 s)→ 整链 `clear()` 广播 → 恢复数据通路
超时。任一步失败就保持 dead,并做 5 s 节流,避免每个请求都卡在 connect 上。

**安全闸门是结构性的,不是靠猜**:重建后链的唯一一致状态是「所有段都空」,而空链只能从位置 0
开始写。所以「batch 不从 0 开始就拒绝重建」这一条,让「KV 空了但位置接着算」在结构上不可能发生。

**不需要「链代数」计数器**。查代码确认:远程链只有**一个** slot(`split_attach_remote` 硬拒
`n_seq_max > 1`),而它发现失败的那个请求走 `decode` 错误路径时 server 自己就 `prompt_clear()` 了
(`server-context.cpp` 的 `ret < -1` 分支),所以恢复后的第一个请求必然 `n_past = 0`。这比加信号
更简单,也不用改 server 主循环。

### 实测

- 只重启 stage、不重启 head:`/completion` **200 in 0.50 s**,输出与基线**逐字节相同**
- **`prompt_n = 5`(等于基线)、`cache_n = 0`** —— 这是「slot 被正确重置、没有接着旧位置算」的直接证据
- stage 一直不回来:连发 5 个请求耗时 `[1.51, 0.01, 0.01, 0.01, 0.01]`,没有一个卡在 120 s
- 节流:5 个请求 → `rebuild attempt = 1`、`rebuild suppressed = 4`
- `verify_chain_death.py` 从 27 项扩到 **36 项**(D 组从「只重启 stage 仍 500」反转为「只重启
  stage 就 200,且 prompt_n / cache_n / 输出三项必须同时成立」,新增 F 组节流计数与 G 组
  `-np 2 + --split-remote` 启动即拒)

### 两个说清楚的边界

1. **失败在请求之外被发现时,客户端可能要多重试一次**:那种情况下 slot 的 cache 没被清、恢复后
   第一个请求会因为 batch 不从 0 开始而被拒,server 随即清 slot,第二个请求才自愈。这是有意选的
   「宁可多一次 500,也不猜」。
2. **协议没有身份握手,自愈让它更容易被触发**:stage 重启成不同 `--layer-range` 或不同模型时,
   重建不会发现,会静默算错。这是 attach 阶段就存在的旧风险,不是自愈引入的,但自愈让「重启
   stage」变得可行,也就让这个旧风险更容易撞上一次。要堵它得在协议里加 model/layer-range 的
   身份校验,那是下一个决定。

================================================================
十一、身份握手:接错的 stage 不再被当成「链好了」
================================================================

自愈让「重启 stage」变成常规运维动作,于是「重启成另一个 stage」的概率从「几乎不可能」变成
「手滑就会碰上」——而以前协议没有握手,重连只是纯 TCP 重连,接错了不会发现,会静默算错。
这个风险在 attach 阶段就存在,但自愈把它推到了前排。

`PROTO_VER` → 4,新增 `OP_HELLO`:连接建立后的**第一帧**,客户端带它期望的身份,stage 回自己的
身份,客户端比对。`reconnect()` 也必须重新握手——**重建时接错的 stage 必须被拒绝,而不是被当成
链好了**。

身份内容(`stage_id`,28 字节,`static_assert` 锁尺寸):`layer_lo` / `layer_hi` /
`n_layer_src` / `n_embd_inp` / `n_embd_out` / `n_vocab` / `role`。**不做模型文件哈希**——读几百
MB 只为拿一个 ID 不划算;这七项加起来足以认出「层范围错、模型换错、层数不同、角色配反」。

失败信息直接说人话:`this stage is layers [8, 16) of a 24-layer model (... role relay), but the
chain expects [20, 24) of 24 (... role tail) (layer_lo expected 20, the stage reports 8). It looks
like the wrong stage is listening on 127.0.0.1:9331.` 版本不符也明说「两端必须同源重建,这不是
网络问题」——以前只回 `bad reply header`,运维会去查网络。

`split_attach_remote` 现在**串行** connect + hello,本地 `split_attach` 那套 tiling 校验搬到了
线上:`layer_lo` 必须接上一段的 `hi`、最后一段的 `hi` 必须等于 `n_layer_src`、role 必须是 tail。
三段链里第二段接错时,错误只指向 stage 2,第一段仍被接受。

### 验收

- 接错 stage → attach 失败,信息点名「它是什么、我期望什么」
- **自愈时接错 → 重建失败、链保持 dead、请求 500 in 0.02 s**(不是静默成功)
- 自愈时接对 → 恢复、`prompt_n` 等于完整 prompt 长度、输出与基线逐字节相同
- 旧版 stage 连新版 → 「protocol version mismatch: this build speaks v4, the peer answered v3 …
  this is not a network problem」
- `verify.sh` 25 项、`verify_chain_death.py` 36 项、`.qlh_tmp/verify_hello.py` 40 项断言全过

### 这条边界要留着

**握手防「接错」,不防「恶意替换」**(无密钥、无 HMAC),也**区分不了同形状但不同权重/不同量化/
不同微调的 GGUF**——layer 范围、层数、宽度、vocab、role 全相同就被视为同一个 stage。这是
「不做模型哈希」的代价,也是这个设计最主要的剩余风险。真要区分,得把量化类型(`general.file_type`)
加进 `stage_id`,或者做权重摘要;前者便宜但只挡一部分,后者不划算。

================================================================
十二、远程 tail 回传从 993 KB 降到 352 B
================================================================

跨机 decode 只有整模 45–54% 的主因是远程 tail 每 token 要回传整词表 logits
(`248320 × f32 ≈ 993 KB`)。这一轮把它降到**每 token 352 B**(头 32 B + 40 个候选 × 8 B),
**2821 倍**,而且不改采样语义。

### 为什么可以等价

`common_sampler` 的链顺序是 `penalties → dry → top_n_sigma → top_k → typ_p → top_p → min_p
→ xtc → temp`。**`top_k` 之后的所有步骤只在 k 个候选内作用**——一旦截断到 40 个,后面的
`top_p`/`min_p`/`temperature`/`dist` 再怎么算也只会挑那 40 个里的。所以回传这 40 个
`(id, logit)` 再让 server 跑完剩余链,与回传整行**数学等价**。

前提是 `penalties` 必须在 `top_k` **之前**跑完,所以 **tail 侧建一个
`logit_bias → penalties → top_n_sigma → top_k` 的 chain 先跑**,server 从 `cand_first`
(top_k 在链里的下一个节点)接着跑,**不重复施加 penalties**。

### 惩罚历史用「每帧窗口」而不是增量式

tail 收到的是 hidden、不知道 token,所以 server 每帧带最近 `min(penalty_last_n, n_prev)` 个
token,tail 从零 `reset` + 重放。代价 256 B/帧(相对 320 B 候选可忽略),换来的是:重连、
`seq_rm`、`state_restore`、slot 复用之后两端自动一致。**增量式一旦两端对「哪些 token 被
accept」有分歧就会静默错**,而这个错误看起来输出仍然「正常」。

### 回退是白名单预判,不是运行时兜底

集中在一个函数(`plan_remote_candidates`,每请求一次),条件包括:非远程链、grammar(GBNF
能把 top-k 外的 token 变合法)、reasoning-budget、pre-sampling logprobs(要整行 softmax 分母)、
投机、`penalty_last_n > n_prev`、`top_k <= 0`、`top_k >= n_vocab`、DRY 启用、mirostat、
backend sampling、chain 前段有不可复现步骤。每条都打一行
`[split] this request takes the whole-logits path: <原因>`——**漏一个回退会产出不合语法的
输出,而且是静默的**,所以不能靠运行时 `token=-1` 兜底。

### 实测

- **等价**:4 prompt × 64 token、penalties 三参、`top_n_sigma`、xtc、temp=0、`top_k=1`、
  logit_bias、ignore_eos、post-sampling logprobs、cache 复用两轮、400 token 长生成、
  10 组随机参数 fuzz —— **全部逐 token 相同**
- **带宽**(TCP 代理计数):同一 64-token 请求,整行 67,932,452 B vs 候选 4,383,012 B →
  每 token 省 992,960 B
- **loopback 延迟**:57.92 → 52.92 ms/token(+8.6%)。loopback 等效 ~200 MB/s 所以只值 5 ms;
  按跨机 LAN 的 24 ms/0.95 MiB 折算,每 token 省约 24 ms,跨机 decode 预计从
  4.67/5.38/6.05 到 **6.6/8.1/9.7 tok/s**(整模的 66–87%,原 45–54%)
- `verify.sh` 25 项、`verify_chain_death.py` 36 项、`verify_multislot --np 2` 全过;
  本地链不走这条路径,组 1/3/6/8/9 不受影响

### 没做的

prefill 阶段的 tail 仍整行回传(只有「将被采样的那一行」才请求候选),prompt 处理的带宽
未优化。

================================================================
十三、候选回传在跨机上是负收益,直到修掉 TCP Nagle
================================================================

候选通道在 loopback 上确实是正收益(A−B = −3.0/−0.4/−10.2 ms/token),**跨机却翻转成慢
22–31 ms/token**。三道独立证据指向同一个原因:

1. **代理抓包**:候选回复是「32 B 头 → 隔 48–52 ms → 320 B 载荷」,整行回复是「32 B 头 →
   隔 10 ms → 993 KB 连续」。up 方向(头 + 8208 B hidden)间隔 0.1–0.2 ms,无停顿。
2. **形状复现探针**:`32 B 两次 send` → 42.6 ms;`32 B + 320 B 一次 send` → 0.02 ms。
3. **代码**:`llama-split-net.cpp` 全文没有 `TCP_NODELAY`,而 `reply()` 是
   `send_all(头)` + `send_all(体)` 两次写。

320 B < MSS,被 Nagle 扣住等对端延迟 ACK;993 KB 按整 MSS 发,Nagle 免疫。**所以「把数据
变少」反而触发了「每次多等 50 ms」——优化只在跨机上变成负优化。**

修法:`net::send_two()`(WSASend 双缓冲 / POSIX `writev`,头+体一次系统调用,**993 KB
不复制**),`reply()` 只在 `data_bytes <= 1400`(一个 MTU)时走合并,大帧保持两次写——大帧
本来就按满 MSS 段发、Nagle 免疫,合并只会多一次 993 KB 拷贝。accept 后设 `TCP_NODELAY`
(head 侧本来就有,这正是 up 方向一直没问题的原因)。

修后抓包:旧的 24 次「32 B → 52.90 ms → 320 B」变成一次 352 B 到达,间隔 **0**。

### Surface 上重测(第一次用目标设备当 tail)

Surface Pro 7(i5-1035G4 4C8T、16 GB,只加载 `32:40` 八层)当 tail,Tailscale direct 9–10 ms:

| n_predict | A 候选 | B 整行 | A−B |
|---|---:|---:|---:|
| 32 | 174.3 ms(5.74 tok/s) | 378.5 | **−204.2** |
| 64 | 175.8(5.69) | 350.3 | **−174.5** |
| 128 | 164.6(6.08) | 403.5 | **−238.9** |

方向与符号翻转正确。幅度远大于 ROG 上预期的 +22~30 ms,因为 B 每 token 的 993 KB 在
Tailscale(~5 MB/s)上要 ~200 ms——**链路越慢,省掉整行越值钱**。

绝对值没到 ROG 的 110 ms/9.1 tok/s:那是 LAN + i9 的数。这里是 Tailscale 10 ms RTT +
Surface 那台 4C8T 的算力,loopback A=118.8 ms 对跨机 A=174.3 ms,差 55 ms ≈ 2×RTT +
Surface 比本机 tail 慢 + WireGuard 开销。

### 没有第二个 Nagle 类等待

修复后每 token 只剩 1 次 RTT 的固有成本(抓包:up 8372 → dn 352 = 72.8 ms,dn 352 →
next up = 74.0 ms)。`TCP_NODELAY` 对 up 方向无新增包(8 KB hidden 始终是 5–6 个满 MSS 段)。

`verify.sh` 25 项、`verify_chain_death.py` 36 项全过;跨机等价性 4 prompt × 64 token
**ALL IDENTICAL**;loopback 上 A 仍快 2.1–5.4 ms(无退化)。

================================================================
十四、每请求 13.17 MB 的状态搬运改成 8 字节句柄
================================================================

候选回传之后,远程链还剩一个**每请求固定 13.17 MB** 的成本——比 logits 那部分大一个数量级
(993 KB/token × 若干 token,而这是每请求一次)。在 5 MB/s 的弱链路上就是 2.8 秒/请求。

### 这 13,172,908 B 是什么

qwen35moe 35B 的 8 层尾段(`32:40`)的 recurrent state,f32、单序列 1 个 cell、不含 KV。
该段 recurrent 层是 32/33/34/36/37/38 共 6 层(35 与 39 是全注意力层,贡献 0):

```
R(conv)/层 = 3×(4096 + 2×16×128) = 24,576 f32 = 98,304 B      (4.5%)
S(ssm) /层 = 128 × 4096         = 524,288 f32 = 2,097,152 B   (95.5%)
13,172,908 = 8 + 4 + 8 + 8 + 6 × (24 + 98,304 + 2,097,152)
```

三件「没有」:没有 KV cell(`PARTIAL_ONLY` + 非 SWA 直接 return)、没有 rs 回滚环(只写当前
平面,所以与 `pos_max` / `--rs-seq` 无关)、没有 PLE。旧文档的 6.4 MiB 不是错——那是 2B
(`d_inner=2048`,6,733,996 B),35B 是 12.56 MiB。

### 为什么每请求都传

hybrid → `seq_rm_type = RS` → checkpoint 永远开着;recurrent cache 的 `pos_min == pos_max`
使恢复**只能**走「找 checkpoint 恢复」这一支;恢复点之后又解码、末尾断点前移,于是又存新的
(实测甚至有「恢复 117 号后立刻在 117 号原地重存」)。`cache_prompt` 只控制**恢复**、不控制
**创建**,所以两种配置都付。

### 句柄化:让 stage 自己留着,head 只收一个 ID

状态本来就在 stage 的内存里,而旧协议是「head 把它拉回来、存着、恢复时再推回去」——纯搬运。
现在 `OP_STATE_SAVE` 让 stage 存进自己有界 LRU 快照缓存,回一个 **8 字节句柄**;
`OP_STATE_LOAD` 只传句柄。

三个关键设计:

1. **随机 64 位句柄,不用计数器**。计数器在 stage 重启后会从 1 重新开始,而 head 手里的旧句柄
   可能正好等于新进程的某个快照——**静默错 token**。随机句柄让「重启后旧句柄必然失效」。
2. **`OP_HELLO` 时清空快照**(重建 = 整链已 clear),所以身份握手同时承担了「代」的区分。
3. **过期是良性失败**:stage 在应用前拒绝、head 最后才恢复自己的 KV,两边都没动;
   `state_stale` 与 `remote_failure` 分开,server 走「丢 checkpoint、从头重算」,不 500、不 abort。

内存:默认 32 份 = 402 MiB(35B)/ 205 MiB(2B),但 head 侧每份 checkpoint 同时从
62.81 → 50.25 MiB,**整链净增量≈0,只是从 head 挪到 stage**。16 GB 机器 +402 MiB 是 2.6%。

`--state-cache N` 默认 32(对齐 head 的 `--ctx-checkpoints`)。旧 slot 文件保留 inline 分支
(`n_bytes == 8` 才是句柄),不会把 12.56 MiB 误读成句柄。

### 实测(TCP 代理计数,2B 8 层尾段,同 slot 3 请求)

| | 改前下行 | 改后下行 | 改前上行 | 改后上行 |
|---|---:|---:|---:|---:|
| `cache_prompt=false` #0 | 7,728,876 | **994,888** | 1,216,368 | 1,216,368 |
| `cache_prompt=true` 命中 | 14,463,000 | **995,024** | 6,834,236 | **100,248** |

一份 checkpoint:6,733,996 B → **8 B**。按 35B 折算:一份 13.17 MB → 8 B,`cache_prompt=false`
一请求 14.17 MB → 0.99 MB(剩下的就是 logits 行),warm 请求 ~40.5 MB → ~1.1 MB。

### 评估过但不做的

- **增量**:不成立。rs 环的粒度是 cell,而一个 cell 就是整条序列的整份状态(`s_l` 是
  `[n_embd_s, mem_size*(1+n_rs_seq)]`,每 token 整行重写)。证据:blob 与 `pos_max` /
  prompt 长度恒无关。
- **磁盘**:每份 12.56 MiB 在请求路径上多一次同步 IO(NVMe 20–30 ms),换来 402 MiB 内存,
  不值;且文件生命周期更难管。
- **`cache_prompt=false` 时干脆不建 checkpoint**:纯 stateless 下那是 13 MB 买 0(建出来的
  checkpoint 只能被之后同 slot 的 `cache_prompt=true` 用到)。一行 `is_stateless()` 守卫能省,
  但改的是 server 行为,留作单独评估。

`verify.sh` 25 项、`verify_chain_death.py` 36 项、`verify_multislot --np 2` 全过;
新增 `verify_state_stale.py`(淘汰 → STALE → 重算 → 输出与不淘汰逐字节相同)。

================================================================
十五、重构:把隐式依赖变成类型约束
================================================================

`decode_split` 374 行、`tools/split-stage` 的 `main()` 1111 行,各自承担了四五件事。这一轮只
拆函数、不改行为——判据是「改前改后 25 + 36 项验收全过」而不是「看起来一样」。

- `decode_split` → 20 个单元,最大 65 行,本体 34 行,读起来是
  `admit → 本地 head decode_plain → carrier → gather → remote 或 local`
- `main()` → 本体 33 行,只剩 `parse → init → accept`

真正有价值的是三处「先做 A 因为 C」的顺序依赖,从注释变成了**编译器能检查的约束**:

1. **`synchronize` 必须在 `gather` 之前**(decode 是 async,`get_embeddings_ith` 内部不同步):
   引入 `struct split_synced`(构造即 synchronize),`gather` 只接受 `const split_synced &`——
   拿不到同步标记就进不去。
2. **`any_output` 的回退**(整批没有 output 标记时退回「最后一行」):
   `split_logit_plan` + `split_plan_logits()` 一次算出 rows,`build_hop` 与 `run_hop` 都收
   `const split_logit_plan &`——请求的行和校验的行不可能不一致。
3. **remote logits 先清再填**:五个 `split_remote_*` 槽位只能经 `reset` / `store_cands` /
   `store_logits` 写,两个 `store` 都先 `reset`——「填」蕴含「清」。

`vlog` / `send_two` / 状态快照缓存 / `reply()` 的 1400 字节合并阈值全部原样未动(那个阈值是修
Nagle 的关键)。

### 重构中发现但没改的四处(留作后续)

1. `decode_run` 的 tail 路径把整行 logits 拷进临时 vector(993 KB/token),`reply()` 其实可以
   直接发 `lg`——候选回传之后只有整行回退时才走这里,但仍是白拷贝。
2. stage 侧 `req.seq_id` 不校验范围就交给 memory 层(`seq_rm` / `pos_max` / `state`)。
3. `--layer-range` 用 `sscanf` 不检查返回值。
4. 候选请求越界时整帧未读完就断连(不回复),保持原样。

================================================================
十六、远程链的投机验证通道(协议 v7)
================================================================

之前判断「远程链不做投机」的理由是协议只回最后一行 logits、候选通道又显式拒绝 speculative。
这一轮把验证通道补上了:**tail 对验证帧的每一行都回一个 argmax**,一帧 k+1 行是 4(k+1) 字节。

### 为什么只要 argmax 就够

`common_sampler_sample_and_accept_n` 在 `temp=0` 时逐行调 `common_sampler_sample`,贪心下等价
于 argmax。所以验证只需要「每行一个 token id」,不需要完整分布——后者是采样拒绝验证才需要的
(v2 试过,每轮 5–7 MB,比不投机慢 1.9×)。v2 当年就是这么做的:tail 端算 argmax、只回
`int32` 数组,k=2 一轮过网约 56 KB。

### 协议 v7

`PROTO_VER` 7。关键设计是把「帧内行号」和「batch 绝对下标」的歧义**堵死在 arming 处**:

- `DECODE_FLAG_VERIFY_ROWS` 与 `DECODE_FLAG_CANDIDATES` 互斥
- 回复体 = `n_tokens × int32`,行序;`n_vocab`/`n_embd` 为 0
- `MAX_VERIFY_ROWS = 17` 是两端共享常量(tail 的 `n_outputs_max`、head 的判据、server 的草稿
  上限三处同一个数)。只在一端限制的话,tail 的 `output_reserve` 会 abort 而不是错 token
- **`request_remote_verify_rows` 硬性要求 `off == 0`**——按帧内行号索引与 batch 绝对下标只在
  帧首对齐时相同;不满足就不 arm(fail loud,不静默错位)。这是将来远程链支持多 slot 或把
  prompt 块与投机块拼进同一帧时最先出事的地方

### 回退只能在发帧前定

token id 里没有分布,**帧内无法改路**。所以 `plan_remote_verify_rows` 在 launch 时一次定死;
不满足条件时远程链**不能**退回整行(整行只有最后一行有 logits),必须整请求关掉投机——这就是
`spec_blocked` 的由来,顺带修掉了原来 remote + spec 直接 `GGML_ASSERT(logits != nullptr)` 崩溃。

### 实测

| 指标 | 值 |
|---|---|
| 单帧回复(4 行) | 993,312 B → **48 B**(20,694×) |
| 本地链端到端(64 token) | 15,875 → 31,056 B/token,**13.7 → 31.2 tok/s** |
| **ROG 跨机(32 token,ngram 投机)** | **1.86 → 8.08 tok/s(4.3×)**,输出逐字节相同 |

ROG 那个 4.3× 值得记一笔:**收益不只来自省往返,更来自省 tail 的前向次数**。ROG 上 4 行 ×
8 层 35B 要 66–123 ms,而每个 decode 帧都要付——投机把 4 行压进一帧,省的是 4 次 tail 前向。

`verify.sh` 25 项、`verify_chain_death.py` 36 项、`verify_multislot --np 2`、
`verify_seq_id.py` 全过;普通 `/completion`(temp=0)改前改后逐字节相同。

================================================================
十七、远程链的 MTP draft(协议 v8)
================================================================

验证通道通了之后,远程链还只能拿 ngram 当 draft——而 ngram 依赖文本重复,在真实负载上
往往一个 draft 都提不出来(实测:ROG 上同一个新鲜 prompt,ngram 组接受率 0,比不投机还慢)。
这一轮把 **MTP draft 下沉到远程 tail**,让它跑真正的草稿头。

### MTP 为什么必须建在尾段

MTP 是**完整的一层 transformer**(`blk.40` 856.36 MiB,其中 MoE 专家 820.18 MiB 占 95.8%),
不是「草稿头小部件」——全文件只有 1 个 `output.weight`、1 个 `token_embd.weight`,所以它
不自带 lm_head 也不自带 embedding;输入是 `t_h_nextn = RMSNorm(最后一层输出, output_norm)`。
三条结构性限制(输入只在末层之后、词表张量只在末段、loader 的
`nextn_keep = (hi >= n_layer_src) ? nextn_all : 0`)让它只能跟最后一段。

### 协议 v8 的两处布局改动

1. `OP_MTP_DRAFT`(op 8):请求体 `hidden` 一行 + `mtp_req{token,pos,k}`;回复是 k 个 int32。
   **k 步递归在 stage 内部完成**——每步的输入 h 是上一步的输出,不能批处理。
2. `DECODE_FLAG_NEXTN_ROWS` / `RSP_FLAG_NEXTN_ROWS`:decode 回复追加 `n_rows × n_embd` 个 float。
   **`n_rows` 只能取 `rsp_header.n_tokens`**,不能从字节数反推,否则帧边界错位。

`stage_id.has_nextn` 占原来的 `_pad` 字节(struct 仍 28 B),而且**故意不参与身份比较**——
「能力」不是「身份」。

### 一个容易被当成「效果不好」的 bug

`split_remote_reset()` 会清掉所有 per-frame 槽位,**包括新加的 h_nextn 行**。原来先存行、后存
logits,结果行被 `store_logits()` 的 reset 抹掉 → stage 回 2048 floats、head 收到 0 行 →
**draft 静默消失**:不报错、不变慢,只是不投机。现在 `store_nextn` 在三个回答分支之后执行,
回归判据是 wire 上的 h_nextn 与整模逐位相同。

### 实测(ROG,head 0:32 + tail 32:40,LAN)

| 组 | tok/s | 接受率 | mean len |
|---|---:|---|---|
| 不投机 | 8.88 | — | — |
| ngram-simple | 6.82 | **0 draft(新鲜 prompt 提不出来)** | — |
| MTP k=3 | 9.76 | 0.625 | 2.88 |
| **MTP k=2** | **10.20** | 0.853 | 2.71 |
| MTP k=1 | 10.11 | 0.880 | 1.88 |

**甜点是 k=2(+15%)**;k≥3 被验证帧拖累——head 32 层要把 k+1 行全算,而 tail 只有 8 层,
宽帧的代价几乎全在 head。

ngram 那组的 6.82 是个有用的反例:**同一链路、同一 prompt,ngram 接受率 0,比不投机还慢**。
之前那次「ngram 8.08 tok/s」用的是 `A+B+A+B+A` 这种人为重复文本,不代表真实负载。

### 逐 token 判据

`verify_mtp.sh`:同一行 h(先证明与整模 `h_nextn` 逐位相同)、同一 token、同一 pos,远程
tail 内部递归 3 步的结果与「整模 + MTP」**逐个相同**(11751/13/271 三个 token 全中)。
`verify_mtp_e2e.sh`:远程链三组(不投机 / ngram / MTP)输出**逐字节相同**。

`verify.sh`(带构建)25 项、`verify_chain_death.py` 36 项、`verify_multislot --np 2`、
`verify_seq_id.py` 7 项全过。

================================================================
十八、split-stage 的线程参数,与「批量 forward ≠ 逐行 forward」
================================================================

### `-t` / `-tb` / `-ub`

`split-stage` 之前不解析线程参数,而 llama.cpp 的默认值是 **`GGML_DEFAULT_N_THREADS = 4`**,
**且 `n_threads_batch` 也是 4、不会自动跟随**。所以在 Surface(4C8T)上,tail 只用了 4 个线程,
SMT 空着。

现在加 `-t/--threads`(与 llama-server 同义,同时设两者)、`-tb/--threads-batch`(只设 batch)、
`-ub/--ubatch-size`(诊断用)。不指定时完全不动 `cparams`,默认行为不变。启动日志打印实际
线程数与 ubatch。

Surface 实测(p1 散文 882 token、temp 0、n=64):

| 配置 | 不投机 | MTP k=2 |
|---|---:|---:|
| 缺省(4/4) | 7.41 | 5.12 |
| `-t 8`(8/8) | **7.67(+3.5%)** | **5.48(+7%)** |
| `-t 8 -tb 4`(只设 n_threads) | — | 5.16(≈没赚) |

**只设 `n_threads` 拿不到收益,batch 那一半必须一起设。** 收益小是因为 tail 只占 8/40 层。
8 线程也没把投机救回来(5.48 < 7.67)。

### 批量 forward 与逐行 forward 是不同的数

这条值得单独记,因为它推翻了「投机应该与不投机逐字节相同」这个判据。

整模、不分段、纯 embeddings 模式下的判定性对照:

```
同一情形跑两遍    max|Δh| = 0              ← 确定性,不是噪声
1 行 vs 2 行      h 的 2048 个元素全部不同,max|Δ| = 0.273
rows=2 与 rows=3  差异数值完全相同
```

第三条说明它不是「行数越多差越多」,而是 **ggml 的 kernel 形状切换**(`ncols=1` 走 gemv,
`ncols>1` 走另一条路径)。**这是 llama.cpp 的固有性质,不是分段引入的。**

所以正确的判据是「**分段不改变投机结果**」——链上 MTP 与整模 MTP 逐字节相同(已 PASS,
k=2、acceptance 0.909)。而「投机 == 不投机」只能作 INFO:链上任何一次批量验证都会漂,
是否翻转取决于那一步的 top-2 差是否小于漂移量。

**v2 当年也没做到**:`chain_client.py` 的 `forward_batch(clients, block, n_past+1)` 也是 k+1 行
一次 forward;它声称的逐位一致来自 `probe_perfect_draft.py`,而那个 probe 只测了 2 行 + 30 token。

### per-row 通道没有固定开销

之前以为 Surface 上「ngram 1 行、0 接受、仍慢 97 ms/token」是 per-row 通道的固定开销。实测
(`QLH_STAGE_TIMING=1`)否掉了这个推断:

| 帧类型 | 准备 | decode | post | 回包 |
|---|---:|---:|---:|---:|
| 不投机(候选通道) | — | 66.8 ms | 2.50 ms | 0.10 ms |
| verify(3 行) | 0.02 ms | 170.0 ms | 2.38 + 0.19 ms | 0.00 ms |

per-row 干的活和候选通道一样多(2.57 vs 2.50 ms)。真正的开销是**单行 66.8 ms、第 2/3 行各
+51.6 ms(3 行 = 2.54× 单行)**,以及 **MTP draft 每 step ~31 ms**(1 层 NextN + 一次 248k
输出投影,k=2 一轮 64 ms)。

MTP k=2 一轮的账:tail 170 + draft 64 + head 3 行 ~75 + 3 次往返 ~36 ≈ 345 ms / 1.94 token
≈ 178 ms/token(实测 204)。不投机 137 ms/token。**弱机器上投机仍不划算,但原因不是
「per-row 固定开销」,而是「tail 批量只省 17% + draft 每步 31 ms」。**

================================================================
十九、grammar 与逐行验证通道:让 agent/tools 负载能真正投机
================================================================

上一轮实测发现,**这个项目的目标负载(agent 后端 + 工具调用)一条投机都跑不到**:
llama-server 为 tool calling 自动建 grammar,而 `common_sampler_verify_rows_check()` 里有一条
`if (grammar) return false`,于是 `spec_blocked=true`。

而那条拒绝的理由是从候选通道(v5)沿用过来的——「GBNF 能把 top-k 外的 token 变合法」。
对 per-row argmax 通道(v7)它不成立:tail 回的是「每行最可能的 token」,head 只要问一句
「这个 token 语法上合法吗」就够,不需要 tail 理解 GBNF。

### 做法:head 侧单 token 自检 + 非法整帧回退

核心约束是 **`llama_grammar_accept_token` 对非法 token 抛 `runtime_error`**。所以:
- **验证通过才 accept**,被拒就返回 `LLAMA_TOKEN_NULL`——绝不 accept,也不用替代 token
  (那会是 row 路径不会产出的 token)
- 自检用 `llama_grammar_apply_impl`,它只把不合法 token 置 -INFINITY、**不推进状态**,所以可以
  反复问而不污染
- `sample_and_accept_n` 遇 NULL → **整帧作废**(不是截短:截短后的回放帧最后一行还是被拒位置,
  下一轮同样被拒,会空转)
- 回退要撤三样:**KV、prompt、sampler(含 grammar 那一份)**。漏掉 sampler,grammar 就会吃掉
  一行从未输出的 token,之后所有约束都错,而且**静默**

### 一个必然崩的前提

整帧回退要从 KV 移除 `n_draft + 1` 个位置,而 `need_n_rs_seq()` 原来返回 `draft.n_max`——只保证
移除 `n_max` 个。于是 `llama_memory_recurrent::seq_rm` 的 `rollback <= n_rs_seq` 拒绝,
`common_context_seq_rm` 直接 `GGML_ABORT` 杀进程。

**触发条件是「第一个验证帧就被 grammar 拒」——正常速度必现。** 改成 `n_max + 1` 后消失。
这个 bug 的性质值得记:它藏在「只要 grammar 不拒就永远不触发」的位置,只测无 grammar 的路径
永远发现不了。

还需要 `skip_draft_once`(回退后跳过恰好一轮 drafting),否则同一位置会被同一个被拒的 argmax
反复拒——空转,一个 token 都出不来。

### 判据的最终形态

「链上投机 == 整模投机」在**发生回退后不再成立**,而且这不是 bug:回退让链多一次 1 行重算,
帧对齐从此与整模永久错开,kernel 形状差(h 差 0.27 量级)在 top-2 近似并列处会翻。所以判据拆成:

- **(a) 无回退时**:必须逐字节相同(严格)
- **(b) 带回退时**:只能保证到「漂移翻掉的第一个近似并列处」

实测:k=1 带 3–5 次回退、k=2 json 带 4 次回退——**都逐字节相同**;只有 k=2 natural(2 次回退)
在 `18` vs `18.0` 上翻,两边都是合法 JSON。而**不投机时链 == 整模逐字节相同**,说明 grammar
逻辑本身不引入差异,回退也不改变结果(每次回退紧跟的 token 都与整模一致)。

### 实测:本机回环上是负收益

| 配置(2B、CPU、回环、40 token) | ms/token | tok/s |
|---|---:|---:|
| 不投机 | 48.02 | 20.82 |
| 投机 k=2 | 71.66 | 13.95 |
| 投机 k=1 | 62.65 | 15.96 |

三条原因:每帧两次 hop、**MTP draft 不看 grammar**(接受率只有 1.46–1.73 token/帧,无 grammar
时 2.76)、回退率 9–19%(每次回退 ≈ 一整个普通 round)。回环上 993 KB 只要约 1 ms,所以
「带宽省四个数量级」完全体现不出来——**真实链路上会反过来,这条必须在真链路上测**。

而且**回退率随 grammar 紧度暴涨**:`toolcall.gbnf`(4 选 1 枚举 + 固定 city)实测 11/16 帧被拒,
那种语法下投机基本没意义。grammar 越严格,投机越不划算——这是与「带宽省得多」相反方向的力。

### 还有第二道闸

真实 `/v1/chat/completions` + tools 在 2B 上还会撞 `rbudget`(模板的 lazy tool grammar 会建
reasoning-budget sampler,`verify_rows_check` 仍拒它)。`common_reasoning_budget_apply` 是纯掩码
(只在 FORCING 把非 forced token 置 -INFINITY),同样的「自检 + 回退」可以直接套用。

`verify.sh` 25 项、`verify_chain_death.py` 36 项、`verify_seq_id.py` 7 项、`verify_mtp.sh` 6 项、
`verify_mtp_e2e.sh` 6 项、新增 `verify_grammar_spec.sh` 22 项——全过。

================================================================
二十、reasoning-budget:真实 tools 请求的最后一道门
================================================================

grammar 通了之后,真实的 `/v1/chat/completions` + tools 仍然走不到投机:

```
speculative decoding is off for this request:
the reasoning-budget sampler masks the whole vocabulary outside the chain
```

模板的 lazy tool grammar 会让 `common_sampler_init` 额外建一个 **reasoning-budget sampler**
(`common/reasoning-budget.cpp`),而 `verify_rows_check()` 仍拒它。

### 先查清状态语义,再动手

`common_reasoning_budget_apply()` 是**纯掩码、零状态推进**:仅当 `state == FORCING` 且
`force_pos < |forced_tokens|` 时,把 `cur_p` 里除 `forced_tokens[force_pos]` 外全部置 -INFINITY;
其它状态 passthrough。**状态只在 `accept()` 里推进**(IDLE → COUNTING → DONE/FORCING,计数、
`force_pos`、两个 matcher 都在那儿动)。

所以「先问再决定」这个模式成立。但**没有直接调 `apply`**——而是加了
`common_reasoning_budget_rejects()` 纯读谓词(复制 `apply` 的两个守卫,只读
`(state, force_pos, forced[force_pos])`)。理由:`apply` 今天无副作用,但状态机在 `accept`,
显式谓词不会漂。

### 一个反直觉的语义

**预算耗尽不是放开而是收紧**:整词表只剩 `forced_tokens[force_pos]`,forced 序列走完才 DONE。
所以 FORCING 期间,tail 回的**未掩码 argmax 基本每轮都被拒** → 整帧回退 → plain decode 再采。
功能正确,但有约 2 倍的重复计算——这是带 grammar/rbudget 的投机收益打折的直接原因之一。

### 顺序必须与 row 路径一致

row 路径是「先 rbudget 后 grammar」,verified 分支必须同序。而且 lazy grammar 在 rbudget
非 IDLE/DONE 时本来就不 apply(`grammar_should_apply`),所以 FORCING 期间 `grammar_rejects`
自然返回 false——两边自动一致,不用特判。

### 验证:7 次回退后 `[capped]` 恰好 1 次

用 `reasoning_budget_tokens=6` + `reasoning_budget_message="\n\n[capped]\n"`、forced 7 个 token:

```
budget exhausted, forcing end sequence
7 × "row rejected by the grammar or the reasoning budget; rolled back 3 row(s)"(pos 379..385)
forced sequence complete, done
```

输出里 **`[capped]` 恰好出现 1 次**——预算没被「退回来」(否则 message 重复),也没被「多扣」
(否则提前强制、位置与长度都变)。而 `msg mtp(7 次回退)== msg none(无回退)== msg whole`
逐字节相同,证明 `state / remaining / force_pos` 与「那一行从未生成」完全一致。

`common_sampler_candidates_check` 对 rbudget 的拦截**必须保留**:候选通道不 apply rbudget,
而 top-k 截断可能不含那个唯一的 forced token。

### 真实 tools 请求现在真的在投机

```
reasoning budget: tokens=-1, start=1 toks, end=3 seqs, forced=2 toks
[split] this request verifies its drafts through the per-row channel ...
draft acceptance = 0.37500 (27 accepted / 72 generated), mean len = 1.75
tail: first OP_DECODE verify frame: 3 rows -> 3 int32 (12 B)
```

(`reasoning budget: ...` 那行证明 rbudget 真的存在,不是靠「没有 grammar 的请求」蒙混过去的。)

`verify.sh` 25 项、`verify_chain_death.py` 36 项、`verify_seq_id.py` 7 项、`verify_mtp.sh` 6 项、
`verify_mtp_e2e.sh` 6 项、`verify_grammar_spec.sh` 22 项、新增 `verify_rbudget_spec.sh` 36 项
——全过。

================================================================
二十一、seq_rm 失败不再静默,以及它引出的两个坑
================================================================

上线前的一次投机评测发现「同一个位置,回退前后算出的 h 不同」。追下去不是投机的问题,
而是 `seq_rm` 失败被静默忽略了。

### 根因:hybrid 的 seq_rm 会短路

`llama_memory_hybrid::seq_rm` 先删 recurrent,失败就 `return false`——**attention KV 的删除
被整体跳过**。而 hybrid 在 server 默认配置下 `n_rs_seq = 0`,partial 分支要求
`rollback <= n_rs_seq` 直接不成立,于是「删尾部」永远失败。

更糟的是 `common_context_seq_rm` 在 split 链上**只 flush 日志就返回**——调用方(回退、prompt-cache
复用、checkpoint 恢复)都不知道删除失败了,继续在「prompt 已回退、KV 没回退」的状态上跑。

(上游同样如此:`src/llama-memory-hybrid.cpp` 在 193 个提交里零改动,`seq_rm` 与我们逐字节相同。
上游已有 open PR ggml-org#28007 和 issue ggml-org#31656 描述同一件事,所以这里不提新 issue。)

### 改法

`common_memory::seq_rm` / `common_context_seq_rm`:`void` → `bool`。五个调用点按场景退化:

| 场景 | 失败后 |
|---|---|
| prompt 预处理(`p0`) | `prompt_clear` + **用 task 的 tokens 重建 `prompt.tokens`** + `return`,下一轮从 pos 0 全量重算 |
| context shift | `stop = STOP_TYPE_LIMIT`,跳过 `seq_add` 与 prompt 重写(滑动是全有或全无) |
| cache shift / 验证帧回退 | `send_error` + `prompt_clear` + `release` |
| spec trim(两处) | 先把手上这批 token 发完,再结束响应 + 全清(保住已生成内容) |

关键细节:**只 `prompt_clear()` 是不够的**。我们的 prompt 处理循环不会从空 prompt 重建内容
(那发生在 `launch_slot_with_task`),所以清空后 fall-through 会「从零生成」——比 500 更糟。
必须把 task 的 tokens 装回去,才是真的「全 prompt 重算」。

### 坑一:链死时不能结束请求

第一版把「链死」也走「失败 → `send_error` + `release`」,结果**自愈永久失效**:

```
[FAIL] 只重启 stage,/completion -> 500
[FAIL] 自愈后 prompt_n = None(应 5)
```

原因:`llama_memory_split::try_rebuild` 只在**一次从 pos 0 开始的 decode** 里触发,而「结束请求」
会跳过那次 decode。**一次也不 rebuild,链就永远死。**

最终形态:**链死时只记 ERROR、不结束请求**,让正常路径失败并释放 slot,下一个请求从 pos 0
触发重建。自愈于是保住。

这条值得记:一个「看起来更严谨」的失败处理(失败就结束)反而堵死了系统里唯一的自愈入口。

### 坑二:`p0 > pos_max` 是成功,不是失败

做故障注入时最初让所有 partial `seq_rm` 都返回 false,包括 `p0 > pos_max` 的空删除——结果
降级调用方在同一位置无限重试,5 次循环后超时。

查实现:`llama_kv_cache::seq_rm` 在 `pos_in` 不匹配时跳过,末尾**无条件 `return true`**;
`llama_memory_recurrent::seq_rm` 同样。所以空删除是成功。注入已改为只在 `p0 <= pos_max` 时拒绝。

### 已知未覆盖

- `p0` 那条退化分支(`server-context.cpp`)标为 **code-review-verified, not run**:它与
  spec trim 那条结构相同(后者已端到端跑过),但没有测试能构造出「cache 复用形态下真的走
  一次 `p0 <= pos_max && p0 > 0` 的 partial `seq_rm`」。
- shared-prefix 隔离:`copy_prompt_to` / `copy_state_to` / `wait_shared` 这条路径**不调用**
  partial `seq_rm`,所以「`prompt_clear` 误伤另一个 slot」不可达。脚本
  `verify_seq_rm_shared.py` 留下 `[INFO] injection never fired` 记录这一点——**看到这行就说明
  这次跑没测到东西,别当绿灯**。

### 新增验收

- `verify_seq_rm_exact.py --expect-known-fail`:纯 llama API、无 split、无 server。断言「删掉 p
  之后的 KV 后重放第 p 行,logits 必须逐位相同」。当前 **A(FULL 形态)两条红、B(RS 形态)
  三条绿、C 一条绿**,退出 0。修好上游 FULL 缺陷后它会变成「0 红」并提示关掉该开关。
- `verify_seq_rm_shared.py`:shared-prefix 形态,注入不触发时显式标 INFO。

七组全绿:`verify.sh` 24 / `chain_death` 36 / `seq_id` 7 / `mtp` 6 / `mtp_e2e` 6 /
`grammar_spec` 22 / `rbudget_spec` 36。

================================================================
二十二、DSpark 也需要 head 作为 tap 目标
================================================================

`server-context.cpp` 里选「speculative 的 target context」时只匹配了 `DRAFT_DFLASH`:

```cpp
const bool spec_dflash = ... == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH;
llama_context * ctx_spec_tgt = (ctx_tail != nullptr && !spec_dflash) ? ctx_tail : ctx_tgt;
```

DSpark 与 DFlash 由同一份实现驱动(`common/speculative.cpp` 用 `markov_w1` 区分两者),读的也是
同一组 `layer_inp` tap。漏掉 DSpark 就把 `ctx_spec_tgt` 指向了 tail(8 层),于是
`target_layers = [2,10,20,30,37]` 里的 20 被当成 tail local 12,impl 构造时 abort:

```
common/speculative.cpp:1074: DFlash: target layer 20 maps to tail layer 12, but the tail has 8
```

修法是把判断改成「是否需要 layer_inp tap」,并且**变量名改成描述语义而不是类型**:

```cpp
const bool spec_needs_layer_inp = is_dflash || is_dspark;
```

注释里写清「这个名字说的是这个选择对什么有意义,不是哪个类型设的它」——否则下一个人看到
变量叫 `spec_needs_layer_inp` 却只维护 DFLASH 会困惑。

================================================================
二十三、链上投机:DFlash / DSpark 的损失是 0,MTP 是 −24%
================================================================

这一段是选型的决定性数据。同一个 prompt 集(英 prose / Python 代码 / 中文,T=0,n=64),
同一台机器,同一个二进制:

| draft | 整模 accept / mean len | 链上 accept / mean len | 链上损失 |
|---|---|---|---|
| **MTP k=2** | 0.9098 / 2.81 | 0.6879 / 2.37 | **−24.4%** |
| **DFlash k=2** | 0.8298 / 2.65 | 0.8298 / 2.65 | **0** |
| **DSpark k=2** | 0.7986 / 2.61 | 0.7986 / 2.61 | **0** |

**不是「损失小」,是逐位相同。** 链 vs 整模的输出逐字节比较:6 个配置 × 3 个 prompt =
18/18 完全一致(含 `reasoning_content`)。

### 为什么 MTP 掉、DFlash/DSpark 不掉

- **MTP**:`speculative.cpp:1796` 的 catch-up decode 被 `!is_chain` 跳过,`draft()` 每轮
  `llama_memory_clear`(L1977-1987),所以链上的 MTP draft **看不到 prompt 上下文**。
- **DFlash / DSpark**:prompt 上下文由 `process()` 走 `layer_inp` tap 注入 draft 的 KV
  (`speculative.cpp:1285-1302`),链上照常执行;跨段 tap 从 `ctx_tail` **直接内存读**
  (`tap_ctx` / `tap_lid`,L1056-1078),不走网络;`draft()` 不清 KV。

### 一个独立的交叉验证

DSpark k=4 的 accept 是 **0.6291**,而 RedHatAI 公布的官方基线是 **0.6281**。两条完全不同的
实现路径(vLLM Speculators vs 我们的 llama.cpp 分段链)得出同一个数——这不仅证明「链 == 整模」,
还证明**我们这条通道相对官方参考实现没有引入偏差**。

### 选型结论

| | 最优选择 | 依据 |
|---|---|---|
| **整模** | MTP k=2(0.910 / 10.54 tok/s) | draft 看得到 prompt,MTP 更省(1 层) |
| **链上** | DSpark k=2 或 DFlash k=4(~9.3–9.8 tok/s) | 损失 0,且都优于链上 MTP 的 8.76 |

所以「**链上换 DFlash/DSpark,整模留 MTP**」是当前最优分工。

### DFlash 的 k 上不去

`requested draft size (n_max=16, n_min=0) exceeds the trained block size 16 -- clamping to 15`
——DFlash 最多 15 draft + 1 target = 16 行,`MAX_VERIFY_ROWS = 17` 没被卡到(差一行)。这是
DFlash 的 `[id_last, mask*(n)]` 布局决定的:`n_max = block_size − 1`。要卡满 17 需要 anchor-first
语义(DSpark 那种 `sample_from_anchor`)。

而 DFlash 在 k=15 时接受率只有 **0.2890**(mean len 5.30),所以「整块全中」几乎不会发生——
这直接否掉了 v2 那个「DFlash 块 + cascade MTP」的级联方案在本模型上的价值(级联只在全中时
触发)。v2 当年拿到的收益,主要来自 DFlash 本身而不是级联。

================================================================
二十四、远程链的 layer_inp:让 DFlash / DSpark 跨机器也能工作
================================================================

实测把这件事的必要性钉死了。同一 prompt 集、同机、同二进制:

| draft | 整模 accept / mean | 链上 accept / mean | 链上损失 |
|---|---|---|---|
| MTP k=2 | 0.9098 / 2.81 | 0.6879 / 2.37 | **−24.4%** |
| DFlash k=2 | 0.8298 / 2.65 | 0.8298 / 2.65 | **0** |
| DSpark k=2 | 0.7986 / 2.61 | 0.7986 / 2.61 | **0** |

本地链上 DFlash / DSpark 的损失是**零**(逐位相同,18/18 prompt 逐字节)。根因:MTP 走 nextn
通道,`speculative.cpp` 的 catch-up decode 被 `!is_chain` 跳过 + `draft()` 每轮清 KV;而
DFlash/DSpark 走 `layer_inp` tap,`process()` 在链上照常注入。**但远程链没有 tap 通道**,
所以远程链此前只能用最差的那个选项。

### 传输量:大头是 prefill,不是 draft

`draft()` 一个 tap 都不用。tap 只被 `process()` 用,注入的是**那一帧的每一个位置**(draft 必须
能 attend 到整条 prompt)。所以代价按 `n_ubatch × n_tail_taps × n_embd × 4` 算:

| 帧 | DFlash(2 路远程 tap) | DSpark(1 路) |
|---|---|---|
| 1 行 decode | 16 KB | 8 KB |
| k=2 verify(3 行) | 48 KB | 24 KB |
| k=8 verify(9 行) | 144 KB | 72 KB |
| **prefill 一个 ubatch(512 行)** | **8 MB** | **4 MB** |

对照一行 logits 是 993 KB。账仍是正的(256 token 生成省 254 MB,远大于 prefill 的 16 MB),
但**对「短生成 + 长 prompt」不利**,而且这一段是纯新增开销(本地链是 0)。

### 协议:v9,复用 decode 回复而不是新开 op

- `PROTO_VER = 9`;`DECODE_FLAG_LAYER_INP = 0x08`、`RSP_FLAG_LAYER_INP = 0x08`
- 请求体在所有现有段之后追加 `layer_inp_req{ n_taps, n_embd }` + n_taps 个 **int32 源模型层号**
- 回复体**最后**追加 n_taps 个 id + n_rows × n_taps × n_embd 个 f32
- `rsp_header` 把原 `_pad` 的一个字节改成 `n_taps`(尺寸仍是 32),所以前四段
  (ids / h_nextn / cands / logits)的解析与 v8 逐字相同
- `MAX_LAYER_INP_TAPS = 16`

**为什么复用而不是新开 op**:tap 是「这一帧的 tail 隐藏行的附带品」,语义上必须和产生它的那一帧
绑定;独立 op 要么逼 tail 缓存上一帧(多一份状态 + 一条错误路径),要么多一个 round trip。

**为什么用源层号而不是 stage 本地层号**:stage 自己用 `layer_lo` 减即可,于是**同一个请求可以发给
链上每个远程段**,head 不需要知道链在哪切——三段链(relay 拥有一部分 tap)自然成立。

**为什么必须升版本号**:`n_taps` 只挪了 padding,v8/v9 的帧长完全一样,唯一的防线就是
`PROTO_VER` 的前置检查。`verify_seq_id.py` 新增了「构造一个 v8 HELLO 必须被 ST_BAD_REQ 拒,且
stage 日志要说 version mismatch 而不是 bad request」。

### tap 缺失的退化:停掉本请求的投机,不结束请求

draft 的 KV 是**按绝…

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

3 participants