attention\__init__.py
查看源码attention 子包的包标记文件。attention 包收录 NPU 上全部注意力后端实现:通用 FlashAttention(attention_v1)、MLA、SFA 稀疏注意力、DSA(DeepSeek-V4)、FA3、KV offload,以及 context_parallel 下的 DCP/PCP 上下文并行变体。
类: 无
attention\attention_mask.py
查看源码注意力掩码构建器(70 行)。AttentionMaskBuilder 按最大序列长度生成并缓存下三角掩码(_generate_attn_mask),提供普通掩码(get_attn_mask)、splitfuse 掩码(get_splitfuse_attn_mask)与统一入口 get_attention_mask,供不走 fused 算子的注意力路径使用。
类: 无
func_generate_attn_mask[10行] 内部:生成 attention mask 张量
func__init__[5行] 初始化类实例(绑定配置、参数、模块)
funcget_attn_mask[8行] 对外接口:返回 attention mask
funcget_splitfuse_attn_mask[6行] 返回 SplitFuse 阶段 attention mask
funcget_attention_mask[14行] 统一入口:按当前阶段返回对应的 attention mask
attention\attention_v1.py
查看源码NPU 通用注意力后端(2223 行,attention 包核心)。AscendAttentionBackend 定义后端元信息(名称/KV cache 形状/支持 PCP)与 swap/copy blocks;AscendAttentionMetadataBuilder 把 vLLM 的 CommonAttentionMetadata 转成 AscendMetadata(含 decode/prefill 拆分、批重排、PCP 元数据、graph capture 支持);AscendAttentionBackendImpl 实现前向:full graph FIA(fused infer attention)/PA(paged attention)路径、chunked prefill 分段、编码器注意力、KV cache 写入(do_kv_cache_update/reshape_and_cache 及 PCP 变体);AscendC8AttentionBackendImpl 为 INT8 KV cache(C8/QuaRot)模型提供独立实现:分页 KV 反量化到稠密、激活量化、专用 decode/chunked prefill 前向。
类: AscendAttentionBackend, AscendAttentionState, AscendAttentionMetadataBuilder, AscendAttentionBackendImpl, AscendC8AttentionBackendImpl
funcget_name[2行] 返回后端的注册名称
funcget_impl_cls[6行] 返回 attention 实现类
funcget_builder_cls[6行] 返回 attention metadata builder 类
funcsupports_pcp[5行] 返回是否支持 prefill context parallel
funcget_kv_cache_shape[8行] 返回 KV 缓存张量形状
funcswap_blocks[12行] 交换两个 block group 的内容(prefix cache)
funccopy_blocks[12行] 拷贝若干 KV cache block
funcget_supported_kernel_block_sizes[2行] 返回支持的 kernel 块大小列表
func__init__[51行] 初始化类实例(绑定配置、参数、模块)
funcget_cudagraph_support[8行] 返回 backend 对 CUDA graph 捕获的支持程度
funcreorder_batch[2行] 按 chunked-prefill 需求重排 batch
func_split_decodes_and_prefills[9行] 把 batch 拆为 decode / prefill 子集
func_build_backend_metadata[17行] Extension point for layouts such as DCP.
funcbuild[109行] 构造 attention metadata
func_finalize_pcp_metadata[22行] 完成 PCP metadata 的填充
funcbuild_for_graph_capture[21行] 为 cudagraph 捕获构造 mock metadata
func_graph_metadata_layer_name[5行] 返回当前 graph 的 metadata 层名
funcupdate_graph_params[370行] DCP/PCP 模式下更新 graph 参数
funcextract_layer_index[3行] 从层名称中提取数字索引
funcis_direct_target_attn_key[8行] 判断当前 key 是否是直接目标 attention key
funcprocess_weights_after_loading[2行] 权重加载后的后处理(如 layout cast、NZ 转换)
funcfull_graph_fia[171行] FIA 全图 forward
funcfull_graph_fia_v2[125行] FIA 全图 forward (V2)
funcfull_graph_pa[65行] PA 全图 forward
func_get_fia_params[59行] 取得 FIA forward 参数
funcforward_fused_infer_attention[141行] FIA 融合 forward
func_forward_fia_chunked_prefill_split[80行] ChunkedPrefill with mixed prefill/decode: run decode and prefill in
funcforward_paged_attention[20行] PA 物理 forward
func_forward_encoder_attention[23行] encoder 阶段 attention forward
funcdo_kv_cache_update[21行]
funcreshape_and_cache[31行]
func_reshape_and_cache_pcp[38行]
funcforward_impl[22行] attention 前向底层实现
funcforward[70行] attention 前向入口
func_nz_5d_view[4行] View a KV cache tensor in NZ 5D layout: (num_blocks, num_kv_heads, head_size//nz, block_size, nz).
func_prepare_c8_scales[34行] Shard per-channel C8 scales/offsets to this TP rank and pre-compute
func_shard_and_reshape[13行]
func_dequant_paged_kv_to_dense[47行] Gather paged INT8 KV blocks and dequantize.
func_quantize_kv_to_int8[22行] Quantize K/V from float to INT8 using static per-channel C8 scales.
func_forward_c8_decode[37行] C8 decode via FIA V1 BNSD with native paged INT8 KV + perchannel antiquant.
func_forward_c8_chunked_prefill[100行] C8 ChunkedPrefill: decode via FIA V1 BNSD paged INT8 (zero gather),
func_forward_c8_fused_infer_attention[58行] C8 FIA V1 TND for prefill states (PrefillNoCache uses float KV directly,
func_reshape_and_cache[36行]
attention\dsa_attn_kv_plan.py
查看源码DeepSeek-V4 DSA 注意力-KV 执行方案的中心化决策(182 行)。根据硬件(A5/Ascend950)与配置决定 KV cache dtype(resolve_dsv4_cache_dtype/get_dsv4_attn_kv_dtype)、是否启用 BF16 SparseFlashMla(is_a5_bf16_kv_enabled);DsaAttnKvPlan 封装一套执行参数:稀疏注意力算子与元数据算子的选择、slot_mapping 是否需拆成(块号,块内偏移)二维格式、压缩 KV 的 scatter 写入路径(SparseFlashMla 走 npu_scatter_nd_update_,量化 epilogue 走 kv_compress_epilog 算子)。get_dsa_attn_kv_plan 返回 A5 BF16 或上游兼容 FP8 方案。
类: 无
func_supports_dsv4_compressed_cache[2行] 判断当前硬件是否支持 DSV4 压缩 cache
funcresolve_dsv4_cache_dtype[12行] 依据模型 dtype 解析 DSV4 cache 实际 dtype
funcis_a5_bf16_kv_enabled[13行] 判断 A5 设备是否启用 BF16 KV 路径
funcget_dsv4_attn_kv_dtype[7行] 返回 DSV4 attention KV 的目标 dtype
funcget_dsa_sparse_attn_metadata_op[2行] 返回 DSA 稀疏 attention metadata 算子
funcget_dsa_sparse_attn_metadata_kwargs[5行]
funcget_dsa_sparse_attn_op[2行] 返回 DSA 稀疏 attention 计算算子
funcget_dsa_sparse_attn_base_kwargs[2行]
funcadd_dsa_sparse_attn_extra_kwargs[3行]
funcget_dsa_compressor_slot_mapping_format[2行]
funcformat_dsa_slot_mapping[8行]
funcdsa_kv_compress_scatter[25行]
funcget_dsa_attn_kv_plan[45行] 返回当前配置对应的 DSA KV cache 布局
DSA(DeepSeek 稀疏注意力)后端族(1709 行)。定义 5 个后端变体:AscendDSABackend(基类)、C4/C128(不同压缩比缓存)、SWA(滑窗)、C4State/C128State(带 state 缓存)。AscendDSAMetadataBuilder 构建统一请求元数据(AscendDSAReqMetadata):SAS 稀疏元数据、QLI 量化 lightning indexer 元数据、DSpark 滑窗可见 slot 索引、Hadamard 旋转初始化、draft 模式支持;AscendDSAImpl 实现前向:MLA prolog 单流/多流、压缩器 topk 选择、稀疏注意力计算、o_proj 输出(含 A5 FP8 量化路径、oproj TP 权重切换路径,用静态 buffer 保证 ACL graph 重放时 HCCL 通信地址稳定)。
类: AscendDSABackend, AscendDSAC4Backend, AscendDSAC128Backend, AscendDSASWABackend, AscendDSAC4StateBackend, AscendDSAC128StateBackend, AscendDSAMetadataBuilder, AscendDSAImpl
funcdsv4_dsa_overlap_stream[5行] 获取 DSV4 与 DSA 重叠计算用的 NPU 流(懒初始化)
func_is_w8a8_dynamic[7行] 判断线性层是否使用 AscendW8A8Dynamic 量化方法
func_has_weight_scale[2行] 判断线性层是否携带 weight_scale 张量
func_dsa_layout_kv[2行] 返回当前 VllmConfig 对应的 KV cache 布局字符串
func_dsa_swa_only_cmp_ratio[5行] BF16 SWA-only 场景下返回 0,否则保留主模型的压缩比
funcget_name[2行] 返回后端的注册名称
funcget_builder_cls[16行] 返回 attention metadata builder 类
funcget_kv_cache_shape[8行] 返回 KV 缓存张量形状
funcget_scale_shape[2行] 返回 scale 张量形状
funcget_impl_cls[16行] 返回 attention 实现类
funcget_supported_kernel_block_sizes[4行] 返回支持的 kernel 块大小列表
func_require_req_metadata[3行] 校验 builder 是否已设置请求级 metadata
funcget_dspark_sparse_sas_window[5行] 计算 DSpark 稀疏 SAS 窗口大小
func_aligned_dspark_index_width[3行] 返回对齐到硬件要求后的 DSpark index 宽度
funcbuild_dspark_swa_indices[49行] 构造 DSpark sliding window 索引表
func__init__[61行] 初始化类实例(绑定 vllm_config、layer_names、device)
func_init_hadamard[20行] 初始化 Hadamard 旋转矩阵
funcget_cudagraph_support[8行] 返回 backend 对 CUDA graph 捕获的支持程度
funcreorder_batch[46行] DSA 专用 batch 重排
funcset_num_actual_tokens[5行] 写入实际 token 数到 metadata
func_num_compressor_metadata_rows[4行]
funcbuild_for_cudagraph_capture[8行] Delegate to build() because DSA needs shared request metadata.
funcbuild[85行] 构造 attention metadata
func_build_sas_metadata[54行]
func_build_qli_metadata[34行]
funcbuild_req_metadata[113行]
funcbuild_for_drafting[47行] 为 draft 模型构造 metadata
funcbuild_req_metadata_for_drafting[110行]
funcbuild_for_graph_capture[20行] 为 CUDA graph 捕获构造 mock metadata
func_get_layer_metadata[35行]
funcupdate_graph_params[10行] DCP/PCP 模式下更新 graph 参数
funcprocess_weights_after_loading[6行] 权重加载后的后处理
func_forward_o_proj[111行]
func_prepare_caches_before_attention[9行] Prepare cache updates and report whether local writes can be skipped.
func_get_o_proj_input_shape[9行]
funcforward[65行] attention 前向入口
func_mla_prolog_single_stream[84行] Run the MLA prolog on the current stream.
func_mla_prolog_multistream[116行] 3-block multi-stream: 3-stage CV parallel + serial tail
func_maybe_update_compressed_caches_and_select_topk[69行] Update compressed caches and return Indexer top-k indices.
funccompute_attention_compressed_kv[6行]
funcscatter_attention_compressed_kv[10行]
func_forward_attention[115行]
FA3(FlashAttention v3 接口)后端的轻量封装(144 行)。AscendFABackend 提供后端元信息与 KV cache 形状;AscendFAImpl 把 vLLM 的 flash_attn_with_kvcache 调用适配到 NPU 实现(_flash_attn_with_kvcache)并在 forward_impl 中按元数据分发,适用于直接使用 FA 接口的模型。
类: AscendFABackend, AscendFAImpl
func__init__[17行] 初始化 AscendFAImpl(校验参数)
funcget_name[2行] 返回后端的注册名称
funcget_impl_cls[2行] 返回 attention 实现类
funcget_builder_cls[2行] 返回 attention metadata builder 类
funcget_kv_cache_shape[8行] 返回 KV 缓存张量形状
funcget_supported_kernel_block_sizes[2行] 返回支持的 kernel 块大小列表
func_flash_attn_with_kvcache[36行] 调用 flash_attn_npu_v3 的 flash_attn_with_kvcache
funcforward_impl[47行] 执行 attention 前向(区分 decode/prefill)
SFA indexer 缓存独立分层的占位后端(93 行)。当 SFA 的 indexer K/scale 缓存作为独立 KV cache group 分层管理时使用:AscendSFAIndexerBackend 提供后端元信息(实际计算由主 SFA 后端完成),AscendSFAIndexerMetadataBuilder 只构建缓存写入所需的元数据(build 填充 slot 映射),不做注意力计算。
类: AscendSFAIndexerBackend, AscendSFAIndexerMetadataBuilder
funcget_impl_cls[2行] 返回 attention 实现类
funcsupports_pcp[2行] 返回是否支持 prefill context parallel
funcget_name[2行] 返回后端的注册名称
funcget_builder_cls[2行] 返回 attention metadata builder 类
funcget_kv_cache_shape[8行] 返回 KV 缓存张量形状
funcget_supported_kernel_block_sizes[2行] 返回支持的 kernel 块大小列表
func__init__[8行] 初始化元数据构建器
funcget_cudagraph_support[6行] 返回 backend 对 CUDA graph 捕获的支持程度
funcbuild[7行] 构造 attention metadata
MLA(Multi-head Latent Attention)后端(2087 行,DeepSeek 系列模型主力路径)。元数据体系:ChunkedContextMetadata(chunked prefill 上下文)、AscendMLAPrefillMetadata/AscendMLADecodeMetadata/AscendMLAMetadata、PCP 专用元数据;AscendMLAMetadataBuilder 处理 chunked prefill workspace 估算、MTP 场景 q 长度填充、prefill/decode 元数据分别构建;AscendMLAImpl 实现前向:fused 融合预处理(_process_weights_for_fused 把 fused_qkv_a_proj/q_proj 权重转成 prolog 消耗的 FRACTAL_NZ 格式并处理量化 scale)、mla_preprocess_decode/prefill(q/kv 投影 + RoPE + KV 写入)、FA3 与 PA 两条前向路径、chunked prefill 上下文重组织(_reorg_kvcache/_compute_prefill_context);AscendMLAPCPImpl 支持 prefill 上下文并行(保留完整 PCP cache 写槽位)。
类: AscendMLABackend, AscendMLAPCPMetadata, AscendMLAMetadataBuilder, AscendMLAPCPMetadataBuilder, DecodeMLAPreprocessResult, PrefillMLAPreprocessResult, AscendMLAImpl, AscendMLAPCPImpl
func_npu_mla_prolog_v3_no_rope[5行] 调用 AscendC MLA prolog(v3)算子,可省略 RoPE 入参
funcget_name[2行] 返回后端的注册名称
funcget_builder_cls[12行] 返回 attention metadata builder 类
funcget_kv_cache_shape[8行] 返回 KV 缓存张量形状
funcget_impl_cls[12行] 返回 attention 实现类
funcget_supported_kernel_block_sizes[2行] 返回支持的 kernel 块大小列表
func__post_init__[2行] MLA dataclass 后置初始化
func__init__[65行] 初始化 MLA backend 或 metadata builder
funcdetermine_chunked_prefill_workspace_size[2行] 估算 chunked prefill workspace 大小
funcget_cudagraph_support[8行] 返回 MLA backend 对 CUDA graph 捕获支持
funcreorder_batch[46行] MLA 专用 batch 重排
funcpad_actual_seq_len_q_mtp_enable_pad[44行] MTP 启用 padding 时 pad 实际序列长度
funcpad_actual_seq_len_q_mtp_disable_pad[21行] MTP 禁用 padding 时直接使用原长度
funcset_num_actual_tokens[5行] 写入实际 token 数到 metadata
funcbuild[40行] 构造 MLA attention metadata
funcbuild_chunked_metadata[43行] 为 chunked prefill 构造 MLA metadata
funcget_block_table_size[11行] 返回 block table 大小
funcbuild_prefill_metadata[41行] 构造 MLA prefill metadata
funcbuild_decode_metadata[83行] 构造 MLA decode metadata
funcbuild_for_graph_capture[17行] 为 CUDA graph 捕获构造 mock MLA metadata
funcupdate_graph_params[113行] DCP/PCP 模式下更新 graph 参数
func_v_up_proj[8行]
func_v_up_proj_batch_major[13行] Project a batch-major partial-attention result.
func_q_proj_and_k_up_proj[13行]
funcprocess_weights_after_loading[68行] 权重加载后的 MLA layout cast
func_load_fa_quant_scales[5行]
func_process_weights_for_fused[74行]
funcget_context_seq_len_npu[8行]
func_reorg_kvcache[9行]
func_compute_prefill_context[108行]
func_forward_prefill[71行]
func_exec_kv_no_rope[30行] Normalize and cache K3 MLA KV without rotating its raw slice.
funcexec_kv_decode[35行]
funcexec_kv_prefill[51行]
funcrope_single[13行]
func_forward_decode[212行]
funcreorg_decode_q[5行]
funcmla_preprocess_only_decode[86行]
func_get_num_prefill_kv_tokens[10行]
funcmla_preprocess_prefill[34行]
funcmla_preprocess_decode[23行]
func_mla_preprocess[39行]
funcget_num_actual_tokens[2行]
funcforward_mha[9行]
funcforward_mqa[9行]
funcforward[85行] MLA attention 前向入口
attention\sfa_kv_offload.py
查看源码Sparse KV offload 专用 SFA 后端(470 行)。把主 MLA 的 K/V 经 CPU 内存池中转以支持超大上下文:AscendSFAKVOffloadMetadataBuilder 填充 offload 专属元数据(decode 拆分 + 请求 ID);AscendSFAKVOffloadImpl 在 decode-only 且不在 graph 捕获/重放状态时把 K/V 路由到 CPU 池(_cpu_cache_pair/_resident_views 管理 topk buffer 的常驻视图),强制使用 native 预处理路径(sfa_prolog_v3/mlapo 被禁用),sparse flash attention 主计算在 _execute_sparse_flash_attention_process 中执行。
类: AscendSFAKVOffloadMetadataBuilder, AscendSFAKVOffloadImpl
func_check_device_kv_cache_exist[9行] 检查当前 prefill/mixed 批次是否需要 keep_device_kv_cache
func__init__[36行] 初始化类实例
func_populate_offload_metadata[21行]
funcbuild[9行] 构造 metadata
funcbuild_for_drafting[12行] 为 draft 模式构造 metadata
func_resolve_preprocess_type[5行]
func_cpu_cache_pair[5行]
func_resident_views[26行]
func_offload_layer_name[5行]
func_is_decode_only[6行]
func_pad_to_input_tokens[9行]
func_in_graph_runtime[13行]
funcforward[13行] 前向计算
func_compute_kv_only[25行] Decode-only KV generation that never touches an NPU paged cache.
funcexec_kv[47行] KV 路径入口
func_execute_sparse_flash_attention_process[126行]
SFA(Sparse Flash Attention)后端(1742 行)。面向 DeepSeek-V3.2 等稀疏注意力模型:AscendSFAMetadataBuilder 构建稀疏注意力元数据(支持 DSA-CP token 分片、DCP KV 视图的并行元数据准备);AscendSFAImpl 按量化方法选择融合预处理路径——PROLOG_V3(W8A8 dynamic/MXFP8,走 npu_mla_prolog_v3 系算子)或 MLAPO(W8A8,权重转 FRACTAL_NZ + trans_rope_weight 重排),否则回退 native;indexer 选择前后处理(indexer_select_pre/post_process)完成 lightning indexer 的 K 缓存写入与 topk 选择;_execute_sparse_flash_attention_process 执行稀疏主计算;_v_up_proj 用 batch_matmul_transpose/npu_transpose_batchmatmul 完成 V 上投影;custom_kv_rmsnorm_rope 为融合 RMSNorm+RoPE+FP8 量化的自定义算子入口。
类: PreprocessType, AscendSFABackend, AscendSFAMetadataBuilder, AscendSFAImpl
func_get_indexer_types[8行] 从 config tuple 提取 indexer_types 字段
func_has_shared_indexer_layers[5行] 判断是否有 shared 类型的 indexer 层
func_get_config_bool[5行] 从 config tuple 中按顺序读取 bool 属性
funcget_name[2行] 返回后端的注册名称
funcget_builder_cls[8行] 返回 attention metadata builder 类
funcget_kv_cache_shape[8行] 返回 KV 缓存张量形状
funcget_impl_cls[8行] 返回 attention 实现类
funcget_supported_kernel_block_sizes[2行] 返回支持的 kernel 块大小列表
func__init__[115行] 初始化 AscendSFAImpl / Builder
func_prepare_parallel_metadata[12行] 为 parallel 模式准备 metadata
func_update_parallel_slot_mapping[8行] 更新 parallel slot_mapping(基于 indexer 范围)
funcdetermine_chunked_prefill_workspace_size[2行] 估算 SFA chunked prefill workspace
funcget_cudagraph_support[8行] 返回 SFA backend 对 CUDA graph 的支持
funcreorder_batch[3行] SFA 专用 batch 重排
funcbuild[12行] 构造 SFA attention metadata
funcbuild_for_drafting[13行] 为 draft 模型构造 SFA metadata
func_build_with_metadata_view[11行] 在已有 metadata 视图上填充 SFA 专用字段
func_build[68行] 底层构造 SFA metadata
funcbuild_for_graph_capture[15行] 为 CUDA graph 捕获构造 mock SFA metadata
funckv_cache_indexer_k_idx[14行] 计算 indexer K 缓存的物理 slot 索引
funckv_cache_indexer_scale_idx[3行] Index of the indexer scale cache in the KV cache tuple.
funcupdate_graph_params[10行] DCP/PCP 模式下更新 graph 参数
funcprocess_weights_after_loading[66行] 权重加载后 SFA layout cast
func_get_layer_quant_method[2行]
func_resolve_preprocess_type[18行]
func_try_enable_type[11行]
func_get_fused_type_unsupported_reasons[19行]
func_process_weights_for_fused_prolog_v3[47行]
func_process_weights_for_fused_mlapo[73行]
funcforward_mha[11行]
funcforward_mqa[8行]
funcrope_single[11行]
funcexec_kv[44行] KV 路径入口
func_q_proj_and_k_up_proj[13行]
func_v_up_proj[26行]
func_sfa_preprocess_prolog_v3[113行]
func_sfa_preprocess_mlapo[65行] A3 MLAPO via ``torch.ops._C_ascend.mla_preprocess`` (W8A8, ≤ 1024 tokens).
funcindexer_select_pre_process[48行]
funcindexer_select_post_process[83行]
func_get_indexcache_topk_indices[7行]
func_update_indexcache_topk_indices[11行]
func_use_li_c8_reshape_optim[3行] Whether this layer can use the LI C8 cache-write operator.
func_execute_sparse_flash_attention_process[22行]
func_record_query_gather_context[7行]
func_parallel_query_gather_dim[3行] Dimension restored by an outer DCP query gather.
func_prepare_kv_for_parallel[16行] Prepare native KV tensors for an optional parallel layout.
func_store_parallel_kv[40行] Store KV produced by native preprocessing.
func_get_parallel_forward_context[12行]
func_prepare_native_hidden_states[6行]
func_finalize_o_proj[8行]
func_get_sfa_kv_slot_mapping[5行]
func_compose_sfa_kv_cache[57行] Compose split cache handles into the tuple expected by SFA kernels.
func_write_indexer_cache[45行]
funcforward[201行] SFA attention 前向入口
funccustom_kv_rmsnorm_rope[37行]
attention\sparse_flash_mla.py
查看源码SparseFlashMla BF16 KV 适配层(62 行)。惰性加载 SparseFlashMla 算子(不引入对 vllm_ascend.ops 的依赖),把现有 DSA 元数据 kwargs(sparse_flash_mla_metadata)和注意力 kwargs(sparse_flash_mla)适配为 SparseFlashMla BF16 KV 所需格式(附加压缩 KV 长度参数),供 A5 平台 BF16 DSA 路径调用。
类: 无
func_get_sparse_flash_mla_ops[10行] 懒加载 SparseFlashMla 算子
func_add_compressed_kv_lengths[9行] 为 kwargs 添加压缩 KV 长度信息
funcsparse_flash_mla_metadata[14行] 将 DSA metadata 适配到 SparseFlashMla BF16 KV
funcsparse_flash_mla[11行] 将 DSA attention 适配到 SparseFlashMla BF16 KV 并执行
注意力模块共享工具集(565 行)。包含:共享 buffer 注册(get_or_register_attention_buffer)、SFA topk 掩码构建、graph workspace 缓存与 PA/FIA 共图重放参数(PagedAttentionGraphParam/update_paged_attention_graph_param)、chunked prefill workspace 尺寸估算;AscendCommonAttentionMetadata 定义跨层共享的批次级注意力元数据,split_decodes_and_prefills 按阈值拆分 decode/prefill 段;KV connector 协作钩子(wait_for_kv_layer_from_connector/maybe_save_kv_layer_to_connector/notify_kv_cache_written);权重变换工具 trans_rope_weight(RoPE 维度重排)与 transdata(FRACTAL_NZ 分块重排);DCP/PCP 开关(enable_dcp/enable_pcp)与 AscendDCPMetadata。
类: AscendCommonAttentionMetadata
funcget_or_register_attention_buffer[33行] 注册跨 attention 层共享的非-persistent 缓冲
funcbuild_valid_topk_mask[6行] 生成 top-k 行中的合法位置掩码
funcget_sfa_qsfa_packed_head_dim[12行] 计算 SFA/QSFA packed KV 缓存的 head_dim 字节数
func__iter__[2行] 迭代队列
funcupdate_paged_attention_graph_param[45行] 更新 ACL graph 中 PA 参数
funccache_graph_workspace[20行] 按 graph 大小缓存 FIA workspace 张量
funcneeds_layer_aware_fia_graph_replay[12行] 是否需要逐层感知的 FIA 图 replay
funcascend_chunked_prefill_workspace_size[26行] 计算 chunked prefill 所需的 workspace
funcusing_paged_attention[17行] 判断是否使用 paged attention
funcenable_dcp[3行] 判断当前配置是否启用 decode context parallel
funcenable_pcp[3行] 判断当前配置是否启用 prefill context parallel
funcunpadded[56行] dataclass 字段:原始未对齐 KV 长度
func_slice_reqs[2行] 按请求 id 切片 metadata
funcfilter_chunked_req_indices[23行] 过滤 chunked prefill 阶段请求索引
funcsplit_decodes_and_prefills[89行] 把请求 batch 拆为 decode / prefill 子集
funcwait_for_kv_layer_from_connector[12行] 从 KV connector 等待指定层 KV
funcmaybe_save_kv_layer_to_connector[15行] 如需 offloading,把层 KV 提交给 connector
funcnotify_kv_cache_written[18行] 通知 connector 当前层 cache 已写入
funcround_up[4行] 向上取整到对齐单位
functrans_rope_weight[7行] 把 RoPE 权重从 (B,A) 转 (A,B) 存储布局
functransdata[15行]
funcenabling_mlapo[11行]
attention\context_parallel\__init__.py
查看源码attention.context_parallel 子包标记。该子包实现 NPU 注意力的上下文并行:DCP(decode context parallel,序列分片 decode)与 PCP(prefill context parallel,prefill 上下文并行),覆盖 GQA/MLA/SFA/DSA 四类后端。
类: 无
attention\context_parallel\attention_cp.py
查看源码GQA 注意力的 DCP 实现(610 行)。AscendAttentionDCPMetadataBuilder 拆分 decode/prefill 并构建 DCP 专属元数据(AscendAttentionDCPMetadata);AscendAttentionDCPImpl 的 decode 路径(_forward_decode_dcp)在 rank 本地 KV 分片上计算;prefill chunked 路径:all-gather query(_prefill_query_all_gather)、按 chunk 用 DeviceOperator.kv_cache_load 从分页缓存加载 K/V(_load_kv_for_chunk)、本地注意力输出经 all_to_all 汇聚(_gather_global_context_output)、各 rank 输出与 LSE 在 _update_global_context_output 中用 log-sum-exp 合并,_update_chunk_attn_out_lse_with_current_attn_out_lse 处理 chunk 间增量合并。
类: AscendAttentionDCPMetadata, AscendAttentionDCPMetadataBuilder, AscendAttentionDCPImpl
func_split_decodes_and_prefills[9行] 把 batch 拆为 decode / prefill 子集
func_get_chunked_req_mask[4行]
func_build_backend_metadata[58行] 构造后端 metadata(内部 helper)
funcupdate_graph_params[102行] DCP 模式下更新 graph 参数
func_forward_decode_dcp[116行]
func_update_chunk_attn_out_lse_with_current_attn_out_lse[29行]
func_prefill_query_all_gather[2行]
func_compute_prefill_context[50行]
func_load_kv_for_chunk[20行]
func_gather_global_context_output[12行]
func_update_global_context_output[12行]
funcforward_impl[85行] attention 前向底层实现
attention\context_parallel\common_cp.py
查看源码DCP 共享基础设施(233 行)。get_dcp_local_seq_lens 按 interleave 布局计算每个 DCP rank 持有的 KV 长度;DCPMetadataBuilderMixin 提供元数据构建器对 DCP 元数据的访问与本地/rank 上下文长度提取;DCPImplMixin 封装组生命周期与集合通信(_dcp_all_gather、_dcp_all_gather_fragments 多张量异步 all-gather、_merge_dcp_attention_output);_process_attn_out_lse/_npu_attention_update/_npu_attn_out_lse_update 处理带掩码/无掩码两路输出与 LSE 的合并(npu_attention_update 算子),_update_out_and_lse 实现 LSE=log(sum(exp(LSE_i))) 的数值稳定合并。
类: 无
funcget_dcp_local_seq_lens[19行] Return the interleave-aware KV length of every DCP rank.
func__init__[6行] 初始化类实例(绑定配置、参数、模块)
func_require_dcp_metadata[7行]
func_get_dcp_context_lens[15行]
func_get_dcp_rank_context_lens[14行]
func_dcp_all_gather[8行]
func_dcp_all_gather_fragments[13行]
func_merge_dcp_attention_output[16行]
func_process_attn_out_lse[27行]
func_npu_attention_update[28行]
func_npu_attn_out_lse_update[16行]
func_out_lse_reshape[4行]
func_update_out_and_lse[12行] LSE_final = log(sum(exp(LSE_i))), O_final = sum(exp(LSE_i - LSE_final) * O_i)
attention\context_parallel\dsa_cp.py
查看源码DSA 上下文并行实现(2291 行,子包最大文件)。覆盖两种并行:DSA-CP(TP 组内 token 分片)与 DCP/PCP(序列分片)。AscendDSACPMetadataBuilder 在共享 SFA builder 上叠加 token 分片元数据(compressor 行数计算、SAS/QLI 元数据、比较 seqlens);AscendDSACPImpl 实现核心逻辑:o_proj 的 TP 全量权重切换(_enable_o_proj_tp_full_weight_switch/_switch_o_proj_to_full_weight,配合 TPWeightSwitchMixin 在计算期临时切全量权重)、隐藏层恢复布局(_restore_tp_head_layout)、indexer 缓存更新与 topk 选择(_update_indexer_cache/_indexer_select_topk)、Hadamard 激活旋转(rotate_activation);PCP 侧:AscendDSAPCPMetadataBuilder 构建本地元数据 + 全局规范缓存元数据,AscendDSAPCPImpl 先做批量全局 DSA 缓存更新(SWA/compressor/indexer 三类缓存)再做 rank 本地注意力。from_local_metadata 把本地元数据映射为带规范 cache 写视图的全局元数据。
类: AscendDSACPMetadataBuilder, AscendDSACPImpl, AscendDSAPCPMetadata, AscendDSAPCPMetadataBuilder, AscendDSAPCPImpl
funchadamard_transform_ref[15行]
funcrotate_activation[3行]
func__init__[5行] 初始化类实例(绑定配置、参数、模块)
funcget_cudagraph_support[6行] 返回 backend 对 CUDA graph 捕获的支持程度
funcbuild[38行] 构造 attention metadata
funcbuild_for_drafting[66行] 为 draft 模型构造 metadata
funcbuild_req_metadata_for_drafting[149行] Build DSA-CP metadata for one draft step.
func_num_compressor_metadata_rows[7行]
func_ensure_device_local_metadata[61行] Return device local metadata, cached across kv-cache groups.
funcbuild_req_metadata[146行] Build a single unified metadata for all requests (prefill + decode).
func_build_local_token_metadata[103行] For example:
func_get_cmp_seqlens_for_metadata[6行]
func_build_sas_metadata[73行]
func_build_qli_metadata[33行]
funcbuild_for_graph_capture[20行] 为 cudagraph 捕获构造 mock metadata
func_get_layer_metadata[29行]
func_compute_compressor_metadata[29行]
funcprocess_weights_after_loading[8行] 权重加载后的后处理(如 layout cast、NZ 转换)
func_get_tp_weight_switch_method[9行]
func_enable_linear_tp_weight_switch[14行]
func_enable_o_proj_tp_full_weight_switch[13行] Allocate o_proj TP/full buffers when the DSA-CP backend is enabled.
func_maybe_all_gather_o_proj_full_weight[15行]
func_switch_o_proj_to_full_weight[13行]
func_switch_o_proj_to_tp_weight[11行]
func_apply_wo_b[8行]
func_get_batched_wo_a_weight[17行] Return wo_a in the DSA batched-matmul layout [group, input, rank].
func_get_batched_wo_a_scale[14行] Move the output-sharded wo_a scale's group axis to the front.
func_split_full_hidden_states_for_cp[30行] Return this TP rank's token shard from the replicated model state.
func_gather_cp_output[44行] Restore the replicated model-state layout after DSA-CP.
funcforward[100行] attention 前向入口
func_forward[221行] 内部前向实现
func_restore_tp_head_layout[31行]
func_update_indexer_cache[59行]
func_indexer_select_topk[70行]
funcfrom_local_metadata[21行]
func_build_global_common_attn_metadata[27行]
func_build_local_common_attn_metadata[15行]
func_build_local_dsa_metadata[29行]
func_build_global_dsa_metadata[18行]
func_gather_and_restore_hidden_states[15行] All-gather one padded rank slice and restore scheduler token order.
func_update_global_swa_cache[30行] Update the replicated SWA cache from the canonical global batch.
func_update_global_compressor_cache[20行] Update the DSA compressor cache from the canonical global batch.
func_update_global_indexer_cache[16行] Update the Indexer cache from the canonical global batch.
func_prepare_caches_before_attention[53行] Restore one global batch and update each replicated cache once.
func_get_o_proj_input_shape[13行]
attention\context_parallel\mla_cp.py
查看源码MLA 的 DCP 实现(529 行)。DCPChunkedContextMetadata 维护 DCP 本地上下文分片的 chunk 元数据(含 padding 后的 NPU seq lens);AscendMlaDCPMetadataBuilder 构建 chunked/decode 元数据;AscendMlaDCPImpl 的 decode 前向先 all-gather q(reorg_decode_q 聚合 nope/pe 两段),再在本地 KV 分片上执行 _forward_decode,get_context_seq_len_npu 返回 padding 后的 chunk 长度,_reorg_kvcache 处理 KV 重组织。
类: DCPChunkedContextMetadata, AscendMLADCPDecodeMetadata, AscendMlaDCPMetadataBuilder, AscendMlaDCPImpl
func__init__[16行] 初始化类实例(绑定配置、参数、模块)
funcbuild_chunked_metadata[59行] 为 chunked prefill 构造 MLA metadata
funcbuild_decode_metadata[18行] 构造 MLA decode metadata
funcupdate_graph_params[96行] DCP/PCP 模式下更新 graph 参数
funcget_context_seq_len_npu[9行]
funcreorg_decode_q[6行]
func_forward_decode[161行]
func_reorg_kvcache[85行] reorg and unpad kvcache after cp local gather to tp layout for attn kernel.
attention\context_parallel\sfa_cp.py
查看源码SFA 的上下文并行全家桶(1315 行)。三条路径按两个独立开关组合:DSA-CP(TP token 分片)× DCP(序列分片)。AscendSFADSACPMetadataBuilder/AscendSFADSACPImpl:token 分片下 KV 异步 all-gather(_prepare_kv_for_parallel/_store_parallel_kv,含 indexer K/scale)、o_proj 全量权重切换(复用 TPWeightSwitchMixin + 权重池)、query 聚合;AscendSFADCPMetadataBuilder/AscendSFADCPImpl:序列分片下构建复制视图(block table/slot mapping 的 replicated view)、稀疏索引从全局视图重映射到本地视图(_remap_sparse_indices,Triton kernel 或 fp32 回退实现,无效索引置无效值后按 topk 序紧凑排列)、输出与 LSE 合并;AscendSFADSADCPMetadataBuilder/Impl 把两者复合;resolve_sfa_metadata_builder/resolve_sfa_impl 按开关解析出唯一实现。AscendSFAPCPImpl 处理 PCP 的 KV slot 映射与 indexer 缓存写入。
类: AscendSFAPCPImpl, AscendSFADSACPMetadata, DCPGatherContext, AscendSFADCPMetadata, AscendSFADSADCPMetadata, AscendSFADSACPMetadataBuilder, AscendSFADSACPImpl, AscendSFADCPMetadataBuilder, AscendSFADCPImpl, AscendSFADSADCPMetadataBuilder, AscendSFADSADCPImpl
func_get_sfa_kv_slot_mapping[7行]
funcexec_kv[28行] SFA CP KV 路径入口
func_write_indexer_cache[25行]
func__init__[17行] 初始化类实例(绑定配置、参数、模块)
func_prepare_parallel_metadata[81行]
func_update_parallel_slot_mapping[20行]
funcprocess_weights_after_loading[6行] 权重加载后的后处理(如 layout cast、NZ 转换)
func_get_fused_type_unsupported_reasons[4行]
func_parallel_query_gather_dim[2行]
func_prepare_native_hidden_states[16行]
func_get_parallel_forward_context[24行]
func_prepare_kv_for_parallel[38行]
func_store_parallel_kv[34行]
func_enable_o_proj_tp_full_weight_switch[17行]
func_get_o_proj_linear_method[3行]
func_apply_o_proj_full_weight[2行]
func_finalize_o_proj[56行]
func_get_dcp_local_seq_lens[6行]
func_get_dcp_local_block_table[3行]
func_ensure_replicated_view_buffers[27行]
func_build_block_table_replicated_view[35行]
func_build_slot_mapping_replicated_view[43行]
func_build_compact_kv_gather_metadata[13行] Build the compact cross-DCP KV view used by prefill attention.
func_build_with_metadata_view[60行]
funcbuild_for_graph_capture[19行] 为 cudagraph 捕获构造 mock metadata
func_has_prefill[2行]
func_record_dcp_kv_gather_context[39行] Start the compact KV all-gather used by prefill/mixed DCP batches.
func_start_dcp_gather[13行]
func_finish_dcp_gather[9行]
func_all_gather_dim_async[14行]
func_remap_sparse_indices[48行]
func_merge_dcp_outputs[40行]
func_start_dcp_query_gather[24行]
func_record_query_gather_context[14行]
func_execute_sparse_flash_attention_process[88行]
funcresolve_sfa_metadata_builder[11行] Resolve one SFA metadata builder from the two independent CP switches.
funcresolve_sfa_impl[13行] Resolve one SFA implementation from the two independent CP switches.