← 返回全景索引

1. model_executor(7 文件 · 618 行)

模块综述——模型执行层直下 9 文件:model_loader.py(154 行)get_model/build_model_on_meta/load_hf_checkpoint 三段式装载,checkpoint_load_watchdog 看门狗防挂死,_configure_moe_redundancy 按冗余专家数预配 EPLB;model_metadata_utils.py(189 行)derive_compress_ratios/derive_main_kv_cache_num_per_channels 把 V4.1 的逐层压缩比从 config 摊成张量;sampling_inputs.py(133 行)MTPSamplingInput/MTPDriverInput/MTPDecodeInput 三态采样输入(DSpark 变长验证的数据面);utils.py(102 行)set_random_seed/reconstruct_param 支撑批不变的权重重建。

deepinfer/model_executor/__init__.py查看源码1 行
deepinfer/model_executor/layer_utils.py查看源码17 行
符号行数 · 说明(ast 提取)
iter_runtime_attn_modules11遍历 attention list。注意 lm head 也会出现在 attention list 中,特判掉这一层,不计入 layer id。config_idx 为原始的 id,一般不会被
(已列出全部 1 个顶层符号)
deepinfer/model_executor/model_loader.py查看源码154 行
Utilities for selecting and loading models.
符号行数 · 说明(ast 提取)
_set_default_torch_dtype8Sets the default torch dtype to the given dtype.
_get_model_architecture8
checkpoint_load_watchdog15checkpoint 加载超时保护。在指定时间内未完成加载则 abort 进程
get_model16
_configure_moe_redundancy24Resolve each MoE layout's physical-expert padding before construction.
finalize_model_config17初始化模型构建所需的运行环境,并在已加载的 model_cfg 上写入推理所需的并行 / 运行时字段。 model_cfg 由 ModelConfig 通过 load_model_config
build_model_on_meta6在 meta 设备上构建 HF 模型的语言参数容器
load_hf_checkpoint18Validate parameter coverage and shapes, then load the planned HF weights.
(已列出全部 8 个顶层符号)
deepinfer/model_executor/model_metadata_utils.py查看源码189 行
符号行数 · 说明(ast 提取)
derive_compress_ratios6按 attn 模块配置拆出 dense / sparse 两类 kv 压缩率(升序去重)
derive_main_kv_cache_num_per_channels3FP4 主压缩 KV 每 16 个值共用 scale;MXFP8 主 KV 和 SWA 每 32 个值共用 scale
class ModelMetadata1477 个方法
└ __init__80
└ engram_enabled3
└ ngram_pad_id2
└ resolved_tokens_per_block2
└ kvcache_align_to3MXFP8 / sparse FP4 cache requires 128-byte block alignment.
└ get_input_metadata_class_and_prepare_inputs_func3
└ prepare_inputmetadata_dict43
(已列出全部 3 个顶层符号 + 7 个方法)
deepinfer/model_executor/model_output.py查看源码22 行
符号行数 · 说明(ast 提取)
class CausalLMForwardOutput122 个方法
└ narrow5
└ copy_2
(已列出全部 1 个顶层符号 + 2 个方法)
deepinfer/model_executor/sampling_inputs.py查看源码133 行
Sampling inputs shared by native preparation and Python consumers.
符号行数 · 说明(ast 提取)
class MTPSamplingInput35Driver-only controls used when sampling MTP drafts.
└ build_padding13
└ cut14
class MTPDriverInput23Driver-only verification results and sampling controls for the next MTP drafts.
└ build_padding6
└ cut6
class MTPDecodeInput23Inputs to MTP decode on one rank; followers receive the driver results inside the model.
└ build_padding5
└ cut5
└ req_cnt2
(已列出全部 3 个顶层符号 + 7 个方法)
deepinfer/model_executor/utils.py查看源码102 行
Utils for model executor.
符号行数 · 说明(ast 提取)
set_random_seed6
reconstruct_param5
parse_values32解析形如 '0..3,7,10..12' 的整数集合:逗号分隔的数值或 'start..end' 闭区间,各分段必须严格单调递增
class Movable36A move-only wrapper that simulates C++ std::move semantics. Usage: m = SomeObject() m = Movable(
└ __init__2
└ move6
└ __bool__2
└ __repr__4
(已列出全部 4 个顶层符号 + 4 个方法)

2. model_executor/models(34 文件 · 7,085 行)

模块综述——模型定义 26 文件:deepseek.py(526 行)DeepseekModel/DeepseekForCausalLM 主干装配;decoder_layer.py(240 行)DeepseekDecoderLayer 与 DFlashDecoderLayer(draft 层复用主干块);mtp/dflash.py(393 行)ConfidenceHead+DFlash——DSpark 置信头的模型本体;deepseek_vl.py(268 行)多模态封装;vision_encoder/(vit.py 231 行 deepseek_vit_opt 结构+vl_aligner 142 行+mlp_projector)是 E/P/D 里 E 的模型侧;v4_modules/ 26 文件是 V4.1-Flash 架构真身——attn.py(1,009 行)MLA 运行时(Q/KV 投影、KV 存储、prefill/decode 分路)、compress.py(168 行)KProject+Compressor 压缩 KV 运行时、cross_layer.py(384 行)跨层共享拓扑与 per-forward 状态(CED 层间复用的落点)、index_attn.py(576 行)稀疏 indexer MQA(Lightning Indexer 的引擎侧)、mlp.py(617 行)DeepseekMoE 含 mega-MoE 路径、engram 三件(220+117+65 行)哈希 n-gram 表运行时与词表压缩(ENGRAM_PAD_TOKEN=2、昇腾自动 GPU 存储)、mHC 四件(398+110+36+143 行)hc_mult 路残差混合与 Sinkhorn 归一、yoco.py(124 行)YoCo 截断谓词与边界 compact、builder/containers/parameters 系把 HF 权重映射进运行时容器;ModelRegistry 统一登记。

deepinfer/model_executor/models/__init__.py查看源码38 行
符号行数 · 说明(ast 提取)
class ModelRegistry132 个方法
└ load_model_cls7
└ get_supported_archs2
(已列出全部 1 个顶层符号 + 2 个方法)
deepinfer/model_executor/models/decoder_layer.py查看源码240 行
符号行数 · 说明(ast 提取)
_build_mlp_and_layernorms8
class DeepseekDecoderLayer1283 个方法
└ __init__42
└ _store_dflash_input4
└ forward79
class DFlashDecoderLayer623 个方法
└ __init__28
└ update_main_cache15
└ forward_drafts16
(已列出全部 3 个顶层符号 + 6 个方法)
deepinfer/model_executor/models/deepseek.py查看源码526 行
符号行数 · 说明(ast 提取)
class DeepseekModel1905 个方法
└ __init__57
└ _init_yoco21初始化 yoco 截断相关状态,并校验与 DFlash / Engram 的兼容性
└ build_embed_tokens9
└ allocate_output3
└ forward95
class DeepseekForCausalLM2759 个方法
└ __init__70
└ _init_eplb42
└ __del__3
└ allocate_output2
└ forward8
└ sample28
└ allocate_userbuffer31
└ load_model76
└ from_model_cfg2
(已列出全部 2 个顶层符号 + 14 个方法)
deepinfer/model_executor/models/deepseek_vl.py查看源码268 行
符号行数 · 说明(ast 提取)
class DeepseekVLForCausalLM24211 个方法
└ __init__13
└ _split_cached_prefix31把被 KV cache 完全覆盖的前缀 segment 替换为等长 dummy 文本,使下游跳过缓存图片的 tensor 计算;返回 (替换
└ _load_image_raw_bytes18加载 worker CPU-resize 后的 ResizedImage,打包成 images_raw(裸 RGB bytes concat
└ _cu_patch_lens_from_crop8按 images_spatial_crop 逐图累计 patch 数(n_vit_w * n_vit_h)得 cu_image_patch_
└ multi_modal_mapper83
└ _special_image_token_mask4标记 [vocab_size, vocab_size + NUM_SPECIAL) 区间内的特殊图像 token
└ get_input_embeddings31计算 vision-language 融合后的 embeddings
└ forward9
└ load_model9
└ derive_image_transform_cfg13从 processor 的 image_transform 取 rgb_pad_to_patches 的 normalize/pad 常量写
└ from_model_cfg5
(已列出全部 1 个顶层符号 + 11 个方法)
deepinfer/model_executor/models/mtp/__init__.py查看源码1 行
deepinfer/model_executor/models/mtp/dflash.py查看源码393 行
符号行数 · 说明(ast 提取)
_clone_linear_weight6
class ConfidenceHead34Predict the acceptance probability of each draft token.
└ __init__16
└ forward14
class DFlash31110 个方法
└ __init__104
└ init_mtp_info_pool9Allocate proposal storage on driver completion workers only.
└ update_main_cache31Write every DFlash layer's main-token keys from the target-layer featu
└ _embed_draft_init_tokens10
└ forward_drafts29Run DFlash draft layers on the fixed-stride metadata built by build_df
└ allocate_output7
└ sample_drafts67Sample drafts, store their proposal state, and return scheduler output
└ run_drafts30The whole DFlash decode forward on the GPU, from per-request inputs to
└ decode_forward9
└ moe_layer_list4
(已列出全部 3 个顶层符号 + 12 个方法)
deepinfer/model_executor/models/v4_modules/__init__.py查看源码43 行
DeepSeek V4.1 model modules on the DeepInfer side.
deepinfer/model_executor/models/v4_modules/attn.py查看源码1009 行
MLA attention runtime: Q/KV projection, KV storage, prefill/decode and DFlash drafts.
符号行数 · 说明(ast 提取)
_make_cp_gather_getter9
class V4AttentionBase1617 个方法
└ __init__37
└ _init_q_norms6
└ _permute_q_b_proj_for_fused10
└ _init_wv_o_proj35
└ _q_b_norm_rope15
└ _fused_norm_rope_cast_kwargs16
└ _wv_and_o_proj35
class V4Attention65316 个方法
└ __init__48
└ _init_q_projections29
└ _init_compressor_and_indexer66
└ get_max_ag_bytes_per_token10
└ _project_q_and_swa15Produce q, [kv_swa]. With yoco_swa_share_hidden the kv_swa is produced
└ _prepare_swa_kv50
└ _project_q_b11
└ _resolve_shared_hidden15The first YOCO consumer KV source may use the current attn-norm hidden
└ _project_current_hidden_inputs27Project current hidden states into (projected_kv, index_weights). Only
└ _store_main_kv15
└ _compute_kv_ca_index63
└ _prefill_attention38
└ _decode_attention43
└ _store_yoco_full_kv50Update main/index KV with the full-length hidden, for the compact quer
└ _prepare_prefill_kv28Allocate or reuse the gathered prefill-KV buffer. A KV source starts a
└ forward129
class DFlashAttention126DFlash attention: prefill updates the main-token KV; decode writes a separate draft KV and compu
└ __init__38
└ get_max_ag_bytes_per_token2
└ update_main_cache34
└ forward_drafts46
(已列出全部 4 个顶层符号 + 27 个方法)
deepinfer/model_executor/models/v4_modules/builder.py查看源码131 行
Builder for the V4.1 HF inference parameters.
符号行数 · 说明(ast 提取)
_default_dtype8Temporarily switch the torch default dtype.
class V41Builder97Builder that builds the model from DeepInfer's own hc / moe / attn parameter containers.
└ __init__7
└ _build_block30
└ _attach_shared_index_k16Share source k_proj/k_norm modules; named_parameters() visits them onc
└ build_model38
(已列出全部 2 个顶层符号 + 4 个方法)
deepinfer/model_executor/models/v4_modules/compress.py查看源码168 行
Compressed-KV runtime: gated low-rank compression, norm and KV-cache update.
符号行数 · 说明(ast 提取)
class KProject22The indexer's k projection (linear + RMSNorm); the input is the compressed latent after norm and
└ __init__13
└ forward_pre_norm2
└ forward2
class Compressor112Pure KV compressor: compression + norm; returns the pre-rope compressed kv and writes the post-r
└ __init__18
└ forward_pre_norm39Produce the KV before norm from the projection output.
└ forward8Produce the post-norm, pre-rope KV from the projection output.
└ forward_store_kv_cache37Produce and store the main KV, and return the post-norm, pre-rope KV o
(已列出全部 2 个顶层符号 + 7 个方法)
deepinfer/model_executor/models/v4_modules/containers.py查看源码136 行
HF V4.1 parameter containers with stable paths for weight mapping.
符号行数 · 说明(ast 提取)
class GPTEmbedding8Shared backbone/DFlash token embedding container.
└ __init__5
class MultimodalEmbedding91 个方法
└ __init__8
class HFModelParameters23One inference stage plus a separately named vision parameter tree.
└ __init__20
materialize_hf_parameter49Allocate HF weight destinations and retain their runtime metadata. Loading fills every destinati
prepare_meta_fp823Declare FP8 weights and scale shapes on meta. Heads use BF16. Expert metadata is 2D until packed
(已列出全部 5 个顶层符号 + 3 个方法)
deepinfer/model_executor/models/v4_modules/cross_layer.py查看源码384 行
Cross-layer sharing: config-derived topology, per-forward state and flattened metadata.
符号行数 · 说明(ast 提取)
class SharedLayerTopology252Static cross-layer sharing (share-kv / share-index / share-index-k) topology, derived from confi
└ __init__4
└ _process_cfg15Collect the global config repeatedly carried by the shared layers, ver
└ _build_layer_maps11Normalize the sparse layer maps in the config into a topology covering
└ _validate30Check the legality of the sharing topology config in a single pass.
└ _build_layer_map35Build the layer_map in deepinfer from the layer_map in config NOTE som
└ _build_candidate_layer_map9The candidate blocks of the sparse index are only produced extra on de
└ _validate_segmented_map11
└ _validate_map_refines8
└ _validate_index_kv_compatibility7
└ _validate_candidate_config40
└ _validate_shared_layer_cfg21
└ is_index_source_layer2
└ is_index_k_source_layer2
└ is_kv_source_layer2
└ is_candidate_source_layer2
class CrossLayerRuntime60Container for the mutable values held across layers within one forward: a source layer writes, l
build_shared_layer_topology13Build the sharing topology once at the model level (DeepseekForCausalLM.__init__) and pass it ex
class SharedLayerMetadata9Sharing topology fields exported in runtime layer order; source only describes the sharing relat
build_shared_layer_metadata18Reuse the normalized topology of attention; without sharing, every layer is a source and there i
(已列出全部 5 个顶层符号 + 15 个方法)
deepinfer/model_executor/models/v4_modules/engram.py查看源码220 行
Engram runtime: hash n-grams, gather the sharded tables and gate the fused projection.
符号行数 · 说明(ast 提取)
_pack_ue8m0_to_int6Pack the ue8m0 scales represented in fp32 into int32 (CUDA) / int16 (ASC), 4/2 per group.
class CompressedTokenizer32Global singleton: raw token id -> compressed token id mapping (initialize is not called when tok
└ initialize8Build the compression mapping from the tokenizer file and initialize t
└ release5
└ encode4Ids outside the vocabulary (image sentinels etc.) map to IMAGE_SENTINE
class NgramEmbedding36The Engram n-gram embedding shard; weights live in the userbuffer, and embeddings are fetched ac
└ __init__23
└ gather_sf6
└ release_storage2
class Engram55Fetch the sparse embedding by n-gram hash, project it through the kv projection, then gate-fuse
└ __init__28
└ forward23hidden_states: [total_q, hc_mult, n_embed] images_seq_mask: [total_q],
class EngramRuntime565 个方法
└ __init__4
└ allocate19
└ preallocate2
└ initialize18
└ fetch6
(已列出全部 5 个顶层符号 + 13 个方法)
deepinfer/model_executor/models/v4_modules/engram_metadata.py查看源码117 行
Engram vocabulary compression and hash metadata.
符号行数 · 说明(ast 提取)
class CompressedVocabulary40Build the HF tokenizer's original-token -> compressed-token mapping on CPU. Decode one token at
└ __init__29
└ __len__2
class EngramLayout37Static table layout shared by parameter construction and runtime hashing.
└ from_cfg28
class NgramHashMapping19Per-layer hash tensors consumed by the Engram kernels.
└ __init__16
(已列出全部 3 个顶层符号 + 4 个方法)
deepinfer/model_executor/models/v4_modules/engram_parameters.py查看源码65 行
Inference-only Engram parameter containers for the V4.1 HF loader.
符号行数 · 说明(ast 提取)
class NgramEmbeddingParameters251 个方法
└ __init__24
class EngramEmbedding22Preserve HF parameter paths; forward is implemented by engram.Engram.
└ __init__19
(已列出全部 2 个顶层符号 + 2 个方法)
deepinfer/model_executor/models/v4_modules/hc.py查看源码398 行
mHC runtime: mix the `hc_mult`-way residual trunk around every sub-layer, then fold it back.
符号行数 · 说明(ast 提取)
class HCSubmodules7The hc parameters of one sub-layer (attn or ffn) together with its layer norm
_make_identity_pre_mix5One-hot initial mix used by the first shifted HC layer: equivalent to pre reading only main path
_fused_cast_kwargs3
class HCLayerMixin308mHC layer mixin: the residual trunk is expanded into hc_mult paths, shaped [n, hc_mult, hidden_s
└ __init__31
└ _attn_hc_modules7
└ _ffn_hc_modules7
└ attn_norm_forward21
└ ffn_norm_forward21
└ hc_post9Write the sub-layer output x [n, hidden_size] back into the trunk, ret
└ _hc_fused_post_pre54The previous sub-layer's post + this sub-layer's pre (mixes + apply) +
└ _mega_mhc87A single deep_gemm.mega_mhc call performs the previous sub-layer's pos
└ _hc_pre48
class HCHead31Finishing step before the lm head: mix the hc_mult-path trunk back into single-path hidden state
└ __init__15
└ forward12
(已列出全部 5 个顶层符号 + 11 个方法)
deepinfer/model_executor/models/v4_modules/hc_blocks.py查看源码110 行
FP32 mHC block and head parameter containers consumed by runtime adapters.
符号行数 · 说明(ast 提取)
class SigmoidHCBlockMixin33Declare effective HF base/fn/scale tensors and norm epsilon holders.
└ _init_hc_parameters30
class SigmoidHCHeadMixin14Declare nonshifted HC head tensors in the folded HF layout.
└ _init_hc_head_parameters11
class MoeDecoderBlockHC44A backbone block with stable HF target paths for attention, MoE and HC.
└ __init__41
(已列出全部 3 个顶层符号 + 3 个方法)
deepinfer/model_executor/models/v4_modules/hc_lazy.py查看源码36 行
HC lazy post-application bundle, shared by HC forward, YoCo compaction and the decoder layer.
符号行数 · 说明(ast 提取)
class HCLazyPostData21Backbone and mixing coefficients produced by `_hc_pre`, consumed by the paired `hc_post`. All fi
└ clear_post5Release consumed post data, keeping the pre mix needed by the next shi
└ clear3
(已列出全部 1 个顶层符号 + 2 个方法)
deepinfer/model_executor/models/v4_modules/heads.py查看源码109 行
HF lm head and DFlash parameter containers for runtime forward and sampling.
符号行数 · 说明(ast 提取)
class GPTHead9Output norm and lm head.
└ __init__6
class MarkovGPTHead9Final DFlash head with a first-order Markov correction to logits.
└ __init__6
class AcceptRatePredictor6DFlash acceptance-rate prediction head.
└ __init__3
class MainPredictHeadHC18Main lm head; shifted HC is completed by the final block's pre-mix.
└ __init__15
class DFlashNextPredictHeadHC44One DFlash draft block with first-shift input and last-shift output heads.
└ __init__41
(已列出全部 5 个顶层符号 + 5 个方法)
deepinfer/model_executor/models/v4_modules/index_attn.py查看源码576 行
Sparse indexer runtime: score compressed KV per query and select the top-k blocks.
符号行数 · 说明(ast 提取)
_align_mqa_weights14Keep the logical head count unchanged while meeting the 16-byte row stride required by deep_gemm
class MQA520The indexer of sparse attention: computes the relu(q@k)·weights logits and selects the topk comp
└ __init__70
└ get_max_ag_bytes_per_token2
└ store_index_kv30
└ _quantize_q16Apply RoPE and quantize index Q to FP4, returning (q_fp4, q_sf).
└ _load_prefill_kv22
└ _topk_candidate_block23
└ _get_candidate_inputs16Return candidate blocks, block size and topk lengths; dense uses (None
└ _get_sparse_prefill_metadata38Cache one query chunk's sparse schedule within the current candidate g
└ _compute_prefill_p_sum42Compute one query chunk, preparing sparse metadata inside the prefill
└ _topk_prefill50
└ _get_decode_metadata42Prepare the dense or sparse schedule before entering the decode timer.
└ _compute_decode_p_sum34
└ _topk_decode59
└ forward60HF V4.1 index attention: KProject projects the main compressed KV, and
(已列出全部 2 个顶层符号 + 14 个方法)
deepinfer/model_executor/models/v4_modules/linear.py查看源码35 行
HF linear parameter containers with FP8 layout metadata.
符号行数 · 说明(ast 提取)
class ReplicatedLinear13Complete linear weights, optionally prepared as FP8 on meta.
└ __init__10
class ParallelRoutedLinear12Expert-major grouped GEMM metadata: (n_local_experts * h_in, h_out). HF materialization allocate
└ __init__5
(已列出全部 2 个顶层符号 + 2 个方法)
deepinfer/model_executor/models/v4_modules/mhc_modeling.py查看源码143 行
MHC modeling helpers that only DeepInfer needs.
符号行数 · 说明(ast 提取)
mhc_head48MHC head processing for the final language model head. Combines pre_norm_fn + head_compute_mix +
mhc_pre_big_fuse71Fused inference path: prenorm GEMM + reduce/rmsnorm + split mixes + sinkhorn + apply mix. Only u
(已列出全部 2 个顶层符号)
deepinfer/model_executor/models/v4_modules/mhc_ops.py查看源码149 行
MHC tensor views and output buffers for the tile-kernels inference operators.
符号行数 · 说明(ast 提取)
default_n_splits3Split-K count for the prenorm GEMM: the Ascend kernel reduces inside, CUDA needs the partials.
expand_to_mhc4
mhc_post7
mhc_pre_apply_mix6
mhc_head_compute_mix10
mhc_pre_split_mixes33
sinkhorn_normalize5
mhc_prenorm_gemm13Split-K partials of the prenorm GEMM, shaped [n_splits, num_tokens, 1, mhc_mult3] and [n_splits,
mhc_pre_norm_fn32PolyNorm mixes for the residual: prenorm GEMM, then the partial/reduce RMSNorm epilogue.
(已列出全部 9 个顶层符号)
deepinfer/model_executor/models/v4_modules/mla_attn.py查看源码300 行
Attention parameter containers for MLA + compressed KV + sparse indexer.
符号行数 · 说明(ast 提取)
class ColumnParallelLora35`x -> A -> (norm) -> B` MLA low-rank projection; when `out_features == 0` there is only A (e.g.
└ __init__32
class SoftmaxAPEGatedColumnParallelLora35KV projection of the compressor: `A` produces the values, `Gate` produces the logits. The single
└ __init__29
class MQAIndexer54Indexer of sparse attention (the `attn_index.use_kproj=True` variant).
└ __init__51
class LoraRopeCompressFlashMHAAutoRecomp137V4.1 main-model attention container for MLA + compressed KV + sparse indexer. `cfg` must be the
└ __init__131
runtime_attn_sink5Transfer effective HF FP32 sink logits without rescaling or copying.
(已列出全部 5 个顶层符号 + 4 个方法)
deepinfer/model_executor/models/v4_modules/mlp.py查看源码617 行
MoE runtime: gate, dispatch/combine and the routed, shared and mega-MoE GEMM paths.
符号行数 · 说明(ast 提取)
process_moe_weight50
_convert_mega_moe_weight14
_grouped_gemm29
_get_swiglu_kwargs2
_replicated_linear2
class DeepseekMoE46915 个方法
└ __init__109
└ post_load_weights14
└ fused_norm_cast_kwargs28
└ allocate_userbuffer22
└ _eplb_layer2
└ _get_selections_by_factor17
└ _map_unbalanced_ratio_to_factor11
└ gate_forward43
└ _weight_and_sf2
└ routed_experts_forward54
└ dispatch30
└ combine19
└ shared_forward14
└ mega_moe_forward36
└ forward52
(已列出全部 6 个顶层符号 + 15 个方法)
deepinfer/model_executor/models/v4_modules/moe.py查看源码113 行
MoE parameter containers: `FusedExperts` / `TopKGate` / `ReplicatedSharedExpert`.
符号行数 · 说明(ast 提取)
class ReplicatedSharedExpert14Shared experts: `n_shared_experts` are only concatenated along the hidden dim, without producing
└ __init__11
class TopKGate28Top-k routing gate of the MoE. Scoring uses sqrtsoftplus; top-k selection uses noaux_tc plus a l
└ __init__21
class FusedExperts43Parameter container of the routed experts + shared experts + gate; HF loads this rank's experts
└ __init__40
(已列出全部 3 个顶层符号 + 3 个方法)
deepinfer/model_executor/models/v4_modules/norm.py查看源码40 行
RMSNorm parameter containers for HF loading.
符号行数 · 说明(ast 提取)
class DropoutAddRMSNorm27Keep the native parameter path and runtime norm interface, without forward.
└ __init__19
└ get_weight4
(已列出全部 1 个顶层符号 + 2 个方法)
deepinfer/model_executor/models/v4_modules/rope.py查看源码54 行
RoPE hyperparameter containers; utils.convert_rope builds the runtime cos_sin_cache from them.
符号行数 · 说明(ast 提取)
class CustomRotaryEmbedding7Position-interpolation / base RoPE (no parameters).
└ __init__4
class RotaryEmbeddingYarn21YaRN-interpolated RoPE (no parameters).
└ __init__18
build_rotary_emb12Build the RoPE container for `rope_variant` (the cache is not warmed up).
(已列出全部 3 个顶层符号 + 2 个方法)
deepinfer/model_executor/models/v4_modules/utils.py查看源码144 行
Container-to-runtime conversions, plus the timer layer grouping.
符号行数 · 说明(ast 提取)
convert_rope30
merge_linear_weights11
_init_fp84
_apply_in_gpu_chunks13
_apply_random_init5
init_dummy_weight15
convert_rmsnorm8
layer_group_key5key of the timer sampling group: module structure repr + attention config
create_deepseek_decode_layer7
get_enable_timer_layer5
(已列出全部 10 个顶层符号)
deepinfer/model_executor/models/v4_modules/yoco.py查看源码124 行
Predicates and runtime operations for YoCo prefill truncation.
符号行数 · 说明(ast 提取)
yoco_enabled3Whether the model enables YOCO (layers after n_prefill_layer are consumer layers).
is_yoco_consumer_layer3YOCO consumer layer: [n_prefill_layer, n_layer) in the main model.
yoco_shared_hidden_required29Whether the YOCO shared hidden (the attn-norm hidden of the first consumer layer) must be captur
yoco_boundary_compact22x must hold per-token values along the first dimension. Transform it to obtain the new x after c
gather_hc_lazy12Gather the compact copy of HCLazyPostData over the kept intervals (used by the yoco consumer com
compact_yoco_boundary31Rearrange the boundary data and update the runtime; returns the compact copies and the original
(已列出全部 6 个顶层符号)
deepinfer/model_executor/models/vision_encoder/__init__.py查看源码1 行
deepinfer/model_executor/models/vision_encoder/mlp_projector.py查看源码24 行
Vision-language aligner;视觉前向直接调用 aligner.layers(x)
符号行数 · 说明(ast 提取)
class MlpProjector141 个方法
└ __init__13
(已列出全部 1 个顶层符号 + 1 个方法)
deepinfer/model_executor/models/vision_encoder/vit.py查看源码231 行
deepseek_vit_opt ViT:结构、权重与推理前向
符号行数 · 说明(ast 提取)
_linear15bf16 GEMM:bias 走 addmm(cublas);无 bias 走 deep_gemm(输出行 stride 须 16B 对齐)
_norm5RMSNorm + 融合残差加;residual=None 时透传 x 作为下一段的 residual
class RMSNorm6RMSNorm 参数容器;前向统一走 _norm(需要融合残差加)
└ __init__3
class PatchEmbedFlatten82 个方法
└ __init__3
└ forward3images: [n, 3, p, p] -> [n, embed_dim]
class VisionRotaryEmbedding92 个方法
└ __init__4
└ forward3
class Attention342 个方法
└ __init__7
└ forward25
class SwiGLU112 个方法
└ __init__5
└ forward4
class Block272 个方法
└ __init__8
└ forward17返回 (x, residual);residual 非 None 表示留给下一块的 norm kernel 融合相加
class VisionTransformer63V4.1 视觉编码器,构造参数取自 model_cfg.vision.params
└ __init__28
└ _rope4gather 出 [n, 4*half] 的 cos_sin,列序为 (cos_row, cos_col, sin_row, sin_col
└ forward25images: [sum_n_patch, 3, p, p] bf16;pos_id: [sum_n_patch, 2];返回 [sum_n
(已列出全部 9 个顶层符号 + 14 个方法)
deepinfer/model_executor/models/vision_encoder/vl_aligner.py查看源码142 行
符号行数 · 说明(ast 提取)
class VisionLanguageInstructTuner1324 个方法
└ __init__35接管 HF 已加载的视觉模块和 image_* 参数,不重新构建/复制权重
└ _encode_images31ViT -> downsample -> aligner,输出与 IMAGE token 逐一对应的 embeddings。 vit_att
└ _merge_image_embeds16把 IMAGE token 位置替换为 image embeddings、特殊 token 位置替换为对应参数(原地,input_embed
└ forward46把 worker 透传的裸 RGB bytes 补齐成 image patch(居中 pad + normalize),编码后融合进 inp
(已列出全部 1 个顶层符号 + 4 个方法)

3. model_executor/input_metadata(5 文件 · 1,156 行)

模块综述——输入元数据 5 文件:input_metadata.py(491 行)四类元数据(InputMetadata/V4/VL/V4VL)是 C++ prepare_prompt_v4 与 Python 世界的交接面;yoco.py(183 行)YoCo 截断 mixin(mask/compact 两布局的字段全家与 consumer/mask 视图);prepare_tensor_input_zos.py(383 行)零开销调度的 decode 输入预装配(DecodeInputsZOS/CommonDecodeBuffersZOS 常驻缓冲);dflash.py(85 行)DSpark draft 注意力 mixin——三大特性(YoCo/zos/DSpark)的调度侧数据全在此落位。

deepinfer/model_executor/input_metadata/__init__.py查看源码14 行
deepinfer/model_executor/input_metadata/dflash.py查看源码85 行
DFlash draft attention 的 metadata mixin(InputMetadataV4 继承)
符号行数 · 说明(ast 提取)
class DFlashMetadataMixin58DFlash 专属字段与 fixed-stride metadata 构造
└ build_dflash_input49Build fixed-stride metadata consumed by DFlash draft attention. Args:
(已列出全部 1 个顶层符号 + 1 个方法)
deepinfer/model_executor/input_metadata/input_metadata.py查看源码491 行
符号行数 · 说明(ast 提取)
class InputMetadata188Fields and methods shared by all InputMetadata variants.
└ get_clean_list3Fields to clear (set to None) when reusing a cudagraph; they are recom
└ compute_attn_info4Expand compact index fields into the full attention indices consumed b
└ to_dict4prepare_input_tensor fields nest at most one dict level (ratio buckets
└ recursive_fn13
└ recursive_copy_10
└ to_flatten_dict3
└ from_flatten_dict3
└ broadcast48Broadcast to the other ranks in the CP group: non-tensor fields via cp
└ prepare_for_mirror_cp39Prepare each sequence's CP-mirror layout (CP > 1, prefill only). input
└ _cp_gather5Reorder a varlen tensor into this rank's CP-mirror layout; identity wh
class InputMetadataV4196InputMetadata for V4. Zero-length tensors are padded to length 1. YoCo 截断字段/视图与 DFlash 字段/构造分别见
└ get_clean_list8
└ _expand_kv_swa_full_index6Expand pivots P into a dense prefill SWA index (indices into the gathe
└ compute_attn_info47
└ to_flatten_dict11Flatten dict-valued fields into "field.ratio" keys (broadcast_dict han
└ from_flatten_dict10Inverse of to_flatten_dict: fold "field.ratio" keys back into dicts.
class InputMetadataVL52Input for multi-modal VL modules; image fields are prefill only.
└ prepare_for_mirror_cp7
class InputMetadataV4VL191 个方法
└ get_consumer_view16VL 扩展:images_seq_mask 是唯一跨 compaction 边界仍被消费的 VL per-token 字段 (consume
(已列出全部 4 个顶层符号 + 17 个方法)
deepinfer/model_executor/input_metadata/prepare_tensor_input_zos.py查看源码383 行
符号行数 · 说明(ast 提取)
class DecodeInputsZOS130 个方法
class CommonDecodeBuffersZOS80 个方法
prepare_decode_inputs_zos72Batch per-sequence CPU extraction into named pinned tensors.
get_or_create5Reuse the pre-allocated buffer d[name] (cudagraph), or allocate a fresh one (eager).
get_or_create_stacked40按 key 分桶但由 kernel 一次性写入的一组 buffer。返回 (kernel_out, {key: buffer})。 - kernel_out: kernel 写入的 [len(
prepare_common_decode_buffers_zos17
prepare_token_ids_zos96input_ids (D2D scatter for prev seqs, CPU fill for fresh seqs), plus engram ngram_token_ids when
finalize_decode_outputs_zos21
_dummy_fix_routing_mask3为 decode metadata kernel 的 fix_routing_mask 输出分配占位 buffer;调用方不读取其内容
prepare_decode_v4_zos76
(已列出全部 10 个顶层符号)
deepinfer/model_executor/input_metadata/yoco.py查看源码183 行
YoCo prefill 截断的 metadata mixin(InputMetadataV4 继承)
符号行数 · 说明(ast 提取)
class YocoMetadataMixin151YoCo 截断专属字段与 consumer / mask 视图
└ yoco_compaction_enabled7YoCo prefill consumer compaction 是否对本批生效。CP 无关(CP > 1 走"先 compact 再 CP
└ yoco_mask_enabled4YoCo prefill mask 截断(DEEPINFER_YOCO_PREFILL_TRUNCATION_MODE == "mask")
└ yoco_truncation_enabled3YoCo prefill 截断(任一模式)是否对本批生效
└ get_mask_view7yoco decoder 截断只改 mask,不做真截断
└ get_consumer_view89为第一个 YoCo consumer 层创建 compact metadata 浅拷贝。 将 query-aligned 字段和 SWA 可
(已列出全部 1 个顶层符号 + 5 个方法)

4. model_executor/eplb(3 文件 · 795 行)

模块综述——EPLB 三件 795 行:__init__.py(435 行)ExpertLoadBalancer/Manager 管统计窗口与重排节奏(prefill 4 冗余/1,000 步重排、decode 1 冗余/10,000 步重排的生产参数对应的运行时);policy.py(141 行)logical→physical expert 的全局重排(_batch_greedy_indices 贪心装箱,rebalance_experts_global);shuffle.py(219 行)按新旧映射 p2p 搬运专家权重 inplace(expert_model_parallel_shuffle_inplace,NVLink symm_mem 通道的上层调度)——moe_lb=1.045~1.090 的均衡账出自这里。

deepinfer/model_executor/eplb/__init__.py查看源码435 行
符号行数 · 说明(ast 提取)
resolve_num_extra_experts8取不小于下限、且使 num_physical_experts 能被 ep_size 整除的冗余 expert 数
get_initial_global_physical_to_logical_map9初始布局:[原始 routed experts, 复制的 routed experts]
class ExpertLoadBalancer302EPLB 运行时状态:累计各 expert 的 token 数,按周期重算放置并 shuffle 权重。 所有环境配置均在构造时读取并固定
└ __init__69
└ step8由 DeepseekForCausalLM.sample 每 step 调用,更新重排与负载统计
└ steps_until_lb_stat_flush5距下次 LB 统计 flush(EP all_gather)的 step 数;ep=1 不统计时返回 None
└ _update_rearrangement20
└ _update_load_balance_stats27
└ _initialize_shuffle26首次 rearrange:释放缓存显存防 OOM;单机时建 symm_mem 镜像走 IPC shuffle
└ _rearrange_experts66
└ _log_rearrangement_metrics54
class ExpertLoadBalancerLayerState40 个方法
class ExpertLoadBalancerManager506 个方法
└ __init__12
└ num_moe_layers2
└ layer7
└ step8
└ take_moe_load_balance_ratio9
└ steps_until_lb_stat_flush5距下次 LB 统计 flush 的 step 数;均不统计(如 ep=1)时返回 None
current3当前进程的 EPLB manager,未启用(如 dense 模型)时为 None
set_current4
destroy_current3
(已列出全部 8 个顶层符号 + 14 个方法)
deepinfer/model_executor/eplb/policy.py查看源码141 行
MoE 负载均衡策略:根据 token 统计重算 physical expert 放置
符号行数 · 说明(ast 提取)
_batch_greedy_indices59确定 physical expert 如何复制后,根据历史 batch 的信息贪心排布到各 rank 上 Parameters: tokens_per_expert: [num_steps,
rebalance_experts_global68全局负载均衡:给热点 logical expert 分配冗余副本,再把所有副本均衡到各 GPU。 Parameters: tokens_per_expert: [num_steps, num_
(已列出全部 2 个顶层符号)
deepinfer/model_executor/eplb/shuffle.py查看源码219 行
EPLB 专家权重重排:按新旧 physical -> logical 映射搬运 expert 权重(inplace)
符号行数 · 说明(ast 提取)
_plan_intra_copies10本卡内部能满足的搬运。received[dst] 表示槽位 dst 无需远端数据;copies 是卡内 (src, dst) 拷贝对
_remote_routes17expert 的跨卡收发双方。 senders: 持有 expert 的 (rank, 第一个本地槽位),按 rank 升序; receivers: 需要 expert 且卡内无法满足(ori
_paired_sender7第 j 个 receiver 由第几个 sender 供给:前 n * num_senders 个均分(每个 sender 连续 n 个),其余轮转补齐。 收发双方用同一函数配对,保证 P2P
_first_slot_per_expert7(expert, 第一个槽位) 列表,按 expert 升序;skip[i] 为 True 的槽位不参与
expert_model_parallel_shuffle_inplace27重排专家权重(inplace)。 当前 rank 对应专家编号是 origin_global_experts_indices[:, ep_rank*num_local_experts : (e
_shuffle_layer_p2p54
expert_model_parallel_shuffle_inplace_intranode26同 expert_model_parallel_shuffle_inplace,但限单机:权重经 IPC 镜像直接读对端,无 P2P 通信。 镜像只有一层的量,逐层刷新复用
_shuffle_layer_intranode41
(已列出全部 8 个顶层符号)

5. model_executor/parallel_utils(6 文件 · 712 行)

模块综述——并行工具 5 文件:parallel_state.py(231 行)ParallelProcessGroup 进程组管理;userbuffer.py(241 行)_SymBufferSpec/_UserBufferManager 对称内存缓冲(通信与权重 shuffle 共用的 NVLink 通道);cp.py(55 行)CPManager 序列分片;nccl_memory.py(101 行)NCCL 显存采样统计(配 DEEPINFER_NCCL_MEMORY_SAMPLE_INTERVAL);communication_op.py(83 行)张量元数据广播。

deepinfer/model_executor/parallel_utils/__init__.py查看源码1 行
deepinfer/model_executor/parallel_utils/communication_op.py查看源码83 行
符号行数 · 说明(ast 提取)
gather14Gather input_ from all ranks of group and concat along dim; returns None on non-dst ranks.
cp_broadcast6Broadcast input_ in place across the CP group.
cp_broadcast_multi_tensor8Broadcast multiple tensors in place across the CP group.
class TensorMetadata30 个方法
broadcast_tensor_dict32Broadcast a dict across the CP group: cuda tensors via NCCL, everything else via shm object broa
(已列出全部 5 个顶层符号)
deepinfer/model_executor/parallel_utils/cp.py查看源码55 行
符号行数 · 说明(ast 提取)
class CPManager46Manage CP communication storage, sessions, and all-gather operations. Wait callbacks must be con
└ __init__5
└ num_bytes2
└ session8
└ get_inplace_tensor5Allocate the gathered region and return this rank's contiguous shard.
└ all_gather10Launch all-gather; waiting concatenates rank shards along the token ax
└ destroy2
(已列出全部 1 个顶层符号 + 6 个方法)
deepinfer/model_executor/parallel_utils/nccl_memory.py查看源码101 行
符号行数 · 说明(ast 提取)
class NCCLMemoryStatsLogger88Sample driver-local communicators and log snapshots when they change.
└ __init__9
└ _get_group_aliases8
└ _collect24Return (label, total_bytes) for every initialized NCCL communicator.
└ _sample16
└ step22
(已列出全部 1 个顶层符号 + 5 个方法)
deepinfer/model_executor/parallel_utils/parallel_state.py查看源码231 行
符号行数 · 说明(ast 提取)
cp_broadcast_object7
_split_group_cached11
_split_group9
class ParallelProcessGroup13712 个方法
└ __init__17
└ create_process_groups57
└ is_within_nvl_domain4
└ data_parallel_group2
└ cpu_data_parallel_group2
└ context_parallel_group2
└ expert_parallel_group2
└ engram_parallel_group2
└ world_group2
└ get_rank2
└ cleanup_shm_broadcast9Explicitly close and unlink shared memory used by MessageQueue, so tha
└ init_device_groups15默认 PG 改为 CPU(gloo) 后端后,NCCL/HCCL 子组失去 eager/split 初始化,全部 lazy:必须先跑一次 c
init_parallel_groups35
(已列出全部 5 个顶层符号 + 12 个方法)
deepinfer/model_executor/parallel_utils/userbuffer.py查看源码241 行
符号行数 · 说明(ast 提取)
class _SymBufferSpec12Identity of one SymmBuffer view; fields are exactly the deep_gemm.SymmBuffer kwargs.
_gib2
limit_num_sms12
class _UserBufferManager184Owns all process-wide communication buffers used by one loaded model.
└ __init__5
└ allocate_ep33
└ allocate_cp21
└ cp_session6
└ allocate_engram55
└ allocate_sym_buffer43The first spec allocated must be the largest: it owns the backing stor
└ close11
(已列出全部 4 个顶层符号 + 7 个方法)
首页