← 返回全景索引

1. engine(6 文件 · 1,963 行)

模块综述——引擎层 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 区分离线/服务形态。

deepinfer/engine/__init__.py查看源码1 行
deepinfer/engine/arg_utils.py查看源码115 行
符号行数 · 说明(ast 提取)
class EngineArgs97Arguments for DeepInfer engine.
└ __post_init__13
└ create_engine_configs53
(已列出全部 1 个顶层符号 + 2 个方法)
deepinfer/engine/engine_type.py查看源码18 行
符号行数 · 说明(ast 提取)
class EngineType14LLMEngine type 请和 csrc/engine/scheduler.hpp 中的 enum class EngineType 保持一致
└ default_zero_overhead_scheduling2
(已列出全部 1 个顶层符号 + 1 个方法)
deepinfer/engine/llm_engine.py查看源码1030 行
符号行数 · 说明(ast 提取)
class DeferredRelease53延后一轮释放 step 产出的资源,保证调用方读完。 回收(collect)要释放的资源;在下一次的 pre_sampler_sync 时释放(release),与 GPU 计算 overla
└ __init__15
└ collect_sequence_metadata2
└ collect_request_outputs2
└ collect_clone_unpins4
└ release20在 pre_sampler_sync 调用,释放资源
_spawn_worker6
class LLMEngine900An LLM engine that receives requests and generates texts. This is the main class for the DeepInf
└ __init__151
└ _create_scheduler21
└ so_matcher_builder13
└ so_builder_has_pending2
└ __del__2
└ close17
└ _init_workers47
└ _init_cache43Profiles the memory usage and initializes the KV cache. The engine wil
└ from_engine_args9Creates an LLM engine from the engine arguments.
└ add_request160Add a request to the engine's request pool. The request is added to th
└ abort_request24Aborts a request(s) with the given ID. Args: request_id: The ID(s) of
└ get_num_unfinished_requests6Gets the number of unfinished requests.
└ has_unfinished_requests15Returns True if there are unfinished requests.
└ get_nextn_pad_token_ids4
└ _process_model_outputs99
└ do_copy_state12把给定 seq 当前的 GPU state 拷贝到 copy_state buffer,并更新 last_copy_state_token_
└ init_pd_split2虚函数,初始化 PD 分离需要的数据结构
└ finalize_seq3虚函数,处理结束的请求
└ post_schedule2虚函数,处理每个 step scheduler 的结果
└ should_copy_state3虚函数,判断是否要保存 seq 当前状态
└ do_save_kvcache2虚函数,保存 kvcache, pre_sampler_sync 时调用
└ pe_prepare_save_kvcache2虚函数,pe 准备保存 kvcache
└ pe_do_save_kvcache2虚函数,pe 保存 kvcache
└ process_output5虚函数,处理输出一个 step 输出的 token - ZOS=False: 处理当前 step - ZOS=True: 处理上一个 ste
└ pre_sampler_sync17
└ send_processed_prompts2虚函数,把已经处理完的 prompt sequence 发送给 completion engine 并从 scheduler 中删除
└ get_num_pendings3
└ post_process_model_outputs2虚函数,在处理完模型输出、打印 log 之前调用
└ step100Run one inference step and return the generated outputs. Returns: np.n
└ _execute_model_async_step15
└ flush_inflight_reqs6flush 并 post process ZOS 中所有在途请求
└ post_process32
└ _run_workers9
└ build_extra_metrics_log3Overridden in subclass to return an extra metrics log line.
(已列出全部 3 个顶层符号 + 39 个方法)
deepinfer/engine/profile_server.py查看源码321 行
Engine 运行时 profiling 的 HTTP 接口,每个 engine 进程一个
符号行数 · 说明(ast 提取)
class _Reply112 个方法
└ ok2
└ error2
class _PendingTrace19采集已结束、profiler 已 stop,就差落盘。 落盘丢给线程池,engine 线程不必陪着等。stop() 挪不走:kineto 的 enable/disable 绑定线程, 跨线程
└ export8
class _ProfileRequest10HTTP 侧投递给 engine 线程的一次采集请求。 reply 兼做取消协议:客户端超时 cancel() 与 engine 侧 set_running_or_notify_cancel(
_fmt_error6把 pydantic 的多条报错压成一行;普通 ValueError 原样返回
class ProfileManager214engine 侧的 profiling 状态机。 engine 线程只跑 step/_handle_request/_start/_finish/_stop,HTTP 侧只通过 _pendin
└ __init__19
└ start_http_server24绑端口并在 daemon 线程上跑 uvicorn。失败只记日志,不影响 engine
└ _build_app69
└ _wait22等 engine 回结果。超时后能取消就取消;取消不掉说明已在采集,再等一段宽限期
└ step15取出待处理请求并推进 num_steps 倒计时,在 LLMEngine.step 开头调用
└ _handle_request13
└ _start10起 profiler。不在这里回结果,等 _finish 采满后再回
└ _finish13采满了:停掉 profiler,把落盘的活交给还在等的 HTTP 侧。 在 engine 循环里调用,异常一律吞掉转成 500,否则会把 e
└ _stop10
(已列出全部 5 个顶层符号 + 12 个方法)
deepinfer/engine/stats_logger.py查看源码478 行
Engine statistics collection, aggregation and logging.
符号行数 · 说明(ast 提取)
class StepStats17Per-step statistics fed into :py:meth:`StatsLogger.log_step`.
class Aggregates37Computed per-window / per-step values used for logging and reporting.
class Window22Sliding window of ``(timestamp, payload, step)`` tuples.
└ __init__2
└ __len__2
└ __bool__2
└ append2
└ trim2
└ sum2
_log_worker11
class StatsLogger349Owns all sliding-window data, timing accumulators and logging state. The ``engine`` back-referen
└ __init__43
└ _throughput7(tokens/s, total_tokens) over a window, ignoring the first sample.
└ _mfu7
└ _nextn_stats26Fill nextn accept rates / verified-len / confidence error in *agg*.
└ _moe_lb_ratio4
└ _finished_payload_stats10(avg_prompt_len, avg_completion_len, payload_len);payload 元组为 (num_fin
└ _merge_cuda_timers12把所有 cuda timer 合并为 (times, called, max_time, latest_times)
└ _build_log_messages69Build log lines.
└ _emit_logs3投递日志到固定 worker 线程,主线程不触碰 logger 的 handler 锁
└ close4写完队列中已投递的日志后停掉 worker 线程;重复调用安全
└ _record25Append per-step records and return batch utilization.
└ _should_log10Return (should_log, logging_interval).
└ _collect35Fill window + per-step aggregates into *a*; scheduler/TTFT/payload sta
└ log_nccl_memory4
└ log_step40Collect per-step stats; periodically log. NOTE 假设这里面的操作是无副作用的,即在 shoul
(已列出全部 5 个顶层符号 + 21 个方法)

2. worker(10 文件 · 2,815 行)

模块综述——执行层 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 侧状态灯。

deepinfer/worker/__init__.py查看源码1 行
deepinfer/worker/base.py查看源码358 行
GPU worker resource layer: process/distributed setup, model load, and KV cache.
符号行数 · 说明(ast 提取)
set_pdeathsig5Ask the kernel to send `sig` to this process when its parent dies (libc prctl).
class WorkerBase264Resources and lifecycle of a GPU worker: torch/distributed init, model load, KV cache engine, an
└ __init__66
└ gpu_id2
└ start_slave_worker_loop5
└ stop17
└ maybe_gc_collect5
└ clone_and_zero_states_and_blocks_on_default_stream9
└ set_random_seed_with_rank3
└ _init_torch7
└ init_model13
└ init_dist6
└ load_model7
└ profile_num_available_blocks57Profiles the peak memory usage of the model and returns the maximum nu
└ init_cache_engine3
└ warm_up_model15
└ run_workers13
└ init_engram9
_init_distributed_environment30Initialize the distributed environment.
_bind_numa11
(已列出全部 4 个顶层符号 + 16 个方法)
deepinfer/worker/cache_engine.py查看源码979 行
CacheEngine class for managing the KV cache.
符号行数 · 说明(ast 提取)
_align_to_multiple3把 numerator 个元素按每 denominator 个一组分组后,组数向上对齐到 alignment 的倍数。denominator=1 时即普通向上对齐
_state_bytes3一段 fp32 state [num_state_token, 2, head_dim] 的 bytes
_kv_bytes_per_token11每 token interleaved KV cache 的 data+scale 总字节数
_get_from_attn_index_configs12对每个有 attn_index 的 attn 层取 candidate_fn(attn_index),校验全部一致后返回(无 attn_index 层时返回 0)。 candidate_fn(
_get_qk_topk_bytes8获取这一层 indexer 的 FP4 KV bytes 数(包含 UE8M0 scale)
_get_qk_topk_head_dim3获取这一层 indexer 的 kv 的维度(不包含 sf),计算 state cache 时需要
get_inference_swa_block_size6swa_block_size 等于 window_size 加上为回退功能额外存的部分。 如果 config 里 window_size < 0,说明这个模型没有 swa 层,直接返回 0 n
get_yoco_store_extra_tokens3YoCo 截断开启时,参与落盘重排的 state ring 额外多存的 token 数
get_kvstore_swa_block_size10kvstore 视角的 swa_block_size:inference 大小 + prefill 落盘多存的部分。 因为 kvstore 落盘只在 128(落盘粒度)的整倍数落,prefil
_is_dropped_swa_layer4按模型配置划分 YOCO consumer SWA,不依赖 PE/CE 的截断模式
_needs_compress_state2
_needs_index_state5
get_inference_compress_block_size3Compression ring plus rollback history; environment changes require clearing the cache.
clear_compress_block_size_cache3Clear cached ring sizes after changing DEEPINFER_MAX_BACKTRACKING_TOKENS.
_get_shared_mapped_layer_id22返回 layer_info_shared_cfg[map_key] 里 layer_id 映射到的(被复用的)layer_id。 share-kv / share-index / share-
_get_kv_mapped_layer_id7返回本层实际使用哪一层的 kv cache。 share-kv 场景下 config 会给出 layer_info_shared_cfg.layer_kv_map(layer_id -> 被复
_get_index_mapped_layer_id14返回本层的 indexer(index attention)实际使用哪一层的 K cache。 优先使用 layer_index_k_map;未指定时 K 跟随 layer_index_mod
_iter_owning_compress_state_layers9产出需要且拥有 main/index state 的压缩层
get_num_state_slots2
class KVCache130 个方法
class StateBlock86State cache 中一个 seq 的物理布局。 分区原则:需要落盘的 state 全部放在前面的 stored region,不需要落盘但运行时 仍需保留的 state 放在后面的 dr
└ __init__64根据模型配置计算 state block 的布局
class KVCacheManager226管理 KV cache 的分配和布局。 基于 StateBlock 抽象,为每一层分配 kv cache tensor 和 state tensor, 支持 compress_ratio in
└ __init__50
└ _alloc_state8Allocate non-persisted fp32 compression state after the dropped SWA ri
└ process102为一层 attention 分配 kv cache 和 state cache。 Returns: (KVCache, (layer_id,
└ finalize14在所有层 process 完成后调用,对齐总 kv 大小
└ update_gpu_cache_interface_class_fields41更新 GPUCacheInterface 的类级字段。 这些字段被 _carve_state_views / select_state_sl
class GPUCacheInterface30910 个方法
└ _kvcache_layout72计算 kv cache 和 state cache 的物理布局,并按层切出各自的 cache view。 应该由调用者保证被调用的次数尽量少
└ __init__27
└ _has_SWA5
└ _is_sparse4
└ _is_full4
└ __getitem__2
└ is_valid_layeridx2
└ _carve_state_views53Carve SWA/stored-region cache and tensor views. Returns two parallel l
└ select_state_slice_to_store56从 state cache 里读出 state id 上的值,只读取要落盘的那一部分。 例如如果只在 128 的倍数处落盘,则需要维护最近
└ load_state_from_store_to_prefill_cache28把一个 request 的 state 存到指定 state id 的 state cache 里 Args: state_id (int)
class CacheEngine128Manages the KV cache. This class is responsible for initializing and managing the GPU and CPU KV
└ __init__26
└ get_block_shape4应该由调用者保证被调用的次数尽量少,因为处理 config 的逻辑比较复杂,而且 AttrDict 没法被 functools.lru_ca
└ get_kvcache_layout4应该由调用者保证被调用的次数尽量少,因为处理 config 的逻辑比较复杂,而且 AttrDict 没法被 functools.lru_ca
└ get_state_shape4
└ do_allocate_kv_cache2
└ _alloc_gpu_uint86用 cuda_utils.alloc_tensor 分配 shape 大小的 uint8 GPU tensor
└ allocate_gpu_cache49
└ get_cache_block_size10单个 block(叠加所有层)的总字节数。block_size 为每个 block 在压缩前所表示的 token 个数。 应该由调用者保证被
(已列出全部 24 个顶层符号 + 24 个方法)
deepinfer/worker/cuda_graph_runner.py查看源码169 行
符号行数 · 说明(ast 提取)
class CudaGraphData12Captured graph with preparation and execution buffers. Source tensors are on CPU, or share devic
build_graph_batch_sizes11Build power-of-two warmup sizes followed by fixed-width intervals.
_run_model13
class CudaGraphRunner1005 个方法
└ __init__11
└ capture60
└ select6
└ replay5
└ destroy13
(已列出全部 4 个顶层符号 + 5 个方法)
deepinfer/worker/decode_perf_cache.py查看源码167 行
符号行数 · 说明(ast 提取)
_is_hex2
class DecodePerfCache1417 个方法
└ __init__12
└ _get_hash_key13
└ _parse_filename16文件名格式 <sha256>.<uuid4 hex>.<unix 秒>[.tmp],不符合则返回 None
└ _cleanup18
└ _read34
└ load_decode_perf_cache19
└ write_decode_perf_cache21
(已列出全部 2 个顶层符号 + 7 个方法)
deepinfer/worker/dflash_cuda_graph_runner.py查看源码101 行
符号行数 · 说明(ast 提取)
class DFlashCudaGraphData40 个方法
class DFlashCudaGraphRunner705 个方法
└ __init__9
└ capture34
└ select6
└ replay8
└ destroy8
(已列出全部 2 个顶层符号 + 5 个方法)
deepinfer/worker/model_runner.py查看源码645 行
符号行数 · 说明(ast 提取)
class MainModelOutput40 个方法
class ModelRunner59220 个方法
└ __init__40
└ load_model20
└ set_block_size2
└ _prepare_input_tensors27Build input metadata on CPU, or on device for ZOS decode. If out_dict
└ _prepare_input13Build the forward-pass input on the driver, or receive it on the other
└ _graph_input_metadata6
└ _prepare_input_driver44
└ _prepare_input_follower15
└ prepare_sampler_inputs45
└ execute_model_profile_run26Profile-run only: run one full step (forward + sample + post-process)
└ execute_main_model28Run the main model forward pass (prepare input, launch forward). IMPOR
└ execute_sample31Run sampling on the main model output (prepare sampler inputs, launch
└ post_process15
└ _placeholder_seq_metadata18
└ _build_prompt_profile_seq_lens37
└ profile_run69
└ capture_model15
└ capture_dflash_model28
└ profile_decode_perf70
└ destroy_cuda_graphs12Destroy CUDA graphs and release resources. NOTE: This is necessary to
(已列出全部 2 个顶层符号 + 20 个方法)
deepinfer/worker/runtime_config.py查看源码70 行
符号行数 · 说明(ast 提取)
expose_all_gpus_to_cuda_driver14
configure_worker_environment23Configure process-wide environment variables used by workers.
configure_worker_kernels16Configure process-wide kernel library behavior used by workers.
(已列出全部 3 个顶层符号)
deepinfer/worker/worker.py查看源码284 行
A GPU worker driving per-step model execution: forward, post-process, sample.
符号行数 · 说明(ast 提取)
class _SeqlensCorrection7ZOS 下按上一步采样结果修正后的 seqlens 及其 CPU 输入
class EngineCallbacks5Callbacks injected by the engine, invoked on the driver worker only.
class Worker233Executes model steps on a GPU. Every step runs the Forward-Post_process-Sample round in execute_
└ __init__30
└ execute_model_step101The unified entry for model execution: every step (prompt/decode, ZOS
└ _correct_seqlens_qk55CPU 侧的 seqlens_q/k 在 ZOS 下滞后一步:与上一步 batch 有交集时,需按上一步采样结果在 GPU 上修正
└ _post_process_step25Synchronize on the sampling completion event, run post-processing on t
└ flush_inflight_reqs10Flush inflight requests running on GPU, useful for ZOS. It may cause C
(已列出全部 3 个顶层符号 + 5 个方法)
deepinfer/worker/zos_status.py查看源码41 行
符号行数 · 说明(ast 提取)
class WorkerStepState110 个方法
class MetadataZOS17GPU metadata and the pinned CPU remap used to prepare it.
(已列出全部 2 个顶层符号)

3. distributed(2 文件 · 463 行)

模块综述——分布式最小件:shm_broadcast.py(462 行)ShmRingBuffer/Handle/MessageQueue——引擎进程与 worker 间走共享内存环形队列而非 socket,配 DEEPINFER_GLOO_TIMEOUT=4h 的慢启动容忍;仓库刻意不自带集合通信库,NCCL/HCCL 由平台侧供给。

deepinfer/distributed/__init__.py查看源码1 行
deepinfer/distributed/shm_broadcast.py查看源码462 行
符号行数 · 说明(ast 提取)
class ShmRingBuffer1176 个方法
└ __init__88A shared memory ring buffer implementation for broadcast communication
└ handle2
└ __reduce__2
└ __del__7
└ get_data5
└ get_metadata5
class Handle70 个方法
class MessageQueue30011 个方法
└ __init__77
└ export_handle2
└ create_from_handle40
└ wait_until_ready21This is a collective operation. All processes (including the readers a
└ _spin_wait10自旋等待一轮:让出 CPU、按间隔打 debug 日志、超时抛 TimeoutError。返回更新后的 n_warning
└ acquire_write37
└ acquire_read28
└ enqueue16Write to message queue with optional timeout (in seconds)
└ dequeue17Read from message queue with optional timeout (in seconds)
└ broadcast_object6
└ create_from_process_group30
(已列出全部 3 个顶层符号 + 17 个方法)

4. entrypoints(2 文件 · 200 行)

模块综述——对外入口 2 文件 200 行:llm.py 的 LLM 类即 examples/offline_inference.py 所用 API(generate/采样参数/结构化输出全在此面)——开源版只放离线入口,在线服务层(路由/多副本 LB)属未开源部分。

deepinfer/entrypoints/__init__.py查看源码1 行
deepinfer/entrypoints/llm.py查看源码199 行
符号行数 · 说明(ast 提取)
class LLM176An LLM for generating texts from given prompts and sampling parameters. This class includes a to
└ __init__32
└ get_tokenizer2
└ generate53Generates the completions for the input prompts. NOTE: This class auto
└ _add_request23
└ _run_engine28
└ close2
(已列出全部 1 个顶层符号 + 6 个方法)
首页