LLM 入口、主循环(ALL/ANY 集体 prefill + 异步调度)、装批执行与缓存生命周期、跨机通信——从入口到执行的心脏 · 本组 20 个文件 · 5,441 行 · ast 提取 @ 774ce24 · 2026-10-21
模块综述——引擎层 6 文件 1,963 行:llm_engine.py(1,030 行)是主循环本体——LLMEngine 串起调度、异步 overlap(schedule(N+1) 与 forward(N) 并行)、MTP 变长验证与 prefill ALL/ANY 两档集体触发,DeferredRelease 管张量延迟释放,_spawn_worker 拉起执行进程;stats_logger.py(478 行)StepStats/Aggregates/Window 做滑窗吞吐统计(155 万亿 token/天 生产口径的观测底座);profile_server.py(321 行)每引擎进程一个 HTTP 口,POST /profile 采 num_steps 步 trace——Profiling 不出进程;arg_utils 装配 EngineArgs,engine_type 区分离线/服务形态。
| 符号 | 行数 · 说明(ast 提取) | |
| class EngineArgs | 97 | Arguments for DeepInfer engine. |
| └ __post_init__ | 13 | |
| └ create_engine_configs | 53 | |
| (已列出全部 1 个顶层符号 + 2 个方法) | ||
| 符号 | 行数 · 说明(ast 提取) | |
| class EngineType | 14 | LLMEngine type 请和 csrc/engine/scheduler.hpp 中的 enum class EngineType 保持一致 |
| └ default_zero_overhead_scheduling | 2 | |
| (已列出全部 1 个顶层符号 + 1 个方法) | ||
| 符号 | 行数 · 说明(ast 提取) | |
| class DeferredRelease | 53 | 延后一轮释放 step 产出的资源,保证调用方读完。 回收(collect)要释放的资源;在下一次的 pre_sampler_sync 时释放(release),与 GPU 计算 overla |
| └ __init__ | 15 | |
| └ collect_sequence_metadata | 2 | |
| └ collect_request_outputs | 2 | |
| └ collect_clone_unpins | 4 | |
| └ release | 20 | 在 pre_sampler_sync 调用,释放资源 |
| _spawn_worker | 6 | |
| class LLMEngine | 900 | An LLM engine that receives requests and generates texts. This is the main class for the DeepInf |
| └ __init__ | 151 | |
| └ _create_scheduler | 21 | |
| └ so_matcher_builder | 13 | |
| └ so_builder_has_pending | 2 | |
| └ __del__ | 2 | |
| └ close | 17 | |
| └ _init_workers | 47 | |
| └ _init_cache | 43 | Profiles the memory usage and initializes the KV cache. The engine wil |
| └ from_engine_args | 9 | Creates an LLM engine from the engine arguments. |
| └ add_request | 160 | Add a request to the engine's request pool. The request is added to th |
| └ abort_request | 24 | Aborts a request(s) with the given ID. Args: request_id: The ID(s) of |
| └ get_num_unfinished_requests | 6 | Gets the number of unfinished requests. |
| └ has_unfinished_requests | 15 | Returns True if there are unfinished requests. |
| └ get_nextn_pad_token_ids | 4 | |
| └ _process_model_outputs | 99 | |
| └ do_copy_state | 12 | 把给定 seq 当前的 GPU state 拷贝到 copy_state buffer,并更新 last_copy_state_token_ |
| └ init_pd_split | 2 | 虚函数,初始化 PD 分离需要的数据结构 |
| └ finalize_seq | 3 | 虚函数,处理结束的请求 |
| └ post_schedule | 2 | 虚函数,处理每个 step scheduler 的结果 |
| └ should_copy_state | 3 | 虚函数,判断是否要保存 seq 当前状态 |
| └ do_save_kvcache | 2 | 虚函数,保存 kvcache, pre_sampler_sync 时调用 |
| └ pe_prepare_save_kvcache | 2 | 虚函数,pe 准备保存 kvcache |
| └ pe_do_save_kvcache | 2 | 虚函数,pe 保存 kvcache |
| └ process_output | 5 | 虚函数,处理输出一个 step 输出的 token - ZOS=False: 处理当前 step - ZOS=True: 处理上一个 ste |
| └ pre_sampler_sync | 17 | |
| └ send_processed_prompts | 2 | 虚函数,把已经处理完的 prompt sequence 发送给 completion engine 并从 scheduler 中删除 |
| └ get_num_pendings | 3 | |
| └ post_process_model_outputs | 2 | 虚函数,在处理完模型输出、打印 log 之前调用 |
| └ step | 100 | Run one inference step and return the generated outputs. Returns: np.n |
| └ _execute_model_async_step | 15 | |
| └ flush_inflight_reqs | 6 | flush 并 post process ZOS 中所有在途请求 |
| └ post_process | 32 | |
| └ _run_workers | 9 | |
| └ build_extra_metrics_log | 3 | Overridden in subclass to return an extra metrics log line. |
| (已列出全部 3 个顶层符号 + 39 个方法) | ||
| 符号 | 行数 · 说明(ast 提取) | |
| class _Reply | 11 | 2 个方法 |
| └ ok | 2 | |
| └ error | 2 | |
| class _PendingTrace | 19 | 采集已结束、profiler 已 stop,就差落盘。 落盘丢给线程池,engine 线程不必陪着等。stop() 挪不走:kineto 的 enable/disable 绑定线程, 跨线程 |
| └ export | 8 | |
| class _ProfileRequest | 10 | HTTP 侧投递给 engine 线程的一次采集请求。 reply 兼做取消协议:客户端超时 cancel() 与 engine 侧 set_running_or_notify_cancel( |
| _fmt_error | 6 | 把 pydantic 的多条报错压成一行;普通 ValueError 原样返回 |
| class ProfileManager | 214 | engine 侧的 profiling 状态机。 engine 线程只跑 step/_handle_request/_start/_finish/_stop,HTTP 侧只通过 _pendin |
| └ __init__ | 19 | |
| └ start_http_server | 24 | 绑端口并在 daemon 线程上跑 uvicorn。失败只记日志,不影响 engine |
| └ _build_app | 69 | |
| └ _wait | 22 | 等 engine 回结果。超时后能取消就取消;取消不掉说明已在采集,再等一段宽限期 |
| └ step | 15 | 取出待处理请求并推进 num_steps 倒计时,在 LLMEngine.step 开头调用 |
| └ _handle_request | 13 | |
| └ _start | 10 | 起 profiler。不在这里回结果,等 _finish 采满后再回 |
| └ _finish | 13 | 采满了:停掉 profiler,把落盘的活交给还在等的 HTTP 侧。 在 engine 循环里调用,异常一律吞掉转成 500,否则会把 e |
| └ _stop | 10 | |
| (已列出全部 5 个顶层符号 + 12 个方法) | ||
| 符号 | 行数 · 说明(ast 提取) | |
| class StepStats | 17 | Per-step statistics fed into :py:meth:`StatsLogger.log_step`. |
| class Aggregates | 37 | Computed per-window / per-step values used for logging and reporting. |
| class Window | 22 | Sliding window of ``(timestamp, payload, step)`` tuples. |
| └ __init__ | 2 | |
| └ __len__ | 2 | |
| └ __bool__ | 2 | |
| └ append | 2 | |
| └ trim | 2 | |
| └ sum | 2 | |
| _log_worker | 11 | |
| class StatsLogger | 349 | Owns all sliding-window data, timing accumulators and logging state. The ``engine`` back-referen |
| └ __init__ | 43 | |
| └ _throughput | 7 | (tokens/s, total_tokens) over a window, ignoring the first sample. |
| └ _mfu | 7 | |
| └ _nextn_stats | 26 | Fill nextn accept rates / verified-len / confidence error in *agg*. |
| └ _moe_lb_ratio | 4 | |
| └ _finished_payload_stats | 10 | (avg_prompt_len, avg_completion_len, payload_len);payload 元组为 (num_fin |
| └ _merge_cuda_timers | 12 | 把所有 cuda timer 合并为 (times, called, max_time, latest_times) |
| └ _build_log_messages | 69 | Build log lines. |
| └ _emit_logs | 3 | 投递日志到固定 worker 线程,主线程不触碰 logger 的 handler 锁 |
| └ close | 4 | 写完队列中已投递的日志后停掉 worker 线程;重复调用安全 |
| └ _record | 25 | Append per-step records and return batch utilization. |
| └ _should_log | 10 | Return (should_log, logging_interval). |
| └ _collect | 35 | Fill window + per-step aggregates into *a*; scheduler/TTFT/payload sta |
| └ log_nccl_memory | 4 | |
| └ log_step | 40 | Collect per-step stats; periodically log. NOTE 假设这里面的操作是无副作用的,即在 shoul |
| (已列出全部 5 个顶层符号 + 21 个方法) | ||
模块综述——执行层 10 文件 2,815 行:base.py(358 行)WorkerBase 管进程/分布式环境/NUMA 绑定(set_pdeathsig 保孤儿清理);cache_engine.py(979 行)是 KV 侧最重的一件——KVCache/StateBlock/KVCacheManager/CacheEngine 四层,_kv_bytes_per_token 与 _state_bytes 按 attn index 配置算字节(QA 里 20 层×134×528B=1,415,040B 的账就在这类函数里),get_yoco_store_extra_tokens 对应 YoCo 截断的额外存储;model_runner.py(645 行)装模型/捕图/执行 forward;worker.py(284 行)驱动每步 forward→post-process→sample;cuda_graph_runner(169 行)与 dflash_cuda_graph_runner(101 行)分常规与 DSpark 两条图捕获;decode_perf_cache(167 行)缓存 decode 性能预测(配 DECODE_PERF_CACHE_TTL);zos_status(41 行)是零开销调度的 worker 侧状态灯。
| 符号 | 行数 · 说明(ast 提取) | |
| set_pdeathsig | 5 | Ask the kernel to send `sig` to this process when its parent dies (libc prctl). |
| class WorkerBase | 264 | Resources and lifecycle of a GPU worker: torch/distributed init, model load, KV cache engine, an |
| └ __init__ | 66 | |
| └ gpu_id | 2 | |
| └ start_slave_worker_loop | 5 | |
| └ stop | 17 | |
| └ maybe_gc_collect | 5 | |
| └ clone_and_zero_states_and_blocks_on_default_stream | 9 | |
| └ set_random_seed_with_rank | 3 | |
| └ _init_torch | 7 | |
| └ init_model | 13 | |
| └ init_dist | 6 | |
| └ load_model | 7 | |
| └ profile_num_available_blocks | 57 | Profiles the peak memory usage of the model and returns the maximum nu |
| └ init_cache_engine | 3 | |
| └ warm_up_model | 15 | |
| └ run_workers | 13 | |
| └ init_engram | 9 | |
| _init_distributed_environment | 30 | Initialize the distributed environment. |
| _bind_numa | 11 | |
| (已列出全部 4 个顶层符号 + 16 个方法) | ||
| 符号 | 行数 · 说明(ast 提取) | |
| _align_to_multiple | 3 | 把 numerator 个元素按每 denominator 个一组分组后,组数向上对齐到 alignment 的倍数。denominator=1 时即普通向上对齐 |
| _state_bytes | 3 | 一段 fp32 state [num_state_token, 2, head_dim] 的 bytes |
| _kv_bytes_per_token | 11 | 每 token interleaved KV cache 的 data+scale 总字节数 |
| _get_from_attn_index_configs | 12 | 对每个有 attn_index 的 attn 层取 candidate_fn(attn_index),校验全部一致后返回(无 attn_index 层时返回 0)。 candidate_fn( |
| _get_qk_topk_bytes | 8 | 获取这一层 indexer 的 FP4 KV bytes 数(包含 UE8M0 scale) |
| _get_qk_topk_head_dim | 3 | 获取这一层 indexer 的 kv 的维度(不包含 sf),计算 state cache 时需要 |
| get_inference_swa_block_size | 6 | swa_block_size 等于 window_size 加上为回退功能额外存的部分。 如果 config 里 window_size < 0,说明这个模型没有 swa 层,直接返回 0 n |
| get_yoco_store_extra_tokens | 3 | YoCo 截断开启时,参与落盘重排的 state ring 额外多存的 token 数 |
| get_kvstore_swa_block_size | 10 | kvstore 视角的 swa_block_size:inference 大小 + prefill 落盘多存的部分。 因为 kvstore 落盘只在 128(落盘粒度)的整倍数落,prefil |
| _is_dropped_swa_layer | 4 | 按模型配置划分 YOCO consumer SWA,不依赖 PE/CE 的截断模式 |
| _needs_compress_state | 2 | |
| _needs_index_state | 5 | |
| get_inference_compress_block_size | 3 | Compression ring plus rollback history; environment changes require clearing the cache. |
| clear_compress_block_size_cache | 3 | Clear cached ring sizes after changing DEEPINFER_MAX_BACKTRACKING_TOKENS. |
| _get_shared_mapped_layer_id | 22 | 返回 layer_info_shared_cfg[map_key] 里 layer_id 映射到的(被复用的)layer_id。 share-kv / share-index / share- |
| _get_kv_mapped_layer_id | 7 | 返回本层实际使用哪一层的 kv cache。 share-kv 场景下 config 会给出 layer_info_shared_cfg.layer_kv_map(layer_id -> 被复 |
| _get_index_mapped_layer_id | 14 | 返回本层的 indexer(index attention)实际使用哪一层的 K cache。 优先使用 layer_index_k_map;未指定时 K 跟随 layer_index_mod |
| _iter_owning_compress_state_layers | 9 | 产出需要且拥有 main/index state 的压缩层 |
| get_num_state_slots | 2 | |
| class KVCache | 13 | 0 个方法 |
| class StateBlock | 86 | State cache 中一个 seq 的物理布局。 分区原则:需要落盘的 state 全部放在前面的 stored region,不需要落盘但运行时 仍需保留的 state 放在后面的 dr |
| └ __init__ | 64 | 根据模型配置计算 state block 的布局 |
| class KVCacheManager | 226 | 管理 KV cache 的分配和布局。 基于 StateBlock 抽象,为每一层分配 kv cache tensor 和 state tensor, 支持 compress_ratio in |
| └ __init__ | 50 | |
| └ _alloc_state | 8 | Allocate non-persisted fp32 compression state after the dropped SWA ri |
| └ process | 102 | 为一层 attention 分配 kv cache 和 state cache。 Returns: (KVCache, (layer_id, |
| └ finalize | 14 | 在所有层 process 完成后调用,对齐总 kv 大小 |
| └ update_gpu_cache_interface_class_fields | 41 | 更新 GPUCacheInterface 的类级字段。 这些字段被 _carve_state_views / select_state_sl |
| class GPUCacheInterface | 309 | 10 个方法 |
| └ _kvcache_layout | 72 | 计算 kv cache 和 state cache 的物理布局,并按层切出各自的 cache view。 应该由调用者保证被调用的次数尽量少 |
| └ __init__ | 27 | |
| └ _has_SWA | 5 | |
| └ _is_sparse | 4 | |
| └ _is_full | 4 | |
| └ __getitem__ | 2 | |
| └ is_valid_layeridx | 2 | |
| └ _carve_state_views | 53 | Carve SWA/stored-region cache and tensor views. Returns two parallel l |
| └ select_state_slice_to_store | 56 | 从 state cache 里读出 state id 上的值,只读取要落盘的那一部分。 例如如果只在 128 的倍数处落盘,则需要维护最近 |
| └ load_state_from_store_to_prefill_cache | 28 | 把一个 request 的 state 存到指定 state id 的 state cache 里 Args: state_id (int) |
| class CacheEngine | 128 | Manages the KV cache. This class is responsible for initializing and managing the GPU and CPU KV |
| └ __init__ | 26 | |
| └ get_block_shape | 4 | 应该由调用者保证被调用的次数尽量少,因为处理 config 的逻辑比较复杂,而且 AttrDict 没法被 functools.lru_ca |
| └ get_kvcache_layout | 4 | 应该由调用者保证被调用的次数尽量少,因为处理 config 的逻辑比较复杂,而且 AttrDict 没法被 functools.lru_ca |
| └ get_state_shape | 4 | |
| └ do_allocate_kv_cache | 2 | |
| └ _alloc_gpu_uint8 | 6 | 用 cuda_utils.alloc_tensor 分配 shape 大小的 uint8 GPU tensor |
| └ allocate_gpu_cache | 49 | |
| └ get_cache_block_size | 10 | 单个 block(叠加所有层)的总字节数。block_size 为每个 block 在压缩前所表示的 token 个数。 应该由调用者保证被 |
| (已列出全部 24 个顶层符号 + 24 个方法) | ||
| 符号 | 行数 · 说明(ast 提取) | |
| class CudaGraphData | 12 | Captured graph with preparation and execution buffers. Source tensors are on CPU, or share devic |
| build_graph_batch_sizes | 11 | Build power-of-two warmup sizes followed by fixed-width intervals. |
| _run_model | 13 | |
| class CudaGraphRunner | 100 | 5 个方法 |
| └ __init__ | 11 | |
| └ capture | 60 | |
| └ select | 6 | |
| └ replay | 5 | |
| └ destroy | 13 | |
| (已列出全部 4 个顶层符号 + 5 个方法) | ||
| 符号 | 行数 · 说明(ast 提取) | |
| _is_hex | 2 | |
| class DecodePerfCache | 141 | 7 个方法 |
| └ __init__ | 12 | |
| └ _get_hash_key | 13 | |
| └ _parse_filename | 16 | 文件名格式 <sha256>.<uuid4 hex>.<unix 秒>[.tmp],不符合则返回 None |
| └ _cleanup | 18 | |
| └ _read | 34 | |
| └ load_decode_perf_cache | 19 | |
| └ write_decode_perf_cache | 21 | |
| (已列出全部 2 个顶层符号 + 7 个方法) | ||
| 符号 | 行数 · 说明(ast 提取) | |
| class DFlashCudaGraphData | 4 | 0 个方法 |
| class DFlashCudaGraphRunner | 70 | 5 个方法 |
| └ __init__ | 9 | |
| └ capture | 34 | |
| └ select | 6 | |
| └ replay | 8 | |
| └ destroy | 8 | |
| (已列出全部 2 个顶层符号 + 5 个方法) | ||
| 符号 | 行数 · 说明(ast 提取) | |
| class MainModelOutput | 4 | 0 个方法 |
| class ModelRunner | 592 | 20 个方法 |
| └ __init__ | 40 | |
| └ load_model | 20 | |
| └ set_block_size | 2 | |
| └ _prepare_input_tensors | 27 | Build input metadata on CPU, or on device for ZOS decode. If out_dict |
| └ _prepare_input | 13 | Build the forward-pass input on the driver, or receive it on the other |
| └ _graph_input_metadata | 6 | |
| └ _prepare_input_driver | 44 | |
| └ _prepare_input_follower | 15 | |
| └ prepare_sampler_inputs | 45 | |
| └ execute_model_profile_run | 26 | Profile-run only: run one full step (forward + sample + post-process) |
| └ execute_main_model | 28 | Run the main model forward pass (prepare input, launch forward). IMPOR |
| └ execute_sample | 31 | Run sampling on the main model output (prepare sampler inputs, launch |
| └ post_process | 15 | |
| └ _placeholder_seq_metadata | 18 | |
| └ _build_prompt_profile_seq_lens | 37 | |
| └ profile_run | 69 | |
| └ capture_model | 15 | |
| └ capture_dflash_model | 28 | |
| └ profile_decode_perf | 70 | |
| └ destroy_cuda_graphs | 12 | Destroy CUDA graphs and release resources. NOTE: This is necessary to |
| (已列出全部 2 个顶层符号 + 20 个方法) | ||
| 符号 | 行数 · 说明(ast 提取) | |
| expose_all_gpus_to_cuda_driver | 14 | |
| configure_worker_environment | 23 | Configure process-wide environment variables used by workers. |
| configure_worker_kernels | 16 | Configure process-wide kernel library behavior used by workers. |
| (已列出全部 3 个顶层符号) | ||
| 符号 | 行数 · 说明(ast 提取) | |
| class _SeqlensCorrection | 7 | ZOS 下按上一步采样结果修正后的 seqlens 及其 CPU 输入 |
| class EngineCallbacks | 5 | Callbacks injected by the engine, invoked on the driver worker only. |
| class Worker | 233 | Executes model steps on a GPU. Every step runs the Forward-Post_process-Sample round in execute_ |
| └ __init__ | 30 | |
| └ execute_model_step | 101 | The unified entry for model execution: every step (prompt/decode, ZOS |
| └ _correct_seqlens_qk | 55 | CPU 侧的 seqlens_q/k 在 ZOS 下滞后一步:与上一步 batch 有交集时,需按上一步采样结果在 GPU 上修正 |
| └ _post_process_step | 25 | Synchronize on the sampling completion event, run post-processing on t |
| └ flush_inflight_reqs | 10 | Flush inflight requests running on GPU, useful for ZOS. It may cause C |
| (已列出全部 3 个顶层符号 + 5 个方法) | ||
| 符号 | 行数 · 说明(ast 提取) | |
| class WorkerStepState | 11 | 0 个方法 |
| class MetadataZOS | 17 | GPU metadata and the pinned CPU remap used to prepare it. |
| (已列出全部 2 个顶层符号) | ||
模块综述——分布式最小件:shm_broadcast.py(462 行)ShmRingBuffer/Handle/MessageQueue——引擎进程与 worker 间走共享内存环形队列而非 socket,配 DEEPINFER_GLOO_TIMEOUT=4h 的慢启动容忍;仓库刻意不自带集合通信库,NCCL/HCCL 由平台侧供给。
| 符号 | 行数 · 说明(ast 提取) | |
| class ShmRingBuffer | 117 | 6 个方法 |
| └ __init__ | 88 | A shared memory ring buffer implementation for broadcast communication |
| └ handle | 2 | |
| └ __reduce__ | 2 | |
| └ __del__ | 7 | |
| └ get_data | 5 | |
| └ get_metadata | 5 | |
| class Handle | 7 | 0 个方法 |
| class MessageQueue | 300 | 11 个方法 |
| └ __init__ | 77 | |
| └ export_handle | 2 | |
| └ create_from_handle | 40 | |
| └ wait_until_ready | 21 | This is a collective operation. All processes (including the readers a |
| └ _spin_wait | 10 | 自旋等待一轮:让出 CPU、按间隔打 debug 日志、超时抛 TimeoutError。返回更新后的 n_warning |
| └ acquire_write | 37 | |
| └ acquire_read | 28 | |
| └ enqueue | 16 | Write to message queue with optional timeout (in seconds) |
| └ dequeue | 17 | Read from message queue with optional timeout (in seconds) |
| └ broadcast_object | 6 | |
| └ create_from_process_group | 30 | |
| (已列出全部 3 个顶层符号 + 17 个方法) | ||
模块综述——对外入口 2 文件 200 行:llm.py 的 LLM 类即 examples/offline_inference.py 所用 API(generate/采样参数/结构化输出全在此面)——开源版只放离线入口,在线服务层(路由/多副本 LB)属未开源部分。
| 符号 | 行数 · 说明(ast 提取) | |
| class LLM | 176 | An LLM for generating texts from given prompts and sampling parameters. This class includes a to |
| └ __init__ | 32 | |
| └ get_tokenizer | 2 | |
| └ generate | 53 | Generates the completions for the input prompts. NOTE: This class auto |
| └ _add_request | 23 | |
| └ _run_engine | 28 | |
| └ close | 2 | |
| (已列出全部 1 个顶层符号 + 6 个方法) | ||