worker/block_table.py查看源码
KV cache 块表管理(458 行)。BlockTable 把每个请求的逻辑块序列映射到物理块:行级操作(append/add/clear/move/swap row)、slot mapping 计算(含 draft 模式与 DCP 变体 _compute_dcp_slot_mapping)、提交(commit_block_table 把 host 表同步到 device)、物理/逻辑块转换,并提供 device tensor/CPU tensor/numpy 三种视图供不同消费者使用;MultiGroupBlockTable 为多个 KV cache 组(如 MLA 主缓存 + indexer 缓存)各维护一张 BlockTable 并统一转发行操作。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\block_table.py
__init__[73行] 代码量 73 行
append_row[3行] 代码量 3 行
add_row[3行] 代码量 3 行
clear_row[3行] 代码量 3 行
move_row[3行] 代码量 3 行
swap_row[3行] 代码量 3 行
compute_slot_mapping[15行] 代码量 15 行
compute_slot_mapping_draft[14行] 代码量 14 行
_compute_dcp_slot_mapping[46行] 代码量 46 行
commit_block_table[3行] 代码量 3 行
clear[3行] 代码量 3 行
_convert_physical_to_logical_blocks[16行] Convert physical block IDs to logical block IDs.
get_device_tensor[5行] Returns the device tensor of the block table.
get_cpu_tensor[3行] Returns the CPU tensor of the block table.
get_numpy_array[3行] Returns the numpy array of the block table.
_make_buffer[2行] 代码量 2 行
__getitem__[3行] Returns the BlockTable for the i-th KV cache group.
worker/dcp_utils.py查看源码
Decode Context Parallel(DCP)工具集(696 行)。DCPManager 负责按 DCP 切分 decode 批次的元数据与可复用缓冲:classify_decode_request_mask 分类可迁移请求、init_batch_info 初始化批信息、generate_dcp_metadata 生成本地元数据、_get_dcp_local_seq_lens 按 interleave 布局计算本地 KV 长度;投机解码支持:prepare_spec_decode_first_pass_inputs(首趟 draft 的 DCP 元数据)、prepare_spec_decode_mtp_drafting_inputs(MTP draft 输入与 slot)、rebuild_async_spec_decode_inputs(异步调度下重建投机输入)、generate_mtp_attention_mask_for_decode(MTP decode 掩码)。DCPSpecDecodeMTPInputs/DCPSpecDecodeFirstPassInputs/DCPAsyncSpecDecodeRebuildResult 为配套设备侧数据类。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\dcp_utils.py
__init__[52行] 代码量 52 行
classify_decode_request_mask[14行] Match vLLM's decode/prefill batch classification.
init_batch_info[21行] 代码量 21 行
prepare_spec_decode_first_pass_inputs[29行] 代码量 29 行
_get_spec_decode_mtp_slot_inputs[15行] 代码量 15 行
prepare_spec_decode_mtp_drafting_inputs[35行] 代码量 35 行
rebuild_async_spec_decode_inputs[138行] 代码量 138 行
generate_dcp_mtp_input[70行] 代码量 70 行
_get_dcp_local_seq_lens[10行] Return each request's interleave-aware KV length on every DCP rank.
_is_mla_kv_cache_spec[4行] 代码量 4 行
_is_sfa_dcp_metadata_builder[10行] 代码量 10 行
prepare_spec_decode_drafting_cp_metadata[70行] Prepare draft-local DCP metadata before the backend metadata build.
update_spec_decode_drafting_cp_metadata[40行] 代码量 40 行
generate_dcp_metadata[47行] 代码量 47 行
generate_mtp_attention_mask_for_decode[49行] Build interleave-aware causal masks for DCP speculative decode.
worker/encoder_acl_graph.py查看源码
视觉编码器的 ACL graph 支持(374 行)。EncoderGraphParams 按 token budget 键控的图参数(镜像 LLM 侧 GraphParams);EncoderForwardContext 携带重放时的运行标志与 host 侧 FIA 参数(每次重放必须传入长度);EncoderAclGraphManager 把编码器的 capture/replay 挂到 Ascend FIA graph-task 基础设施上(按 budget 分别捕获/执行);update_encoder_graph_params 在 graph 重放时重绑 fused infer attention 的 host 张量;maybe_compute_actual_seq_lengths 把 cu_seqlens 转成 FIA 需要的 actual_seq_lengths。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\encoder_acl_graph.py
set_encoder_graph_params[9行] 代码量 9 行
get_encoder_graph_params[2行] 代码量 2 行
update_encoder_graph_workspace[4行] 代码量 4 行
get_encoder_forward_context[2行] 代码量 2 行
_reset_encoder_forward_context[6行] Clear replay-time host length fields.
set_encoder_forward_context[19行] Enter encoder graph replay (FIA host args): callers must pass lengths each time.
maybe_compute_actual_seq_lengths[40行] Convert ``cu_seqlens`` to FIA host ``actual_seq_lengths``.
update_encoder_graph_params[74行] Re-bind fused infer attention host tensors inside the encoder NPUGraph (parallel to LLM path).
weak_ref_workspaces[8行] 代码量 8 行
__init__[4行] 代码量 4 行
capture[9行] 代码量 9 行
_capture_budget_graph[41行] 代码量 41 行
_run_budget_graph[49行] 代码量 49 行
worker/model_runner_v1.py查看源码
V1 模型运行器 NPUModelRunner(5368 行,全仓最大文件)。继承 GPUModelRunner 并适配 NPU:设备属性初始化、drafter(投机起草器)装配、Eagle3 辅助层解析、ACL graph 启用判定、DP rank 间元数据同步、PD 分离架构 prefill worker 判定、PP 场景采样 token 后处理;graph_capture 上下文管理器包围图捕获过程。模块级工具:_post_process_cudagraph_mode 在 DP ranks 间取最小 cudagraph 模式保证一致、_get_gpu_model_runner_module_name 定位 MRO 中的 GPUModelRunner 模块、_replace_gpu_model_runner_function_wrapper 对其函数做 NPU 替换包装、update_pass_config 更新编译 pass 配置。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\model_runner_v1.py
graph_capture[28行] `graph_capture` is a context manager which should surround the code that
get_tp_context[2行] 代码量 2 行
_post_process_cudagraph_mode[7行] Synchronize cudagraph_mode across DP ranks by taking the minimum.
_get_gpu_model_runner_module_name[12行] Return the module name of GPUModelRunner found in the MRO.
_torch_cuda_wrapper[52行] 代码量 52 行
_replace_gpu_model_runner_function_wrapper[18行] 代码量 18 行
update_pass_config[7行] 代码量 7 行
__init__[2行] 代码量 2 行
use_dcp[2行] 代码量 2 行
_init_device_properties[2行] 代码量 2 行
_sync_device[2行] 代码量 2 行
reset_encoder_cache[14行] Clear device and score-based encoder cache state.
_set_up_drafter[37行] 代码量 37 行
_get_drafter[2行] 代码量 2 行
_eagle3_uses_aux_hidden_state[12行] 代码量 12 行
_get_eagle3_aux_layers_from_config[15行] 代码量 15 行
_draft_uses_qwen3_gqa_dspark[10行] Return whether the draft expects Kimi's materialized residual.
_use_aclgraph[9行] 代码量 9 行
_sync_metadata_across_dp[39行] 代码量 39 行
get_model[5行] 代码量 5 行
_is_pd_prefill_worker[2行] 代码量 2 行
_apply_pp_sampled_tokens_from_scheduler_output[64行] 代码量 64 行
_update_states[19行] 代码量 19 行
_update_states_after_model_execute[38行] 代码量 38 行
_sync_num_accepted_tokens[17行] Publish accepted counts in current request order after the D2H event.
_pad_query_start_loc_for_fia[48行] This function is only designed to satisfied the constraint that when the layout is TND,
_track_tmp_encoder_cache_refs[11行] 代码量 11 行
_on_request_state_removed[20行] 代码量 20 行
_process_encoder_cache_scheduler_output[42行] 代码量 42 行
_get_encoder_output_from_cache[25行] 代码量 25 行
_clear_finished_encoder_cache_copies[6行] 代码量 6 行
_copy_cpu_encoder_cache_to_device[19行] 代码量 19 行
_cache_encoder_output[40行] 代码量 40 行
_prepare_inputs[419行] :return: tuple[
_build_attn_state[28行] 代码量 28 行
_sanitize_placeholder_input_ids_for_forward[16行] 代码量 16 行
_calc_spec_decode_metadata[65行] 代码量 65 行
_correct_optimistic_seq_lens_cpu[27行] Correct ``optimistic_seq_lens_cpu`` for async spec-decode drift.
_copy_valid_sampled_token_count[21行] 代码量 21 行
propose_draft_token_ids[16行] 代码量 16 行
_log_propose_draft_token_ids_entry[36行] DFX entry probe for propose_draft_token_ids.
_copy_draft_token_ids_to_cpu[41行] 代码量 41 行
take_draft_token_ids[22行] 代码量 22 行
execute_model[438行] 代码量 438 行
sample_tokens[234行] 代码量 234 行
_sample[28行] 代码量 28 行
_bookkeeping_sync[137行] 代码量 137 行
_update_full_graph_params_if_needed[21行] 代码量 21 行
_model_forward[31行] 代码量 31 行
_pad_for_sequence_parallelism[9行] 代码量 9 行
sync_and_slice_intermediate_tensors[30行] 代码量 30 行
sync_and_gather_intermediate_tensors[10行] 代码量 10 行
_determine_batch_execution_and_padding[100行] 代码量 100 行
_build_attention_metadata[310行] :return: tuple[attn_metadata, spec_decode_common_attn_metadata]
_should_build_dummy_attn_metadata[13行] Determine whether attention metadata should be built during dummy_run.
_dummy_run[312行] 代码量 312 行
_dummy_sampler_run[17行] 代码量 17 行
profile_run[15行] 代码量 15 行
eplb_warmup[7行] 代码量 7 行
update_eplb_heat_collection_status[10行] 代码量 10 行
load_model[146行] 代码量 146 行
_start_dump_data[5行] 代码量 5 行
_finalize_dump_data[8行] 代码量 8 行
initialize_kv_cache[69行] Initialize KV cache based on `kv_cache_config`.
_align_memory[5行] 代码量 5 行
initialize_kv_cache_tensors[45行] Initialize the memory buffer for KV cache.
_get_layer_kv_cache_specs[21行] 代码量 21 行
_get_attention_kv_cache_dims[20行] 代码量 20 行
_align_up[2行] 代码量 2 行
_allocate_int8_cache_tensor[22行] Allocate an int8 raw cache tensor.
_allocate_sparse_c8_indexer_tensors[54行] Allocate dsa_k and dsa_k_scale from one aligned int8 raw allocation.
_allocate_kv_cache_tensors[207行] Initializes the KV cache buffer with the correct size. The buffer needs
_adjust_kv_layout[31行] 代码量 31 行
_reshape_kv_cache_tensors[345行] Reshape the KV cache tensors to the desired shape and dtype.
may_reinitialize_input_batch[87行] Re-initialize the input batch if the block sizes are different from
initialize_attn_backend[114行] Initialize the attention backends and attention metadata builders.
get_kv_cache_spec[143行] Generates the KVCacheSpec by parsing the kv cache format from each
_check_and_update_cudagraph_mode[83行] 代码量 83 行
capture_model[11行] Capture NPU graphs and return actual graph pool memory bytes consumed.
_prepare_multimodal_fields[24行] Ensures specific multimodal tensors are on CPU.
_init_kv_zero_meta[14行] One-time precomputation for _zero_block_ids.
dispatch_cudagraph[12行] 代码量 12 行
_get_dcp_metadata[19行] 代码量 19 行
_get_block_table_and_slot_mapping[34行] 代码量 34 行
_build_attn_group_metadata[60行] 代码量 60 行
get_attn_backends_for_group[62行] 代码量 62 行
create_attn_groups[22行] 代码量 22 行
dummy_compute_logits[4行] 代码量 4 行
dummy_drafter_compute_logits[5行] 代码量 5 行
mock_true[2行] 代码量 2 行
backend_supports_kernel_block_size[14行] 代码量 14 行
mock_pass[2行] 代码量 2 行
worker/npu_input_batch.py查看源码
NPUInputBatch(258 行):V1 运行器的输入批次扩展,在 vLLM InputBatch 基础上增加 NPU 专用的批状态字段,构造时按 NPU 需求初始化。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\npu_input_batch.py
__init__[215行] 代码量 215 行
worker/utils.py查看源码
KV 块清零工具(184 行)。AscendKVBlockZeroer 用一个 Triton kernel(_zero_kv_blocks_kernel)单次 launch 清零多个 KV cache 块的全部段(segments):init_meta 预计算地址元数据,zero_block_ids 按块 ID 列表批量清零,用于抢占/释放时快速复位缓存,避免逐块循环。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\utils.py
_zero_kv_blocks_kernel[36行] Zero KV cache blocks across all segments in a single launch.
__init__[7行] 代码量 7 行
init_meta[83行] One-time precomputation for zero_block_ids.
zero_block_ids[32行] Zero the KV cache memory for the given block IDs.
worker/v2/aclgraph_utils.py查看源码
V2 ACL graph 管理工具(299 行)。ModelAclGraphManager 是 Ascend NPU 的 ACL 图管理器:init_breakable_cg_runner 初始化可中断图运行器、run_fullgraph 全图执行、capture 按桶捕获;_prepare_pcp_inputs_to_capture 以与重放一致的 PCP 本地布局构建捕获输入;collect_sorted_captured_token_sizes 收集每张图实际捕获的 token 数;ModelWithContext 包装模型注入 forward context(含 compute_logits/draft logits/Markov embed 等接口转发);model_capture_wrapper 在投机解码捕获期间临时替换 speculator 的模型。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\aclgraph_utils.py
_prepare_pcp_inputs_to_capture[34行] Build graph inputs with the same PCP-local layout used on replay.
collect_sorted_captured_token_sizes[12行] Collect the actual per-graph token counts that will be captured.
_get_graph_update_backend[9行] 代码量 9 行
model_capture_wrapper[7行] Context manager to override speculator's model for speculator capturing.
init_breakable_cg_runner[3行] 代码量 3 行
run_fullgraph[41行] Override run_fullgraph to update full graph params in run_fullgraph.
capture[36行] Capture CUDA graphs for model forward pass.
__init__[24行] 代码量 24 行
forward[14行] 代码量 14 行
get_original_model[2行] 代码量 2 行
compute_logits[3行] 代码量 3 行
compute_draft_logits[2行] 代码量 2 行
markov_embed[2行] 代码量 2 行
markov_bias[2行] 代码量 2 行
map_draft_to_target[2行] 代码量 2 行
worker/v2/attn_utils.py查看源码
V2 运行器注意力工具箱(936 行)。get_kv_cache_spec 构建 Ascend 专属 KV cache 规格;build_attn_metadata/build_attn_state 构建注意力元数据与执行状态;DSV4 布局支持:_adjust_dsv4_kv_layout 调整 KV 布局、_view_dsv4_cache 不做 MLA K/V 切分直接建 DSA 缓存视图、_allocate_sparse_c8_indexer_tensors 从单一对齐 int8 raw 分配中切出 dsa_k 与 dsa_k_scale;_allocate_kv_cache 按配置初始化 KV 缓存大缓冲;_reshape_mamba_kv_cache 为 Mamba 混合模型建连续 per-state 视图;build_attn_metadata_wrapper/build_draft_attn_metadata_factory 为 draft 块包装元数据构建(转发旋转位置编码)。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\attn_utils.py
get_kv_cache_spec[106行] Build Ascend-specific KV cache specs for v2 worker patching.
build_attn_metadata[4行] 代码量 4 行
build_attn_state[39行] Build attention state for npu's attention backend.
_get_layer_kv_cache_specs[10行] 代码量 10 行
_is_dsv4_model[4行] 代码量 4 行
_get_attention_kv_cache_dims[13行] 代码量 13 行
_adjust_dsv4_kv_layout[28行] 代码量 28 行
_view_dsv4_cache[52行] Create DSA cache views without applying normal MLA K/V splitting.
_align_memory[5行] 代码量 5 行
_align_up[2行] 代码量 2 行
_allocate_int8_cache_tensor[23行] Allocate an int8 raw cache tensor.
_allocate_sparse_c8_indexer_tensors[49行] Allocate dsa_k and dsa_k_scale from one aligned int8 raw allocation.
_allocate_kv_cache[142行] Initialize the KV cache buffer with the correct size. The buffer needs to be
_reshape_mamba_kv_cache[28行] Create the contiguous per-state views used by the Ascend v1 runner.
_reshape_kv_cache_v2[171行] 代码量 171 行
build_attn_metadata_wrapper[8行] Context manager to override attention metadata building for Ascend NPUs.
build_draft_attn_metadata_factory[20行] Wrap build_attn_metadata to forward rotary positions for the draft block.
worker/v2/block_table.py查看源码
AscendBlockTables(61 行):V2 运行器的块表集合,按 KV cache 组组织各请求的块表,是 v2/block_table.py 对 V1 BlockTable 的轻量替换。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\block_table.py
__init__[36行] 代码量 36 行
worker/v2/eplb.py查看源码
专家并行负载均衡(EPLB)控制器 V2(97 行)。AscendEPLBController 在标准 EPLB 状态上叠加按阶段过滤的负载收集:is_eplad_load_collection_phase_matched 判断当前批次是否属于配置的收集阶段(prefill/decode),prepare_load/set_batch_phase/prepare_forward/setup_from_mapping 管理负载统计与专家映射应用;_unwrap_moe 解包获取真实 MoE 模块。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\eplb.py
is_eplb_load_collection_phase_matched[9行] Return whether the batch belongs to the configured collection phase.
_unwrap_moe[4行] 代码量 4 行
__init__[9行] 代码量 9 行
prepare_load[5行] 代码量 5 行
set_batch_phase[5行] 代码量 5 行
prepare_forward[18行] 代码量 18 行
setup_from_mapping[20行] 代码量 20 行
worker/v2/input_batch.py查看源码
V2 输入批(142 行)。AscendInputBatch 在 vLLM V2 InputBatch 基础上增加 NPU 字段;AscendInputBuffers 预分配输入缓冲(positions/seq_lens 等 device 张量),减少每步分配开销。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\input_batch.py
__init__[31行] 代码量 31 行
make_dummy[28行] Override the make_dummy method to calculate seq_lens_np.
worker/v2/model_runner.py查看源码
V2 模型运行器 NPUModelRunner(995 行)。全新架构的执行核心:execute_model 驱动每步推理、sample_tokens/sample 采样、profile_run/_dummy_run 性能剖析与形状探测、initialize_kv_cache 初始化 KV 缓存、_lmhead_tp_max_num_logits 计算 LM head TP 分片下的最大 logits 数、_pad_query_start_loc_for_fia 为 FIA 填充 query start loc;pcp_manager_cls 集成 AscendPCPManager,_use_ascend_pcp_manager_for_vllm_0271 兼容 vLLM 0.27.1 的 legacy PCP builder;graph_manager_wrapper 上下文用于替换图管理器。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\model_runner.py
_use_ascend_pcp_manager_for_vllm_0271[21行] Make the legacy vLLM PCP builder instantiate the Ascend manager.
graph_manager_wrapper[47行] Context manager to override graph manager.
__init__[103行] 代码量 103 行
pcp_manager_cls[2行] 代码量 2 行
sample_tokens[8行] 代码量 8 行
initialize_kv_cache[9行] 代码量 9 行
execute_model[39行] 代码量 39 行
profile_run[16行] Override GPUModelRunner.profile_run for Ascend NPUs.
_lmhead_tp_max_num_logits[8行] Logits row capacity shared by every rank of the lmhead-TP group.
sample[55行] Override GPUModelRunner.sample for lmhead TP.
_dummy_run[35行] Join the LM-head collectives on dummy batches for lmhead TP.
postprocess_sampled[24行] Override GPUModelRunner.postprocess_sampled for Ascend NPUs.
_copy_num_computed_tokens_to_cpu[13行] 代码量 13 行
_update_seq_lens_cpu[24行] 代码量 24 行
_pad_query_start_loc_for_fia[40行] This function is only designed to satisfied the constraint that when the layout is TND,
prepare_inputs[218行] Override GPUModelRunner.prepare_inputs for Ascend NPUs.
factory[17行] 代码量 17 行
worker/v2/model_states/__init__.py查看源码
V2 模型状态工厂(71 行)。init_asecnd_model_state 按模型类型/配置选择并实例化对应的 AscendModelState(默认或 Mamba 混合),把模型、encoder cache、设备绑定到状态对象。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\model_states\__init__.py
init_asecnd_model_state[44行] 代码量 44 行
worker/v2/model_states/default.py查看源码
默认模型状态 AscendModelState(106 行):V2 运行器中封装模型前向的注意力准备逻辑(prepare_attn 构建并注入注意力元数据),是大多数模型的标准状态。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\model_states\default.py
prepare_attn[67行] Override prepare_attn method because `build_attn_metadata` is different from vllm.
worker/v2/model_states/mamba_hybrid.py查看源码
Mamba 混合模型状态 AscendMambaHybridModelState(106 行):在默认状态基础上,为 Mamba-Attention 混合架构定制 prepare_attn——注意力元数据构建需区分 Mamba 层与注意力层的 KV 组。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\model_states\mamba_hybrid.py
prepare_attn[63行] 代码量 63 行
worker/v2/pcp_manager.py查看源码
Prefill Context Parallel(PCP)管理器 V2(218 行)。AscendPCPManager 在 PCP 各 rank 间切分 prefill 批次:validate_config 校验配置、partition_batch 做批次切分、prepare_slot_mappings 生成本地 KV 写入的 slot 映射、build_attention_context 产出规范全局视图 AscendPCPAttentionContext(供注意力后端构建本地元数据与全局缓存写视图,如 DSA-PCP 的 from_local_metadata)。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\pcp_manager.py
validate_config[31行] Validate the graph-safe Ascend MRV2 PCP configuration.
partition_batch[61行] Partition the batch and update Ascend-specific local metadata.
prepare_slot_mappings[39行] Pad PCP slot mappings to the fixed FULL-decode graph layout.
build_attention_context[37行] Build the PCP context consumed by attention metadata builders.
worker/v2/pp_utils.py查看源码
V2 流水线并行工具(196 行)。解决投机解码 × PP 的兼容:SpecPPSupport 描述每种投机方法在 PP 下的能力、resolve_spec_pp_support 按配置解析、bypass_upstream_spec_pp_guard 让上游 runner 以 PP=1 初始化绕过其 Spec+PP 守卫、restore_pp_after_upstream_init 再恢复真实 PP 状态;PPTransportDataType 定义 PP rank 间经 IntermediateTensors 传输的数据类型,make_empty_intermediate_tensors 包装张量工厂附加接收缓冲,get/add_pp_transport_tensors/buffers 管理按类型的传输张量与预分配接收缓冲。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\pp_utils.py
resolve_spec_pp_support[16行] Return the registered Spec+PP capabilities for this configuration.
bypass_upstream_spec_pp_guard[17行] Initialize the upstream runner as PP=1 to bypass its Spec+PP guard.
restore_pp_after_upstream_init[19行] Restore PP state skipped while the upstream runner initialized as PP=1.
make_empty_intermediate_tensors[23行] Wrap a model's PP tensor factory with auxiliary receive buffers.
_get_transport_key_prefix[2行] 代码量 2 行
get_pp_transport_tensors[16行] Return tensors of one transport type in their original order.
add_pp_transport_tensors[10行] Add tensors of one transport type to a PP payload.
add_pp_transport_buffers[11行] Add empty receive buffers for one PP transport data type.
wrapped_tensor_factory[15行] 代码量 15 行
worker/v2/sample/apply_top_k_top_p.py查看源码
V2 采样的 top-k/top-p 过滤入口(14 行):apply_top_k_top_p_npu 对 logits 应用 NPU 实现的 top-k/top-p 截断,是 vLLM 采样管线中该步骤的 Ascend 替换点。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\sample\apply_top_k_top_p.py
apply_top_k_top_p_npu[9行] 代码量 9 行
worker/v2/sample/bad_words.py查看源码
违禁词过滤(185 行)。Triton kernel _bad_words_kernel 按请求展开索引查其已生成 token 序列并屏蔽命中的违禁词末 token;apply_bad_words 组织输入(违禁词 token ID、偏移、数量、全 token 序列)并 launch kernel,逐请求把违禁续写位置的 logits 置 -inf。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\sample\bad_words.py
_bad_words_kernel[99行] Optimized bad words filtering kernel for Ascend NPU.
apply_bad_words[54行] Apply bad words filtering to logits.
worker/v2/sample/gumbel.py查看源码
Gumbel 采样(219 行)。apply_temperature 用 Triton kernel 按请求温度缩放 logits;gumbel_sample 先做温度处理,再用 _gumbel_sample_kernel 对处理后的 logits 做 Gumbel 扰动并取 argmax(支持种子与位置偏移保证可复现),是解码期随机采样的 NPU 路径。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\sample\gumbel.py
_temperature_kernel[23行] 代码量 23 行
apply_temperature[27行] Args:
_gumbel_sample_kernel[76行] 代码量 76 行
gumbel_sample[53行] 代码量 53 行
worker/v2/sample/logprob.py查看源码
logprob 计算(169 行)。compute_token_logprobs 用 _topk_log_softmax_kernel 对采样 token 计算对数概率;compute_topk_logprobs 用 _ranks_kernel 等 kernel 计算每个请求 top-k 候选的 logprob 与 token ID(写入预分配的 state 缓冲),服务 logprobs 请求参数。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\sample\logprob.py
_topk_log_softmax_kernel[37行] 代码量 37 行
compute_token_logprobs[17行] 代码量 17 行
_ranks_kernel[29行] 代码量 29 行
compute_topk_logprobs[51行] 代码量 51 行
worker/v2/sample/min_p.py查看源码
min_p 过滤(91 行)。apply_min_p 用 Triton kernel 对每请求计算概率阈值(最大概率×min_p),低于阈值的 logits 置 -inf,避免逐请求 host 循环。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\sample\min_p.py
_min_p_kernel[44行] 代码量 44 行
apply_min_p[19行] 代码量 19 行
worker/v2/sample/penalties.py查看源码
采样惩罚(225 行)。apply_penalties 用 Triton kernel 应用重复惩罚(repetition_penalty)与频率惩罚(frequency_penalty):按已生成 token 计数调整 logits;bincount kernel 统计 prompt+生成 token 的出现次数(prompt 与生成段分别掩码),为惩罚计算提供计数输入。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\sample\penalties.py
_penalties_kernel[89行] 代码量 89 行
apply_penalties[33行] 代码量 33 行
_bincount_kernel[45行] 代码量 45 行
bincount[26行] 代码量 26 行
worker/v2/spec_decode/__init__.py查看源码
V2 投机解码入口(58 行)。init_speculator 覆盖 vLLM GPU 版本的 speculator 工厂:按 vllm_config 中的投机方法(Eagle/MTP/DFlash/DSpark/自回归等)实例化对应的 Ascend speculator 并完成设备初始化。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\spec_decode\__init__.py
init_speculator[36行] Override GPU init_speculator for Ascend NPUs.
worker/v2/spec_decode/autoregressive/aclgraph.py查看源码
自回归投机解码的 ACL graph 管理器(179 行)。AutoRegressiveAclGraphManager 管理draft 模型多步解码图的捕获(capture)与全图执行(run_fullgraph),按 token 数分桶以覆盖 draft 循环的不同形状。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\spec_decode\autoregressive\aclgraph.py
__init__[33行] 代码量 33 行
capture[53行] Capture ACL graphs for autoregressive speculative decoding.
run_fullgraph[53行] Replay the draft ACL graph and update its attention parameters.
create_forward_fn[26行] 代码量 26 行
worker/v2/spec_decode/autoregressive/speculator.py查看源码
自回归投机解码共享循环(507 行)。AscendAutoRegressiveSpeculator 是 AscendEagle/AscendMTPSpeculator 共用的 NPU 投机循环:_create_draft_vllm_config 构建 draft 模型配置、propose 驱动 propose-verify 流程、_prefill 处理 draft prefill、_multi_step_decode 多步 draft 解码、_build_draft_attn_metadata 系列构建/更新 draft 注意力元数据(含 decode 期增量更新与 seq lens CPU 计算);init_cudagraph_manager 接 ACL graph;torch_gather_wrapper 上下文替换 torch.gather 以适配 NPU 算子行为差异。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\spec_decode\autoregressive\speculator.py
gather[5行] 代码量 5 行
torch_gather_wrapper[8行] Context manager to override torch.gather for Ascend NPUs.
__init__[33行] Override the upstream __init__ for Ascend NPUs.
_create_draft_vllm_config[11行] Build the runtime config used while executing the draft model.
init_cudagraph_manager[9行] 代码量 9 行
propose[54行] Override GPU EagleSpeculator.propose for Ascend NPUs,
set_attn[29行] 代码量 29 行
capture[39行] 代码量 39 行
_run_model[19行] Override AutoRegressiveSpeculator._run_model for Ascend NPUs.
_generate_draft[22行] Thin override: delegate to upstream single-step ``_generate_draft``,
_multi_step_decode[21行] Minimal override to handle the merged multi-step graph in FULL mode.
_prefill[26行] 代码量 26 行
_build_draft_attn_metadata[32行] 代码量 32 行
build_draft_attn_metadatas[18行] Build draft_attn_metadatas for partial-merged draft graph.
_init_decode_draft_attn_metadatas[43行] Initialize per-step decode attention metadata for graph mode.
_update_decode_attn_metadata[27行] Update per-step decode attention metadata on Ascend.
_calc_next_seq_lens_cpu[8行] 代码量 8 行
_get_seq_lens_cpu[12行] Return the target sequence lengths for the padded graph batch.
worker/v2/spec_decode/dflash/aclgraph.py查看源码
DFlash 投机解码的 ACL graph 管理器(122 行)。DFlashAclGraphManager 管理 DFlash draft 路径的图捕获与全图重放,参数与桶策略对齐 DFlash 的分组卷积候选生成流程。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\spec_decode\dflash\aclgraph.py
__init__[29行] 代码量 29 行
capture[23行] Capture ACL graphs for DFlash.
run_fullgraph[42行] Override run_fullgraph to update full graph params in run_fullgraph.
worker/v2/spec_decode/dflash/speculator.py查看源码
DFlash 投机解码器 AscendDFlashSpeculator(452 行):基于分组卷积多 token 预测的投机路径。propose 驱动候选生成与验证;build_draft_attn_metadatas/_update_draft_attn_metadata 管理 draft 注意力元数据;init_cudagraph_manager 接入 DFlashAclGraphManager;set_attn 绑定目标模型注意力后端。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\spec_decode\dflash\speculator.py
build_draft_attn_metadatas[13行] 代码量 13 行
_update_draft_attn_metadata[17行] Rebuild ``actual_seq_lengths_q`` from the padded request count,
__init__[2行] 代码量 2 行
init_cudagraph_manager[7行] 代码量 7 行
set_attn[36行] 代码量 36 行
propose[39行] 代码量 39 行
_prepare_dflash_inputs_kernel_ascend[147行] 代码量 147 行
worker/v2/spec_decode/dspark/speculator.py查看源码
DSpark 投机解码器 AscendDSparkSpeculator(196 行):基于 Markov/置信度头的 draft 路径。load_draft_model 加载 draft 权重、propose 生成候选序列、build_draft_attn_metadatas/_update_draft_attn_metadata 维护 draft 元数据、init_cudagraph_manager 接图管理器。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\spec_decode\dspark\speculator.py
__init__[3行] 代码量 3 行
load_draft_model[19行] 代码量 19 行
init_cudagraph_manager[7行] 代码量 7 行
set_attn[31行] 代码量 31 行
build_draft_attn_metadatas[23行] 代码量 23 行
_update_draft_attn_metadata[19行] Rebuild ``actual_seq_lengths_q`` from the padded request count,
propose[45行] 代码量 45 行
worker/v2/spec_decode/eagle/speculator.py查看源码
Eagle 投机解码器 AscendEagleSpeculator(44 行):复用 AscendAutoRegressiveSpeculator 的完整 NPU 循环,仅定制 _create_draft_vllm_config 以加载 Eagle 风格 draft 模型配置。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\spec_decode\eagle\speculator.py
_create_draft_vllm_config[14行] 代码量 14 行
worker/v2/spec_decode/rejection_sampler_utils.py查看源码
拒绝采样工具(507 行)。rejection_sample 实现投机解码的验证采样:对目标/草稿 logits 逐位置比较,接受概率内的 draft token、拒绝处从目标分布重采样;配套 Triton kernel:_npu_gumbel_block_argmax(分块 Gumbel argmax)、_resample_kernel(重采样)、_probabilistic_rejection_kernel(概率拒绝判定),全部在设备端完成避免 host 往返。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\spec_decode\rejection_sampler_utils.py
_npu_gumbel_block_argmax[45行] 代码量 45 行
_resample_kernel[107行] 代码量 107 行
_probabilistic_rejection_kernel[136行] 代码量 136 行
rejection_sample[178行] 代码量 178 行
worker/v2/states.py查看源码
V2 请求状态 AscendRequestState(71 行):在 vLLM 请求状态上扩展 NPU 字段,add_request 完成请求级状态初始化,供运行器跟踪每个请求的执行上下文。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\states.py
__init__[27行] 代码量 27 行
add_request[17行] 代码量 17 行
worker/v2/utils.py查看源码
V2 运行器上下文包装(61 行)。提供三个上下文管理器/函数:torch_cuda_wrapper 把 torch.cuda 调用映射到 torch.npu、communicator_switch 切换通信器实现、torch_npu_graph_wrapper 适配 graph 相关 API,是 V2 运行器 GPU→NPU 兼容层的组成部分。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\v2\utils.py
torch_cuda_wrapper[20行] 代码量 20 行
communicator_switch[14行] 代码量 14 行
torch_npu_graph_wrapper[10行] 代码量 10 行
worker/worker.py查看源码
NPUWorker(1152 行):V1 worker 本体,vLLM Worker 的 NPU 实现。设备生命周期:init_device/_init_device 初始化 NPU 与设备属性、initialize_cache 初始化 KV 缓存、sleep/wake_up 睡眠唤醒(释放/恢复显存);权重传输引擎:_check_weight_transfer_engine/init_weight_transfer_engine/start_weight_update/update_weights/finish_weight_update 支持训练侧增量权重拉取更新;_apply_kv_offload_decode_memory_constraints 应用 KV offload 场景的 decode 内存约束;uninstall_static_kernel 卸载静态 kernel;parse_text_output 解析设备端文本输出。
D:\demo\202609\vllm-ascend\vllm-ascend-main\vllm_ascend\worker\worker.py
parse_text_output[8行] 代码量 8 行
__init__[89行] Initialize the worker for Ascend.
uninstall_static_kernel[31行] 代码量 31 行
sleep[30行] 代码量 30 行
wake_up[27行] 代码量 27 行
_check_weight_transfer_engine[5行] 代码量 5 行
init_weight_transfer_engine[6行] Initialize the HCCL weight transfer process group with the trainer.
_check_nz_disabled[8行] 代码量 8 行
start_weight_update[14行] Begin a new weight update; prepares the model for layerwise reload.
update_weights[14行] Receive a chunk of weights from the trainer and load them in place.
finish_weight_update[10行] Finish the current weight update; runs layerwise postprocessing.
shutdown[14行] 代码量 14 行
initialize_cache[3行] 代码量 3 行
_init_device[103行] 代码量 103 行
init_device[20行] 代码量 20 行
_apply_kv_offload_decode_memory_constraints[35行] 代码量 35 行
determine_available_memory[94行] Profiles the peak memory usage of the model to determine how much
log_memory_stats[11行] Profiles the torch reserved memory, torch allocated memory in execute_model().
execute_model[67行] 代码量 67 行
sample_tokens[11行] 代码量 11 行
load_model[24行] 代码量 24 行
compile_or_warm_up_model[98行] 代码量 98 行
_warm_up_atb[5行] 代码量 5 行
get_model[2行] 代码量 2 行
profile_prefill_latency[70行] Profile prefill latency for a given number of tokens.
get_kv_connector_handshake_metadata[20行] Get KV connector metadata from this worker if available.
_get_layerwise_kv_cache_memory_info[31行] 代码量 31 行
get_kv_cache_spec[12行] 代码量 12 行
update_max_model_len[12行] Update max_model_len after auto-fit to NPU memory.
initialize_from_config[30行] Allocate NPU KV cache with the specified kv_cache_config.
profile[29行] 代码量 29 行
add_lora[2行] 代码量 2 行
remove_lora[2行] 代码量 2 行
list_loras[2行] 代码量 2 行
pin_lora[2行] 代码量 2 行
reset_encoder_cache[2行] 代码量 2 行
execute_dummy_batch[4行] 代码量 4 行
_init_worker_distributed_environment[14行] Initialize the distributed environment.
get_supported_pooling_tasks[2行] 代码量 2 行
get_supported_tasks[2行] 代码量 2 行
take_draft_token_ids[2行] 代码量 2 行
update_config[2行] 代码量 2 行
reload_weights[2行] 代码量 2 行
check_health[24行] 代码量 24 行
signal_handler[6行] 代码量 6 行
首页