From ede072baa8e771c3de765226548e7916fb350a2f Mon Sep 17 00:00:00 2001 From: Martin Vit Date: Sat, 15 Aug 2026 02:28:21 +0000 Subject: [PATCH 1/2] Serve Kimi-K3 QSRT on TP16 with DCP Serve the official MXFP4 checkpoint and tensor-parallel-independent QSRT checkpoints through B12X dense MLA, routed MoE, projection collectives, exact expert selection, and PCIe vocabulary reduction. Support DCP4, DCP8, and DCP16 with target-only, DSpark, and DFlash execution, bounded prefill workspace, graph-owned scratch, and InstantTensor loading. Kimi-K3 has 896 routed experts and projection shapes that do not divide uniformly across TP16. The integration preserves canonical expert identities, gathers only required projection rows, sanitizes empty DCP shards before LSE reduction, and maintains causal and non-causal speculative metadata. A narrow backport from vllm-project/flash-attention initializes FA4 split-KV state and passes dynamic-causal metadata without importing unrelated SM90 FP8-KV changes. Compatibility: model-specific gates preserve other architectures and TP12/DCP1 QSRT behavior. Process groups without B12X pools retain no-op graph-capture behavior. Zero keeps automatic MLA workspace sizing; negative explicit bounds fail configuration. Validation: Ruff and Python compilation pass for every changed Python file. Focused CPU and GPU-visible suites pass 54 tests with 11 hardware-inapplicable skips. The FA4 patch applies to flash-attention f3e1a4f74c99145c0717709860bf765de1703779 and produces the qualified wrapper SHA-256 80058d9ea24fb51eaf1edecf4413d9c2008b0a5538127263a2e2500e8f838479. Full-model qualification results are recorded in the pull request. AI assistance: Codex composed the implementation, generated tests and validation commands, and inspected the resulting diff. Human review remains required for merge. --- cmake/external_projects/vllm_flash_attn.cmake | 2 + .../vllm_flash_attn_fa4_dynamic_causal.patch | 10 + serve-kimi-k3-full-mxfp4-dcp16-1m-dflash.sh | 70 ++ serve-kimi-k3-full-mxfp4-dcp16-1m-dspark.sh | 145 ++++ serve-kimi-k3-full-mxfp4-dcp16-1m-no-spec.sh | 114 ++++ tests/distributed/test_dcp_a2a.py | 108 ++- .../test_dcp_direct_a2a_lse_reduce.py | 29 + tests/kernels/moe/test_fused_topk.py | 33 + .../instanttensor_loader/test_weight_utils.py | 76 ++- .../model_loader/test_reload.py | 51 ++ .../test_kimi_k3_triton_warmup.py | 45 ++ .../models/kimi_k3/test_sequence_parallel.py | 16 + .../test_dspark_mla_config.py | 75 ++- tests/v1/attention/test_b12x_mla.py | 82 ++- tests/v1/attention/test_mla_context_chunks.py | 18 + tests/v1/attention/test_mla_noncausal.py | 3 +- .../test_dflash_prefix_cache_masking.py | 32 + .../test_dspark_attention_config.py | 141 ++++ .../spec_decode/test_dspark_sharded_markov.py | 133 ++++ tools/kimi_k3/benchmark_nospec_decode.py | 188 ++++++ vllm/compilation/b12x_capture.py | 21 + vllm/config/speculative.py | 12 +- vllm/distributed/communication_op.py | 5 + .../base_device_communicator.py | 5 + .../device_communicators/cuda_communicator.py | 16 + .../device_communicators/custom_all_reduce.py | 177 +++-- vllm/distributed/parallel_state.py | 61 +- vllm/envs.py | 88 +++ .../layers/attention/mla_attention.py | 99 ++- .../layers/fused_moe/modular_kernel.py | 3 +- .../model_loader/reload/layerwise.py | 111 +++- .../model_loader/weight_utils.py | 174 +++-- vllm/model_executor/models/qwen3_dflash.py | 6 + vllm/model_executor/models/qwen3_dspark.py | 43 +- vllm/model_executor/warmup/kernel_warmup.py | 69 +- .../warmup/kimi_k3_triton_warmup.py | 31 +- vllm/models/kimi_k3/nvidia/dspark_mla.py | 305 ++++++++- vllm/models/kimi_k3/nvidia/kda.py | 90 ++- vllm/models/kimi_k3/nvidia/mla.py | 192 +++++- vllm/models/kimi_k3/nvidia/model.py | 194 +++++- vllm/models/kimi_k3/nvidia/ops/topk16.cu | 187 ++++++ vllm/models/kimi_k3/nvidia/ops/topk16.py | 58 ++ vllm/models/kimi_k3/nvidia/tp_projection.py | 189 ++++++ vllm/v1/attention/backends/mla/b12x_mla.py | 623 +++++++++++++++--- vllm/v1/attention/ops/dcp_alltoall.py | 436 ++++++++++-- vllm/v1/core/kv_cache_utils.py | 50 +- vllm/v1/kv_cache_interface.py | 17 +- .../gpu/spec_decode/dflash/cudagraph.py | 1 + .../gpu/spec_decode/dflash/speculator.py | 137 +++- .../gpu/spec_decode/dspark/speculator.py | 201 +++++- .../v1/worker/gpu/spec_decode/dspark/utils.py | 44 +- vllm/v1/worker/gpu/spec_decode/speculator.py | 2 +- 52 files changed, 4591 insertions(+), 427 deletions(-) create mode 100644 cmake/patches/vllm_flash_attn_fa4_dynamic_causal.patch create mode 100755 serve-kimi-k3-full-mxfp4-dcp16-1m-dflash.sh create mode 100755 serve-kimi-k3-full-mxfp4-dcp16-1m-dspark.sh create mode 100755 serve-kimi-k3-full-mxfp4-dcp16-1m-no-spec.sh create mode 100644 tests/model_executor/test_kimi_k3_triton_warmup.py create mode 100644 tests/v1/spec_decode/test_dspark_attention_config.py create mode 100644 tests/v1/spec_decode/test_dspark_sharded_markov.py create mode 100644 tools/kimi_k3/benchmark_nospec_decode.py create mode 100644 vllm/models/kimi_k3/nvidia/ops/topk16.cu create mode 100644 vllm/models/kimi_k3/nvidia/ops/topk16.py create mode 100644 vllm/models/kimi_k3/nvidia/tp_projection.py diff --git a/cmake/external_projects/vllm_flash_attn.cmake b/cmake/external_projects/vllm_flash_attn.cmake index 2fa76be4fd64..96607f1bdb9c 100644 --- a/cmake/external_projects/vllm_flash_attn.cmake +++ b/cmake/external_projects/vllm_flash_attn.cmake @@ -46,6 +46,8 @@ else() GIT_TAG f3e1a4f74c99145c0717709860bf765de1703779 GIT_SUBMODULES ${VLLM_FLASH_ATTN_GIT_SUBMODULES} GIT_PROGRESS TRUE + PATCH_COMMAND git apply --unidiff-zero --whitespace=nowarn + ${CMAKE_SOURCE_DIR}/cmake/patches/vllm_flash_attn_fa4_dynamic_causal.patch # Don't share the vllm-flash-attn build between build types BINARY_DIR ${CMAKE_BINARY_DIR}/vllm-flash-attn ) diff --git a/cmake/patches/vllm_flash_attn_fa4_dynamic_causal.patch b/cmake/patches/vllm_flash_attn_fa4_dynamic_causal.patch new file mode 100644 index 000000000000..d557c8642291 --- /dev/null +++ b/cmake/patches/vllm_flash_attn_fa4_dynamic_causal.patch @@ -0,0 +1,10 @@ +diff --git a/flash_attn/cute/flash_fwd.py b/flash_attn/cute/flash_fwd.py +index 91f7826..5987ace 100644 +--- a/flash_attn/cute/flash_fwd.py ++++ b/flash_attn/cute/flash_fwd.py +@@ -624,0 +625 @@ class FlashAttentionForwardSm80(FlashAttentionForwardBase): ++ self.is_split_kv = False +@@ -791,0 +793 @@ class FlashAttentionForwardSm80(FlashAttentionForwardBase): ++ mDynamicCausal, +@@ -831,0 +834 @@ class FlashAttentionForwardSm80(FlashAttentionForwardBase): ++ mDynamicCausal: Optional[cute.Tensor] = None, diff --git a/serve-kimi-k3-full-mxfp4-dcp16-1m-dflash.sh b/serve-kimi-k3-full-mxfp4-dcp16-1m-dflash.sh new file mode 100755 index 000000000000..c8b71fd4d839 --- /dev/null +++ b/serve-kimi-k3-full-mxfp4-dcp16-1m-dflash.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# Serve the stock Kimi-K3 MXFP4 target with the modal-labs Kimi-K3-DFlash +# draft on TP16/DCP16. The target retains a physical one-million-token FP8 +# cache; KDA input projections and eligible draft linears use weight-only +# MXFP8 to fit both models without changing target activation precision. +set -euo pipefail + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +DFLASH_DRAFT="${DFLASH_DRAFT:-/root/.cache/huggingface/hub/models--modal-labs--Kimi-K3-DFlash/snapshots/c192d15a43407bf758b5ae0880d5c72052fef1de}" +DFLASH_TOKENS="${DFLASH_TOKENS:-7}" +DFLASH_ATTENTION_BACKEND="${DFLASH_ATTENTION_BACKEND:-TRITON_ATTN}" +DFLASH_DRAFT_MXFP8="${DFLASH_DRAFT_MXFP8:-1}" + +if [[ ! -f "${DFLASH_DRAFT}/config.json" || ! -f "${DFLASH_DRAFT}/model.safetensors" ]]; then + echo "Kimi-K3 DFlash checkpoint is incomplete: ${DFLASH_DRAFT}" >&2 + exit 1 +fi +if (( DFLASH_TOKENS != 7 )); then + echo "The Kimi-K3 DFlash profile requires DFLASH_TOKENS=7" >&2 + exit 2 +fi +case "${DFLASH_DRAFT_MXFP8}" in + 0 | 1) ;; + *) + echo "DFLASH_DRAFT_MXFP8 must be 0 or 1" >&2 + exit 2 + ;; +esac + +export SERVED_MODEL_NAME="${SERVED_MODEL_NAME:-Kimi-K3-MXFP4-DFlash-DCP16-1M}" +export MAX_MODEL_LEN="${MAX_MODEL_LEN:-1048576}" +export KV_CACHE_MEMORY_BYTES="${KV_CACHE_MEMORY_BYTES:-1200000000}" +export VLLM_USE_B12X_FP8_GEMM="${VLLM_USE_B12X_FP8_GEMM:-1}" +export VLLM_KIMI_FUSED_TOPK16="${VLLM_KIMI_FUSED_TOPK16:-1}" +export VLLM_DCP_A2A_MAX_TOKENS="${VLLM_DCP_A2A_MAX_TOKENS:-$((DFLASH_TOKENS + 1))}" +export VLLM_MEMORY_PROFILER_ESTIMATE_CUDAGRAPHS="${VLLM_MEMORY_PROFILER_ESTIMATE_CUDAGRAPHS:-1}" +# The target and DFlash capture sequences require distinct MoE output storage. +export VLLM_DISABLE_FUSED_MOE_OUTPUT_ALIAS="${VLLM_DISABLE_FUSED_MOE_OUTPUT_ALIAS:-1}" +export GLOO_SOCKET_IFNAME="${GLOO_SOCKET_IFNAME:-lo}" +export TP_SOCKET_IFNAME="${TP_SOCKET_IFNAME:-lo}" + +if [[ -z "${COMPILATION_CONFIG:-}" ]]; then + export COMPILATION_CONFIG="{\"mode\":0,\"cudagraph_mode\":\"FULL_AND_PIECEWISE\",\"cudagraph_capture_sizes\":[$((DFLASH_TOKENS + 1))],\"pass_config\":{\"fuse_allreduce_rms\":true}}" +fi + +DRAFT_QUANT_JSON="" +if [[ "${DFLASH_DRAFT_MXFP8}" == 1 ]]; then + # qkv_proj remains BF16 because context-KV precompute consumes the raw + # projection weights through torch.nn.functional.linear. + DRAFT_QUANT_JSON=',"quantization":"mxfp8","quantization_config":{"linear":"mxfp8","ignore":["re:.*qkv_proj$"]}' +fi + +printf -v SPECULATIVE_CONFIG \ + '{"method":"dflash","model":"%s","num_speculative_tokens":%s,"attention_backend":"%s","draft_load_config":{"load_format":"auto"}%s}' \ + "${DFLASH_DRAFT}" "${DFLASH_TOKENS}" "${DFLASH_ATTENTION_BACKEND}" \ + "${DRAFT_QUANT_JSON}" + +TARGET_QUANT_CONFIG='{"linear":"mxfp8","ignore":["re:^(?!.*self_attn\\.(?:q_proj|k_proj|v_proj|b_proj|f_a_proj)$).*$"]}' + +NO_SPEC_LAUNCHER="${KIMI_NO_SPEC_LAUNCHER:-${SCRIPT_DIR}/serve-kimi-k3-full-mxfp4-dcp16-1m-no-spec.sh}" +if [[ ! -x "${NO_SPEC_LAUNCHER}" ]]; then + echo "Kimi-K3 no-spec launcher is missing: ${NO_SPEC_LAUNCHER}" >&2 + exit 1 +fi + +exec "${NO_SPEC_LAUNCHER}" \ + --additional-config '{"kda_shard_f_a":false}' \ + --quantization-config "${TARGET_QUANT_CONFIG}" \ + --speculative-config "${SPECULATIVE_CONFIG}" \ + "$@" diff --git a/serve-kimi-k3-full-mxfp4-dcp16-1m-dspark.sh b/serve-kimi-k3-full-mxfp4-dcp16-1m-dspark.sh new file mode 100755 index 000000000000..31b9685012f1 --- /dev/null +++ b/serve-kimi-k3-full-mxfp4-dcp16-1m-dspark.sh @@ -0,0 +1,145 @@ +#!/usr/bin/env bash +# Serve the stock Kimi-K3 MXFP4 target with the Inferact five-layer DSpark +# draft on TP16/DCP16. Target KDA input projections and draft linear weights +# use weight-only MXFP8/Marlin; target verification preserves model semantics. +set -euo pipefail + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +PYTHON_BIN="${PYTHON_BIN:-/opt/venv/bin/python}" +VLLM_SOURCE_DIR="${VLLM_SOURCE_DIR:-${SCRIPT_DIR}}" +B12X_SOURCE_DIR="${B12X_SOURCE_DIR:-/opt/kimi-k3/b12x}" +MODEL="${MODEL:-/root/.cache/huggingface/hub/models--moonshotai--Kimi-K3/snapshots/2496450e92e425c886db095102a52a6682ca3970}" +DRAFT_MODEL="${DRAFT_MODEL:-/root/.cache/huggingface/hub/models--Inferact--Kimi-K3-DSpark/snapshots/cf6b8244620e7ea4b0651d214f28e89eac75bed6}" + +for required in \ + "${PYTHON_BIN}" \ + "${VLLM_SOURCE_DIR}/vllm/__init__.py" \ + "${B12X_SOURCE_DIR}/b12x/attention/dense_mla/__init__.py" \ + "${MODEL}/model.safetensors.index.json" \ + "${DRAFT_MODEL}/model.safetensors"; do + if [[ ! -e "${required}" ]]; then + echo "Required Kimi-K3 serving artifact is missing: ${required}" >&2 + exit 1 + fi +done + +TP_SIZE="${TP_SIZE:-16}" +DCP_SIZE="${DCP_SIZE:-16}" +if (( TP_SIZE != 16 || DCP_SIZE != 16 )); then + echo "This serving profile requires TP_SIZE=16 and DCP_SIZE=16" >&2 + exit 2 +fi + +export PYTHONPATH="${VLLM_SOURCE_DIR}:${B12X_SOURCE_DIR}${PYTHONPATH:+:${PYTHONPATH}}" +export CUTE_DSL_ARCH="${CUTE_DSL_ARCH:-sm_120a}" +export OMP_NUM_THREADS="${OMP_NUM_THREADS:-16}" +export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}" +export CUDA_MODULE_LOADING="${CUDA_MODULE_LOADING:-LAZY}" +export CUDA_MODULE_DATA_LOADING="${CUDA_MODULE_DATA_LOADING:-LAZY}" +export VLLM_WORKER_MULTIPROC_METHOD="${VLLM_WORKER_MULTIPROC_METHOD:-spawn}" +export VLLM_USE_V2_MODEL_RUNNER="${VLLM_USE_V2_MODEL_RUNNER:-1}" +export VLLM_USE_BREAKABLE_CUDAGRAPH="${VLLM_USE_BREAKABLE_CUDAGRAPH:-1}" + +export VLLM_USE_B12X_MOE="${VLLM_USE_B12X_MOE:-1}" +export B12X_MOE_FORCE_A16="${B12X_MOE_FORCE_A16:-1}" +export B12X_MOE_WORKSPACE_TOKEN_LIMIT="${B12X_MOE_WORKSPACE_TOKEN_LIMIT:-1024}" +export B12X_W4A16_SMALL_M_DIRECT="${B12X_W4A16_SMALL_M_DIRECT:-1}" +export B12X_W4A16_SMALL_M_HOST_BARRIER_RESET="${B12X_W4A16_SMALL_M_HOST_BARRIER_RESET:-0}" +export VLLM_DISABLE_SHARED_EXPERTS_STREAM="${VLLM_DISABLE_SHARED_EXPERTS_STREAM:-1}" + +export VLLM_KIMI_SHARD_QKV_A="${VLLM_KIMI_SHARD_QKV_A:-1}" +export VLLM_KIMI_USE_B12X_PROJECTION_GATHER="${VLLM_KIMI_USE_B12X_PROJECTION_GATHER:-1}" +export VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_GATHER="${VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_GATHER:-1}" +export VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_TOPK="${VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_TOPK:-1}" +export VLLM_KIMI_USE_B12X_BATCHED_PROJECTION_TOPK="${VLLM_KIMI_USE_B12X_BATCHED_PROJECTION_TOPK:-0}" + +export VLLM_USE_B12X_DCP_A2A="${VLLM_USE_B12X_DCP_A2A:-1}" +export VLLM_DCP_A2A_MAX_TOKENS="${VLLM_DCP_A2A_MAX_TOKENS:-8}" +export VLLM_DCP_A2A_LARGE_BACKEND="${VLLM_DCP_A2A_LARGE_BACKEND:-ag_rs}" +export VLLM_DCP_SHARD_DRAFT="${VLLM_DCP_SHARD_DRAFT:-0}" +export VLLM_ENABLE_PCIE_ALLREDUCE="${VLLM_ENABLE_PCIE_ALLREDUCE:-1}" +export VLLM_PCIE_ALLREDUCE_BACKEND="${VLLM_PCIE_ALLREDUCE_BACKEND:-b12x}" +export VLLM_PCIE_ONESHOT_SINGLE_CHANNEL="${VLLM_PCIE_ONESHOT_SINGLE_CHANNEL:-1}" +export B12X_PCIE_HIERARCHICAL_DEFERRED_CONSUMPTION="${B12X_PCIE_HIERARCHICAL_DEFERRED_CONSUMPTION:-1}" +export B12X_PCIE_HIERARCHICAL_DOUBLE_BUFFER="${B12X_PCIE_HIERARCHICAL_DOUBLE_BUFFER:-0}" +export B12X_PCIE_HIERARCHICAL_THREADS="${B12X_PCIE_HIERARCHICAL_THREADS:-256}" +export B12X_PCIE_HIERARCHICAL_NANOSLEEP_CYCLES="${B12X_PCIE_HIERARCHICAL_NANOSLEEP_CYCLES:-24}" +export B12X_PCIE_HIERARCHICAL_BF16X2="${B12X_PCIE_HIERARCHICAL_BF16X2:-1}" +export B12X_PCIE_HIERARCHICAL_BF16X2_MAX_ELEMENTS="${B12X_PCIE_HIERARCHICAL_BF16X2_MAX_ELEMENTS:-7168}" +export B12X_PCIE_DCP_THREADS="${B12X_PCIE_DCP_THREADS:-512}" +export B12X_PCIE_DCP_BLOCK_LIMIT="${B12X_PCIE_DCP_BLOCK_LIMIT:-8}" +export B12X_PCIE_KIMI_TOPK_THREADS="${B12X_PCIE_KIMI_TOPK_THREADS:-384}" + +export VLLM_DSPARK_DRAFT_KV_WINDOW="${VLLM_DSPARK_DRAFT_KV_WINDOW:-32768}" +export VLLM_DSPARK_COMPACT_ROPE="${VLLM_DSPARK_COMPACT_ROPE:-1}" +export VLLM_DSPARK_SHARD_MARKOV_HEAD="${VLLM_DSPARK_SHARD_MARKOV_HEAD:-1}" +export VLLM_DSPARK_CAPTURE_SHARDED_MARKOV="${VLLM_DSPARK_CAPTURE_SHARDED_MARKOV:-1}" +# Replicating the 80 MiB W1 table avoids a graph-captured TP all-reduce while +# preserving TP sharding for the vocabulary-sized W2 projection. +export VLLM_DSPARK_REPLICATE_MARKOV_W1="${VLLM_DSPARK_REPLICATE_MARKOV_W1:-1}" +export VLLM_KIMI_FUSED_TOPK16="${VLLM_KIMI_FUSED_TOPK16:-1}" +export VLLM_KIMI_K3_B12X_DSPARK_ARGMAX="${VLLM_KIMI_K3_B12X_DSPARK_ARGMAX:-1}" +export VLLM_K3_KV_GROUP_SIZE="${VLLM_K3_KV_GROUP_SIZE:-6}" + +export VLLM_MEMORY_PROFILE_INCLUDE_ATTN="${VLLM_MEMORY_PROFILE_INCLUDE_ATTN:-0}" +export VLLM_MEMORY_PROFILER_ESTIMATE_CUDAGRAPHS="${VLLM_MEMORY_PROFILER_ESTIMATE_CUDAGRAPHS:-0}" +export VLLM_MLA_CHUNKED_PREFILL_WORKSPACE_SIZE="${VLLM_MLA_CHUNKED_PREFILL_WORKSPACE_SIZE:-4096}" +export INSTANTTENSOR_COPY="${INSTANTTENSOR_COPY:-0}" +export INSTANTTENSOR_BUFFER_SIZE="${INSTANTTENSOR_BUFFER_SIZE:-536870912}" +export INSTANTTENSOR_BACKEND="${INSTANTTENSOR_BACKEND:-AIO}" +export INSTANTTENSOR_MAX_FREE_MEM_USAGE="${INSTANTTENSOR_MAX_FREE_MEM_USAGE:-0.6}" +export SAFETENSORS_FAST_GPU="${SAFETENSORS_FAST_GPU:-1}" +export NCCL_P2P_DISABLE="${NCCL_P2P_DISABLE:-0}" +unset NCCL_GRAPH_FILE + +for kernel in \ + B12xMxfp8LinearKernel \ + FlashInferCutedslMxfp8LinearKernel \ + FlashInferCutlassMxfp8LinearKernel; do + case ",${VLLM_DISABLED_KERNELS:-}," in + *,"${kernel}",*) ;; + *) VLLM_DISABLED_KERNELS="${VLLM_DISABLED_KERNELS:+${VLLM_DISABLED_KERNELS},}${kernel}" ;; + esac +done +export VLLM_DISABLED_KERNELS + +printf -v SPECULATIVE_CONFIG \ + '{"method":"dspark","model":"%s","num_speculative_tokens":7,"attention_backend":"B12X_MLA","kv_cache_dtype":"fp8","draft_sample_method":"greedy","rejection_sample_method":"block","quantization":"mxfp8","quantization_config":{"linear":"mxfp8","ignore":["re:.*fused_qkv_a_proj$"]}}' \ + "${DRAFT_MODEL}" +TARGET_QUANT_CONFIG='{"linear":"mxfp8","ignore":["re:^(?!.*self_attn\\.(?:q_proj|k_proj|v_proj|b_proj|f_a_proj)$).*$"]}' +if [[ -z "${COMPILATION_CONFIG:-}" ]]; then + COMPILATION_CONFIG='{"mode":0,"cudagraph_mode":"FULL_AND_PIECEWISE","cudagraph_capture_sizes":[8],"pass_config":{"fuse_allreduce_rms":true}}' +fi + +cd "${VLLM_SOURCE_DIR}" +exec "${PYTHON_BIN}" -m vllm.entrypoints.cli.main serve "${MODEL}" \ + --served-model-name "${SERVED_MODEL_NAME:-Kimi-K3-MXFP4-DSpark7-DCP16-1M}" \ + --trust-remote-code \ + --language-model-only \ + --host "${HOST:-0.0.0.0}" \ + --port "${PORT:-8000}" \ + --tensor-parallel-size "${TP_SIZE}" \ + --decode-context-parallel-size "${DCP_SIZE}" \ + --dcp-comm-backend a2a \ + --dcp-kv-cache-interleave-size 1 \ + --load-format instanttensor \ + --moe-backend b12x \ + --linear-backend auto \ + --attention-backend B12X_MLA \ + --kda-prefill-backend triton \ + --additional-config '{"kda_shard_f_a":false}' \ + --kv-cache-dtype fp8 \ + --kv-cache-memory-bytes "${KV_CACHE_MEMORY_BYTES:-1325000000}" \ + --max-model-len "${MAX_MODEL_LEN:-1048576}" \ + --max-num-batched-tokens "${MAX_NUM_BATCHED_TOKENS:-4096}" \ + --max-num-seqs "${MAX_NUM_SEQS:-1}" \ + --gpu-memory-utilization "${GPU_MEMORY_UTILIZATION:-0.985}" \ + --enable-chunked-prefill \ + --no-enable-prefix-caching \ + --quantization-config "${TARGET_QUANT_CONFIG}" \ + --speculative-config "${SPECULATIVE_CONFIG}" \ + --compilation-config "${COMPILATION_CONFIG}" \ + --reasoning-parser kimi_k3 \ + --tool-call-parser kimi_k3 \ + --enable-auto-tool-choice \ + "$@" diff --git a/serve-kimi-k3-full-mxfp4-dcp16-1m-no-spec.sh b/serve-kimi-k3-full-mxfp4-dcp16-1m-no-spec.sh new file mode 100755 index 000000000000..62a71ceeb668 --- /dev/null +++ b/serve-kimi-k3-full-mxfp4-dcp16-1m-no-spec.sh @@ -0,0 +1,114 @@ +#!/usr/bin/env bash +# Serve the stock Kimi-K3 MXFP4 checkpoint on 16 SM120 GPUs. Routed experts +# retain their checkpoint MXFP4 weights; dense tensors remain BF16. TP16 and +# DCP16 provide a physical one-million-token FP8 KV cache. +set -euo pipefail + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +PYTHON_BIN="${PYTHON_BIN:-/opt/venv/bin/python}" +VLLM_SOURCE_DIR="${VLLM_SOURCE_DIR:-${SCRIPT_DIR}}" +B12X_SOURCE_DIR="${B12X_SOURCE_DIR:-/opt/kimi-k3/b12x}" +MODEL="${MODEL:-/root/.cache/huggingface/hub/models--moonshotai--Kimi-K3/snapshots/2496450e92e425c886db095102a52a6682ca3970}" + +if [[ ! -x "${PYTHON_BIN}" ]]; then + echo "Python interpreter is missing: ${PYTHON_BIN}" >&2 + exit 1 +fi +if [[ ! -f "${VLLM_SOURCE_DIR}/vllm/__init__.py" ]]; then + echo "vLLM source tree is missing: ${VLLM_SOURCE_DIR}" >&2 + exit 1 +fi +if [[ ! -f "${B12X_SOURCE_DIR}/b12x/attention/dense_mla/__init__.py" ]]; then + echo "B12X dense MLA source is missing: ${B12X_SOURCE_DIR}" >&2 + exit 1 +fi +if [[ ! -f "${MODEL}/model.safetensors.index.json" ]]; then + echo "Kimi-K3 checkpoint is incomplete: ${MODEL}" >&2 + exit 1 +fi + +TP_SIZE="${TP_SIZE:-16}" +DCP_SIZE="${DCP_SIZE:-16}" +if (( TP_SIZE != 16 || DCP_SIZE != 16 )); then + echo "This serving profile requires TP_SIZE=16 and DCP_SIZE=16" >&2 + exit 2 +fi + +export PYTHONPATH="${VLLM_SOURCE_DIR}:${B12X_SOURCE_DIR}${PYTHONPATH:+:${PYTHONPATH}}" +export CUTE_DSL_ARCH="${CUTE_DSL_ARCH:-sm_120a}" +export OMP_NUM_THREADS="${OMP_NUM_THREADS:-16}" +export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}" +export CUDA_MODULE_LOADING="${CUDA_MODULE_LOADING:-LAZY}" +export CUDA_MODULE_DATA_LOADING="${CUDA_MODULE_DATA_LOADING:-LAZY}" +export VLLM_WORKER_MULTIPROC_METHOD="${VLLM_WORKER_MULTIPROC_METHOD:-spawn}" +export VLLM_USE_V2_MODEL_RUNNER="${VLLM_USE_V2_MODEL_RUNNER:-1}" +export VLLM_USE_BREAKABLE_CUDAGRAPH="${VLLM_USE_BREAKABLE_CUDAGRAPH:-1}" +export VLLM_USE_B12X_MOE="${VLLM_USE_B12X_MOE:-1}" +export B12X_MOE_FORCE_A16="${B12X_MOE_FORCE_A16:-1}" +export VLLM_KIMI_SHARD_QKV_A="${VLLM_KIMI_SHARD_QKV_A:-1}" +export VLLM_KIMI_FUSED_TOPK16="${VLLM_KIMI_FUSED_TOPK16:-1}" +export VLLM_KIMI_USE_B12X_PROJECTION_GATHER="${VLLM_KIMI_USE_B12X_PROJECTION_GATHER:-1}" +export VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_GATHER="${VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_GATHER:-1}" +export VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_TOPK="${VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_TOPK:-1}" +export VLLM_KIMI_USE_B12X_BATCHED_PROJECTION_TOPK="${VLLM_KIMI_USE_B12X_BATCHED_PROJECTION_TOPK:-0}" +export VLLM_USE_B12X_DCP_A2A="${VLLM_USE_B12X_DCP_A2A:-1}" +export VLLM_DCP_A2A_MAX_TOKENS="${VLLM_DCP_A2A_MAX_TOKENS:-1}" +export VLLM_DCP_A2A_LARGE_BACKEND="${VLLM_DCP_A2A_LARGE_BACKEND:-ag_rs}" +export VLLM_ENABLE_PCIE_ALLREDUCE="${VLLM_ENABLE_PCIE_ALLREDUCE:-1}" +export VLLM_PCIE_ALLREDUCE_BACKEND="${VLLM_PCIE_ALLREDUCE_BACKEND:-b12x}" +export VLLM_PCIE_ONESHOT_SINGLE_CHANNEL="${VLLM_PCIE_ONESHOT_SINGLE_CHANNEL:-1}" +export B12X_PCIE_HIERARCHICAL_DEFERRED_CONSUMPTION="${B12X_PCIE_HIERARCHICAL_DEFERRED_CONSUMPTION:-0}" +export B12X_PCIE_HIERARCHICAL_DOUBLE_BUFFER="${B12X_PCIE_HIERARCHICAL_DOUBLE_BUFFER:-1}" +export B12X_PCIE_HIERARCHICAL_THREADS="${B12X_PCIE_HIERARCHICAL_THREADS:-224}" +export B12X_PCIE_HIERARCHICAL_NANOSLEEP_CYCLES="${B12X_PCIE_HIERARCHICAL_NANOSLEEP_CYCLES:-24}" +export B12X_PCIE_HIERARCHICAL_BF16X2="${B12X_PCIE_HIERARCHICAL_BF16X2:-1}" +export B12X_PCIE_DCP_THREADS="${B12X_PCIE_DCP_THREADS:-512}" +export B12X_PCIE_DCP_BLOCK_LIMIT="${B12X_PCIE_DCP_BLOCK_LIMIT:-4}" +export B12X_PCIE_KIMI_TOPK_THREADS="${B12X_PCIE_KIMI_TOPK_THREADS:-384}" +export B12X_MOE_WORKSPACE_TOKEN_LIMIT="${B12X_MOE_WORKSPACE_TOKEN_LIMIT:-2048}" +export VLLM_DISABLE_SHARED_EXPERTS_STREAM="${VLLM_DISABLE_SHARED_EXPERTS_STREAM:-0}" +export VLLM_K3_KV_GROUP_SIZE="${VLLM_K3_KV_GROUP_SIZE:-6}" +export VLLM_MLA_CHUNKED_PREFILL_WORKSPACE_SIZE="${VLLM_MLA_CHUNKED_PREFILL_WORKSPACE_SIZE:-4096}" +export VLLM_MEMORY_PROFILE_INCLUDE_ATTN="${VLLM_MEMORY_PROFILE_INCLUDE_ATTN:-0}" +export VLLM_MEMORY_PROFILER_ESTIMATE_CUDAGRAPHS="${VLLM_MEMORY_PROFILER_ESTIMATE_CUDAGRAPHS:-0}" +export INSTANTTENSOR_COPY="${INSTANTTENSOR_COPY:-0}" +export INSTANTTENSOR_BUFFER_SIZE="${INSTANTTENSOR_BUFFER_SIZE:-536870912}" +export INSTANTTENSOR_BACKEND="${INSTANTTENSOR_BACKEND:-AIO}" +export INSTANTTENSOR_MAX_FREE_MEM_USAGE="${INSTANTTENSOR_MAX_FREE_MEM_USAGE:-0.6}" +export SAFETENSORS_FAST_GPU="${SAFETENSORS_FAST_GPU:-1}" +export NCCL_P2P_DISABLE="${NCCL_P2P_DISABLE:-0}" +unset NCCL_GRAPH_FILE + +if [[ -z "${COMPILATION_CONFIG:-}" ]]; then + COMPILATION_CONFIG='{"mode":0,"cudagraph_mode":"FULL_AND_PIECEWISE","cudagraph_capture_sizes":[1],"pass_config":{"fuse_allreduce_rms":true}}' +fi + +cd "${VLLM_SOURCE_DIR}" +exec "${PYTHON_BIN}" -m vllm.entrypoints.cli.main serve "${MODEL}" \ + --served-model-name "${SERVED_MODEL_NAME:-Kimi-K3-MXFP4-DCP16-1M}" \ + --trust-remote-code \ + --language-model-only \ + --host "${HOST:-0.0.0.0}" \ + --port "${PORT:-8000}" \ + --tensor-parallel-size "${TP_SIZE}" \ + --decode-context-parallel-size "${DCP_SIZE}" \ + --dcp-comm-backend a2a \ + --dcp-kv-cache-interleave-size 1 \ + --load-format instanttensor \ + --moe-backend b12x \ + --linear-backend b12x \ + --attention-backend B12X_MLA \ + --kda-prefill-backend triton \ + --kv-cache-dtype fp8 \ + --kv-cache-memory-bytes "${KV_CACHE_MEMORY_BYTES:-1325000000}" \ + --max-model-len "${MAX_MODEL_LEN:-1048576}" \ + --max-num-batched-tokens "${MAX_NUM_BATCHED_TOKENS:-2048}" \ + --max-num-seqs "${MAX_NUM_SEQS:-1}" \ + --gpu-memory-utilization "${GPU_MEMORY_UTILIZATION:-0.985}" \ + --enable-chunked-prefill \ + --no-enable-prefix-caching \ + --compilation-config "${COMPILATION_CONFIG}" \ + --reasoning-parser kimi_k3 \ + --tool-call-parser kimi_k3 \ + --enable-auto-tool-choice \ + "$@" diff --git a/tests/distributed/test_dcp_a2a.py b/tests/distributed/test_dcp_a2a.py index 909cb93c1bca..abb7bc4f2d53 100644 --- a/tests/distributed/test_dcp_a2a.py +++ b/tests/distributed/test_dcp_a2a.py @@ -749,23 +749,25 @@ def rollback_pcie_channels(self, checkpoint): events.append(("rollback-tp", checkpoint)) class _FakeGroup: - def __init__(self, *, world_size, communicator=None): + def __init__(self, name, *, world_size, communicator=None): + self.name = name self.world_size = world_size + self.device_group = object() self.device_communicator = type( "DeviceCommunicator", (), {"ca_comm": communicator} )() communicator = _FakeCommunicator() - tp_group = _FakeGroup(world_size=8, communicator=communicator) - pp_group = _FakeGroup(world_size=1, communicator=communicator) - dcp_group = _FakeGroup(world_size=2) + tp_group = _FakeGroup("tp", world_size=8, communicator=communicator) + pp_group = _FakeGroup("pp", world_size=1, communicator=communicator) + dcp_group = _FakeGroup("dcp", world_size=2) monkeypatch.setattr(parallel_state, "_TP", tp_group) monkeypatch.setattr(parallel_state, "_PP", pp_group) monkeypatch.setattr(parallel_state, "_DCP", dcp_group) def checkpoint_dcp(group): - events.append("checkpoint-dcp") - return "dcp-checkpoint" + events.append(("checkpoint-pool", group.name)) + return f"{group.name}-pool-checkpoint" monkeypatch.setattr( dcp_alltoall, @@ -783,13 +785,46 @@ def checkpoint_dcp(group): assert events == [ "checkpoint-tp", - "checkpoint-dcp", - ("rollback-dcp", "dcp-checkpoint"), + ("checkpoint-pool", "tp"), + ("checkpoint-pool", "dcp"), + ("rollback-dcp", "dcp-pool-checkpoint"), + ("rollback-dcp", "tp-pool-checkpoint"), ("rollback-tp", "tp-checkpoint"), ] -def test_global_graph_capture_enters_b12x_dcp_pool(monkeypatch): +def test_profile_channel_checkpoint_deduplicates_shared_b12x_pool(monkeypatch): + from vllm.distributed import parallel_state + from vllm.v1.attention.ops import dcp_alltoall + + class _FakeGroup: + def __init__(self, name, *, world_size, device_group): + self.name = name + self.world_size = world_size + self.device_group = device_group + self.device_communicator = type( + "DeviceCommunicator", (), {"ca_comm": None} + )() + + events: list[str] = [] + shared_device_group = object() + tp_group = _FakeGroup("tp", world_size=16, device_group=shared_device_group) + dcp_group = _FakeGroup("dcp", world_size=16, device_group=shared_device_group) + monkeypatch.setattr(parallel_state, "_TP", tp_group) + monkeypatch.setattr(parallel_state, "_PP", None) + monkeypatch.setattr(parallel_state, "_DCP", dcp_group) + monkeypatch.setattr( + dcp_alltoall, + "checkpoint_b12x_dcp_a2a_channels", + lambda group: events.append(group.name) or group.name, + ) + + parallel_state.checkpoint_b12x_graph_channels() + + assert events == ["tp"] + + +def test_global_graph_capture_enters_b12x_tp_and_dcp_pools(monkeypatch): from vllm.distributed import parallel_state from vllm.v1.attention.ops import dcp_alltoall @@ -800,6 +835,7 @@ class _FakeGroup: def __init__(self, name): self.name = name + self.device_group = object() @contextmanager def graph_capture(self, context): @@ -839,6 +875,12 @@ def fake_b12x_capture(group, selected_stream, *, channel_id): ("enter-group", "tp", "vllm:target:profile"), ("enter-group", "pp", "vllm:target:profile"), ("enter-group", "dcp", "vllm:target:profile"), + ( + "enter-b12x", + tp_group, + stream, + "vllm:target:profile", + ), ( "enter-b12x", dcp_group, @@ -851,12 +893,60 @@ def fake_b12x_capture(group, selected_stream, *, channel_id): stream, "vllm:target:profile", ), + ( + "exit-b12x", + tp_group, + stream, + "vllm:target:profile", + ), ("exit-group", "dcp", "vllm:target:profile"), ("exit-group", "pp", "vllm:target:profile"), ("exit-group", "tp", "vllm:target:profile"), ] +def test_global_graph_capture_does_not_deduplicate_b12x_coordinators(monkeypatch): + from vllm.distributed import parallel_state + from vllm.v1.attention.ops import dcp_alltoall + + class _FakeGroup: + world_size = 16 + + def __init__(self, name, device_group): + self.name = name + self.device_group = device_group + + @contextmanager + def graph_capture(self, context): + yield context + + shared_device_group = object() + tp_group = _FakeGroup("tp", shared_device_group) + dcp_group = _FakeGroup("dcp", shared_device_group) + pp_group = _FakeGroup("pp", object()) + entered_pools: list[str] = [] + + @contextmanager + def fake_b12x_capture(group, selected_stream, *, channel_id): + entered_pools.append(group.name) + yield + + monkeypatch.setattr(parallel_state, "_DCP", dcp_group) + monkeypatch.setattr(parallel_state, "get_tp_group", lambda: tp_group) + monkeypatch.setattr(parallel_state, "get_pp_group", lambda: pp_group) + monkeypatch.setattr(parallel_state, "get_dcp_group", lambda: dcp_group) + monkeypatch.setattr(dcp_alltoall, "capture_b12x_dcp_a2a", fake_b12x_capture) + context = parallel_state.GraphCaptureContext( # type: ignore[arg-type] + object(), + channel_id="vllm:target:decode", + ) + + with parallel_state.graph_capture(torch.device("cpu"), context): + pass + + assert entered_pools == ["tp", "dcp"] + + def test_group_capture_forwards_semantic_id_to_custom_allreduce(monkeypatch): from vllm._aiter_ops import rocm_aiter_ops from vllm.distributed import parallel_state diff --git a/tests/distributed/test_dcp_direct_a2a_lse_reduce.py b/tests/distributed/test_dcp_direct_a2a_lse_reduce.py index b05a54825d91..ebe1625356aa 100644 --- a/tests/distributed/test_dcp_direct_a2a_lse_reduce.py +++ b/tests/distributed/test_dcp_direct_a2a_lse_reduce.py @@ -499,6 +499,35 @@ def test_dcp_chunk_workspace_alignment_covers_interleave(): assert align_mla_chunked_context_workspace_size(config, 100) == 192 +def test_mla_chunk_workspace_honors_configured_token_limit(monkeypatch): + from vllm.model_executor.layers.attention.mla_attention import ( + MLACommonMetadataBuilder, + ) + + monkeypatch.setenv("VLLM_MLA_CHUNKED_PREFILL_WORKSPACE_SIZE", "4096") + config = MagicMock() + config.model_config.max_model_len = 1_048_576 + config.scheduler_config.max_num_seqs = 8 + config.cache_config.block_size = 32 + config.parallel_config.decode_context_parallel_size = 16 + config.parallel_config.cp_kv_cache_interleave_size = 1 + + assert ( + MLACommonMetadataBuilder.determine_chunked_prefill_workspace_size(config) + == 4096 + ) + + monkeypatch.setenv("VLLM_MLA_CHUNKED_PREFILL_WORKSPACE_SIZE", "0") + assert ( + MLACommonMetadataBuilder.determine_chunked_prefill_workspace_size(config) + == 64 * 1024 + ) + + monkeypatch.setenv("VLLM_MLA_CHUNKED_PREFILL_WORKSPACE_SIZE", "-1") + with pytest.raises(ValueError, match="must be non-negative"): + MLACommonMetadataBuilder.determine_chunked_prefill_workspace_size(config) + + def test_sparse_mla_builder_initializes_dcp_manager(monkeypatch): import vllm.model_executor.layers.attention.sparse_mla_attention as sparse_mla diff --git a/tests/kernels/moe/test_fused_topk.py b/tests/kernels/moe/test_fused_topk.py index 825cd20263d7..43644689a777 100644 --- a/tests/kernels/moe/test_fused_topk.py +++ b/tests/kernels/moe/test_fused_topk.py @@ -12,6 +12,7 @@ fused_topk_bias, ) from vllm.model_executor.layers.fused_moe.router.fused_topk_router import fused_topk +from vllm.models.kimi_k3.nvidia.ops.topk16 import kimi_topk16_sigmoid from vllm.platforms import current_platform @@ -137,6 +138,38 @@ def test_fused_topk_bias( torch.testing.assert_close(topk_ids_ref.to(torch.int32), topk_ids, atol=0, rtol=0) +@pytest.mark.skipif( + not current_platform.is_cuda(), reason="This test is skipped on non-CUDA platform." +) +@pytest.mark.parametrize("num_tokens", [1, 2, 8]) +def test_kimi_k3_fused_sigmoid_topk16_matches_reference(num_tokens: int): + torch.manual_seed(20260812) + logits = torch.randn((num_tokens, 896), dtype=torch.float32, device="cuda") + correction_bias = torch.randn((896,), dtype=torch.float32, device="cuda") + hidden_states = torch.empty((num_tokens, 1), dtype=torch.float32, device="cuda") + routed_scaling_factor = 1.7 + + expected_weights, expected_indices = fused_topk_bias( + hidden_states=hidden_states, + gating_output=logits, + scoring_func="sigmoid", + e_score_correction_bias=correction_bias, + topk=16, + renormalize=True, + routed_scaling_factor=routed_scaling_factor, + ) + actual_weights, actual_indices = kimi_topk16_sigmoid( + logits, + correction_bias, + None, + renormalize=True, + routed_scaling_factor=routed_scaling_factor, + ) + + torch.testing.assert_close(actual_weights, expected_weights, atol=0, rtol=0) + torch.testing.assert_close(actual_indices, expected_indices, atol=0, rtol=0) + + @pytest.mark.skipif( not current_platform.is_cuda(), reason="This test is skipped on non-CUDA platform." ) diff --git a/tests/model_executor/model_loader/instanttensor_loader/test_weight_utils.py b/tests/model_executor/model_loader/instanttensor_loader/test_weight_utils.py index a98d882e5d67..e660ba82d36b 100644 --- a/tests/model_executor/model_loader/instanttensor_loader/test_weight_utils.py +++ b/tests/model_executor/model_loader/instanttensor_loader/test_weight_utils.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import glob +import inspect import sys from contextlib import contextmanager from types import SimpleNamespace @@ -11,6 +12,9 @@ from safetensors.torch import save_file import vllm.model_executor.model_loader.weight_utils as weight_utils +from vllm.model_executor.model_loader.reload.layerwise import ( + _own_deferred_accelerator_tensors, +) from vllm.model_executor.model_loader.weight_utils import ( download_weights_from_hf, instanttensor_weights_iterator, @@ -53,6 +57,7 @@ def no_world_group(): raise AssertionError monkeypatch.setenv("INSTANTTENSOR_COPY", setting) + monkeypatch.delenv("INSTANTTENSOR_BUFFER_SIZE", raising=False) monkeypatch.setattr( weight_utils, "current_platform", @@ -136,7 +141,7 @@ def test_instanttensor_restricts_io_to_indexed_shards(tmp_path): "model.expert.weight": str(overlay_shard.resolve()), } - weight_utils._restrict_instanttensor_to_selected_ranges( + cpu_fallback = weight_utils._restrict_instanttensor_to_selected_ranges( instant_open, indexed_tensor_files=indexed_tensor_files, weight_name_prefixes=None, @@ -160,6 +165,75 @@ def test_instanttensor_restricts_io_to_indexed_shards(tmp_path): "model.expert.weight": 1, } assert buffer_sizes == [None] + assert cpu_fallback == [] + + +def test_instanttensor_routes_oversized_selected_tensors_to_cpu(tmp_path): + shard = tmp_path / "model.safetensors" + save_file( + { + "model.large.weight": torch.arange(8, dtype=torch.float32), + "model.small.weight": torch.arange(2, dtype=torch.float32), + }, + shard, + ) + physical_names = [] + with weight_utils.safe_open(shard, framework="pt") as physical_file: + physical_names = list(physical_file.offset_keys()) + metadata_by_name = { + "model.large.weight": {"data_offsets": [0, 32]}, + "model.small.weight": {"data_offsets": [32, 40]}, + } + offsets_by_name = { + "model.large.weight": (0, 32), + "model.small.weight": (32, 40), + } + metadata = [(name, metadata_by_name[name]) for name in physical_names] + offsets = [(0, offsets_by_name[physical_names[0]][0])] + offsets.extend((0, offsets_by_name[name][1]) for name in physical_names) + buffer_sizes = [] + instant_open = SimpleNamespace( + filename=[str(shard)], + ordered_tensor_metadatas=metadata, + tensor_offsets=offsets, + tensor_sizes=[32, 8], + total_tensor_size=40, + tensor_name_to_index={}, + loader_handle=None, + _determine_buffer_size=lambda requested: buffer_sizes.append(requested), + ) + + cpu_fallback = weight_utils._restrict_instanttensor_to_selected_ranges( + instant_open, + indexed_tensor_files=None, + weight_name_prefixes=None, + max_tensor_size=16, + ) + + assert [name for name, _ in instant_open.ordered_tensor_metadatas] == [ + "model.small.weight" + ] + assert cpu_fallback == [("model.large.weight", str(shard))] + assert instant_open.total_tensor_size == 8 + assert buffer_sizes == [None] + + +@pytest.mark.skipif( + not current_platform.is_cuda(), + reason="Borrowed accelerator storage requires CUDA", +) +def test_deferred_loader_owns_accelerator_tensor(): + def loader(param, loaded_weight): + pass + + source = torch.arange(8, device="cuda") + bound_args = inspect.signature(loader).bind(None, source) + + _own_deferred_accelerator_tensors(bound_args) + + owned = bound_args.arguments["loaded_weight"] + assert owned.data_ptr() != source.data_ptr() + assert torch.equal(owned, source) @pytest.mark.skipif( diff --git a/tests/model_executor/model_loader/test_reload.py b/tests/model_executor/model_loader/test_reload.py index 4963f3ae5b42..cbd2c14ff6ee 100644 --- a/tests/model_executor/model_loader/test_reload.py +++ b/tests/model_executor/model_loader/test_reload.py @@ -16,6 +16,7 @@ from vllm.model_executor.layers.quantization.base_config import QuantizeMethodBase from vllm.model_executor.model_loader.reload.layerwise import ( finalize_layerwise_reload, + get_layerwise_info, initialize_layerwise_reload, initialize_online_processing, record_metadata_for_reloading, @@ -686,6 +687,56 @@ def test_online_processing_waits_for_late_registered_bias(): assert torch.equal(quant_method.bias_at_process, loaded_bias) +def test_online_processing_finalizes_checkpoint_omitted_padding(): + class RecordingWeightQuantMethod(QuantizeMethodBase): + uses_meta_device = True + + def __init__(self): + self.weight_at_process = None + self.deferred_weight_count_at_process = None + + def create_weights(self, layer, *args, **kwargs): + raise NotImplementedError + + def apply(self, layer, *args, **kwargs): + raise NotImplementedError + + def process_weights_after_loading(self, layer): + self.weight_at_process = layer.weight.detach().clone() + self.deferred_weight_count_at_process = len( + get_layerwise_info(layer).loaded_weights + ) + + def shard_loader(param, loaded_weight, shard_id): + start = shard_id * loaded_weight.shape[0] + param.data[start : start + loaded_weight.shape[0]].copy_(loaded_weight) + + quant_method = RecordingWeightQuantMethod() + layer = torch.nn.Module() + layer.quant_method = quant_method + weight = torch.nn.Parameter(torch.empty(6, 2, device="meta")) + weight.weight_loader = shard_loader + layer.register_parameter("weight", weight) + initialize_online_processing(layer) + layer._vllm_online_processing_unloaded = {"weight": 4} + + first = torch.full((2, 2), 3.0) + second = torch.full((2, 2), 7.0) + layer.weight.weight_loader(layer.weight, first, 0) + assert quant_method.weight_at_process is None + assert not layer.weight.is_meta + assert torch.equal(layer.weight[:2], first) + assert not get_layerwise_info(layer).loaded_weights + layer.weight.weight_loader(layer.weight, second, 1) + + expected = torch.cat((first, second, torch.zeros(2, 2))) + assert torch.equal(quant_method.weight_at_process, expected) + assert quant_method.deferred_weight_count_at_process == 0 + info = get_layerwise_info(layer) + assert not info.can_load() + assert not info.loaded_weights + + def test_layerwise_reload_skips_non_persistent_parameter_alias_buffers(monkeypatch): layer = _AliasedBufferLayer() model = torch.nn.Sequential(layer) diff --git a/tests/model_executor/test_kimi_k3_triton_warmup.py b/tests/model_executor/test_kimi_k3_triton_warmup.py new file mode 100644 index 000000000000..02c09845e4a6 --- /dev/null +++ b/tests/model_executor/test_kimi_k3_triton_warmup.py @@ -0,0 +1,45 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from types import SimpleNamespace + +import torch + +from vllm.model_executor.warmup.kimi_k3_triton_warmup import ( + _warm_recurrent_kda, +) +from vllm.models.kimi_k3.nvidia.ops.third_party.kda import fused_recurrent + + +def test_speculative_kda_warmup_before_kv_cache_binding(monkeypatch) -> None: + calls = [] + monkeypatch.setattr( + fused_recurrent, + "get_fused_recurrent_kda_fwd_warmup_profiles", + lambda _num_heads: (2,), + ) + monkeypatch.setattr( + fused_recurrent, + "fused_recurrent_kda", + lambda **kwargs: calls.append(kwargs), + ) + + layer = SimpleNamespace( + num_spec=7, + local_num_heads=2, + head_dim=4, + A_log=torch.empty(2, dtype=torch.float32), + dt_bias=torch.empty(8, dtype=torch.float32), + gate_lower_bound=-10.0, + get_state_shape=lambda: ((10, 4), (2, 4, 4)), + get_state_dtype=lambda: (torch.bfloat16, torch.float32), + ) + + _warm_recurrent_kda(layer, torch.bfloat16) + + assert len(calls) == 1 + call = calls[0] + assert call["initial_state"].shape == (1, 2, 4, 4) + assert call["initial_state"].dtype == torch.float32 + assert call["q"].shape == (1, 16, 2, 4) + assert call["ssm_state_indices"].shape == (2, 8) diff --git a/tests/models/kimi_k3/test_sequence_parallel.py b/tests/models/kimi_k3/test_sequence_parallel.py index d5571dda5268..cc73e8bbdd5e 100644 --- a/tests/models/kimi_k3/test_sequence_parallel.py +++ b/tests/models/kimi_k3/test_sequence_parallel.py @@ -358,6 +358,22 @@ def test_kimi_column_parallel_loader_zero_fills_tail(): torch.testing.assert_close(param, expected) +def test_kimi_gate_local_projection_preserves_linear_return_contract(): + layer = object.__new__(kimi_model.KimiColumnParallelGate) + nn.Module.__init__(layer) + layer.weight = nn.Parameter(torch.arange(12).view(3, 4).float()) + hidden_states = torch.arange(8).view(2, 4).float() + + output, bias = layer.forward_local(hidden_states) + + torch.testing.assert_close( + output, + torch.nn.functional.linear(hidden_states, layer.weight), + ) + assert output.dtype == torch.float32 + assert bias is None + + def test_kimi_row_parallel_loader_zero_fills_tail(): layer = object.__new__(kimi_model.KimiPaddedRowParallelLinear) layer.tp_rank = 1 diff --git a/tests/transformers_utils/test_dspark_mla_config.py b/tests/transformers_utils/test_dspark_mla_config.py index f43d668b73cd..6db97703947d 100644 --- a/tests/transformers_utils/test_dspark_mla_config.py +++ b/tests/transformers_utils/test_dspark_mla_config.py @@ -5,9 +5,15 @@ import pytest -from vllm.config import ModelConfig, ParallelConfig, SpeculativeConfig +from vllm.config import LoadConfig, ModelConfig, ParallelConfig, SpeculativeConfig +from vllm.config.quantization import QuantizationConfigArgs, QuantSpec +from vllm.model_executor.layers.quantization.online.base import ( + OnlineQuantizationConfig, +) +from vllm.model_executor.model_loader.weight_utils import get_quant_config from vllm.transformers_utils.config import get_config from vllm.transformers_utils.configs.k3_dspark import K3DSparkConfig +from vllm.v1.attention.backends.registry import AttentionBackendEnum def _write_dspark_config(path, **overrides): @@ -142,7 +148,44 @@ def test_dspark_mla_speculative_config_preserves_architecture(tmp_path): assert speculative_config.draft_model_config.use_mla -def test_dspark_mla_rejects_decode_context_parallelism(tmp_path): +def test_dspark_mla_accepts_draft_online_quantization(tmp_path): + target_path = tmp_path / "target" + draft_path = tmp_path / "draft" + _write_target_config(target_path) + _write_dspark_config(draft_path) + target_config = ModelConfig( + model=str(target_path), tokenizer_mode="skip", max_model_len=32768 + ) + + speculative_config = SpeculativeConfig( + model=str(draft_path), + method="dspark", + num_speculative_tokens=7, + quantization="mxfp8", + quantization_config={ + "linear": "mxfp8", + "ignore": ["re:.*fused_qkv_a_proj$", "model.markov_head.markov_w2"], + }, + target_model_config=target_config, + target_parallel_config=ParallelConfig(), + ) + + draft = speculative_config.draft_model_config + assert draft.quantization == "mxfp8" + assert isinstance(draft.quantization_config, QuantizationConfigArgs) + assert draft.quantization_config.linear == QuantSpec(weight="mxfp8") + assert draft.quantization_config.ignore == [ + "re:.*fused_qkv_a_proj$", + "model.markov_head.markov_w2", + ] + + draft.hf_overrides = lambda hf_config: hf_config + quant_config = get_quant_config(draft, LoadConfig()) + assert isinstance(quant_config, OnlineQuantizationConfig) + assert quant_config.args == draft.quantization_config + + +def test_dspark_mla_dcp_requires_b12x_backend(tmp_path): target_path = tmp_path / "target" draft_path = tmp_path / "draft" _write_target_config(target_path) @@ -151,7 +194,7 @@ def test_dspark_mla_rejects_decode_context_parallelism(tmp_path): model=str(target_path), tokenizer_mode="skip", max_model_len=32768 ) - with pytest.raises(ValueError, match="does not currently support decode context"): + with pytest.raises(ValueError, match="requires attention_backend=B12X_MLA"): SpeculativeConfig( model=str(draft_path), method="dspark", @@ -163,3 +206,29 @@ def test_dspark_mla_rejects_decode_context_parallelism(tmp_path): distributed_executor_backend="external_launcher", ), ) + + +def test_dspark_mla_allows_dcp_with_b12x_backend(tmp_path): + target_path = tmp_path / "target" + draft_path = tmp_path / "draft" + _write_target_config(target_path) + _write_dspark_config(draft_path) + target_config = ModelConfig( + model=str(target_path), tokenizer_mode="skip", max_model_len=32768 + ) + + config = SpeculativeConfig( + model=str(draft_path), + method="dspark", + num_speculative_tokens=7, + attention_backend=AttentionBackendEnum.B12X_MLA, + target_model_config=target_config, + target_parallel_config=ParallelConfig( + tensor_parallel_size=8, + decode_context_parallel_size=8, + distributed_executor_backend="external_launcher", + ), + ) + + assert config.attention_backend is AttentionBackendEnum.B12X_MLA + assert config.target_parallel_config.decode_context_parallel_size == 8 diff --git a/tests/v1/attention/test_b12x_mla.py b/tests/v1/attention/test_b12x_mla.py index 67e662648ce0..3e3867c71c79 100644 --- a/tests/v1/attention/test_b12x_mla.py +++ b/tests/v1/attention/test_b12x_mla.py @@ -32,6 +32,10 @@ def test_b12x_mla_is_registered_with_k3_envelope() -> None: class _FakePlan: + caps = SimpleNamespace(max_page_table_width=4) + num_splits = 1 + chunks_per_split = 1 + def shapes_and_dtypes(self): return (((256,), torch.uint8),) @@ -59,13 +63,18 @@ def run(self, *, binding): def _fake_impl(monkeypatch, *, num_heads: int = 8) -> tuple[B12xMLAImpl, _FakeDenseMLA]: - monkeypatch.setattr(b12x_mla, "is_workspace_manager_initialized", lambda: False) impl = object.__new__(B12xMLAImpl) impl.num_heads = num_heads impl.kv_lora_rank = 512 impl.scale = 192**-0.5 + impl.dcp_world_size = 1 + impl._effective_heads = num_heads + impl._kernel_heads = 8 + impl._dcp_comm_backend = "a2a" + impl._dcp_max_batch_size = 16 impl._compiled_bindings = set() - impl._fallback_scratch = {} + impl._scratch_by_plan = {} + impl._padded_io_by_plan = {} dense_mla = _FakeDenseMLA() impl._dense_mla = dense_mla return impl, dense_mla @@ -126,7 +135,7 @@ def test_b12x_mla_adapter_accepts_non_multiple_of_eight_heads(monkeypatch) -> No output, _ = impl.forward_mqa(q, cache, metadata, layer) assert output.shape == (1, 6, 512) - assert dense_mla.bindings[0].q.shape == (1, 6, 576) + assert dense_mla.bindings[0].q.shape == (1, 8, 576) def test_b12x_mla_adapter_binds_causal_multiquery_blocks(monkeypatch) -> None: @@ -137,11 +146,23 @@ def test_b12x_mla_adapter_binds_causal_multiquery_blocks(monkeypatch) -> None: q = torch.randn(total_q, 8, 576, dtype=torch.bfloat16) cache = torch.randn(8, 16, 576, dtype=torch.bfloat16) query_start_loc = torch.tensor([0, 8, 16], dtype=torch.int32) + source_table = torch.tensor([[0, 1, 2, 3], [4, 5, 6, 7]], dtype=torch.int32) + flat_table = source_table[:, None, :].expand(-1, query_len, -1).reshape(total_q, -1) + flat_lens = torch.cat( + ( + torch.arange(25, 33, dtype=torch.int32), + torch.arange(41, 49, dtype=torch.int32), + ) + ) + flat_query_start = torch.arange(total_q + 1, dtype=torch.int32) metadata = SimpleNamespace( dense_mla_plan=_FakePlan(), + dense_mla_flat_block_table=flat_table, + dense_mla_flat_seq_lens=flat_lens, + dense_mla_flat_query_start_loc=flat_query_start, query_start_loc=query_start_loc, decode=SimpleNamespace( - block_table=torch.tensor([[0, 1, 2, 3], [4, 5, 6, 7]], dtype=torch.int32), + block_table=source_table, seq_lens=torch.tensor([32, 48], dtype=torch.int32), ), ) @@ -156,13 +177,16 @@ def test_b12x_mla_adapter_binds_causal_multiquery_blocks(monkeypatch) -> None: assert output.shape == (total_q, 8, 512) assert lse is not None and lse.shape == (total_q, 8) assert binding.q.shape[0] == total_q - assert binding.cache_seqlens.shape[0] == batch - assert binding.cu_seqlens_q.data_ptr() == query_start_loc.data_ptr() + assert binding.cache_seqlens.data_ptr() == flat_lens.data_ptr() + assert binding.cu_seqlens_q.data_ptr() == flat_query_start.data_ptr() def test_b12x_mla_builder_flattens_non_causal_draft_block(monkeypatch) -> None: builder = object.__new__(B12xMLAMetadataBuilder) builder._dense_mla_plan = _FakePlan() + builder._dense_mla_scratch = None + builder._dense_mla_padded_q = None + builder._dense_mla_padded_output = None builder._max_dense_mla_rows = 16 builder._dense_mla_flat_block_table = torch.zeros(16, 4, dtype=torch.int32) builder._dense_mla_flat_seq_lens = torch.empty(16, dtype=torch.int32) @@ -200,6 +224,52 @@ def test_b12x_mla_builder_flattens_non_causal_draft_block(monkeypatch) -> None: ) +def test_b12x_mla_builder_bounds_single_token_draft_table(monkeypatch) -> None: + page_size = 16 + builder = object.__new__(B12xMLAMetadataBuilder) + builder._dense_mla_plan = _FakePlan() + builder._dense_mla_scratch = None + builder._dense_mla_padded_q = None + builder._dense_mla_padded_output = None + builder._max_dense_mla_rows = 2 + builder._dense_mla_flat_block_table = torch.zeros(2, 4, dtype=torch.int32) + builder._dense_mla_flat_seq_lens = torch.empty(2, dtype=torch.int32) + builder._dense_mla_flat_query_start_loc = torch.arange(3, dtype=torch.int32) + + source_table = torch.tensor( + [[0, 1, 2, 3, 90, 91], [4, 5, 6, 7, 92, 93]], + dtype=torch.int32, + ) + source_lens = torch.tensor([32, 48], dtype=torch.int32) + assert int(source_lens.max()) <= _FakePlan.caps.max_page_table_width * page_size + metadata = SimpleNamespace( + causal=False, + num_decodes=2, + num_decode_tokens=2, + decode=SimpleNamespace( + block_table=source_table, + seq_lens=source_lens, + ), + ) + monkeypatch.setattr( + b12x_mla.MLACommonMetadataBuilder, + "build", + lambda *args, **kwargs: metadata, + ) + + result = builder.build(0, SimpleNamespace()) + + torch.testing.assert_close( + result.dense_mla_flat_block_table, + source_table[:, :4], + ) + torch.testing.assert_close(result.dense_mla_flat_seq_lens, source_lens) + torch.testing.assert_close( + result.dense_mla_flat_query_start_loc, + torch.arange(3, dtype=torch.int32), + ) + + def test_b12x_mla_adapter_uses_flattened_non_causal_rows(monkeypatch) -> None: impl, dense_mla = _fake_impl(monkeypatch, num_heads=6) query_rows = 8 diff --git a/tests/v1/attention/test_mla_context_chunks.py b/tests/v1/attention/test_mla_context_chunks.py index 02363cffa194..9834607e624a 100644 --- a/tests/v1/attention/test_mla_context_chunks.py +++ b/tests/v1/attention/test_mla_context_chunks.py @@ -27,6 +27,7 @@ def build_chunked_context( block_size: int = BLOCK_SIZE, dcp_world_size: int = 1, dcp_local_block_size: int = 1, + direct_dcp_kv_gather: bool = False, ): query_start_loc = torch.zeros(len(query_lens) + 1, dtype=torch.int32) query_start_loc[1:] = torch.tensor(query_lens, dtype=torch.int32).cumsum(0) @@ -42,6 +43,7 @@ def build_chunked_context( dcp_world_size=dcp_world_size, dcp_local_block_size=dcp_local_block_size, dcp_virtual_block_size=dcp_local_block_size * dcp_world_size, + direct_dcp_kv_gather=direct_dcp_kv_gather, ) @@ -233,6 +235,22 @@ def test_dcp_chunks_fit_the_per_rank_row_budget(): assert local_cursor[request] == padded_local +def test_dcp_metadata_preserves_direct_kv_gather_capability(): + """A native DCP backend records its manager-free context gather path.""" + metadata = build_chunked_context( + [256], + [4], + 1024, + dcp_world_size=2, + dcp_local_block_size=64, + direct_dcp_kv_gather=True, + ) + + assert metadata is not None + assert metadata.dcp_manager is None + assert metadata.direct_dcp_kv_gather + + def test_dcp_reorg_uses_each_chunks_local_starts(): """Reorganization drops DCP padding at each request's own chunk offset.""" dcp_world_size, interleave, workspace_size = 2, 64, 1024 diff --git a/tests/v1/attention/test_mla_noncausal.py b/tests/v1/attention/test_mla_noncausal.py index 7aca8400f993..f09f6eeab7bc 100644 --- a/tests/v1/attention/test_mla_noncausal.py +++ b/tests/v1/attention/test_mla_noncausal.py @@ -120,7 +120,8 @@ def test_mla_cache_marker_is_promoted_to_group_capability(): unmarked = MLAAttentionSpec(**kwargs) assert MLAAttentionSpec.merge([marked, marked]).non_causal_multi_token_decode - assert MLAAttentionSpec.merge([marked, unmarked]).non_causal_multi_token_decode + with pytest.raises(AssertionError, match="causal mode"): + MLAAttentionSpec.merge([marked, unmarked]) assert not MLAAttentionSpec.merge( [unmarked, unmarked] ).non_causal_multi_token_decode diff --git a/tests/v1/spec_decode/test_dflash_prefix_cache_masking.py b/tests/v1/spec_decode/test_dflash_prefix_cache_masking.py index 1f8fbc547091..714d8d8c6a09 100644 --- a/tests/v1/spec_decode/test_dflash_prefix_cache_masking.py +++ b/tests/v1/spec_decode/test_dflash_prefix_cache_masking.py @@ -168,3 +168,35 @@ def test_shift_copy_bounded_by_seq_len(): torch.testing.assert_close(block_table[0, :4], original[0, 4:8]) torch.testing.assert_close(block_table[0, 4:], original[0, 4:]) + + +def test_window_shift_updates_shared_sequence_length_once_for_two_groups(): + tables = [_make_block_table(1), _make_block_table(1)] + originals = [table.clone() for table in tables] + idx_mapping = torch.zeros(1, dtype=torch.int32, device=DEVICE) + num_cached_tokens = torch.zeros(1, dtype=torch.int32, device=DEVICE) + seq_lens = torch.full((1,), 8 * BLOCK_SIZE, dtype=torch.int32, device=DEVICE) + draft_kv_window = 4 * BLOCK_SIZE + + shift_draft_block_tables( + tables[0], + idx_mapping, + num_cached_tokens, + seq_lens, + BLOCK_SIZE, + draft_kv_window, + update_seq_lens=False, + ) + shift_draft_block_tables( + tables[1], + idx_mapping, + num_cached_tokens, + seq_lens, + BLOCK_SIZE, + draft_kv_window, + update_seq_lens=True, + ) + + assert seq_lens.item() == draft_kv_window + for table, original in zip(tables, originals): + torch.testing.assert_close(table[0, :4], original[0, 4:8]) diff --git a/tests/v1/spec_decode/test_dspark_attention_config.py b/tests/v1/spec_decode/test_dspark_attention_config.py new file mode 100644 index 000000000000..79665a407570 --- /dev/null +++ b/tests/v1/spec_decode/test_dspark_attention_config.py @@ -0,0 +1,141 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +import copy +from dataclasses import dataclass +from types import SimpleNamespace + +import pytest + +from vllm.v1.attention.backends.registry import AttentionBackendEnum +from vllm.v1.worker.gpu.spec_decode.dflash import speculator as dflash_speculator +from vllm.v1.worker.gpu.spec_decode.dspark import utils as dspark_utils + + +def _speculator(target_config, *, window: int | None = None): + speculator = object.__new__(dflash_speculator.DFlashSpeculator) + speculator.vllm_config = target_config + speculator.requires_non_causal = True + speculator.draft_kv_window = window + speculator.draft_kv_window_block_size = 768 if window is not None else None + return speculator + + +def test_dspark_loader_constructs_model_with_draft_parallel_geometry( + monkeypatch, +) -> None: + """The draft model constructor receives its own DCP and attention config.""" + draft_model_config = SimpleNamespace(hf_config=SimpleNamespace()) + target_config = SimpleNamespace( + speculative_config=SimpleNamespace( + draft_model_config=draft_model_config, + attention_backend=AttentionBackendEnum.B12X_MLA, + ) + ) + draft_config = SimpleNamespace( + parallel_config=SimpleNamespace(decode_context_parallel_size=1), + attention_config=SimpleNamespace(backend=None, use_non_causal=False), + ) + captured = {} + + def fake_replace(value, **updates): + result = copy.copy(value) + for key, update in updates.items(): + setattr(result, key, update) + return result + + class ModelCaptured(RuntimeError): + pass + + def fake_get_model(*, vllm_config, model_config): + captured["vllm_config"] = vllm_config + captured["model_config"] = model_config + raise ModelCaptured + + monkeypatch.setattr( + dspark_utils, + "_create_draft_vllm_config", + lambda config: draft_config if config is target_config else None, + ) + monkeypatch.setattr(dspark_utils, "replace", fake_replace) + monkeypatch.setattr(dspark_utils, "get_model", fake_get_model) + monkeypatch.setattr( + "vllm.model_executor.models.qwen3_dflash.dflash_has_any_non_causal", + lambda _config: True, + ) + + with pytest.raises(ModelCaptured): + dspark_utils.load_dspark_model(object(), target_config) + + assert captured["model_config"] is draft_model_config + loaded_config = captured["vllm_config"] + assert loaded_config.parallel_config.decode_context_parallel_size == 1 + assert loaded_config.attention_config.backend == AttentionBackendEnum.B12X_MLA + assert loaded_config.attention_config.use_non_causal + + +def test_dspark_attention_metadata_uses_draft_parallel_geometry(monkeypatch) -> None: + """An external draft cache retains its configured DCP geometry.""" + target_config = SimpleNamespace( + parallel_config=SimpleNamespace(decode_context_parallel_size=16) + ) + draft_config = SimpleNamespace( + parallel_config=SimpleNamespace(decode_context_parallel_size=1), + attention_config=SimpleNamespace( + backend=AttentionBackendEnum.B12X_MLA, + use_non_causal=False, + ), + ) + monkeypatch.setattr( + dflash_speculator, + "_create_draft_vllm_config", + lambda config: draft_config if config is target_config else None, + ) + + attention_config = _speculator(target_config).attn_vllm_config + + assert attention_config.parallel_config.decode_context_parallel_size == 1 + assert attention_config.attention_config.use_non_causal + assert not draft_config.attention_config.use_non_causal + + +def test_bounded_draft_attention_preserves_derived_model_attributes( + monkeypatch, +) -> None: + """Plan sizing copies runtime objects without reconstructing dataclasses.""" + + @dataclass + class DraftModelConfig: + max_model_len: int + + @dataclass + class DraftAttentionConfig: + use_non_causal: bool + + @dataclass + class DraftConfig: + model_config: DraftModelConfig + attention_config: DraftAttentionConfig + + draft_model_config = DraftModelConfig(max_model_len=1_048_576) + draft_model_config.model_arch_config = object() + draft_config = DraftConfig( + model_config=draft_model_config, + attention_config=DraftAttentionConfig(use_non_causal=False), + ) + target_config = object() + monkeypatch.setattr( + dflash_speculator, + "_create_draft_vllm_config", + lambda config: draft_config if config is target_config else None, + ) + + attention_config = _speculator( + target_config, + window=65_536, + ).attn_vllm_config + + assert draft_model_config.max_model_len == 1_048_576 + assert attention_config.model_config.max_model_len == 65_536 + 768 - 1 + assert attention_config.model_config.model_arch_config is not None + assert attention_config.attention_config.use_non_causal diff --git a/tests/v1/spec_decode/test_dspark_sharded_markov.py b/tests/v1/spec_decode/test_dspark_sharded_markov.py new file mode 100644 index 000000000000..6bd60155dff8 --- /dev/null +++ b/tests/v1/spec_decode/test_dspark_sharded_markov.py @@ -0,0 +1,133 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from types import SimpleNamespace +from unittest.mock import Mock + +import torch + +from vllm.config.compilation import CUDAGraphMode +from vllm.v1.worker.gpu.spec_decode.dspark.speculator import DSparkSpeculator + + +def _make_speculator() -> SimpleNamespace: + head_hidden = torch.randn(8, 16) + model = SimpleNamespace( + compute_local_draft_logits=Mock(side_effect=lambda hidden: hidden[:, :11] + 1) + ) + return SimpleNamespace( + _run_model=Mock(return_value=head_hidden), + model=model, + _markov_outside_cudagraph=True, + _ensure_captured_markov_buffers=Mock(), + _captured_markov_hidden=torch.empty(7, 16), + _captured_base_logits=torch.empty(7, 11), + sample_indices=torch.arange(7), + num_query_per_req=7, + _speculative_steps_for_query_len=lambda query_len: query_len, + _sample_sequential=Mock(), + capacity_activation_batch_size=0, + ) + + +def test_capture_records_backbone_output_without_markov_collectives(monkeypatch): + speculator = _make_speculator() + monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: True) + + DSparkSpeculator._generate_draft( + speculator, + num_reqs=1, + num_tokens_padded=8, + attn_metadata=None, + slot_mappings=None, + num_tokens_across_dp=None, + cudagraph_runtime_mode=CUDAGraphMode.FULL, + ) + + speculator._sample_sequential.assert_not_called() + speculator._ensure_captured_markov_buffers.assert_called_once_with() + torch.testing.assert_close( + speculator._captured_markov_hidden, + speculator._run_model.return_value[:7], + ) + torch.testing.assert_close( + speculator._captured_base_logits, + speculator._run_model.return_value[:7, :11] + 1, + ) + + +def test_capture_warmup_does_not_launch_markov_collectives(monkeypatch): + speculator = _make_speculator() + monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False) + + DSparkSpeculator._generate_draft( + speculator, + num_reqs=1, + num_tokens_padded=8, + attn_metadata=None, + slot_mappings=None, + num_tokens_across_dp=None, + cudagraph_runtime_mode=CUDAGraphMode.NONE, + capture_only=True, + ) + + speculator._sample_sequential.assert_not_called() + speculator._ensure_captured_markov_buffers.assert_called_once_with() + torch.testing.assert_close( + speculator._captured_markov_hidden, + speculator._run_model.return_value[:7], + ) + torch.testing.assert_close( + speculator._captured_base_logits, + speculator._run_model.return_value[:7, :11] + 1, + ) + + +def test_eager_generation_samples_markov_tail(monkeypatch): + speculator = _make_speculator() + monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False) + + DSparkSpeculator._generate_draft( + speculator, + num_reqs=1, + num_tokens_padded=8, + attn_metadata=None, + slot_mappings=None, + num_tokens_across_dp=None, + cudagraph_runtime_mode=CUDAGraphMode.NONE, + ) + + speculator._sample_sequential.assert_called_once_with( + 1, + speculator._run_model.return_value, + 7, + 7, + is_profile=False, + use_capacity=True, + ) + speculator._ensure_captured_markov_buffers.assert_not_called() + + +def test_graph_replay_finishes_markov_tail_from_stable_buffers(): + speculator = _make_speculator() + + DSparkSpeculator._finish_captured_draft( + speculator, + num_reqs=1, + num_tokens_padded=8, + num_query_per_req=7, + is_profile=False, + ) + + args = speculator._sample_sequential.call_args + assert args.args[:4] == (1, None, 7, 7) + assert args.kwargs["is_profile"] is False + assert args.kwargs["use_capacity"] is True + assert ( + args.kwargs["prepared_sample_hidden"].untyped_storage().data_ptr() + == speculator._captured_markov_hidden.untyped_storage().data_ptr() + ) + assert ( + args.kwargs["precomputed_base_logits"].untyped_storage().data_ptr() + == speculator._captured_base_logits.untyped_storage().data_ptr() + ) diff --git a/tools/kimi_k3/benchmark_nospec_decode.py b/tools/kimi_k3/benchmark_nospec_decode.py new file mode 100644 index 000000000000..dae311231fa7 --- /dev/null +++ b/tools/kimi_k3/benchmark_nospec_decode.py @@ -0,0 +1,188 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Measure single-request non-speculative decode throughput.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import statistics +import time +import urllib.request +from pathlib import Path +from typing import Any +from urllib.parse import urlparse + + +def _validated_http_url(url: str) -> str: + """Return an HTTP(S) URL or reject unsupported URL schemes.""" + parsed = urlparse(url) + if parsed.scheme not in {"http", "https"} or not parsed.netloc: + raise ValueError(f"expected an HTTP(S) URL, got {url!r}") + return url + + +def _get(url: str) -> bytes: + url = _validated_http_url(url) + with urllib.request.urlopen(url, timeout=30) as response: # noqa: S310 + return response.read() + + +def _discover_model(url: str) -> str: + payload = json.loads(_get(f"{url}/v1/models")) + models = payload.get("data") or [] + if ( + len(models) != 1 + or not isinstance(models[0], dict) + or not isinstance(models[0].get("id"), str) + ): + raise RuntimeError("--model is required when /v1/models is not singular") + return models[0]["id"] + + +def _run( + *, + url: str, + model: str, + prompt: list[int], + max_tokens: int, + allowed_token_id: int, + output_path: Path, +) -> dict[str, Any]: + payload = json.dumps( + { + "model": model, + "prompt": prompt, + "max_tokens": max_tokens, + "temperature": 0, + "ignore_eos": True, + "allowed_token_ids": [allowed_token_id], + "stream": True, + "stream_options": {"include_usage": True}, + } + ).encode() + request = urllib.request.Request( + f"{url}/v1/completions", + data=payload, + headers={"Content-Type": "application/json"}, + ) + + started = time.perf_counter() + token_times: list[float] = [] + output_parts: list[str] = [] + usage: dict[str, int] = {} + _validated_http_url(request.full_url) + with urllib.request.urlopen(request, timeout=3600) as response: # noqa: S310 + for raw_line in response: + if not raw_line.startswith(b"data: "): + continue + data = raw_line[6:].strip() + if data == b"[DONE]": + break + event = json.loads(data) + if event.get("usage"): + usage = event["usage"] + choices = event.get("choices") or [] + if choices: + token_times.append(time.perf_counter()) + output_parts.append(choices[0].get("text") or "") + ended = time.perf_counter() + + completion_tokens = int(usage.get("completion_tokens", 0)) + if completion_tokens < 2 or len(token_times) < 2: + raise RuntimeError( + f"insufficient stream: usage={usage}, events={len(token_times)}" + ) + if len(token_times) != completion_tokens: + raise RuntimeError( + "stream events do not match completion tokens: " + f"events={len(token_times)}, usage={usage}" + ) + output = "".join(output_parts) + output_path.write_text(output, encoding="utf-8") + decode_seconds = token_times[-1] - token_times[0] + return { + "formula": "(completion_tokens - 1) / (last_token_time - first_token_time)", + "prompt_tokens": int(usage.get("prompt_tokens", len(prompt))), + "completion_tokens": completion_tokens, + "allowed_token_id": allowed_token_id, + "timed_events": len(token_times), + "ttft_seconds": token_times[0] - started, + "decode_seconds": decode_seconds, + "decode_tokens_per_second": (completion_tokens - 1) / decode_seconds, + "wall_seconds": ended - started, + "output_sha256": hashlib.sha256(output.encode()).hexdigest(), + "output_file": str(output_path), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--url", default="http://127.0.0.1:8000") + parser.add_argument("--model") + parser.add_argument("--token-file", type=Path, required=True) + parser.add_argument("--prompt-tokens", type=int, default=256) + parser.add_argument("--max-tokens", type=int, default=1024) + parser.add_argument("--allowed-token-id", type=int, default=13) + parser.add_argument("--warmups", type=int, default=2) + parser.add_argument("--runs", type=int, default=8) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.runs < 1: + parser.error("--runs must be at least 1") + if args.warmups < 0: + parser.error("--warmups must not be negative") + + url = _validated_http_url(args.url.rstrip("/")) + model = args.model or _discover_model(url) + all_prompt = json.loads(args.token_file.read_text(encoding="utf-8")) + prompt = all_prompt[: args.prompt_tokens] + if len(prompt) != args.prompt_tokens or not all( + isinstance(token, int) for token in prompt + ): + raise ValueError("token file lacks the requested integer token prefix") + args.output_dir.mkdir(parents=True, exist_ok=True) + + measured: list[dict[str, Any]] = [] + for index in range(args.warmups + args.runs): + is_warmup = index < args.warmups + run_index = index + 1 if is_warmup else index - args.warmups + 1 + label = f"warmup-{run_index}" if is_warmup else f"run-{run_index}" + result = _run( + url=url, + model=model, + prompt=prompt, + max_tokens=args.max_tokens, + allowed_token_id=args.allowed_token_id, + output_path=args.output_dir / f"{label}.txt", + ) + result = {"run": label, **result} + (args.output_dir / f"{label}.json").write_text( + json.dumps(result, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + print(json.dumps(result, sort_keys=True), flush=True) + if not is_warmup: + measured.append(result) + + rates = [result["decode_tokens_per_second"] for result in measured] + summary = { + "model": model, + "prompt_tokens": args.prompt_tokens, + "max_tokens": args.max_tokens, + "allowed_token_id": args.allowed_token_id, + "runs": args.runs, + "decode_tokens_per_second_median": statistics.median(rates), + "decode_tokens_per_second_min": min(rates), + "decode_tokens_per_second_max": max(rates), + "output_sha256s": [result["output_sha256"] for result in measured], + } + (args.output_dir / "summary.json").write_text( + json.dumps(summary, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + print(json.dumps({"summary": summary}, sort_keys=True), flush=True) + + +if __name__ == "__main__": + main() diff --git a/vllm/compilation/b12x_capture.py b/vllm/compilation/b12x_capture.py index dbaabd148dc0..443f942d7847 100644 --- a/vllm/compilation/b12x_capture.py +++ b/vllm/compilation/b12x_capture.py @@ -3,9 +3,30 @@ from collections.abc import Iterator from contextlib import contextmanager +from contextvars import ContextVar import vllm.envs as envs +_b12x_compile_only_warmup: ContextVar[bool] = ContextVar( + "b12x_compile_only_warmup", + default=False, +) + + +def is_b12x_compile_only_warmup() -> bool: + """Return whether B12X kernels may compile but must not launch.""" + return _b12x_compile_only_warmup.get() + + +@contextmanager +def b12x_compile_only_warmup() -> Iterator[None]: + """Resolve B12X bindings without launching their compute kernels.""" + token = _b12x_compile_only_warmup.set(True) + try: + yield + finally: + _b12x_compile_only_warmup.reset(token) + def b12x_cuda_graph_prewarm_enabled() -> bool: return ( diff --git a/vllm/config/speculative.py b/vllm/config/speculative.py index 1d1f27a58ad3..a51b03e62787 100644 --- a/vllm/config/speculative.py +++ b/vllm/config/speculative.py @@ -16,6 +16,7 @@ from vllm.config.kernel import MoEBackend from vllm.config.model import HfOverrides, ModelConfig from vllm.config.parallel import ParallelConfig +from vllm.config.quantization import QuantizationConfigArgs, resolve_quantization_config from vllm.config.utils import config from vllm.logger import init_logger from vllm.transformers_utils.config import get_hf_text_config @@ -117,6 +118,8 @@ class SpeculativeConfig: """Quantization method that was used to quantize the draft model weights. If `None`, we assume the model weights are not quantized. Note that it only takes effect when using the draft model-based speculative method.""" + quantization_config: dict[str, Any] | QuantizationConfigArgs | None = None + """Optional per-layer online quantization settings for the draft model.""" moe_backend: MoEBackend | None = None """MoE backend to use for the draft model. When `None`, the draft model inherits the target model's `--moe-backend` setting. Useful when the @@ -1035,6 +1038,9 @@ def __post_init__(self): max_model_len=self.max_model_len, # type: ignore[arg-type] spec_target_max_model_len=self.target_model_config.max_model_len, quantization=self.quantization, + quantization_config=resolve_quantization_config( + self.quantization, self.quantization_config + ), enforce_eager=self.target_model_config.enforce_eager, max_logprobs=self.target_model_config.max_logprobs, hf_overrides=draft_hf_overrides, @@ -1166,10 +1172,12 @@ def __post_init__(self): self.method == "dspark" and "K3DSparkModel" in self.draft_model_config.architectures and self.target_parallel_config.decode_context_parallel_size > 1 + and self.attention_backend != AttentionBackendEnum.B12X_MLA ): raise ValueError( - "MLA DSpark does not currently support decode context " - "parallelism; set decode_context_parallel_size=1." + "K3 DSpark decode context parallelism requires " + "attention_backend=B12X_MLA; otherwise set " + "decode_context_parallel_size=1." ) if self.num_speculative_tokens is not None and hasattr( diff --git a/vllm/distributed/communication_op.py b/vllm/distributed/communication_op.py index 5ad99e4e1592..1bc270f3084f 100644 --- a/vllm/distributed/communication_op.py +++ b/vllm/distributed/communication_op.py @@ -14,6 +14,11 @@ def tensor_model_parallel_all_reduce(input_: torch.Tensor) -> torch.Tensor: return get_tp_group().all_reduce(input_) +def tensor_model_parallel_all_reduce_in_place(input_: torch.Tensor) -> torch.Tensor: + """All-reduce a dead input tensor without allocating an output tensor.""" + return get_tp_group().all_reduce_in_place(input_) + + def tensor_model_parallel_all_gather( input_: torch.Tensor, dim: int = -1 ) -> torch.Tensor: diff --git a/vllm/distributed/device_communicators/base_device_communicator.py b/vllm/distributed/device_communicators/base_device_communicator.py index fc4def37f7c9..f752dd49f324 100644 --- a/vllm/distributed/device_communicators/base_device_communicator.py +++ b/vllm/distributed/device_communicators/base_device_communicator.py @@ -220,6 +220,11 @@ def all_reduce(self, input_: torch.Tensor) -> torch.Tensor: dist.all_reduce(input_, group=self.device_group) return input_ + def all_reduce_in_place(self, input_: torch.Tensor) -> torch.Tensor: + """All-reduce while allowing the input storage to hold the result.""" + dist.all_reduce(input_, group=self.device_group) + return input_ + def checkpoint_prepare(self) -> None: """Prepare reclaimable communicator state for checkpoint (default: no-op).""" diff --git a/vllm/distributed/device_communicators/cuda_communicator.py b/vllm/distributed/device_communicators/cuda_communicator.py index 97ba133249fa..32694068b8c3 100644 --- a/vllm/distributed/device_communicators/cuda_communicator.py +++ b/vllm/distributed/device_communicators/cuda_communicator.py @@ -348,6 +348,22 @@ def all_reduce(self, input_): torch.distributed.all_reduce(out, group=self.device_group) return out + def all_reduce_in_place(self, input_: torch.Tensor) -> torch.Tensor: + """Run NCCL with the same tensor as its input and output. + + Functional custom operators cannot return aliased mutable storage, so + callers must use this method only when the source tensor is dead after + the collective. + """ + pynccl_comm = self.pynccl_comm + if pynccl_comm is None or pynccl_comm.disabled: + torch.distributed.all_reduce(input_, group=self.device_group) + return input_ + out = pynccl_comm.all_reduce(input_, out_tensor=input_) + if out is None: + torch.distributed.all_reduce(input_, group=self.device_group) + return input_ + def custom_all_gather(self, input_: torch.Tensor) -> torch.Tensor | None: ca_comm = self.ca_comm if ca_comm is None: diff --git a/vllm/distributed/device_communicators/custom_all_reduce.py b/vllm/distributed/device_communicators/custom_all_reduce.py index 2cf46337e34c..a94211a703df 100644 --- a/vllm/distributed/device_communicators/custom_all_reduce.py +++ b/vllm/distributed/device_communicators/custom_all_reduce.py @@ -93,8 +93,32 @@ def _parse_byte_size(value: str) -> int: return int(value) -def _b12x_pcie_oneshot_limits() -> tuple[int, int, int]: - allreduce_max_size = _parse_byte_size(envs.VLLM_PCIE_ONESHOT_ALLREDUCE_MAX_SIZE) +def _b12x_pcie_allreduce_default_max_size(world_size: int) -> str: + """Return the configured or B12X-recommended all-reduce byte limit.""" + configured = os.getenv("VLLM_PCIE_ONESHOT_ALLREDUCE_MAX_SIZE") + if configured is not None: + return configured + try: + from b12x.comm.pcie.pcie_allreduce import recommended_max_bytes + except Exception: + return envs.VLLM_PCIE_ONESHOT_ALLREDUCE_MAX_SIZE + + default = _parse_byte_size(envs.VLLM_PCIE_ONESHOT_ALLREDUCE_MAX_SIZE) + resolved = recommended_max_bytes(world_size, default=default) + if resolved != default: + logger.info( + "B12X raised the PCIe all-reduce limit for TP%d from %d to %d bytes.", + world_size, + default, + resolved, + ) + return str(resolved) + + +def _b12x_pcie_oneshot_limits(world_size: int = 2) -> tuple[int, int, int]: + allreduce_max_size = _parse_byte_size( + _b12x_pcie_allreduce_default_max_size(world_size) + ) fused_max_size = _parse_byte_size( envs.VLLM_PCIE_ONESHOT_FUSED_ADD_RMS_NORM_MAX_SIZE ) @@ -128,6 +152,16 @@ def _load_b12x_pcie_oneshot_pool() -> Any | None: return PCIeOneshotAllReducePool +@lru_cache(maxsize=1) +def _load_b12x_pcie_allreduce() -> Any | None: + """Load the B12X dispatcher that supports bounded-degree TP12 and TP16.""" + try: + from b12x.comm.pcie import AllReduce as PCIeAllReduce + except Exception: + return None + return PCIeAllReduce + + @lru_cache(maxsize=1) def _load_b12x_pcie_dma() -> Any | None: try: @@ -318,6 +352,7 @@ def __init__( self._pcie_dma = None self._pcie_capture_stream: torch.cuda.Stream | None = None self._pcie_capture_channel_id: str | None = None + self._pcie_runtime_semantic_channels = False self._pcie_allreduce_max_size: int | None = None self._pcie_fused_add_rms_norm_max_size: int | None = None self._cpp_ar_cutoff_size: int | None = None @@ -515,12 +550,15 @@ def __init__( physical_device_ids, ) return - pool_cls = ( - _load_b12x_pcie_oneshot_pool() + use_world_dispatched_b12x = pcie_backend == "b12x" and world_size > 8 + runtime_cls = ( + _load_b12x_pcie_allreduce() + if use_world_dispatched_b12x + else _load_b12x_pcie_oneshot_pool() if pcie_backend == "b12x" else _load_flashinfer_pcie_oneshot_pool() ) - if pool_cls is None: + if runtime_cls is None: logger.warning( "%s PCIe custom allreduce was requested, but its runtime " "is unavailable.", @@ -553,7 +591,7 @@ def __init__( self._pcie_allreduce_max_size, self._pcie_fused_add_rms_norm_max_size, pcie_oneshot_buffer_size, - ) = _b12x_pcie_oneshot_limits() + ) = _b12x_pcie_oneshot_limits(world_size) if self.nccl_group is None: logger.warning( "Custom allreduce is disabled because %s PCIe oneshot " @@ -568,21 +606,31 @@ def __init__( pcie_runtime = None pcie_init_error: Exception | None = None try: - pcie_runtime = pool_cls.from_exchange_group( - exchange_group=self.nccl_group, - device=self.device, - eager_buffer_bytes=pcie_oneshot_buffer_size, - max_size=pcie_oneshot_buffer_size, - single_channel=pcie_single_channel, - max_concurrent_channels=_B12X_PCIE_MAX_CONCURRENT_CHANNELS, - ) - if not pcie_single_channel: - pcie_runtime.prepare_channels((_B12X_PCIE_EAGER_CHANNEL_ID,)) - pcie_runtime.for_stream( - channel_id=( - None if pcie_single_channel else _B12X_PCIE_EAGER_CHANNEL_ID + if use_world_dispatched_b12x: + pcie_runtime = runtime_cls.from_exchange_group( + exchange_group=self.nccl_group, + device=self.device, + eager_buffer_bytes=pcie_oneshot_buffer_size, + max_size=pcie_oneshot_buffer_size, + single_channel=pcie_single_channel, + ) + pcie_runtime.for_stream() + else: + pcie_runtime = runtime_cls.from_exchange_group( + exchange_group=self.nccl_group, + device=self.device, + eager_buffer_bytes=pcie_oneshot_buffer_size, + max_size=pcie_oneshot_buffer_size, + single_channel=pcie_single_channel, + max_concurrent_channels=_B12X_PCIE_MAX_CONCURRENT_CHANNELS, + ) + if not pcie_single_channel: + pcie_runtime.prepare_channels((_B12X_PCIE_EAGER_CHANNEL_ID,)) + pcie_runtime.for_stream( + channel_id=( + None if pcie_single_channel else _B12X_PCIE_EAGER_CHANNEL_ID + ) ) - ) except Exception as exc: pcie_init_error = exc @@ -610,12 +658,18 @@ def __init__( return assert pcie_runtime is not None self._pcie_runtime = pcie_runtime + self._pcie_runtime_semantic_channels = not use_world_dispatched_b12x self._pcie_backend_name = pcie_backend # Prefill-size DMA allreduce alongside the oneshot. A deployment # preflight can tune its crossover or disable it when lossless DMA # never beats NCCL on the selected PCIe topology. + supports_all_peer_auxiliary = bool( + getattr(pcie_runtime, "supports_all_peer_auxiliary", True) + ) dma_min_bytes = ( - _b12x_pcie_dma_min_bytes() if pcie_backend == "b12x" else None + _b12x_pcie_dma_min_bytes() + if pcie_backend == "b12x" and supports_all_peer_auxiliary + else None ) dma_cls = None if dma_min_bytes is None else _load_b12x_pcie_dma() if pcie_backend != "b12x": @@ -623,6 +677,12 @@ def __init__( "FlashInfer PCIe IPC handles only tuned one-shot shapes; " "larger allreduces stay on PyNCCL." ) + elif not supports_all_peer_auxiliary: + logger.info( + "B12X PCIe %s all-reduce does not expose the all-peer " + "topology required by DMA; larger tensors use PyNCCL.", + getattr(pcie_runtime, "algorithm", "bounded-degree"), + ) elif dma_min_bytes is None: logger.info( "b12x PCIe DMA allreduce disabled by " @@ -678,8 +738,9 @@ def __init__( if rank == 0: logger.info( "Configured %s PCIe crossovers: " - "oneshot max=%d, fused max=%d, DMA min=%s.", + "algorithm=%s, allreduce max=%d, fused max=%d, DMA min=%s.", pcie_backend, + getattr(pcie_runtime, "algorithm", "oneshot"), self._pcie_allreduce_max_size, self._pcie_fused_add_rms_norm_max_size, dma_min_bytes if dma_min_bytes is not None else "off", @@ -873,18 +934,25 @@ def capture( if self._pcie_runtime is None: yield else: - if channel_id is None: + uses_semantic_channels = getattr( + self, "_pcie_runtime_semantic_channels", True + ) + if uses_semantic_channels and channel_id is None: raise RuntimeError( "distributed PCIe graph capture requires an explicit " "semantic channel_id" ) self._pcie_capture_stream = stream self._pcie_capture_channel_id = channel_id - with self._pcie_runtime.capture( - stream=stream, - channel_id=channel_id, - ): - yield + if uses_semantic_channels: + with self._pcie_runtime.capture( + stream=stream, + channel_id=channel_id, + ): + yield + else: + with self._pcie_runtime.capture(stream=stream): + yield finally: self._pcie_capture_stream = old_pcie_capture_stream self._pcie_capture_channel_id = old_pcie_capture_channel_id @@ -942,12 +1010,20 @@ def _pcie_runtime_stream(self) -> torch.cuda.Stream | None: def _pcie_runtime_channel_id(self) -> str: return self._pcie_capture_channel_id or _B12X_PCIE_EAGER_CHANNEL_ID + def _pcie_runtime_for_stream(self) -> Any: + """Bind the active PCIe runtime using its stream-ownership contract.""" + assert self._pcie_runtime is not None + stream = self._pcie_runtime_stream() + if getattr(self, "_pcie_runtime_semantic_channels", True): + return self._pcie_runtime.for_stream( + stream, + channel_id=self._pcie_runtime_channel_id(), + ) + return self._pcie_runtime.for_stream(stream) + def register_graph_buffers(self): if self._pcie_runtime is not None: - self._pcie_runtime.for_stream( - self._pcie_runtime_stream(), - channel_id=self._pcie_runtime_channel_id(), - ).register_graph_buffers() + self._pcie_runtime_for_stream().register_graph_buffers() return handle, offset = ops.get_graph_buffer_ipc_meta(self._ptr) logger.debug("Registering %d cuda graph addresses", len(offset)) @@ -975,10 +1051,7 @@ def should_custom_ar(self, inp: torch.Tensor): use_custom = ( self._pcie_allreduce_max_size is not None and inp_size <= self._pcie_allreduce_max_size - and self._pcie_runtime.for_stream( - self._pcie_runtime_stream(), - channel_id=self._pcie_runtime_channel_id(), - ).should_allreduce(inp) + and self._pcie_runtime_for_stream().should_allreduce(inp) ) if ( not use_custom @@ -1060,12 +1133,15 @@ def all_reduce( inp.numel() * inp.element_size(), self._pcie_runtime_stream() is not None, ) - return self._pcie_runtime.all_reduce( - inp, - out=out, - stream=self._pcie_runtime_stream(), - channel_id=self._pcie_runtime_channel_id(), - ) + stream = self._pcie_runtime_stream() + if getattr(self, "_pcie_runtime_semantic_channels", True): + return self._pcie_runtime.all_reduce( + inp, + out=out, + stream=stream, + channel_id=self._pcie_runtime_channel_id(), + ) + return self._pcie_runtime.all_reduce(inp, out=out, stream=stream) if out is None: out = torch.empty_like(inp) if registered: @@ -1105,10 +1181,7 @@ def try_fused_add_rms_norm( ): return False assert self._pcie_runtime is not None - if not self._pcie_runtime.for_stream( - self._pcie_runtime_stream(), - channel_id=self._pcie_runtime_channel_id(), - ).should_allreduce(inp): + if not self._pcie_runtime_for_stream().should_allreduce(inp): return False if ( inp.ndim == 0 @@ -1126,15 +1199,19 @@ def try_fused_add_rms_norm( ): return False + kwargs: dict[str, Any] = { + "out": inp, + "residual_out": residual, + "stream": self._pcie_runtime_stream(), + } + if getattr(self, "_pcie_runtime_semantic_channels", True): + kwargs["channel_id"] = self._pcie_runtime_channel_id() self._pcie_runtime.all_reduce_fused_add_rms_norm( inp, residual, weight, epsilon, - out=inp, - residual_out=residual, - stream=self._pcie_runtime_stream(), - channel_id=self._pcie_runtime_channel_id(), + **kwargs, ) return True diff --git a/vllm/distributed/parallel_state.py b/vllm/distributed/parallel_state.py index 9f2803bc3ae8..c5c4582fbbcf 100644 --- a/vllm/distributed/parallel_state.py +++ b/vllm/distributed/parallel_state.py @@ -687,6 +687,14 @@ def all_reduce(self, input_: torch.Tensor) -> torch.Tensor: else: return self._all_reduce_out_place(input_) + def all_reduce_in_place(self, input_: torch.Tensor) -> torch.Tensor: + """All-reduce a tensor whose input storage may hold the result.""" + if self.world_size == 1: + return input_ + if self.device_communicator is None: + raise ValueError("No device communicator found") + return self.device_communicator.all_reduce_in_place(input_) + def _all_reduce_out_place(self, input_: torch.Tensor) -> torch.Tensor: if self.device_communicator is None: raise ValueError("No device communicator found") @@ -1462,6 +1470,11 @@ def get_dcp_group() -> GroupCoordinator: return _DCP +def dcp_group_is_initialized() -> bool: + """Return whether the decode-context parallel group is initialized.""" + return _DCP is not None + + _QUERY_SPLIT: GroupCoordinator | None = None @@ -1606,18 +1619,30 @@ def checkpoint_b12x_graph_channels() -> tuple[tuple[Callable[[Any], None], Any], if checkpoint is not None: checkpoints.append((rollback_fn, checkpoint)) - if _DCP is not None and _DCP.world_size > 1: + b12x_pool_groups: list[GroupCoordinator] = [] + seen_device_groups: set[int] = set() + for group in (_TP, _DCP): + if group is None or group.world_size <= 1: + continue + group_id = id(group.device_group) + if group_id in seen_device_groups: + continue + seen_device_groups.add(group_id) + b12x_pool_groups.append(group) + + if b12x_pool_groups: from vllm.v1.attention.ops.dcp_alltoall import ( checkpoint_b12x_dcp_a2a_channels, rollback_b12x_dcp_a2a_channels, ) - checkpoints.append( - ( - rollback_b12x_dcp_a2a_channels, - checkpoint_b12x_dcp_a2a_channels(_DCP), + for group in b12x_pool_groups: + checkpoints.append( + ( + rollback_b12x_dcp_a2a_channels, + checkpoint_b12x_dcp_a2a_channels(group), + ) ) - ) return tuple(checkpoints) @@ -1721,15 +1746,26 @@ def graph_capture( if _DCP is not None and get_dcp_group().world_size > 1 else nullcontext() ) + from vllm.v1.attention.ops.dcp_alltoall import capture_b12x_dcp_a2a + + maybe_b12x_tp_capture: contextlib.AbstractContextManager[Any] + if get_tp_group().world_size > 1: + # Kimi-K3 projection gathers use the generic B12X PCIe pool with the + # tensor-parallel process group. Bind that pool to the graph owner in + # the same way as attention's DCP pool. + maybe_b12x_tp_capture = capture_b12x_dcp_a2a( + get_tp_group(), + context.stream, + channel_id=context.channel_id, + ) + else: + maybe_b12x_tp_capture = nullcontext() + maybe_b12x_dcp_capture: contextlib.AbstractContextManager[Any] if _DCP is not None and get_dcp_group().world_size > 1: - # Import locally to avoid making distributed initialization depend on - # attention modules. The helper is a no-op until DCP warmup creates a - # B12X pool for this process group. - from vllm.v1.attention.ops.dcp_alltoall import capture_b12x_dcp_a2a - + dcp_group = get_dcp_group() maybe_b12x_dcp_capture = capture_b12x_dcp_a2a( - get_dcp_group(), + dcp_group, context.stream, channel_id=context.channel_id, ) @@ -1739,6 +1775,7 @@ def graph_capture( get_tp_group().graph_capture(context), get_pp_group().graph_capture(context), maybe_dcp_capture, + maybe_b12x_tp_capture, maybe_b12x_dcp_capture, ): yield context diff --git a/vllm/envs.py b/vllm/envs.py index 6b3d5d275e11..8e4a9a738229 100755 --- a/vllm/envs.py +++ b/vllm/envs.py @@ -64,6 +64,14 @@ VLLM_NVFP4_MLA_SCALES_FILE: str = "" VLLM_B12X_ABSORB_BMM: bool = False VLLM_DSPARK_FP8_DRAFT_HEAD: bool = False + VLLM_DSPARK_DRAFT_KV_WINDOW: int = 0 + VLLM_DSPARK_COMPACT_ROPE: bool = False + VLLM_DSPARK_SHARD_MARKOV_HEAD: bool = False + VLLM_DSPARK_REPLICATE_MARKOV_W1: bool = False + VLLM_KIMI_K3_B12X_DSPARK_ARGMAX: bool = False + VLLM_DSPARK_CAPTURE_SHARDED_MARKOV: bool = False + VLLM_K3_KV_GROUP_SIZE: int = 0 + VLLM_MLA_CHUNKED_PREFILL_WORKSPACE_SIZE: int = 0 VLLM_USE_B12X_WO_PROJECTION: bool = False VLLM_USE_B12X_MOE: bool = False VLLM_NF3_GRID188_DECODE: bool = True @@ -330,6 +338,7 @@ VLLM_GC_DEBUG: str = "" VLLM_DEBUG_WORKSPACE: bool = False VLLM_DISABLE_SHARED_EXPERTS_STREAM: bool = False + VLLM_DISABLE_FUSED_MOE_OUTPUT_ALIAS: bool = False VLLM_SHARED_EXPERTS_STREAM_TOKEN_THRESHOLD: int = 256 VLLM_MULTI_STREAM_GEMM_TOKEN_THRESHOLD: int = 1024 VLLM_COMPILE_CACHE_SAVE_FORMAT: Literal["binary", "unpacked"] = "binary" @@ -351,6 +360,12 @@ VLLM_ELASTIC_EP_DRAIN_REQUESTS: bool = False VLLM_MEMORY_PROFILER_ESTIMATE_CUDAGRAPHS: bool = True VLLM_MEMORY_PROFILE_INCLUDE_ATTN: bool = False + VLLM_KIMI_SHARD_QKV_A: bool = False + VLLM_KIMI_FUSED_TOPK16: bool = False + VLLM_KIMI_USE_B12X_PROJECTION_GATHER: bool = False + VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_GATHER: bool = False + VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_TOPK: bool = False + VLLM_KIMI_USE_B12X_BATCHED_PROJECTION_TOPK: bool = False VLLM_NIXL_EP_MAX_NUM_RANKS: int = 32 VLLM_XPU_ENABLE_XPU_GRAPH: bool = False VLLM_XPU_USE_SAMPLER_KERNEL: bool = True @@ -1138,6 +1153,37 @@ def _resolve_rust_cli_path() -> str | None: "VLLM_DSPARK_FP8_DRAFT_HEAD": lambda: bool( int(os.getenv("VLLM_DSPARK_FP8_DRAFT_HEAD", "0")) ), + # Limit an external DSpark draft to a replicated rolling MLA KV tail while + # the target model retains its complete context. The target verifies every + # proposal, so this can alter acceptance but not target-model semantics. + "VLLM_DSPARK_DRAFT_KV_WINDOW": lambda: int( + os.getenv("VLLM_DSPARK_DRAFT_KV_WINDOW", "0") + ), + # Replace the persistent 1M-position K3 draft RoPE table with stable + # workspaces that materialize only rows consumed by each draft forward. + "VLLM_DSPARK_COMPACT_ROPE": lambda: bool( + int(os.getenv("VLLM_DSPARK_COMPACT_ROPE", "0")) + ), + "VLLM_DSPARK_SHARD_MARKOV_HEAD": lambda: bool( + int(os.getenv("VLLM_DSPARK_SHARD_MARKOV_HEAD", "0")) + ), + "VLLM_DSPARK_REPLICATE_MARKOV_W1": lambda: bool( + int(os.getenv("VLLM_DSPARK_REPLICATE_MARKOV_W1", "0")) + ), + "VLLM_KIMI_K3_B12X_DSPARK_ARGMAX": lambda: bool( + int(os.getenv("VLLM_KIMI_K3_B12X_DSPARK_ARGMAX", "0")) + ), + # Capture TP-sharded deterministic Markov sampling only when every + # collective in the tail uses a CUDA-graph-safe B12X implementation. + "VLLM_DSPARK_CAPTURE_SHARDED_MARKOV": lambda: bool( + int(os.getenv("VLLM_DSPARK_CAPTURE_SHARDED_MARKOV", "0")) + ), + "VLLM_K3_KV_GROUP_SIZE": lambda: int(os.getenv("VLLM_K3_KV_GROUP_SIZE", "0")), + # Bound the number of context tokens expanded into dense MLA K/V tensors + # per attention call. Zero selects the memory-based automatic limit. + "VLLM_MLA_CHUNKED_PREFILL_WORKSPACE_SIZE": lambda: int( + os.getenv("VLLM_MLA_CHUNKED_PREFILL_WORKSPACE_SIZE", "0") + ), # Use b12x for the DeepSeek V4 WO-A/WO-B fused projection. # This is separate from the generic FP8 linear switch for perf isolation. "VLLM_USE_B12X_WO_PROJECTION": lambda: bool( @@ -2244,6 +2290,9 @@ def _resolve_rust_cli_path() -> str | None: "VLLM_DISABLE_SHARED_EXPERTS_STREAM": lambda: bool( int(os.getenv("VLLM_DISABLE_SHARED_EXPERTS_STREAM", "0")) ), + "VLLM_DISABLE_FUSED_MOE_OUTPUT_ALIAS": lambda: bool( + int(os.getenv("VLLM_DISABLE_FUSED_MOE_OUTPUT_ALIAS", "0")) + ), # Limits when we run shared_experts in a separate stream. # We found out that for large batch sizes, the separate stream # execution is not beneficial (most likely because of the input clone) @@ -2343,6 +2392,45 @@ def _resolve_rust_cli_path() -> str | None: "VLLM_MEMORY_PROFILE_INCLUDE_ATTN": lambda: bool( int(os.getenv("VLLM_MEMORY_PROFILE_INCLUDE_ATTN", "0")) ), + # TP-shard Kimi-K3's merged MLA q_a/kv_a projection. The rank-major + # result is reconstructed losslessly before the two logical outputs are + # consumed. + "VLLM_KIMI_SHARD_QKV_A": lambda: bool(int(os.getenv("VLLM_KIMI_SHARD_QKV_A", "0"))), + # Use B12X copy collectives for decode-sized Kimi-K3 projection shards. + # The path is byte-exact and falls back to the ordinary TP collective when + # its shape or topology contract is not satisfied. + "VLLM_KIMI_USE_B12X_PROJECTION_GATHER": lambda: bool( + int(os.getenv("VLLM_KIMI_USE_B12X_PROJECTION_GATHER", "0")) + ), + # Use the bit-exact fused sigmoid and top-16 router for Kimi-K3's + # 896-expert decode shape. + "VLLM_KIMI_FUSED_TOPK16": lambda: bool( + int(os.getenv("VLLM_KIMI_FUSED_TOPK16", "0")) + ), + "VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_GATHER": lambda: bool( + int( + os.getenv( + "VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_GATHER", + "0", + ) + ) + ), + "VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_TOPK": lambda: bool( + int( + os.getenv( + "VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_TOPK", + "0", + ) + ) + ), + "VLLM_KIMI_USE_B12X_BATCHED_PROJECTION_TOPK": lambda: bool( + int( + os.getenv( + "VLLM_KIMI_USE_B12X_BATCHED_PROJECTION_TOPK", + "0", + ) + ) + ), # NIXL EP environment variables "VLLM_NIXL_EP_MAX_NUM_RANKS": lambda: int( os.getenv("VLLM_NIXL_EP_MAX_NUM_RANKS", "32") diff --git a/vllm/model_executor/layers/attention/mla_attention.py b/vllm/model_executor/layers/attention/mla_attention.py index 9adfcfd29c94..6fc64dae5c11 100644 --- a/vllm/model_executor/layers/attention/mla_attention.py +++ b/vllm/model_executor/layers/attention/mla_attention.py @@ -1669,6 +1669,7 @@ def forward_impl( self._v_up_proj_bmm_chunked(attn_out, projected, w_uv_dcp) attn_out = projected if dcp_use_b12x: + sanitize_dcp_attn_empty_rows(attn_out, lse, valid_counts) attn_out = dcp_a2a_lse_reduce( attn_out, lse, @@ -1677,8 +1678,6 @@ def forward_impl( use_b12x=dcp_use_b12x, b12x_max_batch_size=self.dcp_max_batch_size, b12x_query_head_dim=(self.kv_lora_rank + self.qk_rope_head_dim), - seq_lens=seq_lens, - query_start_loc=query_start_loc, ) elif project_before_merge or use_ag_rs_fallback: if project_before_merge: @@ -2503,6 +2502,7 @@ class ChunkedContextMetadata: context_lens_list: list[int] empty_token_slices: list[slice] dcp_manager: MLADCPManager | None = None + direct_dcp_kv_gather: bool = False block_table: torch.Tensor query_start_loc: torch.Tensor @@ -2792,6 +2792,7 @@ def build_mla_chunked_context_metadata( dcp_local_block_size: int, dcp_virtual_block_size: int, dcp_manager: MLADCPManager | None = None, + direct_dcp_kv_gather: bool = False, ) -> "MLACommonPrefillMetadata.ChunkedContextMetadata | None": """Build chunked-context metadata for an MLA prefill. @@ -2811,6 +2812,9 @@ def build_mla_chunked_context_metadata( dcp_local_block_size: Per-rank interleave block size for DCP. dcp_virtual_block_size: ``dcp_local_block_size * dcp_world_size``. dcp_manager: Shared MLA DCP collective manager. + direct_dcp_kv_gather: Use the process DCP group for the context-cache + all-gather when the attention backend implements decode DCP without + a shared ``MLADCPManager``. Returns: The chunked-context metadata, or None when no prefill has any context. @@ -3000,6 +3004,7 @@ def padded_rows(rows: int) -> int: context_lens_list=context_lens, empty_token_slices=empty_token_slices, dcp_manager=dcp_manager, + direct_dcp_kv_gather=direct_dcp_kv_gather, ) @@ -3022,6 +3027,10 @@ class MLACommonMetadataBuilder(AttentionMetadataBuilder[M]): # Whether this builder can flatten a non-causal query block into decode rows. supports_non_causal_multi_token_decode: ClassVar[bool] = False + # A backend with native decode-DCP collectives may omit MLADCPManager. Its + # chunked-prefill path gathers context KV through the process DCP group. + supports_direct_dcp_kv_gather: ClassVar[bool] = False + # The threshold for reordering the batch into decode and prefill requests. # If > 1, the batch will be reordered such that requests with # query length <= threshold are classified as decode requests. @@ -3035,22 +3044,25 @@ def determine_chunked_prefill_workspace_size(vllm_config: VllmConfig) -> int: cache_config = vllm_config.cache_config model_config = vllm_config.model_config - chunked_prefill_workspace_size = min( - # Try for 8 full length request or at least 4 pages per-request - max( - 8 * model_config.max_model_len, - 4 * scheduler_config.max_num_seqs * cache_config.block_size, - ), - # For long-context models try not to over-allocate limiting - # kv-cache space, limiting it to 64k tokens, - # which would result in the workspace being: - # 2*(576)*(64*1024) = 144mb - # (assuming 576 MLA head dim, and fp16) - # which would result in up-projected context being - # 2*(192*128)*(64*1024) = 3gb - # (assuming 192 QK head dim, 128 heads, and fp16) - 64 * 1024, - ) + configured_workspace_size = envs.VLLM_MLA_CHUNKED_PREFILL_WORKSPACE_SIZE + if configured_workspace_size < 0: + raise ValueError( + "VLLM_MLA_CHUNKED_PREFILL_WORKSPACE_SIZE must be non-negative, " + f"got {configured_workspace_size}." + ) + if configured_workspace_size: + chunked_prefill_workspace_size = configured_workspace_size + else: + chunked_prefill_workspace_size = min( + # Try for 8 full length requests or at least 4 pages per request. + max( + 8 * model_config.max_model_len, + 4 * scheduler_config.max_num_seqs * cache_config.block_size, + ), + # Bound persistent compressed-KV storage and transient dense K/V + # projections for long-context models. + 64 * 1024, + ) return align_mla_chunked_context_workspace_size( vllm_config, @@ -3144,11 +3156,14 @@ def __init__( ) attention_layer = self.compilation_config.static_forward_context[layer_names[0]] - try: - self.dcp_world_size = get_dcp_group().world_size - except AssertionError: - # DCP might not be initialized in testing - self.dcp_world_size = 1 + # A model-specific cache group may be replicated even when the target + # model uses DCP. The cache specification is the source of truth for + # the metadata geometry of that group. + self.dcp_world_size = ( + 1 + if getattr(kv_cache_spec, "dcp_replicated", False) + else int(parallel_config.decode_context_parallel_size) + ) self.dcp_local_block_size = parallel_config.cp_kv_cache_interleave_size self.dcp_virtual_block_size = self.dcp_local_block_size * self.dcp_world_size self.cp_kv_cache_interleave_size = parallel_config.cp_kv_cache_interleave_size @@ -3179,11 +3194,20 @@ def __init__( device=device, ) self.dcp_manager = getattr(attention_layer, "dcp_manager", None) - assert isinstance(self.dcp_manager, MLADCPManager) - self.dcp_manager.init_kv_gather( - self.chunked_prefill_workspace, - self.chunked_prefill_workspace_size, - ) + if self.dcp_manager is not None: + if not isinstance(self.dcp_manager, MLADCPManager): + raise TypeError( + "MLA attention layer dcp_manager must be an " + f"MLADCPManager, got {type(self.dcp_manager).__name__}." + ) + self.dcp_manager.init_kv_gather( + self.chunked_prefill_workspace, + self.chunked_prefill_workspace_size, + ) + elif not self.supports_direct_dcp_kv_gather: + raise RuntimeError( + f"{type(self).__name__} requires MLADCPManager when DCP is enabled." + ) else: self.chunked_prefill_workspace = torch.empty( ( @@ -3339,6 +3363,11 @@ def build( dcp_local_block_size=self.dcp_local_block_size, dcp_virtual_block_size=self.dcp_virtual_block_size, dcp_manager=self.dcp_manager, + direct_dcp_kv_gather=( + self.dcp_world_size > 1 + and self.dcp_manager is None + and self.supports_direct_dcp_kv_gather + ), ) prefill_metadata = MLACommonPrefillMetadata( @@ -3778,8 +3807,18 @@ def _context_parallel_compute_prefill_context( ] assert toks * dcp_world_size <= cur_allgather_workspace.shape[0] cur_allgather_kvcache = cur_allgather_workspace[: toks * dcp_world_size] - dcp_manager = cast(MLADCPManager, chunked_context.dcp_manager) - dcp_manager.kv_gather(cur_allgather_kvcache, local_gathered_kvcache) + if chunked_context.dcp_manager is not None: + chunked_context.dcp_manager.kv_gather( + cur_allgather_kvcache, local_gathered_kvcache + ) + elif chunked_context.direct_dcp_kv_gather: + cur_allgather_kvcache.copy_( + get_dcp_group().all_gather(local_gathered_kvcache, dim=0) + ) + else: + raise RuntimeError( + "MLA DCP chunked prefill has no configured KV gather path." + ) assert ( cur_allgather_kvcache.shape[-1] == self.kv_lora_rank + self.qk_rope_head_dim diff --git a/vllm/model_executor/layers/fused_moe/modular_kernel.py b/vllm/model_executor/layers/fused_moe/modular_kernel.py index 7dba2d271a39..94248e36617d 100644 --- a/vllm/model_executor/layers/fused_moe/modular_kernel.py +++ b/vllm/model_executor/layers/fused_moe/modular_kernel.py @@ -1307,7 +1307,8 @@ def _fused_experts( ) use_output_alias = ( - output_alias is not None + not envs.VLLM_DISABLE_FUSED_MOE_OUTPUT_ALIAS + and output_alias is not None and output_alias.shape == fused_out.shape and output_alias.dtype == fused_out.dtype and output_alias.device == fused_out.device diff --git a/vllm/model_executor/model_loader/reload/layerwise.py b/vllm/model_executor/model_loader/reload/layerwise.py index 5aa510a6242a..0116efe28053 100644 --- a/vllm/model_executor/model_loader/reload/layerwise.py +++ b/vllm/model_executor/model_loader/reload/layerwise.py @@ -52,6 +52,50 @@ # Global set used to track loading for logging purposes only LOADING_LAYERS: WeakSet[torch.nn.Module] = WeakSet() +_ONLINE_PROCESSING_UNLOADED_ATTR = "_vllm_online_processing_unloaded" + + +def _online_processing_load_numel_total(layer: torch.nn.Module) -> int: + """Count checkpoint elements required before processing a layer. + + Args: + layer: Layer whose registered tensors and unloaded-tail annotations + define the expected checkpoint payload. + + Returns: + Number of tensor elements that checkpoint weight loaders must provide. + + Raises: + TypeError: If the unloaded-tail annotation is not a dictionary. + ValueError: If an annotated tensor is absent or its unloaded element + count is outside the tensor's bounds. + """ + total = get_layer_size(layer) + unloaded = getattr(layer, _ONLINE_PROCESSING_UNLOADED_ATTR, {}) + if not isinstance(unloaded, dict): + raise TypeError( + f"{_ONLINE_PROCESSING_UNLOADED_ATTR} must be a dict, " + f"got {type(unloaded).__name__}" + ) + for name, numel in unloaded.items(): + tensor = get_layer_tensors(layer).get(name) + if tensor is None: + raise ValueError(f"Annotated unloaded tensor {name!r} is missing") + if not isinstance(numel, int) or not 0 <= numel <= tensor.numel(): + raise ValueError( + f"Invalid unloaded element count for {name}: {numel} " + f"(tensor numel={tensor.numel()})" + ) + total -= numel + return total + + +def _zero_online_processing_unloaded(layer: torch.nn.Module) -> None: + unloaded = getattr(layer, _ONLINE_PROCESSING_UNLOADED_ATTR, {}) + for name, numel in unloaded.items(): + if numel: + getattr(layer, name).data.view(-1)[-numel:].zero_() + def get_layerwise_info(layer: torch.nn.Module) -> LayerReloadingInfo: """ @@ -132,7 +176,7 @@ def initialize_online_processing(layer: torch.nn.Module): # Track loading progress to determine when to process/copy info.load_numel = 0 - info.load_numel_total = get_layer_size(layer) + info.load_numel_total = _online_processing_load_numel_total(layer) _wrap_parameters_weight_loader(layer) @@ -146,6 +190,28 @@ def _wrap_parameters_weight_loader(layer: torch.nn.Module) -> None: tensor.weight_loader = make_online_process_loader(layer, name) +def _own_deferred_accelerator_tensors(bound_args: inspect.BoundArguments) -> None: + """Give deferred weight-loader arguments independent device storage. + + Streaming model loaders may yield views into reusable staging storage. + Layerwise processing replays bound arguments only after every checkpoint + shard for a layer arrives, so accelerator tensors must be cloned before + they enter the deferred queue. This also covers views created by name or + shard mapping because custom attributes on the source tensor are not + guaranteed to propagate to those views. + + Args: + bound_args: Normalized weight-loader arguments to update in place. + """ + for name, value in tuple(bound_args.arguments.items()): + if ( + name != "param" + and isinstance(value, torch.Tensor) + and value.device.type not in ("meta", "cpu") + ): + bound_args.arguments[name] = value.clone() + + def make_online_process_loader(layer: torch.nn.Module, param_name: str) -> Callable: """Create a wrapped weight loader that defers processing.""" info = get_layerwise_info(layer) @@ -176,16 +242,31 @@ def online_process_loader(*args, **kwargs): # Re-run on each load: layers may register parameters later (e.g., `bias`). # Wrap late parameters and refresh `load_numel_total` so processing waits # until all parameters are loaded. - info.load_numel_total = get_layer_size(layer) + info.load_numel_total = _online_processing_load_numel_total(layer) _wrap_parameters_weight_loader(layer) # Bind and normalize arguments bound_args = loader_signature.bind(*args, **kwargs) bound_args.apply_defaults() - # Buffer loaded weights, track loading progress - info.loaded_weights.append((param_name, bound_args)) - num_loaded, ret = get_numel_loaded(original_loader, bound_args) + direct_load = info.kernel_tensors is None and not is_deferred_attention_layer( + layer + ) + if direct_load: + # Initial online quantization does not need to preserve checkpoint + # tensors for a later reload. Load each shard directly into the + # materialized TP-local parameter so a streaming loader never has + # to retain a full checkpoint-wide shard. + materialize_layer(layer, info) + bound_args.arguments["param"] = getattr(layer, param_name) + num_loaded, ret = get_numel_loaded(original_loader, bound_args) + else: + _own_deferred_accelerator_tensors(bound_args) + info.loaded_weights.append((param_name, bound_args)) + num_loaded, ret = get_numel_loaded(original_loader, bound_args) + + # Track loading progress after the destination has been updated or the + # deferred arguments have acquired independent storage. info.load_numel += num_loaded logger.debug( @@ -199,8 +280,9 @@ def online_process_loader(*args, **kwargs): if is_deferred_attention_layer(layer): return ret - # Log warnings allocating excessive buffers on device - if has_device_tensors(bound_args): + # Reloading preserves the existing kernel tensor addresses, so its + # checkpoint arguments still need deferred independent storage. + if not direct_load and has_device_tensors(bound_args): LOADING_LAYERS.add(layer) if len(LOADING_LAYERS) >= 2: names = sorted([layer.__class__.__name__ for layer in LOADING_LAYERS]) @@ -217,6 +299,10 @@ def online_process_loader(*args, **kwargs): # Process and copy when all weights are loaded if info.load_numel >= info.load_numel_total: # type: ignore[operator] + # The source tensor can be a view into a reusable streaming ring. + # Drop the final reference before quantization allocates its output + # and repack workspace. + del bound_args _layerwise_process(layer, info) LOADING_LAYERS.discard(layer) @@ -357,6 +443,17 @@ def _layerwise_process(layer: torch.nn.Module, info: LayerReloadingInfo): args.arguments["param"] = param param.weight_loader(*args.args, **args.kwargs) + if info.kernel_tensors is None: + # Initial online quantization no longer needs the checkpoint tensors + # after they have been copied into the materialized layer. Releasing + # them before quantization keeps the source weights from overlapping + # the quantizer and kernel-repack workspaces. + info.loaded_weights.clear() + if "args" in locals(): + del args + + _zero_online_processing_unloaded(layer) + # Process weights (quantization, repacking, etc.) quant_method = getattr(layer, "quant_method", None) if isinstance(quant_method, QuantizeMethodBase): diff --git a/vllm/model_executor/model_loader/weight_utils.py b/vllm/model_executor/model_loader/weight_utils.py index c63912c576dd..dc3ae8104518 100644 --- a/vllm/model_executor/model_loader/weight_utils.py +++ b/vllm/model_executor/model_loader/weight_utils.py @@ -290,12 +290,20 @@ def get_quant_config( # if hf_quant_config is None, we will try to get config from # hf_overrides hf_overrides = model_config.hf_overrides - if not isinstance(hf_overrides, dict): + if not isinstance(hf_overrides, dict) and model_config.quantization_config is None: raise ValueError( "hf_overrides must be a dict for get_quant_config " "to get the quantization config from it." ) - quantization_config_file = hf_overrides.get("quantization_config_file", None) + # Callable HF overrides cannot carry checkpoint-side quantization metadata, + # but are valid with online quantization: its complete configuration lives + # in ModelConfig.quantization_config. Draft models commonly inherit a + # callable override from the target. + quantization_config_file = ( + hf_overrides.get("quantization_config_file", None) + if isinstance(hf_overrides, dict) + else None + ) if quantization_config_file is not None: if hasattr(quant_cls, "from_config_file"): return quant_cls.from_config_file(quantization_config_file) @@ -305,7 +313,11 @@ def get_quant_config( "but quant_cls.from_config_file is not implemented in " f"{quant_cls}" ) - quantization_config_json = hf_overrides.get("quantization_config_dict_json", None) + quantization_config_json = ( + hf_overrides.get("quantization_config_dict_json", None) + if isinstance(hf_overrides, dict) + else None + ) if quantization_config_json is not None: if hasattr(quant_cls, "from_config_dict_json"): return quant_cls.from_config_dict_json(quantization_config_json) @@ -1229,7 +1241,23 @@ def instanttensor_weights_iterator( raise ValueError(f"INSTANTTENSOR_COPY must be 0 or 1, got {copy_setting!r}") copy_tensors = copy_setting == "1" - restrict_before_io = indexed_tensor_files is not None or bool(weight_name_prefixes) + configured_buffer_size = os.getenv("INSTANTTENSOR_BUFFER_SIZE") + max_gpu_tensor_size: int | None = None + if configured_buffer_size is not None: + try: + max_gpu_tensor_size = int(configured_buffer_size) + except ValueError as e: + raise ValueError( + "INSTANTTENSOR_BUFFER_SIZE must be an integer number of bytes" + ) from e + if max_gpu_tensor_size <= 0: + raise ValueError("INSTANTTENSOR_BUFFER_SIZE must be greater than zero") + + restrict_before_io = ( + indexed_tensor_files is not None + or bool(weight_name_prefixes) + or max_gpu_tensor_size is not None + ) open_kwargs: dict[str, Any] = {} if restrict_before_io: open_kwargs["load_now"] = False @@ -1244,41 +1272,63 @@ def instanttensor_weights_iterator( copy=copy_tensors, **open_kwargs, ) + cpu_fallback_weights: list[tuple[str, str]] = [] if restrict_before_io: - _restrict_instanttensor_to_selected_ranges( + cpu_fallback_weights = _restrict_instanttensor_to_selected_ranges( instant_open, indexed_tensor_files=indexed_tensor_files, weight_name_prefixes=weight_name_prefixes, + max_tensor_size=max_gpu_tensor_size, ) - with instant_open as f: - # Track bytes so the bar reports load throughput (GB/s). - pbar = tqdm( - total=f.total_tensor_size, - desc="Loading safetensors using InstantTensor loader", - disable=not enable_tqdm(use_tqdm_on_load), - bar_format=_BAR_FORMAT, - position=tqdm._get_free_pos(), - unit="B", - unit_scale=True, - unit_divisor=1024, - mininterval=1.0, + if not restrict_before_io or instant_open.ordered_tensor_metadatas: + with instant_open as f: + # Track bytes so the bar reports load throughput (GB/s). + pbar = tqdm( + total=f.total_tensor_size, + desc="Loading safetensors using InstantTensor loader", + disable=not enable_tqdm(use_tqdm_on_load), + bar_format=_BAR_FORMAT, + position=tqdm._get_free_pos(), + unit="B", + unit_scale=True, + unit_divisor=1024, + mininterval=1.0, + ) + try: + tensor: torch.Tensor | None = None + for name, tensor in f.tensors(): + pbar.update(tensor.numel() * tensor.element_size()) + if weight_name_prefixes and not _matches_weight_name_prefixes( + name, weight_name_prefixes + ): + continue + if not copy_tensors: + # Parameter loaders consume borrowed tensors synchronously. + # A deferred loader must own the tensor before advancing. + tensor._vllm_instanttensor_borrowed = True + yield name, tensor + # A generator frame retains its final DLPack-backed view. Drop it + # before the InstantTensor context releases the staging ring. + tensor = None + finally: + pbar.close() + + if cpu_fallback_weights: + assert max_gpu_tensor_size is not None + logger.info_once( + "Loading %d tensors larger than the %d-byte InstantTensor buffer " + "through CPU safetensors", + len(cpu_fallback_weights), + max_gpu_tensor_size, ) - try: - for name, tensor in f.tensors(): - pbar.update(tensor.numel() * tensor.element_size()) - if weight_name_prefixes and not _matches_weight_name_prefixes( - name, weight_name_prefixes - ): - continue - if not copy_tensors: - # Parameter loaders consume borrowed tensors synchronously. - # Loaders retaining a tensor past this yield must materialize - # owned storage before InstantTensor advances its ring buffer. - tensor._vllm_instanttensor_borrowed = True - yield name, tensor - finally: - pbar.close() + fallback_by_file: dict[str, list[str]] = defaultdict(list) + for name, filename in cpu_fallback_weights: + fallback_by_file[filename].append(name) + for filename, names in fallback_by_file.items(): + with safe_open(filename, framework="pt", device="cpu") as fallback_file: + for name in names: + yield name, fallback_file.get_tensor(name) def _restrict_instanttensor_to_selected_ranges( @@ -1286,8 +1336,23 @@ def _restrict_instanttensor_to_selected_ranges( *, indexed_tensor_files: dict[str, str] | None, weight_name_prefixes: Sequence[str] | None, -) -> None: - """Replace an unopened InstantTensor layout with selected byte ranges.""" + max_tensor_size: int | None = None, +) -> list[tuple[str, str]]: + """Restrict an InstantTensor loader to the requested checkpoint ranges. + + Args: + instant_open: Unopened InstantTensor safetensors loader whose metadata + can be restricted before I/O starts. + indexed_tensor_files: Mapping from tensor names to their canonical + checkpoint files. ``None`` accepts tensors from every input file. + weight_name_prefixes: Model parameter prefixes selected for loading. + ``None`` or an empty sequence accepts every prefix. + max_tensor_size: Largest tensor payload, in bytes, retained in the GPU + staging path. Larger selected tensors are assigned to CPU loading. + + Returns: + Pairs of tensor name and checkpoint filename assigned to CPU loading. + """ required_attrs = ( "filename", "ordered_tensor_metadatas", @@ -1313,6 +1378,7 @@ def _restrict_instanttensor_to_selected_ranges( selected_filenames: list[str] = [] selected_metadata: list[tuple[str, dict[str, Any]]] = [] selected_offsets: list[tuple[int, int]] = [] + cpu_fallback_weights: list[tuple[str, str]] = [] metadata_pos = 0 offset_pos = 0 @@ -1334,17 +1400,26 @@ def _restrict_instanttensor_to_selected_ranges( f"for {filename}" ) - keep = [ - ( - indexed_tensor_files is None - or indexed_tensor_files.get(name) == filename_abs + keep = [] + for item_index, name in enumerate(physical_names): + indexed_here = indexed_tensor_files is None or ( + indexed_tensor_files.get(name) == filename_abs ) - and ( - not weight_name_prefixes - or _matches_weight_name_prefixes(name, weight_name_prefixes) + prefix_matches = not weight_name_prefixes or _matches_weight_name_prefixes( + name, weight_name_prefixes ) - for name in physical_names - ] + selected_here = indexed_here and prefix_matches + tensor_size = int(file_offsets[item_index + 1][1]) - int( + file_offsets[item_index][1] + ) + use_cpu_fallback = ( + selected_here + and max_tensor_size is not None + and tensor_size > max_tensor_size + ) + keep.append(selected_here and not use_cpu_fallback) + if use_cpu_fallback: + cpu_fallback_weights.append((name, filename)) run_start = 0 while run_start < tensor_count: @@ -1373,7 +1448,7 @@ def _restrict_instanttensor_to_selected_ranges( raise RuntimeError( "InstantTensor layout contains unaccounted metadata or offsets" ) - if not selected_metadata: + if not selected_metadata and not cpu_fallback_weights: raise RuntimeError("InstantTensor index/prefix selection matched no tensors") selected_names = [name for name, _ in selected_metadata] @@ -1381,6 +1456,16 @@ def _restrict_instanttensor_to_selected_ranges( raise RuntimeError( "InstantTensor index-aware selection still contains duplicate tensor names" ) + fallback_names = [name for name, _ in cpu_fallback_weights] + if len(fallback_names) != len(set(fallback_names)): + raise RuntimeError( + "InstantTensor CPU fallback selection contains duplicate tensor names" + ) + overlap = set(selected_names).intersection(fallback_names) + if overlap: + raise RuntimeError( + f"InstantTensor GPU and CPU selections overlap: {sorted(overlap)[:3]}" + ) selected_sizes = [ int(item["data_offsets"][1]) - int(item["data_offsets"][0]) for _, item in selected_metadata @@ -1394,6 +1479,7 @@ def _restrict_instanttensor_to_selected_ranges( instant_open.tensor_sizes = selected_sizes instant_open.total_tensor_size = sum(selected_sizes) instant_open._determine_buffer_size(None) + return cpu_fallback_weights def pt_weights_iterator( diff --git a/vllm/model_executor/models/qwen3_dflash.py b/vllm/model_executor/models/qwen3_dflash.py index 0cc49dd7ccfe..3351c9a58949 100644 --- a/vllm/model_executor/models/qwen3_dflash.py +++ b/vllm/model_executor/models/qwen3_dflash.py @@ -866,6 +866,12 @@ def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]): name = "model." + name if "embed_tokens" in name: includes_embed_tokens = True + if loaded_weight.is_cuda: + # The draft loader retains every checkpoint tensor until name + # mapping is complete. Streaming loaders can return views into + # a recycled device buffer, so retained tensors need stable + # storage across iterator advancement. + loaded_weight = loaded_weight.to("cpu", copy=True) model_weights[name] = loaded_weight process_eagle_weight(self, name) diff --git a/vllm/model_executor/models/qwen3_dspark.py b/vllm/model_executor/models/qwen3_dspark.py index 01b12f1f0596..bea0a529ad93 100644 --- a/vllm/model_executor/models/qwen3_dspark.py +++ b/vllm/model_executor/models/qwen3_dspark.py @@ -20,6 +20,7 @@ import torch import torch.nn as nn +from vllm import envs from vllm.config import VllmConfig from vllm.logger import init_logger from vllm.model_executor.layers.linear import ReplicatedLinear @@ -27,6 +28,7 @@ from vllm.model_executor.layers.quantization import QuantizationConfig from vllm.model_executor.layers.vocab_parallel_embedding import ( ParallelLMHead, + VocabParallelEmbedding, ) from .qwen3_dflash import DFlashQwen3ForCausalLM, DFlashQwen3Model @@ -43,9 +45,9 @@ class DSparkMarkovHead(nn.Module): (``draft_vocab_size``) added to the base draft logits. The two sizes coincide for full-vocab drafts. - Both weights are replicated because the head runs sequentially for every - draft position. Sharding them would add an all-reduce and a full-vocab - gather to each position. + The default layout replicates both weights. A TP-sharded layout is + available to models that combine local base and Markov logits before an + exact distributed greedy reduction. """ def __init__( @@ -57,6 +59,31 @@ def __init__( quant_config: QuantizationConfig | None = None, ) -> None: super().__init__() + self.shard_across_tp = envs.VLLM_DSPARK_SHARD_MARKOV_HEAD + self.replicate_w1 = envs.VLLM_DSPARK_REPLICATE_MARKOV_W1 + if self.replicate_w1 and not self.shard_across_tp: + raise ValueError( + "VLLM_DSPARK_REPLICATE_MARKOV_W1 requires " + "VLLM_DSPARK_SHARD_MARKOV_HEAD=1." + ) + if self.shard_across_tp: + self.markov_w1 = ( + nn.Embedding(vocab_size, markov_rank) + if self.replicate_w1 + else VocabParallelEmbedding( + vocab_size, + markov_rank, + prefix=maybe_prefix(prefix, "markov_w1"), + ) + ) + self.markov_w2 = ParallelLMHead( + draft_vocab_size, + markov_rank, + bias=False, + quant_config=quant_config, + prefix=maybe_prefix(prefix, "markov_w2"), + ) + return self.markov_w1 = nn.Embedding(vocab_size, markov_rank) self.markov_w2 = ParallelLMHead( draft_vocab_size, @@ -79,6 +106,16 @@ def bias( """Vocab-size transition bias from a Markov embedding ([B, r] -> [B, V]).""" return logits_processor(self.markov_w2, markov_embed) + def local_bias( + self, + markov_embed: torch.Tensor, + logits_processor: LogitsProcessor, + ) -> torch.Tensor: + """Return the unprocessed transition-bias shard owned by this TP rank.""" + if not self.shard_across_tp: + raise RuntimeError("Local Markov bias requires a TP-sharded head.") + return logits_processor._apply_head(self.markov_w2, markov_embed, None) + def apply_bias_gathered( self, markov_embed: torch.Tensor, diff --git a/vllm/model_executor/warmup/kernel_warmup.py b/vllm/model_executor/warmup/kernel_warmup.py index fb273a7f8c33..925d8498e13b 100644 --- a/vllm/model_executor/warmup/kernel_warmup.py +++ b/vllm/model_executor/warmup/kernel_warmup.py @@ -210,21 +210,35 @@ def _warmup_b12x_dcp_a2a(worker: "Worker") -> int: from vllm.models.deepseek_v4.nvidia.b12x import ( DeepseekV4B12xMLAAttention, ) - from vllm.v1.attention.ops.dcp_alltoall import warmup_b12x_dcp_a2a + from vllm.models.kimi_k3.nvidia.mla import ( + MultiHeadLatentAttention as KimiK3MLAAttention, + ) + from vllm.v1.attention.ops.dcp_alltoall import ( + warmup_b12x_dcp_a2a, + ) model = worker.get_model() - candidates = list(model.modules()) + target_dtype = worker.model_config.dtype + candidates = [(module, target_dtype) for module in model.modules()] + speculator = getattr(worker.model_runner, "speculator", None) + draft_model = getattr(speculator, "model", None) + if isinstance(draft_model, nn.Module): + draft_model_config = getattr(speculator, "draft_model_config", None) + draft_dtype = getattr(draft_model_config, "dtype", target_dtype) + candidates.extend((module, draft_dtype) for module in draft_model.modules()) candidates.extend( - worker.vllm_config.compilation_config.static_forward_context.values() + (module, target_dtype) + for module in ( + worker.vllm_config.compilation_config.static_forward_context.values() + ) ) seen_modules: set[int] = set() warmed_signatures: set[tuple[torch.device, torch.dtype, int, int, int]] = set() - for module in candidates: + for module, dtype in candidates: if id(module) in seen_modules: continue seen_modules.add(id(module)) - dtype = worker.model_config.dtype if isinstance(module, DeepseekV4B12xMLAAttention): device = module.attn_sink.device total_heads = int(module.n_local_heads) * dcp_world_size @@ -235,6 +249,17 @@ def _warmup_b12x_dcp_a2a(worker: "Worker") -> int: total_heads = int(module.num_heads) * dcp_world_size query_head_dim = int(module.kv_lora_rank + module.qk_rope_head_dim) output_head_dim = int(module.kv_lora_rank) + elif ( + isinstance(module, KimiK3MLAAttention) + and module.attn_backend.get_name() == "B12X_MLA" + ): + module_dcp_world_size = int(module.impl.dcp_world_size) + if module_dcp_world_size <= 1: + continue + device = next(module.parameters()).device + total_heads = int(module.num_local_heads) * module_dcp_world_size + query_head_dim = int(module.head_size) + output_head_dim = int(module.kv_lora_rank) else: continue @@ -262,6 +287,34 @@ def _warmup_b12x_dcp_a2a(worker: "Worker") -> int: return len(warmed_signatures) +def _warmup_b12x_kimi_projection_gathers(worker: "Worker") -> int: + """Create Kimi projection channels independently of attention DCP.""" + if ( + not envs.VLLM_KIMI_USE_B12X_PROJECTION_GATHER + or not envs.VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_GATHER + ): + return 0 + + from vllm.distributed.parallel_state import get_dcp_group, get_tp_group + from vllm.v1.attention.ops.dcp_alltoall import ( + warmup_b12x_kimi_projection_gathers, + ) + + dcp_group = get_dcp_group() + tp_group = get_tp_group() + projection_group = ( + dcp_group + if dcp_group.world_size == tp_group.world_size + and list(dcp_group.ranks) == list(tp_group.ranks) + else tp_group + ) + model = worker.get_model() + return warmup_b12x_kimi_projection_gathers( + projection_group, + device=next(model.parameters()).device, + ) + + def kernel_warmup(worker: "Worker", *, process_local_only: bool = False) -> bool: if not worker.use_v2_model_runner: # Pooling models do not use the generation slot-mapping path. @@ -323,6 +376,12 @@ def kernel_warmup(worker: "Worker", *, process_local_only: bool = False) -> bool "Warmed up %d B12X DCP collective signature(s).", warmed_dcp_a2a, ) + warmed_projection_gathers = _warmup_b12x_kimi_projection_gathers(worker) + if warmed_projection_gathers: + logger.info( + "Warmed up %d B12X Kimi projection signature(s).", + warmed_projection_gathers, + ) flashinfer_sparse_mla_decode_autotune_warmup(worker) deepseek_v4_sparse_mla_attention_warmup(worker) diff --git a/vllm/model_executor/warmup/kimi_k3_triton_warmup.py b/vllm/model_executor/warmup/kimi_k3_triton_warmup.py index 55390f182423..9900953aa1b1 100644 --- a/vllm/model_executor/warmup/kimi_k3_triton_warmup.py +++ b/vllm/model_executor/warmup/kimi_k3_triton_warmup.py @@ -8,6 +8,7 @@ import torch +import vllm.envs as envs from vllm.logger import init_logger from vllm.platforms import current_platform @@ -103,12 +104,25 @@ def _warm_recurrent_kda( if num_speculative_tokens <= 0: return - kv_cache = layer.kv_cache - if not isinstance(kv_cache, (list, tuple)) or len(kv_cache) < 2: - return - state = kv_cache[1] - if not isinstance(state, torch.Tensor) or not state.numel(): - return + # Kernel warmup precedes production KV-cache allocation. One state page + # uses the production layout and is released when warmup completes. + kv_cache = getattr(layer, "kv_cache", None) + state = ( + kv_cache[1] + if isinstance(kv_cache, (list, tuple)) + and len(kv_cache) >= 2 + and isinstance(kv_cache[1], torch.Tensor) + and kv_cache[1].numel() + else None + ) + if state is None: + state_shape = layer.get_state_shape()[1] + state_dtype = layer.get_state_dtype()[1] + state = torch.empty( + (1, *state_shape), + dtype=state_dtype, + device=layer.A_log.device, + ) logger.info("Warming up Kimi-K3 speculative KDA kernels.") h = int(layer.local_num_heads) @@ -178,5 +192,10 @@ def kimi_k3_triton_warmup(worker: Worker) -> None: if layer is None: return + if envs.VLLM_KIMI_FUSED_TOPK16: + from vllm.models.kimi_k3.nvidia.ops.topk16 import warmup_kimi_topk16 + + warmup_kimi_topk16() + _warm_attn_res(worker) _warm_recurrent_kda(layer, worker.model_config.dtype) diff --git a/vllm/models/kimi_k3/nvidia/dspark_mla.py b/vllm/models/kimi_k3/nvidia/dspark_mla.py index 81715e02c921..bbfeac1b2358 100644 --- a/vllm/models/kimi_k3/nvidia/dspark_mla.py +++ b/vllm/models/kimi_k3/nvidia/dspark_mla.py @@ -2,19 +2,27 @@ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """K3 dense MLA draft model for DSpark speculative decoding.""" -from collections.abc import Iterable +from collections.abc import Iterable, Iterator +from contextlib import contextmanager +from typing import Any import torch import torch.nn as nn import vllm._custom_ops as ops +from vllm import envs from vllm.config import VllmConfig +from vllm.distributed import get_tp_group, tensor_model_parallel_all_gather +from vllm.logger import init_logger from vllm.model_executor.layers.layernorm import RMSNorm from vllm.model_executor.layers.linear import ( + ColumnParallelLinear, MergedColumnParallelLinear, - ReplicatedLinear, ) from vllm.model_executor.layers.logits_processor import LogitsProcessor +from vllm.model_executor.layers.vocab_parallel_embedding import ( + VocabParallelEmbedding, +) from vllm.model_executor.models.qwen3_dspark import DSparkMarkovHead from vllm.model_executor.models.utils import ( AutoWeightsLoader, @@ -28,6 +36,37 @@ from vllm.utils.torch_utils import is_quantized_kv_cache from vllm.v1.worker.workspace import current_workspace_manager +logger = init_logger(__name__) + +_COMPACT_ROPE_PROTECTED_IDS: set[int] = set() + + +def _load_b12x_vocab_parallel_argmax() -> Any | None: + """Return the B12X vocabulary reducer when its full contract is present.""" + try: + from b12x.comm.pcie import VocabParallelArgmax + except ImportError: + return None + if not callable(getattr(VocabParallelArgmax, "from_exchange_group", None)): + return None + if not callable(getattr(VocabParallelArgmax, "fused_add_argmax", None)): + return None + return VocabParallelArgmax + + +@contextmanager +def protect_k3_compact_rope_sources(model: nn.Module) -> Iterator[None]: + """Prevent a K3 draft from truncating RoPE modules owned by ``model``.""" + previous = _COMPACT_ROPE_PROTECTED_IDS.copy() + _COMPACT_ROPE_PROTECTED_IDS.update( + id(module) for module in model.modules() if hasattr(module, "cos_sin_cache") + ) + try: + yield + finally: + _COMPACT_ROPE_PROTECTED_IDS.clear() + _COMPACT_ROPE_PROTECTED_IDS.update(previous) + def _duplicate_context_kv_weights( weights: Iterable[tuple[str, torch.Tensor]], num_layers: int @@ -51,6 +90,32 @@ def _duplicate_context_kv_weights( yield f"context_kv_proj.{param_name}", fused_weight +def _fill_compact_rope_cache( + positions: torch.Tensor, + inv_freq: torch.Tensor, + freqs_workspace: torch.Tensor, + cache_workspace: torch.Tensor, + *, + mscale: float, +) -> torch.Tensor: + """Materialize RoPE rows consumed by one K3 draft forward.""" + num_positions = int(positions.shape[0]) + if num_positions > int(freqs_workspace.shape[0]): + raise ValueError( + "K3 DSpark compact RoPE workspace is too small: " + f"positions={num_positions}, capacity={freqs_workspace.shape[0]}." + ) + freqs = freqs_workspace[:num_positions] + cache = cache_workspace[:num_positions] + half_dim = int(inv_freq.shape[0]) + torch.mul(positions[:, None], inv_freq[None, :], out=freqs) + torch.cos(freqs, out=cache[:, :half_dim]) + torch.sin(freqs, out=cache[:, half_dim:]) + if mscale != 1.0: + cache.mul_(mscale) + return cache + + class K3DSparkDecoderLayer(nn.Module): def __init__( self, @@ -101,6 +166,7 @@ def forward( positions: torch.Tensor, hidden_states: torch.Tensor, residual: torch.Tensor | None, + rope_cos_sin_cache: torch.Tensor | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: if residual is None: # First layer: hidden_states is the (already reduced) embedding. @@ -114,6 +180,7 @@ def forward( hidden_states = self.self_attn( positions=positions, hidden_states=hidden_states, + rope_cos_sin_cache=rope_cos_sin_cache, ) hidden_states, residual = fused_allreduce_rms_norm( hidden_states, residual, self.post_attention_layernorm @@ -140,10 +207,14 @@ def __init__( # The frozen target embedding is aliased after the draft checkpoint loads. self.embed_tokens: nn.Module | None = None - self.context_proj = ReplicatedLinear( + # Target auxiliary states are identical across TP ranks. Shard the + # projection's output rows and gather its small activation instead of + # retaining and evaluating the complete matrix on every rank. + self.context_proj = ColumnParallelLinear( self.config.target_hidden_size * self.config.num_target_layers, self.config.hidden_size, bias=False, + gather_output=True, return_bias=False, quant_config=self.quant_config, prefix=maybe_prefix(prefix, "context_proj"), @@ -187,6 +258,106 @@ def __init__( self._max_num_context_tokens = ( vllm_config.scheduler_config.max_num_batched_tokens ) + self._compact_rope_enabled = bool(envs.VLLM_DSPARK_COMPACT_ROPE) + if self._compact_rope_enabled: + self._init_compact_rope() + + def _init_compact_rope(self) -> None: + rotary_modules = [layer.self_attn.rotary_emb for layer in self.layers] + if not rotary_modules or any(rotary is None for rotary in rotary_modules): + raise RuntimeError("K3 DSpark compact RoPE requires rotary draft layers.") + rotary = rotary_modules[0] + assert rotary is not None + if any(candidate is not rotary for candidate in rotary_modules[1:]): + raise RuntimeError( + "K3 DSpark compact RoPE requires all draft layers to share one " + "immutable rotary embedding." + ) + if not hasattr(rotary, "scaling_factor"): + raise TypeError( + "K3 DSpark compact RoPE requires a YaRN rotary embedding, got " + f"{type(rotary).__name__}." + ) + + full_cache = rotary.cos_sin_cache + if full_cache.dtype != torch.float32 or full_cache.ndim != 2: + raise TypeError( + "K3 DSpark compact RoPE requires a 2-D fp32 source cache, got " + f"shape={tuple(full_cache.shape)}, dtype={full_cache.dtype}." + ) + with torch.device(full_cache.device): + inv_freq = rotary._compute_inv_freq(rotary.scaling_factor) # noqa: SLF001 + inv_freq = inv_freq.to(dtype=torch.float32) + half_dim = int(inv_freq.shape[0]) + if int(full_cache.shape[1]) != 2 * half_dim: + raise ValueError( + "K3 DSpark compact RoPE frequency width does not match its " + f"source table: inv_freq={half_dim}, cache={full_cache.shape[1]}." + ) + + self.register_buffer("_compact_rope_inv_freq", inv_freq, persistent=False) + self.register_buffer( + "_compact_rope_freqs", + torch.empty( + (self._max_num_context_tokens, half_dim), + dtype=torch.float32, + device=full_cache.device, + ), + persistent=False, + ) + self.register_buffer( + "_compact_rope_cache", + torch.empty( + (self._max_num_context_tokens, 2 * half_dim), + dtype=torch.float32, + device=full_cache.device, + ), + persistent=False, + ) + self.register_buffer( + "_compact_rope_positions", + torch.arange( + self._max_num_context_tokens, + dtype=torch.int64, + device=full_cache.device, + ), + persistent=False, + ) + self._compact_rope_mscale = float(rotary.mscale) + + if id(rotary) in _COMPACT_ROPE_PROTECTED_IDS: + logger.warning_once( + "K3 DSpark compact RoPE retains a source table shared with " + "the target model." + ) + return + + released_bytes = full_cache.numel() * full_cache.element_size() + rotary.cos_sin_cache = torch.empty( + (0, 2 * half_dim), dtype=torch.float32, device=full_cache.device + ) + logger.info_once( + "K3 DSpark compact RoPE released %.2f MiB/rank; materializing at " + "most %d fp32 rows per forward.", + released_bytes / (1024**2), + self._max_num_context_tokens, + ) + + def _get_rope_inputs( + self, positions: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + rotary = self.layers[0].self_attn.rotary_emb + assert rotary is not None + if not self._compact_rope_enabled: + return positions, rotary.cos_sin_cache + cache = _fill_compact_rope_cache( + positions, + self._compact_rope_inv_freq, + self._compact_rope_freqs, + self._compact_rope_cache, + mscale=self._compact_rope_mscale, + ) + return self._compact_rope_positions[: positions.shape[0]], cache def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: assert self.embed_tokens is not None @@ -267,7 +438,8 @@ def _precompute_fused_context_kv( ((num_layers * self._max_num_context_tokens,), torch.int64), ) repeated_positions = repeated_positions[: num_layers * num_ctx] - repeated_positions.view(num_layers, num_ctx).copy_(context_positions) + rope_positions, rope_cos_sin_cache = self._get_rope_inputs(context_positions) + repeated_positions.view(num_layers, num_ctx).copy_(rope_positions) # Keep the single-tensor context RoPE on vLLM's optimized CUDA op; # DeepSeek YaRN's FlashInfer wrapper assumes a non-null key tensor. rotary_emb = self.layers[0].self_attn.rotary_emb @@ -277,7 +449,7 @@ def _precompute_fused_context_kv( all_k_pe_flat, None, rotary_emb.head_size, - rotary_emb.cos_sin_cache, + rope_cos_sin_cache, rotary_emb.is_neox_style, ) all_k_pe = all_k_pe_flat.view(num_layers, num_ctx, 1, self._context_rope_dim) @@ -383,11 +555,13 @@ def forward( hidden_states = inputs_embeds residual = None + rope_positions, rope_cos_sin_cache = self._get_rope_inputs(positions) for layer in self.layers: hidden_states, residual = layer( - positions=positions, + positions=rope_positions, hidden_states=hidden_states, residual=residual, + rope_cos_sin_cache=rope_cos_sin_cache, ) hidden_states, _ = fused_allreduce_rms_norm( hidden_states, residual, self.final_norm @@ -432,6 +606,21 @@ def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None: self.logits_processor = LogitsProcessor( self.config.draft_vocab_size, scale=logit_scale ) + argmax_requested = bool(envs.VLLM_KIMI_K3_B12X_DSPARK_ARGMAX) + self._b12x_dspark_argmax_cls = ( + _load_b12x_vocab_parallel_argmax() if argmax_requested else None + ) + self._b12x_dspark_argmax_enabled = self._b12x_dspark_argmax_cls is not None + if argmax_requested and not self._b12x_dspark_argmax_enabled: + logger.warning_once( + "B12X does not provide the complete VocabParallelArgmax API; " + "Kimi-K3 DSpark uses the exact vocabulary all-gather fallback." + ) + self._b12x_dspark_argmax_max_batch = min( + vllm_config.scheduler_config.max_num_seqs, 8 + ) + self._b12x_dspark_argmax_runtime: Any = None + self._b12x_dspark_argmax_output: torch.Tensor | None = None def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: return self.model.embed_input_ids(input_ids) @@ -467,6 +656,110 @@ def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor: def compute_draft_logits(self, hidden_states: torch.Tensor) -> torch.Tensor: return self.compute_logits(hidden_states) + def supports_local_draft_argmax(self) -> bool: + """Check whether exact local-shard greedy sampling is supported. + + Returns: + True when target and Markov vocabulary shards have compatible + layouts and logits processing preserves greedy ordering. + """ + markov_head = self.model.markov_head + if not markov_head.shard_across_tp: + return False + if not isinstance(self.lm_head, VocabParallelEmbedding): + return False + markov_w2 = markov_head.markov_w2 + if not isinstance(markov_w2, VocabParallelEmbedding): + return False + layout_fields = ( + "tp_size", + "tp_rank", + "num_embeddings", + "org_vocab_size", + "num_embeddings_padded", + "num_embeddings_per_partition", + ) + mismatches = [ + field + for field in layout_fields + if getattr(self.lm_head, field) != getattr(markov_w2, field) + ] + if mismatches or self.lm_head.shard_indices != markov_w2.shard_indices: + return False + if self.logits_processor.soft_cap is not None: + return False + return self.logits_processor.scale > 0.0 + + def compute_local_draft_logits(self, hidden_states: torch.Tensor) -> torch.Tensor: + assert isinstance(self.lm_head, VocabParallelEmbedding) + return self.logits_processor._apply_head(self.lm_head, hidden_states, None) + + def compute_local_markov_bias(self, markov_embed: torch.Tensor) -> torch.Tensor: + return self.model.markov_head.local_bias(markov_embed, self.logits_processor) + + def gather_local_draft_logits( + self, + base_logits: torch.Tensor, + markov_bias: torch.Tensor, + ) -> torch.Tensor: + """Gather a complete distribution after adding matching local shards.""" + assert isinstance(self.lm_head, VocabParallelEmbedding) + logits = tensor_model_parallel_all_gather(base_logits + markov_bias, dim=-1) + return logits[..., : self.logits_processor.org_vocab_size] + + def _get_b12x_dspark_argmax(self, base_logits: torch.Tensor) -> Any | None: + runtime = self._b12x_dspark_argmax_runtime + if runtime is not None: + return runtime + + argmax_cls = self._b12x_dspark_argmax_cls + if argmax_cls is None: + self._b12x_dspark_argmax_enabled = False + return None + + runtime = argmax_cls.from_exchange_group( + exchange_group=get_tp_group().cpu_group, + device=base_logits.device, + local_vocab_size=base_logits.shape[-1], + max_batch_size=self._b12x_dspark_argmax_max_batch, + ) + self._b12x_dspark_argmax_output = torch.empty( + self._b12x_dspark_argmax_max_batch, + dtype=torch.int64, + device=base_logits.device, + ) + self._b12x_dspark_argmax_runtime = runtime + logger.info_once( + "Kimi-K3 DSpark uses B12X TP16 fused BF16 add/global argmax " + "for up to %d requests.", + self._b12x_dspark_argmax_max_batch, + ) + return runtime + + def sample_local_draft_logits( + self, + base_logits: torch.Tensor, + markov_bias: torch.Tensor, + ) -> torch.Tensor: + assert isinstance(self.lm_head, VocabParallelEmbedding) + batch_size = int(base_logits.shape[0]) + if ( + self._b12x_dspark_argmax_enabled + and self.lm_head.tp_size == 16 + and base_logits.dtype == torch.bfloat16 + and markov_bias.dtype == torch.bfloat16 + and 0 < batch_size <= self._b12x_dspark_argmax_max_batch + ): + runtime = self._get_b12x_dspark_argmax(base_logits) + if runtime is not None: + assert self._b12x_dspark_argmax_output is not None + return runtime.fused_add_argmax( + base_logits, + markov_bias, + out=self._b12x_dspark_argmax_output[:batch_size], + ) + return self.gather_local_draft_logits(base_logits, markov_bias).argmax(dim=-1) + def map_draft_to_target(self, draft_ids: torch.Tensor) -> torch.Tensor: return draft_ids diff --git a/vllm/models/kimi_k3/nvidia/kda.py b/vllm/models/kimi_k3/nvidia/kda.py index 0abec01e36cf..f306c572f658 100644 --- a/vllm/models/kimi_k3/nvidia/kda.py +++ b/vllm/models/kimi_k3/nvidia/kda.py @@ -43,6 +43,9 @@ KimiK3KDAAttentionBackend, KimiK3KDAMetadata, ) +from vllm.models.kimi_k3.nvidia.tp_projection import ( + gather_kimi_sharded_projection, +) from vllm.platforms import current_platform from vllm.third_party.flash_linear_attention.ops.kda import FusedRMSNormGated from vllm.transformers_utils.configs.kimi_linear import KimiLinearConfig @@ -334,6 +337,25 @@ def __init__( self.num_heads = kda_config["num_heads"] assert self.num_heads % self.tp_size == 0 self.local_num_heads = divide(self.num_heads, self.tp_size) + additional_config = vllm_config.additional_config + self.shard_f_a = bool( + additional_config.get("kda_shard_f_a", False) + if isinstance(additional_config, dict) + else False + ) + if self.shard_f_a: + assert self.head_dim % self.tp_size == 0, ( + "KDA f_a output sharding requires head_dim to be divisible " + f"by TP size, got head_dim={self.head_dim}, TP={self.tp_size}." + ) + self.local_fa_size = divide(self.head_dim, self.tp_size) + logger.info_once( + "TP-sharding the KDA f_a projection output (%d -> %d rows/rank).", + self.head_dim, + self.local_fa_size, + ) + else: + self.local_fa_size = self.head_dim self.projection_size = self.head_dim * self.num_heads self.local_projection_size = divide(self.projection_size, self.tp_size) self.conv_size = kda_config["short_conv_kernel_size"] @@ -349,7 +371,7 @@ def __init__( self.num_heads, ] local_output_size = ( - 4 * self.local_projection_size + self.head_dim + self.local_num_heads + 4 * self.local_projection_size + self.local_fa_size + self.local_num_heads ) self.in_proj_padding = -local_output_size % 16 self.split_mixed_precision_input = use_split_mixed_precision_input_projection( @@ -373,30 +395,54 @@ def __init__( ] if self.in_proj_padding: gfab_output_sizes.append(self.in_proj_padding * self.tp_size) - self.in_proj_gfab = _KimiGDNMergedColumnParallelLinear( - self.hidden_size, - gfab_output_sizes, - replicated_shard_id=1, - tp_size=self.tp_size, - bias=False, - quant_config=self.quant_config, - prefix=f"{prefix}.in_proj_gfab", - ) + if self.shard_f_a: + self.in_proj_gfab = MergedColumnParallelLinear( + self.hidden_size, + gfab_output_sizes, + bias=False, + quant_config=self.quant_config, + prefix=f"{prefix}.in_proj_gfab", + ) + else: + self.in_proj_gfab = _KimiGDNMergedColumnParallelLinear( + self.hidden_size, + gfab_output_sizes, + replicated_shard_id=1, + tp_size=self.tp_size, + bias=False, + quant_config=self.quant_config, + prefix=f"{prefix}.in_proj_gfab", + ) if self.in_proj_padding: + self.in_proj_gfab._vllm_online_processing_unloaded = { + "weight": self.in_proj_padding * self.hidden_size, + } self.in_proj_gfab.weight.data[-self.in_proj_padding :].zero_() else: if self.in_proj_padding: in_proj_output_sizes.append(self.in_proj_padding * self.tp_size) - self.in_proj_qkvgfab = _KimiGDNMergedColumnParallelLinear( - self.hidden_size, - in_proj_output_sizes, - replicated_shard_id=4, - tp_size=self.tp_size, - bias=False, - quant_config=self.quant_config, - prefix=f"{prefix}.in_proj_qkvgfab", - ) + if self.shard_f_a: + self.in_proj_qkvgfab = MergedColumnParallelLinear( + self.hidden_size, + in_proj_output_sizes, + bias=False, + quant_config=self.quant_config, + prefix=f"{prefix}.in_proj_qkvgfab", + ) + else: + self.in_proj_qkvgfab = _KimiGDNMergedColumnParallelLinear( + self.hidden_size, + in_proj_output_sizes, + replicated_shard_id=4, + tp_size=self.tp_size, + bias=False, + quant_config=self.quant_config, + prefix=f"{prefix}.in_proj_qkvgfab", + ) if self.in_proj_padding: + self.in_proj_qkvgfab._vllm_online_processing_unloaded = { + "weight": self.in_proj_padding * self.hidden_size, + } self.in_proj_qkvgfab.weight.data[-self.in_proj_padding :].zero_() self.f_b_proj = ColumnParallelLinear( @@ -524,7 +570,7 @@ def forward( mixed_qkv = self.in_proj_qkv(hidden_states)[0] gfab_split_sizes = [ self.local_projection_size, - self.head_dim, + self.local_fa_size, self.local_num_heads, ] if self.in_proj_padding: @@ -538,7 +584,7 @@ def forward( split_sizes = [ 3 * self.local_projection_size, self.local_projection_size, - self.head_dim, + self.local_fa_size, self.local_num_heads, ] if self.in_proj_padding: @@ -546,6 +592,8 @@ def forward( projected = projected_qkvgfab.split(split_sizes, dim=-1) mixed_qkv, g_proj_states, f_a, beta = projected[:4] + if self.shard_f_a: + f_a = gather_kimi_sharded_projection(f_a) g1 = self.f_b_proj(f_a)[0] beta = beta.unsqueeze(0) g1 = rearrange(g1, "n (h d) -> 1 n h d", d=self.head_dim) diff --git a/vllm/models/kimi_k3/nvidia/mla.py b/vllm/models/kimi_k3/nvidia/mla.py index a079406f805a..96a70be67600 100644 --- a/vllm/models/kimi_k3/nvidia/mla.py +++ b/vllm/models/kimi_k3/nvidia/mla.py @@ -34,6 +34,7 @@ import torch from torch import nn +import vllm.envs as envs from vllm import _custom_ops as ops from vllm.compilation.breakable_cudagraph import eager_break_during_capture from vllm.config import ( @@ -70,6 +71,9 @@ fused_mla_key_concat_kv_cache_insert, fused_mla_qkv_quant_kv_cache_fp8_insert, ) +from vllm.models.kimi_k3.nvidia.tp_projection import ( + gather_kimi_sharded_projection, +) from vllm.platforms import current_platform from vllm.transformers_utils.configs.kimi_linear import KimiLinearConfig from vllm.utils.multi_stream_utils import maybe_execute_in_parallel @@ -86,7 +90,12 @@ from vllm.v1.attention.ops.dcp_utils import MLADCPManager from vllm.v1.attention.ops.merge_attn_states import merge_attn_states from vllm.v1.attention.selector import get_attn_backend -from vllm.v1.kv_cache_interface import KVCacheSpec, MLAAttentionSpec, get_kv_quant_mode +from vllm.v1.kv_cache_interface import ( + KVCacheSpec, + MLAAttentionSpec, + SlidingWindowMLASpec, + get_kv_quant_mode, +) if TYPE_CHECKING: from vllm.model_executor.layers.attention.mla_attention import MLACommonMetadata @@ -105,6 +114,67 @@ def _gate_sigmoid_mul(attn_out: torch.Tensor, gate: torch.Tensor) -> torch.Tenso return attn_out * gate.sigmoid() +def _restore_merged_output_order( + rank_major_output: torch.Tensor, + output_sizes: list[int], + tp_size: int, +) -> torch.Tensor: + """Convert rank-major merged shards into logical projection order.""" + if tp_size == 1: + return rank_major_output + if any(size % tp_size for size in output_sizes): + raise ValueError( + f"Merged output sizes {output_sizes} must be divisible by TP={tp_size}" + ) + local_sizes = [size // tp_size for size in output_sizes] + local_total = sum(local_sizes) + expected_width = local_total * tp_size + if rank_major_output.shape[-1] != expected_width: + raise ValueError( + "Unexpected gathered merged projection width: " + f"got {rank_major_output.shape[-1]}, expected {expected_width}" + ) + rank_major = rank_major_output.unflatten(-1, (tp_size, local_total)) + logical_local_shards = rank_major.split(local_sizes, dim=-1) + return torch.cat( + [shards.flatten(-2) for shards in logical_local_shards], + dim=-1, + ) + + +class KimiShardedMergedColumnParallelLinear(MergedColumnParallelLinear): + """Merged column projection with one gather and logical-shard reorder.""" + + def __init__( + self, + input_size: int, + output_sizes: list[int], + *, + quant_config: QuantizationConfig | None, + prefix: str, + ) -> None: + super().__init__( + input_size, + output_sizes, + bias=False, + gather_output=False, + quant_config=quant_config, + prefix=prefix, + ) + + def forward(self, x: torch.Tensor): + output_parallel, output_bias = super().forward(x) + if self.tp_size == 1: + return output_parallel, output_bias + rank_major_output = gather_kimi_sharded_projection(output_parallel) + output = _restore_merged_output_order( + rank_major_output, + self.output_sizes, + self.tp_size, + ) + return output, output_bias + + class MultiHeadLatentAttention(nn.Module, AttentionLayerBase): """Kimi-K3 Multi-head Latent Attention with optional RoPE and output gate.""" @@ -135,6 +205,16 @@ def __init__( self.q_lora_rank = q_lora_rank self.kv_lora_rank = kv_lora_rank self.non_causal_multi_token_decode = non_causal_multi_token_decode + self.draft_kv_window = ( + int(envs.VLLM_DSPARK_DRAFT_KV_WINDOW) + if non_causal_multi_token_decode + else 0 + ) + if self.draft_kv_window < 0: + raise ValueError( + "VLLM_DSPARK_DRAFT_KV_WINDOW must be non-negative, got " + f"{self.draft_kv_window}." + ) # Latent "head" seen by the attention kernel / KV cache. self.head_size = kv_lora_rank + qk_rope_head_dim self.scale = self.qk_head_dim**-0.5 @@ -190,14 +270,26 @@ def __init__( # the low-rank latents are shared across TP ranks; TP splitting # happens at q_b_proj / kv_b_proj. Checkpoint weights ``q_a_proj`` # and ``kv_a_proj_with_mqa`` map onto shards 0 and 1 respectively. - self.fused_qkv_a_proj = MergedColumnParallelLinear( - self.hidden_size, - [self.q_lora_rank, self.kv_lora_rank + self.qk_rope_head_dim], - bias=False, - quant_config=quant_config, - prefix=f"{prefix}.fused_qkv_a_proj", - disable_tp=True, - ) + qkv_a_output_sizes = [ + self.q_lora_rank, + self.kv_lora_rank + self.qk_rope_head_dim, + ] + if envs.VLLM_KIMI_SHARD_QKV_A and tp_size > 1: + self.fused_qkv_a_proj = KimiShardedMergedColumnParallelLinear( + self.hidden_size, + qkv_a_output_sizes, + quant_config=quant_config, + prefix=f"{prefix}.fused_qkv_a_proj", + ) + else: + self.fused_qkv_a_proj = MergedColumnParallelLinear( + self.hidden_size, + qkv_a_output_sizes, + bias=False, + quant_config=quant_config, + prefix=f"{prefix}.fused_qkv_a_proj", + disable_tp=True, + ) self.q_a_layernorm = RMSNorm(self.q_lora_rank, eps=config.rms_norm_eps) self.q_b_proj = ColumnParallelLinear( self.q_lora_rank, @@ -321,13 +413,17 @@ def __init__( "parallelism." ) self.dcp_world_size = parallel_config.decode_context_parallel_size - assert self.dcp_world_size <= 1 or self.rotary_emb is None, ( - "Kimi-K3 MultiHeadLatentAttention does not support RoPE with decode " - "context parallelism because gathered queries require gathered " - "positions." + self.impl_handles_dcp = ( + self.dcp_world_size > 1 and self.attn_backend.get_name() == "B12X_MLA" + ) + assert ( + self.dcp_world_size <= 1 or self.rotary_emb is None or self.impl_handles_dcp + ), ( + "Kimi-K3 RoPE with decode context parallelism requires an attention " + "backend that implements DCP natively." ) self.dcp_manager: MLADCPManager | None = None - if self.dcp_world_size > 1: + if self.dcp_world_size > 1 and not self.impl_handles_dcp: query_dtype = ( torch.float8_e4m3fn if is_quantized_kv_cache(self.kv_cache_dtype) @@ -372,14 +468,42 @@ def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec: kv_cache_dtype = kv_cache_dtype_str_to_dtype( self.kv_cache_dtype, vllm_config.model_config ) - # TODO: Remove this mypy workaround once the K3 PR is fully merged. - return MLAAttentionSpec( # type: ignore[call-arg] + raw_shard_draft = envs.VLLM_DCP_SHARD_DRAFT + shard_draft = ( + False + if raw_shard_draft is None + else raw_shard_draft.lower() in ("1", "true", "yes") + ) + dcp_replicated = bool( + self.non_causal_multi_token_decode + and not shard_draft + and vllm_config.parallel_config.decode_context_parallel_size > 1 + ) + common_kwargs = dict( block_size=vllm_config.cache_config.block_size, num_kv_heads=1, head_size=self.head_size, dtype=kv_cache_dtype, cache_dtype_str=self.kv_cache_dtype, kv_quant_mode=get_kv_quant_mode(self.kv_cache_dtype), + dcp_replicated=dcp_replicated, + ) + if self.draft_kv_window: + if self.draft_kv_window < vllm_config.cache_config.block_size: + raise ValueError( + "VLLM_DSPARK_DRAFT_KV_WINDOW must be at least one KV " + f"block ({vllm_config.cache_config.block_size}), got " + f"{self.draft_kv_window}." + ) + return SlidingWindowMLASpec( + **common_kwargs, + sliding_window=self.draft_kv_window, + non_causal_multi_token_decode=self.non_causal_multi_token_decode, + ) + # TODO: Remove this type suppression when MLAAttentionSpec declares + # non_causal_multi_token_decode in its constructor signature. + return MLAAttentionSpec( # type: ignore[call-arg] + **common_kwargs, non_causal_multi_token_decode=self.non_causal_multi_token_decode, ) @@ -462,6 +586,7 @@ def _forward_attn( self, positions: torch.Tensor, hidden_states: torch.Tensor, + rope_cos_sin_cache: torch.Tensor | None = None, ) -> torch.Tensor: """Attention front-end: fused qkv-a proj -> norms -> q_b -> attention. @@ -500,13 +625,21 @@ def _forward_attn( dtype=hidden_states.dtype, device=hidden_states.device, ) - self._attention(positions, q, kv_c_normed, k_pe, attn_out) + self._attention( + positions, + q, + kv_c_normed, + k_pe, + attn_out, + rope_cos_sin_cache=rope_cos_sin_cache, + ) return attn_out def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, + rope_cos_sin_cache: torch.Tensor | None = None, ) -> torch.Tensor: # Both branches produce (attn_out, gate); they differ only in whether # the g_proj GEMM is overlapped on the aux stream. @@ -519,14 +652,16 @@ def forward( and hidden_states.shape[0] < _GATE_MULTI_STREAM_TOKEN_THRESHOLD ): attn_out, gate = maybe_execute_in_parallel( - lambda: self._forward_attn(positions, hidden_states), + lambda: self._forward_attn( + positions, hidden_states, rope_cos_sin_cache + ), lambda: g_proj(hidden_states)[0], events[0], events[1], self.aux_stream, ) else: - attn_out = self._forward_attn(positions, hidden_states) + attn_out = self._forward_attn(positions, hidden_states, rope_cos_sin_cache) gate = g_proj(hidden_states)[0] if g_proj is not None else None if gate is not None: @@ -546,6 +681,8 @@ def _attention( kv_c_normed: torch.Tensor, k_pe: torch.Tensor, attn_out: torch.Tensor, + *, + rope_cos_sin_cache: torch.Tensor | None = None, ) -> None: forward_context = get_forward_context() attn_metadata_by_layer = forward_context.attn_metadata @@ -558,6 +695,11 @@ def _attention( ) num_actual_toks = attn_metadata.num_actual_tokens + if num_actual_toks < int(attn_out.shape[0]): + # Downstream gate and output projections consume the padded rows. + # Define inactive rows so collective kernels never consume + # uninitialized values. + attn_out[num_actual_toks:].zero_() slot_mapping_by_layer = forward_context.slot_mapping assert isinstance(slot_mapping_by_layer, dict) slot_mapping = slot_mapping_by_layer[self.layer_name] @@ -573,7 +715,11 @@ def _attention( if self.rotary_emb is not None: # Pass the fp32 cos/sin table straight to the fused epilogue (it reads # fp32 and does the RoPE math in fp32) -- no per-forward dtype cast. - cos_sin_cache = self.rotary_emb.cos_sin_cache + cos_sin_cache = ( + rope_cos_sin_cache + if rope_cos_sin_cache is not None + else self.rotary_emb.cos_sin_cache + ) rope_positions = positions # Decode tokens are laid out first, prefill tokens after. The fused @@ -616,16 +762,14 @@ def _attention( cos_sin_cache, slot_mapping[:num_mqa_tokens], ) - if self.dcp_world_size > 1: - assert self.dcp_manager is not None + if self.dcp_manager is not None: assert self.dcp_manager.query_gather is not None mqa_q = self.dcp_manager.query_gather(mqa_q) latent_out, lse = self.impl.forward_mqa( # type: ignore[attr-defined] mqa_q, self._attn_read_kv_cache(), attn_metadata, self ) - if self.dcp_world_size > 1: + if self.dcp_manager is not None: assert lse is not None - assert self.dcp_manager is not None assert attn_metadata.decode is not None latent_out = self.dcp_manager.combine( latent_out, diff --git a/vllm/models/kimi_k3/nvidia/model.py b/vllm/models/kimi_k3/nvidia/model.py index 9c032bf8230d..4baa989e89b7 100644 --- a/vllm/models/kimi_k3/nvidia/model.py +++ b/vllm/models/kimi_k3/nvidia/model.py @@ -17,7 +17,6 @@ get_ep_group, get_pp_group, get_tensor_model_parallel_world_size, - tensor_model_parallel_all_gather, tensor_model_parallel_all_reduce, ) from vllm.forward_context import get_forward_context, is_forward_context_available @@ -30,6 +29,9 @@ from vllm.model_executor.layers.fused_moe.router.base_router import ( eplb_map_to_physical_and_record, ) +from vllm.model_executor.layers.fused_moe.router.fused_topk_bias_router import ( + FusedTopKBiasRouter, +) from vllm.model_executor.layers.fused_moe.router.gate_linear import GateLinear from vllm.model_executor.layers.fused_moe.router.grouped_topk_router import ( fused_grouped_topk, @@ -107,6 +109,11 @@ ) from vllm.models.kimi_k3.nvidia.mla import MultiHeadLatentAttention from vllm.models.kimi_k3.nvidia.ops import attn_res +from vllm.models.kimi_k3.nvidia.tp_projection import ( + gather_kimi_sharded_projection, + gather_kimi_sharded_projection_pair, + try_gather_kimi_sharded_projection_pair_topk, +) from vllm.multimodal import MULTIMODAL_REGISTRY from vllm.multimodal.inputs import NestedTensors from vllm.platforms import current_platform @@ -134,6 +141,22 @@ _ROUTED_DOWN_PROJ_STREAM_TOKEN_THRESHOLD = 256 +def _uses_native_b12x_mxfp4_intermediate_size( + vllm_config: VllmConfig, +) -> bool: + """Return whether B12X consumes the checkpoint's logical MoE shard. + + The B12X W4A16 kernel accepts intermediate tails such as Kimi-K3's + 3072 / TP16 = 192 shard. Generic model-level padding to 256 channels per + rank would expand every routed-expert layer without changing its logical + shape. + """ + if vllm_config.model_config.quantization != "mxfp4": + return False + moe_backend = vllm_config.kernel_config.moe_backend + return moe_backend == "b12x" or (moe_backend == "auto" and envs.VLLM_USE_B12X_MOE) + + def shard_sequence_parallel_mlp( hidden_size: int, intermediate_size: int, @@ -343,19 +366,24 @@ def __init__( ) -> None: tp_size = get_tensor_model_parallel_world_size() self.logical_output_size = output_size + self.kimi_gather_output = gather_output padded_output_size = cdiv(output_size, tp_size) * tp_size super().__init__( input_size, padded_output_size, bias=False, - gather_output=gather_output, + gather_output=False, quant_config=None, prefix=prefix, ) + def forward_local(self, x: torch.Tensor): + return super().forward(x) + def forward(self, x: torch.Tensor): - output, bias = super().forward(x) - if self.gather_output: + output, bias = self.forward_local(x) + if self.kimi_gather_output: + output = gather_kimi_sharded_projection(output) output = output[..., : self.logical_output_size].contiguous() return output, bias @@ -371,17 +399,20 @@ def __init__(self, input_size: int, output_size: int, prefix: str) -> None: gather_output=False, ) - def forward(self, x: torch.Tensor): + def forward_local( + self, x: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor | None]: if x.is_cuda and x.dtype == self.weight.dtype == torch.bfloat16: - output_parallel = torch.mm(x, self.weight.T, out_dtype=torch.float32) + output = torch.mm(x, self.weight.T, out_dtype=torch.float32) else: - output_parallel = torch.nn.functional.linear( + output = torch.nn.functional.linear( x.to(self.weight.dtype), self.weight ).float() - if self.tp_size > 1: - output = tensor_model_parallel_all_gather(output_parallel) - else: - output = output_parallel + return output, None + + def forward(self, x: torch.Tensor): + output_parallel, _ = self.forward_local(x) + output = gather_kimi_sharded_projection(output_parallel) return output[..., : self.logical_output_size].contiguous(), None @@ -602,6 +633,77 @@ def make_kimi_k3_mega_moe_expert_params_mapping( return mapping +class KimiK3PrecomputedTopKRouter(FusedTopKBiasRouter): + """Decode the compact routing payload produced by B12X TP16 collectives.""" + + def _compute_routing( + self, + hidden_states: torch.Tensor, + router_logits: torch.Tensor, + indices_type: torch.dtype | None, + *, + input_ids: torch.Tensor | None = None, + ) -> tuple[torch.Tensor, torch.Tensor]: + num_tokens = hidden_states.shape[0] + if ( + envs.VLLM_KIMI_FUSED_TOPK16 + and self.top_k == 16 + and self.global_num_experts == 896 + and self.scoring_func == "sigmoid" + and self.renormalize + and indices_type in (None, torch.int32) + and input_ids is None + and self.e_score_correction_bias is not None + and router_logits.ndim == 2 + and router_logits.shape == (num_tokens, 896) + and router_logits.dtype == torch.float32 + and router_logits.is_cuda + and router_logits.is_contiguous() + ): + from vllm.model_executor.layers.fused_moe.router.fused_topk_bias_router import ( # noqa: E501 + _get_padding_mask, + ) + from vllm.models.kimi_k3.nvidia.ops.topk16 import ( + kimi_topk16_sigmoid, + ) + + return kimi_topk16_sigmoid( + router_logits, + self.e_score_correction_bias.data, + _get_padding_mask(num_tokens), + renormalize=self.renormalize, + routed_scaling_factor=self.routed_scaling_factor, + ) + if ( + self.top_k == 16 + and self.global_num_experts == 896 + and indices_type in (None, torch.int32) + and router_logits.ndim == 2 + and router_logits.shape == (num_tokens * 2, 16) + and router_logits.dtype == torch.float32 + ): + topk_weights = router_logits[:num_tokens] + topk_ids = router_logits[num_tokens:].view(torch.int32) + return topk_weights, topk_ids + if ( + self.top_k == 16 + and self.global_num_experts == 896 + and indices_type in (None, torch.int32) + and router_logits.ndim == 2 + and router_logits.shape == (num_tokens, 32) + and router_logits.dtype == torch.float32 + ): + topk_weights = router_logits[:, :16] + topk_ids = router_logits[:, 16:].view(torch.int32) + return topk_weights, topk_ids + return super()._compute_routing( + hidden_states, + router_logits, + indices_type, + input_ids=input_ids, + ) + + class KimiMoE(nn.Module): def __init__( self, @@ -667,12 +769,28 @@ def __init__( min_moe_intermediate_per_partition = getattr( config, "min_moe_intermediate_per_partition", 256 ) - if self.tp_size > 1 and not vllm_config.parallel_config.enable_expert_parallel: + use_native_b12x_intermediate = ( + not self.use_mega_moe + and _uses_native_b12x_mxfp4_intermediate_size(vllm_config) + ) + if ( + self.tp_size > 1 + and not vllm_config.parallel_config.enable_expert_parallel + and not use_native_b12x_intermediate + ): moe_intermediate_per_partition = moe_intermediate_size // self.tp_size if moe_intermediate_per_partition < min_moe_intermediate_per_partition: self.padded_moe_intermediate_size = ( min_moe_intermediate_per_partition * self.tp_size ) + elif use_native_b12x_intermediate: + logger.info_once( + "Kimi-K3 B12X MXFP4 keeps the checkpoint MoE intermediate " + "shard (%d / TP%d = %d).", + moe_intermediate_size, + self.tp_size, + moe_intermediate_size // self.tp_size, + ) activation_situ_beta = ( config.activation_situ_beta if config.hidden_act == "situ" else None ) @@ -795,6 +913,14 @@ def __init__( activation_linear_beta=activation_situ_linear_beta, ) else: + router = KimiK3PrecomputedTopKRouter( + top_k=num_experts_per_token, + global_num_experts=num_experts, + e_score_correction_bias=self.gate.e_score_correction_bias, + renormalize=moe_renormalize, + routed_scaling_factor=self.routed_scaling_factor, + scoring_func=self.moe_router_activation_func, + ) self.experts = FusedMoEFactory( shared_experts=self.shared_experts, num_experts=num_experts, @@ -813,6 +939,7 @@ def __init__( scoring_func=config.moe_router_activation_func, e_score_correction_bias=self.gate.e_score_correction_bias, routed_scaling_factor=self.routed_scaling_factor, + router=router, # Down projection runs outside MoERunner so it can overlap the # router gate on the aux stream (see forward()); the original # hidden states are passed to forward() as shared_experts_input @@ -858,10 +985,9 @@ def _maybe_overlap_router_and_down_proj( logits and ``topk_ids`` is ``None``. """ - def _router( - hidden_states: torch.Tensor, + def _finish_router( + router_logits: torch.Tensor, ) -> tuple[torch.Tensor, torch.Tensor | None]: - router_logits, _ = self.gate(hidden_states) if not self.use_mega_moe: return router_logits, None return fused_grouped_topk( @@ -876,11 +1002,49 @@ def _router( routed_scaling_factor=self.routed_scaling_factor, ) + def _router( + hidden_states: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor | None]: + router_logits, _ = self.gate(hidden_states) + return _finish_router(router_logits) + down_proj = self.routed_expert_down_proj if down_proj is None: router_output, topk_ids = _router(hidden_states) return hidden_states, router_output, topk_ids num_tokens = hidden_states.shape[0] + if ( + 0 < num_tokens <= 8 + and envs.VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_GATHER + and not self.use_mega_moe + and isinstance(self.gate, KimiColumnParallelGate) + and isinstance(down_proj, KimiPaddedColumnParallelLinear) + ): + (router_local, _), (down_local, _) = maybe_execute_in_parallel( + lambda: self.gate.forward_local(hidden_states), + lambda: down_proj.forward_local(hidden_states), + self._down_proj_events[0], + self._down_proj_events[1], + self._down_proj_stream, + ) + fused_pair_topk = ( + try_gather_kimi_sharded_projection_pair_topk( + down_local, + router_local, + self.gate.e_score_correction_bias.data, + ) + if num_tokens == 1 or envs.VLLM_KIMI_USE_B12X_BATCHED_PROJECTION_TOPK + else None + ) + if fused_pair_topk is not None: + routed_hidden_states, routing_payload = fused_pair_topk + return routed_hidden_states, routing_payload, None + routed_hidden_states, router_logits = gather_kimi_sharded_projection_pair( + down_local, + router_local, + ) + router_output, topk_ids = _finish_router(router_logits) + return routed_hidden_states, router_output, topk_ids (router_output, topk_ids), (routed_hidden_states, _) = ( maybe_execute_in_parallel( lambda: _router(hidden_states), diff --git a/vllm/models/kimi_k3/nvidia/ops/topk16.cu b/vllm/models/kimi_k3/nvidia/ops/topk16.cu new file mode 100644 index 000000000000..17667602295f --- /dev/null +++ b/vllm/models/kimi_k3/nvidia/ops/topk16.cu @@ -0,0 +1,187 @@ +// Fused sigmoid + biased top-16 routing for Kimi-K3 (896 experts). +// +// Bit-exact replacement for the moeSigmoid + moeTopK pair in +// csrc/libtorch_stable/moe/topk_softmax_kernels.cu for the K3 decode shape: +// - scores = 1/(1+__expf(-logit)), NaN/Inf clamped to 0 (same intrinsic) +// - selection key = score + e_score_correction_bias +// - output weight = unbiased score of the selected expert +// - 16 sequential argmax passes; ties resolved to the LOWER expert index +// (cub::ArgMax semantics) +// - renormalization sums the unbiased scores in selection order and applies +// scale = routed_scaling_factor / (sum > 0 ? sum : 1) +// - padded rows emit indices = -1 while retaining the computed weights +// +// The reference walks global memory 16 times with a 16-deep prior-winner scan +// per element; this kernel stages both arrays in shared memory once and marks +// winners with -inf, which cannot collide with real keys (score in [0,1], +// finite bias). + +#include +#include +#include +#include +#include + +#include + +namespace kimi_topk16 { + +constexpr int kExperts = 896; +constexpr int kTopK = 16; +constexpr int kThreads = 256; +constexpr int kPerThread = (kExperts + kThreads - 1) / kThreads; // 4 +constexpr int kWarps = kThreads / 32; + +// Strictly-greater wins; on equal keys the lower expert index wins. +__device__ __forceinline__ void arg_merge( + float& best_val, int& best_idx, float val, int idx) { + if (val > best_val || (val == best_val && idx < best_idx)) { + best_val = val; + best_idx = idx; + } +} + +__global__ __launch_bounds__(kThreads) void topk16_sigmoid_kernel( + const float* __restrict__ logits, // [rows, 896] + const float* __restrict__ bias, // [896] + float* __restrict__ out_weights, // [rows, 16] + int* __restrict__ out_indices, // [rows, 16] + const bool* __restrict__ is_padding, // [rows] or nullptr + const bool renormalize, + const float routed_scaling_factor) { + __shared__ float score_sm[kExperts]; // unbiased sigmoid scores + __shared__ float key_sm[kExperts]; // selection keys (score + bias) + __shared__ float warp_val[kWarps]; + __shared__ int warp_idx[kWarps]; + __shared__ float sel_weight[kTopK]; + __shared__ int sel_index[kTopK]; + + const int row = blockIdx.x; + const int tid = threadIdx.x; + const int lane = tid & 31; + const int warp = tid >> 5; + const float* row_logits = logits + static_cast(row) * kExperts; + + for (int e = tid; e < kExperts; e += kThreads) { + const float val = row_logits[e]; + float s = 1.0f / (1.0f + __expf(-val)); + if (isnan(s) || isinf(s)) { + s = 0.0f; + } + score_sm[e] = s; + key_sm[e] = s + bias[e]; + } + __syncthreads(); + + for (int k_idx = 0; k_idx < kTopK; ++k_idx) { + float best_val = -CUDART_INF_F; + int best_idx = kExperts; +#pragma unroll + for (int i = 0; i < kPerThread; ++i) { + const int e = tid + i * kThreads; + if (e < kExperts) { + arg_merge(best_val, best_idx, key_sm[e], e); + } + } +#pragma unroll + for (int offset = 16; offset > 0; offset >>= 1) { + const float other_val = __shfl_down_sync(0xffffffffu, best_val, offset); + const int other_idx = __shfl_down_sync(0xffffffffu, best_idx, offset); + arg_merge(best_val, best_idx, other_val, other_idx); + } + if (lane == 0) { + warp_val[warp] = best_val; + warp_idx[warp] = best_idx; + } + __syncthreads(); + if (tid == 0) { + float v = warp_val[0]; + int x = warp_idx[0]; +#pragma unroll + for (int w = 1; w < kWarps; ++w) { + arg_merge(v, x, warp_val[w], warp_idx[w]); + } + sel_index[k_idx] = x; + sel_weight[k_idx] = score_sm[x]; + key_sm[x] = -CUDART_INF_F; + } + __syncthreads(); + } + + if (tid == 0) { + const bool pad = is_padding != nullptr && is_padding[row]; + float selected_sum = 0.0f; + if (renormalize) { + for (int k_idx = 0; k_idx < kTopK; ++k_idx) { + selected_sum += sel_weight[k_idx]; + } + } + float scale = routed_scaling_factor; + if (renormalize) { + const float denom = selected_sum > 0.0f ? selected_sum : 1.0f; + scale /= denom; + } + float* out_w = out_weights + static_cast(row) * kTopK; + int* out_i = out_indices + static_cast(row) * kTopK; + for (int k_idx = 0; k_idx < kTopK; ++k_idx) { + out_w[k_idx] = sel_weight[k_idx] * scale; + out_i[k_idx] = pad ? -1 : sel_index[k_idx]; + } + } +} + +} // namespace kimi_topk16 + +static void topk16_sigmoid( + torch::Tensor logits, + torch::Tensor bias, + torch::Tensor out_weights, + torch::Tensor out_indices, + std::optional is_padding, + bool renormalize, + double routed_scaling_factor) { + TORCH_CHECK(logits.is_cuda() && logits.dtype() == torch::kFloat32 && + logits.dim() == 2 && + logits.size(1) == kimi_topk16::kExperts && + logits.is_contiguous(), + "logits must be contiguous CUDA FP32 [rows, 896]"); + TORCH_CHECK(bias.is_cuda() && bias.dtype() == torch::kFloat32 && + bias.numel() == kimi_topk16::kExperts && + bias.is_contiguous(), + "bias must be contiguous CUDA FP32 [896]"); + const long rows = logits.size(0); + TORCH_CHECK(out_weights.is_cuda() && out_weights.dtype() == torch::kFloat32 && + out_weights.is_contiguous() && + out_weights.numel() == rows * kimi_topk16::kTopK, + "out_weights must be contiguous CUDA FP32 [rows, 16]"); + TORCH_CHECK(out_indices.is_cuda() && out_indices.dtype() == torch::kInt32 && + out_indices.is_contiguous() && + out_indices.numel() == rows * kimi_topk16::kTopK, + "out_indices must be contiguous CUDA INT32 [rows, 16]"); + const bool* pad_ptr = nullptr; + if (is_padding.has_value()) { + TORCH_CHECK(is_padding->is_cuda() && is_padding->dtype() == torch::kBool && + is_padding->is_contiguous() && is_padding->numel() >= rows, + "is_padding must be contiguous CUDA bool [rows]"); + pad_ptr = is_padding->data_ptr(); + } + if (rows == 0) { + return; + } + const c10::cuda::CUDAGuard guard(logits.device()); + const cudaStream_t stream = c10::cuda::getCurrentCUDAStream(); + kimi_topk16::topk16_sigmoid_kernel<<< + static_cast(rows), kimi_topk16::kThreads, 0, stream>>>( + logits.data_ptr(), + bias.data_ptr(), + out_weights.data_ptr(), + out_indices.data_ptr(), + pad_ptr, + renormalize, + static_cast(routed_scaling_factor)); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, module) { + module.def("topk16_sigmoid", &topk16_sigmoid); +} diff --git a/vllm/models/kimi_k3/nvidia/ops/topk16.py b/vllm/models/kimi_k3/nvidia/ops/topk16.py new file mode 100644 index 000000000000..40ea9c5ac1b0 --- /dev/null +++ b/vllm/models/kimi_k3/nvidia/ops/topk16.py @@ -0,0 +1,58 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Fused sigmoid + biased top-16 routing for Kimi-K3 (bit-exact, JIT-built).""" + +from functools import lru_cache +from pathlib import Path + +import torch + +_EXPERTS = 896 +_TOPK = 16 + + +@lru_cache(maxsize=1) +def _load_extension(): + from torch.utils.cpp_extension import load + + source = Path(__file__).with_name("topk16.cu") + return load( + name="vllm_kimi_topk16_ext", + sources=[str(source)], + extra_cuda_cflags=["-O3"], + verbose=False, + ) + + +def warmup_kimi_topk16() -> None: + """Compile the Kimi-K3 fused router before CUDA graph capture.""" + _load_extension() + + +def kimi_topk16_sigmoid( + router_logits: torch.Tensor, + correction_bias: torch.Tensor, + is_padding: torch.Tensor | None = None, + *, + renormalize: bool = True, + routed_scaling_factor: float = 1.0, +) -> tuple[torch.Tensor, torch.Tensor]: + """Return ``(topk_weights, topk_ids)`` for FP32 [rows, 896] logits. + + Bit-exact with vLLM's moeSigmoid + moeTopK pair (same __expf sigmoid, + same lower-index tie break, same selection-order renormalization). + """ + rows = router_logits.shape[0] + weights = torch.empty( + (rows, _TOPK), dtype=torch.float32, device=router_logits.device + ) + indices = torch.empty((rows, _TOPK), dtype=torch.int32, device=router_logits.device) + _load_extension().topk16_sigmoid( + router_logits, + correction_bias, + weights, + indices, + is_padding, + renormalize, + routed_scaling_factor, + ) + return weights, indices diff --git a/vllm/models/kimi_k3/nvidia/tp_projection.py b/vllm/models/kimi_k3/nvidia/tp_projection.py new file mode 100644 index 000000000000..2e7d9807cf4a --- /dev/null +++ b/vllm/models/kimi_k3/nvidia/tp_projection.py @@ -0,0 +1,189 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Memory-bounded TP collectives for Kimi-K3 projection outputs.""" + +import torch + +import vllm.envs as envs +from vllm.distributed import ( + get_dcp_group, + get_tensor_model_parallel_world_size, + get_tp_group, + tensor_model_parallel_all_gather, + tensor_model_parallel_all_reduce, + tensor_model_parallel_all_reduce_in_place, +) +from vllm.v1.attention.ops.dcp_alltoall import ( + dcp_b12x_all_gather_heads, + dcp_b12x_all_gather_pair, + try_dcp_b12x_all_gather_pair_kimi_topk, +) + +_KIMI_OUTPUT_BUFFER_REUSE_MIN_TOKENS = 1024 +_KIMI_B12X_PAIRED_PROJECTION_MAX_TOKENS = 8 + + +def _get_kimi_projection_group(): + """Return the coordinator that spans every projection weight shard. + + Projection weights are sharded across the full tensor-parallel group. The + DCP coordinator is valid only when its ordered rank list matches the + tensor-parallel coordinator. + """ + tp_size = get_tensor_model_parallel_world_size() + dcp_group = get_dcp_group() + tp_group = get_tp_group() + if tp_group.world_size != tp_size: + raise RuntimeError( + "Kimi projection group does not span tensor-parallel ranks: " + f"group={tp_group.world_size}, TP={tp_size}" + ) + if dcp_group.world_size == tp_size and list(dcp_group.ranks) == list( + tp_group.ranks + ): + return dcp_group + return tp_group + + +def _try_b12x_kimi_projection_gather( + output_parallel: torch.Tensor, +) -> torch.Tensor | None: + """Gather one decode projection over the byte-exact B12X copy channel.""" + if ( + not envs.VLLM_KIMI_USE_B12X_PROJECTION_GATHER + or output_parallel.ndim != 2 + or output_parallel.shape[0] != 1 + or not output_parallel.is_cuda + or not output_parallel.is_contiguous() + ): + return None + + tp_size = get_tensor_model_parallel_world_size() + if tp_size <= 1: + return None + projection_group = _get_kimi_projection_group() + + local_width = output_parallel.shape[1] + restore_dtype: torch.dtype | None = None + strip_local_width: int | None = None + if output_parallel.dtype in (torch.float16, torch.bfloat16): + if local_width % 8 == 0: + transport = output_parallel.view(1, 1, local_width) + else: + padded_width = (local_width + 7) // 8 * 8 + transport = torch.nn.functional.pad( + output_parallel, (0, padded_width - local_width) + ).view(1, 1, padded_width) + strip_local_width = local_width + elif output_parallel.dtype == torch.float32: + raw_width = local_width * output_parallel.element_size() + if raw_width % 8 != 0: + return None + # The FP8 view supplies one-byte transport lanes. It does not convert + # the FP32 payload, so every source bit is preserved. + transport = output_parallel.view(torch.float8_e4m3fn).view(1, 1, raw_width) + restore_dtype = torch.float32 + elif output_parallel.dtype == torch.float8_e4m3fn: + if local_width % 16 != 0: + return None + transport = output_parallel.view(1, 1, local_width) + else: + return None + + gathered = dcp_b12x_all_gather_heads( + transport, + projection_group, + max_batch_size=1, + ) + if strip_local_width is not None: + gathered = gathered.narrow(-1, 0, strip_local_width).contiguous() + gathered = gathered.flatten(1) + if restore_dtype is not None: + gathered = gathered.view(restore_dtype) + return gathered + + +def gather_kimi_sharded_projection(output_parallel: torch.Tensor) -> torch.Tensor: + """Gather a rank-major Kimi-K3 projection with a lossless fast path.""" + if get_tensor_model_parallel_world_size() <= 1: + return output_parallel + gathered = _try_b12x_kimi_projection_gather(output_parallel) + if gathered is not None: + return gathered + return tensor_model_parallel_all_gather(output_parallel, dim=-1) + + +def gather_kimi_sharded_projection_pair( + local_first: torch.Tensor, + local_second: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + """Gather two decode projections with one byte-exact B12X barrier.""" + tp_size = get_tensor_model_parallel_world_size() + if tp_size <= 1: + return local_first, local_second + projection_group = _get_kimi_projection_group() + if ( + envs.VLLM_KIMI_USE_B12X_PROJECTION_GATHER + and envs.VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_GATHER + and local_first.ndim == local_second.ndim == 2 + and local_first.shape[0] == local_second.shape[0] + and 0 < local_first.shape[0] <= _KIMI_B12X_PAIRED_PROJECTION_MAX_TOKENS + and local_first.is_cuda + and local_second.is_cuda + and local_first.is_contiguous() + and local_second.is_contiguous() + and projection_group.world_size == tp_size + ): + return dcp_b12x_all_gather_pair( + local_first, + local_second, + projection_group, + max_batch_size=_KIMI_B12X_PAIRED_PROJECTION_MAX_TOKENS, + ) + return ( + gather_kimi_sharded_projection(local_first), + gather_kimi_sharded_projection(local_second), + ) + + +def try_gather_kimi_sharded_projection_pair_topk( + local_down: torch.Tensor, + local_router: torch.Tensor, + correction_bias: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor] | None: + """Fuse TP16 routed-down gather with Kimi-K3 sigmoid top-k routing.""" + tp_size = get_tensor_model_parallel_world_size() + if ( + not envs.VLLM_KIMI_USE_B12X_PROJECTION_GATHER + or not envs.VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_GATHER + or not envs.VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_TOPK + or tp_size != 16 + ): + return None + projection_group = _get_kimi_projection_group() + batch = int(local_down.shape[0]) if local_down.ndim == 2 else 0 + return try_dcp_b12x_all_gather_pair_kimi_topk( + local_down, + local_router, + correction_bias, + projection_group, + max_batch_size=1 if batch == 1 else 8, + ) + + +def should_reuse_kimi_full_width_output(output_buffer: torch.Tensor) -> bool: + """Return whether a prefill-sized dead input can hold a projection output.""" + return output_buffer.ndim >= 2 and output_buffer.shape[0] >= ( + _KIMI_OUTPUT_BUFFER_REUSE_MIN_TOKENS + ) + + +def reduce_kimi_full_width_output( + output: torch.Tensor, + tp_size: int, +) -> torch.Tensor: + """Reduce a rank-local full-width output without another large allocation.""" + if tp_size <= 1: + return output + if should_reuse_kimi_full_width_output(output): + return tensor_model_parallel_all_reduce_in_place(output) + return tensor_model_parallel_all_reduce(output) diff --git a/vllm/v1/attention/backends/mla/b12x_mla.py b/vllm/v1/attention/backends/mla/b12x_mla.py index e858446b02e4..baf1d40698f2 100644 --- a/vllm/v1/attention/backends/mla/b12x_mla.py +++ b/vllm/v1/attention/backends/mla/b12x_mla.py @@ -1,16 +1,22 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Native B12X dense MLA decode backend for Kimi K3 on SM120/SM121.""" +"""Native b12x dense MLA decode backend for Kimi K3 on SM120/SM121.""" from __future__ import annotations +import os from dataclasses import dataclass from typing import Any, ClassVar, cast import torch +from vllm.compilation.b12x_capture import is_b12x_compile_only_warmup from vllm.config import VllmConfig, get_current_vllm_config from vllm.config.cache import CacheDType +from vllm.distributed.parallel_state import ( + dcp_group_is_initialized, + get_dcp_group, +) from vllm.logger import init_logger from vllm.model_executor.layers.attention.mla_attention import ( MLACommonBackend, @@ -28,11 +34,12 @@ CommonAttentionMetadata, MultipleOf, ) -from vllm.v1.kv_cache_interface import AttentionSpec -from vllm.v1.worker.workspace import ( - current_workspace_manager, - is_workspace_manager_initialized, +from vllm.v1.attention.ops.common import cp_lse_ag_out_rs +from vllm.v1.attention.ops.dcp_alltoall import ( + dcp_a2a_lse_reduce, + dcp_b12x_all_gather_heads, ) +from vllm.v1.kv_cache_interface import AttentionSpec logger = init_logger(__name__) @@ -44,7 +51,9 @@ _K3_V_HEAD_DIM = 128 _MAX_B12X_QUERY_ROWS = 1024 _MAX_B12X_CACHE_TOKENS = 1_048_576 +_B12X_QUERY_HEAD_TILE = 8 _MAX_I32 = torch.iinfo(torch.int32).max +_DEBUG_FINITE = os.environ.get("VLLM_KIMI_DEBUG_FINITE") == "1" def _load_dense_mla() -> Any: @@ -55,12 +64,27 @@ def _load_dense_mla() -> Any: def _page_table_width(max_cache_tokens: int, page_size: int) -> int: width = (max_cache_tokens + page_size - 1) // page_size + # vLLM pads block tables to a 128-token boundary for page sizes <= 128. if page_size <= 128: alignment = 128 // page_size width = ((width + alignment - 1) // alignment) * alignment return width +def _max_dcp_local_cache_tokens( + vllm_config: VllmConfig, *, dcp_size: int | None = None +) -> int: + """Return the largest token shard held by one decode-context rank.""" + parallel_config = vllm_config.parallel_config + dcp_size = int( + parallel_config.decode_context_parallel_size if dcp_size is None else dcp_size + ) + interleave = int(parallel_config.cp_kv_cache_interleave_size) + max_model_len = int(vllm_config.model_config.max_model_len) + partitions = dcp_size * interleave + return ((max_model_len + partitions - 1) // partitions) * interleave + + def _planned_kv_dtype(vllm_config: VllmConfig) -> torch.dtype: cache_dtype = vllm_config.cache_config.cache_dtype if cache_dtype == "auto": @@ -80,6 +104,104 @@ def _planned_kv_dtype(vllm_config: VllmConfig) -> torch.dtype: ) +def _kernel_query_heads(local_heads: int, dcp_size: int) -> int: + """Return the head count presented to the tiled dense-MLA kernel. + + B12X computes each query head independently but launches them in + tiles of eight. K3 has 96 heads, so TP16 without DCP produces six local + heads. Padding that DCP1 query to eight is mathematically inert and lets + the native kernel cover this otherwise valid tensor-parallel layout. + + DCP reductions depend on the gathered head layout, so keep their existing + exact-multiple contract rather than introducing synthetic collective + entries. + """ + if local_heads <= 0: + raise ValueError(f"B12X_MLA requires positive local heads, got {local_heads}.") + if dcp_size <= 0: + raise ValueError(f"B12X_MLA requires positive DCP size, got {dcp_size}.") + effective_heads = local_heads * dcp_size + if dcp_size > 1: + if effective_heads % _B12X_QUERY_HEAD_TILE: + raise ValueError( + "B12X_MLA requires a multiple of 8 query heads after DCP " + f"gather, got local={local_heads}, DCP={dcp_size}, " + f"effective={effective_heads}." + ) + return effective_heads + return ( + (effective_heads + _B12X_QUERY_HEAD_TILE - 1) + // _B12X_QUERY_HEAD_TILE + * _B12X_QUERY_HEAD_TILE + ) + + +def _active_dense_mla_splits(plan: Any, max_seq_len: int | None) -> int: + """Return the useful prefix of a capture-static dense-MLA split plan. + + The plan's split boundaries and scratch layout remain fixed at their + maximum-context values. Short decode steps only omit tail splits whose + first 64-token chunk is beyond every live sequence, so this does not alter + the reduction order of any contributing partial. + """ + num_splits = int(getattr(plan, "num_splits", 1)) + chunks_per_split = int(getattr(plan, "chunks_per_split", 1)) + if num_splits <= 0 or chunks_per_split <= 0: + raise ValueError( + "B12X_MLA received an invalid dense MLA split plan: " + f"num_splits={num_splits}, chunks_per_split={chunks_per_split}." + ) + if max_seq_len is None: + return num_splits + valid_chunks = max(1, (max(0, int(max_seq_len)) + 63) // 64) + return min( + num_splits, + (valid_chunks + chunks_per_split - 1) // chunks_per_split, + ) + + +def _dcp_local_seq_lens_from_global( + output: torch.Tensor, + remainder_scratch: torch.Tensor, + global_seq_lens: torch.Tensor, + *, + dcp_size: int, + dcp_rank: int, + interleave: int, +) -> None: + """Convert global lengths to this rank's round-robin DCP lengths. + + This is the allocation-free tensor equivalent of + ``prepare_dcp_local_seq_lens``. DSpark target verification flattens one + causal query block into several independent decode rows, so every row + needs the local length corresponding to its own global token position. + """ + if output.shape != global_seq_lens.shape or output.shape != remainder_scratch.shape: + raise ValueError( + "B12X_MLA DCP sequence-length buffers must have identical shapes, " + f"got output={output.shape}, scratch={remainder_scratch.shape}, " + f"global={global_seq_lens.shape}." + ) + if output.dtype != torch.int32 or remainder_scratch.dtype != torch.int32: + raise TypeError("B12X_MLA DCP sequence-length buffers must use int32.") + if dcp_size <= 0 or not 0 <= dcp_rank < dcp_size or interleave <= 0: + raise ValueError( + "Invalid B12X_MLA DCP layout: " + f"size={dcp_size}, rank={dcp_rank}, interleave={interleave}." + ) + if dcp_size == 1: + output.copy_(global_seq_lens) + return + + virtual_block = dcp_size * interleave + torch.div(global_seq_lens, virtual_block, rounding_mode="floor", out=output) + output.mul_(interleave) + torch.remainder(global_seq_lens, virtual_block, out=remainder_scratch) + remainder_scratch.sub_(dcp_rank * interleave) + remainder_scratch.clamp_(min=0, max=interleave) + output.add_(remainder_scratch) + + def _create_dense_mla_plan( vllm_config: VllmConfig, device: torch.device, @@ -87,6 +209,7 @@ def _create_dense_mla_plan( page_size: int, num_q_heads: int, max_total_q: int | None = None, + dcp_size: int | None = None, ) -> Any: dense_mla = _load_dense_mla() max_total_q = int( @@ -94,7 +217,7 @@ def _create_dense_mla_plan( if max_total_q is not None else vllm_config.scheduler_config.max_num_seqs ) - max_cache_tokens = int(vllm_config.model_config.max_model_len) + max_cache_tokens = _max_dcp_local_cache_tokens(vllm_config, dcp_size=dcp_size) if max_total_q > _MAX_B12X_QUERY_ROWS: raise ValueError( "B12X_MLA supports at most " @@ -117,6 +240,9 @@ def _create_dense_mla_plan( max_batch=max_total_q, max_cache_tokens=max_cache_tokens, max_page_table_width=_page_table_width(max_cache_tokens, page_size), + # This is a validation ceiling only; physical page count is selected + # after memory profiling and can exceed max_model_len / page_size when + # the server has capacity for multiple requests. num_cache_pages=_MAX_I32, use_cuda_graph=True, ) @@ -125,18 +251,28 @@ def _create_dense_mla_plan( @dataclass class B12xMLAMetadata(MLACommonMetadata): - """Common MLA metadata plus the capture-static B12X launch plan.""" + """Common MLA metadata plus the capture-static b12x launch plan.""" dense_mla_plan: Any | None = None + dense_mla_scratch: torch.Tensor | None = None + dense_mla_padded_q: torch.Tensor | None = None + dense_mla_padded_output: torch.Tensor | None = None dense_mla_flat_block_table: torch.Tensor | None = None dense_mla_flat_seq_lens: torch.Tensor | None = None dense_mla_flat_query_start_loc: torch.Tensor | None = None class B12xMLAMetadataBuilder(MLACommonMetadataBuilder[B12xMLAMetadata]): + # The target verifies the accepted token plus the seven DSpark proposals in + # one causal block. B12X exposes a single-query decode primitive, so + # both that block and the draft's non-causal block are flattened below. _cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH query_len_support: ClassVar[QueryLenSupport] = QueryLenSupport.UNIFORM + # A DSpark verify block is flattened into independent single-token decode + # rows. Every row sees the same committed prefix, so sibling draft tokens + # cannot attend to one another. supports_non_causal_multi_token_decode: ClassVar[bool] = True + supports_direct_dcp_kv_gather: ClassVar[bool] = True def __init__( self, @@ -151,50 +287,122 @@ def __init__( vllm_config, device, B12xMLAMetadata, + supports_dcp_with_varlen=True, ) + # Unit tests may construct the builder before distributed init. + self._dcp_rank = ( + int(get_dcp_group().rank_in_group) if dcp_group_is_initialized() else 0 + ) + if self.non_causal_multi_token_decode: + # Mirror Triton MLA's DSpark policy. The speculative block has + # 1 + num_speculative_tokens uniform query rows. + self._init_reorder_batch_threshold( + 1, + supports_spec_as_decode=True, + supports_dcp_with_varlen=True, + ) max_dense_mla_rows = int(vllm_config.scheduler_config.max_num_seqs) * int( self.reorder_batch_threshold ) if max_dense_mla_rows > _MAX_B12X_QUERY_ROWS: raise ValueError( - "B12X_MLA query capacity exceeds its limit: " + "B12X_MLA flattened query capacity exceeds its limit: " f"rows={max_dense_mla_rows}, limit={_MAX_B12X_QUERY_ROWS}." ) self._max_dense_mla_rows = max_dense_mla_rows + # The builder receives the final kernel block size, including K3's + # hybrid-cache alignment (944 in the production launcher). Planning in + # the layer constructor would incorrectly see the initial size of 16. + self._effective_heads = self.num_heads * self.dcp_world_size + self._kernel_heads = _kernel_query_heads(self.num_heads, self.dcp_world_size) self._dense_mla_plan = _create_dense_mla_plan( vllm_config, device, page_size=self.page_size, - num_q_heads=self.num_heads, - max_total_q=max_dense_mla_rows, + num_q_heads=self._kernel_heads, + max_total_q=self._max_dense_mla_rows, + dcp_size=self.dcp_world_size, ) self._workspace_specs = self._dense_mla_plan.shapes_and_dtypes() - if is_workspace_manager_initialized(): - current_workspace_manager().get_simultaneous(*self._workspace_specs) - max_table_width = int(self._dense_mla_plan.caps.max_page_table_width) - self._dense_mla_flat_block_table = torch.zeros( - (max_dense_mla_rows, max_table_width), - dtype=torch.int32, + if len(self._workspace_specs) != 1: + raise RuntimeError("B12X_MLA expected exactly one scratch buffer.") + scratch_shape, scratch_dtype = self._workspace_specs[0] + # All layers represented by this metadata builder execute serially on + # the model stream. Give them one stable arena: CUDA graphs retain its + # address, while sharing avoids keeping an identical arena per layer. + self._dense_mla_scratch = torch.empty( + scratch_shape, + dtype=scratch_dtype, device=device, ) - self._dense_mla_flat_seq_lens = torch.empty( - max_dense_mla_rows, - dtype=torch.int32, + # Keep query-gather and output addresses stable across piecewise eager + # attention replays. This makes graph ownership explicit and avoids + # allocating per-layer destinations; each layer still builds a fresh + # caller-scratch-owned B12X binding. All represented layers + # execute serially on the model stream, so one pair is sufficient. + max_rows = self._max_dense_mla_rows + self._dense_mla_padded_q = torch.empty( + (max_rows, self._kernel_heads, _K3_ABSORBED_HEAD_DIM), + dtype=_planned_kv_dtype(vllm_config), device=device, ) - self._dense_mla_flat_query_start_loc = torch.arange( - max_dense_mla_rows + 1, - dtype=torch.int32, + self._dense_mla_padded_output = torch.empty( + (max_rows, self._kernel_heads, _K3_KV_LORA_RANK), + dtype=torch.bfloat16, device=device, ) + self._dense_mla_flat_block_table: torch.Tensor | None = None + self._dense_mla_flat_seq_lens: torch.Tensor | None = None + self._dense_mla_flat_query_start_loc: torch.Tensor | None = None + self._dense_mla_causal_offsets: torch.Tensor | None = None + self._dense_mla_flat_global_seq_lens: torch.Tensor | None = None + self._dense_mla_flat_dcp_remainder: torch.Tensor | None = None + if self.reorder_batch_threshold > 1: + max_table_width = int(self._dense_mla_plan.caps.max_page_table_width) + self._dense_mla_flat_block_table = torch.zeros( + (self._max_dense_mla_rows, max_table_width), + dtype=torch.int32, + device=device, + ) + self._dense_mla_flat_seq_lens = torch.empty( + self._max_dense_mla_rows, + dtype=torch.int32, + device=device, + ) + self._dense_mla_flat_query_start_loc = torch.arange( + self._max_dense_mla_rows + 1, + dtype=torch.int32, + device=device, + ) + self._dense_mla_causal_offsets = torch.arange( + 1 - int(self.reorder_batch_threshold), + 1, + dtype=torch.int32, + device=device, + ) + if self.dcp_world_size > 1: + self._dense_mla_flat_global_seq_lens = torch.empty( + self._max_dense_mla_rows, + dtype=torch.int32, + device=device, + ) + self._dense_mla_flat_dcp_remainder = torch.empty_like( + self._dense_mla_flat_global_seq_lens + ) logger.info_once( - "B12X dense K3 MLA plan: heads=%d, page_size=%d, " - "max_decode_rows=%d, max_cache_tokens=%d, splits=%d", + "B12X dense K3 MLA plan: local_heads=%d, effective_heads=%d, " + "kernel_heads=%d, " + "page_size=%d, " + "max_decode_rows=%d, max_cache_tokens=%d, splits=%d, " + "shared_scratch=%.2f MiB", self.num_heads, + self._effective_heads, + self._kernel_heads, self.page_size, - max_dense_mla_rows, - vllm_config.model_config.max_model_len, + self._max_dense_mla_rows, + _max_dcp_local_cache_tokens(vllm_config, dcp_size=self.dcp_world_size), self._dense_mla_plan.num_splits, + self._dense_mla_scratch.nbytes / (1 << 20), ) def build( @@ -212,42 +420,94 @@ def build( ), ) metadata.dense_mla_plan = self._dense_mla_plan - decode_metadata = metadata.decode - if ( - not metadata.causal - and decode_metadata is not None - and metadata.num_decodes > 0 - and metadata.num_decode_tokens > metadata.num_decodes - ): + metadata.dense_mla_scratch = self._dense_mla_scratch + metadata.dense_mla_padded_q = self._dense_mla_padded_q + metadata.dense_mla_padded_output = self._dense_mla_padded_output + flatten_decode = False + if metadata.decode is not None and metadata.num_decodes > 0: + plan_table_width = int(self._dense_mla_plan.caps.max_page_table_width) + flatten_decode = ( + metadata.num_decode_tokens > metadata.num_decodes + or int(metadata.decode.block_table.shape[1]) > plan_table_width + ) + if flatten_decode: + if metadata.decode is None or metadata.num_decodes <= 0: + raise ValueError("B12X_MLA flattened metadata requires decode rows.") total_q = int(metadata.num_decode_tokens) if total_q > self._max_dense_mla_rows: raise ValueError( - "B12X_MLA non-causal query block exceeds its capacity: " + "B12X_MLA query block exceeds its flattened capacity: " f"rows={total_q}, capacity={self._max_dense_mla_rows}." ) if total_q % metadata.num_decodes: raise ValueError( - "B12X_MLA requires a uniform non-causal query block, got " + "B12X_MLA requires a uniform query block, got " f"tokens={total_q}, requests={metadata.num_decodes}." ) query_len = total_q // metadata.num_decodes - source_table = decode_metadata.block_table - source_width = int(source_table.shape[1]) + source_table = metadata.decode.block_table + source_lens = metadata.decode.seq_lens + assert self._dense_mla_flat_block_table is not None + assert self._dense_mla_flat_seq_lens is not None + assert self._dense_mla_flat_query_start_loc is not None flat_table = self._dense_mla_flat_block_table[:total_q] - if source_width > int(flat_table.shape[1]): - raise ValueError( - "B12X_MLA block table exceeds its planned width: " - f"actual={source_width}, planned={flat_table.shape[1]}." - ) + # A bounded DSpark cache keeps a position-indexed worker table for + # the target's complete context, but compacts its resident tail to + # the beginning before this builder runs. Copy only the page-table + # prefix the bounded dense-MLA plan can consume. This canonicalizes + # even a one-token adaptive draft, whose query does not otherwise + # require row flattening. cache_seqlens is shortened by the same + # compaction, so entries beyond this prefix are unreachable. + source_width = min(int(source_table.shape[1]), int(flat_table.shape[1])) flat_table[:, :source_width].copy_( - source_table[:, None, :] + source_table[:, None, :source_width] .expand(-1, query_len, -1) .reshape(total_q, source_width) ) flat_lens = self._dense_mla_flat_seq_lens[:total_q] - flat_lens.copy_( - decode_metadata.seq_lens[:, None].expand(-1, query_len).reshape(total_q) - ) + if metadata.causal: + # Every flattened row may see the committed prefix and only + # the verification tokens at or before its own position. + assert self._dense_mla_causal_offsets is not None + if self.dcp_world_size > 1: + # ``source_lens`` is already local under DCP, so it cannot + # be decremented once per *global* verification token. + # Build every row from the preserved global final length, + # then map it through the same round-robin layout used by + # the KV-cache slot mapper. + global_source_lens = metadata.decode.dcp_tot_seq_lens + if global_source_lens is None: + raise RuntimeError( + "B12X_MLA DSpark DCP verification requires global " + "decode sequence lengths." + ) + assert self._dense_mla_flat_global_seq_lens is not None + assert self._dense_mla_flat_dcp_remainder is not None + global_flat_lens = self._dense_mla_flat_global_seq_lens[:total_q] + torch.add( + global_source_lens[:, None], + self._dense_mla_causal_offsets[-query_len:], + out=global_flat_lens.view(metadata.num_decodes, query_len), + ) + _dcp_local_seq_lens_from_global( + flat_lens, + self._dense_mla_flat_dcp_remainder[:total_q], + global_flat_lens, + dcp_size=self.dcp_world_size, + dcp_rank=self._dcp_rank, + interleave=self.cp_kv_cache_interleave_size, + ) + else: + # ``source_lens`` includes the complete verification block. + torch.add( + source_lens[:, None], + self._dense_mla_causal_offsets[-query_len:], + out=flat_lens.view(metadata.num_decodes, query_len), + ) + else: + flat_lens.copy_( + source_lens[:, None].expand(-1, query_len).reshape(total_q) + ) metadata.dense_mla_flat_block_table = flat_table metadata.dense_mla_flat_seq_lens = flat_lens metadata.dense_mla_flat_query_start_loc = ( @@ -257,7 +517,7 @@ def build( class B12xMLABackend(MLACommonBackend): - """Opt-in dense Kimi K3 MLA backend backed by B12X.""" + """Opt-in dense Kimi K3 MLA backend backed by b12x.""" supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16] supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [ @@ -269,6 +529,7 @@ class B12xMLABackend(MLACommonBackend): @classmethod def get_supported_head_sizes(cls) -> list[int]: + # Keep the literal visible to the generated backend capability table. return [576] @staticmethod @@ -315,7 +576,7 @@ def supports_combination( try: _load_dense_mla() except (ImportError, AttributeError): - return "B12X_MLA requires a B12X build that provides dense_mla" + return "B12X_MLA requires a b12x build that provides dense_mla" vllm_config = get_current_vllm_config() model_config = vllm_config.model_config @@ -348,20 +609,24 @@ def supports_combination( ) parallel_config = vllm_config.parallel_config - if parallel_config.decode_context_parallel_size != 1: - return "B12X_MLA does not support decode context parallelism" + if parallel_config.prefill_context_parallel_size != 1: + return "B12X_MLA does not support prefill context parallelism" + dcp_size = int(parallel_config.decode_context_parallel_size) local_heads = model_config.get_num_attention_heads(parallel_config) - if local_heads <= 0: - return f"B12X_MLA requires a positive query-head count, got {local_heads}" + try: + _kernel_query_heads(local_heads, dcp_size) + except ValueError as exc: + return str(exc) if vllm_config.scheduler_config.max_num_seqs > _MAX_B12X_QUERY_ROWS: return ( "B12X_MLA max_num_seqs exceeds its 1024-row decode capacity: " f"{vllm_config.scheduler_config.max_num_seqs}" ) - if model_config.max_model_len > _MAX_B12X_CACHE_TOKENS: + local_cache_tokens = _max_dcp_local_cache_tokens(vllm_config) + if local_cache_tokens > _MAX_B12X_CACHE_TOKENS: return ( - "B12X_MLA max_model_len exceeds its 1048576-token capacity: " - f"{model_config.max_model_len}" + "B12X_MLA local DCP cache exceeds its 1048576-token capacity: " + f"{local_cache_tokens}" ) return None @@ -372,7 +637,7 @@ def supports_non_causal(cls) -> bool: class B12xMLAImpl(MLACommonImpl[B12xMLAMetadata]): can_return_lse_for_decode: bool = True - supports_dcp: bool = False + supports_quant_query_input: bool = True def __init__( self, @@ -436,35 +701,109 @@ def __init__( f"B12xMLAImpl received non-K3 MLA dimensions {actual_dims}; " f"required {required_dims}." ) - if num_heads <= 0: - raise ValueError( - f"B12xMLAImpl requires a positive query-head count, got {num_heads}." - ) - if get_current_vllm_config().parallel_config.decode_context_parallel_size != 1: + vllm_config = get_current_vllm_config() + dcp_world_size = int(vllm_config.parallel_config.decode_context_parallel_size) + # KimiK3Attention calls this implementation directly instead of going + # through MLAAttention.forward(), where the common MLA path normally + # replaces the sentinel value (-1) with the initialized DCP group size. + # Keep the configured value here so TP16/DCP8 gathers 6 local heads to + # the 48-head shape used by the B12X plan. + self.dcp_world_size = dcp_world_size + self._effective_heads = num_heads * dcp_world_size + self._kernel_heads = _kernel_query_heads(num_heads, dcp_world_size) + if vllm_config.parallel_config.prefill_context_parallel_size != 1: raise NotImplementedError( - "B12xMLAImpl does not support decode context parallelism." + "B12xMLAImpl does not support prefill context parallelism." ) self._dense_mla = _load_dense_mla() + self._dcp_comm_backend = vllm_config.parallel_config.dcp_comm_backend + self._dcp_max_batch_size = vllm_config.scheduler_config.max_num_batched_tokens self._compiled_bindings: set[tuple[object, ...]] = set() - self._fallback_scratch: dict[int, torch.Tensor] = {} + self._scratch_by_plan: dict[int, torch.Tensor] = {} + self._padded_io_by_plan: dict[ + tuple[int, torch.dtype, torch.device], tuple[torch.Tensor, torch.Tensor] + ] = {} def _borrow_scratch(self, plan: Any, device: torch.device) -> torch.Tensor: - specs = plan.shapes_and_dtypes() - if is_workspace_manager_initialized(): - (scratch,) = current_workspace_manager().get_simultaneous(*specs) - return scratch + """Return fallback storage stable for this backend instance. + Production metadata provides a group-shared arena. Direct backend + users may not, so retain the per-backend private allocation as a compatibility + path rather than borrowing vLLM's resizable general workspace. + """ + specs = plan.shapes_and_dtypes() key = id(plan) - scratch = self._fallback_scratch.get(key) + scratch = self._scratch_by_plan.get(key) if scratch is None: if len(specs) != 1: raise RuntimeError("B12X_MLA expected exactly one scratch buffer.") shape, dtype = specs[0] scratch = torch.empty(shape, dtype=dtype, device=device) - self._fallback_scratch[key] = scratch + self._scratch_by_plan[key] = scratch return scratch + def _borrow_padded_io( + self, + plan: Any, + q: torch.Tensor, + batch: int, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Compatibility storage for direct users lacking production metadata.""" + key = (id(plan), q.dtype, q.device) + buffers = self._padded_io_by_plan.get(key) + if buffers is None or int(buffers[0].shape[0]) < batch: + if q.is_cuda and torch.cuda.is_current_stream_capturing(): + raise RuntimeError( + "B12X_MLA cannot allocate padded query storage during CUDA " + "graph capture; use B12xMLAMetadataBuilder." + ) + buffers = ( + torch.empty( + (batch, self._kernel_heads, _K3_ABSORBED_HEAD_DIM), + dtype=q.dtype, + device=q.device, + ), + torch.empty( + (batch, self._kernel_heads, _K3_KV_LORA_RANK), + dtype=torch.bfloat16, + device=q.device, + ), + ) + self._padded_io_by_plan[key] = buffers + return buffers[0][:batch], buffers[1][:batch] + + def _bind_dense_mla( + self, + plan: Any, + *, + scratch: torch.Tensor, + q: torch.Tensor, + kv_cache: torch.Tensor, + output: torch.Tensor, + page_table: torch.Tensor, + cache_seqlens: torch.Tensor, + cu_seqlens_q: torch.Tensor, + q_scale: torch.Tensor | None, + kv_scale: torch.Tensor | None, + active_splits: int, + ) -> Any: + """Build a binding from metadata-validated caller-owned scratch.""" + return self._dense_mla.bind( + plan, + scratch=scratch, + q=q, + kv_cache=kv_cache, + output=output, + page_table=page_table, + cache_seqlens=cache_seqlens, + cu_seqlens_q=cu_seqlens_q, + q_scale=q_scale, + kv_scale=kv_scale, + sm_scale=self.scale, + active_splits=active_splits, + ) + def forward_mqa( self, q: torch.Tensor | tuple[torch.Tensor, torch.Tensor], @@ -495,31 +834,98 @@ def forward_mqa( query_start_loc = getattr( attn_metadata, "dense_mla_flat_query_start_loc", None ) - if seq_lens is None or query_start_loc is None: + if block_table is None or seq_lens is None or query_start_loc is None: raise RuntimeError( - "B12X_MLA metadata is missing flattened non-causal rows." + "B12X_MLA metadata is missing flattened decode rows." ) - batch = int(seq_lens.shape[0]) - total_q = int(q.shape[0]) - if total_q < batch: + if int(q.shape[0]) != batch: raise ValueError( - "B12X_MLA requires at least one query row per prepared decode " - f"sequence, got {total_q} rows for {batch} sequences." + "B12X_MLA's single-token decode path requires one query row per " + f"request, got {q.shape[0]} rows for {batch} requests." ) if int(q.shape[1]) != self.num_heads: raise ValueError( f"B12X_MLA expected {self.num_heads} query heads, got {q.shape[1]}." ) - output = torch.empty( - (total_q, self.num_heads, self.kv_lora_rank), - dtype=torch.bfloat16, - device=q.device, - ) - scratch = self._borrow_scratch(plan, q.device) + dcp_group = None + if self.dcp_world_size > 1: + dcp_group = get_dcp_group() + gathered_q = getattr(attn_metadata, "dense_mla_padded_q", None) + if gathered_q is not None: + if int(gathered_q.shape[0]) < batch: + raise ValueError( + "B12X_MLA shared query buffer is too small: " + f"capacity={gathered_q.shape[0]}, batch={batch}." + ) + gathered_q = gathered_q[:batch, : self._effective_heads] + q = dcp_b12x_all_gather_heads( + q, + dcp_group, + max_batch_size=self._dcp_max_batch_size, + output_head_dim=self.kv_lora_rank, + out=gathered_q, + ) + + effective_heads = int(q.shape[1]) + if effective_heads != self._effective_heads: + raise ValueError( + "B12X_MLA gathered an unexpected query-head count: " + f"expected {self._effective_heads}, got {effective_heads}." + ) + padded_q = getattr(attn_metadata, "dense_mla_padded_q", None) + padded_output = getattr(attn_metadata, "dense_mla_padded_output", None) + if self._kernel_heads != effective_heads: + if padded_q is None or padded_output is None: + padded_q, padded_output = self._borrow_padded_io(plan, q, batch) + else: + if int(padded_q.shape[0]) < batch: + raise ValueError( + "B12X_MLA shared padded query buffer is too small: " + f"capacity={padded_q.shape[0]}, batch={batch}." + ) + padded_q = padded_q[:batch] + padded_output = padded_output[:batch] + if padded_q.dtype != q.dtype: + raise TypeError( + "B12X_MLA padded query dtype does not match the live query: " + f"buffer={padded_q.dtype}, query={q.dtype}." + ) + padded_q[:, :effective_heads].copy_(q) + padded_q[:, effective_heads:].zero_() + q = padded_q + output = padded_output + else: + if padded_output is None: + _, padded_output = self._borrow_padded_io(plan, q, batch) + elif int(padded_output.shape[0]) < batch: + raise ValueError( + "B12X_MLA shared output buffer is too small: " + f"capacity={padded_output.shape[0]}, batch={batch}." + ) + output = padded_output[:batch] + scratch = getattr(attn_metadata, "dense_mla_scratch", None) + if scratch is None: + # Compatibility fallback for direct backend users and metadata + # builders without shared scratch. K3 serving metadata supplies + # the capture-stable arena allocated above. + scratch = self._borrow_scratch(plan, q.device) quantized = q.dtype == torch.float8_e4m3fn - binding = self._dense_mla.bind( + # A conventional CUDA graph fixes kernel grid dimensions and scalar + # launch arguments at capture time. Breakable PIECEWISE execution + # calls attention outside the captured segments, so it reaches the + # adaptive branch below on every replay. If another graph mode ever + # captures this backend directly, retain the full plan for correctness. + if q.is_cuda and torch.cuda.is_current_stream_capturing(): + active_splits = int(plan.num_splits) + else: + active_splits = _active_dense_mla_splits( + plan, + getattr(attn_metadata, "max_seq_len", None), + ) + cu_seqlens_q = query_start_loc[: batch + 1] + binding = self._bind_dense_mla( plan, scratch=scratch, q=q, @@ -527,10 +933,10 @@ def forward_mqa( output=output, page_table=block_table, cache_seqlens=seq_lens, - cu_seqlens_q=query_start_loc[: batch + 1], + cu_seqlens_q=cu_seqlens_q, q_scale=layer._q_scale if quantized else None, kv_scale=layer._k_scale if quantized else None, - sm_scale=self.scale, + active_splits=active_splits, ) compile_key = ( @@ -544,12 +950,55 @@ def forward_mqa( if q.is_cuda and torch.cuda.is_current_stream_capturing(): raise RuntimeError( "B12X_MLA encountered an uncompiled layout during CUDA graph " - "capture; eager warmup did not exercise this cache layout." + "capture; the eager graph warmup did not exercise this cache " + "layout." ) self._dense_mla.compile(binding=binding) self._compiled_bindings.add(compile_key) - return self._dense_mla.run(binding=binding) + if is_b12x_compile_only_warmup(): + # The binding above carries the exact FP8/BF16 strides retained by + # capture. Compilation is sufficient here: launching the complete + # K3 warmup forward against capture-prepared workspaces is unsafe. + local_output = output[:, : self.num_heads] + local_output.zero_() + return local_output, None + + output, lse = self._dense_mla.run(binding=binding) + if _DEBUG_FINITE: + torch.cuda.synchronize() + output_ok = bool(torch.isfinite(output).all().item()) + lse_ok = bool((~torch.isnan(lse) & ~torch.isposinf(lse)).all().item()) + if not output_ok or not lse_ok: + raise RuntimeError( + "B12X_MLA produced invalid local output/LSE: " + f"output_finite={output_ok}, lse_valid={lse_ok}" + ) + if dcp_group is None: + return output[:, : self.num_heads], lse[:, : self.num_heads] + + if self._dcp_comm_backend == "a2a": + reduced = dcp_a2a_lse_reduce( + output, + lse, + dcp_group, + is_lse_base_on_e=True, + use_b12x=True, + b12x_max_batch_size=self._dcp_max_batch_size, + b12x_query_head_dim=_K3_ABSORBED_HEAD_DIM, + ) + else: + reduced = cp_lse_ag_out_rs( + output, + lse, + dcp_group, + is_lse_base_on_e=True, + ) + if _DEBUG_FINITE: + torch.cuda.synchronize() + if not bool(torch.isfinite(reduced).all().item()): + raise RuntimeError("B12X_MLA DCP reduction produced nonfinite output") + return reduced, None __all__ = [ diff --git a/vllm/v1/attention/ops/dcp_alltoall.py b/vllm/v1/attention/ops/dcp_alltoall.py index bae050d2881a..ce117bea2b35 100644 --- a/vllm/v1/attention/ops/dcp_alltoall.py +++ b/vllm/v1/attention/ops/dcp_alltoall.py @@ -31,7 +31,6 @@ from vllm.logger import init_logger from vllm.triton_utils import tl, triton from vllm.utils.multi_stream_utils import is_vllm_cudagraph_capture_active -from vllm.v1.attention.ops.common import mask_dcp_empty_shards_ if TYPE_CHECKING: from vllm.distributed.parallel_state import GroupCoordinator @@ -42,10 +41,33 @@ _B12X_DCP_A2A_POOLS: dict[tuple[int, int, int, int, int, int], Any] = {} _B12X_DCP_A2A_DISABLED: set[tuple[int, int, int, int, int, int]] = set() -# DCP likewise has one stable eager scheduler owner. Graph target/draft/encoder -# identities are supplied separately by their GraphCaptureContext. _B12X_DCP_EAGER_CHANNEL_ID = "vllm:eager:dcp" _B12X_DCP_MAX_CONCURRENT_CHANNELS = 2 +# Each entry records the semantic channel, stream, and cleanup stack owned by +# an in-flight graph capture. A pool created after the capture context opens +# must join this context before its first graph launch. +_B12X_DCP_ACTIVE_CAPTURE: dict[int, tuple[str, Any, ExitStack]] = {} + + +def _b12x_dcp_channel_id(cp_group: GroupCoordinator | None = None) -> str: + """Return the channel bound to the active DCP graph-capture context.""" + if cp_group is not None: + active = _B12X_DCP_ACTIVE_CAPTURE.get(id(cp_group.device_group)) + if active is not None: + return active[0] + elif len(_B12X_DCP_ACTIVE_CAPTURE) == 1: + return next(iter(_B12X_DCP_ACTIVE_CAPTURE.values()))[0] + return _B12X_DCP_EAGER_CHANNEL_ID + + +_B12X_DCP_WORLD_SIZES = (2, 4, 8, 16) +_KIMI_TP16_WORLD_SIZE = 16 +_KIMI_LOCAL_LATENT_WIDTH = 224 +_KIMI_LOCAL_ROUTER_WIDTH = 56 +_KIMI_GATHERED_LATENT_WIDTH = _KIMI_LOCAL_LATENT_WIDTH * _KIMI_TP16_WORLD_SIZE +_KIMI_ROUTED_EXPERTS = _KIMI_LOCAL_ROUTER_WIDTH * _KIMI_TP16_WORLD_SIZE +_KIMI_TOPK = 16 +_KIMI_PAIRED_MAX_BATCH_SIZE = 8 _DCP_A2A_GRAPH_BUFFERS: dict[ tuple[tuple[int, ...], torch.device, torch.dtype], tuple[torch.Tensor, torch.Tensor], @@ -135,8 +157,28 @@ def _get_b12x_dcp_a2a_pool( single_channel=False, max_concurrent_channels=_B12X_DCP_MAX_CONCURRENT_CHANNELS, ) - pool.prepare_channels((_B12X_DCP_EAGER_CHANNEL_ID,)) - pool.for_stream(channel_id=_B12X_DCP_EAGER_CHANNEL_ID) + # B12X identifies independently replayable channels by a stable + # semantic name. Stream handles are process-local and can be recycled, + # so they are not a valid distributed identity. + # A pool can be created lazily inside a graph capture (the first + # projection gather of the first captured shape). The capture scope + # bound the pools that existed when it opened, so a pool born here + # must join the graph's channel itself or its first launch is rejected + # for using the eager channel while a graph owns capture. + active = _B12X_DCP_ACTIVE_CAPTURE.get(id(cp_group.device_group)) + if active is None: + pool.prepare_channels((_B12X_DCP_EAGER_CHANNEL_ID,)) + pool.for_stream(channel_id=_B12X_DCP_EAGER_CHANNEL_ID) + else: + # Join the capture already in flight, through its own ExitStack so + # the scope releases the channel when it closes. Binding the eager + # channel here instead would pin this stream to a channel the graph + # does not own. + active_channel, active_stream, active_stack = active + pool.prepare_channels((_B12X_DCP_EAGER_CHANNEL_ID, active_channel)) + active_stack.enter_context( + pool.capture(stream=active_stream, channel_id=active_channel) + ) except Exception as exc: init_error = exc @@ -198,15 +240,27 @@ def capture_b12x_dcp_a2a( ), key=lambda item: item[0][1:], ) - if matching_pools and channel_id is None: - raise RuntimeError( - "distributed PCIe DCP graph capture requires an explicit semantic " - "channel_id" - ) - with ExitStack() as stack: - for _, pool in matching_pools: - stack.enter_context(pool.capture(stream=stream, channel_id=channel_id)) + if channel_id is None: + if matching_pools or envs.VLLM_USE_B12X_DCP_A2A: + raise RuntimeError( + "distributed PCIe DCP graph capture requires an explicit " + "semantic channel_id" + ) yield + return + + previous_active = _B12X_DCP_ACTIVE_CAPTURE.get(group_id) + try: + with ExitStack() as stack: + _B12X_DCP_ACTIVE_CAPTURE[group_id] = (channel_id, stream, stack) + for _, pool in matching_pools: + stack.enter_context(pool.capture(stream=stream, channel_id=channel_id)) + yield + finally: + if previous_active is None: + _B12X_DCP_ACTIVE_CAPTURE.pop(group_id, None) + else: + _B12X_DCP_ACTIVE_CAPTURE[group_id] = previous_active def checkpoint_b12x_dcp_a2a_channels( @@ -259,7 +313,7 @@ def _try_b12x_dcp_lse_reduce( or not cp_attn_out.is_cuda or cp_attn_out.dtype not in (torch.float16, torch.bfloat16) or cp_attn_lse.dtype != torch.float32 - or world_size not in (2, 4, 8) + or world_size not in _B12X_DCP_WORLD_SIZES or cp_attn_out.ndim != 3 or cp_attn_lse.shape != cp_attn_out.shape[:2] ): @@ -326,7 +380,7 @@ def _try_b12x_dcp_lse_reduce( cp_attn_lse, out=reduced, is_lse_base_on_e=is_lse_base_on_e, - channel_id=_B12X_DCP_EAGER_CHANNEL_ID, + channel_id=_b12x_dcp_channel_id(cp_group), ) @@ -336,20 +390,22 @@ def _try_b12x_dcp_all_gather_heads( *, max_batch_size: int | None, output_head_dim: int | None, + out: torch.Tensor | None = None, ) -> torch.Tensor | None: """Gather rank-local query heads with the B12X PCIe channel.""" world_size = cp_group.world_size if ( not local_input.is_cuda - or local_input.dtype not in (torch.float16, torch.bfloat16) - or world_size not in (2, 4, 8) + or local_input.dtype not in (torch.float16, torch.bfloat16, torch.float8_e4m3fn) + or world_size not in _B12X_DCP_WORLD_SIZES or local_input.ndim != 3 or not local_input.is_contiguous() ): return None batch, local_heads, head_dim = local_input.shape - if local_heads <= 0 or head_dim % 8 != 0: + gather_alignment = 16 if local_input.dtype == torch.float8_e4m3fn else 8 + if local_heads <= 0 or head_dim % gather_alignment != 0: return None if max_batch_size is None: max_batch_size = batch @@ -377,9 +433,15 @@ def _try_b12x_dcp_all_gather_heads( ) if pool is None: return None + if out is None: + return pool.all_gather_heads( + local_input, + channel_id=_b12x_dcp_channel_id(cp_group), + ) return pool.all_gather_heads( local_input, - channel_id=_B12X_DCP_EAGER_CHANNEL_ID, + out=out, + channel_id=_b12x_dcp_channel_id(cp_group), ) @@ -389,19 +451,289 @@ def dcp_b12x_all_gather_heads( *, max_batch_size: int | None = None, output_head_dim: int | None = None, + out: torch.Tensor | None = None, ) -> torch.Tensor: """Gather query heads with B12X, falling back to the group backend.""" local_input = local_input.contiguous() if envs.VLLM_USE_B12X_DCP_A2A: - result = _try_b12x_dcp_all_gather_heads( - local_input, + if out is None: + result = _try_b12x_dcp_all_gather_heads( + local_input, + cp_group, + max_batch_size=max_batch_size, + output_head_dim=output_head_dim, + ) + else: + result = _try_b12x_dcp_all_gather_heads( + local_input, + cp_group, + max_batch_size=max_batch_size, + output_head_dim=output_head_dim, + out=out, + ) + if result is not None: + return result + result = cp_group.all_gather(local_input, dim=1) + if out is None: + return result + out.copy_(result) + return out + + +def _try_b12x_dcp_all_gather_pair( + local_first: torch.Tensor, + local_second: torch.Tensor, + cp_group: GroupCoordinator, + *, + max_batch_size: int | None, +) -> tuple[torch.Tensor, torch.Tensor] | None: + """Gather two decode projections behind one B12X IPC barrier.""" + world_size = cp_group.world_size + supported_dtypes = ( + torch.float16, + torch.bfloat16, + torch.float32, + torch.float8_e4m3fn, + ) + if ( + world_size not in _B12X_DCP_WORLD_SIZES + or local_first.dtype not in supported_dtypes + or local_second.dtype not in supported_dtypes + or not local_first.is_cuda + or not local_second.is_cuda + or local_first.device != local_second.device + or local_first.ndim != 2 + or local_second.ndim != 2 + or local_first.shape[0] != local_second.shape[0] + or not local_first.is_contiguous() + or not local_second.is_contiguous() + ): + return None + batch = int(local_first.shape[0]) + first_row_bytes = int(local_first.shape[1]) * local_first.element_size() + second_row_bytes = int(local_second.shape[1]) * local_second.element_size() + if batch < 1 or first_row_bytes % 16 != 0 or second_row_bytes % 16 != 0: + return None + if max_batch_size is None: + max_batch_size = batch + max_batch_size = int(max_batch_size) + token_cap = envs.VLLM_DCP_A2A_MAX_TOKENS + if token_cap > 0: + if batch > token_cap: + return None + max_batch_size = min(max_batch_size, token_cap) + if max_batch_size < batch: + return None + + combined_row_bytes = first_row_bytes + second_row_bytes + pool = _get_b12x_dcp_a2a_pool( + cp_group, + device=local_first.device, + total_heads=world_size, + head_dim=combined_row_bytes, + query_head_dim=combined_row_bytes, + max_batch_size=max_batch_size, + ) + if pool is None or not hasattr(pool, "all_gather_pair"): + return None + return pool.all_gather_pair( + local_first, + local_second, + channel_id=_b12x_dcp_channel_id(cp_group), + ) + + +def dcp_b12x_all_gather_pair( + local_first: torch.Tensor, + local_second: torch.Tensor, + cp_group: GroupCoordinator, + *, + max_batch_size: int | None = None, +) -> tuple[torch.Tensor, torch.Tensor]: + """Gather two rank-local rows together, with exact separate fallbacks.""" + if envs.VLLM_USE_B12X_DCP_A2A: + result = _try_b12x_dcp_all_gather_pair( + local_first, + local_second, cp_group, max_batch_size=max_batch_size, - output_head_dim=output_head_dim, ) if result is not None: return result - return cp_group.all_gather(local_input, dim=1) + return ( + cp_group.all_gather(local_first, dim=-1), + cp_group.all_gather(local_second, dim=-1), + ) + + +def try_dcp_b12x_all_gather_pair_kimi_topk( + local_down: torch.Tensor, + local_router: torch.Tensor, + correction_bias: torch.Tensor, + cp_group: GroupCoordinator, + *, + max_batch_size: int | None = None, +) -> tuple[torch.Tensor, torch.Tensor] | None: + """Return Kimi's gathered latent and compact routing payload on TP16. + + The payload is one FP32 tensor with contiguous ``[M, 16]`` weight and ID + planes; the ID plane is viewed as int32 by the K3 router. This function + deliberately has no semantic NCCL fallback; its caller retains the + ordinary paired gather plus router implementation when the exact K3 + contract is unavailable. + """ + batch = int(local_down.shape[0]) if local_down.ndim == 2 else 0 + if ( + not envs.VLLM_USE_B12X_DCP_A2A + or cp_group.world_size != _KIMI_TP16_WORLD_SIZE + or not 1 <= batch <= _KIMI_PAIRED_MAX_BATCH_SIZE + or local_down.shape != (batch, _KIMI_LOCAL_LATENT_WIDTH) + or local_down.dtype != torch.bfloat16 + or local_router.shape != (batch, _KIMI_LOCAL_ROUTER_WIDTH) + or local_router.dtype != torch.float32 + or correction_bias.shape != (_KIMI_ROUTED_EXPERTS,) + or correction_bias.dtype != torch.float32 + or not local_down.is_cuda + or not local_router.is_cuda + or not correction_bias.is_cuda + or local_down.device != local_router.device + or local_down.device != correction_bias.device + or not local_down.is_contiguous() + or not local_router.is_contiguous() + or not correction_bias.is_contiguous() + ): + return None + if max_batch_size is None: + max_batch_size = 1 if batch == 1 else _KIMI_PAIRED_MAX_BATCH_SIZE + if int(max_batch_size) < batch: + return None + + combined_row_bytes = _KIMI_LOCAL_LATENT_WIDTH * 2 + _KIMI_LOCAL_ROUTER_WIDTH * 4 + pool = _get_b12x_dcp_a2a_pool( + cp_group, + device=local_down.device, + total_heads=_KIMI_TP16_WORLD_SIZE, + head_dim=combined_row_bytes, + query_head_dim=combined_row_bytes, + max_batch_size=int(max_batch_size), + ) + if pool is None or not hasattr(pool, "all_gather_pair_kimi_topk"): + return None + + routed_hidden_states = torch.empty( + (batch, _KIMI_GATHERED_LATENT_WIDTH), + device=local_down.device, + dtype=torch.bfloat16, + ) + routing_payload = torch.empty( + (batch * 2, _KIMI_TOPK), + device=local_down.device, + dtype=torch.float32, + ) + topk_weights = routing_payload[:batch] + topk_ids = routing_payload[batch:].view(torch.int32) + pool.all_gather_pair_kimi_topk( + local_down, + local_router, + correction_bias, + routed_hidden_states, + topk_weights, + topk_ids, + channel_id=_b12x_dcp_channel_id(cp_group), + ) + return routed_hidden_states, routing_payload + + +def warmup_b12x_kimi_projection_gathers( + projection_group: GroupCoordinator, + *, + device: torch.device, +) -> int: + """Create Kimi's paired TP channels before CUDA graph capture. + + The M=8 paired projection is first reached by DSpark verification, while + the M=1 gather+top-k channel is first reached by ordinary decode. Neither + geometry is guaranteed to run during the large-token memory-profile + forward. Creating either pool from inside ``graph_capture()`` is too late: + it misses the graph-specific channel binding established on context entry + and leaves captured nodes sharing the eager channel. + """ + if ( + not envs.VLLM_USE_B12X_DCP_A2A + or not envs.VLLM_KIMI_USE_B12X_PROJECTION_GATHER + or not envs.VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_GATHER + or projection_group.world_size != _KIMI_TP16_WORLD_SIZE + ): + return 0 + + # A target-only max-num-seqs=1 profile deliberately caps the B12X DCP + # path at one token and routes larger batches through its exact NCCL + # fallback. Do not make that profile initialize an M=8 channel it can + # never dispatch; DSpark profiles set the cap to at least eight and still + # precreate this graph channel before verification capture. + token_cap = envs.VLLM_DCP_A2A_MAX_TOKENS + warmed = 0 + if token_cap <= 0 or token_cap >= _KIMI_PAIRED_MAX_BATCH_SIZE: + local_down = torch.zeros( + (_KIMI_PAIRED_MAX_BATCH_SIZE, _KIMI_LOCAL_LATENT_WIDTH), + device=device, + dtype=torch.bfloat16, + ) + local_router = torch.zeros( + (_KIMI_PAIRED_MAX_BATCH_SIZE, _KIMI_LOCAL_ROUTER_WIDTH), + device=device, + dtype=torch.float32, + ) + if ( + envs.VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_TOPK + and envs.VLLM_KIMI_USE_B12X_BATCHED_PROJECTION_TOPK + ): + correction_bias = torch.zeros( + (_KIMI_ROUTED_EXPERTS,), device=device, dtype=torch.float32 + ) + paired = try_dcp_b12x_all_gather_pair_kimi_topk( + local_down, + local_router, + correction_bias, + projection_group, + max_batch_size=_KIMI_PAIRED_MAX_BATCH_SIZE, + ) + else: + paired = _try_b12x_dcp_all_gather_pair( + local_down, + local_router, + projection_group, + max_batch_size=_KIMI_PAIRED_MAX_BATCH_SIZE, + ) + if paired is None: + raise RuntimeError( + "B12X Kimi M=8 paired projection gather path is unavailable" + ) + warmed += 1 + + if envs.VLLM_KIMI_USE_B12X_PAIRED_PROJECTION_TOPK: + local_down = torch.zeros( + (1, _KIMI_LOCAL_LATENT_WIDTH), device=device, dtype=torch.bfloat16 + ) + local_router = torch.zeros( + (1, _KIMI_LOCAL_ROUTER_WIDTH), device=device, dtype=torch.float32 + ) + correction_bias = torch.zeros( + (_KIMI_ROUTED_EXPERTS,), device=device, dtype=torch.float32 + ) + fused = try_dcp_b12x_all_gather_pair_kimi_topk( + local_down, + local_router, + correction_bias, + projection_group, + max_batch_size=1, + ) + if fused is None: + raise RuntimeError( + "B12X Kimi M=1 paired projection gather+top-k is unavailable" + ) + warmed += 1 + return warmed def warmup_b12x_dcp_a2a( @@ -417,12 +749,12 @@ def warmup_b12x_dcp_a2a( """Create and exercise the B12X DCP channel before CUDA graph capture.""" if not envs.VLLM_USE_B12X_DCP_A2A: return - if cp_group.world_size not in (2, 4, 8): + if cp_group.world_size not in _B12X_DCP_WORLD_SIZES: # The PCIe channel only exists for these world sizes. The runtime # dispatchers already fall back to NCCL collectives per call, so an # unsupported DCP size (e.g. TP6 with DCP3/DCP6) must not fail boot. logger.warning_once( - "B12X PCIe DCP collectives support world sizes 2/4/8; " + "B12X PCIe DCP collectives support world sizes 2/4/8/16; " "DCP world size %d uses NCCL collectives instead.", cp_group.world_size, ) @@ -525,10 +857,14 @@ def _lse_weighted_combine( weight_sum = weights.sum(dim=0, keepdim=True) # [1, B, H] weights = weights / weight_sum.clamp(min=1e-10) # [N, B, H] - # Weighted combination: sum over N dimension - weights = weights.unsqueeze(-1) - outputs = torch.where(weights == 0, torch.zeros_like(outputs), outputs) - result = (outputs * weights).sum(dim=0) # [B, H, D] + # Empty shards may leave non-finite output values paired with a zero LSE + # weight. Mask those values before multiplication because zero times NaN + # is still NaN under IEEE arithmetic. + expanded_weights = weights.unsqueeze(-1) + finite_outputs = torch.where( + expanded_weights == 0, torch.zeros_like(outputs), outputs + ) + result = (finite_outputs * expanded_weights).sum(dim=0) # [B, H, D] if return_lse: if is_lse_base_on_e: @@ -709,7 +1045,7 @@ def _dcp_a2a_pack_send_kernel( lse_val = tl.load( lse_ptr + batch_idx * lse_stride_B + src_head_idx * lse_stride_H - ).to(tl.float32) + ) if LSE_PACK_DIM == 1: tl.store( send_ptr + send_base + HEAD_DIM * send_stride_D, @@ -862,10 +1198,7 @@ def _dcp_a2a_pack_send( h_per_rank: int, head_dim: int, lse_pack_dim: int, - seq_lens: torch.Tensor | None = None, - query_start_loc: torch.Tensor | None = None, ) -> None: - mask_dcp_empty_shards_(cp_attn_lse, seq_lens, query_start_loc) grid = (cp_attn_out.shape[0], h_per_rank, 1) _dcp_a2a_pack_send_kernel[grid]( cp_attn_out, @@ -938,8 +1271,6 @@ def dcp_a2a_lse_reduce( ctx: CPTritonContext | None = None, return_lse: bool = False, is_lse_base_on_e: bool = True, - seq_lens: torch.Tensor | None = None, - query_start_loc: torch.Tensor | None = None, use_b12x: bool = False, b12x_max_batch_size: int | None = None, b12x_query_head_dim: int | None = None, @@ -947,18 +1278,16 @@ def dcp_a2a_lse_reduce( """ Combine partial attention outputs across DCP ranks using All-to-All. - The output and LSE are packed into a single output-dtype buffer, sent + The output and fp32 LSE are packed into a single output-dtype buffer, sent with one All-to-All, then unpacked and combined with exact LSE weighting. Args: cp_attn_out: [B, H, D] where B=num_tokens, H=total_heads, D=head_dim - cp_attn_lse: [B, H] floating-point log-sum-exp values + cp_attn_lse: [B, H] log-sum-exp values (fp32) cp_group: GroupCoordinator for DCP communication ctx: CPTritonContext (unused, for signature compatibility) return_lse: If True, also return the combined global LSE is_lse_base_on_e: If True, LSE is base e; if False, base 2 - seq_lens: Local KV lengths. Empty shards contribute zero weight. - query_start_loc: Cumulative query-token offsets for each request. use_b12x: Try the low-latency B12X PCIe path before NCCL A2A b12x_max_batch_size: Configured token capacity for B12X staging b12x_query_head_dim: Query width when it differs from output width @@ -975,7 +1304,6 @@ def dcp_a2a_lse_reduce( return cp_attn_out if use_b12x and envs.VLLM_USE_B12X_DCP_A2A: - mask_dcp_empty_shards_(cp_attn_lse, seq_lens, query_start_loc) b12x_result = _try_b12x_dcp_lse_reduce( cp_attn_out, cp_attn_lse, @@ -987,11 +1315,37 @@ def dcp_a2a_lse_reduce( ) if b12x_result is not None: return b12x_result + token_cap = envs.VLLM_DCP_A2A_MAX_TOKENS + if ( + token_cap > 0 + and cp_attn_out.shape[0] > token_cap + and envs.VLLM_DCP_A2A_LARGE_BACKEND == "ag_rs" + ): + # ProcessGroupNCCL lazily reserves a sizable transport workspace + # on its first all-to-all. That hidden allocation can fail after + # an explicitly sized, near-capacity KV cache has been created. + # PyNccl AG+RS uses the already-warmed DCP communicator and keeps + # the low-latency B12X path unchanged for decode-sized batches. + from vllm.v1.attention.ops.common import cp_lse_ag_out_rs + + return cp_lse_ag_out_rs( + cp_attn_out, + cp_attn_lse, + cp_group, + ctx=ctx, + return_lse=return_lse, + is_lse_base_on_e=is_lse_base_on_e, + head_major_output=True, + ) B, H, D = cp_attn_out.shape if H % world_size != 0: raise ValueError(f"H={H} must be divisible by DCP world size {world_size}.") H_per_rank = H // world_size + # The pack kernel bit-casts the LSE as fp32; some MLA backends return it in + # the activation dtype (bf16/fp16), so enforce the documented fp32 contract. + if cp_attn_lse.dtype != torch.float32: + cp_attn_lse = cp_attn_lse.to(torch.float32) lse_pack_dim = _dcp_a2a_lse_pack_dim(cp_attn_out.dtype) send_buffer, recv_buffer = _dcp_a2a_send_recv_buffers( @@ -1008,8 +1362,6 @@ def dcp_a2a_lse_reduce( H_per_rank, D, lse_pack_dim, - seq_lens=seq_lens, - query_start_loc=query_start_loc, ) work = dist.all_to_all_single( diff --git a/vllm/v1/core/kv_cache_utils.py b/vllm/v1/core/kv_cache_utils.py index 0317e9ded0f0..675bbfc3ac0c 100644 --- a/vllm/v1/core/kv_cache_utils.py +++ b/vllm/v1/core/kv_cache_utils.py @@ -1181,6 +1181,7 @@ def is_kv_cache_type_attention_free(kv_cache_spec: dict[str, KVCacheSpec]) -> bo def _get_kv_cache_groups_uniform_page_size( kv_cache_spec: dict[str, KVCacheSpec], + group_size_override: int | None = None, ) -> list[KVCacheGroupSpec]: """ Generates the KV cache groups for hybrid models with multiple @@ -1240,9 +1241,16 @@ def _get_kv_cache_groups_uniform_page_size( memory per block is the same for all groups. Args: - kv_cache_spec: The KVCacheSpec of each attention layer in the model + kv_cache_spec: KV-cache specification for each attention layer. + group_size_override: Number of physical layers assigned to every + cache group. When omitted, the grouping heuristic derives the + size from the attention-layer counts. + Returns: - The generated KVCacheGroupSpecs + Cache-group specifications with a uniform physical page size. + + Raises: + ValueError: If ``group_size_override`` is not positive. """ # Group all layers by kv_cache_spec. # E.g., 2 full attention layers and 3 sliding window attention layers, @@ -1296,6 +1304,13 @@ def _get_kv_cache_groups_uniform_page_size( # layers while accommodating speculative decoding drafters that add # extra layers to one attention type. group_size = max_num_layers + if group_size_override is not None: + if group_size_override <= 0: + raise ValueError( + "KV cache group size override must be positive, got " + f"{group_size_override}." + ) + group_size = group_size_override grouped_layers = [] for layers in layer_buckets: num_padding_layers = group_size - len(layers) % group_size @@ -1745,6 +1760,12 @@ def group_and_unify_kv_cache_specs( Group the KV cache specs and unify each group into one UniformTypeKVCacheSpecs. Currently, this is only used for DeepseekV4. """ + # Recurrent state pages require the generic hybrid-cache planner. Packing + # them into the DeepSeek-V4 MLA tuple layout would charge the larger state + # page to every packed block and can collapse attention-cache capacity. + if any(isinstance(spec, MambaSpec) for spec in kv_cache_spec.values()): + return None + has_swa = any( isinstance(spec, SlidingWindowMLASpec) for spec in kv_cache_spec.values() ) @@ -2064,7 +2085,30 @@ def get_kv_cache_groups( if fallback_groups is None: raise return fallback_groups - groups = _get_kv_cache_groups_uniform_page_size(filtered_spec) + model_type = getattr(vllm_config.model_config.hf_config, "model_type", None) + k3_group_size = envs.VLLM_K3_KV_GROUP_SIZE + use_k3_group_size_override = ( + k3_group_size > 0 + and model_type == "kimi_k3" + and any(isinstance(spec, MambaSpec) for spec in filtered_spec.values()) + and any( + isinstance(spec, SlidingWindowMLASpec) + and spec.non_causal_multi_token_decode + for spec in filtered_spec.values() + ) + ) + if use_k3_group_size_override: + groups = _get_kv_cache_groups_uniform_page_size( + filtered_spec, group_size_override=k3_group_size + ) + logger.info_once( + "Kimi-K3 uses hybrid KV group size %d (%d groups) to reduce " + "cache padding and block-table overhead.", + k3_group_size, + len(groups), + ) + else: + groups = _get_kv_cache_groups_uniform_page_size(filtered_spec) # Add hidden-state layers back with page aligned to the common page. if hidden_specs: diff --git a/vllm/v1/kv_cache_interface.py b/vllm/v1/kv_cache_interface.py index ef7c7b8b83f3..14f238b4c735 100644 --- a/vllm/v1/kv_cache_interface.py +++ b/vllm/v1/kv_cache_interface.py @@ -533,6 +533,7 @@ def merge(cls, specs: list[Self]) -> Self: block_stride_set = set(spec.indexes_kv_by_block_stride for spec in specs) dcp_replicated_set = set(spec.dcp_replicated for spec in specs) dcp_kv_shard_count_set = set(spec.dcp_kv_shard_count for spec in specs) + non_causal_set = set(spec.non_causal_multi_token_decode for spec in specs) assert ( len(cache_dtype_str_set) == 1 and len(dtype_set) == 1 @@ -542,10 +543,11 @@ def merge(cls, specs: list[Self]) -> Self: and len(block_stride_set) == 1 and len(dcp_replicated_set) == 1 and len(dcp_kv_shard_count_set) == 1 + and len(non_causal_set) == 1 ), ( "All attention layers in the same KV cache group must use the same " "dtype, quantization method, compress ratio, model version, and " - "KV block stride indexing, and DCP replication mode." + "KV block stride indexing, DCP replication mode, and causal mode." ) merged_spec = cls( block_size=specs[0].block_size, @@ -558,9 +560,7 @@ def merge(cls, specs: list[Self]) -> Self: cache_dtype_str=cache_dtype_str_set.pop(), compress_ratio=compress_ratio_set.pop(), model_version=model_version_set.pop(), - non_causal_multi_token_decode=any( - spec.non_causal_multi_token_decode for spec in specs - ), + non_causal_multi_token_decode=non_causal_set.pop(), dcp_replicated=dcp_replicated_set.pop(), dcp_kv_shard_count=dcp_kv_shard_count_set.pop(), ) @@ -750,6 +750,9 @@ class SlidingWindowMLASpec(SlidingWindowSpec): compress_ratio: int = 1 model_version: str | None = None dcp_sharded: bool = False + # Parallel draft blocks are flattened into independent decode rows by MLA + # backends. Preserve that execution property when the cache is windowed. + non_causal_multi_token_decode: bool = False def __post_init__(self): _apply_alignment_padding(self) @@ -812,6 +815,7 @@ def merge(cls, specs: list[Self]) -> Self: block_stride_set = set(spec.indexes_kv_by_block_stride for spec in specs) dcp_replicated_set = set(spec.dcp_replicated for spec in specs) dcp_sharded_set = set(spec.dcp_sharded for spec in specs) + non_causal_set = set(spec.non_causal_multi_token_decode for spec in specs) assert ( len(cache_dtype_str_set) == 1 and len(dtype_set) == 1 @@ -822,11 +826,12 @@ def merge(cls, specs: list[Self]) -> Self: and len(block_stride_set) == 1 and len(dcp_replicated_set) == 1 and len(dcp_sharded_set) == 1 + and len(non_causal_set) == 1 ), ( "All attention layers in the same KV cache group must use the same " "dtype, quantization method, compress ratio, model version, " "sliding window size, KV block stride indexing, and DCP sharding " - "mode." + "mode and causal mode." ) return cls( block_size=specs[0].block_size, @@ -842,6 +847,7 @@ def merge(cls, specs: list[Self]) -> Self: compress_ratio=compress_ratio_set.pop(), model_version=model_version_set.pop(), dcp_sharded=dcp_sharded_set.pop(), + non_causal_multi_token_decode=non_causal_set.pop(), ) def is_uniform_with_collection( @@ -852,6 +858,7 @@ def is_uniform_with_collection( and spec.sliding_window == self.sliding_window and spec.dcp_replicated == self.dcp_replicated and spec.dcp_sharded == self.dcp_sharded + and spec.non_causal_multi_token_decode == self.non_causal_multi_token_decode for spec in kv_cache_specs.values() ) diff --git a/vllm/v1/worker/gpu/spec_decode/dflash/cudagraph.py b/vllm/v1/worker/gpu/spec_decode/dflash/cudagraph.py index 53669876d69f..6a17861c339a 100644 --- a/vllm/v1/worker/gpu/spec_decode/dflash/cudagraph.py +++ b/vllm/v1/worker/gpu/spec_decode/dflash/cudagraph.py @@ -109,6 +109,7 @@ def create_forward_fn( num_tokens_across_dp, cg_mode, num_query_per_req=desc.uniform_token_count, + capture_only=True, ) super().capture( diff --git a/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py b/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py index fb6e072628c4..a417c26918da 100644 --- a/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py +++ b/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py @@ -9,6 +9,7 @@ layer, and written into the draft KV cache. """ +import copy from collections.abc import Mapping from typing import Any, NamedTuple @@ -17,14 +18,19 @@ import torch.nn as nn import vllm.envs as envs -from vllm.config import VllmConfig, replace +from vllm.config import VllmConfig from vllm.config.compilation import CUDAGraphMode from vllm.forward_context import BatchDescriptor, set_forward_context from vllm.logger import init_logger from vllm.triton_utils import tl, triton from vllm.v1.attention.backend import AttentionCGSupport from vllm.v1.attention.backends.utils import PAD_SLOT_ID -from vllm.v1.kv_cache_interface import KVCacheConfig +from vllm.v1.kv_cache_interface import ( + KVCacheConfig, + SlidingWindowMLASpec, + UniformTypeKVCacheSpecs, + get_kv_cache_spec_sliding_window, +) from vllm.v1.worker.gpu.attn_utils import build_slot_mappings_by_layer from vllm.v1.worker.gpu.block_table import BlockTables from vllm.v1.worker.gpu.cudagraph_utils import ( @@ -42,6 +48,7 @@ load_dflash_model, maybe_load_mask_embedding, ) +from vllm.v1.worker.gpu.spec_decode.eagle.utils import _create_draft_vllm_config from vllm.v1.worker.gpu.spec_decode.speculator import ( CUDAGraphCapturePhase, DraftModelSpeculator, @@ -149,6 +156,10 @@ def __init__(self, vllm_config: VllmConfig, device: torch.device): self.query_cudagraph_manager: DFlashCudaGraphManager | None = None self.context_cudagraph_manager: DFlashContextCudaGraphManager | None = None self.draft_kv_cache_group_id: int = -1 + # A K3 draft can retain a bounded, replicated DCP1 cache tail while + # the target cache remains DCP-sharded over its complete context. + self.draft_kv_window: int | None = None + self.draft_kv_window_block_size: int | None = None # Manual CUDA graphs keep raw addresses for model intermediates. Retain # each captured backbone output so its storage cannot be recycled while # a graph still reads it during sampling. @@ -169,14 +180,24 @@ def _speculative_steps_for_query_len(self, query_len: int) -> int: @property def attn_vllm_config(self) -> VllmConfig: - # The draft's attention differs from the target's in causality. - return replace( - self.vllm_config, - attention_config=replace( - self.vllm_config.attention_config, - use_non_causal=self.requires_non_causal, - ), - ) + # Metadata uses the external draft model's parallel geometry. The + # returned object is an isolated view of an already validated runtime + # configuration, so derived attributes remain intact without invoking + # dataclass or Pydantic construction again. + draft_vllm_config = copy.copy(_create_draft_vllm_config(self.vllm_config)) + if self.draft_kv_window is not None: + # The bounded length sizes only the draft attention plan. Token + # positions and target request admission retain their global range. + assert self.draft_kv_window_block_size is not None + draft_model_config = copy.copy(draft_vllm_config.model_config) + draft_model_config.max_model_len = ( + self.draft_kv_window + self.draft_kv_window_block_size - 1 + ) + draft_vllm_config.model_config = draft_model_config + draft_attention_config = copy.copy(draft_vllm_config.attention_config) + draft_attention_config.use_non_causal = self.requires_non_causal + draft_vllm_config.attention_config = draft_attention_config + return draft_vllm_config def init_cudagraph_manager(self, cudagraph_mode: CUDAGraphMode) -> None: wants_full = cudagraph_mode.decode_mode() == CUDAGraphMode.FULL @@ -386,6 +407,7 @@ def set_attn( target_input_buffers: InputBuffers, target_attn_groups: list[list[AttentionGroup]], ) -> None: + self._configure_bounded_k3_draft_kv(kv_cache_config) super().set_attn( model_state, kv_cache_config, @@ -444,6 +466,56 @@ def set_attn( ) } + def _configure_bounded_k3_draft_kv(self, kv_cache_config: KVCacheConfig) -> None: + """Discover one uniform rolling window for K3 draft MLA layers.""" + self.draft_kv_window = None + self.draft_kv_window_block_size = None + if ( + getattr(self.draft_model_config.hf_config, "model_type", None) + != "k3_dspark" + ): + return + + draft_windows: set[int] = set() + draft_block_sizes: set[int] = set() + saw_non_mla_window = False + for group in kv_cache_config.kv_cache_groups: + active_names = set(group.layer_names) & self.draft_attn_layer_names + if not active_names: + continue + group_spec = group.kv_cache_spec + for layer_name in active_names: + layer_spec = ( + group_spec.kv_cache_specs[layer_name] + if isinstance(group_spec, UniformTypeKVCacheSpecs) + else group_spec + ) + window = get_kv_cache_spec_sliding_window(layer_spec) + if window is None: + continue + if not isinstance(layer_spec, SlidingWindowMLASpec): + saw_non_mla_window = True + continue + draft_windows.add(int(window)) + draft_block_sizes.add(int(layer_spec.block_size)) + + if saw_non_mla_window or not draft_windows: + return + if len(draft_windows) != 1 or len(draft_block_sizes) != 1: + raise ValueError( + "K3 DSpark bounded KV requires one uniform window and block " + f"size, got windows={sorted(draft_windows)}, " + f"block_sizes={sorted(draft_block_sizes)}." + ) + self.draft_kv_window = draft_windows.pop() + self.draft_kv_window_block_size = draft_block_sizes.pop() + logger.info_once( + "K3 DSpark uses a bounded replicated DCP1 KV tail: window=%d, " + "manager_block_size=%d.", + self.draft_kv_window, + self.draft_kv_window_block_size, + ) + @torch.inference_mode() def _run_model( self, @@ -514,6 +586,7 @@ def _generate_draft( cudagraph_runtime_mode: CUDAGraphMode = CUDAGraphMode.NONE, is_profile: bool = False, num_query_per_req: int | None = None, + capture_only: bool = False, ) -> None: if num_query_per_req is None: num_speculative_steps = self.num_speculative_steps @@ -549,6 +622,16 @@ def _generate_draft( num_reqs, num_speculative_steps ) + def _finish_captured_draft( + self, + *, + num_reqs: int, + num_tokens_padded: int, + num_query_per_req: int, + is_profile: bool, + ) -> None: + """Run speculator work that is intentionally excluded from its graph.""" + def _build_draft_attn_metadata( self, num_reqs: int, @@ -630,6 +713,12 @@ def propose( num_query_tokens = num_reqs * active_query_len max_seq_len = input_batch.seq_lens_cpu_upper_bound[:num_reqs].max().item() self.draft_max_seq_len = min(max_seq_len + active_query_len, self.max_model_len) + if self.draft_kv_window is not None: + assert self.draft_kv_window_block_size is not None + self.draft_max_seq_len = min( + self.draft_max_seq_len, + self.draft_kv_window + self.draft_kv_window_block_size - 1, + ) # NOTE: To avoid CPU-GPU synchronization without CPU knowing the # number of rejected tokens, we maintain the size of input_ids and @@ -724,13 +813,16 @@ def propose( # block-table shift cannot hide the residual partial block. Skipped for # dummy runs, whose idx_mapping does not reference live requests. if not dummy_run: - for gid in self.draft_kv_cache_group_ids: + last_group_index = len(self.draft_kv_cache_group_ids) - 1 + for group_index, gid in enumerate(self.draft_kv_cache_group_ids): shift_draft_block_tables( self.block_tables.input_block_tables[gid], input_batch.idx_mapping, self.num_cached_tokens, self.input_buffers.seq_lens, self.block_tables.kernel_block_sizes[gid], + self.draft_kv_window or 0, + update_seq_lens=group_index == last_group_index, ) # Pre-insert context K/V into the cache. Decode replays a row-bucketed @@ -789,6 +881,12 @@ def propose( if batch_desc.cg_mode == CUDAGraphMode.FULL: assert self.query_cudagraph_manager is not None self.query_cudagraph_manager.run_fullgraph(batch_desc) + self._finish_captured_draft( + num_reqs=num_reqs, + num_tokens_padded=num_tokens_padded, + num_query_per_req=active_query_len, + is_profile=is_profile, + ) else: self._generate_draft( num_reqs, @@ -1111,19 +1209,27 @@ def _shift_draft_block_tables_kernel( num_cached_tokens_ptr, seq_lens_ptr, block_size, + draft_kv_window, BLOCK_SIZE: tl.constexpr, + UPDATE_SEQ_LENS: tl.constexpr, ): req_idx = tl.program_id(0) req_state_idx = tl.load(idx_mapping_ptr + req_idx) num_cached = tl.load(num_cached_tokens_ptr + req_state_idx) - shift = num_cached // block_size + cached_shift = num_cached // block_size + seq_len = tl.load(seq_lens_ptr + req_idx) + window_shift = tl.maximum(seq_len - draft_kv_window, 0) // block_size + window_shift = tl.where(draft_kv_window > 0, window_shift, 0) + shift = cached_shift + window_shift if shift == 0: return row_ptr = block_table_ptr + req_idx.to(tl.int64) * block_table_stride # Only the blocks the shifted sequence still references need to move; # seq_lens holds the cache-shifted draft length (written by # _prepare_dflash_inputs_kernel, which must run first). - seq_len = tl.load(seq_lens_ptr + req_idx) + seq_len -= window_shift * block_size + if UPDATE_SEQ_LENS: + tl.store(seq_lens_ptr + req_idx, seq_len) num_needed = (seq_len + block_size - 1) // block_size num_remaining = tl.minimum(block_table_stride - shift, num_needed) # In-place left shift is safe: iterations run in ascending order and each @@ -1157,6 +1263,9 @@ def shift_draft_block_tables( # [num_reqs] cache-shifted draft sequence lengths seq_lens: torch.Tensor, block_size: int, + draft_kv_window: int = 0, + *, + update_seq_lens: bool = True, ) -> None: """Shift each request's draft block-table row left by its cache-restored whole blocks, hiding slots that hold no draft context KV from the draft's @@ -1170,5 +1279,7 @@ def shift_draft_block_tables( num_cached_tokens, seq_lens, block_size, + draft_kv_window, BLOCK_SIZE=1024, # type: ignore + UPDATE_SEQ_LENS=update_seq_lens, ) diff --git a/vllm/v1/worker/gpu/spec_decode/dspark/speculator.py b/vllm/v1/worker/gpu/spec_decode/dspark/speculator.py index 0d126f672c89..565b4cdb42c0 100644 --- a/vllm/v1/worker/gpu/spec_decode/dspark/speculator.py +++ b/vllm/v1/worker/gpu/spec_decode/dspark/speculator.py @@ -30,6 +30,7 @@ import vllm.envs as envs from vllm.config import VllmConfig from vllm.config.compilation import CUDAGraphMode +from vllm.logger import init_logger from vllm.triton_utils import triton from vllm.v1.worker.gpu.input_batch import InputBatch from vllm.v1.worker.gpu.spec_decode.dflash.speculator import DFlashSpeculator @@ -40,6 +41,8 @@ from vllm.v1.worker.gpu.spec_decode.dspark.online_sts import DSparkOnlineSTS from vllm.v1.worker.gpu.spec_decode.dspark.utils import load_dspark_model +logger = init_logger(__name__) + class DSparkSpeculator(DFlashSpeculator): _speculator_name = "DSpark" @@ -67,6 +70,18 @@ def __init__(self, vllm_config: VllmConfig, device: torch.device): self.max_num_tokens, draft_hidden, dtype=self.dtype, device=device ) + self._capture_sharded_markov = envs.VLLM_DSPARK_CAPTURE_SHARDED_MARKOV + if self._capture_sharded_markov and not envs.VLLM_DSPARK_SHARD_MARKOV_HEAD: + raise ValueError( + "VLLM_DSPARK_CAPTURE_SHARDED_MARKOV requires " + "VLLM_DSPARK_SHARD_MARKOV_HEAD=1." + ) + self._markov_outside_cudagraph = ( + envs.VLLM_DSPARK_SHARD_MARKOV_HEAD and not self._capture_sharded_markov + ) + self._captured_markov_hidden: torch.Tensor | None = None + self._captured_base_logits: torch.Tensor | None = None + self._step_cols = torch.arange( self.num_speculative_steps, dtype=torch.int32, device=device ) @@ -77,6 +92,7 @@ def __init__(self, vllm_config: VllmConfig, device: torch.device): self._draft_topk: int | None = getattr( self.draft_model_config.hf_config, "dspark_draft_topk", None ) + self._use_local_draft_argmax = False self.draft_token_confidence_logits = torch.empty( self.max_num_reqs, @@ -192,8 +208,94 @@ def load_draft_model( dtype=self.draft_logits.dtype, device=self.device, ) + if envs.VLLM_DSPARK_SHARD_MARKOV_HEAD: + supports_local_argmax = getattr(model, "supports_local_draft_argmax", None) + if supports_local_argmax is None or not supports_local_argmax(): + raise RuntimeError( + "A TP-sharded DSpark Markov head requires model support " + "for local draft argmax." + ) + if self._draft_topk is not None: + raise ValueError( + "TP-sharded DSpark Markov sampling does not support " + "dspark_draft_topk." + ) + self._use_local_draft_argmax = True + if self._capture_sharded_markov: + if not getattr(model, "_b12x_dspark_argmax_enabled", False): + raise RuntimeError( + "Captured TP-sharded Markov sampling requires the B12X " + "vocabulary argmax." + ) + markov_head = model.model.markov_head + if not markov_head.replicate_w1: + from vllm.distributed.device_communicators.custom_all_reduce import ( + get_active_b12x_pcie_allreduce, + ) + + custom_allreduce = get_active_b12x_pcie_allreduce() + if custom_allreduce is None: + raise RuntimeError( + "Captured TP-sharded Markov sampling requires an active " + "B12X TP all-reduce runtime." + ) + probe = torch.empty( + self.max_num_reqs, + self.draft_model_config.hf_config.markov_rank, + dtype=self.dtype, + device=self.device, + ) + if not custom_allreduce.should_custom_ar(probe): + raise RuntimeError( + "The active B12X TP all-reduce cannot capture the " + f"Markov W1 output shape {tuple(probe.shape)}." + ) + logger.info_once( + "DSpark captures its TP-sharded Markov tail with B12X W1 " + "all-reduce and B12X vocabulary argmax." + ) + elif self._markov_outside_cudagraph: + logger.info_once( + "DSpark keeps TP-sharded Markov collectives outside the draft " + "CUDA graph. The graph retains the draft backbone and local " + "base-logit projection." + ) return model + def _ensure_captured_markov_buffers(self) -> None: + """Allocate graph handoff buffers before stream capture begins.""" + if ( + self._captured_markov_hidden is not None + and self._captured_base_logits is not None + ): + return + if ( + self._captured_markov_hidden is not None + or self._captured_base_logits is not None + ): + raise RuntimeError("DSpark captured Markov buffers are only partly set") + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError( + "DSpark captured Markov buffers must be allocated by the eager " + "graph warmup before stream capture" + ) + + max_markov_rows = self.max_num_reqs * self.num_speculative_steps + local_vocab_size = self.model.lm_head.num_embeddings_per_partition + logits_dtype = self.model.logits_processor.head_dtype or self.dtype + self._captured_markov_hidden = torch.empty( + max_markov_rows, + self.draft_model_config.get_hidden_size(), + dtype=self.dtype, + device=self.device, + ) + self._captured_base_logits = torch.empty( + max_markov_rows, + local_vocab_size, + dtype=logits_dtype, + device=self.device, + ) + def _sample_logits( self, logits: torch.Tensor, @@ -227,22 +329,35 @@ def _sample_logits( def _sample_sequential( self, num_reqs: int, - head_hidden: torch.Tensor, + head_hidden: torch.Tensor | None, num_speculative_steps: int, num_query_per_req: int, is_profile: bool = False, use_capacity: bool = True, + prepared_sample_hidden: torch.Tensor | None = None, + precomputed_base_logits: torch.Tensor | None = None, ) -> None: # Sequential Markov sampling over the backbone's output hidden states. n_spec = num_speculative_steps num_sample = num_reqs * n_spec # Per-(req, position) head hidden, ordered (req, step). - sample_hidden = head_hidden[self.sample_indices[:num_sample]] - sample_hidden = sample_hidden.view(num_reqs, n_spec, -1) + if prepared_sample_hidden is None: + assert head_hidden is not None + sample_hidden = head_hidden[self.sample_indices[:num_sample]] + sample_hidden = sample_hidden.view(num_reqs, n_spec, -1) + else: + sample_hidden = prepared_sample_hidden.view(num_reqs, n_spec, -1) # Draft-vocab logits; sampled ids are remapped to target vocab below. - base_logits = self.model.compute_draft_logits( - sample_hidden.reshape(num_sample, -1) - ) + if precomputed_base_logits is not None: + base_logits = precomputed_base_logits + elif self._use_local_draft_argmax: + base_logits = self.model.compute_local_draft_logits( + sample_hidden.reshape(num_sample, -1) + ) + else: + base_logits = self.model.compute_draft_logits( + sample_hidden.reshape(num_sample, -1) + ) vocab_size = base_logits.shape[-1] base_logits = base_logits.view(num_reqs, n_spec, vocab_size) base_values = draft_indices = None @@ -279,7 +394,24 @@ def _sample_sequential( ) confidence_logits[:, i] = confidence_i if draft_indices is None: - logits_i = base_logits[:, i] + self.model.markov_bias(markov_embed) + if self._use_local_draft_argmax: + markov_bias = self.model.compute_local_markov_bias(markov_embed) + if self.draft_logits is None: + draft_sampled_i = self.model.sample_local_draft_logits( + base_logits[:, i], markov_bias + ) + else: + logits_i = self.model.gather_local_draft_logits( + base_logits[:, i], markov_bias + ) + draft_sampled_i = self._sample_logits( + logits_i, idx_map[:, i], sample_pos[:, i], i + ) + else: + logits_i = base_logits[:, i] + self.model.markov_bias(markov_embed) + draft_sampled_i = self._sample_logits( + logits_i, idx_map[:, i], sample_pos[:, i], i + ) else: assert base_values is not None logits_i = self.model.apply_markov_bias_gathered( @@ -288,9 +420,9 @@ def _sample_sequential( base_values[:, i], draft_indices[:, i], ) - draft_sampled_i = self._sample_logits( - logits_i, idx_map[:, i], sample_pos[:, i], i - ) + draft_sampled_i = self._sample_logits( + logits_i, idx_map[:, i], sample_pos[:, i], i + ) valid_prefix.logical_and_( (draft_sampled_i >= 0) & (draft_sampled_i < self.vocab_size) ) @@ -424,6 +556,7 @@ def _generate_draft( cudagraph_runtime_mode: CUDAGraphMode = CUDAGraphMode.NONE, is_profile: bool = False, num_query_per_req: int | None = None, + capture_only: bool = False, ) -> None: if num_query_per_req is None: num_query_per_req = self.num_query_per_req @@ -437,6 +570,26 @@ def _generate_draft( num_tokens_across_dp, cudagraph_runtime_mode, ) + if self._markov_outside_cudagraph and ( + capture_only or torch.cuda.is_current_stream_capturing() + ): + # Graph creation executes one eager warmup before stream capture. + # Neither path may launch collectives assigned to the eager tail. + self._ensure_captured_markov_buffers() + assert self._captured_markov_hidden is not None + assert self._captured_base_logits is not None + num_sample = num_reqs * num_speculative_steps + if num_sample > self._captured_markov_hidden.shape[0]: + raise ValueError( + "DSpark captured Markov buffer is too small: " + f"rows={num_sample}, " + f"capacity={self._captured_markov_hidden.shape[0]}." + ) + sample_hidden = head_hidden[self.sample_indices[:num_sample]] + base_logits = self.model.compute_local_draft_logits(sample_hidden) + self._captured_markov_hidden[:num_sample].copy_(sample_hidden) + self._captured_base_logits[:num_sample].copy_(base_logits) + return self._sample_sequential( num_reqs, head_hidden, @@ -448,3 +601,31 @@ def _generate_draft( or num_reqs >= self.capacity_activation_batch_size ), ) + + def _finish_captured_draft( + self, + *, + num_reqs: int, + num_tokens_padded: int, + num_query_per_req: int, + is_profile: bool, + ) -> None: + if not self._markov_outside_cudagraph: + return + assert self._captured_markov_hidden is not None + assert self._captured_base_logits is not None + num_speculative_steps = self._speculative_steps_for_query_len(num_query_per_req) + num_sample = num_reqs * num_speculative_steps + self._sample_sequential( + num_reqs, + None, + num_speculative_steps, + num_query_per_req, + is_profile=is_profile, + use_capacity=( + self.capacity_activation_batch_size <= 0 + or num_reqs >= self.capacity_activation_batch_size + ), + prepared_sample_hidden=self._captured_markov_hidden[:num_sample], + precomputed_base_logits=self._captured_base_logits[:num_sample], + ) diff --git a/vllm/v1/worker/gpu/spec_decode/dspark/utils.py b/vllm/v1/worker/gpu/spec_decode/dspark/utils.py index 05c377c538b2..bc49a065162e 100644 --- a/vllm/v1/worker/gpu/spec_decode/dspark/utils.py +++ b/vllm/v1/worker/gpu/spec_decode/dspark/utils.py @@ -8,6 +8,7 @@ from vllm.model_executor.model_loader import get_model from vllm.v1.attention.backends.registry import AttentionBackendEnum from vllm.v1.worker.gpu.spec_decode.eagle.utils import ( + _create_draft_vllm_config, _should_share, get_target_lm_head, ) @@ -20,7 +21,6 @@ def load_dspark_model(target_model: nn.Module, vllm_config: VllmConfig) -> nn.Mo from vllm.compilation.backends import set_model_tag from vllm.model_executor.models.qwen3_dflash import dflash_has_any_non_causal - from vllm.model_executor.models.utils import get_draft_quant_config backend = speculative_config.attention_backend if backend is None: @@ -28,27 +28,36 @@ def load_dspark_model(target_model: nn.Module, vllm_config: VllmConfig) -> nn.Mo # auto-selection may pick one that downgrades the spec-decode # cudagraph to PIECEWISE. backend = AttentionBackendEnum.FLASH_ATTN + # The external draft owns its model, cache, and parallel geometry. In + # particular, its complete replicated cache uses DCP1 while the target can + # shard a separate cache across its DCP group. + draft_vllm_config = _create_draft_vllm_config(vllm_config) draft_vllm_config = replace( - vllm_config, + draft_vllm_config, attention_config=replace( - vllm_config.attention_config, + draft_vllm_config.attention_config, use_non_causal=dflash_has_any_non_causal(draft_model_config.hf_config), backend=backend, ), - cache_config=( - replace( - vllm_config.cache_config, - cache_dtype=speculative_config.kv_cache_dtype, - ) - if speculative_config.kv_cache_dtype is not None - else vllm_config.cache_config - ), ) - # VllmConfig post-init restores the target's quant config because the target - # config is retained for DSpark's target-layer metadata, so we must override it. - draft_vllm_config.quant_config = get_draft_quant_config(vllm_config) - with set_model_tag("dspark_head"): + target_language_model = ( + target_model.get_language_model() + if hasattr(target_model, "get_language_model") + else target_model + ) + if getattr(draft_model_config.hf_config, "model_type", None) == "k3_dspark": + from vllm.models.kimi_k3.nvidia.dspark_mla import ( + protect_k3_compact_rope_sources, + ) + + rope_ownership = protect_k3_compact_rope_sources(target_language_model) + else: + from contextlib import nullcontext + + rope_ownership = nullcontext() + + with rope_ownership, set_model_tag("dspark_head"): draft_model = get_model( vllm_config=draft_vllm_config, model_config=draft_model_config ) @@ -56,11 +65,6 @@ def load_dspark_model(target_model: nn.Module, vllm_config: VllmConfig) -> nn.Mo if get_pp_group().world_size != 1: raise NotImplementedError("DSpark does not support pipeline parallelism.") - target_language_model = ( - target_model.get_language_model() - if hasattr(target_model, "get_language_model") - else target_model - ) target_inner = target_language_model.model draft_inner = draft_model.model diff --git a/vllm/v1/worker/gpu/spec_decode/speculator.py b/vllm/v1/worker/gpu/spec_decode/speculator.py index 122a1a41ebde..1bfd9f2fd3d2 100644 --- a/vllm/v1/worker/gpu/spec_decode/speculator.py +++ b/vllm/v1/worker/gpu/spec_decode/speculator.py @@ -318,7 +318,7 @@ def _build_draft_attn_metadata( step, out=draft_seq_lens_cpu_upper_bound[:num_reqs], ) - draft_seq_lens_cpu_upper_bound[:num_reqs].clamp_(max=self.max_model_len) + draft_seq_lens_cpu_upper_bound[:num_reqs].clamp_(max=self.draft_max_seq_len) seq_lens = self.input_buffers.seq_lens[:num_reqs_padded] dcp_local_seq_lens = None if self.block_tables.cp_size > 1: From 3a50cc050cf70ad3be0f862d361e5fc0a3ec730a Mon Sep 17 00:00:00 2001 From: Martin Vit Date: Sat, 15 Aug 2026 03:30:42 +0000 Subject: [PATCH 2/2] Fix Kimi-K3 integration invariants Apply the FlashAttention source patch idempotently, compile the fused Kimi router before graph capture, preserve the draft checkpoint quantization config, and validate the complete sharded Markov all-reduce shape. Expose the active hierarchical B12X all-reduce runtime required by captured sharded Markov sampling. Validation: Ruff and compileall pass for affected Python files; 12 focused CPU tests pass with 9 CUDA-only skips; the FlashAttention patch applies exactly once across two invocations at f3e1a4f74c99145c0717709860bf765de1703779. AI assistance: Codex implemented the changes and generated the regression tests; human review is required before merge. --- cmake/external_projects/vllm_flash_attn.cmake | 7 +- cmake/patches/apply_git_patch.cmake | 47 +++++++++++ .../test_kimi_k3_triton_warmup.py | 14 ++++ .../test_dflash_prefix_cache_masking.py | 2 +- .../test_dspark_attention_config.py | 7 ++ .../spec_decode/test_dspark_sharded_markov.py | 81 +++++++++++++++++++ tools/kimi_k3/benchmark_nospec_decode.py | 12 ++- .../device_communicators/custom_all_reduce.py | 20 +++++ .../warmup/kimi_k3_triton_warmup.py | 8 +- .../gpu/spec_decode/dspark/speculator.py | 2 +- .../v1/worker/gpu/spec_decode/dspark/utils.py | 4 + 11 files changed, 195 insertions(+), 9 deletions(-) create mode 100644 cmake/patches/apply_git_patch.cmake diff --git a/cmake/external_projects/vllm_flash_attn.cmake b/cmake/external_projects/vllm_flash_attn.cmake index 96607f1bdb9c..dcd8f5a9d356 100644 --- a/cmake/external_projects/vllm_flash_attn.cmake +++ b/cmake/external_projects/vllm_flash_attn.cmake @@ -46,8 +46,11 @@ else() GIT_TAG f3e1a4f74c99145c0717709860bf765de1703779 GIT_SUBMODULES ${VLLM_FLASH_ATTN_GIT_SUBMODULES} GIT_PROGRESS TRUE - PATCH_COMMAND git apply --unidiff-zero --whitespace=nowarn - ${CMAKE_SOURCE_DIR}/cmake/patches/vllm_flash_attn_fa4_dynamic_causal.patch + PATCH_COMMAND ${CMAKE_COMMAND} + -DGIT_EXECUTABLE=git + -DSOURCE_DIR= + -DPATCH_FILE=${CMAKE_SOURCE_DIR}/cmake/patches/vllm_flash_attn_fa4_dynamic_causal.patch + -P ${CMAKE_SOURCE_DIR}/cmake/patches/apply_git_patch.cmake # Don't share the vllm-flash-attn build between build types BINARY_DIR ${CMAKE_BINARY_DIR}/vllm-flash-attn ) diff --git a/cmake/patches/apply_git_patch.cmake b/cmake/patches/apply_git_patch.cmake new file mode 100644 index 000000000000..4abec038bbac --- /dev/null +++ b/cmake/patches/apply_git_patch.cmake @@ -0,0 +1,47 @@ +# Apply a Git patch exactly once to an ExternalProject source tree. + +foreach(required_variable GIT_EXECUTABLE SOURCE_DIR PATCH_FILE) + if(NOT DEFINED ${required_variable}) + message(FATAL_ERROR "${required_variable} is required") + endif() +endforeach() + +execute_process( + COMMAND "${GIT_EXECUTABLE}" -C "${SOURCE_DIR}" apply --reverse --check + --unidiff-zero --whitespace=nowarn "${PATCH_FILE}" + RESULT_VARIABLE reverse_check_result + OUTPUT_QUIET + ERROR_QUIET +) +if(reverse_check_result EQUAL 0) + message(STATUS "Git patch is already applied: ${PATCH_FILE}") + return() +endif() + +execute_process( + COMMAND "${GIT_EXECUTABLE}" -C "${SOURCE_DIR}" apply --check + --unidiff-zero --whitespace=nowarn "${PATCH_FILE}" + RESULT_VARIABLE apply_check_result + OUTPUT_VARIABLE apply_check_output + ERROR_VARIABLE apply_check_error +) +if(NOT apply_check_result EQUAL 0) + message(FATAL_ERROR + "Git patch cannot be applied to ${SOURCE_DIR}: ${PATCH_FILE}\n" + "${apply_check_output}${apply_check_error}" + ) +endif() + +execute_process( + COMMAND "${GIT_EXECUTABLE}" -C "${SOURCE_DIR}" apply + --unidiff-zero --whitespace=nowarn "${PATCH_FILE}" + RESULT_VARIABLE apply_result + OUTPUT_VARIABLE apply_output + ERROR_VARIABLE apply_error +) +if(NOT apply_result EQUAL 0) + message(FATAL_ERROR + "Git patch application failed in ${SOURCE_DIR}: ${PATCH_FILE}\n" + "${apply_output}${apply_error}" + ) +endif() diff --git a/tests/model_executor/test_kimi_k3_triton_warmup.py b/tests/model_executor/test_kimi_k3_triton_warmup.py index 02c09845e4a6..45ef86b078e1 100644 --- a/tests/model_executor/test_kimi_k3_triton_warmup.py +++ b/tests/model_executor/test_kimi_k3_triton_warmup.py @@ -5,12 +5,26 @@ import torch +from vllm.model_executor.warmup import kimi_k3_triton_warmup as warmup_module from vllm.model_executor.warmup.kimi_k3_triton_warmup import ( _warm_recurrent_kda, ) +from vllm.models.kimi_k3.nvidia.ops import topk16 from vllm.models.kimi_k3.nvidia.ops.third_party.kda import fused_recurrent +def test_fused_router_warmup_does_not_require_a_kda_layer(monkeypatch) -> None: + calls = [] + monkeypatch.setenv("VLLM_KIMI_FUSED_TOPK16", "1") + monkeypatch.setattr(warmup_module.current_platform, "is_cuda", lambda: True) + monkeypatch.setattr(warmup_module, "_get_kda_layer", lambda _worker: None) + monkeypatch.setattr(topk16, "warmup_kimi_topk16", lambda: calls.append("topk16")) + + warmup_module.kimi_k3_triton_warmup(SimpleNamespace()) + + assert calls == ["topk16"] + + def test_speculative_kda_warmup_before_kv_cache_binding(monkeypatch) -> None: calls = [] monkeypatch.setattr( diff --git a/tests/v1/spec_decode/test_dflash_prefix_cache_masking.py b/tests/v1/spec_decode/test_dflash_prefix_cache_masking.py index 714d8d8c6a09..e254c99624c0 100644 --- a/tests/v1/spec_decode/test_dflash_prefix_cache_masking.py +++ b/tests/v1/spec_decode/test_dflash_prefix_cache_masking.py @@ -198,5 +198,5 @@ def test_window_shift_updates_shared_sequence_length_once_for_two_groups(): ) assert seq_lens.item() == draft_kv_window - for table, original in zip(tables, originals): + for table, original in zip(tables, originals, strict=True): torch.testing.assert_close(table[0, :4], original[0, 4:8]) diff --git a/tests/v1/spec_decode/test_dspark_attention_config.py b/tests/v1/spec_decode/test_dspark_attention_config.py index 79665a407570..86f363b55b18 100644 --- a/tests/v1/spec_decode/test_dspark_attention_config.py +++ b/tests/v1/spec_decode/test_dspark_attention_config.py @@ -35,7 +35,9 @@ def test_dspark_loader_constructs_model_with_draft_parallel_geometry( draft_config = SimpleNamespace( parallel_config=SimpleNamespace(decode_context_parallel_size=1), attention_config=SimpleNamespace(backend=None, use_non_causal=False), + quant_config=object(), ) + draft_quant_config = object() captured = {} def fake_replace(value, **updates): @@ -63,6 +65,10 @@ def fake_get_model(*, vllm_config, model_config): "vllm.model_executor.models.qwen3_dflash.dflash_has_any_non_causal", lambda _config: True, ) + monkeypatch.setattr( + "vllm.model_executor.models.utils.get_draft_quant_config", + lambda config: draft_quant_config if config is target_config else None, + ) with pytest.raises(ModelCaptured): dspark_utils.load_dspark_model(object(), target_config) @@ -72,6 +78,7 @@ def fake_get_model(*, vllm_config, model_config): assert loaded_config.parallel_config.decode_context_parallel_size == 1 assert loaded_config.attention_config.backend == AttentionBackendEnum.B12X_MLA assert loaded_config.attention_config.use_non_causal + assert loaded_config.quant_config is draft_quant_config def test_dspark_attention_metadata_uses_draft_parallel_geometry(monkeypatch) -> None: diff --git a/tests/v1/spec_decode/test_dspark_sharded_markov.py b/tests/v1/spec_decode/test_dspark_sharded_markov.py index 6bd60155dff8..87c33c0e7fea 100644 --- a/tests/v1/spec_decode/test_dspark_sharded_markov.py +++ b/tests/v1/spec_decode/test_dspark_sharded_markov.py @@ -7,6 +7,10 @@ import torch from vllm.config.compilation import CUDAGraphMode +from vllm.distributed.device_communicators.custom_all_reduce import ( + CustomAllreduce, + get_active_b12x_pcie_allreduce, +) from vllm.v1.worker.gpu.spec_decode.dspark.speculator import DSparkSpeculator @@ -131,3 +135,80 @@ def test_graph_replay_finishes_markov_tail_from_stable_buffers(): args.kwargs["precomputed_base_logits"].untyped_storage().data_ptr() == speculator._captured_base_logits.untyped_storage().data_ptr() ) + + +def test_captured_markov_allreduce_probe_covers_every_draft_step(monkeypatch): + probe_shapes = [] + + class CustomAllreduce: + def should_custom_ar(self, probe): + probe_shapes.append(tuple(probe.shape)) + return True + + model = SimpleNamespace( + supports_local_draft_argmax=lambda: True, + _b12x_dspark_argmax_enabled=True, + model=SimpleNamespace(markov_head=SimpleNamespace(replicate_w1=False)), + ) + speculator = SimpleNamespace( + use_draft_token_capacity=False, + draft_logits=None, + _draft_topk=None, + _capture_sharded_markov=True, + _markov_outside_cudagraph=False, + max_num_reqs=8, + num_speculative_steps=7, + vllm_config=object(), + draft_model_config=SimpleNamespace( + hf_config=SimpleNamespace(markov_rank=128) + ), + dtype=torch.bfloat16, + device=torch.device("cpu"), + ) + monkeypatch.setenv("VLLM_DSPARK_SHARD_MARKOV_HEAD", "1") + monkeypatch.setattr( + "vllm.v1.worker.gpu.spec_decode.dspark.speculator.load_dspark_model", + lambda _target_model, _config: model, + ) + monkeypatch.setattr( + "vllm.distributed.device_communicators.custom_all_reduce." + "get_active_b12x_pcie_allreduce", + lambda: CustomAllreduce(), + ) + + loaded = DSparkSpeculator.load_draft_model( + speculator, + target_model=object(), + target_attn_layer_names=set(), + ) + + assert loaded is model + assert probe_shapes == [(56, 128)] + + +def test_active_b12x_accessor_accepts_hierarchical_runtime(monkeypatch): + custom_allreduce = object.__new__(CustomAllreduce) + custom_allreduce.disabled = False + custom_allreduce._pcie_runtime = object() + group = SimpleNamespace( + device_communicator=SimpleNamespace(ca_comm=custom_allreduce) + ) + monkeypatch.setattr( + "vllm.distributed.parallel_state.get_tp_group", lambda: group + ) + + assert get_active_b12x_pcie_allreduce() is custom_allreduce + + +def test_active_b12x_accessor_rejects_disabled_runtime(monkeypatch): + custom_allreduce = object.__new__(CustomAllreduce) + custom_allreduce.disabled = True + custom_allreduce._pcie_runtime = object() + group = SimpleNamespace( + device_communicator=SimpleNamespace(ca_comm=custom_allreduce) + ) + monkeypatch.setattr( + "vllm.distributed.parallel_state.get_tp_group", lambda: group + ) + + assert get_active_b12x_pcie_allreduce() is None diff --git a/tools/kimi_k3/benchmark_nospec_decode.py b/tools/kimi_k3/benchmark_nospec_decode.py index dae311231fa7..227aa9e691ad 100644 --- a/tools/kimi_k3/benchmark_nospec_decode.py +++ b/tools/kimi_k3/benchmark_nospec_decode.py @@ -15,7 +15,17 @@ def _validated_http_url(url: str) -> str: - """Return an HTTP(S) URL or reject unsupported URL schemes.""" + """Validate that a URL uses HTTP or HTTPS and has a network location. + + Args: + url: URL accepted from the command line or discovered endpoint. + + Returns: + The unchanged validated URL. + + Raises: + ValueError: If the URL is not an absolute HTTP or HTTPS URL. + """ parsed = urlparse(url) if parsed.scheme not in {"http", "https"} or not parsed.netloc: raise ValueError(f"expected an HTTP(S) URL, got {url!r}") diff --git a/vllm/distributed/device_communicators/custom_all_reduce.py b/vllm/distributed/device_communicators/custom_all_reduce.py index a94211a703df..a57927b311b5 100644 --- a/vllm/distributed/device_communicators/custom_all_reduce.py +++ b/vllm/distributed/device_communicators/custom_all_reduce.py @@ -1445,3 +1445,23 @@ def get_b12x_pcie_allreduce() -> CustomAllreduce | None: ): return custom_allreduce return None + + +def get_active_b12x_pcie_allreduce() -> CustomAllreduce | None: + """Return the active TP B12X runtime, including hierarchical mode.""" + try: + from vllm.distributed.parallel_state import get_tp_group + + device_communicator = get_tp_group().device_communicator + except (AssertionError, RuntimeError): + return None + if device_communicator is None: + return None + custom_allreduce = getattr(device_communicator, "ca_comm", None) + if ( + isinstance(custom_allreduce, CustomAllreduce) + and not custom_allreduce.disabled + and custom_allreduce._pcie_runtime is not None + ): + return custom_allreduce + return None diff --git a/vllm/model_executor/warmup/kimi_k3_triton_warmup.py b/vllm/model_executor/warmup/kimi_k3_triton_warmup.py index 9900953aa1b1..fe555221cbd1 100644 --- a/vllm/model_executor/warmup/kimi_k3_triton_warmup.py +++ b/vllm/model_executor/warmup/kimi_k3_triton_warmup.py @@ -188,14 +188,14 @@ def kimi_k3_triton_warmup(worker: Worker) -> None: if not current_platform.is_cuda(): return - layer = _get_kda_layer(worker) - if layer is None: - return - if envs.VLLM_KIMI_FUSED_TOPK16: from vllm.models.kimi_k3.nvidia.ops.topk16 import warmup_kimi_topk16 warmup_kimi_topk16() + layer = _get_kda_layer(worker) + if layer is None: + return + _warm_attn_res(worker) _warm_recurrent_kda(layer, worker.model_config.dtype) diff --git a/vllm/v1/worker/gpu/spec_decode/dspark/speculator.py b/vllm/v1/worker/gpu/spec_decode/dspark/speculator.py index 565b4cdb42c0..1f7e765fe4ca 100644 --- a/vllm/v1/worker/gpu/spec_decode/dspark/speculator.py +++ b/vllm/v1/worker/gpu/spec_decode/dspark/speculator.py @@ -240,7 +240,7 @@ def load_draft_model( "B12X TP all-reduce runtime." ) probe = torch.empty( - self.max_num_reqs, + self.max_num_reqs * self.num_speculative_steps, self.draft_model_config.hf_config.markov_rank, dtype=self.dtype, device=self.device, diff --git a/vllm/v1/worker/gpu/spec_decode/dspark/utils.py b/vllm/v1/worker/gpu/spec_decode/dspark/utils.py index bc49a065162e..97d288edf24f 100644 --- a/vllm/v1/worker/gpu/spec_decode/dspark/utils.py +++ b/vllm/v1/worker/gpu/spec_decode/dspark/utils.py @@ -21,6 +21,7 @@ def load_dspark_model(target_model: nn.Module, vllm_config: VllmConfig) -> nn.Mo from vllm.compilation.backends import set_model_tag from vllm.model_executor.models.qwen3_dflash import dflash_has_any_non_causal + from vllm.model_executor.models.utils import get_draft_quant_config backend = speculative_config.attention_backend if backend is None: @@ -32,6 +33,9 @@ def load_dspark_model(target_model: nn.Module, vllm_config: VllmConfig) -> nn.Mo # particular, its complete replicated cache uses DCP1 while the target can # shard a separate cache across its DCP group. draft_vllm_config = _create_draft_vllm_config(vllm_config) + # Replacing the model config does not recompute VllmConfig.quant_config. + # The draft must not inherit the target checkpoint's quantization method. + draft_vllm_config.quant_config = get_draft_quant_config(vllm_config) draft_vllm_config = replace( draft_vllm_config, attention_config=replace(