ExecuTorch端侧推理教程 · 07-LLM端侧推理链路
07 - LLM 端侧推理链路:Runner 主循环、KV cache 与采样
所属系列:ExecuTorch 端侧推理教程 | 前置:06-后端委派体系 | 下一篇:08-批处理调度与服务化
证据基线:commit8c3f75df(version.txt = 1.6.0)。本章所有文件:行号均在本 checkout 实测。
本篇知识图谱
1 | %%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%% |
本篇目标
- 走通 IRunner 五动词(load/generate/prefill/stop/reset)与
generate()主循环四段:tokenize → KV 容量检查 → 分块 prefill → decode while 循环。 - 掌握逐 token 合同:
decode(prev,cur)增量拼 UTF-8、LLMSession 的 POISONED 错误契约与协作式 stop。 - 分清 KV cache 双路线:经典 CPU 路径 KV 在
.pte内自管理(IOManager 直通),新实验路径经kvcache::update_and_attend访问进程级 registry。 - 确认采样全在 host CPU:argmax/top-k/top-p/全体采样共用 xorshift coin,LogitProcessor 就地改 logits。
1. IRunner 五动词(extension/llm/runner/irunner.h:116-177)
IRunner(标注 ET_EXPERIMENTAL,:116)是 LLM runner 的基类接口,五动词全部实测:
| 动词 | 行号 | 语义 |
|---|---|---|
load() |
:132 | 加载模型准备推理;is_loaded()(:125)查态 |
generate(prompt, config, token_callback, stats_callback) |
:143-147 | 一站式:tokenize→prefill→循环 decode,逐 token 回调字符串 |
prefill(MultimodalInput..., num_bos, num_eos) |
:158-163 | 多模态输入灌 KV cache 不出文本;基类默认 NotSupported(:162)——多模态扩展点 |
stop() |
:168 | 停止生成 |
reset() |
:176 | 注释原文 “Force remove prefilled tokens and reset KV cache start position”(:171-174) |
2. generate() 主循环四段(text_llm_runner.cpp:74-282)
TextLLMRunner::generate(Observed in source)四段推进:
① 惰性加载与回调包装(:79-104):未加载先 load() 并计时(:79-83);config.warming 标记 warmup 跑(:85-87);token_callback 包一层 safe_printf + fflush(:95-104)。
② tokenize 与 KV 容量检查(:121-171):tokenizer_->encode(prompt, bos, eos)(:122-123)。容量检查是两分支(:152-171):max_seq_len >= max_context_len 时查 pos_ + num_prompt_tokens < max_context_len(:153-161);否则(滑动窗/分块 prefill 模型)只查 num_prompt_tokens < max_context_len(:163-171)。前有一段关键注释(:142-147):故意不按 max_seq_len 卡 prompt——“TextPrefiller::prefill() supports chunked prefill: when num_prompt_tokens > max_seq_len it splits the prompt into max_seq_len chunks”,例如 1024 的 prefill 块配 4096 的 KV cache。
③ 分块 prefill(:174-184):text_prefiller_->prefill(prompt_tokens, pos_)(:181)返回 prompt 后的第一个预测 token cur_token。空 prompt 分支则消费先前 prefill() 调用暂存的 prefill_next_token_(:186-192)——这就是多模态先 prefill() 图像、再 generate("") 续文本的玩法(Derived)。
④ decode 委托与收尾(:195-282):滑动窗模型的 effective_pos 归零取满预算(:195-199,ring buffer 复位);首 token 用 decode(cur_token, cur_token) 打出(:219,注释 “No prev_token so use cur_token” :218);主循环交给 text_token_generator_->generate(prompt_tokens, pos_, max_new_tokens - 1, ...)(:244-245,注释 :243 “Generate max_new_tokens - 1 because prefill already generated 1 token”);pos_ += num_generated_tokens(:252);stats 回调(:277-279)。
3. decode while 循环与逐 token 合同(text_token_generator.h:134-184)
TextTokenGenerator 的循环(Observed in source)每步六拍:
1 | while (pos < start_pos + max_new_tokens) { // :134 |
关键合同:tokenizer_->decode(prev_token, cur_token)(:164)——只给上一个 token 和当前 token,tokenizer 内部维护 BPE 合并状态做增量解码;输出是字符串片段直接回调。首 token 特判用 (cur, cur)(text_llm_runner.cpp:219)。
KV 与非 KV 的输入管理分岔(:152-161):use_kv_cache_ 时 token tensor 固定形状、只写 token_data[0] = cur_token(:155)——每步喂一个新 token、位置靠 pos 推进;无 KV 时 push_back + resize(:158-160)——整个序列重喂。
4. LLMSession 合同与 POISONED(llm_session.h)
更底层的逐 token 合同是 LLMSession(extension/llm/runner/llm_session.h:67-112,文件头注释 :9-11:“LLMEngine owns loaded model resources; LLMSession owns one logical generation state. Higher-level generation APIs can wrap this lower-level token-step contract”):
prefill_tokens(tokens, initial_sampling)/decode_one(sampling)(:84-96):decode_one原文 “runs one forward pass and is not interruptible mid-call”(:88-90)——一步一 token,循环即完整生成;- DecodeResult(:48-53):
token_id + text_piece + is_eos + is_terminal。text_piece是 “raw bytes; may be a partial UTF-8 sequence the caller assembles”(:37 注释)——回调方负责拼 UTF-8;is_eos是事实陈述、is_terminal是循环信号(:39-43,“every EOS step is also terminal, but a stop step is terminal without being EOS”); - POISONED 错误契约(:79-83 注释原文):prefill/decode 报错时可能后端状态已经变了——“the session is POISONED – position() may no longer agree with resident state. The caller must call reset() … it must NOT retry the failed call”。即:错误后唯一合法动作是 reset(:102),重试原调用是未定义行为;
- 协作式
stop()(:104-111):TOKEN-BOUNDARY 粒度——可跨线程调用但不打断进行中的 decode_one;生效时返回合成终止步(is_terminal=true、is_eos=false、token_id=0、text_piece 空、position 不前进)。这就是 TextTokenGenerator 里should_stop_原子标志的语义源头(:174)。
5. KV cache 双路线:图内自管理 vs 图外 registry
经典 CPU 路径(图内):prefill/decode 双方法的 .pte 里,KV cache 就是 Method 的 planned 张量(第 04 章),随图自管理;host 侧只递 token 与 pos。IOManager(extension/llm/runner/io_manager/io_manager.h:26)的基类方法自带直通默认实现——load() 默认体就是 (void)prefill_method; (void)decode_method; return runtime::Error::Ok;(:47-52)——CPU 路径不装 IOManager 子类,I/O 语义全在图内。TextLLMRunner 构造持 std::unique_ptr<IOManager>(text_llm_runner.h:65/:182),load 时调 io_manager_->load()(text_llm_runner.cpp:61)。
新实验路径(图外):kvcache::update_and_attend custom op(extension/llm/cache/update_and_attend.py:64,Observed in source)。docstring 一句话定性(:9-13):“the KV cache is not a graph tensor but off-graph runtime state, reached through a process-global registry”。机制:
CacheRegistry(:25-58):按 cache_key 装/卸 cache,active(key)上下文选激活项(:40-50),current()取当前(:52-58);进程级单例REGISTRY(:61);- op 签名(:65-73):q/k/v/position/layer_id/scale/out_dtype;对 tracer 声明
mutates_args=()(:9)——KV 写入对导出图不可见,图里它是个纯函数; update_and_fetch(layer_id, k, v, position)(:98)append 本步 k/v 并取回 attention 规格,BHSD 布局、GQA/MQA 原生、v_head_dim可异于 head_dim(MLA,:85-87)。
两条路线对应两代导出形态:经典 llama 导出(02 章旧 CLI 主路径)KV 图内自管理;新 registry 路线为服务化/多会话铺路(08 章缓存键经 BackendOptions 绑定)。
6. 采样与输出:全在 host CPU
LogitProcessor 就地改 logits(Observed in source):apply_logit_processors(text_token_generator.h:59-65)循环 processor->process(logits),直接改张量——processors 定义在 extension/llm/sampler/logit_processor.h(目录 ls 实测:logit_processor.h + sampler.h/.cpp)。
Sampler(extension/llm/sampler/sampler.cpp:224-252,Observed in source)一棵四叉决策树:
1 | if (inv_temperature_ == 0.0f) next = sample_argmax(logits); // :227-229 greedy |
熵源 random_u32 是 xorshift*(:211-217,注释直接贴了 Wikipedia 链接),random_f32 = (u32 >> 8) / 2^24(:219-221)——一个 64 位状态自给自足,无系统调用,seed 可复现。BFloat16 logits 先拷进 float 缓冲再走同一模板(:254-263)。采样全在 host CPU 执行(这些函数都不在 .pte 图内,Derived 由调用位置为证:decode 循环 :146 的 logits_to_token 在 runner 侧)。
本篇小结
- IRunner 五动词(irunner.h:116-177):load/generate/prefill(多模态默认 NotSupported)/stop/reset;
generate()四段(text_llm_runner.cpp:74-282):惰性 load → tokenize + KV 容量两分支检查(:152-171,滑动窗不按 max_seq_len 卡)→ 分块 prefill 出首 token(:181)→ decode 委托(:244)。 - decode 循环六拍(text_token_generator.h:134-184):step → LogitProcessor 就地改 → logits_to_token →
decode(prev,cur)增量拼 UTF-8 回调 → should_stop → EOS;KV 模式只写 token_data[0](:155)。 - LLMSession 逐 token 合同(llm_session.h):DecodeResult 的 text_piece 是可能不完整的 UTF-8 字节;错误即 POISONED(:79-83),唯一合法动作 reset;stop 是 token 边界协作停(:104-111)。
- KV 双路线:经典路径 KV 图内自管理 + IOManager 直通默认体(io_manager.h:47-52);新路径
kvcache::update_and_attend图外 registry(update_and_attend.py:9-13、:25-64),对 tracer 声明mutates_args=()。 - 采样四叉树共用 xorshift coin(sampler.cpp:211-252):argmax / temperature+softmax / top-k / top-p,全在 host CPU。
前置:06-后端委派体系 | 下一篇:08-批处理调度与服务化 | 回目录