From 0b9c38484e78a43bca6419416f170aafb70180bb Mon Sep 17 00:00:00 2001 From: Xinyuan Tong Date: Wed, 26 Aug 2026 12:57:21 +0000 Subject: [PATCH 01/44] feat(model): support GLM-5.3-Flash Squashed from zai/glm-5-next (PR #4) onto main @ 27c36368b6. Hybrid MoE architecture: MLA attention, DSA sparse attention with KPool indexer, KDA linear attention, mHC, and native NEXTN draft layer for speculative decoding (fixed 5/1/6 and adaptive). Multimodal serving for image and video (up to 240K visual tokens), with encoder disaggregation (EPD) for ultra-long-video workloads. FP8 weights with BF16 KV cache; verified on 4x GB300 (TP4/EP4) and 8x H100 (TP8/EP8). Co-authored-by: zRzRzRzRzRzRzR Co-authored-by: Shijin Zhang <75300765+Dovis01@users.noreply.github.com> Co-authored-by: zanes-ops --- .gitignore | 1 + .../silu_and_mul_masked_post_quant.cuh | 46 +- .../jit/csrc/dsa/kpool_topk_transform.cuh | 465 +++++ .../sglang/kernels/ops/attention/__init__.py | 1 + .../ops/attention/dsa/quant_k_cache.py | 76 +- .../ops/attention/dsa/tilelang_kernel.py | 56 +- .../ops/attention/dsa/transform_index.py | 52 + .../kernels/ops/attention/dsa_metadata.py | 406 +++- .../sglang/kernels/ops/attention/dsv4/topk.py | 19 +- .../kernels/ops/attention/fla/cumsum.py | 3 +- .../ops/attention/fla/fused_recurrent.py | 5 +- .../fla/fused_sigmoid_gating_recurrent.py | 34 +- .../sglang/kernels/ops/attention/fla/kda.py | 14 +- python/sglang/kernels/ops/attention/utils.py | 21 + .../sglang/kernels/ops/kvcache/mla_buffer.py | 106 +- python/sglang/kernels/ops/layernorm/mhc.py | 214 ++ .../kernels/ops/moe/kpool_topk_transform.py | 80 + .../sglang/kernels/ops/speculative/eagle.py | 62 + python/sglang/srt/arg_groups/overrides.py | 4 + python/sglang/srt/configs/__init__.py | 3 + python/sglang/srt/configs/glm5_next.py | 349 ++++ python/sglang/srt/configs/hybrid_arch.py | 8 + python/sglang/srt/configs/model_config.py | 82 +- python/sglang/srt/configs/qwen3_asr.py | 4 +- python/sglang/srt/disaggregation/base/conn.py | 3 + python/sglang/srt/disaggregation/decode.py | 49 +- .../disaggregation/encoder/preprocessor.py | 222 +- .../srt/disaggregation/encoder/receiver.py | 15 + .../srt/disaggregation/mooncake/conn.py | 78 +- python/sglang/srt/disaggregation/nixl/conn.py | 212 +- python/sglang/srt/disaggregation/prefill.py | 10 + python/sglang/srt/disaggregation/utils.py | 322 ++- .../sglang/srt/entrypoints/openai/protocol.py | 4 + .../srt/entrypoints/openai/serving_chat.py | 129 ++ python/sglang/srt/environ.py | 10 + .../hardware_backend/npu/memory_pool_npu.py | 12 +- .../layers/attention/attention_registry.py | 3 + .../dsa/dsa_backend_mtp_precompute.py | 27 +- .../srt/layers/attention/dsa/dsa_indexer.py | 65 +- .../layers/attention/dsa/dsa_indexer_kpool.py | 1767 ++++++++++++++++ .../layers/attention/dsa/kpool_fp8_index.py | 1720 ++++++++++++++++ .../srt/layers/attention/dsa/kpool_plan.py | 871 ++++++++ .../sglang/srt/layers/attention/dsa/utils.py | 372 +++- .../srt/layers/attention/dsa_backend.py | 1511 +++++++++++++- .../attention/flashattention_backend.py | 137 +- .../attention/flashinfer_mla_backend.py | 264 ++- .../attention/hybrid_linear_attn_backend.py | 48 +- .../layers/attention/linear/kda_backend.py | 108 +- .../attention/linear/kernels/kda_cutedsl.py | 2 + .../attention/linear/kernels/kda_flashkda.py | 18 +- .../attention/linear/kernels/kda_triton.py | 13 +- python/sglang/srt/layers/attention/vision.py | 3 +- python/sglang/srt/layers/communicator.py | 71 +- .../sglang/srt/layers/communicator_dsa_cp.py | 26 +- python/sglang/srt/layers/communicator_mhc.py | 565 +++++ .../srt/layers/communicator_mhc_hybrid_cp.py | 222 ++ python/sglang/srt/layers/dcp/comm.py | 5 +- python/sglang/srt/layers/dp_attention.py | 19 + python/sglang/srt/layers/utils/cp_utils.py | 4 +- python/sglang/srt/managers/schedule_batch.py | 5 +- python/sglang/srt/managers/schedule_policy.py | 5 + python/sglang/srt/managers/scheduler.py | 38 +- .../sglang/srt/managers/tokenizer_manager.py | 86 +- python/sglang/srt/mem_cache/allocator/base.py | 6 +- .../sglang/srt/mem_cache/allocator/paged.py | 17 +- python/sglang/srt/mem_cache/allocator/swa.py | 17 +- .../sglang/srt/mem_cache/allocator/token.py | 17 +- .../srt/mem_cache/deepseek_v4_memory_pool.py | 6 +- .../srt/mem_cache/dsa_cache_layer_split.py | 31 +- .../srt/mem_cache/hisparse_memory_pool.py | 6 +- .../sglang/srt/mem_cache/kv_cache_builder.py | 25 +- .../srt/mem_cache/kv_cache_configurator.py | 127 +- python/sglang/srt/mem_cache/memory_pool.py | 579 +++++- python/sglang/srt/mem_cache/radix_cache.py | 41 +- .../sglang/srt/mem_cache/swa_memory_pool.py | 14 +- .../unified_cache/unified_tree_core.py | 13 +- .../srt/mem_cache/unified_memory_pool.py | 14 +- .../srt/model_executor/forward_batch_info.py | 21 + .../sglang/srt/model_executor/model_runner.py | 8 +- .../spec_aux_hidden_state.py | 68 +- .../srt/model_executor/pool_configurator.py | 111 +- .../srt/model_executor/runner/eager_runner.py | 8 +- .../runner/prefill_cuda_graph_runner.py | 19 +- .../breakable_cuda_graph.py | 12 +- python/sglang/srt/model_loader/loader.py | 6 +- .../sglang/srt/model_loader/weight_utils.py | 11 +- .../attention_backend_handler.py | 6 +- .../attention_forward_methods/forward_mha.py | 40 +- .../attention_forward_methods/forward_mla.py | 2 + .../deepseek_common/deepseek_weight_loader.py | 5 +- python/sglang/srt/models/deepseek_nextn.py | 15 +- python/sglang/srt/models/deepseek_v2.py | 19 +- python/sglang/srt/models/glm5_next.py | 1825 +++++++++++++++++ python/sglang/srt/models/glm5_next_nextn.py | 89 + python/sglang/srt/models/glm_ocr.py | 12 +- python/sglang/srt/multimodal/mm_utils.py | 68 + .../multimodal/processors/base_processor.py | 17 +- .../sglang/srt/multimodal/processors/glm4v.py | 489 ++++- .../srt/observability/metrics_collector.py | 8 + python/sglang/srt/parser/conversation.py | 18 +- .../sglang/srt/parser/jinja_template_utils.py | 83 +- python/sglang/srt/parser/template_manager.py | 14 +- python/sglang/srt/server_args.py | 24 +- .../srt/speculative/adaptive_spec_params.py | 2 +- .../eagle_draft_cuda_graph_runner.py | 2 +- .../eagle_draft_extend_cuda_graph_runner.py | 24 +- python/sglang/srt/speculative/eagle_utils.py | 43 +- .../srt/speculative/eagle_worker_common.py | 13 + .../sglang/srt/speculative/eagle_worker_v2.py | 111 +- python/sglang/srt/speculative/spec_utils.py | 125 +- .../srt/speculative/standalone_worker_v2.py | 1 + python/sglang/srt/utils/common.py | 51 +- .../srt/utils/hf_transformers/common.py | 4 + python/sglang/srt/utils/video_decoder.py | 43 +- test/registered/dcp/test_dcp_layout_unit.py | 24 + .../kernels/ops/attention/test_dsa_indexer.py | 2 + .../attention/test_fused_verify_triton_gdn.py | 37 +- .../ops/attention/test_silu_and_mul_clamp.py | 90 + .../ops/moe/test_minimax_quant_scatter.py | 39 + .../kernels/test_dsa_kpool_multi_pool.py | 213 ++ .../attention/test_dsa_multistep_dedup.py | 144 ++ .../unit/configs/test_glm5_next_config.py | 107 + .../test_decode_queue_cleanup.py | 64 + .../entrypoints/openai/test_serving_chat.py | 133 ++ test/registered/unit/layers/test_dcp_comm.py | 42 + .../test_scheduler_chunked_abort_race.py | 68 + .../test_tokenizer_manager_rid_cleanup.py | 151 +- .../mem_cache/test_retraction_mamba_backup.py | 6 +- .../test_spec_aux_hidden_state.py | 67 +- .../runner/test_eager_runner_dcp_metadata.py | 74 + .../model_executor/test_pool_configurator.py | 53 +- .../test_prefill_cuda_graph_runner.py | 34 + .../unit/models/test_glm5_next_dcp.py | 49 + .../test_glm5_next_nextn_weight_loading.py | 68 + .../unit/models/test_glm5_next_pp_metadata.py | 39 + .../models/test_nextn_hf_to_sglang_mapper.py | 73 + .../unit/models/test_nope_mha_k_cast.py | 52 + .../multimodal/test_alpha_channel_gating.py | 72 + .../unit/parser/test_jinja_template_utils.py | 29 + .../unit/server_args/test_server_args.py | 44 + .../spec/test_ngram_mamba_verify_update.py | 95 + .../spec/test_spec_cpu_overlap_constraint.py | 50 + .../registered/unit/test_dsa_trtllm_fp8_cp.py | 81 + 143 files changed, 16647 insertions(+), 835 deletions(-) create mode 100644 python/sglang/kernels/jit/csrc/dsa/kpool_topk_transform.cuh create mode 100644 python/sglang/kernels/ops/moe/kpool_topk_transform.py create mode 100644 python/sglang/srt/configs/glm5_next.py create mode 100644 python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py create mode 100644 python/sglang/srt/layers/attention/dsa/kpool_fp8_index.py create mode 100644 python/sglang/srt/layers/attention/dsa/kpool_plan.py create mode 100644 python/sglang/srt/layers/communicator_mhc.py create mode 100644 python/sglang/srt/layers/communicator_mhc_hybrid_cp.py create mode 100644 python/sglang/srt/models/glm5_next.py create mode 100644 python/sglang/srt/models/glm5_next_nextn.py create mode 100644 test/registered/kernels/ops/attention/test_silu_and_mul_clamp.py create mode 100644 test/registered/kernels/test_dsa_kpool_multi_pool.py create mode 100644 test/registered/unit/attention/test_dsa_multistep_dedup.py create mode 100644 test/registered/unit/configs/test_glm5_next_config.py create mode 100644 test/registered/unit/layers/test_dcp_comm.py create mode 100644 test/registered/unit/managers/test_scheduler_chunked_abort_race.py create mode 100644 test/registered/unit/model_executor/runner/test_eager_runner_dcp_metadata.py create mode 100644 test/registered/unit/models/test_glm5_next_dcp.py create mode 100644 test/registered/unit/models/test_glm5_next_nextn_weight_loading.py create mode 100644 test/registered/unit/models/test_glm5_next_pp_metadata.py create mode 100644 test/registered/unit/models/test_nextn_hf_to_sglang_mapper.py create mode 100644 test/registered/unit/models/test_nope_mha_k_cast.py create mode 100644 test/registered/unit/multimodal/test_alpha_channel_gating.py create mode 100644 test/registered/unit/test_dsa_trtllm_fp8_cp.py diff --git a/.gitignore b/.gitignore index cd1c6325d3559..777fbcff6019d 100644 --- a/.gitignore +++ b/.gitignore @@ -281,3 +281,4 @@ artifacts/ # Internal, non-published docs internal-docs/ +.trellis diff --git a/python/sglang/kernels/jit/csrc/deepseek_v4/silu_and_mul_masked_post_quant.cuh b/python/sglang/kernels/jit/csrc/deepseek_v4/silu_and_mul_masked_post_quant.cuh index f09f9adeed67d..fa85507826207 100644 --- a/python/sglang/kernels/jit/csrc/deepseek_v4/silu_and_mul_masked_post_quant.cuh +++ b/python/sglang/kernels/jit/csrc/deepseek_v4/silu_and_mul_masked_post_quant.cuh @@ -10,6 +10,7 @@ #include +#include #include #include #include @@ -208,8 +209,19 @@ struct SiluAndMulClampParams { const void* __restrict__ input; void* __restrict__ output; float swiglu_limit; + uint32_t out_vecs; + uint32_t blocks_per_row; }; +template +SGL_DEVICE bf16x2_t to_bf16x2(DType2 value) { + if constexpr (std::is_same_v) { + return value; + } else { + return device::cast(device::cast(value)); + } +} + template __global__ __launch_bounds__(1024, 2) void // maximize occupancy silu_mul_clamp_kernel(const SiluAndMulClampParams __grid_constant__ params) { @@ -219,21 +231,27 @@ __global__ __launch_bounds__(1024, 2) void // maximize occupancy constexpr auto kVecSize = 16 / sizeof(DType); static_assert(kVecSize % 2 == 0 && kVecSize > 0); using Vec = AlignedVector; - const auto bid = blockIdx.x; - const auto tile = tile::Memory::cta(); + const auto row = blockIdx.x / params.blocks_per_row; + const auto block_in_row = blockIdx.x % params.blocks_per_row; + const auto vec_id = block_in_row * blockDim.x + threadIdx.x; const float limit = params.swiglu_limit; PDLWaitPrimary(); - const auto gate = tile.load(params.input, bid * 2 + 0); - const auto up = tile.load(params.input, bid * 2 + 1); - Vec out; + if (vec_id < params.out_vecs) { + const auto input = static_cast(params.input); + auto output = static_cast(params.output); + const auto input_row = row * 2 * params.out_vecs; + const auto gate = input[input_row + vec_id]; + const auto up = input[input_row + params.out_vecs + vec_id]; + Vec out; #pragma unroll - for (uint32_t i = 0; i < kVecSize / 2; ++i) { - out[i] = cast(silu_and_mul(cast(gate[i]), cast(up[i]), limit)); - } + for (uint32_t i = 0; i < kVecSize / 2; ++i) { + out[i] = cast(silu_and_mul(to_bf16x2(gate[i]), to_bf16x2(up[i]), limit)); + } - tile.store(params.output, out, bid); + output[row * params.out_vecs + vec_id] = out; + } PDLTriggerSecondary(); } @@ -349,16 +367,20 @@ struct SiluAndMulClampKernel { constexpr uint32_t kVecSize = 16 / sizeof(DType); const auto out_dim = static_cast(H.unwrap()); const auto num_tokens = static_cast(M.unwrap()); + RuntimeCheck(out_dim > 0, "out_dim must be positive"); RuntimeCheck(out_dim % kVecSize == 0, "out_dim must be divisible by vector size"); - const auto num_threads = out_dim / kVecSize; - RuntimeCheck(num_threads <= 1024, "out_dim too large for single-block-per-row launch"); + const auto out_vecs = out_dim / kVecSize; + const auto num_threads = std::min(out_vecs, 1024u); + const auto blocks_per_row = host::div_ceil(out_vecs, num_threads); const auto params = SiluAndMulClampParams{ .input = input.data_ptr(), .output = output.data_ptr(), .swiglu_limit = static_cast(swiglu_limit), + .out_vecs = out_vecs, + .blocks_per_row = blocks_per_row, }; - LaunchKernel(num_tokens, num_threads, device.unwrap()) // + LaunchKernel(num_tokens * blocks_per_row, num_threads, device.unwrap()) // .enable_pdl(kUsePDL)(kernel, params); } }; diff --git a/python/sglang/kernels/jit/csrc/dsa/kpool_topk_transform.cuh b/python/sglang/kernels/jit/csrc/dsa/kpool_topk_transform.cuh new file mode 100644 index 0000000000000..2accb0f699628 --- /dev/null +++ b/python/sglang/kernels/jit/csrc/dsa/kpool_topk_transform.cuh @@ -0,0 +1,465 @@ +/** + * @NOTE: The radix top-k core (fast_topk_cuda_tl_impl) is adapted from + * https://github.com/tile-ai/tilelang/blob/main/examples/deepseek_v32/topk_selector.py + * and was previously shipped as an AOT sgl-kernel op (fast_kpool_topk_transform_fused). + * It is re-implemented here as a lightweight JIT kernel for the NSA kpool indexer: + * select pool groups at pool granularity, expand each group to `pool_size` token + * indices, and optionally transform those indices through a page table or ragged offset. + * + * The pool-level top-k value is a compile-time constant injected via -DSGL_GROUP_TOPK. + */ +#include // For TensorMatcher, SymbolicSize, SymbolicDevice, is_type +#include // For RuntimeCheck, RuntimeDeviceCheck + +#include // For LaunchKernel, type aliases + +#include +#include + +#include +#include +#include +#include + +namespace sglang { +namespace { + +#ifndef C10_LIKELY +#define C10_LIKELY(expr) (__builtin_expect(static_cast(expr), 1)) +#endif + +#ifndef SGL_GROUP_TOPK +#define SGL_GROUP_TOPK 256 +#endif + +// Compile-time pool-level top-k (number of groups selected per row). +inline constexpr int kGroupTopK = SGL_GROUP_TOPK; +inline constexpr int kThreadsPerBlock = 1024; + +// Reduced from 128KB to 32KB to improve occupancy. +// Each radix pass needs at most ~K candidates in the threshold bin, +// so 4K entries per round (2 rounds = 8K entries = 32KB) is sufficient. +inline constexpr std::size_t kSmem = 8 * 1024 * sizeof(uint32_t); // 32KB (bytes) + +struct FastTopKParams { + const float* __restrict__ input; // [B, input_stride] + const int32_t* __restrict__ row_starts; // [B] or nullptr + int32_t* __restrict__ indices; // unused here (kept for layout parity) + const int32_t* __restrict__ lengths; // [B] + int64_t input_stride; +}; + +__device__ __forceinline__ auto convert_to_uint8(float x) -> uint8_t { + __half h = __float2half_rn(x); + uint16_t bits = __half_as_ushort(h); + uint16_t key = (bits & 0x8000) ? static_cast(~bits) : static_cast(bits | 0x8000); + return static_cast(key >> 8); +} + +__device__ __forceinline__ auto convert_to_uint32(float x) -> uint32_t { + uint32_t bits = __float_as_uint(x); + return (bits & 0x80000000u) ? ~bits : (bits | 0x80000000u); +} + +template +__device__ void +fast_topk_cuda_tl_impl(const float* __restrict__ input, int* __restrict__ index, int row_start, int length) { + // An optimized topk kernel copied from tilelang kernel + // We assume length > K here, or it will crash + int topk = K; + constexpr auto BLOCK_SIZE = 1024; + constexpr auto RADIX = 256; + constexpr auto SMEM_INPUT_SIZE = kSmem / (2 * sizeof(int)); + + alignas(128) __shared__ int s_histogram_buf[2][RADIX + 128]; + alignas(128) __shared__ int s_counter; + alignas(128) __shared__ int s_threshold_bin_id; + alignas(128) __shared__ int s_num_input[2]; + + auto& s_histogram = s_histogram_buf[0]; + // allocate for two rounds + extern __shared__ int s_input_idx[][SMEM_INPUT_SIZE]; + + const int tx = threadIdx.x; + + // stage 1: 8bit coarse histogram + if (tx < RADIX + 1) s_histogram[tx] = 0; + __syncthreads(); + + for (int idx = tx; idx < length; idx += BLOCK_SIZE) { + const auto bin = convert_to_uint8(input[idx + row_start]); + ::atomicAdd(&s_histogram[bin], 1); + } + __syncthreads(); + + const auto run_cumsum = [&] { +#pragma unroll 8 + for (int i = 0; i < 8; ++i) { + static_assert(1 << 8 == RADIX); + if (C10_LIKELY(tx < RADIX)) { + const auto j = 1 << i; + const auto k = i & 1; + auto value = s_histogram_buf[k][tx]; + if (tx < RADIX - j) { + value += s_histogram_buf[k][tx + j]; + } + s_histogram_buf[k ^ 1][tx] = value; + } + __syncthreads(); + } + }; + + run_cumsum(); + if (tx < RADIX && s_histogram[tx] > topk && s_histogram[tx + 1] <= topk) { + s_threshold_bin_id = tx; + s_num_input[0] = 0; + s_counter = 0; + } + __syncthreads(); + + const auto threshold_bin = s_threshold_bin_id; + topk -= s_histogram[threshold_bin + 1]; + + if (topk == 0) { + for (int idx = tx; idx < length; idx += BLOCK_SIZE) { + const auto bin = static_cast(convert_to_uint8(input[idx + row_start])); + if (bin > threshold_bin) { + const auto pos = ::atomicAdd(&s_counter, 1); + index[pos] = idx; + } + } + __syncthreads(); + return; + } else { + __syncthreads(); + if (tx < RADIX + 1) { + s_histogram[tx] = 0; + } + __syncthreads(); + + for (int idx = tx; idx < length; idx += BLOCK_SIZE) { + const auto raw_input = input[idx + row_start]; + const auto bin = static_cast(convert_to_uint8(raw_input)); + if (bin > threshold_bin) { + const auto pos = ::atomicAdd(&s_counter, 1); + index[pos] = idx; + } else if (bin == threshold_bin) { + const auto pos = ::atomicAdd(&s_num_input[0], 1); + /// NOTE: (dark) fuse the histogram computation here + if (C10_LIKELY(pos < SMEM_INPUT_SIZE)) { + s_input_idx[0][pos] = idx; + const auto bin = convert_to_uint32(raw_input); + const auto sub_bin = (bin >> 24) & 0xFF; + ::atomicAdd(&s_histogram[sub_bin], 1); + } + } + } + __syncthreads(); + } + + // stage 2: refine with 8bit radix passes +#pragma unroll 4 + for (int round = 0; round < 4; ++round) { + __shared__ int s_last_remain; + const auto r_idx = round % 2; + + // clip here to prevent overflow + const auto _raw_num_input = s_num_input[r_idx]; + const auto num_input = (_raw_num_input < int(SMEM_INPUT_SIZE)) ? _raw_num_input : int(SMEM_INPUT_SIZE); + + run_cumsum(); + if (tx < RADIX && s_histogram[tx] > topk && s_histogram[tx + 1] <= topk) { + s_threshold_bin_id = tx; + s_num_input[r_idx ^ 1] = 0; + s_last_remain = topk - s_histogram[tx + 1]; + } + __syncthreads(); + + const auto threshold_bin = s_threshold_bin_id; + topk -= s_histogram[threshold_bin + 1]; + + if (topk == 0) { + for (int i = tx; i < num_input; i += BLOCK_SIZE) { + const auto idx = s_input_idx[r_idx][i]; + const auto offset = 24 - round * 8; + const auto bin = (convert_to_uint32(input[idx + row_start]) >> offset) & 0xFF; + if (bin > threshold_bin) { + const auto pos = ::atomicAdd(&s_counter, 1); + index[pos] = idx; + } + } + __syncthreads(); + break; + } else { + __syncthreads(); + if (tx < RADIX + 1) { + s_histogram[tx] = 0; + } + __syncthreads(); + for (int i = tx; i < num_input; i += BLOCK_SIZE) { + const auto idx = s_input_idx[r_idx][i]; + const auto raw_input = input[idx + row_start]; + const auto offset = 24 - round * 8; + const auto bin = (convert_to_uint32(raw_input) >> offset) & 0xFF; + if (bin > threshold_bin) { + const auto pos = ::atomicAdd(&s_counter, 1); + index[pos] = idx; + } else if (bin == threshold_bin) { + if (round == 3) { + const auto pos = ::atomicAdd(&s_last_remain, -1); + if (pos > 0) { + index[K - pos] = idx; + } + } else { + const auto pos = ::atomicAdd(&s_num_input[r_idx ^ 1], 1); + if (C10_LIKELY(pos < SMEM_INPUT_SIZE)) { + /// NOTE: (dark) fuse the histogram computation here + s_input_idx[r_idx ^ 1][pos] = idx; + const auto bin = convert_to_uint32(raw_input); + const auto sub_bin = (bin >> (offset - 8)) & 0xFF; + ::atomicAdd(&s_histogram[sub_bin], 1); + } + } + } + } + __syncthreads(); + } + } +} + +__device__ __forceinline__ int32_t transform_kpool_token( + int32_t raw_token, + const int32_t* __restrict__ page_table_entry, + const int32_t* __restrict__ topk_indices_offset, + int32_t offset) { + if (page_table_entry != nullptr) { + return page_table_entry[raw_token]; + } + if (topk_indices_offset != nullptr) { + return raw_token + offset; + } + return raw_token; +} + +template +__global__ __launch_bounds__(kThreadsPerBlock) void kpool_topk_transform_kernel( + const __grid_constant__ FastTopKParams params, + int32_t* __restrict__ dst_token_indices, + const int64_t dst_stride, + const int32_t pool_size, + const int32_t token_topk, + const int32_t out_cols, + const int32_t* __restrict__ page_table, + const int64_t page_table_stride, + const int32_t* __restrict__ page_table_row_index, + const int32_t* __restrict__ topk_indices_offset, + const int32_t* __restrict__ seq_lens) { + const auto& [input, row_starts, _, lengths, input_stride] = params; + const auto bid = static_cast(blockIdx.x); + const auto tid = threadIdx.x; + const auto row_start = row_starts == nullptr ? 0 : row_starts[bid]; + const auto length = lengths[bid]; + const auto score = input + bid * input_stride; + const auto dst = dst_token_indices + bid * dst_stride; + const auto page_table_row = page_table_row_index == nullptr ? bid : static_cast(page_table_row_index[bid]); + const auto page_table_entry = page_table == nullptr ? nullptr : page_table + page_table_row * page_table_stride; + const auto offset = topk_indices_offset == nullptr ? 0 : topk_indices_offset[bid]; + const bool append_tail = seq_lens != nullptr; + const auto full_pool_token_len = length * pool_size; + const auto history_len = full_pool_token_len < token_topk ? full_pool_token_len : token_topk; + const auto tail_count = append_tail ? seq_lens[bid] % pool_size : 0; + + if (length <= K) { + for (int col = tid; col < out_cols; col += kThreadsPerBlock) { + if (col < history_len) { + const auto group_rank = col / pool_size; + const auto slot = col % pool_size; + const auto raw_token = group_rank * pool_size + slot; + dst[col] = transform_kpool_token(raw_token, page_table_entry, topk_indices_offset, offset); + } else if (append_tail && col < history_len + tail_count) { + const auto raw_token = length * pool_size + (col - history_len); + dst[col] = transform_kpool_token(raw_token, page_table_entry, topk_indices_offset, offset); + } else { + dst[col] = -1; + } + } + return; + } + + __shared__ int s_indices[K]; + fast_topk_cuda_tl_impl(score, s_indices, row_start, length); + for (int col = tid; col < out_cols; col += kThreadsPerBlock) { + if (col < history_len) { + const auto group_rank = col / pool_size; + const auto group_id = s_indices[group_rank]; + const auto slot = col % pool_size; + const auto raw_token = group_id * pool_size + slot; + dst[col] = transform_kpool_token(raw_token, page_table_entry, topk_indices_offset, offset); + } else if (append_tail && col < history_len + tail_count) { + const auto raw_token = length * pool_size + (col - history_len); + dst[col] = transform_kpool_token(raw_token, page_table_entry, topk_indices_offset, offset); + } else { + dst[col] = -1; + } + } +} + +template +void setup_kernel_smem_once(host::DebugInfo where = {}) { + [[maybe_unused]] + static const auto result = [] { + const auto fptr = std::bit_cast(f); + return ::cudaFuncSetAttribute(fptr, ::cudaFuncAttributeMaxDynamicSharedMemorySize, kMaxDynamicSMEM); + }(); + host::RuntimeDeviceCheck(result, where); +} + +template +const T* optional_data_ptr(const tvm::ffi::Optional& opt) { + if (!opt.has_value()) { + return nullptr; + } + return static_cast(opt.value().data_ptr()); +} + +struct KpoolTopKTransformKernel { + static constexpr auto kernel = kpool_topk_transform_kernel; + + // Pool-level radix top-k for the NSA kpool indexer. + // score : [B, S] strided float32 scores (one score per pool group) + // lengths : [B] int32 valid group count per row + // dst_token_indices : [B, out_cols] int32 output token indices (contiguous) + // pool_size : tokens per pool group + // page_table (opt) : [B, P] strided int32 raw-token -> real-token map + // topk_indices_offset : [B] int32 per-row offset added to raw tokens (ragged) + // row_starts (opt) : [B] int32 score row start offsets + // seq_lens (opt) : [B] int32 sequence lengths; enables tail append + static void transform( + const tvm::ffi::TensorView score, + const tvm::ffi::TensorView lengths, + const tvm::ffi::TensorView dst_token_indices, + const int64_t pool_size, + const tvm::ffi::Optional page_table_opt, + const tvm::ffi::Optional topk_indices_offset_opt, + const tvm::ffi::Optional row_starts_opt, + const tvm::ffi::Optional seq_lens_opt, + const tvm::ffi::Optional page_table_row_index_opt) { + using namespace host; + + auto B = SymbolicSize{"batch_size"}; + auto S = SymbolicSize{"score_stride"}; + auto out_cols_sym = SymbolicSize{"out_cols"}; + auto device = SymbolicDevice{}; + device.set_options(); + + TensorMatcher({B, -1}) // strided scores + .with_strides({S, 1}) + .with_dtype() + .with_device(device) + .verify(score); + TensorMatcher({B}) // lengths, contiguous int32 + .with_dtype() + .with_device(device) + .verify(lengths); + TensorMatcher({B, out_cols_sym}) // output, contiguous int32 + .with_dtype() + .with_device(device) + .verify(dst_token_indices); + + RuntimeCheck(pool_size > 1, "pool_size must be > 1, got ", pool_size); + RuntimeCheck( + !(page_table_opt.has_value() && topk_indices_offset_opt.has_value()), + "page_table and topk_indices_offset are mutually exclusive"); + RuntimeCheck( + !page_table_row_index_opt.has_value() || page_table_opt.has_value(), + "page_table_row_index requires page_table"); + + const auto out_cols = static_cast(out_cols_sym.unwrap()); + const auto tail_cols = seq_lens_opt.has_value() ? static_cast(pool_size) - 1 : 0; + RuntimeCheck(out_cols > tail_cols, "dst_token_indices columns ", out_cols, " must exceed tail ", tail_cols); + const auto token_topk = out_cols - tail_cols; + RuntimeCheck(token_topk % static_cast(pool_size) == 0, "token_topk must be a multiple of pool_size"); + RuntimeCheck( + token_topk / static_cast(pool_size) == kGroupTopK, + "this module is built for group_topk=", + kGroupTopK, + " but got ", + token_topk / static_cast(pool_size)); + + const auto batch_size = static_cast(B.unwrap()); + + int64_t page_table_stride = 0; + const int32_t* page_table_ptr = nullptr; + if (page_table_opt.has_value()) { + auto P = SymbolicSize{"page_table_stride"}; + if (page_table_row_index_opt.has_value()) { + auto page_table_rows = SymbolicSize{"page_table_rows"}; + TensorMatcher({page_table_rows, -1}) // compact shared page table + .with_strides({P, 1}) + .with_dtype() + .with_device(device) + .verify(page_table_opt.value()); + } else { + TensorMatcher({B, -1}) // one page-table row per score row + .with_strides({P, 1}) + .with_dtype() + .with_device(device) + .verify(page_table_opt.value()); + } + page_table_ptr = static_cast(page_table_opt.value().data_ptr()); + page_table_stride = static_cast(P.unwrap()); + } + + if (topk_indices_offset_opt.has_value()) { + TensorMatcher({B}) // + .with_dtype() + .with_device(device) + .verify(topk_indices_offset_opt.value()); + } + if (row_starts_opt.has_value()) { + TensorMatcher({B}) // + .with_dtype() + .with_device(device) + .verify(row_starts_opt.value()); + } + if (seq_lens_opt.has_value()) { + TensorMatcher({B}) // + .with_dtype() + .with_device(device) + .verify(seq_lens_opt.value()); + } + if (page_table_row_index_opt.has_value()) { + TensorMatcher({B}) // + .with_dtype() + .with_device(device) + .verify(page_table_row_index_opt.value()); + } + + const auto params = FastTopKParams{ + .input = static_cast(score.data_ptr()), + .row_starts = optional_data_ptr(row_starts_opt), + .indices = nullptr, + .lengths = static_cast(lengths.data_ptr()), + .input_stride = static_cast(S.unwrap()), + }; + + setup_kernel_smem_once(); + LaunchKernel(batch_size, kThreadsPerBlock, device.unwrap(), kSmem)( + kernel, + params, + static_cast(dst_token_indices.data_ptr()), + static_cast(dst_token_indices.strides()[0]), + static_cast(pool_size), + token_topk, + out_cols, + page_table_ptr, + page_table_stride, + optional_data_ptr(page_table_row_index_opt), + optional_data_ptr(topk_indices_offset_opt), + optional_data_ptr(seq_lens_opt)); + } +}; + +} // namespace + +} // namespace sglang diff --git a/python/sglang/kernels/ops/attention/__init__.py b/python/sglang/kernels/ops/attention/__init__.py index 4030ea3bcb709..f40c07bb734c5 100644 --- a/python/sglang/kernels/ops/attention/__init__.py +++ b/python/sglang/kernels/ops/attention/__init__.py @@ -94,6 +94,7 @@ ("dsa.triton_sparse_mla", "triton_sparse_mla_fwd"), ("dsa.transform_index", "transform_index_page_table_prefill"), ("dsa.transform_index", "transform_index_page_table_decode"), + ("dsa.transform_index", "prepare_trtllm_nope_sparse_metadata"), ("dsa.cp_split", "dsa_cp_round_robin_split_q_seqs_kernel"), ("dsv4.fp4_indexer", "quantize_fp4_indexer_tensor"), ("dsv4.fp4_indexer", "store_fp4_index_k_cache"), diff --git a/python/sglang/kernels/ops/attention/dsa/quant_k_cache.py b/python/sglang/kernels/ops/attention/dsa/quant_k_cache.py index 5454071b897d3..d7b1e5a50cb96 100644 --- a/python/sglang/kernels/ops/attention/dsa/quant_k_cache.py +++ b/python/sglang/kernels/ops/attention/dsa/quant_k_cache.py @@ -3,6 +3,57 @@ import triton.language as tl +def gather_dsa_kv_scales( + scale_src, + scale_dst, + kv_indices, + kv_indptr, + kv_indptr_idx, +): + _gather_dsa_kv_scales[(32,)]( + scale_src, + scale_dst, + kv_indices, + kv_indptr, + scale_src.stride(0), + KV_INDPTR_IDX=kv_indptr_idx, + NUM_TILES=scale_src.shape[-1], + BLOCK=256, + ) + + +@triton.jit +def _gather_dsa_kv_scales( + scale_src, + scale_dst, + kv_indices, + kv_indptr, + scale_src_stride, + KV_INDPTR_IDX: tl.constexpr, + NUM_TILES: tl.constexpr, + BLOCK: tl.constexpr, +): + pid = tl.program_id(0) + num_programs = tl.num_programs(0) + active = tl.load(kv_indptr + KV_INDPTR_IDX) + block_start = pid * BLOCK + tiles = tl.arange(0, NUM_TILES) + while block_start < active: + offsets = block_start + tl.arange(0, BLOCK) + mask = offsets < active + rows = tl.load(kv_indices + offsets, mask=mask, other=0) + values = tl.load( + scale_src + rows[:, None] * scale_src_stride + tiles[None, :], + mask=mask[:, None], + ) + tl.store( + scale_dst + rows[:, None] * NUM_TILES + tiles[None, :], + values, + mask=mask[:, None], + ) + block_start += num_programs * BLOCK + + def quantize_k_cache(cache_k): return _quantize_k_cache_fast_wrapped(cache_k) @@ -22,19 +73,27 @@ def quantize_k_cache_separate( k_nope: (num_tokens, dim_nope) or (num_tokens, 1, dim_nope) Must have dim_nope=512 for FP8 MLA quantization k_rope: (num_tokens, dim_rope) or (num_tokens, 1, dim_rope) - Must have dim_rope=64 for FP8 MLA quantization + Must have dim_rope=64 for FP8 MLA quantization, or dim_rope=0 + for no-PE MLA (empty rope); None is treated + the same as an empty rope. tile_size: quantization tile size (default 128) Returns: Tuple of (nope_part, rope_part) where: - nope_part: (num_tokens, 1, 528) as uint8 view, contains [nope_fp8(512) | scales(16)] - rope_part: (num_tokens, 1, 128) as uint8 view, contains [rope_bf16_bytes(128)] + (empty, (num_tokens, 1, 0), when dim_rope=0) These two tensors can be directly passed to set_mla_kv_buffer_triton(kv_buffer, loc, nope_part, rope_part) """ # Squeeze middle dimension if present k_nope_2d = k_nope.squeeze(1) if k_nope.ndim == 3 else k_nope - k_rope_2d = k_rope.squeeze(1) if k_rope.ndim == 3 else k_rope + if k_rope is None or k_rope.numel() == 0: + k_rope_2d = torch.empty( + (k_nope_2d.shape[0], 0), dtype=k_nope_2d.dtype, device=k_nope_2d.device + ) + else: + k_rope_2d = k_rope.squeeze(1) if k_rope.ndim == 3 else k_rope num_tokens = k_nope_2d.shape[0] dim_nope = k_nope_2d.shape[1] @@ -43,8 +102,8 @@ def quantize_k_cache_separate( # Validate dimensions for FP8 MLA if dim_nope != 512: raise ValueError(f"Expected dim_nope=512 for FP8 MLA, got {dim_nope}") - if dim_rope != 64: - raise ValueError(f"Expected dim_rope=64 for FP8 MLA, got {dim_rope}") + if dim_rope not in (0, 64): + raise ValueError(f"Expected dim_rope=64 (or 0 for no-PE MLA), got {dim_rope}") if k_rope_2d.shape[0] != num_tokens: raise ValueError( f"k_nope and k_rope must have same num_tokens, got {num_tokens} vs {k_rope_2d.shape[0]}" @@ -234,7 +293,12 @@ def _quantize_k_cache_fast_separate(k_nope, k_rope, group_size: int = 128): # Fixed byte layout for rope_part: [rope_bf16 (dim_rope*2 bytes)] nope_q_view = nope_part_u8[:, :dim_nope].view(torch.float8_e4m3fn) nope_s_view = nope_part_u8[:, dim_nope:].view(torch.float32) - rope_view = rope_part_u8.view(torch.bfloat16) + if dim_rope > 0: + rope_view = rope_part_u8.view(torch.bfloat16) + else: + rope_view = torch.empty( + (num_tokens, 0), dtype=torch.bfloat16, device=k_rope.device + ) # Kernel launch parameters num_blocks_per_token = triton.cdiv(dim_nope + dim_rope, group_size) @@ -283,7 +347,7 @@ def _quantize_k_cache_fast_kernel( FP8_MIN: tl.constexpr, FP8_MAX: tl.constexpr, ): - token_id = tl.program_id(0) + token_id = tl.program_id(0).to(tl.int64) raw_block_id = tl.program_id(1) if raw_block_id < NUM_NOPE_BLOCKS: diff --git a/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py b/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py index d2dc851325e1c..4bd96eecccac7 100644 --- a/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py +++ b/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py @@ -272,12 +272,13 @@ def sparse_attention_fwd_kernel_v1( num_stages=2, threads=256, ): - assert dim == tilelang.math.next_power_of_2( - dim - ), f"haven't check padding correctness yet, dim={dim}" - assert tail_dim == tilelang.math.next_power_of_2( + assert ( + dim == tilelang.math.next_power_of_2(dim) or dim % 64 == 0 + ), f"dim={dim} must be a power of 2 or a multiple of 64" + assert tail_dim == 0 or tail_dim == tilelang.math.next_power_of_2( tail_dim - ), f"haven't check padding correctness yet, dim={tail_dim}" + ), f"tail_dim={tail_dim} must be 0 or a power of 2" + has_tail = tail_dim > 0 assert is_causal == True, "non-casual is not supported" assert ( topk % block_I == 0 @@ -330,9 +331,11 @@ def main( bz, ): Q_shared = T.alloc_shared([H_per_block, D], dtype) - Q_tail_shared = T.alloc_shared([H_per_block, D_tail], dtype) + if has_tail: + Q_tail_shared = T.alloc_shared([H_per_block, D_tail], dtype) KV_shared = T.alloc_shared([BI, D], dtype) - K_tail_shared = T.alloc_shared([BI, D_tail], dtype) + if has_tail: + K_tail_shared = T.alloc_shared([BI, D_tail], dtype) O_shared = T.alloc_shared([H_per_block, D], dtype) mask = T.alloc_fragment([BI], "bool") @@ -358,7 +361,8 @@ def main( H1 = H0 + H_per_block T.copy(Q[b_i, s_i, H0:H1, :D], Q_shared) - T.copy(Q[b_i, s_i, H0:H1, D:], Q_tail_shared) + if has_tail: + T.copy(Q[b_i, s_i, H0:H1, D:], Q_tail_shared) for i_i in T.Pipelined(NI, num_stages=num_stages): @@ -369,10 +373,14 @@ def main( KV_shared[bi_i, d_i] = KV[ b_i, Indices[b_i, s_i, g_i, i_i * BI + bi_i], g_i, d_i ] - for bi_i, d_i in T.Parallel(BI, D_tail): - K_tail_shared[bi_i, d_i] = KV[ - b_i, Indices[b_i, s_i, g_i, i_i * BI + bi_i], g_i, D + d_i - ] + if has_tail: + for bi_i, d_i in T.Parallel(BI, D_tail): + K_tail_shared[bi_i, d_i] = KV[ + b_i, + Indices[b_i, s_i, g_i, i_i * BI + bi_i], + g_i, + D + d_i, + ] for h_i, bi_i in T.Parallel(H_per_block, BI): acc_s[h_i, bi_i] = T.if_then_else( @@ -385,13 +393,14 @@ def main( transpose_B=True, policy=T.GemmWarpPolicy.FullCol, ) - T.gemm( - Q_tail_shared, - K_tail_shared, - acc_s, - transpose_B=True, - policy=T.GemmWarpPolicy.FullCol, - ) + if has_tail: + T.gemm( + Q_tail_shared, + K_tail_shared, + acc_s, + transpose_B=True, + policy=T.GemmWarpPolicy.FullCol, + ) T.copy(m_i, m_i_prev) T.reduce_max(acc_s, m_i, dim=1, clear=False) for h_i in T.Parallel(H_per_block): @@ -1326,7 +1335,7 @@ def tilelang_sparse_fwd( dim = q.shape[2] tail_dim = dim - d_v topk = indices.shape[-1] - assert topk == 2048 + assert topk % 64 == 0, "topk must be padded to a multiple of 64" if _is_hip: is_fp8_kv = kv.dtype in (torch.float8_e4m3fn, torch.float8_e4m3fnuz) @@ -1380,9 +1389,12 @@ def tilelang_sparse_fwd( ) out = kernel_combine(partial_o_batched, partial_lse_batched) else: - kernel = sparse_attention_fwd_kernel_v2( - num_heads, d_v, tail_dim, topk, sm_scale=sm_scale + kernel_factory = ( + sparse_attention_fwd_kernel_v1 + if tail_dim == 0 + else sparse_attention_fwd_kernel_v2 ) + kernel = kernel_factory(num_heads, d_v, tail_dim, topk, sm_scale=sm_scale) out = kernel(q.unsqueeze(0), kv.unsqueeze(0), indices.unsqueeze(0)) # type: ignore return out diff --git a/python/sglang/kernels/ops/attention/dsa/transform_index.py b/python/sglang/kernels/ops/attention/dsa/transform_index.py index 2d7dd105e1876..8fbfa190f5b97 100644 --- a/python/sglang/kernels/ops/attention/dsa/transform_index.py +++ b/python/sglang/kernels/ops/attention/dsa/transform_index.py @@ -14,6 +14,58 @@ def transform_index_page_table_decode(**kwargs): return transform_index_page_table_decode_fast(**kwargs) +@triton.jit +def prepare_trtllm_nope_sparse_metadata_kernel( + page_table_ptr: torch.Tensor, + topk_lens_ptr: torch.Tensor, + row_stride: tl.constexpr, + TOPK: tl.constexpr, + BLOCK_TOPK: tl.constexpr, +): + row = tl.program_id(0) + offsets = tl.arange(0, BLOCK_TOPK) + valid = offsets < TOPK + indices = tl.load( + page_table_ptr + row * row_stride + offsets, + mask=valid, + other=-1, + ) + topk_len = tl.sum((valid & (indices >= 0)).to(tl.int32), axis=0) + + # TRTLLM-GEN's native H512 dynamic sparse kernel produces NaNs for an + # empty row. CUDA-graph padding rows are never consumed, so point them at + # a valid dummy token and run a one-element attention instead. + is_empty = topk_len == 0 + tl.store(page_table_ptr + row * row_stride, 0, mask=is_empty) + tl.store(topk_lens_ptr + row, tl.maximum(topk_len, 1)) + + +def prepare_trtllm_nope_sparse_metadata( + page_table: torch.Tensor, +) -> torch.Tensor: + """Build per-query active top-k lengths for native H512 TRTLLM-GEN MLA. + + ``page_table`` must contain packed valid token locations followed by ``-1`` + padding. The tensor is only modified for fully empty CUDA-graph padding + rows, whose first entry is replaced with the valid dummy token location 0. + """ + assert page_table.ndim == 2 + assert page_table.dtype == torch.int32 + assert page_table.is_contiguous() + num_rows, topk = page_table.shape + topk_lens = torch.empty(num_rows, dtype=torch.int32, device=page_table.device) + block_topk = triton.next_power_of_2(topk) + prepare_trtllm_nope_sparse_metadata_kernel[(num_rows,)]( + page_table, + topk_lens, + page_table.stride(0), + TOPK=topk, + BLOCK_TOPK=block_topk, + num_warps=8, + ) + return topk_lens + + def _allocate_prefill_result( topk_indices: torch.Tensor, real_num_tokens: int, diff --git a/python/sglang/kernels/ops/attention/dsa_metadata.py b/python/sglang/kernels/ops/attention/dsa_metadata.py index 21a1fedb44ecd..cc79645d70e1d 100644 --- a/python/sglang/kernels/ops/attention/dsa_metadata.py +++ b/python/sglang/kernels/ops/attention/dsa_metadata.py @@ -4,12 +4,35 @@ import triton import triton.language as tl +# Target page-table tile-program count per launch for the bounded column scan +# below. Enough programs to saturate a datacenter GPU for this copy kernel, +# while the dispatch cost of a full grid of idle programs stays at a few +# microseconds. +_TILE_PROGRAM_TARGET = 8192 + + +def _bounded_scan_num_splits(rows: int, num_col_blocks: int) -> int: + """Column-split factor for the bounded page-table scan. + + Each of ``rows`` output rows gets this many tile programs; program ``s`` + of a row covers column blocks ``s, s + splits, s + 2*splits, ...`` up to + the row's own kv length, which the kernel reads at run time. The grid is + therefore data-independent (CUDA-graph-safe by construction) while the + traversal is bounded by the live data: dispatch scales with + ``rows * splits`` instead of ``rows * table_width / BLOCK_N``. The factor + never exceeds the full-width column-block count, so the grid is never + larger than the full-width scan's. + """ + assert rows > 0 + return max(1, min(num_col_blocks, _TILE_PROGRAM_TARGET // rows)) + @triton.jit( do_not_specialize=[ "page_table_stride_0", "real_page_table_stride_0", "max_len", + "num_splits", ] ) def _fused_dsa_decode_metadata_kernel( @@ -32,7 +55,9 @@ def _fused_dsa_decode_metadata_kernel( real_page_table_stride_1: tl.constexpr, bs: tl.constexpr, max_len, + num_splits, dsa_index_topk: tl.constexpr, + index_kpool: tl.constexpr, real_page_size: tl.constexpr, HAS_REAL_PAGE_TABLE: tl.constexpr, HAS_PAGE_TABLE_1: tl.constexpr, @@ -46,7 +71,17 @@ def _fused_dsa_decode_metadata_kernel( mask_b = offs_b < bs seq = tl.load(seq_lens + offs_b * seq_lens_stride, mask=mask_b, other=0) seq_i32 = seq.to(tl.int32) - dsa_seq = tl.minimum(seq_i32, dsa_index_topk) + if index_kpool <= 1: + dsa_seq = tl.minimum(seq_i32, dsa_index_topk) + else: + # Match compute_dsa_seqlens exactly (same formula as the + # target-verify kernel below): select complete history pools up + # to top-k, then retain the partial trailing pool. In + # particular, topk+pool-1 -> topk+pool-1 while topk+pool -> topk. + full_pool_tokens = (seq_i32 // index_kpool) * index_kpool + selected_history_tokens = tl.minimum(full_pool_tokens, dsa_index_topk) + tail_tokens = seq_i32 - full_pool_tokens + dsa_seq = selected_history_tokens + tail_tokens cu = tl.cumsum(seq_i32, 0) dsa_cu = tl.cumsum(dsa_seq, 0) @@ -59,52 +94,69 @@ def _fused_dsa_decode_metadata_kernel( tl.store(dsa_cu_seqlens_k + 1 + offs_b, dsa_cu, mask=mask_b) return - num_col_blocks = tl.cdiv(max_len, BLOCK_N) page_pid = pid - 1 - row = page_pid // num_col_blocks - col_block = page_pid - row * num_col_blocks - offs_n = col_block * BLOCK_N + tl.arange(0, BLOCK_N) - mask = (row < bs) & (offs_n < max_len) + row = page_pid // num_splits + split_id = page_pid - row * num_splits req_idx = tl.load( req_pool_indices + row * req_pool_indices_stride, mask=row < bs, other=0, ) - # Skip column blocks past the request's kv length: no consumer reads there - # (attention and the indexer both stay within cache_seqlens). Loaded after - # req_idx so the two scalar loads pipeline (no added latency when live). kv_len = tl.load( seq_lens + row * seq_lens_stride, mask=row < bs, other=0, ).to(tl.int32) - if col_block * BLOCK_N >= kv_len: - return - vals = tl.load( - req_to_token + req_idx * req_to_token_stride_0 + offs_n * req_to_token_stride_1, - mask=mask, - other=0, - ).to(tl.int32) - # Write the wide page_size=1 table only when the caller provides it; the - # fused decode CUDA graph drops it and consumes real_page_table alone. - if HAS_PAGE_TABLE_1: - tl.store( - page_table_1 + row * page_table_stride_0 + offs_n * page_table_stride_1, - vals, + # Same int64 row-term promotion as the target-verify and draft-extend + # kernels below: the wide table's row stride is ~max_context_len (2^20 + + # headroom on 1M-context models), so the int32 product row * stride wraps + # negative once row reaches 2^31 / stride (~2048). Decode rows equal the + # batch size, so today's graph buckets stay below the wrap, but the store + # math should not depend on that. + row_i64 = row.to(tl.int64) + # Bounded traversal: scan only up to this row's kv length, read here at + # run (replay) time. Column blocks past kv_len hold no consumer-visible + # data (attention and the indexer both stay within cache_seqlens), so the + # write set is identical to a full-width scan that early-exits dead + # blocks; what changes is that those blocks are never dispatched. + num_live_blocks = tl.minimum(tl.cdiv(kv_len, BLOCK_N), tl.cdiv(max_len, BLOCK_N)) + # num_stages: this dot-free copy loop is not software-pipelined by + # default, which would leave one load in flight per warp and make + # multi-iteration rows (long contexts at high row counts) latency-bound; + # explicit staging turns the loads into multi-buffered async copies. + for col_block in tl.range(split_id, num_live_blocks, num_splits, num_stages=3): + offs_n = col_block * BLOCK_N + tl.arange(0, BLOCK_N) + mask = (row < bs) & (offs_n < max_len) + vals = tl.load( + req_to_token + + req_idx * req_to_token_stride_0 + + offs_n * req_to_token_stride_1, mask=mask, - ) + other=0, + ).to(tl.int32) + # Write the wide page_size=1 table only when the caller provides it; + # the fused decode CUDA graph drops it and consumes real_page_table + # alone. + if HAS_PAGE_TABLE_1: + tl.store( + page_table_1 + + row_i64 * page_table_stride_0 + + offs_n * page_table_stride_1, + vals, + mask=mask, + ) - if HAS_REAL_PAGE_TABLE: - real_mask = mask & ((offs_n % real_page_size) == 0) - real_cols = offs_n // real_page_size - tl.store( - real_page_table - + row * real_page_table_stride_0 - + real_cols * real_page_table_stride_1, - vals // real_page_size, - mask=real_mask, - ) + if HAS_REAL_PAGE_TABLE: + real_mask = mask & ((offs_n % real_page_size) == 0) + real_cols = offs_n // real_page_size + tl.store( + real_page_table + + row_i64 * real_page_table_stride_0 + + real_cols * real_page_table_stride_1, + vals // real_page_size, + mask=real_mask, + ) def fused_dsa_decode_metadata( @@ -121,6 +173,7 @@ def fused_dsa_decode_metadata( max_len: int, dsa_index_topk: int, real_page_size: int, + index_kpool: int = 1, ) -> None: """Fill decode-graph DSA metadata (seqlens + page tables) from req_to_token. @@ -134,6 +187,11 @@ def fused_dsa_decode_metadata( Contract: each page-table row is written only over its live prefix ([:cache_seqlens]); the tail keeps stale values across CUDA-graph replays, so consumers must bound reads by cache_seqlens. + + The column scan is bounded inside the kernel by each row's own kv length + (read at run time), so the cost scales with the live sequence lengths and + not with ``max_len`` (the table width); the grid itself stays + data-independent. See :func:`_bounded_scan_num_splits`. """ assert seq_lens.is_cuda assert req_pool_indices.is_cuda @@ -147,6 +205,7 @@ def fused_dsa_decode_metadata( cu_seqlens_k[:1].zero_() dsa_cu_seqlens_k[:1].zero_() return + assert index_kpool > 0 has_real_page_table = real_page_size > 1 if has_real_page_table: @@ -169,7 +228,8 @@ def fused_dsa_decode_metadata( block_bs = triton.next_power_of_2(bs) block_n = 128 num_col_blocks = triton.cdiv(max_len, block_n) - grid = (1 + bs * num_col_blocks,) + num_splits = _bounded_scan_num_splits(bs, num_col_blocks) + grid = (1 + bs * num_splits,) _fused_dsa_decode_metadata_kernel[grid]( seq_lens, @@ -191,7 +251,9 @@ def fused_dsa_decode_metadata( real_page_table.stride(1) if has_real_page_table else 0, bs, max_len, + num_splits, dsa_index_topk, + index_kpool, real_page_size, has_real_page_table, has_page_table_1, @@ -205,6 +267,7 @@ def fused_dsa_decode_metadata( "page_table_stride_0", "real_page_table_stride_0", "max_seqlen_k", + "num_splits", ] ) def _fused_dsa_target_verify_metadata_kernel( @@ -231,7 +294,9 @@ def _fused_dsa_target_verify_metadata_kernel( paged_mqa_ctx_lens_stride_1: tl.constexpr, bs: tl.constexpr, max_seqlen_k, + num_splits, dsa_index_topk: tl.constexpr, + index_kpool: tl.constexpr, real_page_size: tl.constexpr, next_n: tl.constexpr, HAS_REAL_PAGE_TABLE: tl.constexpr, @@ -266,7 +331,16 @@ def _fused_dsa_target_verify_metadata_kernel( ).to(tl.int32) expanded_seq = base_seq + draft_off + 1 expanded_seq = tl.where(mask_e, expanded_seq, 0) - dsa_seq = tl.minimum(expanded_seq, dsa_index_topk) + if index_kpool <= 1: + dsa_seq = tl.minimum(expanded_seq, dsa_index_topk) + else: + # Match compute_dsa_seqlens exactly: select complete history pools + # up to top-k, then retain the partial trailing pool. In + # particular, topk+pool-1 -> topk+pool-1 while topk+pool -> topk. + full_pool_tokens = (expanded_seq // index_kpool) * index_kpool + selected_history_tokens = tl.minimum(full_pool_tokens, dsa_index_topk) + tail_tokens = expanded_seq - full_pool_tokens + dsa_seq = selected_history_tokens + tail_tokens dsa_cu = tl.cumsum(dsa_seq, 0) tl.store(seqlens_expanded + offs_e, expanded_seq, mask=mask_e) @@ -284,12 +358,9 @@ def _fused_dsa_target_verify_metadata_kernel( ) return - num_col_blocks = tl.cdiv(max_seqlen_k, BLOCK_N) page_pid = pid - 1 - out_row = page_pid // num_col_blocks - col_block = page_pid - out_row * num_col_blocks - offs_n = col_block * BLOCK_N + tl.arange(0, BLOCK_N) - mask = (out_row < expanded_size) & (offs_n < max_seqlen_k) + out_row = page_pid // num_splits + split_id = page_pid - out_row * num_splits req_row = out_row // next_n req_idx = tl.load( @@ -297,10 +368,6 @@ def _fused_dsa_target_verify_metadata_kernel( mask=out_row < expanded_size, other=0, ) - # Skip column blocks past the request's kv length (seq_len + next_n): no - # consumer reads there (attention and the indexer stay within cache_seqlens). - # Loaded after req_idx so the two scalar loads pipeline (no added latency - # when live). kv_len = ( tl.load( seq_lens + req_row * seq_lens_stride, @@ -309,35 +376,58 @@ def _fused_dsa_target_verify_metadata_kernel( ).to(tl.int32) + next_n ) - if col_block * BLOCK_N >= kv_len: - return - vals = tl.load( - req_to_token + req_idx * req_to_token_stride_0 + offs_n * req_to_token_stride_1, - mask=mask, - other=0, - ).to(tl.int32) - # Write the wide page_size=1 table only when the caller provides it (see - # fused_dsa_decode_metadata for the optional-page_table_1 contract). - if HAS_PAGE_TABLE_1: - tl.store( - page_table_1 + out_row * page_table_stride_0 + offs_n * page_table_stride_1, - vals, + # Promote the row term to int64 before the pointer add: the wide table's + # row stride is ~max_context_len (2^20 + headroom for 1M-context models), + # so the int32 product out_row * stride wraps negative from + # out_row == 2048 (expanded rows = bs * next_n > 2048), sending the + # stores below wild. The column term stays int32 (bounded by the row + # stride itself). + out_row_i64 = out_row.to(tl.int64) + # Bounded traversal: scan only up to this row's kv length + # (seq_len + next_n), read here at run (replay) time. Column blocks past + # kv_len hold no consumer-visible data (attention and the indexer stay + # within cache_seqlens), so the write set is identical to a full-width + # scan that early-exits dead blocks; what changes is that those blocks + # are never dispatched. + num_live_blocks = tl.minimum( + tl.cdiv(kv_len, BLOCK_N), tl.cdiv(max_seqlen_k, BLOCK_N) + ) + # num_stages: see the decode kernel above. + for col_block in tl.range(split_id, num_live_blocks, num_splits, num_stages=3): + offs_n = col_block * BLOCK_N + tl.arange(0, BLOCK_N) + mask = (out_row < expanded_size) & (offs_n < max_seqlen_k) + vals = tl.load( + req_to_token + + req_idx * req_to_token_stride_0 + + offs_n * req_to_token_stride_1, mask=mask, - ) + other=0, + ).to(tl.int32) + # Write the wide page_size=1 table only when the caller provides it + # (see fused_dsa_decode_metadata for the optional-page_table_1 + # contract). + if HAS_PAGE_TABLE_1: + tl.store( + page_table_1 + + out_row_i64 * page_table_stride_0 + + offs_n * page_table_stride_1, + vals, + mask=mask, + ) - if HAS_REAL_PAGE_TABLE: - real_mask = mask & ((offs_n % real_page_size) == 0) - real_cols = offs_n // real_page_size - tl.store( - real_page_table - + out_row * real_page_table_stride_0 - + real_cols * real_page_table_stride_1, - vals // real_page_size, - mask=real_mask, - ) + if HAS_REAL_PAGE_TABLE: + real_mask = mask & ((offs_n % real_page_size) == 0) + real_cols = offs_n // real_page_size + tl.store( + real_page_table + + out_row_i64 * real_page_table_stride_0 + + real_cols * real_page_table_stride_1, + vals // real_page_size, + mask=real_mask, + ) -def fused_dsa_target_verify_metadata( +def _prep_fused_dsa_target_verify_metadata_launch( seq_lens: torch.Tensor, req_pool_indices: torch.Tensor, req_to_token: torch.Tensor, @@ -354,7 +444,11 @@ def fused_dsa_target_verify_metadata( real_page_size: int, next_n: int, paged_mqa_ctx_lens_2d: torch.Tensor = None, -) -> None: + index_kpool: int = 1, +): + """Validate and build the (grid, args, constexpr kwargs) launch spec for + the target-verify metadata kernel (bs > 0). Shared between the per-call + wrapper below and the prebound cuda-graph replay launcher.""" assert seq_lens.is_cuda assert req_pool_indices.is_cuda assert req_to_token.is_cuda @@ -364,11 +458,9 @@ def fused_dsa_target_verify_metadata( assert dsa_cache_seqlens.is_cuda assert dsa_cu_seqlens_k.is_cuda - if bs == 0: - cu_seqlens_k[:1].zero_() - dsa_cu_seqlens_k[:1].zero_() - return + assert bs > 0 assert next_n > 0 + assert index_kpool > 0 has_real_page_table = real_page_size > 1 if has_real_page_table: @@ -402,9 +494,10 @@ def fused_dsa_target_verify_metadata( block_expanded = triton.next_power_of_2(expanded_size) block_n = 128 num_col_blocks = triton.cdiv(max_seqlen_k, block_n) - grid = (1 + expanded_size * num_col_blocks,) + num_splits = _bounded_scan_num_splits(expanded_size, num_col_blocks) + grid = (1 + expanded_size * num_splits,) - _fused_dsa_target_verify_metadata_kernel[grid]( + args = ( seq_lens, req_pool_indices, req_to_token, @@ -428,16 +521,69 @@ def fused_dsa_target_verify_metadata( paged_mqa_ctx_lens_2d.stride(1) if has_paged_mqa_ctx_lens else 0, bs, max_seqlen_k, + num_splits, dsa_index_topk, + index_kpool, real_page_size, next_n, has_real_page_table, has_paged_mqa_ctx_lens, has_page_table_1, + ) + constexprs = dict( BLOCK_BS=block_bs, BLOCK_EXPANDED=block_expanded, BLOCK_N=block_n, ) + return grid, args, constexprs + + +def fused_dsa_target_verify_metadata( + seq_lens: torch.Tensor, + req_pool_indices: torch.Tensor, + req_to_token: torch.Tensor, + cache_seqlens: torch.Tensor, + cu_seqlens_k: torch.Tensor, + page_table_1: Optional[torch.Tensor], + seqlens_expanded: torch.Tensor, + dsa_cache_seqlens: torch.Tensor, + dsa_cu_seqlens_k: torch.Tensor, + real_page_table: torch.Tensor, + bs: int, + max_seqlen_k: int, + dsa_index_topk: int, + real_page_size: int, + next_n: int, + paged_mqa_ctx_lens_2d: torch.Tensor = None, + index_kpool: int = 1, +) -> None: + if bs == 0: + assert cu_seqlens_k.is_cuda + assert dsa_cu_seqlens_k.is_cuda + cu_seqlens_k[:1].zero_() + dsa_cu_seqlens_k[:1].zero_() + return + + grid, args, constexprs = _prep_fused_dsa_target_verify_metadata_launch( + seq_lens, + req_pool_indices, + req_to_token, + cache_seqlens, + cu_seqlens_k, + page_table_1, + seqlens_expanded, + dsa_cache_seqlens, + dsa_cu_seqlens_k, + real_page_table, + bs, + max_seqlen_k, + dsa_index_topk, + real_page_size, + next_n, + paged_mqa_ctx_lens_2d, + index_kpool, + ) + _fused_dsa_target_verify_metadata_kernel[grid](*args, **constexprs) @triton.jit( @@ -446,6 +592,7 @@ def fused_dsa_target_verify_metadata( "real_page_table_stride_0", "total_len", "max_seqlen_k", + "num_splits", ] ) def _fused_dsa_draft_extend_metadata_kernel( @@ -472,7 +619,9 @@ def _fused_dsa_draft_extend_metadata_kernel( bs: tl.constexpr, total_len, max_seqlen_k, + num_splits, dsa_index_topk: tl.constexpr, + index_kpool: tl.constexpr, real_page_size: tl.constexpr, HAS_REAL_PAGE_TABLE: tl.constexpr, HAS_PAGE_TABLE_1: tl.constexpr, @@ -532,7 +681,17 @@ def _fused_dsa_draft_extend_metadata_kernel( expanded_seq = base_seq - qo_len_for_row + local_off + 1 expanded_seq = tl.maximum(expanded_seq, 0) expanded_seq = tl.where(mask_e, expanded_seq, 0) - dsa_seq = tl.minimum(expanded_seq, dsa_index_topk) + if index_kpool <= 1: + dsa_seq = tl.minimum(expanded_seq, dsa_index_topk) + else: + # Match compute_dsa_seqlens exactly (same formula as the + # target-verify kernel above): select complete history pools up + # to top-k, then retain the partial trailing pool. In + # particular, topk+pool-1 -> topk+pool-1 while topk+pool -> topk. + full_pool_tokens = (expanded_seq // index_kpool) * index_kpool + selected_history_tokens = tl.minimum(full_pool_tokens, dsa_index_topk) + tail_tokens = expanded_seq - full_pool_tokens + dsa_seq = selected_history_tokens + tail_tokens dsa_cu = tl.cumsum(dsa_seq, 0) tl.store(seqlens_expanded + offs_e, expanded_seq, mask=mask_e) @@ -541,25 +700,31 @@ def _fused_dsa_draft_extend_metadata_kernel( tl.store(dsa_cu_seqlens_k + 1 + offs_e, dsa_cu, mask=mask_e) return - num_col_blocks = tl.cdiv(max_seqlen_k, BLOCK_N) page_pid = pid - 1 - req_row = page_pid // num_col_blocks - col_block = page_pid - req_row * num_col_blocks - offs_n = col_block * BLOCK_N + tl.arange(0, BLOCK_N) + req_row = page_pid // num_splits + split_id = page_pid - req_row * num_splits qo_len = tl.load( extend_seq_lens + req_row * extend_seq_lens_stride, mask=req_row < bs, other=0, ).to(tl.int32) - # Skip column blocks past the request's kv length: no consumer reads there - # (attention and the indexer both stay within cache_seqlens). kv_len = tl.load( seq_lens + req_row * seq_lens_stride, mask=req_row < bs, other=0, ).to(tl.int32) - if col_block * BLOCK_N >= kv_len: + # Bounded traversal: scan only up to this request's kv length, read here + # at run (replay) time. Column blocks past kv_len hold no + # consumer-visible data (attention and the indexer both stay within + # cache_seqlens), so the write set is identical to a full-width scan that + # early-exits dead blocks; what changes is that those blocks are never + # dispatched. The early return below also keeps idle programs from paying + # the dynamic-extend prefix loop. + num_live_blocks = tl.minimum( + tl.cdiv(kv_len, BLOCK_N), tl.cdiv(max_seqlen_k, BLOCK_N) + ) + if split_id >= num_live_blocks: return if STATIC_EXTEND_LEN: prefix = req_row * qo_len @@ -573,41 +738,53 @@ def _fused_dsa_draft_extend_metadata_kernel( offs_r = tl.arange(0, BLOCK_ROWS) out_rows = prefix + offs_r row_mask = (req_row < bs) & (offs_r < qo_len) & (out_rows < total_len) - col_mask = offs_n < max_seqlen_k has_rows = (req_row < bs) & (qo_len > 0) - mask = row_mask[:, None] & col_mask[None, :] req_idx = tl.load( req_pool_indices + req_row * req_pool_indices_stride, mask=has_rows, other=0, ) - vals = tl.load( - req_to_token + req_idx * req_to_token_stride_0 + offs_n * req_to_token_stride_1, - mask=col_mask & has_rows, - other=0, - ).to(tl.int32) - # Write the wide page_size=1 table only when the caller provides it (see - # fused_dsa_decode_metadata for the optional-page_table_1 contract). - if HAS_PAGE_TABLE_1: - tl.store( - page_table_1 - + out_rows[:, None] * page_table_stride_0 - + offs_n[None, :] * page_table_stride_1, - vals[None, :], - mask=mask, - ) + # Same int64 row-term promotion as the target-verify kernel above: + # out_rows spans bs * max_extend_len rows and the wide table's row stride + # is ~max_context_len, so the int32 product wraps negative once + # row * stride reaches 2^31. + out_rows_i64 = out_rows.to(tl.int64) + # num_stages: see the decode kernel above. + for col_block in tl.range(split_id, num_live_blocks, num_splits, num_stages=3): + offs_n = col_block * BLOCK_N + tl.arange(0, BLOCK_N) + col_mask = offs_n < max_seqlen_k + mask = row_mask[:, None] & col_mask[None, :] + + vals = tl.load( + req_to_token + + req_idx * req_to_token_stride_0 + + offs_n * req_to_token_stride_1, + mask=col_mask & has_rows, + other=0, + ).to(tl.int32) + # Write the wide page_size=1 table only when the caller provides it + # (see fused_dsa_decode_metadata for the optional-page_table_1 + # contract). + if HAS_PAGE_TABLE_1: + tl.store( + page_table_1 + + out_rows_i64[:, None] * page_table_stride_0 + + offs_n[None, :] * page_table_stride_1, + vals[None, :], + mask=mask, + ) - if HAS_REAL_PAGE_TABLE: - real_mask = mask & ((offs_n[None, :] % real_page_size) == 0) - real_cols = offs_n // real_page_size - tl.store( - real_page_table - + out_rows[:, None] * real_page_table_stride_0 - + real_cols[None, :] * real_page_table_stride_1, - (vals // real_page_size)[None, :], - mask=real_mask, - ) + if HAS_REAL_PAGE_TABLE: + real_mask = mask & ((offs_n[None, :] % real_page_size) == 0) + real_cols = offs_n // real_page_size + tl.store( + real_page_table + + out_rows_i64[:, None] * real_page_table_stride_0 + + real_cols[None, :] * real_page_table_stride_1, + (vals // real_page_size)[None, :], + mask=real_mask, + ) def fused_dsa_draft_extend_metadata( @@ -630,6 +807,7 @@ def fused_dsa_draft_extend_metadata( max_extend_len: int, max_total_len: int, static_extend_len: bool = False, + index_kpool: int = 1, ) -> None: assert seq_lens.is_cuda assert extend_seq_lens.is_cuda @@ -658,6 +836,7 @@ def fused_dsa_draft_extend_metadata( # that would sync in the replay hot path. assert max_extend_len > 0 assert total_len <= bs * max_extend_len + assert index_kpool > 0 has_real_page_table = real_page_size > 1 if has_real_page_table: @@ -681,7 +860,8 @@ def fused_dsa_draft_extend_metadata( block_rows = triton.next_power_of_2(max_extend_len) block_n = 128 num_col_blocks = triton.cdiv(max_seqlen_k, block_n) - grid = (1 + bs * num_col_blocks,) + num_splits = _bounded_scan_num_splits(bs, num_col_blocks) + grid = (1 + bs * num_splits,) _fused_dsa_draft_extend_metadata_kernel[grid]( seq_lens, @@ -707,7 +887,9 @@ def fused_dsa_draft_extend_metadata( bs, total_len, max_seqlen_k, + num_splits, dsa_index_topk, + index_kpool, real_page_size, has_real_page_table, has_page_table_1, diff --git a/python/sglang/kernels/ops/attention/dsv4/topk.py b/python/sglang/kernels/ops/attention/dsv4/topk.py index 8597f89ee7792..f989a8a066631 100644 --- a/python/sglang/kernels/ops/attention/dsv4/topk.py +++ b/python/sglang/kernels/ops/attention/dsv4/topk.py @@ -70,7 +70,11 @@ def topk_transform_512( _PLAN_METADATA_INTS_PER_BATCH = 2 -def plan_topk_v2(seq_lens: torch.Tensor, static_threshold: int = 0) -> torch.Tensor: +def plan_topk_v2( + seq_lens: torch.Tensor, + static_threshold: int = 0, + out: Optional[torch.Tensor] = None, +) -> torch.Tensor: """Preprocess the per-batch routing plan for :func:`topk_transform_512_v2`. IMPORTANT: every entry of ``seq_lens`` must be NON-NEGATIVE. The device @@ -79,12 +83,17 @@ def plan_topk_v2(seq_lens: torch.Tensor, static_threshold: int = 0) -> torch.Ten the plan, and drives the transform kernel into an illegal memory access. Producers of padded rows must clamp their lengths to 0 (0 selects the trivial all-(-1) output path, which is safe). + + ``out``, when given, must be a plan previously produced by this function + for the same batch size (shape ``(bs + 1, _PLAN_METADATA_INTS_PER_BATCH)``) + and is rewritten in place instead of allocating a fresh buffer. """ module = _jit_topk_v2_module() - bs = seq_lens.shape[0] - metadata = seq_lens.new_empty(bs + 1, _PLAN_METADATA_INTS_PER_BATCH) - module.topk_plan(seq_lens, metadata, static_threshold) - return metadata + if out is None: + bs = seq_lens.shape[0] + out = seq_lens.new_empty(bs + 1, _PLAN_METADATA_INTS_PER_BATCH) + module.topk_plan(seq_lens, out, static_threshold) + return out def topk_transform_ragged_v2( diff --git a/python/sglang/kernels/ops/attention/fla/cumsum.py b/python/sglang/kernels/ops/attention/fla/cumsum.py index 775a8f800ed6d..182211e55b35a 100644 --- a/python/sglang/kernels/ops/attention/fla/cumsum.py +++ b/python/sglang/kernels/ops/attention/fla/cumsum.py @@ -70,10 +70,9 @@ def chunk_local_cumsum_scalar_kernel( @triton.autotune( configs=[ - triton.Config({"BS": BS}, num_warps=num_warps, num_stages=num_stages) + triton.Config({"BS": BS}, num_warps=num_warps) for BS in BS_LIST for num_warps in [2, 4, 8] - for num_stages in [2, 3, 4] ], key=["B", "H", "S", "BT", "IS_VARLEN", "REVERSE", "HAS_SCALE"], ) diff --git a/python/sglang/kernels/ops/attention/fla/fused_recurrent.py b/python/sglang/kernels/ops/attention/fla/fused_recurrent.py index 5ffdea77662ac..4528b7c36e2b0 100644 --- a/python/sglang/kernels/ops/attention/fla/fused_recurrent.py +++ b/python/sglang/kernels/ops/attention/fla/fused_recurrent.py @@ -434,8 +434,7 @@ def fused_recurrent_kda_packed_decode_kernel( """KDA packed decode: same shape as the GDN packed decode kernel, but with a per-K gate (``a`` is ``[B, HV*K]`` and ``dt_bias`` is ``[HV*K]``), so the state decay is a per-K vector ``exp(g)`` rather than a scalar.""" - i_v, i_nh = tl.program_id(0), tl.program_id(1) - i_n, i_hv = i_nh // HV, i_nh % HV + i_v, i_n, i_hv = tl.program_id(0), tl.program_id(1), tl.program_id(2) i_h = i_hv // (HV // H) o_k = tl.arange(0, BK) @@ -672,7 +671,7 @@ def fused_recurrent_kda_packed_decode( stride_indices_seq = ssm_state_indices.stride(0) NV = triton.cdiv(V, BV) - grid = (NV, B * HV) + grid = (NV, B, HV) fused_recurrent_kda_packed_decode_kernel[grid]( mixed_qkv=mixed_qkv, a=a, diff --git a/python/sglang/kernels/ops/attention/fla/fused_sigmoid_gating_recurrent.py b/python/sglang/kernels/ops/attention/fla/fused_sigmoid_gating_recurrent.py index a7ffe49e64281..296f0c54307f7 100644 --- a/python/sglang/kernels/ops/attention/fla/fused_sigmoid_gating_recurrent.py +++ b/python/sglang/kernels/ops/attention/fla/fused_sigmoid_gating_recurrent.py @@ -67,12 +67,19 @@ def fused_sigmoid_gating_delta_rule_update_kernel( stride_beta_slot: tl.constexpr = 0, MAX_CACHE_LEN: tl.constexpr = 0, CACHE_RING: tl.constexpr = False, + SPLIT_N_HV_GRID: tl.constexpr = False, ): """ Fused kernel that combines sigmoid gating computation with recurrent delta rule update. """ - i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2) - i_n, i_hv = i_nh // HV, i_nh % HV + if SPLIT_N_HV_GRID: + i_v, i_n, i_hv = tl.program_id(0), tl.program_id(1), tl.program_id(2) + # The GPU wrapper asserts NK == 1. Keep N and HV on independent grid + # axes so large GLM5 decode batches do not exceed CUDA's grid limit. + i_k = 0 + else: + i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2) + i_n, i_hv = i_nh // HV, i_nh % HV i_h = i_hv // (HV // H) if IS_VARLEN: @@ -348,9 +355,7 @@ def fused_sigmoid_gating_delta_rule_update( disable_state_update: bool = False, intermediate_states_buffer: Optional[torch.Tensor] = None, intermediate_state_indices: Optional[torch.Tensor] = None, - cache_steps: Optional[ - int - ] = None, # kept for API compat; stride is derived from ``intermediate_states_buffer.shape[1]`` + cache_steps: Optional[int] = None, retrieve_parent_token: Optional[torch.Tensor] = None, # fused ReplaySSM ring-write (spec verify). When cache_ring, each draft step # stores pre-norm k / raw v / gate / beta into these per-slot rings, @@ -407,15 +412,17 @@ def fused_sigmoid_gating_delta_rule_update( NP2_T = triton.next_power_of_2(T) - grid = (NK, NV, N * HV) + split_n_hv_grid = q.device.type == "cuda" + grid = (NV, N, HV) if split_n_hv_grid else (NK, NV, N * HV) - # Per-req stride must match the buffer's allocated dim, not runtime steps - # (they can differ under --speculative-adaptive). - cache_stride_steps = ( - intermediate_states_buffer.shape[1] - if intermediate_states_buffer is not None - else 0 - ) + # Adaptive spec changes the runtime draft count without changing the + # allocated per-request pitch, which is preserved in stride(0). + if intermediate_states_buffer is not None: + cache_stride_steps = intermediate_states_buffer.stride(0) // (HV * K * V) + elif cache_steps is not None and cache_steps > 0: + cache_stride_steps = cache_steps + else: + cache_stride_steps = 0 # ring strides (per-slot rings are contiguous [num_slots, heads, L, dim]; # the kernel offsets within a slot with MAX_CACHE_LEN and the dim extents). @@ -499,6 +506,7 @@ def fused_sigmoid_gating_delta_rule_update( stride_beta_slot=stride_beta_slot, MAX_CACHE_LEN=max_cache_len, CACHE_RING=cache_ring, + SPLIT_N_HV_GRID=split_n_hv_grid, num_warps=num_warps, num_stages=num_stages, ) diff --git a/python/sglang/kernels/ops/attention/fla/kda.py b/python/sglang/kernels/ops/attention/fla/kda.py index c5d2defc1b1f2..d3e9a6c1fce78 100644 --- a/python/sglang/kernels/ops/attention/fla/kda.py +++ b/python/sglang/kernels/ops/attention/fla/kda.py @@ -29,7 +29,6 @@ check_shared_mem, is_intel, is_nvidia, - is_tf32_supported, ) if is_intel: @@ -742,7 +741,7 @@ def recompute_w_u_fwd( BT=BT, STORE_KG=kg is not None, IS_VARLEN=cu_seqlens is not None, - DOT_PRECISION="tf32" if is_tf32_supported else "ieee", + DOT_PRECISION="ieee", **(static_config or {}), ) return w, u, kg @@ -751,8 +750,8 @@ def recompute_w_u_fwd( @triton.autotune( configs=[ triton.Config({"BK": BK, "BV": BV}, num_warps=num_warps, num_stages=num_stages) - for BK in [64] - for BV in [64] + for BK in [32, 64] + for BV in [64, 128] for num_warps in [2, 4, 8] for num_stages in [2, 3, 4] ], @@ -863,7 +862,7 @@ def chunk_gla_fwd_kernel_o( # [BT, BT] b_A = tl.load(p_A, boundary_check=(0, 1)) b_A = tl.where(m_s, b_A, 0.0).to(b_v.dtype) - b_o += tl.dot(b_A, b_v) + b_o += tl.dot(b_A, b_v, allow_tf32=False) tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1)) @@ -1155,6 +1154,7 @@ def chunk_kda_fwd( cu_seqlens=cu_seqlens, chunk_size=chunk_size, chunk_indices=chunk_indices, + safe_gate=lower_bound is not None, fuse_diagonal=_small_grid, fuse_recompute=_small_grid, ) @@ -1210,6 +1210,7 @@ def chunk_kda( dt_bias: Optional[torch.Tensor] = None, lower_bound: Optional[float] = None, output_intermediate_states: bool = False, + beta_is_raw: bool = False, **kwargs, ): if scale is None: @@ -1219,6 +1220,9 @@ def chunk_kda( q = l2norm_fwd(q.contiguous()) k = l2norm_fwd(k.contiguous()) + if beta_is_raw: + beta = beta.float().sigmoid() + # Returns o [B, T, H, V] when output_intermediate_states=False, or (o, h [B, NT, H, V, K]) when output_intermediate_states=True. return chunk_kda_fwd( q=q, diff --git a/python/sglang/kernels/ops/attention/utils.py b/python/sglang/kernels/ops/attention/utils.py index d70fe65a1a8f4..baa7dd27a7057 100644 --- a/python/sglang/kernels/ops/attention/utils.py +++ b/python/sglang/kernels/ops/attention/utils.py @@ -180,6 +180,27 @@ def mla_quantize_and_rope_for_fp8( return q_out, k_nope_out, k_rope_out +def mla_quantize_for_fp8_no_rope( + q_nope: torch.Tensor, + q_rope: torch.Tensor, + k_nope: torch.Tensor, + k_rope: torch.Tensor, + kv_lora_rank: int, + qk_rope_head_dim: int, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + attn_dtype = torch.float8_e4m3fn + q_len, num_heads = q_rope.shape[:2] + q_out = q_rope.new_empty( + q_len, + num_heads, + kv_lora_rank + qk_rope_head_dim, + dtype=attn_dtype, + ) + q_out[..., :kv_lora_rank] = q_nope.to(attn_dtype) + q_out[..., kv_lora_rank:] = q_rope.to(attn_dtype) + return q_out, k_nope.to(attn_dtype), k_rope.to(attn_dtype) + + def mla_quantize_without_rope_for_fp8( q_nope: torch.Tensor, q_rope: torch.Tensor, diff --git a/python/sglang/kernels/ops/kvcache/mla_buffer.py b/python/sglang/kernels/ops/kvcache/mla_buffer.py index ba9b7a5c8cecc..6ed36d5e8a93d 100644 --- a/python/sglang/kernels/ops/kvcache/mla_buffer.py +++ b/python/sglang/kernels/ops/kvcache/mla_buffer.py @@ -1,5 +1,7 @@ from __future__ import annotations +from typing import Optional + import torch import triton import triton.language as tl @@ -81,6 +83,41 @@ def set_mla_kv_buffer_kernel( tl.extra.cuda.gdc_launch_dependents() +@triton.jit +def set_mla_kv_buffer_kernel_norope( + kv_buffer_ptr, + cache_k_nope_ptr, + loc_ptr, + buffer_stride: tl.constexpr, + nope_stride: tl.constexpr, + nope_dim: tl.constexpr, + BLOCK: tl.constexpr, + USE_GDC: tl.constexpr = False, +): + """Variant of ``set_mla_kv_buffer_kernel`` for qk_rope_head_dim==0.""" + pid_loc = tl.program_id(0) + pid_blk = tl.program_id(1) + + base = pid_blk * BLOCK + offs = base + tl.arange(0, BLOCK) + mask = offs < nope_dim + + if USE_GDC: + tl.extra.cuda.gdc_wait() + + loc = tl.load(loc_ptr + pid_loc).to(tl.int64) + dst_ptr = kv_buffer_ptr + loc * buffer_stride + offs + + src = tl.load( + cache_k_nope_ptr + pid_loc * nope_stride + offs, + mask=mask, + ) + tl.store(dst_ptr, src, mask=mask) + + if USE_GDC: + tl.extra.cuda.gdc_launch_dependents() + + # Above this loc count the TMA bulk-store path overtakes the single-CTA-per-loc # Triton kernel. Below it, Triton with BLOCK = next_pow2(total_dim) (one CTA # does the whole row in one tile, no boundary fan-out) is the winning fallback. @@ -92,7 +129,7 @@ def set_mla_kv_buffer_triton( kv_buffer: torch.Tensor, loc: torch.Tensor, cache_k_nope: torch.Tensor, - cache_k_rope: torch.Tensor, + cache_k_rope: Optional[torch.Tensor] = None, *, reserved_skip_index: int = 0, ): @@ -112,6 +149,11 @@ def set_mla_kv_buffer_triton( a one-shot per CTA. This is also the path for SM<90 and for shapes that violate the TMA 16-byte alignment. + A third path is taken when ``cache_k_rope`` is None or empty + (qk_rope_head_dim==0): the dedicated ``set_mla_kv_buffer_kernel_norope`` + Triton kernel bypasses the rope branch entirely. The JIT TMA path assumes + both nope and rope are present, so it is skipped here. + Speedup vs the legacy BLOCK=128 Triton kernel on GB300 (BF16, nope=512, rope=64): ~1.05x at bs=8, ~1.5x at bs=128, 3.5x at bs=512, **11.7x at bs=16384**. @@ -122,6 +164,28 @@ def set_mla_kv_buffer_triton( Writes targeting ``reserved_skip_index`` are skipped. Slot 0 is reserved for CUDA-graph padding by default; pass -1 to disable skipping. """ + has_rope = cache_k_rope is not None and cache_k_rope.numel() > 0 + n_loc = loc.numel() + nope_dim = cache_k_nope.shape[-1] + + if not has_rope: + BLOCK = triton.next_power_of_2(nope_dim) + grid = (n_loc, 1) + pdl_kwargs = ( + {"USE_GDC": True, "launch_pdl": True} if is_arch_support_pdl() else {} + ) + set_mla_kv_buffer_kernel_norope[grid]( + kv_buffer, + cache_k_nope, + loc, + kv_buffer.stride(0), + cache_k_nope.stride(0), + nope_dim, + BLOCK=BLOCK, + **pdl_kwargs, + ) + return + from sglang.kernels.ops.kvcache.set_mla_kv_buffer import ( can_use_set_mla_kv_buffer, ) @@ -129,7 +193,6 @@ def set_mla_kv_buffer_triton( set_mla_kv_buffer as jit_set_mla_kv_buffer, ) - n_loc = loc.numel() nope_bytes = cache_k_nope.shape[-1] * cache_k_nope.element_size() rope_bytes = cache_k_rope.shape[-1] * cache_k_rope.element_size() if ( @@ -152,7 +215,6 @@ def set_mla_kv_buffer_triton( # ``set_mla_kv_buffer_kernel`` handles the over-allocation past total_dim # via the offs 0 + if not has_rope: + get_mla_kv_buffer_kernel_norope[grid]( + kv_buffer, + cache_k_nope, + loc, + kv_buffer.stride(0), + cache_k_nope.stride(0), + nope_dim, + ) + return + + rope_dim = cache_k_rope.shape[-1] # 64 get_mla_kv_buffer_kernel[grid]( kv_buffer, cache_k_nope, diff --git a/python/sglang/kernels/ops/layernorm/mhc.py b/python/sglang/kernels/ops/layernorm/mhc.py index ebe4e3a8ad78a..b4a00c4419f7e 100644 --- a/python/sglang/kernels/ops/layernorm/mhc.py +++ b/python/sglang/kernels/ops/layernorm/mhc.py @@ -1563,6 +1563,220 @@ def mhc_fused_post_pre( ) +def hc_expand(x: torch.Tensor, n: int) -> torch.Tensor: + """[s, hidden_size] -> [s, n * hidden_size] by replication.""" + return x.repeat(1, n) + + +def hc_contract(x: torch.Tensor, n: int) -> torch.Tensor: + """[s, n * hidden_size] -> [s, hidden_size] by averaging.""" + return x.unflatten(-1, (n, -1)).mean(dim=-2) + + +# --------------------------------------------------------------------------- +# Flat (2-D) MHC functional front-ends, matching the GLM reference contract so +# the communicator pipeline (MHCState / MHCLayerCommunicator) can keep hidden +# states as plain ``[tokens, n * hidden]`` 2-D tensors. The tilelang path reuses +# this module's ``mhc_pre`` / ``mhc_post`` kernels; a pure-torch reference is +# kept for fallback / numerics checks. +# --------------------------------------------------------------------------- + + +def _mhc_pre_torch( + residual: torch.Tensor, + fn: torch.Tensor, + hc_scale: torch.Tensor, + hc_base: torch.Tensor, + rms_eps: float, + hc_pre_eps: float, + hc_sinkhorn_eps: float, + hc_post_mult_value: float, + sinkhorn_repeat: int, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Pure-torch reference of mhc_pre. + + residual: (s, n, h); returns (post=(s, n, 1), comb=(s, n, n), layer_input=(s, h)). + """ + import torch.nn.functional as F + + s, n, h = residual.shape + dtype = residual.dtype + + x_flat = residual.view(s, n * h).float() + rsqrt = torch.rsqrt(x_flat.square().mean(-1, keepdim=True) + rms_eps) + mixes = F.linear(x_flat, fn) * rsqrt # (s, mix_hc) + + pre_raw = mixes[:, :n] + post_raw = mixes[:, n : 2 * n] + comb_raw = mixes[:, 2 * n :].view(s, n, n) + pre_base = hc_base[:n] + post_base = hc_base[n : 2 * n] + comb_base = hc_base[2 * n :].view(n, n) + + pre = torch.sigmoid(pre_raw * hc_scale[0] + pre_base) + hc_pre_eps + post = hc_post_mult_value * torch.sigmoid(post_raw * hc_scale[1] + post_base) + comb = comb_raw * hc_scale[2] + comb_base + + comb = comb.softmax(-1) + hc_sinkhorn_eps + comb = comb / (comb.sum(-2, keepdim=True) + hc_sinkhorn_eps) + for _ in range(sinkhorn_repeat - 1): + comb = comb / (comb.sum(-1, keepdim=True) + hc_sinkhorn_eps) + comb = comb / (comb.sum(-2, keepdim=True) + hc_sinkhorn_eps) + + layer_input = (pre.unsqueeze(-1) * residual.float()).sum(dim=1).to(dtype) + return post.unsqueeze(-1), comb, layer_input + + +def _mhc_post_torch( + x: torch.Tensor, + residual: torch.Tensor, + post_layer_mix: torch.Tensor, + comb_res_mix: torch.Tensor, +) -> torch.Tensor: + """Pure-torch reference of mhc_post. x:(s,h) residual:(s,n,h) -> (s,n,h).""" + out = post_layer_mix * x.unsqueeze(1) + ( + comb_res_mix.unsqueeze(-1) * residual.unsqueeze(2) + ).sum(dim=1) + return out.type_as(x) + + +@torch._dynamo.disable +def _mhc_pre_dispatch( + residual: torch.Tensor, + fn: torch.Tensor, + hc_scale: torch.Tensor, + hc_base: torch.Tensor, + rms_eps: float, + hc_pre_eps: float, + hc_sinkhorn_eps: float, + hc_post_mult_value: float, + sinkhorn_repeat: int, + norm_weight: torch.Tensor | None = None, + norm_eps: float | None = None, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, bool]: + """Run mhc_pre using the env-selected backend. + + Returns (post_mix=(s,n,1), comb_mix=(s,n,n), layer_input=(s,h), norm_fused). + """ + assert residual.dim() == 3, f"residual must be (s, n, h); got {residual.shape}" + if not envs.SGLANG_OPT_USE_TILELANG_MHC_PRE.get(): + post_mix, comb_mix, layer_input = _mhc_pre_torch( + residual=residual, + fn=fn, + hc_scale=hc_scale, + hc_base=hc_base, + rms_eps=rms_eps, + hc_pre_eps=hc_pre_eps, + hc_sinkhorn_eps=hc_sinkhorn_eps, + hc_post_mult_value=hc_post_mult_value, + sinkhorn_repeat=sinkhorn_repeat, + ) + return post_mix, comb_mix, layer_input, False + + post_mix, comb_mix, layer_input = mhc_pre( + residual=residual, + fn=fn, + hc_scale=hc_scale, + hc_base=hc_base, + rms_eps=rms_eps, + hc_pre_eps=hc_pre_eps, + hc_sinkhorn_eps=hc_sinkhorn_eps, + hc_post_mult_value=hc_post_mult_value, + sinkhorn_repeat=sinkhorn_repeat, + norm_weight=norm_weight, + norm_eps=norm_eps, + ) + return post_mix, comb_mix, layer_input, norm_weight is not None + + +@torch._dynamo.disable +def _mhc_post_dispatch( + x: torch.Tensor, + residual: torch.Tensor, + post_layer_mix: torch.Tensor, + comb_res_mix: torch.Tensor, +) -> torch.Tensor: + assert x.dim() == 2 and residual.dim() == 3 + assert post_layer_mix.dim() == 3 and comb_res_mix.dim() == 3 + if not envs.SGLANG_OPT_USE_TILELANG_MHC_POST.get(): + return _mhc_post_torch(x, residual, post_layer_mix, comb_res_mix) + return mhc_post(x, residual, post_layer_mix, comb_res_mix) + + +def hc_pre( + x: torch.Tensor, + hc_fn: torch.Tensor, + hc_scale: torch.Tensor, + hc_base: torch.Tensor, + hc_mult: int, + rms_eps: float, + hc_eps: float, + sinkhorn_iters: int, + post_mult_value: float = 2.0, + hc_norm_weight: torch.Tensor | None = None, + out_norm_weight: torch.Tensor | None = None, + out_norm_eps: float | None = None, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, bool]: + """MHC pre for one sublayer. + + x: [s, n*hidden] bf16. Returns (layer_input [s,hidden], h_res [s,n*n] fp32, + h_post [s,n] fp32, norm_fused). + """ + s, total = x.shape + hidden_size = total // hc_mult + if x.numel() == 0: + empty_layer_input = x.new_zeros((s, hidden_size)) + empty_h_res = torch.zeros( + (s, hc_mult * hc_mult), device=x.device, dtype=torch.float32 + ) + empty_h_post = torch.zeros((s, hc_mult), device=x.device, dtype=torch.float32) + return empty_layer_input, empty_h_res, empty_h_post, False + + fn = hc_fn if hc_norm_weight is None else hc_fn * hc_norm_weight + residual_3d = x.view(s, hc_mult, hidden_size) + post_mix, comb_mix, layer_input, norm_fused = _mhc_pre_dispatch( + residual=residual_3d, + fn=fn, + hc_scale=hc_scale, + hc_base=hc_base, + rms_eps=rms_eps, + hc_pre_eps=hc_eps, + hc_sinkhorn_eps=hc_eps, + hc_post_mult_value=post_mult_value, + sinkhorn_repeat=sinkhorn_iters, + norm_weight=out_norm_weight, + norm_eps=out_norm_eps, + ) + return ( + layer_input, + comb_mix.reshape(s, hc_mult * hc_mult), + post_mix.reshape(s, hc_mult), + norm_fused, + ) + + +def hc_post( + x: torch.Tensor, + residual: torch.Tensor, + h_post: torch.Tensor, + h_res: torch.Tensor, + hc_mult: int, +) -> torch.Tensor: + """MHC post for one sublayer. + + x: [s, hidden], residual: [s, n*hidden], h_post: [s,n], h_res: [s,n*n]. + Returns [s, n*hidden]. + """ + s, hidden_size = x.shape + if s == 0: + return x.new_zeros((s, hc_mult * hidden_size)) + residual = residual.view(s, hc_mult, hidden_size) + h_post = h_post.view(s, hc_mult, 1) + h_res = h_res.view(s, hc_mult, hc_mult) + out = _mhc_post_dispatch(x, residual, h_post, h_res) + return out.view(s, -1) + + def npu_hc_pre( x: torch.Tensor, hc_fn: torch.Tensor, diff --git a/python/sglang/kernels/ops/moe/kpool_topk_transform.py b/python/sglang/kernels/ops/moe/kpool_topk_transform.py new file mode 100644 index 0000000000000..a3bfd04fcc0fd --- /dev/null +++ b/python/sglang/kernels/ops/moe/kpool_topk_transform.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Optional + +import torch + +from sglang.kernels.jit.utils import cache_once, load_jit + +if TYPE_CHECKING: + from tvm_ffi.module import Module + +# Pool-level top-k values that have dedicated, validated kernel instantiations. +SUPPORTED_GROUP_TOPK = (128, 160, 192, 224, 256, 512) + + +@cache_once +def _jit_kpool_topk_transform_module(group_topk: int) -> Module: + """Compile and cache the kpool top-k transform module for a given group_topk.""" + assert group_topk in SUPPORTED_GROUP_TOPK, ( + "fast_kpool_topk_transform supports pool-level topk " + f"{SUPPORTED_GROUP_TOPK}, got {group_topk}" + ) + return load_jit( + f"kpool_topk_transform_{group_topk}", + cuda_files=["dsa/kpool_topk_transform.cuh"], + cuda_wrappers=[("kpool_topk_transform", "KpoolTopKTransformKernel::transform")], + extra_cuda_cflags=[f"-DSGL_GROUP_TOPK={group_topk}"], + ) + + +def fast_kpool_topk_transform_fused( + score: torch.Tensor, + lengths: torch.Tensor, + pool_size: int, + topk: int, + page_table: Optional[torch.Tensor] = None, + topk_indices_offset: Optional[torch.Tensor] = None, + row_starts: Optional[torch.Tensor] = None, + seq_lens: Optional[torch.Tensor] = None, + page_table_row_index: Optional[torch.Tensor] = None, +) -> torch.Tensor: + """ + Pool-level radix top-k for the NSA kpool indexer. + + Selects pool groups from ``score`` at pool granularity, expands each selected + group to ``pool_size`` token indices, and optionally transforms those token + indices through a page table or a ragged offset. + """ + assert topk % pool_size == 0 + group_topk = topk // pool_size + assert group_topk in SUPPORTED_GROUP_TOPK, ( + "fast_kpool_topk_transform supports pool-level topk " + f"{SUPPORTED_GROUP_TOPK}, got {group_topk}" + ) + assert score.dim() == 2 + assert page_table is None or topk_indices_offset is None + assert page_table_row_index is None or page_table is not None + if seq_lens is not None: + assert seq_lens.dim() == 1 + assert seq_lens.shape[0] == score.shape[0] + if page_table_row_index is not None: + assert page_table_row_index.dim() == 1 + assert page_table_row_index.shape[0] == score.shape[0] + + out_cols = topk + (pool_size - 1 if seq_lens is not None else 0) + dst_token_indices = score.new_empty((score.shape[0], out_cols), dtype=torch.int32) + + module = _jit_kpool_topk_transform_module(group_topk) + module.kpool_topk_transform( + score, + lengths, + dst_token_indices, + pool_size, + page_table, + topk_indices_offset, + row_starts, + seq_lens, + page_table_row_index, + ) + return dst_token_indices diff --git a/python/sglang/kernels/ops/speculative/eagle.py b/python/sglang/kernels/ops/speculative/eagle.py index 10342899ce469..b8051a6f08baf 100644 --- a/python/sglang/kernels/ops/speculative/eagle.py +++ b/python/sglang/kernels/ops/speculative/eagle.py @@ -89,3 +89,65 @@ def fill_accept_out_cache_loc_func( accept_out_cache_loc, next_power_of_2(size), ) + + +@triton.jit +def nextn_mamba_commit_prologue( + accept_lens_ptr, + seq_lens_ptr, + last_correct_ptr, + steps_to_track_ptr, + mamba_track_interval, + HAS_TRACK: tl.constexpr, +): + # Chain-spec (topk == 1) commit prologue. accept_index[i, j] == i*draft + j + # for accepted slots, so the last-accepted tree step is accept_lens - 1 and + # the interval-crossing candidate step equals its own in-request index — + # no accept_index gathers are needed. One launch replaces the ~21-op eager + # sequence in commit_mamba_states_after_verify. + pid = tl.program_id(axis=0) + al = tl.load(accept_lens_ptr + pid).to(tl.int64) + # Outputs are int32 (matching the eager path, whose gathers preserve the + # int32 accept_index dtype); the values are tree-step indices bounded by + # draft_token_num, so the narrowing cast is always exact. + tl.store(last_correct_ptr + pid, (al - 1).to(tl.int32)) + if HAS_TRACK: + pre = tl.load(seq_lens_ptr + pid).to(tl.int64) + post = pre + al + interval = mamba_track_interval.to(tl.int64) + crossed = (pre // interval) != (post // interval) + tracking_point = (post // interval) * interval + ith = tl.maximum(tracking_point - pre - 1, 0) + out = tl.where(crossed, ith, -1) + tl.store(steps_to_track_ptr + pid, out.to(tl.int32)) + + +def nextn_mamba_commit_prologue_func( + accept_lens: torch.Tensor, + seq_lens: torch.Tensor, + mamba_track_interval: int, + has_track: bool, +): + """Fused topk==1 replacement for the eager commit prologue. + + Returns (last_correct_step_indices, mamba_steps_to_track) with the same + dtypes/values as the eager reference path (int32, the dtype of + accept_index that the eager gathers preserve; track entries are -1 where + no interval crossing happened). + """ + bs = accept_lens.shape[0] + last_correct = torch.empty(bs, dtype=torch.int32, device=accept_lens.device) + steps_to_track = ( + torch.empty(bs, dtype=torch.int32, device=accept_lens.device) + if has_track + else last_correct # unused dummy write target is never launched + ) + nextn_mamba_commit_prologue[(bs,)]( + accept_lens, + seq_lens, + last_correct, + steps_to_track, + mamba_track_interval, + HAS_TRACK=has_track, + ) + return last_correct, (steps_to_track if has_track else None) diff --git a/python/sglang/srt/arg_groups/overrides.py b/python/sglang/srt/arg_groups/overrides.py index 556479e548508..e34d865c98d55 100644 --- a/python/sglang/srt/arg_groups/overrides.py +++ b/python/sglang/srt/arg_groups/overrides.py @@ -785,6 +785,7 @@ def _kimi_k3_moe_runner_overrides(server_args: Any, hf_config: Any) -> dict: "MistralLarge3ForCausalLM", "PixtralForConditionalGeneration", "GlmMoeDsaForCausalLM", + "Glm5NextForConditionalGeneration", "LongcatFlashForCausalLM", "LongcatFlashForCausalLMNextN", "Dots3NoteForCausalLM", @@ -1796,6 +1797,7 @@ def _step3p_overrides(server_args: Any, hf_config: Any) -> dict: "Lfm2ForCausalLM", "Lfm2MoeForCausalLM", "ZayaForCausalLM", + "Glm5NextForConditionalGeneration", } ) @@ -1817,6 +1819,7 @@ def _step3p_overrides(server_args: Any, hf_config: Any) -> dict: "BailingMoeV2_5ForCausalLM", "FalconH1ForCausalLM", "GraniteMoeHybridForCausalLM", + "Glm5NextForConditionalGeneration", "NemotronHForCausalLM", "NemotronHPuzzleForCausalLM", # KDA-based: same MambaPool ping-pong machinery as GDN; requires the @@ -2045,6 +2048,7 @@ def _dsa_split_backend_resolution(view: Any) -> dict: "MistralLarge3ForCausalLM", "PixtralForConditionalGeneration", "GlmMoeDsaForCausalLM", + "Glm5NextForConditionalGeneration", "LongcatFlashForCausalLM", "LongcatFlashForCausalLMNextN", "Dots3NoteForCausalLM", diff --git a/python/sglang/srt/configs/__init__.py b/python/sglang/srt/configs/__init__.py index 492760909ba5d..be3c3fe863ba4 100644 --- a/python/sglang/srt/configs/__init__.py +++ b/python/sglang/srt/configs/__init__.py @@ -9,6 +9,7 @@ from sglang.srt.configs.dots_vlm import DotsVLMConfig from sglang.srt.configs.exaone import ExaoneConfig from sglang.srt.configs.falcon_h1 import FalconH1Config +from sglang.srt.configs.glm5_next import Glm5NextConfig, Glm5NextTextConfig from sglang.srt.configs.granitemoehybrid import GraniteMoeHybridConfig from sglang.srt.configs.inkling import ( InklingAudioConfig, @@ -85,6 +86,8 @@ "Olmo3Config", "MuseGlimmerConfig", "MuseGlimmerAssistantConfig", + "Glm5NextConfig", + "Glm5NextTextConfig", "KimiLinearConfig", "KimiK3Config", "KimiK25Config", diff --git a/python/sglang/srt/configs/glm5_next.py b/python/sglang/srt/configs/glm5_next.py new file mode 100644 index 0000000000000..ddeaf0efdac01 --- /dev/null +++ b/python/sglang/srt/configs/glm5_next.py @@ -0,0 +1,349 @@ +from typing import List, Optional, Union + +from transformers.configuration_utils import PretrainedConfig +from transformers.models.glm_ocr.configuration_glm_ocr import GlmOcrVisionConfig + +from sglang.srt.configs.mamba_utils import KimiLinearCacheParams, KimiLinearStateShape +from sglang.srt.runtime_context import get_parallel + +_GLM5_NEXT_TOP_LEVEL_CONFIG_KEYS = ( + "architectures", + "vocab_size", + "hidden_size", + "head_dim", + "intermediate_size", + "moe_intermediate_size", + "num_hidden_layers", + "num_attention_heads", + "num_key_value_heads", + "hidden_act", + "max_position_embeddings", + "rms_norm_eps", + "use_cache", + "pad_token_id", + "bos_token_id", + "eos_token_id", + "rope_theta", + "rope_scaling", + "rope_parameters", + "partial_rotary_factor", + "tie_word_embeddings", + "attention_bias", + "attention_dropout", + "n_routed_experts", + "num_experts_per_tok", + "n_shared_experts", + "n_group", + "topk_group", + "norm_topk_prob", + "routed_scaling_factor", + "scoring_func", + "topk_method", + "first_k_dense_replace", + "moe_layer_freq", + "q_lora_rank", + "kv_lora_rank", + "qk_nope_head_dim", + "qk_rope_head_dim", + "v_head_dim", + "swiglu_limit", + "mhc", + "hc_mult", + "hc_sinkhorn_iters", + "hc_eps", + "num_nextn_predict_layers", + "linear_attn_config", + "linear_head_dim", + "linear_num_heads", + "linear_conv_kernel_dim", + "linear_lower_bound", + "gate_lower_bound", + "index_head_dim", + "index_topk", + "index_kpool", + "index_kpool_always_select_tail", + "index_kpool_compress", + "index_n_heads", + "index_topk_freq", + "index_topk_pattern", + "index_skip_topk_offset", + "index_share_for_mtp_iteration", + "indexer_rope_interleave", + "layer_types", + "mlp_layer_types", + "quantization_config", +) + + +class Glm5NextTextConfig(PretrainedConfig): + model_type = "glm5_next_text" + base_config_key = "text_config" + keys_to_ignore_at_inference = ["past_key_values"] + + def __init__( + self, + vocab_size: int = 154880, + hidden_size: int = 4096, + head_dim: Optional[int] = None, + intermediate_size: int = 12288, + moe_intermediate_size: int = 2048, + num_hidden_layers: int = 45, + num_attention_heads: int = 64, + num_key_value_heads: Optional[int] = None, + hidden_act: str = "silu", + max_position_embeddings: int = 1013760, + rms_norm_eps: float = 1e-5, + use_cache: bool = True, + pad_token_id: Optional[int] = None, + bos_token_id: Optional[int] = None, + eos_token_id: Optional[Union[int, List[int]]] = None, + rope_theta: float = 800000.0, + rope_scaling: Optional[dict] = None, + rope_parameters: Optional[dict] = None, + partial_rotary_factor: float = 1.0, + tie_word_embeddings: bool = False, + attention_bias: bool = False, + attention_dropout: float = 0.0, + n_routed_experts: Optional[int] = 288, + num_experts_per_tok: int = 7, + n_shared_experts: int = 1, + n_group: int = 1, + topk_group: int = 1, + norm_topk_prob: bool = True, + routed_scaling_factor: float = 2.5, + scoring_func: str = "sigmoid", + topk_method: str = "noaux_tc", + first_k_dense_replace: int = 3, + moe_layer_freq: int = 1, + q_lora_rank: Optional[int] = 1536, + kv_lora_rank: int = 512, + qk_nope_head_dim: int = 256, + qk_rope_head_dim: int = 0, + v_head_dim: int = 256, + swiglu_limit: Optional[float] = None, + mhc: bool = False, + hc_mult: int = 4, + hc_sinkhorn_iters: int = 20, + hc_eps: float = 1e-6, + num_nextn_predict_layers: int = 1, + linear_attn_config: Optional[dict] = None, + linear_head_dim: int = 128, + linear_num_heads: int = 64, + linear_conv_kernel_dim: int = 4, + linear_lower_bound: Optional[float] = None, + gate_lower_bound: Optional[float] = None, + index_head_dim: int | None = None, + index_topk: int | None = None, + index_n_heads: int | None = None, + index_topk_freq: int = 1, + index_topk_pattern: Optional[str] = None, + index_skip_topk_offset: Optional[int] = None, + **kwargs, + ): + if rope_scaling is None and rope_parameters is not None: + rope_scaling = rope_parameters + if rope_parameters is not None: + rope_theta = rope_parameters.get("rope_theta", rope_theta) + partial_rotary_factor = rope_parameters.get( + "partial_rotary_factor", partial_rotary_factor + ) + + self.vocab_size = vocab_size + self.hidden_size = hidden_size + self.head_dim = head_dim + self.intermediate_size = intermediate_size + self.moe_intermediate_size = moe_intermediate_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.num_key_value_heads = num_key_value_heads + self.hidden_act = hidden_act + self.max_position_embeddings = max_position_embeddings + self.rms_norm_eps = rms_norm_eps + self.use_cache = use_cache + self.rope_theta = rope_theta + self.rope_scaling = rope_scaling + self.partial_rotary_factor = partial_rotary_factor + self.attention_bias = attention_bias + self.attention_dropout = attention_dropout + self.n_routed_experts = n_routed_experts + self.num_experts_per_tok = num_experts_per_tok + self.n_shared_experts = n_shared_experts + self.n_group = n_group + self.topk_group = topk_group + self.norm_topk_prob = norm_topk_prob + self.routed_scaling_factor = routed_scaling_factor + self.scoring_func = scoring_func + self.topk_method = topk_method + self.first_k_dense_replace = first_k_dense_replace + self.moe_layer_freq = moe_layer_freq + + self.q_lora_rank = q_lora_rank + self.kv_lora_rank = kv_lora_rank + self.qk_nope_head_dim = qk_nope_head_dim + self.qk_rope_head_dim = qk_rope_head_dim + self.v_head_dim = v_head_dim + self.swiglu_limit = swiglu_limit + self.mhc = mhc + self.hc_mult = hc_mult + self.hc_sinkhorn_iters = hc_sinkhorn_iters + self.hc_eps = hc_eps + + self.num_nextn_predict_layers = num_nextn_predict_layers + self.linear_head_dim = linear_head_dim + self.linear_num_heads = linear_num_heads + self.linear_conv_kernel_dim = linear_conv_kernel_dim + self.linear_lower_bound = linear_lower_bound + self.gate_lower_bound = ( + gate_lower_bound if gate_lower_bound is not None else linear_lower_bound + ) + if linear_attn_config is None: + layer_types = kwargs.get("layer_types") + if layer_types is None: + kda_layers = [ + layer_idx + for layer_idx in range(num_hidden_layers) + if layer_idx % 4 != 3 + ] + else: + kda_layers = [ + layer_idx + for layer_idx, layer_type in enumerate(layer_types) + if layer_type == "linear_attention" + ] + kda_layer_set = set(kda_layers) + linear_attn_config = { + "full_attn_layers": [ + layer_idx + for layer_idx in range(num_hidden_layers) + if layer_idx not in kda_layer_set + ], + "head_dim": linear_head_dim, + "kda_layers": kda_layers, + "num_heads": linear_num_heads, + "short_conv_kernel_size": linear_conv_kernel_dim, + "gate_lower_bound": self.gate_lower_bound, + } + self.linear_attn_config = linear_attn_config + self.index_head_dim = index_head_dim + self.index_topk = index_topk + self.index_n_heads = index_n_heads + self.index_topk_freq = index_topk_freq + self.index_topk_pattern = index_topk_pattern + self.index_skip_topk_offset = index_skip_topk_offset + + super().__init__( + pad_token_id=pad_token_id, + bos_token_id=bos_token_id, + eos_token_id=eos_token_id, + tie_word_embeddings=tie_word_embeddings, + **kwargs, + ) + if rope_parameters is not None or rope_scaling is not None: + self.rope_parameters = rope_parameters or rope_scaling + + def is_kda_layer(self, layer_idx: int): + return ( + self.linear_attn_config is not None + and layer_idx in self.linear_attn_config["kda_layers"] + ) + + @property + def linear_layer_ids(self): + return [i for i in range(self.num_hidden_layers) if self.is_kda_layer(i)] + + @property + def nextn_layer_ids(self): + num_nextn_layers = self.num_nextn_predict_layers or 0 + return [self.num_hidden_layers + i for i in range(num_nextn_layers)] + + @property + def full_attention_layer_ids(self): + return [i for i in range(self.num_hidden_layers) if not self.is_kda_layer(i)] + + @property + def mamba2_cache_params(self) -> KimiLinearCacheParams: + from sglang.srt.layers.attention.dsa.utils import is_dsa_enable_prefill_cp + + head_shard_size = ( + get_parallel().attn_cp_size + if is_dsa_enable_prefill_cp() + else get_parallel().attn_tp_size + ) + + shape = KimiLinearStateShape.create( + tp_world_size=head_shard_size, + num_heads=self.linear_attn_config["num_heads"], + head_dim=self.linear_attn_config["head_dim"], + conv_kernel_size=self.linear_attn_config["short_conv_kernel_size"], + ) + + return KimiLinearCacheParams(shape=shape, layers=self.linear_layer_ids) + + +class Glm5NextVisionConfig(GlmOcrVisionConfig): + def __init__( + self, + swiglu_limit: float, + **kwargs, + ): + super().__init__(**kwargs) + self.swiglu_limit = swiglu_limit + + +class Glm5NextConfig(PretrainedConfig): + model_type = "glm5_next" + sub_configs = { + "vision_config": Glm5NextVisionConfig, + "text_config": Glm5NextTextConfig, + } + keys_to_ignore_at_inference = ["past_key_values"] + + def __init__( + self, + text_config=None, + vision_config=None, + image_token_id: int = 59280, + video_token_id: int = 59281, + image_start_token_id: int = 59256, + image_end_token_id: int = 59257, + video_start_token_id: int = 59258, + video_end_token_id: int = 59259, + **kwargs, + ): + top_level_text_config = { + key: kwargs[key] + for key in _GLM5_NEXT_TOP_LEVEL_CONFIG_KEYS + if key in kwargs + } + + if isinstance(text_config, dict): + text_config = {**top_level_text_config, **text_config} + self.text_config = self.sub_configs["text_config"](**text_config) + elif text_config is None: + self.text_config = self.sub_configs["text_config"](**top_level_text_config) + else: + self.text_config = text_config + + if vision_config is None: + self.vision_config = None + else: + if isinstance(vision_config, dict): + vision_config = dict(vision_config) + else: + vision_config = vision_config.to_dict() + self.vision_config = self.sub_configs["vision_config"](**vision_config) + + self.image_token_id = image_token_id + self.video_token_id = video_token_id + self.image_start_token_id = image_start_token_id + self.image_end_token_id = image_end_token_id + self.video_start_token_id = video_start_token_id + self.video_end_token_id = video_end_token_id + + if getattr(self.text_config, "quantization_config", None) is not None: + self.quantization_config = self.text_config.quantization_config + + super().__init__(**kwargs) + for key in _GLM5_NEXT_TOP_LEVEL_CONFIG_KEYS: + if hasattr(self.text_config, key): + setattr(self, key, getattr(self.text_config, key)) diff --git a/python/sglang/srt/configs/hybrid_arch.py b/python/sglang/srt/configs/hybrid_arch.py index bafd9a5cc4888..5870ee4901b2b 100644 --- a/python/sglang/srt/configs/hybrid_arch.py +++ b/python/sglang/srt/configs/hybrid_arch.py @@ -111,6 +111,13 @@ def kimi_linear_config(model_config: ModelConfig): return None +def glm5_next_config(model_config: ModelConfig): + hf_config = model_config.hf_config + if hf_config.model_type == "glm5_next" and not model_config.is_draft_model: + return hf_config.get_text_config() + return None + + def linear_attn_model_spec(model_config: ModelConfig): result = _get_linear_attn_registry_result(model_config) return result[0] if result else None @@ -121,6 +128,7 @@ def mambaish_config(model_config: ModelConfig): mamba2_config(model_config) or hybrid_gdn_config(model_config) or kimi_linear_config(model_config) + or glm5_next_config(model_config) or hybrid_lightning_config(model_config) ) if existing: diff --git a/python/sglang/srt/configs/model_config.py b/python/sglang/srt/configs/model_config.py index 5ec73e5410c69..3db0a69b5f99f 100644 --- a/python/sglang/srt/configs/model_config.py +++ b/python/sglang/srt/configs/model_config.py @@ -122,6 +122,8 @@ def is_deepseek_dsa(config) -> bool: "PixtralForConditionalGeneration", "GlmMoeDsaForCausalLM", "GlmMoeDsaForCausalLMNextN", + "Glm5NextForConditionalGenerationNextN", + "Glm5NextForConditionalGeneration", "LongcatFlashForCausalLM", "LongcatFlashForCausalLMNextN", "Dots3NoteForCausalLM", @@ -138,6 +140,31 @@ def is_kimi_k3(config) -> bool: ) +def uses_kda_attention(config) -> bool: + configs = [config] + get_text_config = getattr(config, "get_text_config", None) + if callable(get_text_config): + configs.append(get_text_config()) + else: + text_config = _hf_attr(config, "text_config") + if text_config is not None: + configs.append(text_config) + for config in configs: + linear_attn_config = _hf_attr(config, "linear_attn_config") + if isinstance(linear_attn_config, dict) and linear_attn_config.get( + "kda_layers" + ): + return True + layer_types = _hf_attr(config, "layer_types") or [] + if ( + "linear_attention" in layer_types + and _hf_attr(config, "linear_num_heads") is not None + and _hf_attr(config, "linear_head_dim") is not None + ): + return True + return False + + def is_dspark_draft(config) -> bool: return _hf_arch(config) == "DSparkDraftModel" @@ -250,6 +277,26 @@ def get_dsa_index_n_heads(config: PretrainedConfig) -> int: return config.index_n_heads +def get_dsa_index_kpool(config: PretrainedConfig) -> int: + return getattr(config, "index_kpool", 1) + + +def get_dsa_mtp_topk_width(config: PretrainedConfig) -> int: + """Return the physical index width carried by DSA MTP IndexShare. + + KPool selects ``index_topk`` history tokens and appends the unpooled tail, + whose maximum width is ``index_kpool - 1``. Seed buffers must preserve + both parts so their shape matches the indexer's output. + """ + index_kpool = get_dsa_index_kpool(config) + assert index_kpool >= 1, f"index_kpool must be positive, got {index_kpool}" + return get_dsa_index_topk(config) + index_kpool - 1 + + +def get_dsa_index_kpool_compress(config: PretrainedConfig) -> bool: + return getattr(config, "index_kpool_compress", False) + + REQUANTIZATION_METHODS = ["quark_mxfp4"] @@ -681,6 +728,15 @@ def _config_draft_model(self): ): self.hf_config.architectures[0] = "Glm4MoeLiteForCausalLMNextN" + if ( + is_draft_model + and self.hf_config.architectures[0] == "Glm5NextForConditionalGeneration" + ): + self.hf_config.architectures[0] = "Glm5NextForConditionalGenerationNextN" + self.hf_text_config.architectures = list(self.hf_config.architectures) + self.hf_text_config.num_nextn_predict_layers = 1 + self.hf_text_config.linear_attn_config = None + if is_draft_model and self.hf_config.architectures[0] in [ "GlmOcrForConditionalGeneration", ]: @@ -913,6 +969,8 @@ def _derive_model_shapes(self): or "Glm4MoeLiteForCausalLMNextN" in self.hf_config.architectures or "GlmMoeDsaForCausalLM" in self.hf_config.architectures or "GlmMoeDsaForCausalLMNextN" in self.hf_config.architectures + or "Glm5NextForConditionalGeneration" in self.hf_config.architectures + or "Glm5NextForConditionalGenerationNextN" in self.hf_config.architectures or "LongcatFlashForCausalLM" in self.hf_config.architectures or "LongcatFlashForCausalLMNextN" in self.hf_config.architectures or "DotsVLMForCausalLM" in self.hf_config.architectures @@ -1015,7 +1073,10 @@ def _derive_model_shapes(self): self.qk_rope_head_dim = self.hf_text_config.qk_rope_head_dim self.v_head_dim = self.hf_config.v_head_dim self._init_mla_scaling(self.hf_config.rope_scaling) - elif "SarvamMLAForCausalLM" in self.hf_config.architectures: + elif ( + "SarvamMLAForCausalLM" in self.hf_config.architectures + or "Glm5NextForConditionalGeneration" in self.hf_config.architectures + ): self.head_dim = ( self.hf_config.qk_nope_head_dim + self.hf_config.qk_rope_head_dim ) @@ -1068,12 +1129,21 @@ def _derive_model_shapes(self): self.num_key_value_heads = self.num_attention_heads self.hidden_size = self.hf_text_config.hidden_size hc_mult = getattr(self.hf_text_config, "hc_mult", 1) - self.spec_hidden_size = ( - self.hidden_size * hc_mult if hc_mult > 1 else self.hidden_size - ) + if ( + getattr(self.hf_config, "model_type", None) == "glm5_next" + or getattr(self.hf_text_config, "model_type", None) == "glm5_next_text" + ) and not getattr(self.hf_text_config, "mhc", False): + hc_mult = 1 # mHC-flattened hidden size; None when not running an mHC model # (e.g. non-DeepSeek-V4 configs without ``hc_mult``). - self.hc_hidden_size = self.spec_hidden_size if hc_mult > 1 else None + self.hc_hidden_size = self.hidden_size * hc_mult if hc_mult > 1 else None + if hc_mult > 1 and not ( + getattr(self.hf_config, "model_type", None) == "glm5_next" + or getattr(self.hf_text_config, "model_type", None) == "glm5_next_text" + ): + self.spec_hidden_size = self.hidden_size * hc_mult + else: + self.spec_hidden_size = self.hidden_size self.num_hidden_layers = self.hf_text_config.num_hidden_layers self.num_attention_layers = self.num_hidden_layers if "LongcatFlashForCausalLM" in self.hf_config.architectures: @@ -1869,6 +1939,7 @@ def is_generation_model(model_architectures: List[str], is_embedding: bool = Fal "Gemma4UnifiedForConditionalGeneration", "Glm4vForConditionalGeneration", "Glm4vMoeForConditionalGeneration", + "Glm5NextForConditionalGeneration", "GlmOcrForConditionalGeneration", "GlmAsrForConditionalGeneration", "GlmImageForConditionalGeneration", @@ -1936,6 +2007,7 @@ def is_generation_model(model_architectures: List[str], is_embedding: bool = Fal "DeepseekV4ForCausalLMNextN", "DeepseekV4ForCausalLMDSpark", "Qwen3NextForCausalLM", + "Glm5NextForConditionalGeneration", "BailingMoeV2_5ForCausalLM", "LLaDAModelLM", ] diff --git a/python/sglang/srt/configs/qwen3_asr.py b/python/sglang/srt/configs/qwen3_asr.py index cb3252b3d47cc..bf2ce3a074251 100644 --- a/python/sglang/srt/configs/qwen3_asr.py +++ b/python/sglang/srt/configs/qwen3_asr.py @@ -164,5 +164,5 @@ def get_text_config(self, decoder=False) -> PretrainedConfig: return self.thinker_config.text_config -AutoConfig.register("qwen3_asr", Qwen3ASRConfig) -AutoConfig.register("qwen3_asr_thinker", Qwen3ASRThinkerConfig) +AutoConfig.register("qwen3_asr", Qwen3ASRConfig, exist_ok=True) +AutoConfig.register("qwen3_asr_thinker", Qwen3ASRThinkerConfig, exist_ok=True) diff --git a/python/sglang/srt/disaggregation/base/conn.py b/python/sglang/srt/disaggregation/base/conn.py index 1dedb16ebed6f..a09daafebc710 100644 --- a/python/sglang/srt/disaggregation/base/conn.py +++ b/python/sglang/srt/disaggregation/base/conn.py @@ -18,6 +18,9 @@ class StateType(str, enum.Enum): MAMBA = "mamba" SWA = "swa" DSA = "dsa" + # DSA kpool-compress tail: one per-request ring row. The indices encode + # only the live subrange of that row for the current open pool. + DSA_TAIL = "dsa_tail" MINIMAX_INDEX_K = "minimax_index_k" # DeepSeek-V4 unified_kv SWA ring: addressed per-row by ring slot # (req_pool_idx * ring_stride + pos % ring_stride), needs its own component. diff --git a/python/sglang/srt/disaggregation/decode.py b/python/sglang/srt/disaggregation/decode.py index e49da8ee44736..976ebb7a371f0 100644 --- a/python/sglang/srt/disaggregation/decode.py +++ b/python/sglang/srt/disaggregation/decode.py @@ -51,6 +51,7 @@ ReqToMetadataIdxAllocator, TransferBackend, _is_fake_transfer, + get_dsa_tail_state_indices, get_dsv4_c128_state_indices, get_kv_class, is_dsv4_c128_online_enabled, @@ -1090,6 +1091,12 @@ def pop_preallocated( preallocated_reqs = [] indices_to_remove = set() + # The all-waiting shortcut stops receiver polling, so enforce its timeout here. + prealloc_timeout = float( + getattr(getattr(self, "kv_manager", None), "waiting_timeout", 0.0) + ) + prealloc_now = time.perf_counter() + # We need to make sure that the sum of inflight tokens and allocatable tokens is greater than maximum input+output length of each inflight request # Otherwise it is possible for one request running decode out of memory, while all other requests are in the transfer queue that cannot be retracted. retractable_tokens = sum( @@ -1125,16 +1132,48 @@ def pop_preallocated( ) self.queue.sort(key=lambda r: r.req.priority * priority_sign) - # First, remove all failed requests from the queue + # First, remove all failed or timed-out requests from the queue. for i, decode_req in enumerate(self.queue): if rids_to_check is not None and decode_req.req.rid not in rids_to_check: continue + + bootstrap_done_time = getattr( + getattr(decode_req.req, "time_stats", None), + "bootstrap_done_time", + 0.0, + ) + prealloc_timed_out = ( + not isinstance(decode_req.req.finished_reason, FINISH_ABORT) + and prealloc_timeout > 0 + and getattr(decode_req, "waiting_for_input", False) + and bootstrap_done_time > 0 + and prealloc_now - bootstrap_done_time > prealloc_timeout + ) + if prealloc_timed_out: + elapsed = prealloc_now - bootstrap_done_time + error_message = ( + f"Decode preallocation timed out after {elapsed:.1f}s " + f"(timeout={prealloc_timeout:.1f}s) for request " + f"rank={self.tp_rank} {decode_req.req.rid=} " + f"{decode_req.req.bootstrap_room=}" + ) + logger.error(error_message) + prepare_abort( + decode_req.req, + error_message, + status_code=HTTPStatus.GATEWAY_TIMEOUT, + ) + if self.scheduler.metrics_reporter.enable_metrics: + self.scheduler.metrics_collector.increment_prealloc_failed_reqs() + if isinstance(decode_req.req.finished_reason, FINISH_ABORT): if not getattr(decode_req.req, "finished_output", False): self.scheduler.output_streamer.stream_output( [decode_req.req], decode_req.req.return_logprob, ) + if prealloc_timed_out: + decode_req.kv_receiver.abort() decode_req.kv_receiver.clear() decode_req.kv_receiver = None failed_reqs.append(decode_req) @@ -1406,6 +1445,13 @@ def _full_kv_pages_payload(): device_page_size = self.token_to_kv_pool.page_size return kv_to_page_indices(kv_indices_full, device_page_size) + def _dsa_tail_payload(): + return get_dsa_tail_state_indices( + self.token_to_kv_pool, + decode_req.req.req_pool_idx, + seq_len, + ) + def _swa_ring_payload(): # Mirror of prefill _swa_ring_payload using this side's req_pool_idx. # Same window positions and order -> positional match with prefill. @@ -1438,6 +1484,7 @@ def _c128_state_payload(): StateType.MAMBA: _mamba_payload, StateType.SWA: _swa_payload, StateType.DSA: _full_kv_pages_payload, + StateType.DSA_TAIL: _dsa_tail_payload, StateType.MINIMAX_INDEX_K: _full_kv_pages_payload, StateType.SWA_RING: _swa_ring_payload, StateType.C128_STATE: _c128_state_payload, diff --git a/python/sglang/srt/disaggregation/encoder/preprocessor.py b/python/sglang/srt/disaggregation/encoder/preprocessor.py index bd6d3f06e8478..cd1308876cd23 100644 --- a/python/sglang/srt/disaggregation/encoder/preprocessor.py +++ b/python/sglang/srt/disaggregation/encoder/preprocessor.py @@ -11,6 +11,7 @@ import functools import logging from dataclasses import dataclass +from http import HTTPStatus from typing import Callable, List, Optional, Tuple, Union import numpy as np @@ -18,6 +19,11 @@ from transformers import AutoProcessor from sglang.srt.configs.model_config import ModelConfig +from sglang.srt.distributed.parallel_state import ( + get_attn_tensor_model_parallel_rank, + get_attn_tensor_model_parallel_world_size, + get_attn_tp_group, +) from sglang.srt.environ import envs from sglang.srt.managers.schedule_batch import Modality from sglang.srt.multimodal.cache import parse_content_hash, snapshot_media @@ -26,6 +32,17 @@ EncoderPreprocessOutput, invoke_encoder_preprocessor, ) +from sglang.srt.multimodal.processors.glm4v import ( + _glm_effective_presize_budget, + glm_budget_kwargs, + glm_decode_frames_at, + glm_max_image_tokens_from_configs, + glm_processor_video_config, + glm_sample_and_decode_sync, + glm_sample_frame_indices, + preprocess_video_frames_sync, + split_glm_video_items, +) from sglang.srt.multimodal.processors.qwen_vl import preprocess_video from sglang.srt.runtime_context import ( get_device, @@ -220,9 +237,12 @@ def _build_vision_config(self, mm_process_config): self.vision_config[modality_str]["device"] = self.device if modality_str == "video": - video_defaults = {"fps": 2.0, "max_frames": 768, "min_frames": 4} - for k, v in video_defaults.items(): - self.vision_config["video"].setdefault(k, v) + # GLM reads its own defaults from the HF video processor + # (max_frames=2048); applying the Qwen values here would clobber them. + if "glm" not in self.model_type: + video_defaults = {"fps": 2.0, "max_frames": 768, "min_frames": 4} + for k, v in video_defaults.items(): + self.vision_config["video"].setdefault(k, v) if modality_str == "audio": if "return_attention_mask" not in self.vision_config["audio"]: @@ -334,7 +354,17 @@ def _load_single_item( } return img elif modality == Modality.VIDEO: - return load_video(data, frame_count_limit) + vid = load_video(data, frame_count_limit) + if ( + media_metadata + and self.encoder_media_processor_config.preserve_media_metadata + ): + return { + "type": "video", + "video": vid, + **media_metadata, + } + return vid elif modality == Modality.AUDIO: return load_audio(data, self.model_audio_sr) @@ -399,10 +429,110 @@ async def _flatten_and_load_data_by_modality(self, mm_items, modality): async def _flatten_and_load_images(self, mm_items): return await self._flatten_and_load_data_by_modality(mm_items, Modality.IMAGE) + @staticmethod + def _close_video_decoders(video_items) -> None: + for video in video_items or []: + close = getattr(video, "close", None) + if callable(close): + close() + + async def _dp_sharded_decode_single_video( + self, + vr, + video_config, + *, + tp_rank: int, + tp_size: int, + video_processor_kwargs: dict, + precomputed_indices: Optional[List[int]] = None, + ): + """Decode and preprocess only this encoder rank's temporal units.""" + video_config = video_config or {} + video_fps = vr.avg_fps + duration = len(vr) / video_fps if video_fps else 0 + global_indices = precomputed_indices or glm_sample_frame_indices( + len(vr), + video_fps, + duration, + target_fps=video_config.get("fps"), + max_frame_count=video_config.get("max_frames"), + ) + n_units = len(global_indices) // 2 + base, remainder = divmod(n_units, tp_size) + gpu_sample_counts = [ + base + (1 if rank < remainder else 0) for rank in range(tp_size) + ] + start = sum(gpu_sample_counts[:tp_rank]) + count = gpu_sample_counts[tp_rank] + local_indices = global_indices[2 * start : 2 * (start + count)] + + local_error = None + frames = None + try: + frames = await asyncio.get_running_loop().run_in_executor( + self.io_executor, + glm_decode_frames_at, + vr, + local_indices, + video_config, + ) + except Exception as exc: + local_error = exc + + # All ranks must either enter the later ViT all-gather or fail before + # it. A rank-local decoder error must therefore be agreed globally. + ok = torch.tensor([0 if local_error else 1], dtype=torch.int32) + if tp_size > 1: + torch.distributed.all_reduce( + ok, + op=torch.distributed.ReduceOp.MIN, + group=get_attn_tp_group().cpu_group, + ) + if not int(ok.item()): + if local_error is not None: + raise local_error + from sglang.srt.disaggregation.encoder.server import MMError + + raise MMError( + "peer encoder rank failed during sharded video decode", + code=HTTPStatus.SERVICE_UNAVAILABLE, + ) + if frames is None: + height, width = vr.frame_shape + frames = np.zeros((0, height, width, 3), dtype=np.uint8) + + video_processor_kwargs["do_sample_frames"] = False + video_processor_kwargs["return_metadata"] = True + # Preserve the same per-frame spatial budget as the unsharded request. + if global_indices and local_indices: + budget = video_config.get("max_image_tokens") + if budget is None: + budget = getattr(self.video_processor, "max_image_tokens", None) + if budget is not None: + video_processor_kwargs["max_image_tokens"] = max( + 1, int(int(budget) * len(local_indices) / len(global_indices)) + ) + video_processor_kwargs["_dp_meta"] = { + "global_indices": list(global_indices), + "fps": video_fps, + "n_units": n_units, + "gpu_sample_counts": gpu_sample_counts, + } + return [frames], video_processor_kwargs + async def _flatten_and_load_videos(self, mm_items): if not isinstance(mm_items, (list, tuple)): mm_items = [mm_items] + video_configs = [{} for _ in mm_items] + if "glm" in self.model_type: + mm_items, video_configs = split_glm_video_items(mm_items) + defaults = glm_processor_video_config(self.video_processor) + defaults.update(self.vision_config.get("video", {})) + video_configs = [ + {**defaults, **dict(config or {})} for config in video_configs + ] + futures, _ = self._submit_data_loading_tasks( mm_items, [Modality.VIDEO] * len(mm_items) ) @@ -422,10 +552,88 @@ async def _flatten_and_load_videos(self, mm_items): if video_metadata: video_processor_kwargs["video_metadata"] = video_metadata return videos, video_processor_kwargs - else: - raise NotImplementedError( - f"Video processing is not supported for {self.model_type} model." + + if "glm" in self.model_type: + budget_kwargs = glm_budget_kwargs( + self.video_processor, + user_max_image_tokens=glm_max_image_tokens_from_configs(video_configs), + count=len(video_items), + split=True, ) + if budget_kwargs is not None: + video_processor_kwargs.update(budget_kwargs) + video_configs = [ + _glm_effective_presize_budget( + config, budget_kwargs.get("max_image_tokens") + ) + for config in video_configs + ] + + framed = any(isinstance(video, list) for video in video_items) + if framed: + processed = await asyncio.gather( + *[ + asyncio.get_running_loop().run_in_executor( + self.io_executor, preprocess_video_frames_sync, video + ) + for video in video_items + ] + ) + else: + tp_size = get_attn_tensor_model_parallel_world_size() + sampled = None + if len(video_items) == 1: + vr = video_items[0] + config = video_configs[0] + sampled = glm_sample_frame_indices( + len(vr), + vr.avg_fps, + len(vr) / vr.avg_fps if vr.avg_fps else 0, + target_fps=config.get("fps"), + max_frame_count=config.get("max_frames"), + ) + # The static threshold intentionally keeps small videos on the + # simpler path; only large single videos need decode sharding. + if ( + self.server_args.mm_enable_dp_encoder + and tp_size > 1 + and sampled is not None + and len(sampled) >= max(32, tp_size * 2) + ): + result = await self._dp_sharded_decode_single_video( + video_items[0], + video_configs[0], + tp_rank=get_attn_tensor_model_parallel_rank(), + tp_size=tp_size, + video_processor_kwargs=video_processor_kwargs, + precomputed_indices=sampled, + ) + self._close_video_decoders(video_items) + return result + + processed = await asyncio.gather( + *[ + asyncio.get_running_loop().run_in_executor( + self.io_executor, + glm_sample_and_decode_sync, + video, + video_configs[index], + ) + for index, video in enumerate(video_items) + ] + ) + videos, video_metadata = map(list, zip(*processed)) + video_processor_kwargs["do_sample_frames"] = False + video_processor_kwargs["return_metadata"] = True + if video_metadata: + video_processor_kwargs["video_metadata"] = video_metadata + self._close_video_decoders(video_items) + return videos, video_processor_kwargs + + self._close_video_decoders(video_items) + raise NotImplementedError( + f"Video processing is not supported for {self.model_type} model." + ) async def _flatten_and_load_audios(self, mm_items): return await self._flatten_and_load_data_by_modality(mm_items, Modality.AUDIO) diff --git a/python/sglang/srt/disaggregation/encoder/receiver.py b/python/sglang/srt/disaggregation/encoder/receiver.py index ace0bcd8da19d..2fb927f13c9d3 100644 --- a/python/sglang/srt/disaggregation/encoder/receiver.py +++ b/python/sglang/srt/disaggregation/encoder/receiver.py @@ -1888,6 +1888,7 @@ async def recv_mm_data( self, request_obj, mm_processor, prompt, need_wait_for_mm_inputs=True ): req_id = None + encode_task = None try: # ``self.encode_urls`` is shared by reference with the bootstrap # server (when running) so it always reflects the current set. @@ -1950,7 +1951,21 @@ async def recv_mm_data( except asyncio.TimeoutError: elapsed = time.monotonic() - send_time logger.warning(f"[{req_id}] Embedding recv timeout after {elapsed:.3f}s") + await self._abort_encode_and_cleanup(encode_task, req_id) return None + except asyncio.CancelledError: + await self._abort_encode_and_cleanup(encode_task, req_id) + raise + + async def _abort_encode_and_cleanup(self, encode_task, req_id): + if encode_task is not None and not encode_task.done(): + encode_task.cancel() + try: + await encode_task + except (asyncio.CancelledError, Exception): + pass + if req_id is not None: + self._cleanup_mooncake_buffer(req_id) async def _recv_mm_data(self, req_id, recv_socket, mm_processor, prompt): """zmq_to_tokenizer receive: embedding parts arrive as 2-frame ZMQ diff --git a/python/sglang/srt/disaggregation/mooncake/conn.py b/python/sglang/srt/disaggregation/mooncake/conn.py index 1c0955653e8c6..457f88fdcdf37 100644 --- a/python/sglang/srt/disaggregation/mooncake/conn.py +++ b/python/sglang/srt/disaggregation/mooncake/conn.py @@ -46,9 +46,12 @@ ) from sglang.srt.disaggregation.utils import ( DisaggregationMode, + build_dsa_tail_transfer_blocks, build_transfer_entry_pairs, compute_mamba_state_slice_byte_blocks, resolve_dcp_dst_entry_indices, + should_send_aux_metadata, + slice_dsa_tail_dst_ptrs_for_pp, ) from sglang.srt.distributed.parallel_state import get_mooncake_transfer_engine from sglang.srt.environ import envs @@ -1334,10 +1337,25 @@ def maybe_send_extra( ) or rc ) + elif st == StateType.DSA_TAIL: + rc = ( + self._send_slot_state( + req, + src_data_ptrs, + src_item_lens, + dst_data_ptrs, + dst_item_lens, + list(indices), + list(dst_indices), + st.value, + ) + or rc + ) elif self._is_generic_kvcache_state_type(st): if ( target_rank_registration_info is not None and not self.is_mla_backend + and not self.is_hybrid_mla_backend and self.attn_tp_size != target_rank_registration_info.dst_attn_tp_size ): @@ -1419,6 +1437,43 @@ def maybe_send_extra( ) return rc + def _send_slot_state( + self, + req: TransferInfo, + src_ptrs: list[int], + src_item_lens: list[int], + dst_ptrs: list[int], + dst_item_lens: list[int], + src_indices: list[int], + dst_indices: list[int], + label: str, + ) -> int: + try: + dst_ptrs = slice_dsa_tail_dst_ptrs_for_pp( + src_ptrs, + dst_ptrs, + self.kv_args.prefill_start_layer, + getattr(self.kv_args, "prefill_end_layer", None), + ) + dst_item_lens = slice_dsa_tail_dst_ptrs_for_pp( + src_ptrs, + dst_item_lens, + self.kv_args.prefill_start_layer, + getattr(self.kv_args, "prefill_end_layer", None), + ) + transfer_blocks = build_dsa_tail_transfer_blocks( + src_ptrs, + src_item_lens, + dst_ptrs, + src_indices, + dst_indices, + dst_item_lens, + ) + except ValueError as exc: + logger.error("%s: %s", label, exc) + return -1 + return self._transfer_data(req.mooncake_session_id, transfer_blocks) + def _send_mamba_state( self, req: TransferInfo, @@ -1477,7 +1532,8 @@ def _send_mamba_state_slice( attn_tp_size, we slice the state accordingly. GDN conv_state is the concatenation [query | key | value] with each sub-block head-sharded independently, so on the scatter path it is sliced per sub-block via - ``src_state_conv_shard_groups`` (see compute_mamba_state_slice_blocks). + ``src_state_conv_shard_groups`` (see + compute_mamba_state_slice_byte_blocks). """ logger.warning_once( "Using Mamba state slice transfer for different TP sizes between prefill and decode. " @@ -1842,12 +1898,20 @@ def transfer_worker( ) break - # Only the last chunk we need to send the aux data - ret = self.send_aux( - req, - kv_chunk.prefill_aux_index, - target_rank_registration_info.dst_aux_ptrs, - ) + if should_send_aux_metadata( + attn_cp_rank=self.attn_cp_rank, + prefill_attn_tp_size=self.attn_tp_size, + prefill_attn_tp_rank=self.attn_tp_rank, + decode_attn_tp_size=target_rank_registration_info.dst_attn_tp_size, + decode_attn_tp_rank=target_rank_registration_info.dst_tp_rank, + ): + ret = self.send_aux( + req, + kv_chunk.prefill_aux_index, + target_rank_registration_info.dst_aux_ptrs, + ) + else: + ret = 0 polls.append(True if ret == 0 else False) dst_ranks_infos.append( (req.endpoint, req.dst_port, req.room) diff --git a/python/sglang/srt/disaggregation/nixl/conn.py b/python/sglang/srt/disaggregation/nixl/conn.py index f72fb25fc97f7..8ee7e5f63870c 100644 --- a/python/sglang/srt/disaggregation/nixl/conn.py +++ b/python/sglang/srt/disaggregation/nixl/conn.py @@ -41,9 +41,13 @@ ) from sglang.srt.disaggregation.utils import ( DisaggregationMode, + build_dsa_tail_transfer_blocks, build_transfer_entry_pairs, compute_mamba_state_slice_byte_blocks, resolve_dcp_dst_entry_indices, + resolve_linear_state_shards, + should_send_aux_metadata, + slice_dsa_tail_dst_ptrs_for_pp, ) from sglang.srt.environ import envs from sglang.srt.runtime_context import get_parallel, get_schedule @@ -1295,14 +1299,29 @@ def transfer_worker(self, queue: FastQueue, staging_buffer=None): f"_nokv_{self.transfer_source_rank}" f"_{kv_chunk.chunk_id}" ) - aux_xfer_handle = self.send_aux( - req.agent_name, - kv_chunk.prefill_aux_index, - dst_info.dst_aux_ptrs, - req.dst_aux_index, - aux_notif, - ) - handles.append(aux_xfer_handle) + if should_send_aux_metadata( + attn_cp_rank=self.attn_cp_rank, + prefill_attn_tp_size=self.attn_tp_size, + prefill_attn_tp_rank=self.attn_tp_rank, + decode_attn_tp_size=decode_tp_size, + decode_attn_tp_rank=dst_info.decode_tp_rank, + ): + aux_xfer_handle = self.send_aux( + req.agent_name, + kv_chunk.prefill_aux_index, + dst_info.dst_aux_ptrs, + req.dst_aux_index, + aux_notif, + ) + handles.append(aux_xfer_handle) + else: + # The payload is request-global and another source + # rank writes it. Keep this source rank's no-KV + # accounting/completion notification without + # racing that shared destination slot. + self.agent.send_notif( + req.agent_name, aux_notif.encode("ascii") + ) if staging_deferred: # Chunk has been re-enqueued; do not advance status. @@ -2023,6 +2042,60 @@ def send_aux( raise Exception("KVSender failed to post transfer") return xfer_handle + def _send_slot_state( + self, + peer_name: str, + src_data_ptrs: list[int], + src_item_lens: list[int], + dst_data_ptrs: list[int], + dst_item_lens: list[int], + src_indices: list[int], + dst_indices: list[int], + dst_gpu_id: int, + notif: str, + ): + dst_data_ptrs = slice_dsa_tail_dst_ptrs_for_pp( + src_data_ptrs, + dst_data_ptrs, + self.kv_args.prefill_start_layer, + getattr(self.kv_args, "prefill_end_layer", None), + ) + dst_item_lens = slice_dsa_tail_dst_ptrs_for_pp( + src_data_ptrs, + dst_item_lens, + self.kv_args.prefill_start_layer, + getattr(self.kv_args, "prefill_end_layer", None), + ) + transfer_blocks = build_dsa_tail_transfer_blocks( + src_data_ptrs, + src_item_lens, + dst_data_ptrs, + src_indices, + dst_indices, + dst_item_lens, + ) + if not transfer_blocks: + return None + + src_addrs = [ + (src_addr, length, self.kv_args.gpu_id) + for src_addr, _, length in transfer_blocks + ] + dst_addrs = [ + (dst_addr, length, dst_gpu_id) for _, dst_addr, length in transfer_blocks + ] + src_descs = self.agent.get_xfer_descs(src_addrs, "VRAM") + dst_descs = self.agent.get_xfer_descs(dst_addrs, "VRAM") + xfer_handle = self.agent.initialize_xfer( + "WRITE", src_descs, dst_descs, peer_name, notif.encode("ascii") + ) + if not xfer_handle: + raise Exception("KVSender failed to create dsa_tail transfer") + state = self.agent.transfer(xfer_handle) + if state == "ERR": + raise Exception("KVSender failed to post dsa_tail transfer") + return xfer_handle + def _send_mamba_state( self, peer_name: str, @@ -2092,8 +2165,10 @@ def _send_mamba_state_slice( dst_state_dim_per_tensor: list[int], dst_gpu_id: int, notif: str, - decode_tp_size: int, - decode_tp_rank: int, + src_shard_size: int, + src_shard_rank: int, + dst_shard_size: int, + dst_shard_rank: int, src_state_conv_shard_groups: list = None, src_state_slice_outer_counts: list[int] = None, src_layer_ids: list[int] = None, @@ -2101,17 +2176,18 @@ def _send_mamba_state_slice( ): """Transfer Mamba states with TP slice support via RDMA. - When prefill and decode have different attn_tp_size, we slice the - TP-sharded dimension (3rd dim) of conv_state and temporal_state - accordingly, mirroring Mooncake's _send_mamba_state_slice. GDN + When prefill and decode have different head-shard sizes, we slice the + sharded dimension (3rd dim) of conv_state and temporal_state + accordingly. The source shard can be Prefill attention TP or CP. GDN conv_state is [query | key | value] with each sub-block head-sharded independently, so on the scatter path it is sliced per sub-block via - ``src_state_conv_shard_groups`` (see compute_mamba_state_slice_blocks). + ``src_state_conv_shard_groups`` (see + compute_mamba_state_slice_byte_blocks). """ logger.warning_once( - "Using Mamba state slice transfer for different TP sizes. " - f"Prefill attn_tp_size={self.attn_tp_size}, " - f"Decode attn_tp_size={decode_tp_size}." + "Using Mamba state slice transfer for different head-shard sizes. " + f"Prefill shard_size={src_shard_size}, " + f"Decode shard_size={dst_shard_size}." ) assert len(prefill_state_indices) == 1, "Mamba should have single state index" @@ -2129,9 +2205,6 @@ def _send_mamba_state_slice( dst_layer_ids=dst_layer_ids, ) - local_tp_rank_in_group = self.kv_args.engine_rank % self.attn_tp_size - dst_tp_rank_in_group = decode_tp_rank % decode_tp_size - src_addrs = [] dst_addrs = [] @@ -2172,10 +2245,10 @@ def _send_mamba_state_slice( src_dim=src_dim, dst_dim=dst_dim, outer_count=outer_count, - src_attn_tp_size=self.attn_tp_size, - dst_attn_tp_size=decode_tp_size, - dst_tp_rank_in_group=dst_tp_rank_in_group, - local_tp_rank_in_group=local_tp_rank_in_group, + src_attn_tp_size=src_shard_size, + dst_attn_tp_size=dst_shard_size, + dst_tp_rank_in_group=dst_shard_rank, + local_tp_rank_in_group=src_shard_rank, conv_shard_groups=conv_shard_groups, ): src_addr = ( @@ -2241,11 +2314,14 @@ def maybe_send_extra( dst_state_layer_ids = dst_state_layer_ids or [] handles = [] + skipped_replicated_state = False for i, st in enumerate(state_types): src_indices = ( prefill_state_indices[i] if i < len(prefill_state_indices) else None ) - if src_indices is None or len(src_indices) == 0: + if src_indices is None or ( + len(src_indices) == 0 and st != StateType.DSA_TAIL + ): continue src_ptrs = src_state_data_ptrs[i] if i < len(src_state_data_ptrs) else [] src_lens = src_state_item_lens[i] if i < len(src_state_item_lens) else [] @@ -2273,7 +2349,23 @@ def maybe_send_extra( comp_notif = f"{notif}_{i}" if st == StateType.MAMBA: - if self.attn_tp_size != decode_tp_size: + shard_mapping = resolve_linear_state_shards( + prefill_attn_tp_size=self.attn_tp_size, + prefill_attn_tp_rank=self.attn_tp_rank, + prefill_attn_cp_size=self.attn_cp_size, + prefill_attn_cp_rank=self.attn_cp_rank, + decode_attn_tp_size=decode_tp_size, + decode_tp_rank=decode_tp_rank, + ) + if shard_mapping is None: + h = None + elif shard_mapping[0] != shard_mapping[2]: + ( + src_shard_size, + src_shard_rank, + dst_shard_size, + dst_shard_rank, + ) = shard_mapping h = self._send_mamba_state_slice( peer_name, src_indices, @@ -2286,10 +2378,12 @@ def maybe_send_extra( dst_dims, dst_gpu_id, comp_notif, - decode_tp_size, - decode_tp_rank, - src_conv, - src_outer_counts, + src_shard_size=src_shard_size, + src_shard_rank=src_shard_rank, + dst_shard_size=dst_shard_size, + dst_shard_rank=dst_shard_rank, + src_state_conv_shard_groups=src_conv, + src_state_slice_outer_counts=src_outer_counts, src_layer_ids=src_lids, dst_layer_ids=dst_lids, ) @@ -2306,12 +2400,53 @@ def maybe_send_extra( src_layer_ids=src_lids, dst_layer_ids=dst_lids, ) - elif st in ( - StateType.SWA, - StateType.DSA, - StateType.SWA_RING, - StateType.C128_STATE, - ): + elif st == StateType.DSA_TAIL: + if ( + self.attn_cp_size > 1 + and self.attn_cp_rank != 0 + and not self.server_args.enable_dsa_cache_layer_split + ): + skipped_replicated_state = True + h = None + else: + h = self._send_slot_state( + peer_name, + src_ptrs, + src_lens, + dst_ptrs, + dst_lens, + list(src_indices), + list(dst_indices), + dst_gpu_id, + comp_notif, + ) + elif st == StateType.DSA: + if ( + self.attn_cp_size > 1 + and self.attn_cp_rank != 0 + and not self.server_args.enable_dsa_cache_layer_split + ): + skipped_replicated_state = True + h = None + else: + if len(src_indices) != len(dst_indices): + raise RuntimeError( + f"State index length mismatch at component {i}: " + f"prefill={len(src_indices)}, dst={len(dst_indices)}" + ) + h = self._send_kvcache_generic( + peer_name=peer_name, + src_data_ptrs=src_ptrs, + dst_data_ptrs=dst_ptrs, + item_lens=src_lens, + prefill_data_indices=np.array(src_indices, dtype=np.int32), + dst_data_indices=np.array(dst_indices, dtype=np.int32), + dst_gpu_id=dst_gpu_id, + notif=comp_notif, + state_type=st, + force_flat=True, + ) + elif st in (StateType.SWA, StateType.SWA_RING, StateType.C128_STATE): if not self.is_mla_backend and self.attn_tp_size != decode_tp_size: raise RuntimeError( f"PD Disaggregation does NOT support PD different TP sizes for non-MLA {st.upper()} hybrid models yet." @@ -2372,6 +2507,11 @@ def maybe_send_extra( ) if h is not None: handles.append(h) + if skipped_replicated_state and not handles: + # Decode waits for one state notification from every connected + # Prefill source rank. A non-owner CP rank has no bytes to write, + # but it must still satisfy that completion barrier. + self.agent.send_notif(peer_name, f"{notif}_marker".encode("ascii")) return handles def add_transfer_request( diff --git a/python/sglang/srt/disaggregation/prefill.py b/python/sglang/srt/disaggregation/prefill.py index a4e18be31aaff..2576b29ff2021 100644 --- a/python/sglang/srt/disaggregation/prefill.py +++ b/python/sglang/srt/disaggregation/prefill.py @@ -43,6 +43,7 @@ MetadataBuffers, ReqToMetadataIdxAllocator, TransferBackend, + get_dsa_tail_state_indices, get_dsv4_c128_state_indices, get_kv_class, is_aborted, @@ -836,6 +837,7 @@ def advance_logprob_pt(i: int, req: Req) -> None: can_run_cuda_graph=can_run_cuda_graph, dp_cooperation_info=batch.dp_cooperation_info, ) + self.maybe_send_health_check_signal() def process_disagg_prefill_inflight_queue( self: Scheduler, rids_to_check: Optional[List[str]] = None @@ -1210,6 +1212,13 @@ def _full_kv_pages_payload(): ] return kv_to_page_indices(kv_indices_full, page_size) + def _dsa_tail_payload(): + return get_dsa_tail_state_indices( + self.token_to_kv_pool_allocator.get_kvcache(), + req.req_pool_idx, + seq_len, + ) + def _swa_ring_payload(): # Unified_kv SWA ring rows (req_pool_idx*ring_stride + pos%ring_stride) # for the last `window` positions, in ascending position order so @@ -1246,6 +1255,7 @@ def _c128_state_payload(): StateType.MAMBA: _mamba_payload, StateType.SWA: _swa_payload, StateType.DSA: _full_kv_pages_payload, + StateType.DSA_TAIL: _dsa_tail_payload, StateType.MINIMAX_INDEX_K: _full_kv_pages_payload, StateType.SWA_RING: _swa_ring_payload, StateType.C128_STATE: _c128_state_payload, diff --git a/python/sglang/srt/disaggregation/utils.py b/python/sglang/srt/disaggregation/utils.py index 09fd8efa944eb..fcbdcc6405399 100644 --- a/python/sglang/srt/disaggregation/utils.py +++ b/python/sglang/srt/disaggregation/utils.py @@ -19,7 +19,7 @@ import torch import torch.distributed as dist -from sglang.srt.configs.model_config import get_dsa_index_topk +from sglang.srt.configs.model_config import get_dsa_mtp_topk_width from sglang.srt.disaggregation.base import KVPoll from sglang.srt.environ import envs from sglang.srt.runtime_context import ( @@ -71,7 +71,28 @@ def get_dsa_seed_metadata_dim(hf_config) -> int: """Return the model-defined PD seed width, independent of local spec mode.""" if not getattr(hf_config, "index_share_for_mtp_iteration", False): return 0 - return get_dsa_index_topk(hf_config) + return get_dsa_mtp_topk_width(hf_config) + + +def should_send_aux_metadata( + *, + attn_cp_rank: int, + prefill_attn_tp_size: int, + prefill_attn_tp_rank: int, + decode_attn_tp_size: int, + decode_attn_tp_rank: int, +) -> bool: + """Select the sole prefill writer of request-global AUX metadata. + + KV and side-state payloads may be partitioned across CP ranks, but AUX + metadata is replicated and every sender targets the same decode-side slot. + Select CP rank zero and one prefill TP rank for each decode TP destination. + Non-writers must still send their normal completion notifications. + """ + primary_prefill_tp_rank = ( + decode_attn_tp_rank * prefill_attn_tp_size // decode_attn_tp_size + ) + return attn_cp_rank == 0 and prefill_attn_tp_rank == primary_prefill_tp_rank def is_dsv4_c128_online_enabled() -> bool: @@ -156,6 +177,16 @@ def decode_gate() -> bool: ) +def should_bypass_dsa_cp_prefix_cache(server_args) -> bool: + """Bypass prefix cache under DSA Prefill CP until CP-aware radix resharding + exists; without it, cache hits let attention read non-local page rows.""" + return ( + server_args.disaggregation_mode == DisaggregationMode.PREFILL.value + and server_args.attn_cp_size > 1 + and server_args.enable_dsa_prefill_context_parallel + ) + + ######################### # Synchronization ######################### @@ -822,6 +853,57 @@ def compute_mamba_state_slice_blocks( return blocks +def resolve_linear_state_shards( + *, + prefill_attn_tp_size: int, + prefill_attn_tp_rank: int, + prefill_attn_cp_size: int, + prefill_attn_cp_rank: int, + decode_attn_tp_size: int, + decode_tp_rank: int, +) -> Optional[Tuple[int, int, int, int]]: + """Select the linear-state source shard for one destination rank. Prefill + shards by attention CP (DSA Prefill CP) or attention TP; decode by + attention TP only. Returns ``None`` when the two ranks own disjoint head + ranges.""" + values = { + "prefill_attn_tp_size": prefill_attn_tp_size, + "prefill_attn_cp_size": prefill_attn_cp_size, + "decode_attn_tp_size": decode_attn_tp_size, + } + for name, value in values.items(): + if value <= 0: + raise ValueError(f"{name} must be positive, got {value}") + + if prefill_attn_cp_size > 1: + src_shard_size = prefill_attn_cp_size + src_shard_rank = prefill_attn_cp_rank + else: + src_shard_size = prefill_attn_tp_size + src_shard_rank = prefill_attn_tp_rank + dst_shard_size = decode_attn_tp_size + dst_shard_rank = decode_tp_rank % decode_attn_tp_size + + if not 0 <= src_shard_rank < src_shard_size: + raise ValueError( + f"Prefill linear-state shard rank {src_shard_rank} is outside " + f"[0, {src_shard_size})" + ) + if max(src_shard_size, dst_shard_size) % min(src_shard_size, dst_shard_size): + raise ValueError( + "Linear-state shard sizes must divide each other, got " + f"prefill={src_shard_size}, decode={dst_shard_size}" + ) + + if src_shard_size >= dst_shard_size: + overlaps = src_shard_rank * dst_shard_size // src_shard_size == dst_shard_rank + else: + overlaps = dst_shard_rank * src_shard_size // dst_shard_size == src_shard_rank + if not overlaps: + return None + return src_shard_size, src_shard_rank, dst_shard_size, dst_shard_rank + + def compute_mamba_state_slice_byte_blocks( *, src_item_len: int, @@ -963,6 +1045,197 @@ def append_state_component( kv_args.state_layer_ids.append(layer_ids or []) +def get_dsa_tail_state_indices(pool, req_pool_idx: int, seq_len: int) -> List[int]: + if getattr(pool, "use_dsa", False): + pool = pool.full_kv_pool + if not pool.kpool_use_compress: + return [] + + pool_size = int(pool.index_kpool) + tail_size = pool_size + int(getattr(pool, "tail_extra_slots", 0)) + if pool_size <= 1 or tail_size < pool_size: + raise ValueError( + "DSA kpool-compress requires pool_size > 1 and " + f"tail_size >= pool_size, got pool_size={pool_size}, " + f"tail_size={tail_size}" + ) + + n_valid = int(seq_len) % pool_size + if n_valid == 0: + return [] + start_phys = (int(seq_len) - n_valid) % tail_size + first_n = min(n_valid, tail_size - start_phys) + second_n = n_valid - first_n + return [ + int(req_pool_idx), + start_phys, + first_n, + 0, + second_n, + tail_size, + ] + + +def slice_dsa_tail_dst_ptrs_for_pp( + src_ptrs: List[int], + dst_ptrs: List[int], + start_layer: int, + end_layer: Optional[int], +) -> List[int]: + """Align ``[key layers..., score layers...]`` tail pointers across PP.""" + if len(src_ptrs) == len(dst_ptrs): + return list(dst_ptrs) + if len(src_ptrs) % 2 != 0 or len(dst_ptrs) % 2 != 0: + raise ValueError( + "DSA tail pointer lists must contain equal key/score halves, got " + f"src={len(src_ptrs)}, dst={len(dst_ptrs)}" + ) + + src_layers = len(src_ptrs) // 2 + dst_layers = len(dst_ptrs) // 2 + expected_end = start_layer + src_layers + if end_layer is not None and end_layer - start_layer == src_layers: + expected_end = end_layer + if start_layer < 0 or expected_end > dst_layers: + raise ValueError( + "DSA tail pointer count mismatch: " + f"src={len(src_ptrs)}, dst={len(dst_ptrs)}, " + f"prefill_layers=[{start_layer}, {expected_end})" + ) + + return list(dst_ptrs[start_layer:expected_end]) + list( + dst_ptrs[dst_layers + start_layer : dst_layers + expected_end] + ) + + +def build_dsa_tail_transfer_blocks( + src_ptrs: List[int], + src_item_lens: List[int], + dst_ptrs: List[int], + src_indices: List[int], + dst_indices: List[int], + dst_item_lens: Optional[List[int]] = None, +) -> List[Tuple[int, int, int]]: + """Build byte ranges for a request-scoped DSA tail ring transfer. + + The Prefill and Decode pools may reserve different numbers of speculative + tail slots. Preserve the logical token order while remapping between their + physical rings. + """ + if not src_indices and not dst_indices: + return [] + if not src_indices or not dst_indices: + raise ValueError( + f"DSA tail slot index missing: src={src_indices}, dst={dst_indices}" + ) + if len(src_indices) != 6 or len(dst_indices) != 6: + raise ValueError( + "DSA tail slot indices must be 6-tuples, " + f"got src={src_indices}, dst={dst_indices}" + ) + if dst_item_lens is None: + dst_item_lens = src_item_lens + if not (len(src_ptrs) == len(dst_ptrs) == len(src_item_lens) == len(dst_item_lens)): + raise ValueError( + "DSA tail pointer metadata mismatch: " + f"src_ptrs={len(src_ptrs)}, dst_ptrs={len(dst_ptrs)}, " + f"src_item_lens={len(src_item_lens)}, " + f"dst_item_lens={len(dst_item_lens)}" + ) + + src_tail_size = int(src_indices[5]) + dst_tail_size = int(dst_indices[5]) + if src_tail_size <= 0 or dst_tail_size <= 0: + raise ValueError( + "DSA tail ring sizes must be positive: " + f"src={src_tail_size}, dst={dst_tail_size}" + ) + + def parse_segments(indices: List[int], tail_size: int, side: str): + segments = [] + for seg in (1, 2): + off = int(indices[seg * 2 - 1]) + n = int(indices[seg * 2]) + if min(off, n) < 0: + raise ValueError( + f"DSA tail {side} offsets and lengths must be non-negative" + ) + if off + n > tail_size: + raise ValueError( + f"DSA tail {side} segment {seg} exceeds ring size " + f"{tail_size}: ({off}, {n})" + ) + if n: + segments.append((off, n)) + return segments + + src_segments = parse_segments(src_indices, src_tail_size, "source") + dst_segments = parse_segments(dst_indices, dst_tail_size, "destination") + src_count = sum(n for _, n in src_segments) + dst_count = sum(n for _, n in dst_segments) + if src_count != dst_count: + raise ValueError( + f"DSA tail live-token count mismatch: src={src_count}, dst={dst_count}" + ) + + src_idx = int(src_indices[0]) + dst_idx = int(dst_indices[0]) + if src_idx < 0 or dst_idx < 0: + raise ValueError("DSA tail request row indices must be non-negative") + + transfer_blocks = [] + for src_ptr, src_row_bytes, dst_ptr, dst_row_bytes in zip( + src_ptrs, src_item_lens, dst_ptrs, dst_item_lens + ): + src_row_bytes = int(src_row_bytes) + dst_row_bytes = int(dst_row_bytes) + if src_row_bytes == 0 and dst_row_bytes == 0: + continue + if src_row_bytes <= 0 or src_row_bytes % src_tail_size != 0: + raise ValueError( + f"DSA source tail row size {src_row_bytes} is not divisible by " + f"{src_tail_size}" + ) + if dst_row_bytes <= 0 or dst_row_bytes % dst_tail_size != 0: + raise ValueError( + f"DSA destination tail row size {dst_row_bytes} is not " + f"divisible by {dst_tail_size}" + ) + src_slot_bytes = src_row_bytes // src_tail_size + dst_slot_bytes = dst_row_bytes // dst_tail_size + if src_slot_bytes != dst_slot_bytes: + raise ValueError( + "DSA tail slot-size mismatch: " + f"src={src_slot_bytes}, dst={dst_slot_bytes}" + ) + + slot_bytes = src_slot_bytes + src_row_base = int(src_ptr) + src_row_bytes * src_idx + dst_row_base = int(dst_ptr) + dst_row_bytes * dst_idx + src_seg_idx = dst_seg_idx = 0 + src_consumed = dst_consumed = 0 + while src_seg_idx < len(src_segments): + src_off, src_n = src_segments[src_seg_idx] + dst_off, dst_n = dst_segments[dst_seg_idx] + n = min(src_n - src_consumed, dst_n - dst_consumed) + transfer_blocks.append( + ( + src_row_base + (src_off + src_consumed) * slot_bytes, + dst_row_base + (dst_off + dst_consumed) * slot_bytes, + n * slot_bytes, + ) + ) + src_consumed += n + dst_consumed += n + if src_consumed == src_n: + src_seg_idx += 1 + src_consumed = 0 + if dst_consumed == dst_n: + dst_seg_idx += 1 + dst_consumed = 0 + return transfer_blocks + + def setup_state_kv_args( kv_args: KVArgs, token_to_kv_pool, @@ -996,6 +1269,19 @@ def setup_state_kv_args( kv_args.is_hybrid_mla_backend = False kv_args.state_conv_shard_groups = [] + def append_dsa_tail(pool) -> None: + if not pool.kpool_use_compress: + return + tail_ptrs, tail_lens, tail_item_lens = pool.get_compress_tail_buf_infos() + if tail_ptrs: + append_state_component( + kv_args, + StateType.DSA_TAIL, + tail_ptrs, + tail_lens, + tail_item_lens, + ) + if isinstance(token_to_kv_pool, MHATokenToKVPoolMXFP8): append_state_component( kv_args, @@ -1099,7 +1385,25 @@ def setup_state_kv_args( slice_outer_counts, layer_ids, ) + # Hybrid DSA pools keep their index cache and kpool tail in the + # full-attention sub-pool rather than in the Mamba state above. + if getattr(token_to_kv_pool, "use_dsa", False): + dsa_pool = token_to_kv_pool.full_kv_pool + dsa_ptrs, dsa_lens, dsa_item_lens = dsa_pool.get_state_buf_infos() + append_state_component( + kv_args, + StateType.DSA, + dsa_ptrs, + dsa_lens, + dsa_item_lens, + ) + append_dsa_tail(dsa_pool) elif isinstance(token_to_kv_pool, (DSATokenToKVPool, NPUMLATokenToKVPool)): + tail_ptrs, tail_lens, tail_item_lens = [], [], [] + if isinstance(token_to_kv_pool, DSATokenToKVPool): + tail_ptrs, tail_lens, tail_item_lens = ( + token_to_kv_pool.get_compress_tail_buf_infos() + ) if draft_token_to_kv_pool is not None and isinstance( draft_token_to_kv_pool, DSATokenToKVPool ): @@ -1111,6 +1415,12 @@ def setup_state_kv_args( data_ptrs = data_ptrs + draft_data_ptrs data_lens = data_lens + draft_data_lens item_lens = item_lens + draft_item_lens + draft_tail_ptrs, draft_tail_lens, draft_tail_item_lens = ( + draft_token_to_kv_pool.get_compress_tail_buf_infos() + ) + tail_ptrs = tail_ptrs + draft_tail_ptrs + tail_lens = tail_lens + draft_tail_lens + tail_item_lens = tail_item_lens + draft_tail_item_lens if isinstance(token_to_kv_pool, NPUMLATokenToKVPool): kv_args.kv_buf_groups = ( len(kv_args.kv_data_ptrs) // token_to_kv_pool.layer_num @@ -1120,6 +1430,14 @@ def setup_state_kv_args( append_state_component( kv_args, StateType.DSA, data_ptrs, data_lens, item_lens ) + if tail_ptrs: + append_state_component( + kv_args, + StateType.DSA_TAIL, + tail_ptrs, + tail_lens, + tail_item_lens, + ) if is_npu() and isinstance(token_to_kv_pool, DSV4NPUTokenToKVPool): from sglang.srt.disaggregation.ascend.conn import AscendStateType diff --git a/python/sglang/srt/entrypoints/openai/protocol.py b/python/sglang/srt/entrypoints/openai/protocol.py index 109542667f25d..82a384a096a31 100644 --- a/python/sglang/srt/entrypoints/openai/protocol.py +++ b/python/sglang/srt/entrypoints/openai/protocol.py @@ -566,6 +566,10 @@ class ChatCompletionMessageContentVideoURL(BaseModel): url: str max_dynamic_patch: Optional[int] = None min_dynamic_patch: Optional[int] = None + fps: Optional[float] = None + max_frames: Optional[int] = None + max_tokens_per_frame: Optional[int] = None + max_image_tokens: Optional[int] = None class ChatCompletionMessageContentAudioURL(BaseModel): diff --git a/python/sglang/srt/entrypoints/openai/serving_chat.py b/python/sglang/srt/entrypoints/openai/serving_chat.py index 17ecfa782d65f..628b3d48d6e4d 100644 --- a/python/sglang/srt/entrypoints/openai/serving_chat.py +++ b/python/sglang/srt/entrypoints/openai/serving_chat.py @@ -4,6 +4,7 @@ import json import logging import math +import re import time import uuid from enum import Enum @@ -246,6 +247,8 @@ class OpenAIServingChat(OpenAIServingBase): _default_sampling_params_logged = False _KIMI_K3_GENERATION_STUB_TOKENS = 3 + _MM_ORDER_SENTINEL_RE = re.compile("\\x1e\\x1eSGLMM([IVA])(\\d+)\\x1e\\x1e") + _MM_ORDER_TAGS = {"image": "I", "video": "V", "audio": "A"} def __init__( self, @@ -717,6 +720,95 @@ def _reported_prompt_tokens(self, meta_info: Dict[str, Any]) -> int: prompt_tokens = max(0, prompt_tokens - self._KIMI_K3_GENERATION_STUB_TOKENS) return prompt_tokens + def _recover_media_order_from_chat_template( + self, + messages: List[Dict[str, Any]], + tools: Optional[List[Dict]], + extra_template_kwargs: Dict[str, Any], + image_data: List[Any], + video_data: List[Any], + audio_data: List[Any], + ) -> tuple[List[Any], List[Any], List[Any]]: + """Align media data with the order emitted by the chat template. + + Media extraction walks request messages, but templates that associate + tool results by ``tool_call_id`` may emit those results in tool-call + order. Render a media-free copy containing indexed text sentinels and + use their rendered order as the permutation for each modality. + + A permutation is applied only when every collected item appears exactly + once. Templates that drop, duplicate, or transform a sentinel safely + retain the original order. + """ + counters = {media_type: 0 for media_type in self._MM_ORDER_TAGS} + sentinel_messages = [] + for message in messages: + content = message.get("content") + if not isinstance(content, list): + sentinel_messages.append(message) + continue + + sentinel_content = [] + for part in content: + media_type = part.get("type") if isinstance(part, dict) else None + if media_type not in counters: + sentinel_content.append(part) + continue + + index = counters[media_type] + counters[media_type] += 1 + sentinel_content.append( + { + "type": "text", + "text": ( + f"\x1e\x1eSGLMM{self._MM_ORDER_TAGS[media_type]}" + f"{index}\x1e\x1e" + ), + } + ) + + sentinel_message = dict(message) + sentinel_message["content"] = sentinel_content + sentinel_messages.append(sentinel_message) + + try: + rendered = self.tokenizer_manager.tokenizer.apply_chat_template( + sentinel_messages, + tokenize=False, + add_generation_prompt=True, + tools=tools, + return_dict=False, + **extra_template_kwargs, + ) + except Exception as exc: + logger.warning( + "Failed to recover media order from the chat template (%s); " + "using request message order.", + exc, + ) + return image_data, video_data, audio_data + + permutations = {"I": [], "V": [], "A": []} + for tag, index in self._MM_ORDER_SENTINEL_RE.findall(rendered): + permutations[tag].append(int(index)) + + def apply_permutation(data: List[Any], permutation: List[int]) -> List[Any]: + if not data or permutation == list(range(len(data))): + return data + if sorted(permutation) != list(range(len(data))): + logger.warning( + "Chat template did not preserve every media sentinel; " + "using request message order." + ) + return data + return [data[index] for index in permutation] + + return ( + apply_permutation(image_data, permutations["I"]), + apply_permutation(video_data, permutations["V"]), + apply_permutation(audio_data, permutations["A"]), + ) + async def _generate_stream_content( self, content: Dict[str, Any], @@ -1422,6 +1514,43 @@ def _apply_jinja_template( # should be treated as client errors (400 BadRequest) raise ValueError(str(template_error)) from template_error + # Templates that associate results with assistant tool calls can + # emit result messages in call order rather than request order. An + # extra render is needed only when that can change a positional + # media binding: at least two tool-result items of one modality. + if getattr( + self.template_manager, + "jinja_template_may_reorder_tool_results", + False, + ): + tool_media_counts = { + media_type: 0 for media_type in self._MM_ORDER_TAGS + } + for message in openai_compatible_messages: + if message.get("role") not in ("tool", "function"): + continue + content = message.get("content") + if not isinstance(content, list): + continue + for part in content: + media_type = ( + part.get("type") if isinstance(part, dict) else None + ) + if media_type in tool_media_counts: + tool_media_counts[media_type] += 1 + + if any(count >= 2 for count in tool_media_counts.values()): + image_data, video_data, audio_data = ( + self._recover_media_order_from_chat_template( + openai_compatible_messages, + tools, + extra_template_kwargs, + image_data, + video_data, + audio_data, + ) + ) + # Append assistant prefix if continue_final_message is enabled if assistant_prefix: prompt_ids = self._append_assistant_prefix_to_prompt_ids( diff --git a/python/sglang/srt/environ.py b/python/sglang/srt/environ.py index 8e055bbf98e8b..4eeadba143ccb 100644 --- a/python/sglang/srt/environ.py +++ b/python/sglang/srt/environ.py @@ -1387,6 +1387,16 @@ class Envs: SGLANG_DSA_FUSE_TOPK = EnvBoolWithAlias( True, deprecated_name="SGLANG_NSA_FUSE_TOPK" ) + # Ported optimization gates (all default-off). + # KPOOL_METADATA_FUSION covers the fused kpool metadata refresh for all + # three replay phases (verify / decode / draft-extend), including the + # multi-step draft metadata dedup (later step backends D2D-copy the + # derived metadata from step 0 instead of recomputing it). + SGLANG_EXPERIMENTAL_DSA_KPOOL_METADATA_FUSION = EnvBool(False) + # Capture the verify metadata refresh inside the CUDA graph; the + # DG_OUT_OF_GRAPH sub-mode keeps DeepGEMM scheduling out of the graph. + SGLANG_EXPERIMENTAL_DSA_INGRAPH_VERIFY_METADATA = EnvBool(False) + SGLANG_EXPERIMENTAL_DSA_INGRAPH_VERIFY_METADATA_DG_OUT_OF_GRAPH = EnvBool(False) SGLANG_DSA_TOPK_FLASHINFER_DETERMINISTIC = EnvBool(False) SGLANG_DSA_TOPK_FLASHINFER_TIE_BREAK = EnvStr(None) SGLANG_DSA_PREFILL_DENSE_ATTN_KV_LEN_THRESHOLD = EnvIntWithAlias( diff --git a/python/sglang/srt/hardware_backend/npu/memory_pool_npu.py b/python/sglang/srt/hardware_backend/npu/memory_pool_npu.py index b787b033e6631..3ea67bce9a0a3 100644 --- a/python/sglang/srt/hardware_backend/npu/memory_pool_npu.py +++ b/python/sglang/srt/hardware_backend/npu/memory_pool_npu.py @@ -355,7 +355,7 @@ def _chunk_copy_npu_to_cpu(self, buf_of_layers, indices): # NPUMHATokenToKVPool stores buffers as # (num_pages, page_size, head_num, head_dim) # use_fia=False # (num_pages*page_size, 1, head_num, head_dim) # use_fia=True - def get_cpu_copy(self, indices, mamba_indices=None): + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): torch.npu.synchronize() buf_of_layers = [] for local_layer_id in range(self.layer_num): @@ -370,7 +370,9 @@ def get_cpu_copy(self, indices, mamba_indices=None): torch.npu.synchronize() return kv_cache_cpu - def load_cpu_copy(self, kv_cache_cpu, indices, mamba_indices=None): + def load_cpu_copy( + self, kv_cache_cpu, indices, mamba_indices=None, req_pool_index=None + ): torch.npu.synchronize() chunk_size = self.cpu_offloading_chunk_size for local_layer_id in range(self.layer_num): @@ -744,7 +746,7 @@ def _chunk_copy_npu_to_cpu(self, buf_of_layers, indices): out.append(layer_chunks) return out - def get_cpu_copy(self, indices, mamba_indices=None): + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): torch.npu.synchronize() buf_of_layers = [] has_ik = self.index_head_dim is not None @@ -762,7 +764,9 @@ def get_cpu_copy(self, indices, mamba_indices=None): torch.npu.synchronize() return kv_cache_cpu - def load_cpu_copy(self, kv_cache_cpu, indices, mamba_indices=None): + def load_cpu_copy( + self, kv_cache_cpu, indices, mamba_indices=None, req_pool_index=None + ): torch.npu.synchronize() chunk_size = self.cpu_offloading_chunk_size has_ik = self.index_head_dim is not None diff --git a/python/sglang/srt/layers/attention/attention_registry.py b/python/sglang/srt/layers/attention/attention_registry.py index ef9af670e55c7..2b040cf644799 100644 --- a/python/sglang/srt/layers/attention/attention_registry.py +++ b/python/sglang/srt/layers/attention/attention_registry.py @@ -3,6 +3,7 @@ from typing import TYPE_CHECKING from sglang.srt.configs.hybrid_arch import ( + glm5_next_config, hybrid_gdn_config, hybrid_lightning_config, kimi_linear_config, @@ -499,6 +500,8 @@ def attn_backend_wrapper(runner: "ModelRunner", full_attn_backend: "AttentionBac hybrid_backend_cls = AscendKDAHybridLinearAttnBackend else: linear_attn_backend = KDAAttnBackend(runner) + elif glm5_next_config(runner.model_config) is not None: + linear_attn_backend = KDAAttnBackend(runner) elif hybrid_lightning_config(runner.model_config) is not None: linear_attn_backend = LightningAttentionBackend(runner) else: diff --git a/python/sglang/srt/layers/attention/dsa/dsa_backend_mtp_precompute.py b/python/sglang/srt/layers/attention/dsa/dsa_backend_mtp_precompute.py index e4b90b7efee26..5160df62e3844 100644 --- a/python/sglang/srt/layers/attention/dsa/dsa_backend_mtp_precompute.py +++ b/python/sglang/srt/layers/attention/dsa/dsa_backend_mtp_precompute.py @@ -35,6 +35,7 @@ class PrecomputedMetadata: # Basic seqlens cache_seqlens: torch.Tensor # int32, [bs] cu_seqlens_k: torch.Tensor # int32, [bs+1] + req_pool_indices: torch.Tensor # int64, [bs] # Page table page_indices: torch.Tensor # int32, [bs, max_len] or [expanded_bs, max_len] @@ -121,7 +122,14 @@ def _precompute_decode_mode( """Precompute metadata for normal decode mode.""" max_len = self.decode_cuda_graph_metadata[bs].page_table_1.shape[1] - if _is_cuda and not _is_hip: + if ( + _is_cuda + and not _is_hip + and ( + self.dsa_index_kpool <= 1 + or getattr(self, "experimental_kpool_metadata_fusion", False) + ) + ): from sglang.kernels.ops.attention.dsa_metadata import ( fused_dsa_decode_metadata, ) @@ -159,6 +167,7 @@ def _precompute_decode_mode( max_len=max_len, dsa_index_topk=self.dsa_index_topk, real_page_size=self.real_page_size, + index_kpool=self.dsa_index_kpool, ) seqlens_expanded = cache_seqlens seqlens_expanded_size = bs @@ -173,6 +182,7 @@ def _precompute_decode_mode( return PrecomputedMetadata( cache_seqlens=cache_seqlens, cu_seqlens_k=cu_seqlens_k, + req_pool_indices=req_pool_indices, page_indices=page_indices, real_page_table=real_page_table, seqlens_expanded=seqlens_expanded, @@ -193,7 +203,9 @@ def _precompute_decode_mode( # Compute DSA seqlens dsa_cache_seqlens = compute_dsa_seqlens( - cache_seqlens, dsa_index_topk=self.dsa_index_topk + cache_seqlens, + dsa_index_topk=self.dsa_index_topk, + index_kpool=self.dsa_index_kpool, ) seqlens_expanded = cache_seqlens seqlens_expanded_size = seqlens_expanded.shape[0] @@ -218,6 +230,7 @@ def _precompute_decode_mode( return PrecomputedMetadata( cache_seqlens=cache_seqlens, cu_seqlens_k=cu_seqlens_k, + req_pool_indices=req_pool_indices, page_indices=page_indices, real_page_table=real_page_table, seqlens_expanded=seqlens_expanded, @@ -240,7 +253,7 @@ def _precompute_target_verify_mode( max_seqlen_k = self.decode_cuda_graph_metadata[bs].page_table_1.shape[1] seqlens_expanded_size = bs * self.speculative_num_draft_tokens - if _is_cuda and not _is_hip: + if _is_cuda and not _is_hip and self.dsa_index_kpool <= 1: from sglang.kernels.ops.attention.dsa_metadata import ( fused_dsa_target_verify_metadata, ) @@ -305,6 +318,7 @@ def _precompute_target_verify_mode( return PrecomputedMetadata( cache_seqlens=cache_seqlens, cu_seqlens_k=cu_seqlens_k, + req_pool_indices=req_pool_indices, page_indices=page_indices, real_page_table=real_page_table, seqlens_expanded=seqlens_expanded, @@ -342,7 +356,11 @@ def _precompute_target_verify_mode( ) # Compute DSA seqlens - dsa_cache_seqlens = compute_dsa_seqlens(seqlens_expanded, self.dsa_index_topk) + dsa_cache_seqlens = compute_dsa_seqlens( + seqlens_expanded, + self.dsa_index_topk, + index_kpool=self.dsa_index_kpool, + ) seqlens_expanded_size = seqlens_expanded.shape[0] # DSA cumsum @@ -365,6 +383,7 @@ def _precompute_target_verify_mode( return PrecomputedMetadata( cache_seqlens=cache_seqlens, cu_seqlens_k=cu_seqlens_k, + req_pool_indices=req_pool_indices, page_indices=page_indices, real_page_table=real_page_table, seqlens_expanded=seqlens_expanded, diff --git a/python/sglang/srt/layers/attention/dsa/dsa_indexer.py b/python/sglang/srt/layers/attention/dsa/dsa_indexer.py index 2dd615d00f3d1..3ad46e995ac66 100644 --- a/python/sglang/srt/layers/attention/dsa/dsa_indexer.py +++ b/python/sglang/srt/layers/attention/dsa/dsa_indexer.py @@ -478,7 +478,6 @@ def _get_q_k_bf16( dim=-1, ) with torch.cuda.stream(self.alt_stream): - # TODO we should also put DeepGEMM half SM here? if self.use_dsa_indexer_fusion: key, weights_raw = self._fused_k_weights(x) else: @@ -868,10 +867,18 @@ def _get_topk_paged( if use_dg_native: seqlens_32_2d = ctx_2d + elif ctx_2d is not None: + if ctx_2d.size(1) == 1: + seqlens_32_2d = ctx_2d + else: + seqlens_32_2d = ctx_2d.reshape(-1).contiguous().view(-1, 1) elif seqlens_32.dim() == 2: - seqlens_32_2d = seqlens_32 + if seqlens_32.size(1) == 1: + seqlens_32_2d = seqlens_32.contiguous() + else: + seqlens_32_2d = seqlens_32.reshape(-1).contiguous().view(-1, 1) else: - seqlens_32_2d = seqlens_32.unsqueeze(-1) + seqlens_32_2d = seqlens_32.contiguous().view(-1, 1) if _is_cuda: if schedule_metadata is None: schedule_metadata = deep_gemm.get_paged_mqa_logits_metadata( @@ -888,6 +895,54 @@ def _get_topk_paged( assert len(weights.shape) == 3 weights = weights.squeeze(2) + # DeepGEMM SM100 paged MQA misaligns when batch_size exceeds num_sms: + # chunk per sm_count with per-chunk schedule metadata, else defer to the + # plain kernel. Injected into the shared helpers as the kernel fn. + def _chunked_fp8_paged_mqa_logits( + q: torch.Tensor, + kv_cache: torch.Tensor, + w: torch.Tensor, + context_lens: torch.Tensor, + block_table: torch.Tensor, + mqa_schedule_metadata: torch.Tensor, + max_len: int, + clean_logits: bool = False, + ) -> torch.Tensor: + batch_size, chunk_next_n = q.shape[:2] + if batch_size == 0: + return torch.empty((0, max_len), dtype=torch.float32, device=q.device) + if batch_size <= self.sm_count: + return deep_gemm.fp8_paged_mqa_logits( + q, + kv_cache, + w, + context_lens, + block_table, + mqa_schedule_metadata, + max_len, + clean_logits=clean_logits, + ) + logits_chunks = [] + for start in range(0, batch_size, self.sm_count): + end = min(start + self.sm_count, batch_size) + chunk_context_lens = context_lens[start:end] + chunk_schedule_metadata = deep_gemm.get_paged_mqa_logits_metadata( + chunk_context_lens, blocksize, self.sm_count + ) + logits_chunks.append( + deep_gemm.fp8_paged_mqa_logits( + q[start:end], + kv_cache, + w[start * chunk_next_n : end * chunk_next_n], + chunk_context_lens, + block_table[start:end], + chunk_schedule_metadata, + max_len, + clean_logits=clean_logits, + ) + ) + return torch.cat(logits_chunks, dim=0) + if self.paged_mqa_logits_backend.is_aiter(): logits = aiter_paged_mqa_logits( q_fp8, @@ -920,7 +975,7 @@ def _get_topk_paged( ) elif use_dg_native: logits = deepgemm_paged_mqa_logits_native( - deep_gemm.fp8_paged_mqa_logits, + _chunked_fp8_paged_mqa_logits, q_fp8, kv_cache_fp8, weights, @@ -934,7 +989,7 @@ def _get_topk_paged( ) else: logits = deepgemm_paged_mqa_logits_split( - deep_gemm.fp8_paged_mqa_logits, + _chunked_fp8_paged_mqa_logits, q_fp8, kv_cache_fp8, weights, diff --git a/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py b/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py new file mode 100644 index 0000000000000..2cc6a6c477cde --- /dev/null +++ b/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py @@ -0,0 +1,1767 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange +from transformers import PretrainedConfig + +from sglang.srt.layers.attention.dsa.dsa_indexer import ( + DUAL_STREAM_TOKEN_THRESHOLD, + BaseIndexerMetadata, + rotate_activation, +) +from sglang.srt.layers.attention.dsa.dsa_topk_backend import TopkTransformMethod +from sglang.srt.layers.layernorm import LayerNorm +from sglang.srt.layers.utils import MultiPlatformOp +from sglang.srt.utils import add_prefix, ceil_align, is_cuda, is_hip, is_npu + +if is_cuda(): + try: + import deep_gemm + except ImportError as e: + deep_gemm = e + +if is_npu(): + import custom_ops # noqa: F401 + +from sglang.srt.environ import envs +from sglang.srt.layers import deep_gemm_wrapper +from sglang.srt.layers.attention.dsa.utils import ( + cp_zigzag_full_plan_rows, + dsa_use_prefill_cp, + is_dsa_enable_prefill_cp, + is_dsa_prefill_cp_in_seq_split, +) +from sglang.srt.layers.linear import ReplicatedLinear +from sglang.srt.layers.quantization.base_config import QuantizationConfig +from sglang.srt.layers.rotary_embedding import get_rope_wrapper +from sglang.srt.layers.utils.cp_utils import cp_all_gather_rerange_output +from sglang.srt.model_executor.forward_batch_info import ForwardBatch +from sglang.srt.model_executor.forward_context import ( + get_attn_backend, + get_req_to_token_pool, + get_token_to_kv_pool, +) +from sglang.srt.model_executor.runner import get_is_capture_mode +from sglang.srt.runtime_context import get_parallel, get_server_args + +if TYPE_CHECKING: + from sglang.srt.mem_cache.memory_pool import DSATokenToKVPool + + +class IndexerKPool(MultiPlatformOp): + def __init__( + self, + hidden_size: int, + index_n_heads: int, + index_head_dim: int, + rope_head_dim: int, + index_topk: int, + q_lora_rank: int, + max_position_embeddings: int, + rope_theta: float, + layer_id: int, + scale_fmt: Optional[str], + block_size: int = 128, + rope_scaling: Optional[Dict[str, Any]] = None, + is_neox_style: bool = True, + prefix: str = "", + quant_config: Optional[QuantizationConfig] = None, + alt_stream: Optional[torch.cuda.Stream] = None, + skip_rope: bool = False, + config: Optional[PretrainedConfig] = None, + ): + super().__init__() + self.hidden_size = hidden_size + self.n_heads = index_n_heads + self.head_dim = index_head_dim + self.rope_head_dim = rope_head_dim + self.index_topk = index_topk + self.q_lora_rank = q_lora_rank + self.layer_id = layer_id + self.alt_stream = alt_stream + self.compress_gate_stream = None + self.dsa_enable_prefill_cp = is_dsa_enable_prefill_cp() + self.cp_size = get_parallel().attn_cp_size if self.dsa_enable_prefill_cp else 1 + self.skip_rope = skip_rope + + self.index_kpool = config.index_kpool + self.index_kpool_always_select_tail = config.index_kpool_always_select_tail + self.index_kpool_compress = config.index_kpool_compress + + assert ( + self.index_kpool > 1 + and self.index_kpool_compress + and self.index_kpool_always_select_tail + ) + + assert self.index_topk % self.index_kpool == 0, ( + f"index_topk ({self.index_topk}) must be divisible by " + f"index_kpool ({self.index_kpool})" + ) + assert ( + 64 % self.index_kpool == 0 + ), f"index_kpool ({self.index_kpool}) must divide page_size (64)" + + self.index_kpool_compress_ape = nn.Parameter( + torch.zeros(self.index_kpool, self.head_dim, dtype=torch.float32) + ) + self.index_kpool_compress_gate = nn.Parameter( + torch.empty(self.head_dim, self.hidden_size, dtype=torch.bfloat16) + ) + + if is_cuda() and self.alt_stream is not None: + self.compress_gate_stream = torch.cuda.Stream() + + if is_cuda(): + self.sm_count = deep_gemm.get_num_sms() + self.half_device_sm_count = ceil_align(self.sm_count // 2, 8) + + self.wq_b = ReplicatedLinear( + self.q_lora_rank, + self.n_heads * self.head_dim, + bias=False, + quant_config=quant_config, + prefix=add_prefix("wq_b", prefix), + ) + + self.wk = ReplicatedLinear( + self.hidden_size, + self.head_dim, + bias=False, + quant_config=quant_config, + prefix=add_prefix("wk", prefix), + ) + # NOTE: weights_proj in the checkpoint is stored in bf16, while the parameters here are stored in fp32 for convenience + self.weights_proj = ReplicatedLinear( + self.hidden_size, + self.n_heads, + bias=False, + params_dtype=torch.float32, + prefix=add_prefix("weights_proj", prefix), + ) + self.k_norm = LayerNorm(self.head_dim, dtype=torch.float32) + if not self.skip_rope: + self.rotary_emb = get_rope_wrapper( + rope_head_dim, + rotary_dim=rope_head_dim, + max_position=max_position_embeddings, + base=rope_theta, # type: ignore + rope_scaling=rope_scaling, + is_neox_style=is_neox_style, + device=get_server_args().device, + ) + self.block_size = block_size + self.scale_fmt = scale_fmt + self.softmax_scale = self.head_dim**-0.5 + + @torch.compile(dynamic=True) + def _get_logits_head_gate(self, x: torch.Tensor, q_scale: torch.Tensor): + weights, _ = self.weights_proj(x.float()) + weights = weights * self.n_heads**-0.5 + weights = weights.unsqueeze(-1) * q_scale * self.softmax_scale + return weights + + @staticmethod + def _cp_gather_concat( + tensors: List[torch.Tensor], + cp_size: int, + forward_batch: ForwardBatch, + ) -> List[torch.Tensor]: + if not tensors: + return [] + n_local = tensors[0].shape[0] + flats = [] + feature_sizes = [] + tails = [] + for tensor in tensors: + assert tensor.shape[0] == n_local + assert tensor.dtype == tensors[0].dtype + tails.append(tensor.shape[1:]) + flat = tensor.reshape(n_local, -1).contiguous() + feature_sizes.append(flat.shape[1]) + flats.append(flat) + combined = flats[0] if len(flats) == 1 else torch.cat(flats, dim=1) + gathered = cp_all_gather_rerange_output( + combined, + cp_size, + forward_batch, + torch.cuda.current_stream(), + ) + parts = torch.split(gathered, feature_sizes, dim=1) + return [part.reshape(part.shape[0], *tail) for part, tail in zip(parts, tails)] + + @staticmethod + def _get_index_k_read_buffer(pool, layer_id: int) -> torch.Tensor: + if hasattr(pool, "get_broadcastable_index_k_with_scale_buffer"): + return pool.get_broadcastable_index_k_with_scale_buffer(layer_id) + if hasattr(pool, "_get_broadcastable_index_buffer"): + return pool._get_broadcastable_index_buffer(layer_id) + return pool.get_index_k_with_scale_buffer(layer_id=layer_id) + + def _write_compressed_pooled_index_cache( + self, + slot_k, + slot_score, + write_locs, + forward_batch, + layer_id, + write_mask=None, + return_compressed: bool = False, + write_cache: bool = True, + ): + if slot_k.shape[0] == 0: + if return_compressed: + return ( + torch.empty( + (0, self.head_dim), + dtype=torch.float8_e4m3fn, + device=slot_k.device, + ), + torch.empty((0,), dtype=torch.float32, device=slot_k.device), + ) + return None + from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( + kpool_softmax_rotate_write_cache, + ) + + pool = get_token_to_kv_pool() + if hasattr(pool, "invalidate_index_buffer_for_layer"): + pool.invalidate_index_buffer_for_layer(layer_id) + if hasattr(pool, "_is_layer_owned") and not pool._is_layer_owned(layer_id): + if not return_compressed: + return None + write_cache = False + + buf = pool.get_index_k_with_scale_buffer(layer_id=layer_id) + return kpool_softmax_rotate_write_cache( + pool=pool, + buf=buf, + slot_k=slot_k, + slot_score=slot_score, + ape=self.index_kpool_compress_ape, + loc=write_locs.contiguous(), + write_mask=write_mask.contiguous() if write_mask is not None else None, + round_scale=self.scale_fmt is not None, + return_compressed=return_compressed, + write_cache=write_cache, + ) + + @staticmethod + def _write_returned_compressed_pooled_index_cache( + forward_batch, layer_id, write_locs, k_fp8, k_scale + ): + if k_fp8.shape[0] == 0: + return + get_token_to_kv_pool().set_index_k_scale_buffer( + layer_id=layer_id, + loc=write_locs.contiguous(), + index_k=k_fp8.contiguous(), + index_k_scale=k_scale.contiguous(), + ) + + def _compress_write_decode( + self, + key, + gate_score, + positions, + forward_batch, + layer_id, + metadata, + ): + batch = key.shape[0] + if batch == 0: + return + + pool = get_token_to_kv_pool() + if hasattr(pool, "invalidate_index_buffer_for_layer"): + pool.invalidate_index_buffer_for_layer(layer_id) + if hasattr(pool, "_is_layer_owned") and not pool._is_layer_owned(layer_id): + return + + pool.kpool_decode_update_index_cache( + layer_id=layer_id, + key=key, + slot_score=gate_score, + ape=self.index_kpool_compress_ape, + block_tables=metadata.get_page_table_64(), + req_pool_indices=forward_batch.req_pool_indices[:batch], + positions=positions[:batch], + seq_lens=metadata.get_seqlens_int32()[:batch], + out_cache_loc=forward_batch.out_cache_loc[:batch], + round_scale=self.scale_fmt is not None, + ) + + def _compress_write_extend( + self, + key, + gate_score, + positions, + forward_batch, + layer_id, + metadata, + return_compressed: bool = False, + write_cache: bool = True, + ): + assert ( + forward_batch.seq_lens_cpu is not None + and forward_batch.extend_seq_lens_cpu is not None + ) + attn_metadata = metadata.attn_metadata + plan = attn_metadata.kpool_extend_plan + if plan is not None: + import os + + from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( + all_gather_and_scatter_pool_slots, + kpool_assemble_softmax_rotate_write_cache, + scatter_kpool_tail_updates, + ) + + pool = get_token_to_kv_pool() + if hasattr(pool, "invalidate_index_buffer_for_layer"): + pool.invalidate_index_buffer_for_layer(layer_id) + layer_owned = not ( + hasattr(pool, "_is_layer_owned") and not pool._is_layer_owned(layer_id) + ) + if not layer_owned: + return None + + writes, tails, cp = plan.writes, plan.tails, plan.cp + if writes.is_empty and tails.is_empty: + return None + + tail_k_buf, tail_score_buf = pool.get_compress_tail_buffers(layer_id) + layer_sharded = bool(getattr(pool, "layer_shard_enabled", False)) + cache_cp = None if layer_sharded else cp + if os.environ.get("SGLANG_DSA_KPOOL_DEBUG_BOUNDS") == "1": + if not writes.is_empty: + active = ( + cache_cp.local_write_mask + if cache_cp is not None + else torch.ones_like(writes.req, dtype=torch.bool) + ) + if bool(active.any().item()): + active_req = writes.req[active] + active_write_loc = writes.write_loc[active] + active_chunk_max = writes.chunk_src[active].to( + torch.long + ) + torch.clamp( + self.index_kpool + - writes.n_from_tail[active].to(torch.long) + - 1, + min=0, + ) + max_chunk = int(active_chunk_max.max().item()) + min_chunk = int(writes.chunk_src[active].min().item()) + min_req = int(active_req.min().item()) + max_req = int(active_req.max().item()) + min_loc = int(active_write_loc.min().item()) + max_loc = int(active_write_loc.max().item()) + max_page = max_loc // int(pool.slots_per_page) + if ( + min_chunk < 0 + or max_chunk >= key.shape[0] + or max_chunk >= gate_score.shape[0] + or min_req < 0 + or max_req >= tail_k_buf.shape[0] + or min_loc < 0 + or max_page + >= pool.get_index_k_with_scale_buffer( + layer_id=layer_id + ).shape[0] + ): + raise RuntimeError( + "DSA kpool write plan out of bounds: " + f"{key.shape=}, {gate_score.shape=}, {tail_k_buf.shape=}, " + f"{pool.get_index_k_with_scale_buffer(layer_id=layer_id).shape=}, " + f"{min_chunk=}, {max_chunk=}, {min_req=}, {max_req=}, " + f"{min_loc=}, {max_loc=}, {pool.slots_per_page=}, " + f"cp_rank={cache_cp.rank if cache_cp is not None else None}, " + f"cp_size={cache_cp.size if cache_cp is not None else None}" + ) + if not tails.is_empty: + tail_chunk_max = tails.chunk_src.to(torch.long) + torch.clamp( + tails.n_write.to(torch.long) - 1, min=0 + ) + max_tail_chunk = int(tail_chunk_max.max().item()) + min_tail_chunk = int(tails.chunk_src.min().item()) + min_tail_req = int(tails.req.min().item()) + max_tail_req = int(tails.req.max().item()) + if ( + min_tail_chunk < 0 + or max_tail_chunk >= key.shape[0] + or min_tail_req < 0 + or max_tail_req >= tail_k_buf.shape[0] + ): + raise RuntimeError( + "DSA kpool tail plan out of bounds: " + f"{key.shape=}, {tail_k_buf.shape=}, " + f"{min_tail_chunk=}, {max_tail_chunk=}, " + f"{min_tail_req=}, {max_tail_req=}" + ) + if not writes.is_empty: + buf = pool.get_index_k_with_scale_buffer(layer_id=layer_id) + kpool_assemble_softmax_rotate_write_cache( + pool=pool, + buf=buf, + chunk_k=key, + chunk_score=gate_score, + tail_k=tail_k_buf, + tail_score=tail_score_buf, + req_pool_idx=writes.req, + n_from_tail=writes.n_from_tail, + chunk_src_start=writes.chunk_src, + tail_logical_base=writes.tail_logical_base, + ape=self.index_kpool_compress_ape, + loc=writes.write_loc, + write_mask=( + cache_cp.local_write_mask if cache_cp is not None else None + ), + round_scale=self.scale_fmt is not None, + ) + if cache_cp is not None and write_cache: + all_gather_and_scatter_pool_slots( + buf=buf, + local_locs=writes.write_loc, + owner_rank=cache_cp.owner_rank, + cp_size=cache_cp.size, + cp_rank=cache_cp.rank, + slots_per_page=pool.slots_per_page, + ) + + if not tails.is_empty: + scatter_kpool_tail_updates( + pool=pool, + chunk_k=key, + chunk_score=gate_score, + tail_k=tail_k_buf, + tail_score=tail_score_buf, + req_pool_idx=tails.req, + dst_logical_start=tails.dst_logical_start, + chunk_src_start=tails.chunk_src, + n_write=tails.n_write, + ) + return None + + kpool = self.index_kpool + block_tables = metadata.get_page_table_64() + kpool_write_locs = getattr(attn_metadata, "kpool_extend_write_locs", None) + q_offset = 0 + compressed_by_batch = ( + [None for _ in range(forward_batch.batch_size)] + if return_compressed + else None + ) + + for i in range(forward_batch.batch_size): + q_len = int(forward_batch.extend_seq_lens_cpu[i]) + if q_len == 0: + continue + + req_pool_idx = forward_batch.req_pool_indices[i].to(torch.long) + key_chunk = key[q_offset : q_offset + q_len] + score_chunk = gate_score[q_offset : q_offset + q_len] + seq_len = int(forward_batch.seq_lens_cpu[i].item()) + first_pos = seq_len - q_len + first_slot = first_pos % kpool + + if first_slot != 0: + raise NotImplementedError( + "index_kpool_compress extend requires kpool-aligned chunk " + "starts. Set chunked_prefill_size % index_kpool == 0 and " + "avoid non-aligned prefix reuse." + ) + + pool_start_id = first_pos // kpool + page_size = get_token_to_kv_pool().page_size + use_returned_compressed = return_compressed and ( + not write_cache or pool_start_id == 0 + ) + n_pools = q_len // kpool + n_drain = n_pools * kpool + if n_pools > 0: + slot_k = key_chunk[:n_drain].view(n_pools, kpool, self.head_dim) + slot_score = score_chunk[:n_drain].view(n_pools, kpool, self.head_dim) + write_locs = ( + kpool_write_locs[i] if kpool_write_locs is not None else None + ) + if write_locs is None: + from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( + compute_pooled_write_locs, + ) + + num_token_pages = (seq_len + page_size - 1) // page_size + token_page_table = block_tables[i, :num_token_pages].contiguous() + pool_ids = pool_start_id + torch.arange( + n_pools, dtype=torch.int64, device=key.device + ) + write_locs = compute_pooled_write_locs( + token_page_table, pool_ids, kpool + ) + compressed = self._write_compressed_pooled_index_cache( + slot_k, + slot_score, + write_locs, + forward_batch, + layer_id, + return_compressed=use_returned_compressed, + write_cache=write_cache, + ) + else: + compressed = self._write_compressed_pooled_index_cache( + slot_k, + slot_score, + write_locs, + forward_batch, + layer_id, + return_compressed=use_returned_compressed, + write_cache=write_cache, + ) + if compressed_by_batch is not None and compressed is not None: + compressed_by_batch[i] = ( + pool_start_id, + compressed[0], + compressed[1], + write_locs.contiguous(), + ) + + n_remain = q_len - n_drain + get_token_to_kv_pool().set_compress_tail_for_request( + layer_id=layer_id, + req_pool_idx=req_pool_idx, + key_tail=key_chunk[n_drain:] if n_remain > 0 else key_chunk[:0], + score_tail=score_chunk[n_drain:] if n_remain > 0 else score_chunk[:0], + n_remain=n_remain, + dst_logical_start=first_pos + n_drain, + ) + q_offset += q_len + + return compressed_by_batch + + def _compress_write( + self, + x, + key, + positions, + forward_batch, + layer_id, + metadata, + gate_score: Optional[torch.Tensor] = None, + return_compressed: bool = False, + write_cache: bool = True, + ): + if key.shape[0] == 0: + return None + + if gate_score is None: + gate_score = F.linear(x, self.index_kpool_compress_gate) + + if forward_batch.forward_mode.is_decode_or_idle(): + self._compress_write_decode( + key=key, + gate_score=gate_score, + positions=positions, + forward_batch=forward_batch, + layer_id=layer_id, + metadata=metadata, + ) + elif forward_batch.forward_mode.is_extend(): + return self._compress_write_extend( + key=key, + gate_score=gate_score, + positions=positions, + forward_batch=forward_batch, + layer_id=layer_id, + metadata=metadata, + return_compressed=return_compressed, + write_cache=write_cache, + ) + else: + raise NotImplementedError( + "index_kpool_compress currently supports decode and extend only." + ) + return None + + def _compute_gate_score_if_missing( + self, x: torch.Tensor, gate_score: Optional[torch.Tensor] + ) -> torch.Tensor: + if gate_score is not None: + return gate_score + return F.linear(x, self.index_kpool_compress_gate) + + def _get_q_k_bf16( + self, + q_lora: torch.Tensor, + x: torch.Tensor, + positions: torch.Tensor, + enable_dual_stream: bool, + forward_batch: ForwardBatch, + precompute_compress_gate: bool = False, + ): + gate_score = None + if enable_dual_stream: + current_stream = torch.cuda.current_stream() + self.alt_stream.wait_stream(current_stream) + if precompute_compress_gate: + assert self.compress_gate_stream is not None + self.compress_gate_stream.wait_stream(current_stream) + + with deep_gemm_wrapper.configure_deep_gemm_num_sms( + self.half_device_sm_count + ): + query, _ = self.wq_b(q_lora) + query = rearrange(query, "l (h d) -> l h d", d=self.head_dim) + q_rope, _ = torch.split( + query, + [self.rope_head_dim, self.head_dim - self.rope_head_dim], + dim=-1, + ) + with torch.cuda.stream(self.alt_stream): + key, _ = self.wk(x) + key = self.k_norm(key) + + k_rope, _ = torch.split( + key, + [self.rope_head_dim, self.head_dim - self.rope_head_dim], + dim=-1, + ) + + if precompute_compress_gate: + with torch.cuda.stream(self.compress_gate_stream): + gate_score = F.linear(x, self.index_kpool_compress_gate) + + current_stream.wait_stream(self.alt_stream) + else: + query, _ = self.wq_b(q_lora) + query = rearrange(query, "l (h d) -> l h d", d=self.head_dim) + q_rope, _ = torch.split( + query, [self.rope_head_dim, self.head_dim - self.rope_head_dim], dim=-1 + ) + key, _ = self.wk(x) + key = self.k_norm(key) + k_rope, _ = torch.split( + key, [self.rope_head_dim, self.head_dim - self.rope_head_dim], dim=-1 + ) + + if not self.skip_rope: + q_rope, k_rope = self.rotary_emb(positions, q_rope, k_rope) + + query[..., : self.rope_head_dim] = q_rope + key[..., : self.rope_head_dim] = k_rope + + query = rotate_activation(query) + + return query, key, gate_score + + def _get_k_bf16( + self, + x: torch.Tensor, + positions: torch.Tensor, + ): + key, _ = self.wk(x) + key = self.k_norm(key) + k_rope, _ = torch.split( + key, [self.rope_head_dim, self.head_dim - self.rope_head_dim], dim=-1 + ) + + if not self.skip_rope: + _, k_rope = self.rotary_emb(positions, k_rope, k_rope) + key[..., : self.rope_head_dim] = k_rope + return key + + def _full_topk_for_short_sequence( + self, metadata: BaseIndexerMetadata, device: torch.device + ) -> torch.Tensor: + seq_lens_expanded = metadata.get_seqlens_expanded() + dummy_logits = torch.zeros( + seq_lens_expanded.shape[0], + self.index_topk, + dtype=torch.float32, + device=device, + ) + topk_full = metadata.topk_transform(dummy_logits, self.index_topk) + if self.index_kpool == 1: + return topk_full + padding = torch.full( + (topk_full.shape[0], self.index_kpool - 1), + -1, + dtype=topk_full.dtype, + device=topk_full.device, + ) + return torch.cat([topk_full, padding], dim=1) + + def _topk_from_kpool_logits( + self, + logits: torch.Tensor, + pool_lens: torch.Tensor, + seq_lens: Optional[torch.Tensor] = None, + page_table: Optional[torch.Tensor] = None, + topk_offsets: Optional[torch.Tensor] = None, + row_starts: Optional[torch.Tensor] = None, + out_rows: Optional[int] = None, + page_table_row_index: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( + topk_from_pooled_history_logits, + ) + + n_rows = logits.shape[0] + if ( + page_table is not None + and page_table_row_index is None + and page_table.shape[0] != n_rows + ): + page_table = page_table[:n_rows] + if topk_offsets is not None and topk_offsets.shape[0] != n_rows: + topk_offsets = topk_offsets[:n_rows] + if page_table_row_index is not None and page_table_row_index.shape[0] != n_rows: + page_table_row_index = page_table_row_index[:n_rows] + + return topk_from_pooled_history_logits( + logits=logits, + group_lengths=pool_lens, + pool_size=self.index_kpool, + topk=self.index_topk, + page_table=page_table, + topk_offsets=topk_offsets, + seq_lens=seq_lens, + row_starts=row_starts, + out_rows=out_rows, + page_table_row_index=page_table_row_index, + ) + + def _get_kpool_decode_metadata( + self, + metadata: BaseIndexerMetadata, + block_tables: torch.Tensor, + seqlens_32: torch.Tensor, + blocksize: int, + build_schedule_metadata: bool = True, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: + from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( + build_pooled_page_table_64, + ) + + attn_metadata = metadata.attn_metadata + plan = attn_metadata.kpool_write_plan + if plan is not None and plan.pool_seqlens_per_q is not None: + pool_seqlens = plan.pool_seqlens_per_q[: seqlens_32.shape[0]] + pool_context_lens = pool_seqlens.contiguous().view(-1, 1) + pool_block_tables = build_pooled_page_table_64( + block_tables, self.index_kpool + ).contiguous() + pool_schedule_metadata = plan.pool_schedule_metadata + if pool_schedule_metadata is None and build_schedule_metadata: + pool_schedule_metadata = deep_gemm.get_paged_mqa_logits_metadata( + pool_context_lens.clamp(min=1), blocksize, self.sm_count + ) + return ( + pool_seqlens, + pool_context_lens, + pool_block_tables, + pool_schedule_metadata, + ) + + pool_seqlens = attn_metadata.pooled_cache_seqlens_int32 + pool_block_tables = attn_metadata.pooled_real_page_table + pool_schedule_metadata = attn_metadata.pooled_paged_mqa_schedule_metadata + + if ( + pool_seqlens is None + or pool_block_tables is None + or attn_metadata.pooled_index_kpool != self.index_kpool + ): + pool_seqlens = torch.div( + seqlens_32, self.index_kpool, rounding_mode="floor" + ).to(torch.int32) + pool_block_tables = build_pooled_page_table_64( + block_tables, self.index_kpool + ).contiguous() + pool_schedule_metadata = None + else: + pool_seqlens = pool_seqlens[: seqlens_32.shape[0]] + pool_block_tables = pool_block_tables[ + : block_tables.shape[0], + : (block_tables.shape[1] + self.index_kpool - 1) // self.index_kpool, + ] + + pool_context_lens = pool_seqlens.contiguous().view(-1, 1) + if pool_schedule_metadata is None and build_schedule_metadata: + pool_schedule_metadata = deep_gemm.get_paged_mqa_logits_metadata( + pool_context_lens.clamp(min=1), blocksize, self.sm_count + ) + + return ( + pool_seqlens, + pool_context_lens, + pool_block_tables, + pool_schedule_metadata, + ) + + @staticmethod + def _kpool_fused_topk_mapping( + metadata: BaseIndexerMetadata, + paged_page_table: Optional[torch.Tensor] = None, + paged_page_table_row_index: Optional[torch.Tensor] = None, + ) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: + if not envs.SGLANG_DSA_FUSE_TOPK.get(): + return None, None, None + + topk_method = metadata.topk_transform_method + attn_metadata = metadata.attn_metadata + if topk_method == TopkTransformMethod.PAGED: + page_table_1 = ( + paged_page_table + if paged_page_table is not None + else attn_metadata.page_table_1 + ) + assert page_table_1 is not None + row_index = paged_page_table_row_index + return page_table_1, None, row_index + if topk_method == TopkTransformMethod.RAGGED: + return None, attn_metadata.topk_indices_offset, None + return None, None, None + + @staticmethod + def _should_use_tilelang_paged_mqa_logits(q_fp8: torch.Tensor) -> bool: + if not is_cuda(): + return False + arch_major, _ = torch.cuda.get_device_capability(q_fp8.device) + num_heads = q_fp8.shape[2] + return arch_major == 9 and num_heads not in (32, 64) + + def _get_topk_paged( + self, + forward_batch: ForwardBatch, + layer_id: int, + q_fp8: torch.Tensor, + weights: torch.Tensor, + metadata: BaseIndexerMetadata, + ) -> torch.Tensor: + if TYPE_CHECKING: + assert isinstance(get_token_to_kv_pool(), DSATokenToKVPool) + + pool = get_token_to_kv_pool() + page_size = pool.page_size + # NOTE(dark): blocksize = 64 is hardcoded in deep_gemm + assert page_size == 64, "only support page size 64" + + # NOTE(dark): this support extend/decode/decode+graph + block_tables = metadata.get_page_table_64() + + kv_cache_fp8 = self._get_index_k_read_buffer(pool, layer_id) + + blocksize = page_size + if ( + forward_batch.forward_mode.is_target_verify() + or forward_batch.forward_mode.is_draft_extend_v2() + ): + seqlens_32 = metadata.get_seqlens_expanded() + else: + seqlens_32 = metadata.get_seqlens_int32() + assert len(q_fp8.shape) == 3 + num_q_padded = q_fp8.shape[0] + n_real = seqlens_32.shape[0] + if n_real < num_q_padded: + q_fp8 = q_fp8[:n_real] + weights = weights[:n_real] + q_fp8 = q_fp8.unsqueeze(1) # the next_n dim is 1 now + assert len(kv_cache_fp8.shape) == 2 + block_kv = 64 + num_heads_kv = 1 + head_dim_with_sf = 132 + kv_cache_fp8 = kv_cache_fp8.view( + kv_cache_fp8.shape[0], block_kv, num_heads_kv, head_dim_with_sf + ) + assert len(weights.shape) == 3 + weights = weights.squeeze(2) + use_tilelang_paged_mqa = self._should_use_tilelang_paged_mqa_logits(q_fp8) + + pool_seqlens, pool_context_lens, pool_block_tables, pool_schedule_metadata = ( + self._get_kpool_decode_metadata( + metadata, + block_tables, + seqlens_32, + blocksize, + build_schedule_metadata=not use_tilelang_paged_mqa, + ) + ) + pool_max_seq_len = pool_block_tables.shape[1] * blocksize + if use_tilelang_paged_mqa: + from sglang.kernels.ops.attention.dsa.tilelang_kernel import ( + tilelang_fp8_paged_mqa_logits, + ) + + logits = tilelang_fp8_paged_mqa_logits( + q_fp8, + kv_cache_fp8, + weights, + pool_seqlens, + pool_block_tables, + pool_schedule_metadata, + pool_max_seq_len, + clean_logits=False, + ) + else: + logits = deep_gemm.fp8_paged_mqa_logits( + q_fp8, + kv_cache_fp8, + weights, + pool_context_lens, + pool_block_tables, + pool_schedule_metadata, + pool_max_seq_len, + clean_logits=False, + ) + + page_table_1, topk_offsets, _ = self._kpool_fused_topk_mapping(metadata) + topk_result = self._topk_from_kpool_logits( + logits, + pool_seqlens, + seq_lens=seqlens_32, + page_table=page_table_1, + topk_offsets=topk_offsets, + out_rows=num_q_padded if num_q_padded != n_real else None, + ) + return topk_result + + def _should_chunk_mqa_logits( + self, num_q: int, num_k: int, device: torch.device + ) -> Tuple[bool, int]: + """ + Detect whether we need to chunk the MQA logits computation to avoid OOM + Return: (need_chunk, free_mem) + """ + # Quick static check for normal batches + if num_q * num_k < 8_000_000: # 8M elements ≈ 32MB logits + return False, 0 + + free_mem, total_mem = torch.cuda.mem_get_info(device) + bytes_per_elem = 4 # float32 + logits_bytes = num_q * num_k * bytes_per_elem + + # Logits should not exceed 50% of free memory or 30% of total memory + need_chunk = (logits_bytes * 2 > free_mem) or (logits_bytes > total_mem * 0.3) + return need_chunk, free_mem + + def _get_topk_ragged_kpool_plan( + self, + forward_batch: ForwardBatch, + layer_id: int, + q_fp8: torch.Tensor, + weights: torch.Tensor, + metadata: BaseIndexerMetadata, + ) -> torch.Tensor: + from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( + gather_index_k_scale_prefix_into, + ) + + plan = metadata.attn_metadata.kpool_extend_plan + assert plan is not None, "kpool extend plan is required" + assert len(weights.shape) == 3 + weights = weights.squeeze(-1) + + device = q_fp8.device + total_q = q_fp8.shape[0] + seq_lens_expanded = plan.seq_lens_expanded + pool_lens = plan.pooled_seq_lens_expanded + ks_per_q = plan.ragged_q_ks + ke_per_q = plan.ragged_q_ke + total_k_rows = plan.ragged_total_k_rows + + n_real = seq_lens_expanded.shape[0] + row_select = None + if n_real > total_q: + row_select = cp_zigzag_full_plan_rows(forward_batch, device) + if row_select is not None: + seq_lens_expanded = seq_lens_expanded.index_select(0, row_select) + pool_lens = pool_lens.index_select(0, row_select) + ks_per_q = ks_per_q.index_select(0, row_select) + ke_per_q = ke_per_q.index_select(0, row_select) + n_real = seq_lens_expanded.shape[0] + assert ( + n_real <= total_q + ), f"plan has more real rows ({n_real}) than q_fp8 ({total_q})" + + if total_k_rows > 0: + k_u8 = plan.ragged_k_u8 + k_scale = plan.ragged_k_scale + assert k_u8 is not None and k_scale is not None + pool = get_token_to_kv_pool() + gather_index_k_scale_prefix_into( + pool=pool, + buf=self._get_index_k_read_buffer(pool, layer_id), + page_indices=plan.ragged_concat_page_table, + seq_len=total_k_rows, + k_out=k_u8, + scale_out=k_scale, + ) + k_fp8 = k_u8.view(torch.float8_e4m3fn) + logits = deep_gemm.fp8_mqa_logits( + q_fp8[:n_real].contiguous(), + (k_fp8.contiguous(), k_scale.contiguous()), + weights[:n_real].contiguous(), + ks_per_q, + ke_per_q, + clean_logits=True, + ) + else: + logits = torch.empty((n_real, 0), dtype=torch.float32, device=device) + + topk_method = metadata.topk_transform_method + attn_metadata = metadata.attn_metadata + page_table_all = None + page_table_row_index_all = None + topk_offsets_all = None + if envs.SGLANG_DSA_FUSE_TOPK.get(): + if topk_method == TopkTransformMethod.PAGED: + page_table_all = plan.ragged_paged_page_table + page_table_row_index_all = plan.ragged_paged_page_table_row_index + if page_table_row_index_all is not None and row_select is not None: + page_table_row_index_all = page_table_row_index_all.index_select( + 0, row_select + ) + elif page_table_all is not None and row_select is not None: + page_table_all = page_table_all.index_select(0, row_select) + elif topk_method == TopkTransformMethod.RAGGED: + topk_offsets_all = attn_metadata.topk_indices_offset + if topk_offsets_all is not None and row_select is not None: + topk_offsets_all = topk_offsets_all.index_select(0, row_select) + + return self._topk_from_kpool_logits( + logits, + pool_lens, + seq_lens=seq_lens_expanded, + page_table=page_table_all, + topk_offsets=topk_offsets_all, + row_starts=ks_per_q, + out_rows=total_q, + page_table_row_index=page_table_row_index_all, + ) + + def _get_topk_ragged_with_cp( + self, + forward_batch: ForwardBatch, + layer_id: int, + q_fp8: torch.Tensor, + weights: torch.Tensor, + metadata: BaseIndexerMetadata, + kv_len: int, + actual_seq_q: int, + cp_index: Optional[List[Tuple[int, int, int]]] = None, + ) -> torch.Tensor: + from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( + build_pooled_page_table_64, + gather_index_k_scale_prefix_into, + ) + + assert cp_index is None, "DSA kpool CP topk currently supports batch size 1" + assert forward_batch.batch_size == 1 + assert len(weights.shape) == 3 + weights = weights.squeeze(-1) + + pool = get_token_to_kv_pool() + pool_size = self.index_kpool + slots_per_page = pool.slots_per_page + device = q_fp8.device + out_rows = q_fp8.shape[0] + actual_seq_q = int(actual_seq_q) + + assert forward_batch.seq_lens_cpu is not None + assert forward_batch.extend_seq_lens_cpu is not None + kv_len_token = int( + forward_batch.seq_lens_cpu[0].item() + - forward_batch.extend_seq_lens_cpu[0] + + kv_len + ) + pool_kv_len = kv_len_token // pool_size + + q_work = q_fp8[:actual_seq_q].contiguous() + weights_work = weights[:actual_seq_q].contiguous() + tail_tokens = torch.arange( + kv_len_token - actual_seq_q + 1, + kv_len_token + 1, + dtype=torch.int32, + device=device, + ) + + if pool_kv_len > 0 and actual_seq_q > 0: + block_tables = metadata.get_page_table_64() + bt_row = block_tables[0] + n_pages = (pool_kv_len + slots_per_page - 1) // slots_per_page + packed_page_indices = ( + build_pooled_page_table_64(bt_row, pool_size)[:n_pages] + .to(torch.int32) + .contiguous() + ) + k_u8 = torch.empty( + (pool_kv_len, self.head_dim), dtype=torch.uint8, device=device + ) + k_scale = torch.empty((pool_kv_len,), dtype=torch.float32, device=device) + gather_index_k_scale_prefix_into( + pool=pool, + buf=self._get_index_k_read_buffer(pool, layer_id), + page_indices=packed_page_indices, + seq_len=pool_kv_len, + k_out=k_u8, + scale_out=k_scale, + ) + k_fp8 = k_u8.view(torch.float8_e4m3fn) + ks = torch.zeros((actual_seq_q,), dtype=torch.int32, device=device) + ke = torch.div(tail_tokens, pool_size, rounding_mode="floor").to( + torch.int32 + ) + logits = deep_gemm.fp8_mqa_logits( + q_work, + (k_fp8.contiguous(), k_scale.contiguous()), + weights_work, + ks, + ke, + clean_logits=True, + ) + pool_lens = ke + else: + logits = torch.empty((actual_seq_q, 0), dtype=torch.float32, device=device) + pool_lens = torch.zeros((actual_seq_q,), dtype=torch.int32, device=device) + ks = torch.zeros((actual_seq_q,), dtype=torch.int32, device=device) + + page_table_local = None + topk_method = metadata.topk_transform_method + if envs.SGLANG_DSA_FUSE_TOPK.get() and topk_method == TopkTransformMethod.PAGED: + req_pool_idx = int(forward_batch.req_pool_indices[0].item()) + page_table_local = ( + get_req_to_token_pool() + .req_to_token[req_pool_idx, :kv_len_token] + .to(torch.int32) + .unsqueeze(0) + .expand(actual_seq_q, -1) + ) + + return self._topk_from_kpool_logits( + logits, + pool_lens, + seq_lens=tail_tokens, + page_table=page_table_local, + topk_offsets=None, + row_starts=ks, + out_rows=out_rows, + ) + + def _get_topk_ragged_kpool( + self, + forward_batch: ForwardBatch, + layer_id: int, + q_fp8: torch.Tensor, + weights: torch.Tensor, + metadata: BaseIndexerMetadata, + extend_pooled_cache: Optional[ + List[Optional[Tuple[int, torch.Tensor, torch.Tensor, torch.Tensor]]] + ] = None, + ) -> torch.Tensor: + from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( + build_pooled_page_table_64, + gather_index_k_scale_prefix_into, + ) + + assert ( + forward_batch.seq_lens_cpu is not None + and forward_batch.extend_seq_lens_cpu is not None + ) + + pool_size = self.index_kpool + page_size = get_token_to_kv_pool().page_size + token_nums = q_fp8.shape[0] + tail_pool = pool_size - 1 + topk_result = torch.empty( + (token_nums, self.index_topk + tail_pool), + device=q_fp8.device, + dtype=torch.int32, + ) + block_tables = metadata.get_page_table_64() + seq_lens_expanded = metadata.get_seqlens_expanded() + topk_method = metadata.topk_transform_method + attn_metadata = metadata.attn_metadata + topk_offsets = attn_metadata.topk_indices_offset + pooled_page_tables = getattr( + attn_metadata, "kpool_extend_pooled_page_tables", None + ) + zero_starts_by_batch = getattr(attn_metadata, "kpool_extend_zero_starts", None) + pooled_seq_lens_expanded = getattr( + attn_metadata, "kpool_seqlens_expanded", None + ) + + q_offset = 0 + cache_write_stream = None + pending_cache_req_pool_indices = set() + pending_cache_tensors = [] + for i in range(forward_batch.batch_size): + q_len = int(forward_batch.extend_seq_lens_cpu[i]) + if q_len == 0: + continue + + seq_len = int(forward_batch.seq_lens_cpu[i].item()) + pool_seq_len = seq_len // pool_size + req_pool_idx = int(forward_batch.req_pool_indices[i].item()) + if ( + cache_write_stream is not None + and req_pool_idx in pending_cache_req_pool_indices + ): + torch.cuda.current_stream().wait_stream(cache_write_stream) + cache_write_stream = None + pending_cache_req_pool_indices.clear() + pending_cache_tensors.clear() + + q_slice = slice(q_offset, q_offset + q_len) + local_seqlens = seq_lens_expanded[q_slice] + if pooled_seq_lens_expanded is None: + local_pool_lens = torch.div( + local_seqlens, pool_size, rounding_mode="floor" + ).to(torch.int32) + else: + local_pool_lens = pooled_seq_lens_expanded[q_slice] + + if pool_seq_len > 0: + cached_current = ( + extend_pooled_cache[i] if extend_pooled_cache is not None else None + ) + deferred_cache_write = None + if cached_current is not None: + curr_pool_start, curr_k_fp8, curr_k_scale = cached_current[:3] + curr_pool_len = curr_k_fp8.shape[0] + if len(cached_current) == 4: + deferred_cache_write = ( + cached_current[3], + curr_k_fp8, + curr_k_scale, + ) + else: + curr_pool_start, curr_pool_len = pool_seq_len, 0 + if ( + pool_seq_len > 0 + and deferred_cache_write is not None + and self.alt_stream is not None + and not get_is_capture_mode() + ): + write_locs, write_k_fp8, write_k_scale = deferred_cache_write + current_stream = torch.cuda.current_stream() + self.alt_stream.wait_stream(current_stream) + pending_cache_tensors.append( + (write_locs, write_k_fp8, write_k_scale) + ) + with torch.cuda.stream(self.alt_stream): + self._write_returned_compressed_pooled_index_cache( + forward_batch, + layer_id, + write_locs, + write_k_fp8, + write_k_scale, + ) + cache_write_stream = self.alt_stream + pending_cache_req_pool_indices.add(req_pool_idx) + deferred_cache_write = None + + if ( + cached_current is not None + and curr_pool_start == 0 + and curr_pool_len == pool_seq_len + ): + k_fp8 = curr_k_fp8 + k_scale = curr_k_scale + elif ( + cached_current is not None + and curr_pool_start >= 0 + and curr_pool_start + curr_pool_len == pool_seq_len + ): + if curr_pool_start > 0: + pooled_page_table = ( + pooled_page_tables[i] + if pooled_page_tables is not None + else None + ) + if pooled_page_table is None: + num_token_pages = (seq_len + page_size - 1) // page_size + token_page_table = block_tables[ + i, :num_token_pages + ].contiguous() + pool_pages = (curr_pool_start + page_size - 1) // page_size + pooled_page_table = build_pooled_page_table_64( + token_page_table, pool_size + )[:pool_pages].contiguous() + k_u8 = torch.empty( + (pool_seq_len, self.head_dim), + dtype=torch.uint8, + device=q_fp8.device, + ) + k_scale = torch.empty( + (pool_seq_len,), dtype=torch.float32, device=q_fp8.device + ) + pool = get_token_to_kv_pool() + gather_index_k_scale_prefix_into( + pool=pool, + buf=self._get_index_k_read_buffer(pool, layer_id), + page_indices=pooled_page_table, + seq_len=curr_pool_start, + k_out=k_u8, + scale_out=k_scale, + ) + k_u8[curr_pool_start:pool_seq_len].copy_( + curr_k_fp8.view(torch.uint8) + ) + k_scale[curr_pool_start:pool_seq_len].copy_(curr_k_scale) + k_fp8 = k_u8.view(torch.float8_e4m3fn) + else: + k_fp8 = curr_k_fp8 + k_scale = curr_k_scale + else: + pooled_page_table = ( + pooled_page_tables[i] + if pooled_page_tables is not None + else None + ) + if pooled_page_table is None: + num_token_pages = (seq_len + page_size - 1) // page_size + token_page_table = block_tables[ + i, :num_token_pages + ].contiguous() + pool_pages = (pool_seq_len + page_size - 1) // page_size + pooled_page_table = build_pooled_page_table_64( + token_page_table, pool_size + )[:pool_pages].contiguous() + seq_len_t = torch.tensor( + [pool_seq_len], dtype=torch.int32, device=q_fp8.device + ) + k_fp8, k_scale = get_token_to_kv_pool().get_index_k_scale_buffer( + layer_id, + seq_len_t, + pooled_page_table.unsqueeze(0), + pool_seq_len, + pool_seq_len, + ) + k_fp8 = k_fp8.view(torch.float8_e4m3fn) + k_scale = k_scale.view(torch.float32).squeeze(-1) + row_starts = ( + zero_starts_by_batch[i] + if zero_starts_by_batch is not None + and zero_starts_by_batch[i] is not None + else torch.zeros((q_len,), dtype=torch.int32, device=q_fp8.device) + ) + local_logits = deep_gemm.fp8_mqa_logits( + q_fp8[q_slice].contiguous(), + (k_fp8.contiguous(), k_scale.contiguous()), + weights[q_slice].contiguous(), + row_starts, + local_pool_lens, + clean_logits=True, + ) + else: + local_logits = torch.empty( + (q_len, 0), dtype=torch.float32, device=q_fp8.device + ) + + page_table_local = None + topk_offsets_local = None + if ( + envs.SGLANG_DSA_FUSE_TOPK.get() + and topk_method == TopkTransformMethod.PAGED + ): + page_table_local = ( + get_req_to_token_pool() + .req_to_token[req_pool_idx, :seq_len] + .to(torch.int32) + ) + page_table_local = page_table_local.unsqueeze(0).expand(q_len, -1) + elif ( + envs.SGLANG_DSA_FUSE_TOPK.get() + and topk_method == TopkTransformMethod.RAGGED + and topk_offsets is not None + ): + topk_offsets_local = topk_offsets[q_slice] + + local_topk = self._topk_from_kpool_logits( + local_logits, + local_pool_lens, + seq_lens=local_seqlens, + page_table=page_table_local, + topk_offsets=topk_offsets_local, + ) + + topk_result[q_slice] = local_topk + if pool_seq_len > 0 and deferred_cache_write is not None: + write_locs, curr_k_fp8, curr_k_scale = deferred_cache_write + self._write_returned_compressed_pooled_index_cache( + forward_batch, + layer_id, + write_locs, + curr_k_fp8, + curr_k_scale, + ) + q_offset += q_len + + if cache_write_stream is not None: + torch.cuda.current_stream().wait_stream(cache_write_stream) + pending_cache_tensors.clear() + + return topk_result + + def _get_topk_ragged( + self, + forward_batch: ForwardBatch, + layer_id: int, + q_fp8: torch.Tensor, + weights: torch.Tensor, + metadata: BaseIndexerMetadata, + kpool_extend_cache: Optional[ + List[Optional[Tuple[int, torch.Tensor, torch.Tensor, torch.Tensor]]] + ] = None, + ) -> torch.Tensor: + if TYPE_CHECKING: + assert isinstance(get_token_to_kv_pool(), DSATokenToKVPool) + + assert forward_batch.forward_mode.is_extend_without_speculative() + + page_size = get_token_to_kv_pool().page_size + assert page_size == 64, "only support page size 64" + assert len(weights.shape) == 3 + weights = weights.squeeze(-1) + if metadata.attn_metadata.kpool_extend_plan is not None: + return self._get_topk_ragged_kpool_plan( + forward_batch, + layer_id, + q_fp8, + weights, + metadata, + ) + return self._get_topk_ragged_kpool( + forward_batch, + layer_id, + q_fp8, + weights, + metadata, + extend_pooled_cache=kpool_extend_cache, + ) + + def _forward_cuda_skip_logits( + self, + x: torch.Tensor, + positions: torch.Tensor, + forward_batch: ForwardBatch, + layer_id: int, + act_quant, + metadata: BaseIndexerMetadata, + return_indices: bool = True, + ) -> Optional[torch.Tensor]: + assert forward_batch.forward_mode.is_extend_without_speculative() + + key = self._get_k_bf16(x, positions) + self._compress_write( + x=x, + key=key, + positions=positions, + forward_batch=forward_batch, + layer_id=layer_id, + metadata=metadata, + ) + + if not return_indices: + return None + + return self._full_topk_for_short_sequence(metadata, x.device) + + def _forward_cuda_target_verify( + self, + x: torch.Tensor, + q_lora: torch.Tensor, + positions: torch.Tensor, + forward_batch: ForwardBatch, + layer_id: int, + act_quant, + metadata: BaseIndexerMetadata, + enable_dual_stream: bool, + return_indices: bool = True, + ) -> Optional[torch.Tensor]: + assert is_cuda(), "DSA kpool target_verify is CUDA-only" + plan = metadata.attn_metadata.kpool_write_plan + assert plan is not None, "DSA kpool target_verify requires kpool_write_plan" + num_draft_tokens = plan.num_draft_tokens + + query, key, gate_score_maybe = self._get_q_k_bf16( + q_lora, + x, + positions, + enable_dual_stream=enable_dual_stream, + forward_batch=forward_batch, + precompute_compress_gate=( + enable_dual_stream and self.compress_gate_stream is not None + ), + ) + + pool = get_token_to_kv_pool() + tail_k_buf, tail_score_buf = pool.get_compress_tail_buffers(layer_id) + + from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( + kpool_write_tail_and_maybe_compress, + ) + + buf = pool.get_index_k_with_scale_buffer(layer_id=layer_id) + + def _compress_write() -> None: + kpool_write_tail_and_maybe_compress( + pool=pool, + buf=buf, + key=key, + score=self._compute_gate_score_if_missing(x, gate_score_maybe), + tail_k=tail_k_buf, + tail_score=tail_score_buf, + ape=self.index_kpool_compress_ape, + req_pool_indices=plan.req, + write_start=plan.write_start, + tail_logical_start=plan.tail_logical_start, + write_loc=plan.write_loc, + out_cache_loc=forward_batch.out_cache_loc, + num_draft_tokens=num_draft_tokens, + round_scale=self.scale_fmt is not None, + effective_n_per_batch=plan.effective_n_per_batch, + ) + + if enable_dual_stream: + current_stream = torch.cuda.current_stream() + self.alt_stream.wait_stream(current_stream) + if gate_score_maybe is not None: + assert self.compress_gate_stream is not None + self.alt_stream.wait_stream(self.compress_gate_stream) + if return_indices: + q_fp8, q_scale = act_quant(query, self.block_size, self.scale_fmt) + weights = self._get_logits_head_gate(x, q_scale) + with torch.cuda.stream(self.alt_stream): + _compress_write() + current_stream.wait_stream(self.alt_stream) + else: + _compress_write() + if return_indices: + q_fp8, q_scale = act_quant(query, self.block_size, self.scale_fmt) + weights = self._get_logits_head_gate(x, q_scale) + + if not return_indices: + return None + return self._get_topk_paged(forward_batch, layer_id, q_fp8, weights, metadata) + + def forward_cuda( + self, + x: torch.Tensor, + q_lora: torch.Tensor, + positions: torch.Tensor, + forward_batch: ForwardBatch, + layer_id: int, + return_indices: bool = True, + ) -> Optional[torch.Tensor]: + if is_hip(): + from sglang.kernels.ops.attention.dsa.tilelang_kernel import act_quant + elif not is_npu(): + from sglang.kernels.ops.attention.dsa.triton_kernel import act_quant + + if TYPE_CHECKING: + assert isinstance(get_token_to_kv_pool(), DSATokenToKVPool) + + metadata = get_attn_backend().get_indexer_metadata(layer_id, forward_batch) + + enable_dual_stream = ( + self.alt_stream is not None + and get_is_capture_mode() + and q_lora.shape[0] > 0 + and q_lora.shape[0] <= DUAL_STREAM_TOKEN_THRESHOLD + ) + + # Skip DSA if the attention backend chooses to skip this batch. + if metadata is None: + return None + + assert forward_batch.seq_lens_cpu is not None + mode = forward_batch.forward_mode + if mode.is_idle() or len(forward_batch.seq_lens_cpu) == 0: + return torch.full( + (x.shape[0], self.index_topk + self.index_kpool - 1), + -1, + dtype=torch.int, + device=x.device, + ) + + if ( + forward_batch.forward_mode.is_target_verify() + or forward_batch.forward_mode.is_draft_extend_v2() + ): + return self._forward_cuda_target_verify( + x=x, + q_lora=q_lora, + positions=positions, + forward_batch=forward_batch, + layer_id=layer_id, + act_quant=act_quant, + metadata=metadata, + enable_dual_stream=enable_dual_stream, + return_indices=return_indices, + ) + + # CUDA graph capture keeps the full topk path; the skip branch is extend-only. + skip_logits_computation = False + if forward_batch.forward_mode.is_extend_without_speculative(): + if forward_batch.seq_lens_cpu is not None: + max_kv_len = forward_batch.seq_lens_cpu.max().item() + skip_logits_computation = max_kv_len <= self.index_topk + + if skip_logits_computation and (not self.dsa_enable_prefill_cp): + return self._forward_cuda_skip_logits( + x, + positions, + forward_batch, + layer_id, + act_quant, + metadata, + return_indices, + ) + + precompute_compress_gate = ( + self.index_kpool > 1 + and self.index_kpool_compress + and enable_dual_stream + and forward_batch.forward_mode.is_decode_or_idle() + and self.compress_gate_stream is not None + ) + query, key, gate_score = self._get_q_k_bf16( + q_lora, + x, + positions, + enable_dual_stream, + forward_batch=forward_batch, + precompute_compress_gate=precompute_compress_gate, + ) + use_cp = dsa_use_prefill_cp(forward_batch, self.dsa_enable_prefill_cp) + if use_cp: + if gate_score is None: + gate_score = self._compute_gate_score_if_missing(x, gate_score) + key, gate_score = self._cp_gather_concat( + [key, gate_score], self.cp_size, forward_batch + ) + + weights = None + kpool_extend_cache = None + if enable_dual_stream and forward_batch.forward_mode.is_decode_or_idle(): + current_stream = torch.cuda.current_stream() + self.alt_stream.wait_stream(current_stream) + if gate_score is not None: + self.alt_stream.wait_stream(self.compress_gate_stream) + with torch.cuda.stream(self.alt_stream): + self._compress_write( + x=x, + key=key, + positions=positions, + forward_batch=forward_batch, + layer_id=layer_id, + metadata=metadata, + gate_score=gate_score, + ) + q_fp8, q_scale = act_quant(query, self.block_size, self.scale_fmt) + weights = self._get_logits_head_gate(x, q_scale) + current_stream.wait_stream(self.alt_stream) + else: + q_fp8, q_scale = act_quant(query, self.block_size, self.scale_fmt) + has_kpool_extend_plan = metadata.attn_metadata.kpool_extend_plan is not None + defer_kpool_cache_write = ( + forward_batch.forward_mode.is_extend_without_speculative() + and return_indices + and not has_kpool_extend_plan + ) + kpool_extend_cache = self._compress_write( + x=x, + key=key, + positions=positions, + forward_batch=forward_batch, + layer_id=layer_id, + metadata=metadata, + gate_score=gate_score, + return_compressed=( + forward_batch.forward_mode.is_extend_without_speculative() + and return_indices + ), + write_cache=not defer_kpool_cache_write, + ) + if ( + forward_batch.forward_mode.is_extend_without_speculative() + and not return_indices + ): + return None + + if weights is None: + weights = self._get_logits_head_gate(x, q_scale) + + if is_cuda(): + if ( + forward_batch.forward_mode.is_decode_or_idle() + or forward_batch.forward_mode.is_target_verify() + or forward_batch.forward_mode.is_draft_extend_v2() + ): + topk_result = self._get_topk_paged( + forward_batch, layer_id, q_fp8, weights, metadata + ) + else: + if ( + forward_batch.attn_cp_metadata is not None + and self.dsa_enable_prefill_cp + and is_dsa_prefill_cp_in_seq_split() + ): + kv_len_prev = forward_batch.attn_cp_metadata.kv_len_prev_list[0] + kv_len_next = forward_batch.attn_cp_metadata.kv_len_next_list[0] + actual_seq_q_prev = ( + forward_batch.attn_cp_metadata.actual_seq_q_prev_list[0] + ) + actual_seq_q_next = ( + forward_batch.attn_cp_metadata.actual_seq_q_next_list[0] + ) + q_fp8_prev, q_fp8_next = torch.split( + q_fp8, (q_fp8.shape[0] + 1) // 2, dim=0 + ) + weights_prev, weights_next = torch.split( + weights, (weights.shape[0] + 1) // 2, dim=0 + ) + topk_result_prev = self._get_topk_ragged_with_cp( + forward_batch, + layer_id, + q_fp8_prev, + weights_prev, + metadata, + kv_len_prev, + actual_seq_q_prev, + ) + topk_result_next = self._get_topk_ragged_with_cp( + forward_batch, + layer_id, + q_fp8_next, + weights_next, + metadata, + kv_len_next, + actual_seq_q_next, + ) + topk_result = torch.cat([topk_result_prev, topk_result_next], dim=0) + elif has_kpool_extend_plan: + topk_result = self._get_topk_ragged_kpool_plan( + forward_batch, + layer_id, + q_fp8, + weights, + metadata, + ) + else: + topk_result = self._get_topk_ragged( + forward_batch, + layer_id, + q_fp8, + weights, + metadata, + kpool_extend_cache=kpool_extend_cache, + ) + else: + raise NotImplementedError("kpool indexer is only supported on CUDA") + return topk_result diff --git a/python/sglang/srt/layers/attention/dsa/kpool_fp8_index.py b/python/sglang/srt/layers/attention/dsa/kpool_fp8_index.py new file mode 100644 index 0000000000000..6d290a091c528 --- /dev/null +++ b/python/sglang/srt/layers/attention/dsa/kpool_fp8_index.py @@ -0,0 +1,1720 @@ +from typing import Optional, Tuple + +import torch +import triton +import triton.language as tl + +BLOCK_SIZE_K = 64 +INDEX_HEAD_DIM = 128 +KPOOL_SCORE_DTYPES = (torch.float16, torch.bfloat16, torch.float32) + + +def kpool_max_closed_pools(num_draft_tokens: int, pool_size: int) -> int: + """Return the most pools an N-token write can close at any start offset.""" + return (num_draft_tokens + pool_size - 1) // pool_size + + +def build_pooled_page_table_64( + page_table_64: torch.Tensor, + pool_size: int, +) -> torch.Tensor: + """Pack one logical pool page into the first token page of each page group. + + Uses advanced indexing (gather) rather than strided slicing so the result + is always a freshly allocated row-major tensor. Strided slicing produces + a view whose .contiguous() short-circuits for shape==(1, 1), leaving + stride(-1) == pool_size and breaking downstream kernels that require + stride(-1) == 1 (e.g. deep_gemm.fp8_paged_mqa_logits). + """ + assert ( + BLOCK_SIZE_K % pool_size == 0 + ), f"pool_size ({pool_size}) must divide page_size ({BLOCK_SIZE_K})" + idx = torch.arange( + 0, page_table_64.shape[-1], pool_size, device=page_table_64.device + ) + return page_table_64[..., idx] + + +def gather_index_k_scale_prefix_into( + pool, + buf: torch.Tensor, + page_indices: torch.Tensor, + seq_len: int, + k_out: torch.Tensor, + scale_out: torch.Tensor, +) -> None: + assert buf.dtype == torch.uint8 + assert page_indices.dtype in (torch.int32, torch.int64) + assert k_out.dtype == torch.uint8 + assert scale_out.dtype == torch.float32 + assert pool.page_size == BLOCK_SIZE_K + assert k_out.shape[0] >= seq_len + assert k_out.shape[1] == INDEX_HEAD_DIM + assert scale_out.shape[0] >= seq_len + assert buf.is_contiguous() + assert page_indices.is_contiguous() + assert k_out.is_contiguous() + assert scale_out.is_contiguous() + if seq_len == 0: + return + + _gather_index_k_scale_prefix_into_kernel[(seq_len,)]( + buf, + buf.view(torch.float32), + page_indices, + k_out, + scale_out, + PAGE_SIZE=pool.page_size, + BUF_NUMEL_PER_PAGE=buf.shape[1], + HEAD_DIM=INDEX_HEAD_DIM, + S_OFFSET_NBYTES_IN_PAGE=pool.page_size * INDEX_HEAD_DIM, + BLOCK_D=triton.next_power_of_2(INDEX_HEAD_DIM), + ) + + +@triton.jit +def _gather_index_k_scale_prefix_into_kernel( + buf_u8_ptr, + buf_fp32_ptr, + page_indices_ptr, + k_out_ptr, + scale_out_ptr, + PAGE_SIZE: tl.constexpr, + BUF_NUMEL_PER_PAGE: tl.constexpr, + HEAD_DIM: tl.constexpr, + S_OFFSET_NBYTES_IN_PAGE: tl.constexpr, + BLOCK_D: tl.constexpr, +): + token_id = tl.program_id(0) + page_idx = token_id // PAGE_SIZE + token_offset_in_page = token_id % PAGE_SIZE + page = tl.load(page_indices_ptr + page_idx) + + offs = tl.arange(0, BLOCK_D) + mask = offs < HEAD_DIM + src_k_offsets = page * BUF_NUMEL_PER_PAGE + token_offset_in_page * HEAD_DIM + offs + dst_k_offsets = token_id * HEAD_DIM + offs + k = tl.load(buf_u8_ptr + src_k_offsets, mask=mask) + tl.store(k_out_ptr + dst_k_offsets, k, mask=mask) + + src_s_offset = ( + page * BUF_NUMEL_PER_PAGE // 4 + + S_OFFSET_NBYTES_IN_PAGE // 4 + + token_offset_in_page + ) + scale = tl.load(buf_fp32_ptr + src_s_offset) + tl.store(scale_out_ptr + token_id, scale) + + +def kpool_build_ragged_layout( + full_page_table: torch.Tensor, + cu_pages_excl: torch.Tensor, + ragged_pool_pages: torch.Tensor, + cu_q_len_excl: torch.Tensor, + ragged_q_len: torch.Tensor, + pooled_seq_lens_expanded: torch.Tensor, + slots_per_page: int, + total_pool_pages: int, + total_q: int, + pool_size: int, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Build one flat pooled-page table plus per-q row starts/ends. + + DSA stores 64 pooled entries per physical page. A pooled page therefore + corresponds to every ``pool_size``-th 64-token page in the original real + page table. + """ + device = full_page_table.device + n_rag = cu_pages_excl.shape[0] + concat_page_table = torch.empty( + (total_pool_pages,), dtype=full_page_table.dtype, device=device + ) + q_ks = torch.empty((total_q,), dtype=torch.int32, device=device) + q_ke = torch.empty((total_q,), dtype=torch.int32, device=device) + if n_rag == 0: + return concat_page_table, q_ks, q_ke + + max_pool_pages = full_page_table.shape[1] + _kpool_build_ragged_layout_kernel[(n_rag,)]( + full_page_table, + cu_pages_excl, + ragged_pool_pages, + cu_q_len_excl, + ragged_q_len, + pooled_seq_lens_expanded, + concat_page_table, + q_ks, + q_ke, + max_pool_pages, + slots_per_page, + pool_size, + BLOCK_PAGE=128, + BLOCK_Q=128, + ) + return concat_page_table, q_ks, q_ke + + +@triton.jit +def _kpool_build_ragged_layout_kernel( + full_page_table_ptr, + cu_pages_excl_ptr, + ragged_pool_pages_ptr, + cu_q_len_excl_ptr, + ragged_q_len_ptr, + pooled_seq_lens_ptr, + concat_page_table_ptr, + q_ks_ptr, + q_ke_ptr, + MAX_POOL_PAGES, + SLOTS_PER_PAGE: tl.constexpr, + POOL_SIZE: tl.constexpr, + BLOCK_PAGE: tl.constexpr, + BLOCK_Q: tl.constexpr, +): + k = tl.program_id(0) + page_start = tl.load(cu_pages_excl_ptr + k) + n_pages = tl.load(ragged_pool_pages_ptr + k) + q_start = tl.load(cu_q_len_excl_ptr + k) + q_count = tl.load(ragged_q_len_ptr + k) + ks_val = page_start * SLOTS_PER_PAGE + + for p_off in tl.range(0, BLOCK_PAGE * tl.cdiv(n_pages, BLOCK_PAGE), BLOCK_PAGE): + p_offs = p_off + tl.arange(0, BLOCK_PAGE) + p_mask = p_offs < n_pages + source_cols = p_offs * POOL_SIZE + pages = tl.load( + full_page_table_ptr + k * MAX_POOL_PAGES + source_cols, + mask=p_mask, + other=0, + ) + tl.store(concat_page_table_ptr + page_start + p_offs, pages, mask=p_mask) + + for q_off in tl.range(0, BLOCK_Q * tl.cdiv(q_count, BLOCK_Q), BLOCK_Q): + q_offs = q_off + tl.arange(0, BLOCK_Q) + q_mask = q_offs < q_count + plen = tl.load(pooled_seq_lens_ptr + q_start + q_offs, mask=q_mask, other=0) + ke_val = tl.minimum( + ks_val + plen, + (page_start + n_pages) * SLOTS_PER_PAGE, + ) + tl.store( + q_ks_ptr + q_start + q_offs, + tl.full([BLOCK_Q], ks_val, tl.int32), + mask=q_mask, + ) + tl.store(q_ke_ptr + q_start + q_offs, ke_val, mask=q_mask) + + +def _prep_update_kpool_write_plan_launch( + write_start: torch.Tensor, + req_pool_indices: torch.Tensor, + real_page_table: torch.Tensor, + req_out: torch.Tensor, + write_start_out: torch.Tensor, + tail_logical_start_out: torch.Tensor, + write_loc_out: torch.Tensor, + pool_seqlens_per_q_out: Optional[torch.Tensor], + seqlens_per_q_out: Optional[torch.Tensor], + *, + pool_size: int, + num_draft_tokens: int, + slots_per_page: int, +): + """Validate and build the (bs, args, constexpr kwargs) launch spec for the + write-plan kernel. Shared between the per-call wrapper below and the + prebound cuda-graph replay launcher. Mirrors the eager path exactly, + including pool_size < num_draft_tokens support (max_closed_pools).""" + max_closed_pools = kpool_max_closed_pools(num_draft_tokens, pool_size) + bs = write_start.shape[0] + + assert write_loc_out.shape == (bs, max_closed_pools), write_loc_out.shape + assert write_loc_out.stride(1) == 1, write_loc_out.stride() + + has_per_q_outputs = pool_seqlens_per_q_out is not None + assert has_per_q_outputs == ( + seqlens_per_q_out is not None + ), "pool_seqlens_per_q_out and seqlens_per_q_out must be both set or both None" + per_q_dummy = ( + pool_seqlens_per_q_out + if has_per_q_outputs + else torch.empty(1, dtype=torch.int32, device=write_start.device) + ) + + args = ( + write_start, + req_pool_indices, + real_page_table, + req_out, + write_start_out, + tail_logical_start_out, + write_loc_out, + pool_seqlens_per_q_out if has_per_q_outputs else per_q_dummy, + seqlens_per_q_out if has_per_q_outputs else per_q_dummy, + real_page_table.stride(0), + real_page_table.shape[1], + write_loc_out.stride(0), + ) + constexprs = dict( + POOL_SIZE=pool_size, + N=num_draft_tokens, + SLOTS_PER_PAGE=slots_per_page, + MAX_CLOSED_POOLS=max_closed_pools, + HAS_PER_Q=has_per_q_outputs, + ) + return bs, args, constexprs + + +def update_kpool_write_plan_cuda_graph( + write_start: torch.Tensor, + req_pool_indices: torch.Tensor, + real_page_table: torch.Tensor, + req_out: torch.Tensor, + write_start_out: torch.Tensor, + tail_logical_start_out: torch.Tensor, + write_loc_out: torch.Tensor, + pool_seqlens_per_q_out: Optional[torch.Tensor], + seqlens_per_q_out: Optional[torch.Tensor], + *, + pool_size: int, + num_draft_tokens: int, + slots_per_page: int, +) -> None: + if write_start.shape[0] == 0: + return + bs, args, constexprs = _prep_update_kpool_write_plan_launch( + write_start, + req_pool_indices, + real_page_table, + req_out, + write_start_out, + tail_logical_start_out, + write_loc_out, + pool_seqlens_per_q_out, + seqlens_per_q_out, + pool_size=pool_size, + num_draft_tokens=num_draft_tokens, + slots_per_page=slots_per_page, + ) + _update_kpool_write_plan_kernel[(bs,)](*args, **constexprs) + + +@triton.jit +def _update_kpool_write_plan_kernel( + write_start_ptr, + req_pool_indices_ptr, + real_page_table_ptr, + req_out_ptr, + write_start_out_ptr, + tail_logical_start_out_ptr, + write_loc_out_ptr, + pool_seqlens_per_q_out_ptr, + seqlens_per_q_out_ptr, + real_page_table_stride_0, + real_page_table_cols, + write_loc_out_stride_0, + POOL_SIZE: tl.constexpr, + N: tl.constexpr, + SLOTS_PER_PAGE: tl.constexpr, + MAX_CLOSED_POOLS: tl.constexpr, + HAS_PER_Q: tl.constexpr, +): + b = tl.program_id(0) + ws = tl.load(write_start_ptr + b).to(tl.int32) + req = tl.load(req_pool_indices_ptr + b) + base_pool = ws // POOL_SIZE + + if HAS_PER_Q: + for k in tl.static_range(0, N): + row = b * N + k + seqlen_per_q = ws + k + 1 + tl.store(seqlens_per_q_out_ptr + row, seqlen_per_q) + tl.store(pool_seqlens_per_q_out_ptr + row, seqlen_per_q // POOL_SIZE) + + tl.store(req_out_ptr + b, req) + tl.store(write_start_out_ptr + b, ws) + tl.store(tail_logical_start_out_ptr + b, (base_pool * POOL_SIZE).to(tl.int32)) + for p in tl.static_range(0, MAX_CLOSED_POOLS): + pool_id = base_pool + p + pool_page_group = pool_id // SLOTS_PER_PAGE + token_page_row = pool_page_group * POOL_SIZE + token_page_row = tl.minimum( + tl.maximum(token_page_row, 0), real_page_table_cols - 1 + ) + # Promote the row term to int64 before the pointer math (same as the + # fused metadata kernels): a row index times a context-scale stride + # wraps int32 well before the buffer does. + packed_page = tl.load( + real_page_table_ptr + + (b * N).to(tl.int64) * real_page_table_stride_0 + + token_page_row + ).to(tl.int64) + write_loc = packed_page * SLOTS_PER_PAGE + (pool_id % SLOTS_PER_PAGE) + tl.store( + write_loc_out_ptr + b * write_loc_out_stride_0 + p, + write_loc.to(tl.int64), + ) + + +def compute_pooled_write_locs( + page_table_64: torch.Tensor, + pool_ids: torch.Tensor, + pool_size: int, +) -> torch.Tensor: + """Map logical pooled-K ids to packed physical index-cache locations.""" + assert page_table_64.ndim == 1 + pool_ids = pool_ids.to(torch.int64) + pool_page_group = torch.div(pool_ids, BLOCK_SIZE_K, rounding_mode="floor") + token_page_row = pool_page_group * pool_size + packed_page = page_table_64.index_select(0, token_page_row.to(torch.int64)) + return packed_page.to(torch.int64) * BLOCK_SIZE_K + torch.remainder( + pool_ids, BLOCK_SIZE_K + ) + + +def history_group_budget_for_topk(topk: int, pool_size: int) -> int: + assert topk % pool_size == 0 + return topk // pool_size + + +def expand_pooled_groups_to_topk( + group_ids: torch.Tensor, + group_valid: torch.Tensor, + topk: int, + pool_size: int, + page_table: torch.Tensor | None = None, + topk_offsets: torch.Tensor | None = None, +) -> torch.Tensor: + """Expand selected full-pool ids to a strict-width token topk tensor.""" + assert group_ids.ndim == 2 + assert group_valid.shape == group_ids.shape + assert topk % pool_size == 0 + assert group_ids.shape[1] == history_group_budget_for_topk(topk, pool_size) + assert page_table is None or topk_offsets is None + + device = group_ids.device + offsets = torch.arange(pool_size, device=device, dtype=torch.int64) + token_ids = group_ids.to(torch.int64).unsqueeze(-1) * pool_size + offsets + token_ids = token_ids.reshape(group_ids.shape[0], topk) + valid = ( + group_valid.unsqueeze(-1) + .expand(-1, -1, pool_size) + .reshape(group_ids.shape[0], topk) + ) + + if page_table is not None: + assert page_table.ndim == 2 + assert page_table.shape[0] == group_ids.shape[0] + safe_ids = token_ids.clamp(min=0, max=page_table.shape[1] - 1) + output = torch.gather(page_table, dim=1, index=safe_ids).to(torch.int32) + elif topk_offsets is not None: + if topk_offsets.ndim == 2: + assert topk_offsets.shape[1] == 1 + topk_offsets = topk_offsets.squeeze(1) + assert topk_offsets.ndim == 1 + output = (token_ids + topk_offsets.to(torch.int64).unsqueeze(1)).to(torch.int32) + else: + output = token_ids.to(torch.int32) + + return torch.where(valid, output, torch.full_like(output, -1)) + + +def append_kpool_tail_to_topk( + topk_result: torch.Tensor, + seq_lens: torch.Tensor, + pool_lens: torch.Tensor, + pool_size: int, + page_table: torch.Tensor | None = None, + topk_offsets: torch.Tensor | None = None, +) -> torch.Tensor: + """Append non-pooled tail tokens after selected expanded-history tokens.""" + assert topk_result.dtype == torch.int32 + assert seq_lens.ndim == 1 + assert pool_lens.ndim == 1 + assert seq_lens.shape[0] == topk_result.shape[0] + assert pool_lens.shape[0] == topk_result.shape[0] + + tail_pool = pool_size - 1 + if tail_pool == 0: + return topk_result + + rows, n_cols = topk_result.shape + out_cols = n_cols + tail_pool + out = torch.empty( + (rows, out_cols), dtype=topk_result.dtype, device=topk_result.device + ) + + if page_table is None: + page_table = topk_result + has_page_table = False + page_table_cols = 1 + else: + assert page_table.ndim == 2 + has_page_table = True + page_table_cols = page_table.shape[1] + + if topk_offsets is None: + topk_offsets = seq_lens + has_topk_offsets = False + else: + if topk_offsets.ndim == 2: + assert topk_offsets.shape[1] == 1 + topk_offsets = topk_offsets.squeeze(1) + assert topk_offsets.ndim == 1 + has_topk_offsets = True + + block_cols = triton.next_power_of_2(out_cols) + _append_kpool_tail_to_topk_kernel[(rows,)]( + topk_result, + seq_lens, + pool_lens, + page_table, + topk_offsets, + out, + topk_result.stride(0), + topk_result.stride(1), + page_table.stride(0), + page_table.stride(1), + out.stride(0), + out.stride(1), + N_COLS=n_cols, + OUT_COLS=out_cols, + PAGE_TABLE_COLS=page_table_cols, + POOL_SIZE=pool_size, + HAS_PAGE_TABLE=has_page_table, + HAS_TOPK_OFFSETS=has_topk_offsets, + BLOCK_COLS=block_cols, + ) + return out + + +@triton.jit +def _append_kpool_tail_to_topk_kernel( + topk_ptr, + seq_lens_ptr, + pool_lens_ptr, + page_table_ptr, + topk_offsets_ptr, + out_ptr, + topk_stride_0, + topk_stride_1, + page_table_stride_0, + page_table_stride_1, + out_stride_0, + out_stride_1, + N_COLS: tl.constexpr, + OUT_COLS: tl.constexpr, + PAGE_TABLE_COLS: tl.constexpr, + POOL_SIZE: tl.constexpr, + HAS_PAGE_TABLE: tl.constexpr, + HAS_TOPK_OFFSETS: tl.constexpr, + BLOCK_COLS: tl.constexpr, +): + row = tl.program_id(0) + cols = tl.arange(0, BLOCK_COLS) + mask = cols < OUT_COLS + + seq_len = tl.load(seq_lens_ptr + row).to(tl.int32) + pool_len = tl.load(pool_lens_ptr + row).to(tl.int32) + tail_start = pool_len * POOL_SIZE + history_len = tl.minimum(tail_start, N_COLS) + tail_count = seq_len % POOL_SIZE + + is_history = cols < history_len + safe_history_cols = tl.minimum(cols, N_COLS - 1) + history_value = tl.load( + topk_ptr + row * topk_stride_0 + safe_history_cols * topk_stride_1, + mask=mask & is_history, + other=-1, + ) + + tail_offset = cols - history_len + is_tail = (tail_offset >= 0) & (tail_offset < tail_count) + tail_raw = tail_start + tail_offset + tail_value = tail_raw + if HAS_PAGE_TABLE: + safe_tail = tl.minimum(tl.maximum(tail_raw, 0), PAGE_TABLE_COLS - 1) + # int64 row term: the wide page table's row stride is context-scale + # (~2^20 on 1M-context models), so row * stride wraps int32 from + # row ~2048 — same promotion as the fused metadata kernels. + tail_value = tl.load( + page_table_ptr + + row.to(tl.int64) * page_table_stride_0 + + safe_tail * page_table_stride_1, + mask=mask & is_tail, + other=-1, + ).to(tl.int32) + if HAS_TOPK_OFFSETS: + offset = tl.load(topk_offsets_ptr + row).to(tl.int32) + tail_value = tail_raw + offset + + value = tl.where(is_history, history_value, -1) + value = tl.where(is_tail, tail_value, value) + tl.store(out_ptr + row * out_stride_0 + cols * out_stride_1, value, mask=mask) + + +def topk_from_pooled_history_logits( + logits: torch.Tensor, + group_lengths: torch.Tensor, + pool_size: int, + topk: int, + page_table: torch.Tensor | None = None, + topk_offsets: torch.Tensor | None = None, + seq_lens: torch.Tensor | None = None, + row_starts: torch.Tensor | None = None, + out_rows: int | None = None, + page_table_row_index: torch.Tensor | None = None, +) -> torch.Tensor: + """Select full-pool groups, expand to tokens, and optionally append tail.""" + assert logits.ndim == 2 + assert group_lengths.ndim == 1 + assert logits.shape[0] == group_lengths.shape[0] + assert topk > 0 + assert topk % pool_size == 0 + assert out_rows is None or out_rows >= logits.shape[0] + assert page_table_row_index is None or page_table is not None + + _, cols = logits.shape + group_topk = history_group_budget_for_topk(topk, pool_size) + if topk_offsets is not None and topk_offsets.ndim == 2: + assert topk_offsets.shape[1] == 1 + topk_offsets = topk_offsets.squeeze(1) + + if group_topk not in (128, 160, 192, 224, 256, 512, 2048): + raise NotImplementedError( + "index_kpool topk only supports pooled group_topk in " + f"(128, 160, 192, 224, 256, 512, 2048), got {group_topk} " + f"(topk={topk}, pool_size={pool_size})." + ) + if not logits.is_cuda or logits.dtype != torch.float32: + raise NotImplementedError( + "index_kpool topk requires CUDA float32 logits; PyTorch topk fallback " + f"is disabled. Got device={logits.device}, dtype={logits.dtype}." + ) + + if group_topk in (128, 160, 192, 224, 256, 512): + from sglang.kernels.ops.moe.kpool_topk_transform import ( + fast_kpool_topk_transform_fused, + ) + + result = fast_kpool_topk_transform_fused( + score=logits, + lengths=group_lengths.to(torch.int32), + pool_size=pool_size, + topk=topk, + page_table=page_table, + topk_indices_offset=topk_offsets, + row_starts=row_starts, + seq_lens=seq_lens.to(torch.int32) if seq_lens is not None else None, + page_table_row_index=page_table_row_index, + ) + if out_rows is None or out_rows == result.shape[0]: + return result + padded = torch.full( + (out_rows, result.shape[1]), -1, dtype=result.dtype, device=result.device + ) + padded[: result.shape[0]] = result + return padded + + assert ( + page_table_row_index is None + ), "page_table_row_index requires the fused fast_kpool group_topk path" + + from sgl_kernel import fast_topk_v2 + + selected_groups = fast_topk_v2( + logits, + group_lengths.to(torch.int32), + group_topk, + row_starts=row_starts, + ) + + rank = torch.arange(group_topk, device=logits.device, dtype=torch.int32) + max_valid_groups = min(cols, group_topk) + valid_counts = torch.minimum( + group_lengths.to(torch.int32), + torch.full_like(group_lengths.to(torch.int32), max_valid_groups), + ) + group_valid = rank.unsqueeze(0) < valid_counts.unsqueeze(1) + expanded = expand_pooled_groups_to_topk( + selected_groups.contiguous(), + group_valid, + topk=topk, + pool_size=pool_size, + page_table=page_table, + topk_offsets=topk_offsets, + ) + if seq_lens is None: + result = expanded + else: + result = append_kpool_tail_to_topk( + expanded, + seq_lens=seq_lens, + pool_lens=group_lengths, + pool_size=pool_size, + page_table=page_table, + topk_offsets=topk_offsets, + ) + if out_rows is None or out_rows == result.shape[0]: + return result + padded = torch.full( + (out_rows, result.shape[1]), -1, dtype=result.dtype, device=result.device + ) + padded[: result.shape[0]] = result + return padded + + +def kpool_softmax_rotate_write_cache( + pool, + buf: torch.Tensor, + slot_k: torch.Tensor, + slot_score: torch.Tensor, + ape: torch.Tensor, + loc: torch.Tensor, + write_mask: torch.Tensor | None = None, + round_scale: bool = False, + return_compressed: bool = False, + write_cache: bool = True, +) -> Optional[Tuple[torch.Tensor, torch.Tensor]]: + assert slot_k.ndim == 3 + assert slot_score.shape == slot_k.shape + assert ape.shape == slot_k.shape[1:] + assert slot_k.shape[2] == INDEX_HEAD_DIM + assert slot_k.dtype == torch.bfloat16 + assert slot_score.dtype in KPOOL_SCORE_DTYPES + assert ape.dtype == torch.float32 + assert buf.dtype == torch.uint8 + assert pool.page_size == BLOCK_SIZE_K + assert pool.index_head_dim == INDEX_HEAD_DIM + assert loc.dtype == torch.int64 + assert write_cache or return_compressed + + slot_k = slot_k.contiguous() + slot_score = slot_score.contiguous() + ape = ape.contiguous() + loc = loc.contiguous() + if write_mask is None: + write_mask = torch.empty((1,), dtype=torch.bool, device=slot_k.device) + has_write_mask = False + else: + assert write_mask.shape == (slot_k.shape[0],) + assert not return_compressed + write_mask = write_mask.contiguous() + has_write_mask = True + + if slot_k.shape[0] == 0: + if return_compressed: + return ( + torch.empty( + (0, slot_k.shape[2]), + dtype=torch.float8_e4m3fn, + device=slot_k.device, + ), + torch.empty((0,), dtype=torch.float32, device=slot_k.device), + ) + return None + + buf_fp8 = buf.view(torch.float8_e4m3fn) + buf_fp32 = buf.view(torch.float32) + if return_compressed: + compressed_k = torch.empty( + (slot_k.shape[0], slot_k.shape[2]), + dtype=torch.float8_e4m3fn, + device=slot_k.device, + ) + compressed_scale = torch.empty( + (slot_k.shape[0],), dtype=torch.float32, device=slot_k.device + ) + else: + compressed_k = buf_fp8 + compressed_scale = buf_fp32 + _kpool_softmax_rotate_write_cache_kernel[(slot_k.shape[0],)]( + buf_fp8, + buf_fp32, + slot_k, + slot_score, + ape, + loc, + write_mask, + compressed_k, + compressed_scale, + slot_k.stride(0), + slot_k.stride(1), + slot_score.stride(0), + slot_score.stride(1), + ape.stride(0), + PAGE_SIZE=pool.page_size, + BUF_NUMEL_PER_PAGE=buf.shape[1], + POOL_SIZE=slot_k.shape[1], + HEAD_DIM=slot_k.shape[2], + S_OFFSET_NBYTES_IN_PAGE=pool.page_size * pool.index_head_dim, + ROUND_SCALE=round_scale, + HAS_WRITE_MASK=has_write_mask, + RETURN_COMPRESSED=return_compressed, + WRITE_CACHE=write_cache, + BLOCK_D=triton.next_power_of_2(slot_k.shape[2]), + ) + if return_compressed: + return compressed_k, compressed_scale + return None + + +def kpool_decode_update_and_maybe_write_cache( + pool, + buf: torch.Tensor, + tail_k: torch.Tensor, + tail_score: torch.Tensor, + key: torch.Tensor, + slot_score: torch.Tensor, + ape: torch.Tensor, + block_tables: torch.Tensor, + req_pool_indices: torch.Tensor, + positions: torch.Tensor, + seq_lens: torch.Tensor, + out_cache_loc: torch.Tensor, + round_scale: bool = False, +) -> None: + assert tail_k.ndim == 3 + assert tail_score.shape == tail_k.shape + assert tail_k.shape[1] == pool.index_kpool + pool.tail_extra_slots + assert tail_k.shape[2] == INDEX_HEAD_DIM + assert key.ndim == 2 and key.shape[1] == INDEX_HEAD_DIM + assert slot_score.shape == key.shape + assert ape.shape == (pool.index_kpool, INDEX_HEAD_DIM) + assert tail_k.dtype == torch.bfloat16 + assert key.dtype == torch.bfloat16 + assert tail_score.dtype in KPOOL_SCORE_DTYPES + assert slot_score.dtype == tail_score.dtype + assert ape.dtype == torch.float32 + assert buf.dtype == torch.uint8 + assert pool.page_size == BLOCK_SIZE_K + assert pool.index_head_dim == INDEX_HEAD_DIM + assert tail_k.is_contiguous() + assert tail_score.is_contiguous() + + batch = key.shape[0] + if batch == 0: + return + + key = key.contiguous() + slot_score = slot_score.contiguous() + ape = ape.contiguous() + req_pool_indices = req_pool_indices.contiguous() + positions = positions.contiguous() + seq_lens = seq_lens.contiguous() + out_cache_loc = out_cache_loc.contiguous() + + assert req_pool_indices.shape[0] >= batch + assert positions.shape[0] >= batch + assert seq_lens.shape[0] >= batch + assert out_cache_loc.shape[0] >= batch + assert block_tables.ndim == 2 + assert block_tables.shape[0] >= batch + + buf_fp8 = buf.view(torch.float8_e4m3fn) + buf_fp32 = buf.view(torch.float32) + _kpool_decode_update_and_maybe_write_cache_kernel[(batch,)]( + buf_fp8, + buf_fp32, + tail_k, + tail_score, + key, + slot_score, + ape, + block_tables, + req_pool_indices, + positions, + seq_lens, + out_cache_loc, + tail_k.stride(0), + tail_k.stride(1), + tail_score.stride(0), + tail_score.stride(1), + key.stride(0), + slot_score.stride(0), + ape.stride(0), + block_tables.stride(0), + block_tables.stride(1), + REQ_POOL_SIZE=tail_k.shape[0], + PAGE_SIZE=pool.page_size, + BUF_NUMEL_PER_PAGE=buf.shape[1], + POOL_SIZE=pool.index_kpool, + TAIL_SIZE=tail_k.shape[1], + HEAD_DIM=tail_k.shape[2], + BLOCK_TABLE_COLS=block_tables.shape[1], + S_OFFSET_NBYTES_IN_PAGE=pool.slots_per_page * pool.index_head_dim, + ROUND_SCALE=round_scale, + BLOCK_D=triton.next_power_of_2(tail_k.shape[2]), + SLOTS_PER_PAGE=pool.slots_per_page, + ) + + +@triton.jit +def _hadamard128_stage(x, GROUPS: tl.constexpr, STRIDE: tl.constexpr): + x3 = tl.reshape(x, (GROUPS, 2, STRIDE)) + x3 = tl.trans(x3, 0, 2, 1) + a, b = tl.split(x3) + x3 = tl.join(a + b, a - b) + x3 = tl.trans(x3, 0, 2, 1) + return tl.reshape(x3, (128,)) + + +@triton.jit +def _hadamard128(x): + x = _hadamard128_stage(x, 64, 1) + x = _hadamard128_stage(x, 32, 2) + x = _hadamard128_stage(x, 16, 4) + x = _hadamard128_stage(x, 8, 8) + x = _hadamard128_stage(x, 4, 16) + x = _hadamard128_stage(x, 2, 32) + x = _hadamard128_stage(x, 1, 64) + return x * 0.08838834764831845 + + +@triton.jit +def _kpool_softmax_rotate_write_cache_kernel( + buf_fp8_ptr, + buf_fp32_ptr, + slot_k_ptr, + slot_score_ptr, + ape_ptr, + loc_ptr, + write_mask_ptr, + compressed_k_ptr, + compressed_scale_ptr, + slot_k_stride_0, + slot_k_stride_1, + slot_score_stride_0, + slot_score_stride_1, + ape_stride_0, + PAGE_SIZE: tl.constexpr, + BUF_NUMEL_PER_PAGE: tl.constexpr, + POOL_SIZE: tl.constexpr, + HEAD_DIM: tl.constexpr, + S_OFFSET_NBYTES_IN_PAGE: tl.constexpr, + ROUND_SCALE: tl.constexpr, + HAS_WRITE_MASK: tl.constexpr, + RETURN_COMPRESSED: tl.constexpr, + WRITE_CACHE: tl.constexpr, + BLOCK_D: tl.constexpr, +): + row = tl.program_id(0) + do_write = True + if HAS_WRITE_MASK: + do_write = tl.load(write_mask_ptr + row) + + offs = tl.arange(0, BLOCK_D) + mask = (offs < HEAD_DIM) & do_write + + max_score = tl.full((BLOCK_D,), -float("inf"), tl.float32) + for slot in tl.static_range(0, POOL_SIZE): + score = tl.load( + slot_score_ptr + + row * slot_score_stride_0 + + slot * slot_score_stride_1 + + offs, + mask=mask, + other=0.0, + ).to(tl.float32) + score += tl.load(ape_ptr + slot * ape_stride_0 + offs, mask=mask, other=0.0).to( + tl.float32 + ) + max_score = tl.maximum(max_score, score) + + acc = tl.full((BLOCK_D,), 0.0, tl.float32) + denom = tl.full((BLOCK_D,), 0.0, tl.float32) + for slot in tl.static_range(0, POOL_SIZE): + score = tl.load( + slot_score_ptr + + row * slot_score_stride_0 + + slot * slot_score_stride_1 + + offs, + mask=mask, + other=0.0, + ).to(tl.float32) + score += tl.load(ape_ptr + slot * ape_stride_0 + offs, mask=mask, other=0.0).to( + tl.float32 + ) + prob = tl.exp(score - max_score) + denom += prob + k = tl.load( + slot_k_ptr + row * slot_k_stride_0 + slot * slot_k_stride_1 + offs, + mask=mask, + other=0.0, + ).to(tl.float32) + acc += k * prob + + x = acc / denom + x = tl.where(do_write, x, 0.0).to(tl.bfloat16).to(tl.float32) + x = _hadamard128(x).to(tl.bfloat16).to(tl.float32) + + fp8_min = -448.0 + fp8_max = 448.0 + fp8_max_inv = 1.0 / fp8_max + absmax = tl.max(tl.abs(x), axis=0) + absmax = tl.maximum(absmax, 1e-4) + + if ROUND_SCALE: + log_val = tl.log2(absmax * fp8_max_inv) + scale = tl.exp2(tl.ceil(log_val)) + else: + scale = absmax * fp8_max_inv + + quantized = x / scale + quantized = tl.minimum(tl.maximum(quantized, fp8_min), fp8_max) + + if WRITE_CACHE: + loc = tl.load(loc_ptr + row, mask=do_write, other=0) + loc_page_index = loc // PAGE_SIZE + loc_token_offset_in_page = loc % PAGE_SIZE + out_k_offsets = ( + loc_page_index * BUF_NUMEL_PER_PAGE + + loc_token_offset_in_page * HEAD_DIM + + offs + ) + out_s_offset = ( + loc_page_index * BUF_NUMEL_PER_PAGE // 4 + + S_OFFSET_NBYTES_IN_PAGE // 4 + + loc_token_offset_in_page + ) + + tl.store(buf_fp8_ptr + out_k_offsets, quantized, mask=mask) + tl.store(buf_fp32_ptr + out_s_offset, scale, mask=do_write) + if RETURN_COMPRESSED: + tl.store( + compressed_k_ptr + row * HEAD_DIM + offs, + quantized, + mask=offs < HEAD_DIM, + ) + tl.store(compressed_scale_ptr + row, scale) + + +@triton.jit +def _kpool_decode_update_and_maybe_write_cache_kernel( + buf_fp8_ptr, + buf_fp32_ptr, + tail_k_ptr, + tail_score_ptr, + key_ptr, + slot_score_ptr, + ape_ptr, + block_tables_ptr, + req_pool_indices_ptr, + positions_ptr, + seq_lens_ptr, + out_cache_loc_ptr, + tail_k_stride_0, + tail_k_stride_1, + tail_score_stride_0, + tail_score_stride_1, + key_stride_0, + slot_score_stride_0, + ape_stride_0, + block_tables_stride_0, + block_tables_stride_1, + REQ_POOL_SIZE: tl.constexpr, + PAGE_SIZE: tl.constexpr, + BUF_NUMEL_PER_PAGE: tl.constexpr, + POOL_SIZE: tl.constexpr, + TAIL_SIZE: tl.constexpr, + HEAD_DIM: tl.constexpr, + BLOCK_TABLE_COLS: tl.constexpr, + S_OFFSET_NBYTES_IN_PAGE: tl.constexpr, + ROUND_SCALE: tl.constexpr, + BLOCK_D: tl.constexpr, + SLOTS_PER_PAGE: tl.constexpr, +): + row = tl.program_id(0) + offs = tl.arange(0, BLOCK_D) + dim_mask = offs < HEAD_DIM + + req_raw = tl.load(req_pool_indices_ptr + row) + req_valid = (req_raw >= 0) & (req_raw < REQ_POOL_SIZE) + req = tl.minimum(tl.maximum(req_raw, 0), REQ_POOL_SIZE - 1) + + pos = tl.load(positions_ptr + row) + safe_pos = tl.maximum(pos, 0) + seq_len = tl.load(seq_lens_ptr + row) + cache_loc = tl.load(out_cache_loc_ptr + row) + pos_valid = req_valid & (cache_loc != 0) & (pos >= 0) & (pos < seq_len) + + slot = safe_pos % POOL_SIZE + phys_slot = safe_pos % TAIL_SIZE + + key = tl.load( + key_ptr + row * key_stride_0 + offs, + mask=dim_mask, + other=0.0, + ).to(tl.float32) + score_current = tl.load( + slot_score_ptr + row * slot_score_stride_0 + offs, + mask=dim_mask, + other=0.0, + ).to(tl.float32) + + if pos_valid & (slot == POOL_SIZE - 1): + pool_logical_start = safe_pos - slot + max_score = tl.full((BLOCK_D,), -float("inf"), tl.float32) + for pool_slot in tl.static_range(0, POOL_SIZE): + is_current = pool_slot == slot + phys = (pool_logical_start + pool_slot) % TAIL_SIZE + score_buf = tl.load( + tail_score_ptr + + req * tail_score_stride_0 + + phys * tail_score_stride_1 + + offs, + mask=dim_mask, + other=0.0, + ).to(tl.float32) + score = tl.where(is_current, score_current, score_buf) + score += tl.load( + ape_ptr + pool_slot * ape_stride_0 + offs, + mask=dim_mask, + other=0.0, + ).to(tl.float32) + max_score = tl.maximum(max_score, score) + + acc = tl.full((BLOCK_D,), 0.0, tl.float32) + denom = tl.full((BLOCK_D,), 0.0, tl.float32) + for pool_slot in tl.static_range(0, POOL_SIZE): + is_current = pool_slot == slot + phys = (pool_logical_start + pool_slot) % TAIL_SIZE + score_buf = tl.load( + tail_score_ptr + + req * tail_score_stride_0 + + phys * tail_score_stride_1 + + offs, + mask=dim_mask, + other=0.0, + ).to(tl.float32) + score = tl.where(is_current, score_current, score_buf) + score += tl.load( + ape_ptr + pool_slot * ape_stride_0 + offs, + mask=dim_mask, + other=0.0, + ).to(tl.float32) + prob = tl.exp(score - max_score) + denom += prob + k_buf = tl.load( + tail_k_ptr + req * tail_k_stride_0 + phys * tail_k_stride_1 + offs, + mask=dim_mask, + other=0.0, + ).to(tl.float32) + k = tl.where(is_current, key, k_buf) + acc += k * prob + + x = (acc / denom).to(tl.bfloat16).to(tl.float32) + x = _hadamard128(x).to(tl.bfloat16).to(tl.float32) + + fp8_min = -448.0 + fp8_max = 448.0 + fp8_max_inv = 1.0 / fp8_max + absmax = tl.max(tl.abs(x), axis=0) + absmax = tl.maximum(absmax, 1e-4) + + if ROUND_SCALE: + log_val = tl.log2(absmax * fp8_max_inv) + scale = tl.exp2(tl.ceil(log_val)) + else: + scale = absmax * fp8_max_inv + + quantized = x / scale + quantized = tl.minimum(tl.maximum(quantized, fp8_min), fp8_max) + + pool_id = safe_pos // POOL_SIZE + pool_page_group = pool_id // SLOTS_PER_PAGE + token_page_row = pool_page_group * POOL_SIZE + token_page_row = tl.minimum(tl.maximum(token_page_row, 0), BLOCK_TABLE_COLS - 1) + packed_page = tl.load( + block_tables_ptr + + row * block_tables_stride_0 + + token_page_row * block_tables_stride_1, + ) + loc_page_index = packed_page.to(tl.int64) + loc_token_offset_in_page = pool_id % SLOTS_PER_PAGE + out_k_offsets = ( + loc_page_index * BUF_NUMEL_PER_PAGE + + loc_token_offset_in_page * HEAD_DIM + + offs + ) + out_s_offset = ( + loc_page_index * BUF_NUMEL_PER_PAGE // 4 + + S_OFFSET_NBYTES_IN_PAGE // 4 + + loc_token_offset_in_page + ) + + tl.store(buf_fp8_ptr + out_k_offsets, quantized, mask=dim_mask) + tl.store(buf_fp32_ptr + out_s_offset, scale) + + tail_k_offset = req * tail_k_stride_0 + phys_slot * tail_k_stride_1 + offs + tail_score_offset = ( + req * tail_score_stride_0 + phys_slot * tail_score_stride_1 + offs + ) + update_mask = dim_mask & pos_valid + tl.store(tail_k_ptr + tail_k_offset, key, mask=update_mask) + tl.store(tail_score_ptr + tail_score_offset, score_current, mask=update_mask) + + +@triton.jit +def _hadamard_quantize_fp8(acc, denom, ROUND_SCALE: tl.constexpr): + x = (acc / denom).to(tl.bfloat16).to(tl.float32) + x = _hadamard128(x).to(tl.bfloat16).to(tl.float32) + + fp8_max_inv = 1.0 / 448.0 + absmax = tl.maximum(tl.max(tl.abs(x), axis=0), 1e-4) + if ROUND_SCALE: + scale = tl.exp2(tl.ceil(tl.log2(absmax * fp8_max_inv))) + else: + scale = absmax * fp8_max_inv + + quantized = tl.minimum(tl.maximum(x / scale, -448.0), 448.0) + return quantized, scale + + +@triton.jit +def _kpool_assemble_softmax_rotate_write_cache_kernel( + buf_fp8_ptr, + buf_fp32_ptr, + chunk_k_ptr, + chunk_score_ptr, + tail_k_ptr, + tail_score_ptr, + req_pool_idx_ptr, + n_from_tail_ptr, + chunk_src_start_ptr, + tail_logical_base_ptr, + ape_ptr, + loc_ptr, + write_mask_ptr, + chunk_stride_0, + tail_stride_0, + tail_stride_1, + ape_stride_0, + BUF_NUMEL_PER_PAGE: tl.constexpr, + POOL_SIZE: tl.constexpr, + TAIL_SIZE: tl.constexpr, + HEAD_DIM: tl.constexpr, + S_OFFSET_NBYTES_IN_PAGE: tl.constexpr, + ROUND_SCALE: tl.constexpr, + HAS_WRITE_MASK: tl.constexpr, + BLOCK_D: tl.constexpr, + SLOTS_PER_PAGE: tl.constexpr, +): + row = tl.program_id(0) + if HAS_WRITE_MASK: + if not tl.load(write_mask_ptr + row): + return + + offs = tl.arange(0, BLOCK_D) + mask = offs < HEAD_DIM + + n_tail = tl.load(n_from_tail_ptr + row) + req = tl.load(req_pool_idx_ptr + row) + chunk_src = tl.load(chunk_src_start_ptr + row) + tail_base = tl.load(tail_logical_base_ptr + row) + + m = tl.full((BLOCK_D,), -float("inf"), tl.float32) + acc = tl.full((BLOCK_D,), 0.0, tl.float32) + denom = tl.full((BLOCK_D,), 0.0, tl.float32) + for slot in tl.static_range(0, POOL_SIZE): + if slot < n_tail: + phys = (tail_base + slot) % TAIL_SIZE + off = req * tail_stride_0 + phys * tail_stride_1 + offs + score = tl.load(tail_score_ptr + off, mask=mask, other=0.0).to(tl.float32) + k = tl.load(tail_k_ptr + off, mask=mask, other=0.0).to(tl.float32) + else: + off = (chunk_src + (slot - n_tail)) * chunk_stride_0 + offs + score = tl.load(chunk_score_ptr + off, mask=mask, other=0.0).to(tl.float32) + k = tl.load(chunk_k_ptr + off, mask=mask, other=0.0).to(tl.float32) + + score += tl.load(ape_ptr + slot * ape_stride_0 + offs, mask=mask, other=0.0).to( + tl.float32 + ) + new_m = tl.maximum(m, score) + rescale = tl.exp(m - new_m) + prob = tl.exp(score - new_m) + denom = denom * rescale + prob + acc = acc * rescale + k * prob + m = new_m + + quantized, scale = _hadamard_quantize_fp8(acc, denom, ROUND_SCALE) + + loc = tl.load(loc_ptr + row) + loc_page_index = loc // SLOTS_PER_PAGE + loc_token_offset_in_page = loc % SLOTS_PER_PAGE + out_k_offsets = ( + loc_page_index * BUF_NUMEL_PER_PAGE + loc_token_offset_in_page * HEAD_DIM + offs + ) + out_s_offset = ( + loc_page_index * BUF_NUMEL_PER_PAGE // 4 + + S_OFFSET_NBYTES_IN_PAGE // 4 + + loc_token_offset_in_page + ) + + tl.store(buf_fp8_ptr + out_k_offsets, quantized, mask=mask) + tl.store(buf_fp32_ptr + out_s_offset, scale) + + +def kpool_assemble_softmax_rotate_write_cache( + pool, + buf: torch.Tensor, + chunk_k: torch.Tensor, + chunk_score: torch.Tensor, + tail_k: torch.Tensor, + tail_score: torch.Tensor, + req_pool_idx: torch.Tensor, + n_from_tail: torch.Tensor, + chunk_src_start: torch.Tensor, + tail_logical_base: torch.Tensor, + ape: torch.Tensor, + loc: torch.Tensor, + write_mask: torch.Tensor | None = None, + round_scale: bool = False, +) -> None: + pool_size = pool.index_kpool + n_pools = req_pool_idx.shape[0] + if n_pools == 0: + return + + chunk_k = chunk_k.contiguous() + chunk_score = chunk_score.contiguous() + ape = ape.contiguous() + loc = loc.contiguous() + if write_mask is None: + write_mask = torch.empty((1,), dtype=torch.bool, device=chunk_k.device) + has_write_mask = False + else: + write_mask = write_mask.contiguous() + has_write_mask = True + + buf_fp8 = buf.view(torch.float8_e4m3fn) + buf_fp32 = buf.view(torch.float32) + slots_per_page = pool.slots_per_page + + _kpool_assemble_softmax_rotate_write_cache_kernel[(n_pools,)]( + buf_fp8, + buf_fp32, + chunk_k, + chunk_score, + tail_k, + tail_score, + req_pool_idx, + n_from_tail, + chunk_src_start, + tail_logical_base, + ape, + loc, + write_mask, + chunk_k.stride(0), + tail_k.stride(0), + tail_k.stride(1), + ape.stride(0), + BUF_NUMEL_PER_PAGE=buf.shape[1], + POOL_SIZE=pool_size, + TAIL_SIZE=tail_k.shape[1], + HEAD_DIM=INDEX_HEAD_DIM, + S_OFFSET_NBYTES_IN_PAGE=slots_per_page * INDEX_HEAD_DIM, + ROUND_SCALE=round_scale, + HAS_WRITE_MASK=has_write_mask, + BLOCK_D=triton.next_power_of_2(INDEX_HEAD_DIM), + SLOTS_PER_PAGE=slots_per_page, + ) + + +def scatter_kpool_tail_updates( + pool, + chunk_k: torch.Tensor, + chunk_score: torch.Tensor, + tail_k: torch.Tensor, + tail_score: torch.Tensor, + req_pool_idx: torch.Tensor, + dst_logical_start: torch.Tensor, + chunk_src_start: torch.Tensor, + n_write: torch.Tensor, +) -> None: + pool_size = pool.index_kpool + n_rows = req_pool_idx.shape[0] + if n_rows == 0: + return + + chunk_k = chunk_k.contiguous() + chunk_score = chunk_score.contiguous() + _scatter_kpool_tail_updates_kernel[(n_rows, pool_size)]( + chunk_k, + chunk_score, + tail_k, + tail_score, + req_pool_idx, + dst_logical_start, + chunk_src_start, + n_write, + chunk_k.stride(0), + tail_k.stride(0), + tail_k.stride(1), + POOL_SIZE=pool_size, + TAIL_SIZE=tail_k.shape[1], + HEAD_DIM=INDEX_HEAD_DIM, + BLOCK_D=triton.next_power_of_2(INDEX_HEAD_DIM), + ) + + +@triton.jit +def _scatter_kpool_tail_updates_kernel( + chunk_k_ptr, + chunk_score_ptr, + tail_k_ptr, + tail_score_ptr, + req_pool_idx_ptr, + dst_logical_start_ptr, + chunk_src_start_ptr, + n_write_ptr, + chunk_stride_0, + tail_stride_0, + tail_stride_1, + POOL_SIZE: tl.constexpr, + TAIL_SIZE: tl.constexpr, + HEAD_DIM: tl.constexpr, + BLOCK_D: tl.constexpr, +): + row = tl.program_id(0) + slot = tl.program_id(1) + + n_w = tl.load(n_write_ptr + row) + if slot >= n_w: + return + + req = tl.load(req_pool_idx_ptr + row) + dst_logical_start = tl.load(dst_logical_start_ptr + row) + src_off = tl.load(chunk_src_start_ptr + row) + slot + + offs = tl.arange(0, BLOCK_D) + mask = offs < HEAD_DIM + k = tl.load(chunk_k_ptr + src_off * chunk_stride_0 + offs, mask=mask) + s = tl.load(chunk_score_ptr + src_off * chunk_stride_0 + offs, mask=mask) + + dst = ( + req * tail_stride_0 + + ((dst_logical_start + slot) % TAIL_SIZE) * tail_stride_1 + + offs + ) + tl.store(tail_k_ptr + dst, k, mask=mask) + tl.store(tail_score_ptr + dst, s, mask=mask) + + +@triton.jit +def _pack_pool_slots_to_payload_kernel( + buf_ptr, + locs_ptr, + payload_ptr, + payload_bytes: tl.constexpr, + slots_per_page: tl.constexpr, + head_dim: tl.constexpr, + page_bytes: tl.constexpr, + scale_region_off: tl.constexpr, + BLOCK_D: tl.constexpr, +): + row = tl.program_id(0) + loc = tl.load(locs_ptr + row).to(tl.int64) + page = loc // slots_per_page + slot = loc % slots_per_page + page_base = page * page_bytes + + offs = tl.arange(0, BLOCK_D) + mask = offs < head_dim + src = page_base + slot * head_dim + offs + val = tl.load(buf_ptr + src, mask=mask, other=0).to(tl.uint8) + tl.store(payload_ptr + row * payload_bytes + offs, val, mask=mask) + + s_offs = tl.arange(0, 4) + s_src = page_base + scale_region_off + slot * 4 + s_offs + s_val = tl.load(buf_ptr + s_src).to(tl.uint8) + tl.store(payload_ptr + row * payload_bytes + head_dim + s_offs, s_val) + + +@triton.jit +def _select_and_scatter_pool_slots_kernel( + recv_ptr, + owner_ptr, + locs_ptr, + buf_ptr, + cp_rank: tl.constexpr, + payload_bytes: tl.constexpr, + slots_per_page: tl.constexpr, + head_dim: tl.constexpr, + page_bytes: tl.constexpr, + scale_region_off: tl.constexpr, + n_total: tl.constexpr, + BLOCK_D: tl.constexpr, +): + row = tl.program_id(0) + owner = tl.load(owner_ptr + row).to(tl.int64) + if owner == cp_rank: + return + + loc = tl.load(locs_ptr + row).to(tl.int64) + page = loc // slots_per_page + slot = loc % slots_per_page + page_base = page * page_bytes + recv_row_base = (owner * n_total + row) * payload_bytes + + offs = tl.arange(0, BLOCK_D) + mask = offs < head_dim + val = tl.load(recv_ptr + recv_row_base + offs, mask=mask, other=0).to(tl.uint8) + dst = page_base + slot * head_dim + offs + tl.store(buf_ptr + dst, val, mask=mask) + + s_offs = tl.arange(0, 4) + s_val = tl.load(recv_ptr + recv_row_base + head_dim + s_offs).to(tl.uint8) + s_dst = page_base + scale_region_off + slot * 4 + s_offs + tl.store(buf_ptr + s_dst, s_val) + + +def all_gather_and_scatter_pool_slots( + buf: torch.Tensor, + local_locs: torch.Tensor, + owner_rank: torch.Tensor, + cp_size: int, + cp_rank: int, + slots_per_page: int, +) -> None: + from sglang.srt.layers.dp_attention import attn_cp_all_gather_into_tensor + + assert buf.is_contiguous() + n_total = local_locs.shape[0] + if n_total == 0 or cp_size <= 1: + return + + head_dim = INDEX_HEAD_DIM + payload_bytes = head_dim + 4 + scale_region_off = slots_per_page * head_dim + page_bytes = buf.shape[1] + device = buf.device + + send_payload = torch.empty( + (n_total, payload_bytes), dtype=torch.uint8, device=device + ) + _pack_pool_slots_to_payload_kernel[(n_total,)]( + buf, + local_locs, + send_payload, + payload_bytes=payload_bytes, + slots_per_page=slots_per_page, + head_dim=head_dim, + page_bytes=page_bytes, + scale_region_off=scale_region_off, + BLOCK_D=triton.next_power_of_2(head_dim), + ) + + recv = torch.empty( + (cp_size, n_total, payload_bytes), dtype=torch.uint8, device=device + ) + attn_cp_all_gather_into_tensor( + recv.view(cp_size * n_total, payload_bytes), send_payload + ) + + _select_and_scatter_pool_slots_kernel[(n_total,)]( + recv, + owner_rank, + local_locs, + buf, + cp_rank=cp_rank, + payload_bytes=payload_bytes, + slots_per_page=slots_per_page, + head_dim=head_dim, + page_bytes=page_bytes, + scale_region_off=scale_region_off, + n_total=n_total, + BLOCK_D=triton.next_power_of_2(head_dim), + ) + + +@triton.jit +def _kpool_write_tail_and_maybe_compress_kernel( + key_ptr, + score_ptr, + tail_k_ptr, + tail_score_ptr, + ape_ptr, + req_pool_indices_ptr, + write_start_ptr, + tail_logical_start_ptr, + write_loc_ptr, + out_cache_loc_ptr, + effective_n_ptr, + buf_fp8_ptr, + buf_fp32_ptr, + key_stride_0, + score_stride_0, + tail_stride_0, + tail_stride_1, + ape_stride_0, + write_loc_stride_0, + N: tl.constexpr, + POOL_SIZE: tl.constexpr, + TAIL_SIZE: tl.constexpr, + HEAD_DIM: tl.constexpr, + BLOCK_D: tl.constexpr, + SLOTS_PER_PAGE: tl.constexpr, + BUF_NUMEL_PER_PAGE: tl.constexpr, + S_OFFSET_NBYTES_IN_PAGE: tl.constexpr, + ROUND_SCALE: tl.constexpr, + HAS_EFFECTIVE_N: tl.constexpr, + MAX_CLOSED_POOLS: tl.constexpr, +): + b = tl.program_id(0) + cache_loc_0 = tl.load(out_cache_loc_ptr + b * N) + if cache_loc_0 == 0: + return + + req = tl.load(req_pool_indices_ptr + b) + write_start = tl.load(write_start_ptr + b) + offs = tl.arange(0, BLOCK_D) + dim_mask = offs < HEAD_DIM + + for i_n in tl.static_range(0, N): + row = b * N + i_n + k = tl.load(key_ptr + row * key_stride_0 + offs, mask=dim_mask) + s = tl.load(score_ptr + row * score_stride_0 + offs, mask=dim_mask) + phys = (write_start + i_n) % TAIL_SIZE + dst = req * tail_stride_0 + phys * tail_stride_1 + offs + tl.store(tail_k_ptr + dst, k, mask=dim_mask) + tl.store(tail_score_ptr + dst, s, mask=dim_mask) + + if HAS_EFFECTIVE_N: + gate_n = tl.load(effective_n_ptr + b).to(tl.int32) + else: + gate_n = N + base_pool = write_start // POOL_SIZE + n_pool = (write_start + gate_n) // POOL_SIZE - base_pool + if n_pool == 0: + return + + base0 = tl.load(tail_logical_start_ptr + b) + for p in tl.static_range(0, MAX_CLOSED_POOLS): + if p < n_pool: + base = base0 + p * POOL_SIZE + m = tl.full((BLOCK_D,), -float("inf"), tl.float32) + acc = tl.full((BLOCK_D,), 0.0, tl.float32) + denom = tl.full((BLOCK_D,), 0.0, tl.float32) + for slot in tl.static_range(0, POOL_SIZE): + phys = (base + slot) % TAIL_SIZE + off = req * tail_stride_0 + phys * tail_stride_1 + offs + score = tl.load(tail_score_ptr + off, mask=dim_mask, other=0.0).to( + tl.float32 + ) + k_ld = tl.load(tail_k_ptr + off, mask=dim_mask, other=0.0).to( + tl.float32 + ) + score += tl.load( + ape_ptr + slot * ape_stride_0 + offs, + mask=dim_mask, + other=0.0, + ).to(tl.float32) + new_m = tl.maximum(m, score) + rescale = tl.exp(m - new_m) + prob = tl.exp(score - new_m) + denom = denom * rescale + prob + acc = acc * rescale + k_ld * prob + m = new_m + + quantized, scale = _hadamard_quantize_fp8(acc, denom, ROUND_SCALE) + loc = tl.load(write_loc_ptr + b * write_loc_stride_0 + p) + loc_page_index = loc // SLOTS_PER_PAGE + loc_token_offset_in_page = loc % SLOTS_PER_PAGE + out_k_offsets = ( + loc_page_index * BUF_NUMEL_PER_PAGE + + loc_token_offset_in_page * HEAD_DIM + + offs + ) + out_s_offset = ( + loc_page_index * BUF_NUMEL_PER_PAGE // 4 + + S_OFFSET_NBYTES_IN_PAGE // 4 + + loc_token_offset_in_page + ) + tl.store(buf_fp8_ptr + out_k_offsets, quantized, mask=dim_mask) + tl.store(buf_fp32_ptr + out_s_offset, scale) + + +def kpool_write_tail_and_maybe_compress( + pool, + buf: torch.Tensor, + key: torch.Tensor, + score: torch.Tensor, + tail_k: torch.Tensor, + tail_score: torch.Tensor, + ape: torch.Tensor, + req_pool_indices: torch.Tensor, + write_start: torch.Tensor, + tail_logical_start: torch.Tensor, + write_loc: torch.Tensor, + out_cache_loc: torch.Tensor, + num_draft_tokens: int, + round_scale: bool, + effective_n_per_batch: Optional[torch.Tensor] = None, +) -> None: + assert num_draft_tokens > 0 + assert key.dim() == 2 and key.shape[1] == INDEX_HEAD_DIM + assert score.shape == key.shape + assert tail_k.shape == tail_score.shape + assert tail_k.shape[1] == pool.index_kpool + pool.tail_extra_slots + assert tail_k.shape[2] == INDEX_HEAD_DIM + assert key.dtype == torch.bfloat16 + assert score.dtype in KPOOL_SCORE_DTYPES + assert tail_k.dtype == torch.bfloat16 + assert tail_score.dtype in KPOOL_SCORE_DTYPES + assert ape.dtype == torch.float32 + + bn = key.shape[0] + if bn == 0: + return + assert bn % num_draft_tokens == 0 + bs = bn // num_draft_tokens + max_closed_pools = kpool_max_closed_pools(num_draft_tokens, pool.index_kpool) + assert write_loc.shape == (bs, max_closed_pools), write_loc.shape + assert write_loc.stride(1) == 1, write_loc.stride() + + key = key.contiguous() + score = score.contiguous() + ape = ape.contiguous() + req_pool_indices = req_pool_indices.contiguous() + write_start = write_start.contiguous() + tail_logical_start = tail_logical_start.contiguous() + write_loc = write_loc.contiguous() + out_cache_loc = out_cache_loc.contiguous() + if effective_n_per_batch is not None: + effective_n_per_batch = effective_n_per_batch.contiguous() + + slots_per_page = pool.slots_per_page + buf_fp8 = buf.view(torch.float8_e4m3fn) + buf_fp32 = buf.view(torch.float32) + _kpool_write_tail_and_maybe_compress_kernel[(bs,)]( + key, + score, + tail_k, + tail_score, + ape, + req_pool_indices, + write_start, + tail_logical_start, + write_loc, + out_cache_loc, + effective_n_per_batch, + buf_fp8, + buf_fp32, + key.stride(0), + score.stride(0), + tail_k.stride(0), + tail_k.stride(1), + ape.stride(0), + write_loc.stride(0), + N=num_draft_tokens, + POOL_SIZE=pool.index_kpool, + TAIL_SIZE=tail_k.shape[1], + HEAD_DIM=INDEX_HEAD_DIM, + BLOCK_D=triton.next_power_of_2(INDEX_HEAD_DIM), + SLOTS_PER_PAGE=slots_per_page, + BUF_NUMEL_PER_PAGE=buf.shape[1], + S_OFFSET_NBYTES_IN_PAGE=slots_per_page * pool.index_head_dim, + ROUND_SCALE=round_scale, + HAS_EFFECTIVE_N=effective_n_per_batch is not None, + MAX_CLOSED_POOLS=max_closed_pools, + ) diff --git a/python/sglang/srt/layers/attention/dsa/kpool_plan.py b/python/sglang/srt/layers/attention/dsa/kpool_plan.py new file mode 100644 index 0000000000000..8ef618b2aaf38 --- /dev/null +++ b/python/sglang/srt/layers/attention/dsa/kpool_plan.py @@ -0,0 +1,871 @@ +from __future__ import annotations + +import dataclasses +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, List, NamedTuple, Optional + +import torch + +from sglang.srt.environ import envs +from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( + INDEX_HEAD_DIM, + build_pooled_page_table_64, + kpool_build_ragged_layout, + kpool_max_closed_pools, + update_kpool_write_plan_cuda_graph, +) +from sglang.srt.layers.attention.dsa.utils import dsa_use_prefill_cp +from sglang.srt.model_executor.forward_context import get_req_to_token_pool +from sglang.srt.runtime_context import get_parallel +from sglang.srt.utils import is_cuda + +if TYPE_CHECKING: + from sglang.srt.layers.attention.dsa.dsa_topk_backend import TopkTransformMethod + from sglang.srt.layers.attention.dsa_backend import DSAMetadata + from sglang.srt.model_executor.forward_batch_info import ForwardBatch, ForwardMode + + +_RAGGED_SCRATCH_K_U8: Optional[torch.Tensor] = None +_RAGGED_SCRATCH_K_SCALE: Optional[torch.Tensor] = None + + +def _get_ragged_scratch( + total_k_rows: int, device: torch.device +) -> tuple[torch.Tensor, torch.Tensor]: + global _RAGGED_SCRATCH_K_U8, _RAGGED_SCRATCH_K_SCALE + cur = _RAGGED_SCRATCH_K_U8 + grow = ( + cur is None + or cur.device.type != device.type + or (device.index is not None and cur.device.index != device.index) + or cur.shape[0] < total_k_rows + ) + if grow: + _RAGGED_SCRATCH_K_U8 = torch.empty( + (total_k_rows, INDEX_HEAD_DIM), dtype=torch.uint8, device=device + ) + _RAGGED_SCRATCH_K_SCALE = torch.empty( + (total_k_rows,), dtype=torch.float32, device=device + ) + return _RAGGED_SCRATCH_K_U8[:total_k_rows], _RAGGED_SCRATCH_K_SCALE[:total_k_rows] + + +@dataclass(frozen=True) +class PoolWriteRows: + req: torch.Tensor + pool_id: torch.Tensor + n_from_tail: torch.Tensor + chunk_src: torch.Tensor + tail_logical_base: torch.Tensor + write_loc: torch.Tensor + + @property + def is_empty(self) -> bool: + return self.pool_id.shape[0] == 0 + + +@dataclass(frozen=True) +class TailWriteRows: + req: torch.Tensor + dst_logical_start: torch.Tensor + chunk_src: torch.Tensor + n_write: torch.Tensor + + @property + def is_empty(self) -> bool: + return self.req.shape[0] == 0 + + +@dataclass(frozen=True) +class KPoolCpInfo: + size: int + rank: int + owner_rank: torch.Tensor + local_write_mask: torch.Tensor + + +@dataclass(frozen=True) +class KPoolExtendPlan: + writes: PoolWriteRows + tails: TailWriteRows + pooled_seq_lens_expanded: torch.Tensor + seq_lens_expanded: torch.Tensor + ragged_concat_page_table: torch.Tensor + ragged_q_ks: torch.Tensor + ragged_q_ke: torch.Tensor + ragged_total_k_rows: int + ragged_k_u8: Optional[torch.Tensor] + ragged_k_scale: Optional[torch.Tensor] + ragged_paged_page_table: Optional[torch.Tensor] + ragged_paged_page_table_row_index: Optional[torch.Tensor] + cp: Optional[KPoolCpInfo] = None + + +@dataclass(frozen=True) +class KPoolWritePlan: + """Layer-invariant plan for kpool tail writes and closed-pool compression. + + ``write_loc[b, p]`` is the compression destination for logical pool + ``base_pool[b] + p``. The compression kernel determines how many of these + candidate pools were actually closed by each batch. + """ + + req: torch.Tensor + write_start: torch.Tensor + tail_logical_start: torch.Tensor + write_loc: torch.Tensor # int64 [B, max_closed_pools] + num_draft_tokens: int + pool_seqlens_per_q: Optional[torch.Tensor] = None + seqlens_per_q: Optional[torch.Tensor] = None + pool_schedule_metadata: Optional[torch.Tensor] = None + effective_n_per_batch: Optional[torch.Tensor] = None + + +def _is_kpool_layout_enabled(pool_size: int, real_page_size: int) -> bool: + return pool_size > 1 and real_page_size == 64 and real_page_size % pool_size == 0 + + +@dataclass +class _KPoolCpuPlan: + pool_batch_idx: List[int] = field(default_factory=list) + pool_req: List[int] = field(default_factory=list) + pool_pool_id: List[int] = field(default_factory=list) + pool_n_from_tail: List[int] = field(default_factory=list) + pool_chunk_src: List[int] = field(default_factory=list) + pool_tail_logical_base: List[int] = field(default_factory=list) + + tail_req: List[int] = field(default_factory=list) + tail_dst_logical_start: List[int] = field(default_factory=list) + tail_chunk_src: List[int] = field(default_factory=list) + tail_n_write: List[int] = field(default_factory=list) + + ragged_q_len: List[int] = field(default_factory=list) + ragged_pool_pages: List[int] = field(default_factory=list) + cu_pages_excl: List[int] = field(default_factory=list) + cu_q_len_excl: List[int] = field(default_factory=list) + total_pool_pages: int = 0 + + +class _KPoolDecompose(NamedTuple): + first_slot: int + base_pool: int + n_pool: int + tail_n_write: int + + +def _decompose_compress(start: int, length: int, pool_size: int) -> _KPoolDecompose: + first_slot = start % pool_size + base_pool = start // pool_size + n_pool = (start + length) // pool_size - base_pool + consumed = max(0, n_pool * pool_size - first_slot) + tail_n = length - consumed + return _KPoolDecompose( + first_slot=first_slot, + base_pool=base_pool, + n_pool=n_pool, + tail_n_write=tail_n, + ) + + +def _append_compress_rows( + plan: _KPoolCpuPlan, + pool_size: int, + batch_size: int, + extend_seq_lens_cpu: List[int], + seq_lens_cpu: List[int], + req_pool_indices_cpu: List[int], +) -> None: + q_offset = 0 + for i in range(batch_size): + q_len = extend_seq_lens_cpu[i] + assert q_len > 0, f"extend_seq_lens_cpu[{i}] = {q_len}; expected > 0" + + seq_len = seq_lens_cpu[i] + req = req_pool_indices_cpu[i] + d = _decompose_compress(seq_len - q_len, q_len, pool_size) + + if d.n_pool > 0: + plan.pool_batch_idx.extend([i] * d.n_pool) + plan.pool_req.extend([req] * d.n_pool) + plan.pool_pool_id.extend(range(d.base_pool, d.base_pool + d.n_pool)) + plan.pool_n_from_tail.append(d.first_slot) + plan.pool_n_from_tail.extend([0] * (d.n_pool - 1)) + bulk_start = q_offset + pool_size - d.first_slot + plan.pool_chunk_src.append(q_offset) + plan.pool_chunk_src.extend( + range(bulk_start, bulk_start + (d.n_pool - 1) * pool_size, pool_size) + ) + plan.pool_tail_logical_base.extend( + range( + d.base_pool * pool_size, + (d.base_pool + d.n_pool) * pool_size, + pool_size, + ) + ) + + if d.tail_n_write > 0: + consumed = q_len - d.tail_n_write + plan.tail_req.append(req) + plan.tail_dst_logical_start.append(seq_len - q_len + consumed) + plan.tail_chunk_src.append(q_offset + consumed) + plan.tail_n_write.append(d.tail_n_write) + + q_offset += q_len + + +def _append_local_rows( + plan: _KPoolCpuPlan, + pool_size: int, + slots_per_page: int, + local_extend_seq_lens_cpu: List[int], + local_seq_lens_cpu: List[int], +) -> None: + q_offset = 0 + for q_len, seq_len in zip( + local_extend_seq_lens_cpu, local_seq_lens_cpu, strict=True + ): + assert q_len > 0, f"local_extend_seq_lens_cpu has non-positive {q_len = }" + plan.ragged_q_len.append(q_len) + pool_seq_len = seq_len // pool_size + pool_pages_i = (pool_seq_len + slots_per_page - 1) // slots_per_page + plan.ragged_pool_pages.append(pool_pages_i) + plan.cu_pages_excl.append(plan.total_pool_pages) + plan.cu_q_len_excl.append(q_offset) + plan.total_pool_pages += pool_pages_i + q_offset += q_len + + +def _kpool_cpu_plan( + forward_batch: ForwardBatch, + pool_size: int, + slots_per_page: int, + *, + local_extend_seq_lens_cpu: Optional[List[int]] = None, + local_seq_lens_cpu: Optional[List[int]] = None, +) -> _KPoolCpuPlan: + plan = _KPoolCpuPlan() + + extend_seq_lens_cpu = forward_batch.extend_seq_lens_cpu + if isinstance(extend_seq_lens_cpu, torch.Tensor): + extend_seq_lens_cpu = extend_seq_lens_cpu.tolist() + seq_lens_cpu = forward_batch.seq_lens_cpu.tolist() + req_pool_indices_cpu = forward_batch.req_pool_indices.tolist() + + _append_compress_rows( + plan, + pool_size, + forward_batch.batch_size, + extend_seq_lens_cpu, + seq_lens_cpu, + req_pool_indices_cpu, + ) + + if local_extend_seq_lens_cpu is None: + local_extend_seq_lens_cpu = extend_seq_lens_cpu + local_seq_lens_cpu = seq_lens_cpu + + _append_local_rows( + plan, + pool_size, + slots_per_page, + local_extend_seq_lens_cpu, + local_seq_lens_cpu, + ) + return plan + + +def _kpool_plan_to_gpu( + cpu: _KPoolCpuPlan, + forward_batch: ForwardBatch, + full_real_page_table: torch.Tensor, + local_real_page_table: torch.Tensor, + local_seqlens_expanded: torch.Tensor, + local_req_pool_indices: torch.Tensor, + pool_size: int, + slots_per_page: int, + topk_transform_method: TopkTransformMethod, +) -> KPoolExtendPlan: + from sglang.srt.layers.attention.dsa.dsa_topk_backend import TopkTransformMethod + + device = forward_batch.seq_lens.device + n_pool = len(cpu.pool_pool_id) + n_tail = len(cpu.tail_req) + n_rag = len(cpu.ragged_q_len) + + total_pool_pages = cpu.total_pool_pages + ragged_total_k_rows = total_pool_pages * slots_per_page + + need_paged = ( + topk_transform_method == TopkTransformMethod.PAGED + and envs.SGLANG_DSA_FUSE_TOPK.get() + and n_rag > 0 + ) + + i64_total = 4 * n_pool + 2 * n_tail + if i64_total > 0: + i64_cpu = torch.tensor( + cpu.pool_req + + cpu.pool_pool_id + + cpu.pool_chunk_src + + cpu.pool_batch_idx + + cpu.tail_req + + cpu.tail_chunk_src, + dtype=torch.int64, + pin_memory=True, + ) + i64_gpu = i64_cpu.to(device, non_blocking=True) + c = 0 + pool_req_t = i64_gpu[c : c + n_pool] + c += n_pool + pool_pool_id_t = i64_gpu[c : c + n_pool] + c += n_pool + pool_chunk_src_t = i64_gpu[c : c + n_pool] + c += n_pool + pool_batch_idx_t = i64_gpu[c : c + n_pool] + c += n_pool + tail_req_t = i64_gpu[c : c + n_tail] + c += n_tail + tail_chunk_src_t = i64_gpu[c : c + n_tail] + else: + empty_i64 = torch.empty((0,), dtype=torch.int64, device=device) + pool_req_t = pool_pool_id_t = pool_chunk_src_t = pool_batch_idx_t = empty_i64 + tail_req_t = tail_chunk_src_t = empty_i64 + + i32_total = 2 * n_pool + 2 * n_tail + 4 * n_rag + if i32_total > 0: + i32_cpu = torch.tensor( + cpu.pool_n_from_tail + + cpu.pool_tail_logical_base + + cpu.tail_dst_logical_start + + cpu.tail_n_write + + cpu.ragged_pool_pages + + cpu.ragged_q_len + + cpu.cu_pages_excl + + cpu.cu_q_len_excl, + dtype=torch.int32, + pin_memory=True, + ) + i32_gpu = i32_cpu.to(device, non_blocking=True) + c = 0 + pool_n_from_tail_t = i32_gpu[c : c + n_pool] + c += n_pool + pool_tail_logical_base_t = i32_gpu[c : c + n_pool] + c += n_pool + tail_dst_logical_start_t = i32_gpu[c : c + n_tail] + c += n_tail + tail_n_write_t = i32_gpu[c : c + n_tail] + c += n_tail + ragged_pool_pages_t = i32_gpu[c : c + n_rag] + c += n_rag + ragged_q_len_t = i32_gpu[c : c + n_rag] + c += n_rag + cu_pages_excl_t = i32_gpu[c : c + n_rag] + c += n_rag + cu_q_len_excl_t = i32_gpu[c : c + n_rag] + else: + empty_i32 = torch.empty((0,), dtype=torch.int32, device=device) + pool_n_from_tail_t = pool_tail_logical_base_t = empty_i32 + tail_dst_logical_start_t = tail_n_write_t = empty_i32 + ragged_pool_pages_t = ragged_q_len_t = empty_i32 + cu_pages_excl_t = cu_q_len_excl_t = empty_i32 + + if n_pool > 0: + pool_page_group = torch.div( + pool_pool_id_t, slots_per_page, rounding_mode="floor" + ) + token_page_row = pool_page_group * pool_size + packed_page = full_real_page_table[pool_batch_idx_t, token_page_row].to( + torch.int64 + ) + pool_write_locs = packed_page * slots_per_page + torch.remainder( + pool_pool_id_t, slots_per_page + ) + else: + pool_write_locs = torch.empty((0,), dtype=torch.int64, device=device) + + pooled_seq_lens_expanded = torch.div( + local_seqlens_expanded, pool_size, rounding_mode="floor" + ).to(torch.int32) + + if n_rag > 0: + ( + ragged_concat_page_table, + ragged_q_ks, + ragged_q_ke, + ) = kpool_build_ragged_layout( + full_page_table=local_real_page_table, + cu_pages_excl=cu_pages_excl_t, + ragged_pool_pages=ragged_pool_pages_t, + cu_q_len_excl=cu_q_len_excl_t, + ragged_q_len=ragged_q_len_t, + pooled_seq_lens_expanded=pooled_seq_lens_expanded, + slots_per_page=slots_per_page, + total_pool_pages=total_pool_pages, + total_q=pooled_seq_lens_expanded.shape[0], + pool_size=pool_size, + ) + else: + empty_i32_dev = torch.empty((0,), dtype=torch.int32, device=device) + ragged_concat_page_table = empty_i32_dev + ragged_q_ks = empty_i32_dev + ragged_q_ke = empty_i32_dev + + ragged_paged_page_table = None + ragged_paged_page_table_row_index = None + if need_paged: + req_to_token = get_req_to_token_pool().req_to_token + ragged_paged_page_table_row_index = torch.repeat_interleave( + local_req_pool_indices.to(torch.int32), ragged_q_len_t + ) + ragged_paged_page_table = req_to_token + + if ragged_total_k_rows > 0: + ragged_k_u8, ragged_k_scale = _get_ragged_scratch(ragged_total_k_rows, device) + else: + ragged_k_u8 = None + ragged_k_scale = None + + return KPoolExtendPlan( + writes=PoolWriteRows( + req=pool_req_t, + pool_id=pool_pool_id_t, + n_from_tail=pool_n_from_tail_t, + chunk_src=pool_chunk_src_t, + tail_logical_base=pool_tail_logical_base_t, + write_loc=pool_write_locs, + ), + tails=TailWriteRows( + req=tail_req_t, + dst_logical_start=tail_dst_logical_start_t, + chunk_src=tail_chunk_src_t, + n_write=tail_n_write_t, + ), + pooled_seq_lens_expanded=pooled_seq_lens_expanded, + seq_lens_expanded=local_seqlens_expanded, + ragged_concat_page_table=ragged_concat_page_table, + ragged_q_ks=ragged_q_ks, + ragged_q_ke=ragged_q_ke, + ragged_total_k_rows=ragged_total_k_rows, + ragged_k_u8=ragged_k_u8, + ragged_k_scale=ragged_k_scale, + ragged_paged_page_table=ragged_paged_page_table, + ragged_paged_page_table_row_index=ragged_paged_page_table_row_index, + cp=_kpool_cp_owner_rank(forward_batch, n_pool, device), + ) + + +def _kpool_cp_owner_rank( + forward_batch: ForwardBatch, + n_pool: int, + device: torch.device, +) -> Optional[KPoolCpInfo]: + if not dsa_use_prefill_cp(forward_batch): + return None + + cp_size = get_parallel().attn_cp_size + if cp_size <= 1: + return None + + cp_rank = get_parallel().attn_cp_rank + if n_pool > 0: + owner = torch.arange(n_pool, dtype=torch.int32, device=device) % cp_size + local_write_mask = owner == cp_rank + else: + owner = torch.empty((0,), dtype=torch.int32, device=device) + local_write_mask = torch.empty((0,), dtype=torch.bool, device=device) + return KPoolCpInfo( + size=cp_size, + rank=cp_rank, + owner_rank=owner, + local_write_mask=local_write_mask, + ) + + +def init_kpool_extend_metadata( + metadata: DSAMetadata, + forward_batch: ForwardBatch, + *, + pool_size: int, + real_page_size: int, + slots_per_page: int, + topk_transform_method: TopkTransformMethod, + full_real_page_table: torch.Tensor, + full_seqlens_expanded: torch.Tensor, + local_real_page_table: Optional[torch.Tensor] = None, + local_seqlens_expanded: Optional[torch.Tensor] = None, + local_extend_seq_lens_cpu: Optional[List[int]] = None, + local_seq_lens_cpu: Optional[List[int]] = None, + local_req_pool_indices: Optional[torch.Tensor] = None, +) -> DSAMetadata: + mode = forward_batch.forward_mode + is_extend_like = mode.is_extend_without_speculative() or mode.is_draft_extend_v2() + if ( + not _is_kpool_layout_enabled(pool_size, real_page_size) + or not is_extend_like + or forward_batch.extend_seq_lens_cpu is None + or forward_batch.seq_lens_cpu is None + ): + return metadata + + if local_real_page_table is None: + local_real_page_table = full_real_page_table + if local_seqlens_expanded is None: + local_seqlens_expanded = full_seqlens_expanded + if local_req_pool_indices is None: + local_req_pool_indices = forward_batch.req_pool_indices + + cpu = _kpool_cpu_plan( + forward_batch, + pool_size, + slots_per_page, + local_extend_seq_lens_cpu=local_extend_seq_lens_cpu, + local_seq_lens_cpu=local_seq_lens_cpu, + ) + plan = _kpool_plan_to_gpu( + cpu, + forward_batch, + full_real_page_table, + local_real_page_table, + local_seqlens_expanded, + local_req_pool_indices, + pool_size, + slots_per_page, + topk_transform_method, + ) + return dataclasses.replace(metadata, kpool_extend_plan=plan) + + +_DEEP_GEMM_MODULE = None +_DEEP_GEMM_IMPORT_FAILED = False + + +def _get_deep_gemm(): + """Cached deep_gemm import, hoisted out of the per-replay schedule + refresh (the old per-call try-import re-ran the import machinery on + every cuda-graph replay cycle).""" + global _DEEP_GEMM_MODULE, _DEEP_GEMM_IMPORT_FAILED + if _DEEP_GEMM_MODULE is None and not _DEEP_GEMM_IMPORT_FAILED: + try: + import deep_gemm + except (ImportError, ModuleNotFoundError): + _DEEP_GEMM_IMPORT_FAILED = True + else: + _DEEP_GEMM_MODULE = deep_gemm + return _DEEP_GEMM_MODULE + + +def _compute_pool_schedule_metadata( + pool_seqlens: torch.Tensor, + *, + slots_per_page: int, +) -> Optional[torch.Tensor]: + if not is_cuda(): + return None + deep_gemm = _get_deep_gemm() + if deep_gemm is None: + return None + return deep_gemm.get_paged_mqa_logits_metadata( + pool_seqlens.contiguous().view(-1, 1).clamp(min=1), + slots_per_page, + deep_gemm.get_num_sms(), + ) + + +def init_pooled_paged_mqa_metadata( + metadata: DSAMetadata, + seqlens_32: torch.Tensor, + forward_mode: ForwardMode, + *, + pool_size: int, + real_page_size: int, + slots_per_page: int, + build_schedule_metadata: bool = True, +) -> DSAMetadata: + if ( + not _is_kpool_layout_enabled(pool_size, real_page_size) + or not is_cuda() + or not forward_mode.is_decode_or_idle() + ): + return metadata + + pool_seqlens = torch.div(seqlens_32, pool_size, rounding_mode="floor").to( + torch.int32 + ) + pooled_page_table = build_pooled_page_table_64( + metadata.real_page_table, pool_size + ).contiguous() + schedule = ( + _compute_pool_schedule_metadata( + pool_seqlens, + slots_per_page=slots_per_page, + ) + if build_schedule_metadata + else None + ) + return dataclasses.replace( + metadata, + pooled_index_kpool=pool_size, + pooled_cache_seqlens_int32=pool_seqlens, + pooled_real_page_table=pooled_page_table, + pooled_paged_mqa_schedule_metadata=schedule, + ) + + +def update_pooled_paged_mqa_metadata( + metadata: DSAMetadata, + seqlens_32: torch.Tensor, + forward_mode: ForwardMode, + *, + pool_size: int, + real_page_size: int, + slots_per_page: int, + build_schedule_metadata: bool = True, +) -> None: + if ( + not _is_kpool_layout_enabled(pool_size, real_page_size) + or not is_cuda() + or not forward_mode.is_decode_or_idle() + ): + return + + if ( + metadata.pooled_index_kpool != pool_size + or metadata.pooled_cache_seqlens_int32 is None + or metadata.pooled_real_page_table is None + ): + return + + pool_seqlens = torch.div(seqlens_32, pool_size, rounding_mode="floor").to( + torch.int32 + ) + metadata.pooled_cache_seqlens_int32[: pool_seqlens.shape[0]].copy_(pool_seqlens) + pooled_page_table = build_pooled_page_table_64( + metadata.real_page_table, pool_size + ).contiguous() + metadata.pooled_real_page_table[ + : pooled_page_table.shape[0], : pooled_page_table.shape[1] + ].copy_(pooled_page_table) + + if ( + build_schedule_metadata + and metadata.pooled_paged_mqa_schedule_metadata is not None + ): + new_schedule = _compute_pool_schedule_metadata( + metadata.pooled_cache_seqlens_int32, + slots_per_page=slots_per_page, + ) + if new_schedule is not None: + metadata.pooled_paged_mqa_schedule_metadata.copy_(new_schedule) + + +def _alloc_kpool_write_plan_buffers( + *, + max_bs: int, + num_draft_tokens: int, + pool_size: int, + device: torch.device, + is_verify: bool, + is_v2: bool = False, +) -> KPoolWritePlan: + max_closed_pools = kpool_max_closed_pools(num_draft_tokens, pool_size) + verify_extras = {} + if is_verify: + n_rows = max_bs * num_draft_tokens + verify_extras = dict( + pool_seqlens_per_q=torch.zeros(n_rows, dtype=torch.int32, device=device), + seqlens_per_q=torch.zeros(n_rows, dtype=torch.int32, device=device), + ) + if is_v2: + verify_extras["effective_n_per_batch"] = torch.zeros( + max_bs, dtype=torch.int32, device=device + ) + return KPoolWritePlan( + req=torch.zeros(max_bs, dtype=torch.int64, device=device), + write_start=torch.zeros(max_bs, dtype=torch.int32, device=device), + tail_logical_start=torch.zeros(max_bs, dtype=torch.int32, device=device), + write_loc=torch.zeros( + max_bs, max_closed_pools, dtype=torch.int64, device=device + ), + num_draft_tokens=num_draft_tokens, + **verify_extras, + ) + + +def init_kpool_write_plan_capture( + metadata: DSAMetadata, + *, + max_bs: int, + pool_size: int, + real_page_size: int, + num_draft_tokens: int, + device: torch.device, + is_verify: bool, + slots_per_page: int, + is_v2: bool = False, + build_schedule_metadata: bool = True, +) -> DSAMetadata: + if not _is_kpool_layout_enabled(pool_size, real_page_size) or num_draft_tokens == 0: + return metadata + + plan = _alloc_kpool_write_plan_buffers( + max_bs=max_bs, + num_draft_tokens=num_draft_tokens, + pool_size=pool_size, + device=device, + is_verify=is_verify, + is_v2=is_v2, + ) + if is_verify and build_schedule_metadata: + schedule = _compute_pool_schedule_metadata( + plan.pool_seqlens_per_q, + slots_per_page=slots_per_page, + ) + plan = dataclasses.replace(plan, pool_schedule_metadata=schedule) + return dataclasses.replace(metadata, kpool_write_plan=plan) + + +def update_kpool_write_plan( + metadata: DSAMetadata, + *, + write_start: torch.Tensor, + req_pool_indices: torch.Tensor, + real_page_table: torch.Tensor, + pool_size: int, + real_page_size: int, + num_draft_tokens: int, + forward_mode: ForwardMode, + slots_per_page: int, + effective_n_per_batch: Optional[torch.Tensor] = None, + include_deep_gemm_schedule: bool = True, +) -> None: + if not _is_kpool_layout_enabled(pool_size, real_page_size) or not is_cuda(): + return + is_verify = forward_mode.is_target_verify() + is_decode = forward_mode.is_decode_or_idle() + is_v2 = forward_mode.is_draft_extend_v2() + if not (is_verify or is_decode or is_v2): + return + + plan = metadata.kpool_write_plan + assert plan is not None, "kpool_write_plan must be allocated before update" + update_kpool_write_plan_cuda_graph( + write_start=write_start, + req_pool_indices=req_pool_indices, + real_page_table=real_page_table, + req_out=plan.req, + write_start_out=plan.write_start, + tail_logical_start_out=plan.tail_logical_start, + write_loc_out=plan.write_loc, + pool_seqlens_per_q_out=plan.pool_seqlens_per_q, + seqlens_per_q_out=plan.seqlens_per_q, + pool_size=pool_size, + num_draft_tokens=num_draft_tokens, + slots_per_page=slots_per_page, + ) + + if ( + is_v2 + and effective_n_per_batch is not None + and plan.effective_n_per_batch is not None + ): + plan.effective_n_per_batch[: effective_n_per_batch.shape[0]].copy_( + effective_n_per_batch.to(torch.int32) + ) + + # include_deep_gemm_schedule=False: the caller records the write-plan + # kernel inside a cuda graph but keeps the DeepGEMM schedule build + # out-of-graph (SGLANG_EXPERIMENTAL_DSA_INGRAPH_VERIFY_METADATA_DG_OUT_OF_ + # GRAPH); it refreshes the schedule per replay via + # refresh_kpool_pool_schedule_from with a source rebuilt from raw + # seq_lens, since plan.pool_seqlens_per_q is only written when the + # captured kernel replays. + if include_deep_gemm_schedule and plan.pool_schedule_metadata is not None: + new_schedule = _compute_pool_schedule_metadata( + plan.pool_seqlens_per_q, + slots_per_page=slots_per_page, + ) + if new_schedule is not None: + plan.pool_schedule_metadata.copy_(new_schedule) + + +def refresh_kpool_pool_schedule_from( + metadata: DSAMetadata, + pool_seqlens_per_q: torch.Tensor, + *, + slots_per_page: int, +) -> None: + """Refresh ONLY the pooled DeepGEMM schedule of the verify write plan from + an EXPLICIT per-q pooled-seqlens source. + + Out-of-graph residual of the in-graph verify metadata capture (see + update_kpool_write_plan's include_deep_gemm_schedule): the caller derives + ``pool_seqlens_per_q`` from the raw seq_lens buffer using the same closed + form the captured write-plan kernel stores + (``(write_start + k + 1) // pool_size``), because the plan's own + ``pool_seqlens_per_q`` buffer is not refreshed until the captured graph + replays. No-op when the plan or its schedule buffer is absent. + """ + plan = metadata.kpool_write_plan + if plan is None or plan.pool_schedule_metadata is None: + return + new_schedule = _compute_pool_schedule_metadata( + pool_seqlens_per_q, + slots_per_page=slots_per_page, + ) + if new_schedule is not None: + plan.pool_schedule_metadata.copy_(new_schedule) + + +def init_kpool_write_plan( + metadata: DSAMetadata, + forward_batch: ForwardBatch, + *, + pool_size: int, + real_page_size: int, + real_page_table: torch.Tensor, + num_draft_tokens: int, + write_start: torch.Tensor, + slots_per_page: int, + effective_n_per_batch: Optional[torch.Tensor] = None, + build_schedule_metadata: bool = True, +) -> DSAMetadata: + forward_mode = forward_batch.forward_mode + is_verify = forward_mode.is_target_verify() + is_decode = forward_mode.is_decode_or_idle() + is_v2 = forward_mode.is_draft_extend_v2() + is_ring_write = is_verify or is_decode or is_v2 + if not _is_kpool_layout_enabled(pool_size, real_page_size) or not is_ring_write: + return metadata + + pool = getattr(forward_batch, "token_to_kv_pool", None) + if (is_verify or is_v2) and pool is not None: + assert pool.tail_extra_slots == num_draft_tokens, ( + f"tail_extra_slots mismatch: pool={pool.tail_extra_slots}, " + f"forward={num_draft_tokens}" + ) + + metadata = init_kpool_write_plan_capture( + metadata, + max_bs=forward_batch.seq_lens.shape[0], + pool_size=pool_size, + real_page_size=real_page_size, + num_draft_tokens=num_draft_tokens, + device=forward_batch.seq_lens.device, + is_verify=is_verify or is_v2, + slots_per_page=slots_per_page, + is_v2=is_v2, + build_schedule_metadata=build_schedule_metadata, + ) + update_kpool_write_plan( + metadata, + write_start=write_start, + req_pool_indices=forward_batch.req_pool_indices, + real_page_table=real_page_table, + pool_size=pool_size, + real_page_size=real_page_size, + num_draft_tokens=num_draft_tokens, + forward_mode=forward_mode, + slots_per_page=slots_per_page, + effective_n_per_batch=effective_n_per_batch, + ) + return metadata diff --git a/python/sglang/srt/layers/attention/dsa/utils.py b/python/sglang/srt/layers/attention/dsa/utils.py index cce2e525280be..b3543d15f6cea 100644 --- a/python/sglang/srt/layers/attention/dsa/utils.py +++ b/python/sglang/srt/layers/attention/dsa/utils.py @@ -2,10 +2,19 @@ from typing import TYPE_CHECKING, List, Tuple, Union import torch +import torch.nn.functional as F import triton +from sglang.srt.distributed.device_communicators.pynccl_allocator import ( + use_symmetric_memory, +) from sglang.srt.environ import envs -from sglang.srt.layers.dp_attention import DpPaddingMode +from sglang.srt.layers.dp_attention import ( + DpPaddingMode, + attn_cp_all_gather_into_tensor, + attn_cp_reduce_scatter_tensor, + is_allocation_symmetric, +) from sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph import ( is_in_breakable_cuda_graph, ) @@ -71,8 +80,20 @@ def aiter_can_use_preshuffle_paged_mqa() -> bool: from sglang.srt.model_executor.forward_batch_info import ForwardBatch -def compute_dsa_seqlens(original_seq_lens, dsa_index_topk: int): - return original_seq_lens.clamp(max=dsa_index_topk) +def compute_dsa_seqlens(original_seq_lens, dsa_index_topk: int, index_kpool: int = 1): + if index_kpool <= 1: + return original_seq_lens.clamp(max=dsa_index_topk) + + # kpool: history tokens are selected at pool granularity (multiples of + # index_kpool), while the ragged tail (the partial trailing pool) is always + # kept. Round the history part down to a pool boundary, clamp it to topk, + # then add back the tail. + full_pool_tokens = ( + torch.div(original_seq_lens, index_kpool, rounding_mode="floor") * index_kpool + ) + selected_history_tokens = full_pool_tokens.clamp(max=dsa_index_topk) + tail_tokens = original_seq_lens - full_pool_tokens + return selected_history_tokens + tail_tokens def should_remap_pd_dsa_seed_to_local_slots() -> bool: @@ -159,6 +180,45 @@ def can_dsa_prefill_cp_round_robin_split(forward_batch: "ForwardBatch"): ) +def cp_zigzag_full_plan_rows( + forward_batch: "ForwardBatch", device: torch.device +) -> torch.Tensor | None: + cp_meta = getattr(forward_batch, "attn_cp_metadata", None) + if cp_meta is None or getattr(cp_meta, "zigzag_index", None) is None: + return None + if ( + getattr(forward_batch, "extend_seq_lens_cpu", None) is None + or getattr(cp_meta, "split_list", None) is None + ): + return None + + extend_lens = [int(x) for x in forward_batch.extend_seq_lens_cpu] + bs = len(extend_lens) + split_list = [int(x) for x in cp_meta.split_list] + if bs == 0 or len(split_list) % bs != 0: + return None + cp_segment_num = len(split_list) // bs + + q_offsets = [0] + for q_len in extend_lens: + q_offsets.append(q_offsets[-1] + q_len) + + rows: List[int] = [] + for seg_idx in cp_meta.zigzag_index: + seg_idx = int(seg_idx) + batch_id = seg_idx // cp_segment_num + block_id = seg_idx % cp_segment_num + if batch_id >= bs: + return None + block_base = batch_id * cp_segment_num + block_start = sum(split_list[block_base : block_base + block_id]) + block_len = split_list[seg_idx] + row_start = q_offsets[batch_id] + block_start + rows.extend(range(row_start, row_start + block_len)) + + return torch.tensor(rows, dtype=torch.long, device=device) + + def dsa_cp_round_robin_split_data(input_: Union[torch.Tensor, List]): """ # for round-robin-split, split the tokens evenly according to the rule of token_idx % cp_size. @@ -233,6 +293,11 @@ def cal_padded_tokens(forward_batch: "ForwardBatch"): def pad_dsa_cache_seqlens(forward_batch: "ForwardBatch", dsa_cache_seqlens): + if dsa_use_prefill_cp(forward_batch) and not can_dsa_prefill_cp_round_robin_split( + forward_batch + ): + return dsa_cache_seqlens + attn_cp_size = get_parallel().attn_cp_size needs_cp_pad = attn_cp_size > 1 and can_dsa_prefill_cp_round_robin_split( forward_batch @@ -337,6 +402,307 @@ def dsa_use_prefill_cp(forward_batch, dsa_enable_prefill_cp=None): return False +def cp_split_and_rebuild_data(forward_batch, input_: torch.Tensor): + if is_dsa_prefill_cp_round_robin_split(): + cp_size = get_parallel().attn_cp_size + assert ( + input_.shape[0] % cp_size == 0 + ), f"Expect input shape 0 can divided by cp size, but got input shape {input_.shape}, cp size {cp_size}" + return dsa_cp_round_robin_split_data(input_) + + input_list = list( + torch.split(input_, forward_batch.attn_cp_metadata.split_list, dim=0) + ) + result = torch.cat( + [input_list[i] for i in forward_batch.attn_cp_metadata.zigzag_index], dim=0 + ).view(-1, input_.shape[-1]) + return result + + +def cp_split_and_rebuild_position(forward_batch, positions: torch.Tensor): + if is_dsa_prefill_cp_round_robin_split(): + cp_size = get_parallel().attn_cp_size + assert positions.shape[0] % cp_size == 0, ( + f"Expect positions shape 0 can divided by cp size, but got positions shape {positions.shape}, " + f"cp size {cp_size}" + ) + return dsa_cp_round_robin_split_data(positions) + + position_id_list = list( + torch.split(positions, forward_batch.attn_cp_metadata.split_list, dim=-1) + ) + positions = torch.cat( + [position_id_list[i] for i in forward_batch.attn_cp_metadata.zigzag_index], + dim=-1, + ) + return positions + + +def cp_attn_tp_all_gather_reorganazied_into_tensor( + input_: torch.Tensor, attn_tp_size, forward_batch +): + """ + Allgather communication for context_parallel(kv_cache, index_k, hidden_states). + This implementation mainly consists of three parts: + Step 1, padding the input shape to unify the shape for allgather communication (the shape must be the same). + Step 2, synchronized allgather communication. + Step 3, removing the padding and reassembling the data according to the actual tokens. + """ + # The metadata is the source of truth for the per-rank physical extent. + # ceil(total_len / cp_size) can be smaller for multi-request batches whose + # per-sequence remainders accumulate on the same rank. + max_rank_len = forward_batch.attn_cp_metadata.max_rank_len + max_len = max_rank_len[0] + assert len(max_rank_len) == attn_tp_size and all( + rank_len == max_len for rank_len in max_rank_len + ), f"all-gather requires equal physical rank lengths, got {max_rank_len}" + assert input_.shape[0] <= max_len, ( + f"local CP input has {input_.shape[0]} rows, exceeding the metadata " + f"physical extent {max_len}" + ) + pad_size = max_len - input_.shape[0] + if pad_size > 0: + input_ = F.pad(input_, (0, 0, 0, pad_size), mode="constant", value=0) + input_ = input_.contiguous() + group = get_parallel().attn_cp_group + with use_symmetric_memory(group, disabled=not is_allocation_symmetric()): + input_tensor_all = torch.empty( + max_len * attn_tp_size, + input_.shape[1], + device=input_.device, + dtype=input_.dtype, + ) + attn_cp_all_gather_into_tensor(input_tensor_all, input_) + outputs_list_max = list( + torch.split( + input_tensor_all, forward_batch.attn_cp_metadata.max_rank_len, dim=0 + ) + ) + outputs = torch.cat( + [ + outputs_list_max[index][:per_rank_len] + for index, per_rank_len in enumerate( + forward_batch.attn_cp_metadata.per_rank_actual_token + ) + ], + dim=0, + ) + return outputs + + +def cp_all_gather_rerange_output(input_tensor, cp_size, forward_batch, stream): + """ + # for in-seq-split + | +-----------before allgather------------+| + | | dp_atten_tp0: block0, block7 | + | | dp_atten_tp1: block1, block6 | + | | dp_atten_tp2: block2, block5 | + | | dp_atten_tp3: block3, block4 | + | + | +----------before rerange---------------+| + | block0 | block7 | block1 | block6 | block2 | block5 | block3 | block4 | + | + | +--------------result-------------------+ + | block0 | block1 | block2 | block3 | block4 | block5 | block6 | block7 | + | +-------------------------+ + + # for round-robin-split + | +-----------before allgather------------+| + | dp_atten_tp0: token0, token4, token8, token12, token16, ... | + | dp_atten_tp1: token1, token5, token9, token13, token17, ... | + | dp_atten_tp2: token2, token6, token10, token14, token18, ... | + | dp_atten_tp3: token3, token7, token11, token15, token19, ... | + | + | +--------------result-------------------+ + | token0, token1, token2, token3, token4, token5, token6, token7, ... + | +-------------------------+ + """ + if is_dsa_prefill_cp_round_robin_split(): + with use_symmetric_memory( + get_parallel().attn_cp_group, disabled=not is_allocation_symmetric() + ): + output_tensor = input_tensor.new_empty( + (input_tensor.shape[0] * cp_size, *input_tensor.shape[1:]), + ) + attn_cp_all_gather_into_tensor( + output_tensor, + input_tensor, + ) + out_shape = output_tensor.shape + output_tensor = ( + output_tensor.view(cp_size, -1, *out_shape[1:]) + .transpose(0, 1) + .reshape(out_shape) + ) + return output_tensor + + bs_seq_len, hidden_size = input_tensor.shape + output_tensor = cp_attn_tp_all_gather_reorganazied_into_tensor( + input_tensor, + cp_size, + forward_batch, + ) + outputs_list = list( + torch.split( + output_tensor, forward_batch.attn_cp_metadata.reverse_split_len, dim=0 + ) + ) + output_tensor = torch.cat( + [outputs_list[i] for i in forward_batch.attn_cp_metadata.cp_reverse_index], + dim=0, + ) + output_tensor = output_tensor.view(-1, hidden_size) + return output_tensor + + +# "Plain" CP layout: rank i holds the contiguous token slice +# [i*S/cp, (i+1)*S/cp). This is the natural layout produced by a vanilla +# all_gather on rank-major buffers, so KDA layers (which need natural-sequential +# tokens for causal_conv1d / chunk_kda) can use plain all_gather / plain +# reduce_scatter with zero rerange permute. At MLA boundaries the layout is +# converted to/from the configured scattered mode (round-robin or zigzag) that +# MLA's CP attention expects for load balance. +# +# Residual streams stay in plain throughout the layer stack and never need +# conversion -- they are re-derived from hidden_states at each layer entry by +# `mhc.attn_split`, so they inherit hidden_states' layer-input layout, which +# under the plain cross-layer contract is always plain. + + +def cp_plain_split(input_tensor: torch.Tensor) -> torch.Tensor: + """Model entry scatter under the plain layout contract. + + Slice the global [S_total, ...] tensor into this rank's contiguous chunk + [cp_rank * K, (cp_rank+1) * K). Pure local op; replaces + `cp_split_and_rebuild_data` at model entry when the plain contract is on. + """ + cp_size = get_parallel().attn_cp_size + cp_rank = get_parallel().attn_cp_rank + assert input_tensor.shape[0] % cp_size == 0, ( + f"cp_plain_split expects total tokens divisible by cp_size, " + f"got {input_tensor.shape[0]} % {cp_size} != 0" + ) + chunk = input_tensor.shape[0] // cp_size + return input_tensor[cp_rank * chunk : (cp_rank + 1) * chunk].contiguous() + + +def cp_plain_all_gather(input_tensor: torch.Tensor, cp_size: int) -> torch.Tensor: + """Inverse of cp_plain_split: gather plain per-rank slices into the full + [S, ...] tensor in natural sequential order. + + Under the plain contract the all_gather output [rank0_chunk | rank1_chunk | + ...] *is* the natural sequential ordering, so no rerange permute is needed. + Used at model exit and at KDA prepare_attn entry. + """ + out_shape = (input_tensor.shape[0] * cp_size,) + tuple(input_tensor.shape[1:]) + with use_symmetric_memory( + get_parallel().attn_cp_group, disabled=not is_allocation_symmetric() + ): + output_tensor = input_tensor.new_empty(out_shape) + attn_cp_all_gather_into_tensor(output_tensor, input_tensor) + return output_tensor + + +def cp_plain_reduce_scatter(input_tensor: torch.Tensor, cp_size: int) -> torch.Tensor: + """Inverse of cp_plain_all_gather for KDA o_proj output. + + Takes a CP-partial-sum [S, H] in natural sequential order and emits this + rank's contiguous slice [S/cp, H] via a single reduce_scatter. The plain + layout is rank-major contiguous, so reduce_scatter's default contiguous + split is exactly what we want -- no permute or view+transpose. + + Comm cost: (N-1)/N * D, vs all_reduce + split which is 2*(N-1)/N * D + -- ~33% cheaper in NCCL ring traffic than the all_reduce path, and saves + the full-tensor permute that a round-robin reduce_scatter would need. + """ + S = input_tensor.shape[0] + assert S % cp_size == 0, ( + f"cp_plain_reduce_scatter expects S divisible by cp_size, " + f"got S={S}, cp_size={cp_size}" + ) + out_shape = (S // cp_size,) + tuple(input_tensor.shape[1:]) + with use_symmetric_memory( + get_parallel().attn_cp_group, disabled=not is_allocation_symmetric() + ): + output_tensor = input_tensor.new_empty(out_shape) + attn_cp_reduce_scatter_tensor(output_tensor, input_tensor.contiguous()) + return output_tensor + + +def cp_plain_to_scattered( + input_tensor: torch.Tensor, + forward_batch, + cp_size: int, +) -> torch.Tensor: + """Convert a plain per-rank slice [S/cp, H] into the configured CP scatter + layout (round-robin or zigzag), suitable for MLA's CP attention kernel. + + Used at MLA prepare_attn. Composes existing primitives: + 1. plain all_gather: rank-major output IS natural sequential under the + plain contract, so no rerange needed. + 2. cp_split_and_rebuild_data: local split per the active mode + (round-robin via stride-cp_size, or zigzag via metadata indices). + + Fast path: for round-robin mode with K = S/cp divisible by cp, replace + AG + local stride-cp split with a single all_to_all_single. Each rank + sends K/cp rows to each destination instead of broadcasting all K rows -- + cp x less NCCL traffic and no [S, H] intermediate. + """ + K = input_tensor.shape[0] + if is_dsa_prefill_cp_round_robin_split() and K % cp_size == 0: + tail = input_tensor.shape[1:] + send = ( + input_tensor.view(K // cp_size, cp_size, *tail).transpose(0, 1).contiguous() + ) + recv = torch.empty_like(send) + torch.distributed.all_to_all_single( + recv, send, group=get_parallel().attn_cp_group.device_group + ) + return recv.flatten(0, 1) + + full = cp_plain_all_gather(input_tensor, cp_size) + return cp_split_and_rebuild_data(forward_batch, full) + + +def cp_scattered_to_plain( + input_tensor: torch.Tensor, + forward_batch, + cp_size: int, +) -> torch.Tensor: + """Inverse of cp_plain_to_scattered. Takes a scattered (round-robin or + zigzag) per-rank slice [S/cp, H] (MLA's natural output layout) and emits + a plain per-rank slice. + + Used at MLA prepare_mlp. Composes: + 1. cp_all_gather_rerange_output: gather + rerange to natural sequential. + 2. local contiguous slice [cp_rank * K, (cp_rank+1) * K). + + Fast path: for round-robin mode with K = S/cp divisible by cp, replace + AG + rerange + slice with a single all_to_all_single. Each rank sends + K/cp contiguous rows to each destination -- send buffer is already laid + out correctly (no pre-copy), recv needs one transpose-contiguous to + interleave by source rank. cp x less NCCL traffic and no [S, H] alloc. + """ + K = input_tensor.shape[0] + if is_dsa_prefill_cp_round_robin_split() and K % cp_size == 0: + tail = input_tensor.shape[1:] + send = input_tensor.view(cp_size, K // cp_size, *tail) + recv = torch.empty_like(send) + torch.distributed.all_to_all_single( + recv, send, group=get_parallel().attn_cp_group.device_group + ) + # recv[s, n] = global token at position r*K + n*cp + s on this rank r; + # plain out[n*cp + s] = recv[s, n], i.e. transpose dims 0 and 1. + return recv.transpose(0, 1).contiguous().view(K, *tail) + + full = cp_all_gather_rerange_output( + input_tensor, cp_size, forward_batch, torch.cuda.current_stream() + ) + cp_rank = get_parallel().attn_cp_rank + chunk = full.shape[0] // cp_size + return full[cp_rank * chunk : (cp_rank + 1) * chunk].contiguous() + + def fp8_mqa_logits_ceil_to_ue8m0(x: torch.Tensor) -> torch.Tensor: return torch.pow(2.0, torch.ceil(torch.log2(x.abs()))) diff --git a/python/sglang/srt/layers/attention/dsa_backend.py b/python/sglang/srt/layers/attention/dsa_backend.py index 3ac2ae68e5718..d4f24a207d5cb 100644 --- a/python/sglang/srt/layers/attention/dsa_backend.py +++ b/python/sglang/srt/layers/attention/dsa_backend.py @@ -1,9 +1,10 @@ from __future__ import annotations import logging -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import ( TYPE_CHECKING, + Callable, Dict, List, Literal, @@ -14,14 +15,6 @@ import torch -from sglang.srt.configs.model_config import get_dsa_index_topk, is_deepseek_dsa -from sglang.srt.runtime_context import ( - get_exec, - get_parallel, - get_spec, -) - -logger = logging.getLogger(__name__) from sglang.kernels.ops.attention.dsa.dequant_k_cache import ( concat_cast_kv_fp8_pad, dequantize_k_cache_paged, @@ -29,16 +22,28 @@ ) from sglang.kernels.ops.attention.dsa.quant_k_cache import quantize_k_cache from sglang.kernels.ops.attention.dsa.transform_index import ( + prepare_trtllm_nope_sparse_metadata, transform_index_page_table_decode, transform_index_page_table_prefill, ) +from sglang.kernels.ops.attention.dsa_metadata import ( + fused_dsa_decode_metadata, + fused_dsa_draft_extend_metadata, + fused_dsa_target_verify_metadata, +) from sglang.kernels.ops.attention.utils import ( concat_mla_absorb_q_general, mla_quantize_and_rope_for_fp8, + mla_quantize_for_fp8_no_rope, q8kv8_topk_length_from_indices, seqlens_expand_triton, ) from sglang.kernels.ops.kvcache.cache_ops import concat_and_cast_q_fp8_pad +from sglang.srt.configs.model_config import ( + get_dsa_index_kpool, + get_dsa_index_topk, + is_deepseek_dsa, +) from sglang.srt.environ import envs from sglang.srt.layers.attention.base_attn_backend import AttentionBackend from sglang.srt.layers.attention.dsa.dsa_backend_mtp_precompute import ( @@ -51,9 +56,21 @@ DSATopKBackend, TopkTransformMethod, ) +from sglang.srt.layers.attention.dsa.kpool_plan import ( + KPoolExtendPlan, + KPoolWritePlan, + init_kpool_extend_metadata, + init_kpool_write_plan, + init_kpool_write_plan_capture, + init_pooled_paged_mqa_metadata, + refresh_kpool_pool_schedule_from, + update_kpool_write_plan, + update_pooled_paged_mqa_metadata, +) from sglang.srt.layers.attention.dsa.utils import ( can_dsa_prefill_cp_round_robin_split, compute_dsa_seqlens, + cp_zigzag_full_plan_rows, dsa_cp_round_robin_split_data, dsa_cp_round_robin_split_q_seqs, dsa_use_prefill_cp, @@ -73,7 +90,7 @@ cp_split_and_rebuild_position, ) from sglang.srt.model_executor.forward_batch_info import ForwardBatch, ForwardMode -from sglang.srt.runtime_context import get_buffer +from sglang.srt.runtime_context import get_buffer, get_exec, get_parallel, get_spec from sglang.srt.utils import ( get_bool_env_var, is_cuda, @@ -83,6 +100,8 @@ print_warning_once, ) +logger = logging.getLogger(__name__) + # Opt-in (default off): route the fp8 sparse-MLA prefill path through the Triton # per-query flash kernel instead of TileLang. Validated on gfx950 (GLM-5.1 @ # TP4: 16 heads, d_v=512, tail=64). Reads q_nope/q_rope directly (skips the @@ -117,6 +136,21 @@ def _all_gather_dsa_trtllm_fp8_kv( return kv.split((kv_lora_rank, qk_rope_head_dim), dim=-1) +def _should_all_gather_dsa_trtllm_fp8_kv( + *, + save_kv_cache: bool, + cos_sin_cache: Optional[torch.Tensor], + dsa_prefill_cp: bool, +) -> bool: + return save_kv_cache and cos_sin_cache is not None and dsa_prefill_cp + + +def _should_return_dsa_trtllm_lse( + *, forward_mode: ForwardMode, dcp_enabled: bool +) -> bool: + return dcp_enabled and (forward_mode.is_decode() or forward_mode.is_target_verify()) + + def materialize_full_kv_cp( attn_mla, forward_batch: ForwardBatch, @@ -171,6 +205,36 @@ def _to_2d_context_lens(seqlens_32: torch.Tensor, batch_size: int) -> torch.Tens return seqlens_32.contiguous().view(-1, 1) +_PLAN_TOPK_V2 = None + + +def _is_kpool_metadata_fusion_supported( + index_kpool: int, page_size: int, index_topk: int +) -> bool: + return ( + index_kpool > 1 + and page_size == 64 + and page_size % index_kpool == 0 + and index_topk % index_kpool == 0 + ) + + +def _get_plan_topk_v2(): + """Lazy, cached resolver for the JIT top-k v2 plan refresher. + + Deliberately NOT a module-scope import: sglang.kernels.ops.attention.dsv4.topk + builds/loads a JIT extension on first import and must not run at + sglang.srt import time. After the first call this is a global read + instead of the per-replay import statement it replaces. + """ + global _PLAN_TOPK_V2 + if _PLAN_TOPK_V2 is None: + from sglang.kernels.ops.attention.dsv4.topk import plan_topk_v2 + + _PLAN_TOPK_V2 = plan_topk_v2 + return _PLAN_TOPK_V2 + + @dataclass(frozen=True) class DSAFlashMLAMetadata: """Metadata only needed by FlashMLA""" @@ -253,6 +317,20 @@ class DSAMetadata: # batch index for each token. token_to_batch_idx: Optional[torch.Tensor] = None + pooled_index_kpool: int = 1 + pooled_cache_seqlens_int32: Optional[torch.Tensor] = None + pooled_real_page_table: Optional[torch.Tensor] = None + pooled_paged_mqa_schedule_metadata: Optional[torch.Tensor] = None + kpool_extend_plan: Optional[KPoolExtendPlan] = None + kpool_write_plan: Optional[KPoolWritePlan] = None + + +@dataclass +class _KPoolForwardInputs: + full_real_page_table: Optional[torch.Tensor] = None + full_seqlens_expanded: Optional[torch.Tensor] = None + cp_overrides: dict = field(default_factory=dict) + @torch.compile def _compiled_cat(tensors: list[torch.Tensor], dim: int = -1) -> torch.Tensor: @@ -275,6 +353,72 @@ def _cat(tensors: list[torch.Tensor], dim: int = -1) -> torch.Tensor: return _compiled_cat([qk_nope, qk_rope], dim=dim) +class _DSAInGraphVerifyMetadataState: + """Marker + replay-side residual for a TARGET_VERIFY metadata refresh that + was recorded INSIDE the captured cuda graph + (SGLANG_EXPERIMENTAL_DSA_INGRAPH_VERIFY_METADATA). + + Published on the frozen ``decode_cuda_graph_metadata[bs]`` entry by + :py:meth:`DeepseekSparseAttnBackend.init_forward_metadata_in_graph` once + the refresh nodes were recorded, as an UNDECLARED attribute + (``object.__setattr__``), so both a graph recapture (fresh DSAMetadata) + and ``dataclasses.replace()`` drop it automatically. + + Its presence tells :py:meth:`_apply_cuda_graph_metadata` that + ``graph.replay()`` re-executes the whole refresh sequence reading the + LIVE contents of the static seq_lens / req_pool_indices buffers, so the + out-of-graph replay body must skip the corresponding device work: values + it wrote would be recomputed by the captured nodes anyway and -- if + derived from any other buffers -- clobbered by them. Only host-side + state survives out-of-graph: the memoized + ``set_dsa_prefill_impl(None)`` result and the optional DG_OUT_OF_GRAPH + residual (DeepGEMM schedule builds rebuilt from raw seq_lens). + + :py:meth:`matches` revalidates on every replay that the incoming + seq_lens / req_pool_indices alias the storage the captured nodes read + (data_ptr/stride identity). A mismatch + is a HARD ERROR rather than a fallback: running the generic out-of-graph + body against foreign buffers cannot help, because the captured refresh + still re-executes at replay and overwrites the metadata from the static + buffers the caller never filled. + """ + + __slots__ = ( + "prefill_impl_state", + "residual_launch", + "_seq_lens_ptr", + "_seq_lens_stride", + "_req_pool_indices_ptr", + "_req_pool_indices_stride", + ) + + def __init__( + self, + *, + prefill_impl_state: Tuple[bool, str], + seq_lens: torch.Tensor, + req_pool_indices: torch.Tensor, + residual_launch: Optional[Callable[[], None]], + ): + self.prefill_impl_state = prefill_impl_state + self.residual_launch = residual_launch + self._seq_lens_ptr = seq_lens.data_ptr() + self._seq_lens_stride = seq_lens.stride(0) + self._req_pool_indices_ptr = req_pool_indices.data_ptr() + self._req_pool_indices_stride = req_pool_indices.stride(0) + + def matches(self, seq_lens: torch.Tensor, req_pool_indices: torch.Tensor) -> bool: + # A [:bs] slice keeps the base data_ptr/stride, so the raw incoming + # graph-runner buffers compare equal to the sliced views recorded at + # capture time. + return ( + seq_lens.data_ptr() == self._seq_lens_ptr + and req_pool_indices.data_ptr() == self._req_pool_indices_ptr + and seq_lens.stride(0) == self._seq_lens_stride + and req_pool_indices.stride(0) == self._req_pool_indices_stride + ) + + _DSA_IMPL_T: TypeAlias = Literal[ "flashmla_sparse", "flashmla_sparse_q8", @@ -315,12 +459,65 @@ def __init__( self.num_splits = ( 1 if get_exec().deterministic.enable_deterministic_inference else 0 ) - self.use_dsa = is_deepseek_dsa(model_runner.model_config.hf_config) + hf_config = model_runner.model_config.hf_config + self.use_dsa = is_deepseek_dsa(hf_config) assert self.use_dsa, "DSA backend only supports DeepSeek DSA" self.dsa_kv_cache_store_fp8 = ( model_runner.token_to_kv_pool.dsa_kv_cache_store_fp8 ) - self.dsa_index_topk = get_dsa_index_topk(model_runner.model_config.hf_config) + self.dsa_index_topk = get_dsa_index_topk(hf_config) + self.dsa_index_kpool = get_dsa_index_kpool(hf_config) + self.needs_cpu_seq_lens = self.dsa_index_kpool > 1 + # The fused metadata kernels are already the standard path for + # kpool<=1 backends; this flag extends them to page-aligned KPool + # geometries with pool-aligned topk. + # Any other geometry keeps the eager path: the env var is global and + # may be set fleet-wide across heterogeneous DSA backends, so an + # unsupported backend must degrade gracefully, not fail startup. + _kpool_fusion_requested = ( + envs.SGLANG_EXPERIMENTAL_DSA_KPOOL_METADATA_FUSION.get() + ) + _kpool_fusion_supported = _is_kpool_metadata_fusion_supported( + self.dsa_index_kpool, + self.real_page_size, + self.dsa_index_topk, + ) + # The fused kernels and the multi-step sibling-copy dedup are + # CUDA-only (every replay call site guards on is_cuda() and not + # _is_hip); fold the platform into the effective enable so every + # consumer of this attribute inherits it. + _kpool_fusion_platform_ok = is_cuda() and not _is_hip + self.experimental_kpool_metadata_fusion = ( + _kpool_fusion_requested + and _kpool_fusion_supported + and _kpool_fusion_platform_ok + ) + if ( + _kpool_fusion_requested + and self.dsa_index_kpool > 1 + and not _kpool_fusion_supported + ): + logger.warning( + "SGLANG_EXPERIMENTAL_DSA_KPOOL_METADATA_FUSION is set but this " + "DSA backend's geometry is outside the validated envelope " + "(index_kpool=%s, page_size=%s, index_topk=%s; required: " + "page_size=64, page-aligned pool, pool-aligned topk) — keeping " + "the eager metadata path for this backend.", + self.dsa_index_kpool, + self.real_page_size, + self.dsa_index_topk, + ) + # Experimental, default-off: record the whole TARGET_VERIFY metadata + # refresh inside the captured verify graph at capture time so replay + # gets it for free (see init_forward_metadata_in_graph / + # _DSAInGraphVerifyMetadataState). The DG_OUT_OF_GRAPH sub-mode keeps + # only the two DeepGEMM schedule builds out-of-graph. + self.ingraph_verify_metadata_enabled = ( + envs.SGLANG_EXPERIMENTAL_DSA_INGRAPH_VERIFY_METADATA.get() + ) + self.ingraph_verify_metadata_dg_out_of_graph = ( + envs.SGLANG_EXPERIMENTAL_DSA_INGRAPH_VERIFY_METADATA_DG_OUT_OF_GRAPH.get() + ) self.max_context_len = model_runner.model_config.context_len self.num_q_heads = ( model_runner.model_config.num_attention_heads // get_parallel().attn_tp_size @@ -350,6 +547,23 @@ def __init__( self.flashmla_kv_num_q_heads = self.num_q_heads self.enable_auto_select_prefill_impl = self.dsa_prefill_impl == "flashmla_auto" + # Hoisted per-call imports of set_dsa_prefill_impl. Module-scope + # imports would cycle through model_executor (which imports the + # attention backends); backend init runs after those modules are + # fully imported, so binding the function refs here is cycle-safe. + from sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph.context import ( + is_in_breakable_cuda_graph, + ) + from sglang.srt.model_executor.runner_backend_utils.tc_piecewise_cuda_graph import ( + is_in_tc_piecewise_cuda_graph, + ) + from sglang.srt.utils import get_device_sm, is_blackwell + + self._is_in_breakable_cuda_graph = is_in_breakable_cuda_graph + self._is_in_tc_piecewise_cuda_graph = is_in_tc_piecewise_cuda_graph + self._get_device_sm = get_device_sm + self._is_blackwell = is_blackwell + self._arange_buf = torch.arange(16384, device=self.device, dtype=torch.int32) if _is_hip: @@ -654,6 +868,56 @@ def _prepare_aiter_dsa_decode_metadata( "num_kv_splits": self.aiter_dsa_max_split_per_batch, } + def _check_kpool_tail_backend( + self, + topk_indices: Optional[torch.Tensor], + dsa_impl: _DSA_IMPL_T, + phase: str, + ) -> None: + if ( + topk_indices is None + or self.dsa_index_kpool <= 1 + or dsa_impl in ("fa3", "tilelang", "trtllm") + ): + return + raise NotImplementedError( + "index_kpool > 1 appends tail tokens to topk_indices and is " + f"currently only supported by the FA3/TileLang/TRTLLM DSA {phase} " + "backend." + ) + + def _resolve_kpool_tail_backend( + self, + topk_indices: Optional[torch.Tensor], + dsa_impl: _DSA_IMPL_T, + ) -> _DSA_IMPL_T: + if ( + topk_indices is None + or self.dsa_index_kpool <= 1 + or dsa_impl != "flashmla_sparse" + ): + return dsa_impl + if self.device_sm_major >= 10: + return "trtllm" + if self.device_sm_major == 9: + return "fa3" + return dsa_impl + + def _pad_trtllm_sparse_page_table( + self, page_table_1: torch.Tensor + ) -> Tuple[torch.Tensor, int]: + sparse_mla_top_k = page_table_1.shape[1] + padded_top_k = ((sparse_mla_top_k + 3) // 4) * 4 + if padded_top_k == sparse_mla_top_k: + return page_table_1, sparse_mla_top_k + padding = torch.full( + (page_table_1.shape[0], padded_top_k - sparse_mla_top_k), + -1, + dtype=page_table_1.dtype, + device=page_table_1.device, + ) + return torch.cat([page_table_1, padding], dim=1), padded_top_k + def _build_paged_mqa_schedule_2d_ctx_lens( self, forward_mode: ForwardMode, @@ -715,9 +979,10 @@ def _refresh_topk_v2_plan(self, metadata: DSAMetadata) -> None: # nothing to refresh. if metadata.topk_v2_plan is None: return - from sglang.kernels.ops.attention.dsv4.topk import plan_topk_v2 - - metadata.topk_v2_plan.copy_(plan_topk_v2(metadata.dsa_seqlens_expanded)) + # Write straight into the captured buffer: same shape/dtype by + # construction (it was built by plan_topk_v2 at capture), so the + # per-replay staging alloc + copy_ launch are pure overhead. + _get_plan_topk_v2()(metadata.dsa_seqlens_expanded, out=metadata.topk_v2_plan) def _get_fused_topk_page_table(self, topk_indices: torch.Tensor) -> torch.Tensor: if ( @@ -737,6 +1002,9 @@ def get_device_int32_arange(self, length: int) -> torch.Tensor: ) return self._arange_buf[:length] + def update_verify_buffers_to_fill_after_draft(self, *args, **kwargs): + return None + def _graph_page_table_width(self, metadata: DSAMetadata) -> int: """Column count to scan req_to_token during graph replay. Reads the wide page_table_1 width when present, else req_to_token's width (the wide table @@ -755,6 +1023,245 @@ def _transform_table_1_to_real(self, page_table: torch.Tensor) -> torch.Tensor: ) return page_table[:, strided_indices] // page_size + def _kpool_slots_per_page(self) -> int: + return getattr(self.token_to_kv_pool, "slots_per_page", self.real_page_size) + + def _build_kpool_paged_mqa_schedule_metadata(self) -> bool: + if self.device_sm_major == 9: + return self.num_q_heads in (32, 64) + return True + + def _init_kpool_metadata( + self, + metadata: DSAMetadata, + forward_batch: ForwardBatch, + topk_transform_method: Optional[TopkTransformMethod] = None, + kpool_inputs: Optional[_KPoolForwardInputs] = None, + ) -> DSAMetadata: + if self.dsa_index_kpool <= 1: + return metadata + + forward_mode = forward_batch.forward_mode + slots_per_page = self._kpool_slots_per_page() + build_schedule_metadata = self._build_kpool_paged_mqa_schedule_metadata() + if forward_mode.is_extend_without_speculative(): + assert topk_transform_method is not None + assert kpool_inputs is not None + return init_kpool_extend_metadata( + metadata, + forward_batch, + pool_size=self.dsa_index_kpool, + real_page_size=self.real_page_size, + slots_per_page=slots_per_page, + topk_transform_method=topk_transform_method, + full_real_page_table=kpool_inputs.full_real_page_table, + full_seqlens_expanded=kpool_inputs.full_seqlens_expanded, + **kpool_inputs.cp_overrides, + ) + + if forward_mode.is_decode_or_idle(): + metadata = init_pooled_paged_mqa_metadata( + metadata, + metadata.cache_seqlens_int32, + forward_mode, + pool_size=self.dsa_index_kpool, + real_page_size=self.real_page_size, + slots_per_page=slots_per_page, + build_schedule_metadata=build_schedule_metadata, + ) + return init_kpool_write_plan( + metadata, + forward_batch, + pool_size=self.dsa_index_kpool, + real_page_size=self.real_page_size, + real_page_table=metadata.real_page_table, + num_draft_tokens=1, + write_start=(forward_batch.seq_lens - 1).to(torch.int32), + slots_per_page=slots_per_page, + build_schedule_metadata=build_schedule_metadata, + ) + + if forward_mode.is_target_verify(): + return init_kpool_write_plan( + metadata, + forward_batch, + pool_size=self.dsa_index_kpool, + real_page_size=self.real_page_size, + real_page_table=metadata.real_page_table, + num_draft_tokens=self.speculative_num_draft_tokens, + write_start=forward_batch.seq_lens.to(torch.int32), + slots_per_page=slots_per_page, + build_schedule_metadata=build_schedule_metadata, + ) + + if forward_mode.is_draft_extend_v2(): + spec_info = forward_batch.spec_info + effective_n_per_batch = ( + spec_info.num_accept_tokens + if spec_info is not None + and getattr(spec_info, "num_accept_tokens", None) is not None + else None + ) + return init_kpool_write_plan( + metadata, + forward_batch, + pool_size=self.dsa_index_kpool, + real_page_size=self.real_page_size, + real_page_table=metadata.real_page_table, + num_draft_tokens=self.speculative_num_draft_tokens, + write_start=( + forward_batch.seq_lens - self.speculative_num_draft_tokens + ).to(torch.int32), + slots_per_page=slots_per_page, + effective_n_per_batch=effective_n_per_batch, + build_schedule_metadata=build_schedule_metadata, + ) + + return metadata + + def _init_kpool_metadata_capture( + self, metadata: DSAMetadata, bs: int, forward_mode: ForwardMode + ) -> DSAMetadata: + if self.dsa_index_kpool <= 1: + return metadata + + slots_per_page = self._kpool_slots_per_page() + build_schedule_metadata = self._build_kpool_paged_mqa_schedule_metadata() + if forward_mode.is_decode_or_idle(): + metadata = init_pooled_paged_mqa_metadata( + metadata, + metadata.cache_seqlens_int32, + forward_mode, + pool_size=self.dsa_index_kpool, + real_page_size=self.real_page_size, + slots_per_page=slots_per_page, + build_schedule_metadata=build_schedule_metadata, + ) + + if ( + forward_mode.is_decode_or_idle() + or forward_mode.is_target_verify() + or forward_mode.is_draft_extend_v2() + ): + is_decode = forward_mode.is_decode_or_idle() + is_v2 = forward_mode.is_draft_extend_v2() + metadata = init_kpool_write_plan_capture( + metadata, + max_bs=bs, + pool_size=self.dsa_index_kpool, + real_page_size=self.real_page_size, + num_draft_tokens=( + 1 if is_decode else self.speculative_num_draft_tokens + ), + device=self.device, + is_verify=not is_decode, + slots_per_page=slots_per_page, + is_v2=is_v2, + build_schedule_metadata=build_schedule_metadata, + ) + + return metadata + + def _update_kpool_metadata_replay( + self, + metadata: DSAMetadata, + seq_lens: torch.Tensor, + req_pool_indices: torch.Tensor, + forward_mode: ForwardMode, + effective_n_per_batch: Optional[torch.Tensor] = None, + include_deep_gemm_schedule: bool = True, + ) -> None: + if self.dsa_index_kpool <= 1: + return + + slots_per_page = self._kpool_slots_per_page() + build_schedule_metadata = self._build_kpool_paged_mqa_schedule_metadata() + if forward_mode.is_decode_or_idle(): + update_pooled_paged_mqa_metadata( + metadata, + metadata.cache_seqlens_int32, + forward_mode, + pool_size=self.dsa_index_kpool, + real_page_size=self.real_page_size, + slots_per_page=slots_per_page, + build_schedule_metadata=build_schedule_metadata, + ) + + if not ( + forward_mode.is_decode_or_idle() + or forward_mode.is_target_verify() + or forward_mode.is_draft_extend_v2() + ): + return + + is_decode = forward_mode.is_decode_or_idle() + is_v2 = forward_mode.is_draft_extend_v2() + if is_decode: + write_start = seq_lens.to(torch.int32) - 1 + elif is_v2: + write_start = seq_lens.to(torch.int32) - self.speculative_num_draft_tokens + else: + # Target verify: write_start == seq_lens exactly; the plan kernel + # casts on load, so skip the per-replay int32 alloc + conversion. + write_start = seq_lens + update_kpool_write_plan( + metadata, + write_start=write_start, + req_pool_indices=req_pool_indices, + real_page_table=metadata.real_page_table, + pool_size=self.dsa_index_kpool, + real_page_size=self.real_page_size, + num_draft_tokens=(1 if is_decode else self.speculative_num_draft_tokens), + forward_mode=forward_mode, + slots_per_page=slots_per_page, + effective_n_per_batch=effective_n_per_batch, + include_deep_gemm_schedule=include_deep_gemm_schedule, + ) + + def _update_kpool_metadata_from_precomputed( + self, + metadata: DSAMetadata, + precomputed: PrecomputedMetadata, + forward_mode: ForwardMode, + ) -> None: + if self.dsa_index_kpool <= 1: + return + + slots_per_page = self._kpool_slots_per_page() + build_schedule_metadata = self._build_kpool_paged_mqa_schedule_metadata() + if forward_mode.is_decode_or_idle(): + update_pooled_paged_mqa_metadata( + metadata, + precomputed.cache_seqlens, + forward_mode, + pool_size=self.dsa_index_kpool, + real_page_size=self.real_page_size, + slots_per_page=slots_per_page, + build_schedule_metadata=build_schedule_metadata, + ) + + if not (forward_mode.is_decode_or_idle() or forward_mode.is_target_verify()): + return + + is_verify = forward_mode.is_target_verify() + write_start = precomputed.cache_seqlens.to(torch.int32) + write_start = ( + write_start - self.speculative_num_draft_tokens + if is_verify + else write_start - 1 + ) + update_kpool_write_plan( + metadata, + write_start=write_start, + req_pool_indices=precomputed.req_pool_indices, + real_page_table=metadata.real_page_table, + pool_size=self.dsa_index_kpool, + real_page_size=self.real_page_size, + num_draft_tokens=self.speculative_num_draft_tokens if is_verify else 1, + forward_mode=forward_mode, + slots_per_page=slots_per_page, + ) + def init_forward_metadata_out_graph( self, forward_batch: ForwardBatch, @@ -826,6 +1333,17 @@ def init_forward_metadata(self, forward_batch: ForwardBatch): # seq_len_cpu of selected sequences indexer_seq_lens_cpu = forward_batch.seq_lens_cpu indexer_seq_lens = forward_batch.seq_lens + use_kpool = self.dsa_index_kpool > 1 + if use_kpool: + assert ( + self.real_page_size == 64 + and self.real_page_size % self.dsa_index_kpool == 0 + ), ( + f"kpool path requires page_size == 64 and page_size % pool_size == 0; " + f"got page_size={self.real_page_size}, pool_size={self.dsa_index_kpool}." + ) + kpool_inputs = _KPoolForwardInputs() + zigzag_cp_split = False if forward_batch.forward_mode.is_decode_or_idle(): extend_seq_lens_cpu = [1] * batch_size @@ -925,6 +1443,11 @@ def init_forward_metadata(self, forward_batch: ForwardBatch): ) ] ) + if use_kpool: + kpool_inputs.full_real_page_table = self._transform_table_1_to_real( + page_table + ) + kpool_inputs.full_seqlens_expanded = seqlens_expanded if can_dsa_prefill_cp_round_robin_split(forward_batch): if is_cp_v2_active(forward_batch): @@ -950,8 +1473,127 @@ def init_forward_metadata(self, forward_batch: ForwardBatch): else 0 ) page_table = page_table[bs_idx, :max_seqlen_k] + if use_kpool: + kpool_inputs.cp_overrides = dict( + local_real_page_table=self._transform_table_1_to_real( + page_table + ), + local_seqlens_expanded=seqlens_expanded, + local_extend_seq_lens_cpu=list(extend_seq_lens_cpu), + local_seq_lens_cpu=indexer_seq_lens_cpu.tolist(), + local_req_pool_indices=forward_batch.req_pool_indices[bs_idx], + ) + + elif dsa_use_prefill_cp( + forward_batch + ) and not can_dsa_prefill_cp_round_robin_split(forward_batch): + zigzag_cp_split = True + cp_meta = forward_batch.attn_cp_metadata + prev_q_lens = list( + getattr(cp_meta, "actual_seq_q_prev_list", None) + or [int(cp_meta.actual_seq_q_prev)] + ) + next_q_lens = list( + getattr(cp_meta, "actual_seq_q_next_list", None) + or [int(cp_meta.actual_seq_q_next)] + ) + prev_k_lens = list( + getattr(cp_meta, "kv_len_prev_list", None) + or [int(cp_meta.kv_len_prev)] + ) + next_k_lens = list( + getattr(cp_meta, "kv_len_next_list", None) + or [int(cp_meta.kv_len_next)] + ) + cp_bs = len(prev_q_lens) + assert ( + cp_bs == len(next_q_lens) == len(prev_k_lens) == len(next_k_lens) + ), "Mismatched zigzag CP metadata lengths" + + prefix_offsets = [] + seq_lens_cpu_list = forward_batch.seq_lens_cpu.tolist() + for i in range(cp_bs): + prefix_offsets.append( + max( + int(seq_lens_cpu_list[i]) + - int(forward_batch.extend_seq_lens_cpu[i]), + 0, + ) + ) + + local_seq_lens_cpu = [ + prefix_offsets[i] + int(prev_k_lens[i]) for i in range(cp_bs) + ] + [prefix_offsets[i] + int(next_k_lens[i]) for i in range(cp_bs)] + local_extend_seq_lens_cpu = [int(x) for x in prev_q_lens] + [ + int(x) for x in next_q_lens + ] + + local_seqlens = [] + for q_len, kv_len in zip( + local_extend_seq_lens_cpu, local_seq_lens_cpu, strict=True + ): + if q_len <= 0: + continue + local_seqlens.append( + torch.arange( + kv_len - q_len + 1, + kv_len + 1, + dtype=torch.int32, + device=device, + ) + ) + seqlens_expanded = ( + torch.cat(local_seqlens) + if local_seqlens + else torch.empty(0, dtype=torch.int32, device=device) + ) - if any(forward_batch.extend_prefix_lens_cpu) or bs_idx_cpu is not None: + extend_seq_lens_cpu = local_extend_seq_lens_cpu + extend_seq_lens = torch.tensor( + extend_seq_lens_cpu, dtype=torch.int32, device=device + ) + indexer_seq_lens_cpu = torch.tensor( + local_seq_lens_cpu, + dtype=forward_batch.seq_lens_cpu.dtype, + device=forward_batch.seq_lens_cpu.device, + ) + indexer_seq_lens = torch.tensor( + local_seq_lens_cpu, + dtype=forward_batch.seq_lens.dtype, + device=device, + ) + cache_seqlens_int32 = indexer_seq_lens.to(torch.int32) + cu_seqlens_k = compute_cu_seqlens(cache_seqlens_int32) + max_seqlen_k = max(local_seq_lens_cpu) if local_seq_lens_cpu else 0 + + local_page_table = torch.cat( + [page_table[:cp_bs], page_table[:cp_bs]], dim=0 + ) + page_table = local_page_table[:, :max_seqlen_k] + local_req_pool_indices = torch.cat( + [ + forward_batch.req_pool_indices[:cp_bs], + forward_batch.req_pool_indices[:cp_bs], + ], + dim=0, + ) + + if use_kpool: + kpool_inputs.cp_overrides = dict( + local_real_page_table=self._transform_table_1_to_real( + page_table + ), + local_seqlens_expanded=seqlens_expanded, + local_extend_seq_lens_cpu=local_extend_seq_lens_cpu, + local_seq_lens_cpu=local_seq_lens_cpu, + local_req_pool_indices=local_req_pool_indices, + ) + + if ( + any(forward_batch.extend_prefix_lens_cpu) + or bs_idx_cpu is not None + or zigzag_cp_split + ): max_seqlen_q = ( max(extend_seq_lens_cpu) if len(extend_seq_lens_cpu) != 0 else 1 ) @@ -1011,10 +1653,18 @@ def init_forward_metadata(self, forward_batch: ForwardBatch): dsa_cache_seqlens_int32 = compute_dsa_seqlens( original_seq_lens=seqlens_expanded, dsa_index_topk=self.dsa_index_topk, + index_kpool=self.dsa_index_kpool, ) dsa_cache_seqlens_int32 = pad_dsa_cache_seqlens( forward_batch, dsa_cache_seqlens_int32 ) + if ( + zigzag_cp_split + and dsa_cache_seqlens_int32.shape[0] != seqlens_expanded.shape[0] + ): + dsa_cache_seqlens_int32 = dsa_cache_seqlens_int32[ + : seqlens_expanded.shape[0] + ] dsa_cu_seqlens_k = compute_cu_seqlens(dsa_cache_seqlens_int32) dsa_cu_seqlens_q = self.get_device_int32_arange(len(dsa_cu_seqlens_k)) @@ -1072,6 +1722,12 @@ def init_forward_metadata(self, forward_batch: ForwardBatch): token_to_batch_idx=token_to_batch_idx, topk_v2_plan=self._build_topk_v2_plan(seqlens_expanded), ) + metadata = self._init_kpool_metadata( + metadata, + forward_batch, + topk_transform_method=topk_transform_method, + kpool_inputs=kpool_inputs, + ) self.forward_metadata = metadata def _cal_indexer_k_start_end( @@ -1183,6 +1839,8 @@ def init_cuda_graph_state(self, max_bs: int, max_num_tokens: int): and self.real_page_size > 1 and self.hisparse_coordinator is None and not self.speculative_num_draft_tokens + # kpool's PAGED fused-topk mapping still reads page_table_1. + and self.dsa_index_kpool <= 1 and self.use_fused_topk and self.dsa_topk_backend.should_use_topk_v2() and self.dsa_index_topk is not None @@ -1275,7 +1933,9 @@ def _build_forward_metadata_cuda_graph( # NOTE(dark): this is always arange, since we are decoding cu_seqlens_q = self.decode_cuda_graph_metadata["cu_seqlens_q"][: bs + 1] dsa_cache_seqlens_int32 = compute_dsa_seqlens( - cache_seqlens_int32, dsa_index_topk=self.dsa_index_topk + cache_seqlens_int32, + dsa_index_topk=self.dsa_index_topk, + index_kpool=self.dsa_index_kpool, ) seqlens_expanded = cache_seqlens_int32 @@ -1338,7 +1998,9 @@ def _build_forward_metadata_cuda_graph( ] ) dsa_cache_seqlens_int32 = compute_dsa_seqlens( - seqlens_expanded, dsa_index_topk=self.dsa_index_topk + seqlens_expanded, + dsa_index_topk=self.dsa_index_topk, + index_kpool=self.dsa_index_kpool, ) dsa_extend_seq_lens_list = [1] * bs * self.speculative_num_draft_tokens @@ -1400,6 +2062,7 @@ def _build_forward_metadata_cuda_graph( dsa_extend_seq_lens_list=dsa_extend_seq_lens_list, topk_v2_plan=self._build_topk_v2_plan(seqlens_expanded), ) + metadata = self._init_kpool_metadata_capture(metadata, bs, forward_mode) self.decode_cuda_graph_metadata[bs] = metadata self.forward_metadata = metadata @@ -1434,24 +2097,65 @@ def _apply_cuda_graph_metadata( ) return + metadata: DSAMetadata = self.decode_cuda_graph_metadata[bs] + + # Experimental in-graph verify metadata + # (SGLANG_EXPERIMENTAL_DSA_INGRAPH_VERIFY_METADATA): the whole + # TARGET_VERIFY refresh sequence for this entry was recorded INSIDE + # the captured graph at capture time (init_forward_metadata_in_graph), + # so graph.replay() re-executes it -- ahead of the attention kernels, + # reading the CURRENT contents of the static seq_lens / + # req_pool_indices buffers that fill_from refreshed this cycle. Skip + # the corresponding out-of-graph device work here; keep only host + # state (the memoized set_dsa_prefill_impl(None) result) and the + # optional DG_OUT_OF_GRAPH residual. Runs during recapture too + # (in_capture out_graph replays this body): the residual is harmless + # there and the in-graph hook re-publishes a fresh state afterwards. + if forward_mode.is_target_verify(): + ingraph_state = getattr(metadata, "_ingraph_verify_metadata", None) + if ingraph_state is not None: + if not ingraph_state.matches(seq_lens, req_pool_indices): + raise RuntimeError( + "DSA in-graph verify metadata: this replay's seq_lens" + " / req_pool_indices do not alias the static buffers " + "captured into the verify graph; the captured refresh" + " nodes would read buffers this caller never filled. " + "Replay TARGET_VERIFY only through the graph runner's" + " registry buffers, or disable " + "SGLANG_EXPERIMENTAL_DSA_INGRAPH_VERIFY_METADATA." + ) + self.use_mha, self.dsa_prefill_impl = ingraph_state.prefill_impl_state + if ingraph_state.residual_launch is not None: + ingraph_state.residual_launch() + if not getattr(self, "_ingraph_verify_hit_logged", False): + self._ingraph_verify_hit_logged = True + logger.info( + "DSA in-graph verify metadata replay engaged (bs=%d)", + bs, + ) + self.forward_metadata = metadata + return + self.set_dsa_prefill_impl(forward_batch=None) seq_lens = seq_lens[:bs] req_pool_indices = req_pool_indices[:bs] # Normal Decode - metadata: DSAMetadata = self.decode_cuda_graph_metadata[bs] used_fused_metadata_generation = False target_verify_ctx_lens_written = False + if forward_mode.is_decode_or_idle(): # Normal Decode max_len = self._graph_page_table_width(metadata) - if is_cuda() and not _is_hip: - from sglang.kernels.ops.attention.dsa_metadata import ( - fused_dsa_decode_metadata, + if ( + is_cuda() + and not _is_hip + and ( + self.dsa_index_kpool <= 1 or self.experimental_kpool_metadata_fusion ) - + ): fused_dsa_decode_metadata( seq_lens=seq_lens, req_pool_indices=req_pool_indices, @@ -1466,6 +2170,7 @@ def _apply_cuda_graph_metadata( max_len=max_len, dsa_index_topk=self.dsa_index_topk, real_page_size=self.real_page_size, + index_kpool=self.dsa_index_kpool, ) cache_seqlens = metadata.cache_seqlens_int32 dsa_cache_seqlens = metadata.dsa_cache_seqlens_int32 @@ -1482,18 +2187,22 @@ def _apply_cuda_graph_metadata( page_indices = self.req_to_token[req_pool_indices, :max_len] metadata.page_table_1[:, :max_len].copy_(page_indices) dsa_cache_seqlens = compute_dsa_seqlens( - cache_seqlens, dsa_index_topk=self.dsa_index_topk + cache_seqlens, + dsa_index_topk=self.dsa_index_topk, + index_kpool=self.dsa_index_kpool, ) metadata.dsa_cache_seqlens_int32.copy_(dsa_cache_seqlens) seqlens_expanded = cache_seqlens elif forward_mode.is_target_verify(): max_seqlen_k = self._graph_page_table_width(metadata) - if is_cuda() and not _is_hip: - from sglang.kernels.ops.attention.dsa_metadata import ( - fused_dsa_target_verify_metadata, + if ( + is_cuda() + and not _is_hip + and ( + self.dsa_index_kpool <= 1 or self.experimental_kpool_metadata_fusion ) - + ): paged_mqa_ctx_lens_2d = None if ( self.speculative_num_draft_tokens >= 2 @@ -1523,6 +2232,7 @@ def _apply_cuda_graph_metadata( real_page_size=self.real_page_size, next_n=self.speculative_num_draft_tokens, paged_mqa_ctx_lens_2d=paged_mqa_ctx_lens_2d, + index_kpool=self.dsa_index_kpool, ) target_verify_ctx_lens_written = paged_mqa_ctx_lens_2d is not None cache_seqlens = metadata.cache_seqlens_int32 @@ -1565,7 +2275,9 @@ def _apply_cuda_graph_metadata( ) metadata.dsa_seqlens_expanded.copy_(seqlens_expanded) dsa_cache_seqlens = compute_dsa_seqlens( - seqlens_expanded, self.dsa_index_topk + seqlens_expanded, + self.dsa_index_topk, + index_kpool=self.dsa_index_kpool, ) metadata.dsa_cache_seqlens_int32.copy_(dsa_cache_seqlens) elif forward_mode.is_draft_extend_v2(): @@ -1587,11 +2299,13 @@ def _apply_cuda_graph_metadata( device=self.device, ) - if is_cuda() and not _is_hip: - from sglang.kernels.ops.attention.dsa_metadata import ( - fused_dsa_draft_extend_metadata, + if ( + is_cuda() + and not _is_hip + and ( + self.dsa_index_kpool <= 1 or self.experimental_kpool_metadata_fusion ) - + ): fused_dsa_draft_extend_metadata( seq_lens=seq_lens, extend_seq_lens=extend_seq_lens, @@ -1612,6 +2326,7 @@ def _apply_cuda_graph_metadata( max_extend_len=self.speculative_num_draft_tokens, max_total_len=bs * self.speculative_num_draft_tokens, static_extend_len=True, + index_kpool=self.dsa_index_kpool, ) cache_seqlens = metadata.cache_seqlens_int32 seqlens_expanded = metadata.dsa_seqlens_expanded[:total_extend_len] @@ -1642,7 +2357,9 @@ def _apply_cuda_graph_metadata( seqlens_expanded ) dsa_cache_seqlens = compute_dsa_seqlens( - seqlens_expanded, self.dsa_index_topk + seqlens_expanded, + self.dsa_index_topk, + index_kpool=self.dsa_index_kpool, ) metadata.dsa_cache_seqlens_int32.copy_(dsa_cache_seqlens) @@ -1696,6 +2413,19 @@ def _apply_cuda_graph_metadata( else: assert metadata.real_page_table is metadata.page_table_1 + effective_n_per_batch = None + if forward_mode.is_draft_extend_v2() and spec_info is not None: + effective_n_per_batch = getattr(spec_info, "num_accept_tokens", None) + if effective_n_per_batch is not None: + effective_n_per_batch = effective_n_per_batch[:bs] + self._update_kpool_metadata_replay( + metadata, + seq_lens, + req_pool_indices, + forward_mode, + effective_n_per_batch=effective_n_per_batch, + ) + if self.dsa_decode_impl == "flashmla_kv": flashmla_metadata = metadata.flashmla_metadata.slice( slice(0, seqlens_expanded_size + 1) @@ -1709,6 +2439,290 @@ def _apply_cuda_graph_metadata( self.forward_metadata = metadata + def _ingraph_verify_metadata_eligible(self) -> bool: + """Config-level eligibility for the in-graph TARGET_VERIFY refresh. + + Mirrors the eligibility of the fused replay body: the recorded nodes + replicate exactly the FUSED verify + sequence, so configs that would take the unfused aten fallback + (kpool > 1 without the fusion gate), DCP, HIP, or flashmla_kv (whose + per-replay metadata recompute is host-side) stay out-of-graph. + """ + return ( + self.ingraph_verify_metadata_enabled + and is_cuda() + and not _is_hip + and not get_parallel().dcp_enabled + and (self.dsa_index_kpool <= 1 or self.experimental_kpool_metadata_fusion) + and self.dsa_decode_impl != "flashmla_kv" + ) + + def init_forward_metadata_in_graph(self, forward_batch: ForwardBatch): + """Graph-recordable TARGET_VERIFY metadata refresh (experimental, + SGLANG_EXPERIMENTAL_DSA_INGRAPH_VERIFY_METADATA; default no-op). + + Runs inside ``with graph.capture():`` (the decode runner's run_once, + after init_forward_metadata_out_graph(in_capture=True) built the + metadata entry and BEFORE the model forward), so every launch below + is recorded as graph nodes that precede the attention kernels in the + SAME captured graph. At replay they re-execute reading the CURRENT + contents of the runner's static seq_lens / req_pool_indices buffers + -- buffer contents are read at replay execution time, not capture + time, and fill_from refreshes them on the fwd/plan stream before + graph.replay() in stream order. + + Capture-legality per recorded op (base-hook lint contract): + - fused_dsa_target_verify_metadata: plain triton launch; the + JITFunction host planning happens once here at capture. + - ctx-lens publication: captured copy_ between static buffers. + - deep_gemm.get_paged_mqa_logits_metadata: static-shape device + build; the fresh output tensor is allocated in the graph-private + pool (address stable across replays) and the captured copy_ into + the static schedule buffer pins the dataflow. If a deep_gemm + build is ever not stream-capture-safe, set + SGLANG_EXPERIMENTAL_DSA_INGRAPH_VERIFY_METADATA_DG_OUT_OF_GRAPH=1 + to keep both DeepGEMM builds out-of-graph (rebuilt per replay + from raw seq_lens by the residual). + - plan_topk_v2(out=...): single tvm-ffi kernel launch into the + preallocated plan buffer (LaunchKernel resolves the capture + stream; no sync, no alloc). + - KPool write plan: triton launch (+ pooled DeepGEMM schedule when + DG stays in-graph). + + No-op -- leaving the generic out-of-graph replay body in charge -- + for non-TARGET_VERIFY captures (e.g. the multi-step draft DECODE + backends reach this via DeepseekSparseAttnMultiStepBackend), + ineligible configs, and any structural surprise in + _record_ingraph_verify_metadata. The hybrid linear (KDA/mamba) + sibling stays out-of-graph: its query_start_loc clamp and + state-index poisoning depend on the host-side per-replay num_padding + and the live v2p mamba translate, so they are not trivially + graph-recordable. + """ + if not forward_batch.forward_mode.is_target_verify(): + return + if not self._ingraph_verify_metadata_eligible(): + return + bs = forward_batch.batch_size + metadata = self.decode_cuda_graph_metadata.get(bs) + if metadata is None: + return + self._record_ingraph_verify_metadata( + metadata, + bs, + forward_batch.seq_lens[:bs], + forward_batch.req_pool_indices[:bs], + ) + + def _record_ingraph_verify_metadata( + self, + metadata: DSAMetadata, + bs: int, + seq_lens: torch.Tensor, + req_pool_indices: torch.Tensor, + ) -> None: + """Record the fused TARGET_VERIFY refresh into the graph being + captured and publish _DSAInGraphVerifyMetadataState on success. + + Mirrors, node for node and in the same stream order, the fused + TARGET_VERIFY body of _apply_cuda_graph_metadata (fused metadata + kernel -> DeepGEMM schedule -> ctx-lens publication -> top-k v2 plan + -> KPool write plan + pooled schedule). Bails WITHOUT publishing on + any structural surprise, leaving the graph without refresh nodes and + the generic out-of-graph replay in charge. Also runs eagerly during + the pre-capture warmup invocations of run_once, which is idempotent: + it rewrites the same buffers with the same capture-time values. + """ + if metadata.paged_mqa_schedule_metadata is None: + return + next_n = self.speculative_num_draft_tokens + if not next_n: + return + expanded_size = bs * next_n + max_seqlen_k = self._graph_page_table_width(metadata) + + # Same DG-native eligibility checks as the fused replay body. + paged_mqa_ctx_lens_2d = None + if ( + next_n >= 2 + and is_sm100_supported() + and metadata.paged_mqa_ctx_lens_2d is not None + and metadata.paged_mqa_ctx_lens_2d.dim() == 2 + and metadata.paged_mqa_ctx_lens_2d.size(0) == bs + and metadata.paged_mqa_ctx_lens_2d.size(1) == next_n + ): + paged_mqa_ctx_lens_2d = metadata.paged_mqa_ctx_lens_2d + ctx_lens_written = paged_mqa_ctx_lens_2d is not None + + if ctx_lens_written: + # DG-native layout: the fused kernel writes ctx lens straight + # into the captured (bs, next_n) buffer; the schedule reads it. + schedule_src_2d = metadata.paged_mqa_ctx_lens_2d + ctx_lens_copy_src = None + else: + if next_n >= 2 and is_sm100_supported(): + # Degenerate capture (DG-native ctx-lens layout expected but + # missing); keep the whole refresh out-of-graph. + return + seqlens_view = metadata.dsa_seqlens_expanded[:expanded_size] + if not seqlens_view.is_contiguous(): + return + schedule_src_2d = seqlens_view.view(-1, 1) + if metadata.paged_mqa_ctx_lens_2d is None: + # Verify capture always materializes the 2D ctx-lens buffer; + # if missing, leave the object.__setattr__ publication to + # the generic path. + return + ctx_lens_copy_src = schedule_src_2d + + # ---- Recorded nodes; identical device-work order to the fused + # out-of-graph replay body. ------------------------------------ + # 1. Fused verify metadata (triton): cache/dsa seqlens, cu_seqlens, + # page tables, expanded seqlens, optional DG-native ctx lens. + fused_dsa_target_verify_metadata( + seq_lens=seq_lens, + req_pool_indices=req_pool_indices, + req_to_token=self.req_to_token, + cache_seqlens=metadata.cache_seqlens_int32, + cu_seqlens_k=metadata.cu_seqlens_k, + page_table_1=metadata.page_table_1, + seqlens_expanded=metadata.dsa_seqlens_expanded, + dsa_cache_seqlens=metadata.dsa_cache_seqlens_int32, + dsa_cu_seqlens_k=metadata.dsa_cu_seqlens_k, + real_page_table=metadata.real_page_table, + bs=bs, + max_seqlen_k=max_seqlen_k, + dsa_index_topk=self.dsa_index_topk, + real_page_size=self.real_page_size, + next_n=next_n, + paged_mqa_ctx_lens_2d=paged_mqa_ctx_lens_2d, + index_kpool=self.dsa_index_kpool, + ) + + # 2. DeepGEMM paged-MQA schedule refresh + ctx-lens publication. + dg_in_graph = not self.ingraph_verify_metadata_dg_out_of_graph + num_sms = deep_gemm.get_num_sms() + if dg_in_graph: + metadata.paged_mqa_schedule_metadata.copy_( + deep_gemm.get_paged_mqa_logits_metadata(schedule_src_2d, 64, num_sms) + ) + if ctx_lens_copy_src is not None: + metadata.paged_mqa_ctx_lens_2d.copy_(ctx_lens_copy_src) + + # 3. Top-k v2 plan refresh (tvm-ffi kernel into the captured plan). + if metadata.topk_v2_plan is not None: + _get_plan_topk_v2()( + metadata.dsa_seqlens_expanded, out=metadata.topk_v2_plan + ) + + # 4. KPool write plan (+ pooled schedule iff DG stays in-graph). + self._update_kpool_metadata_replay( + metadata, + seq_lens, + req_pool_indices, + ForwardMode.TARGET_VERIFY, + include_deep_gemm_schedule=dg_in_graph, + ) + + residual_launch = None + if not dg_in_graph: + residual_launch = self._build_ingraph_verify_dg_residual( + metadata, + next_n, + seq_lens, + num_sms, + ctx_lens_written, + ) + + # set_dsa_prefill_impl(forward_batch=None) is a pure function of + # init-time config; capture its result for the in-graph replay state. + self.set_dsa_prefill_impl(forward_batch=None) + state = _DSAInGraphVerifyMetadataState( + prefill_impl_state=(self.use_mha, self.dsa_prefill_impl), + seq_lens=seq_lens, + req_pool_indices=req_pool_indices, + residual_launch=residual_launch, + ) + # Undeclared attribute on the frozen dataclass: dropped by both + # recapture (fresh DSAMetadata) and dataclasses.replace(). + object.__setattr__(metadata, "_ingraph_verify_metadata", state) + logger.info( + "DSA in-graph verify metadata recorded: bs=%d next_n=%d " + "ctx_lens_written=%s dg_in_graph=%s", + bs, + next_n, + ctx_lens_written, + dg_in_graph, + ) + + def _build_ingraph_verify_dg_residual( + self, + metadata: DSAMetadata, + next_n: int, + seq_lens: torch.Tensor, + num_sms: int, + ctx_lens_written: bool, + ) -> Callable[[], None]: + """Out-of-graph per-replay residual for the DG_OUT_OF_GRAPH fallback. + + Only the two DeepGEMM schedule builds stay out-of-graph. They must + NOT read the kernel-written metadata buffers here: at residual time + (the out-of-graph replay body, before graph.replay()) the captured + triton refresh has not run yet for this cycle, so those buffers + still hold LAST replay's values. Both schedule sources are instead + rebuilt from the raw seq_lens buffer using the exact closed forms + the captured kernels write: + - main schedule ctx lens: cache_seqlens = seq_lens + next_n + ((bs, next_n) DG-native expand), or the per-token expanded + lens seq_lens + [1..next_n] as (bs*next_n, 1) otherwise; + - pooled KPool per-q lens: (seq_lens + k + 1) // pool_size for + k in [0, next_n) (verify write_start == seq_lens; see + _update_kpool_write_plan_kernel). + """ + schedule_dst = metadata.paged_mqa_schedule_metadata + dg_get = deep_gemm.get_paged_mqa_logits_metadata + pool_size = self.dsa_index_kpool + slots_per_page = self._kpool_slots_per_page() + kpool_plan = metadata.kpool_write_plan if pool_size > 1 else None + has_pool_schedule = ( + kpool_plan is not None and kpool_plan.pool_schedule_metadata is not None + ) + # Built lazily INSIDE the residual: this builder runs during stream + # capture, where a torch.arange would be RECORDED (contents undefined + # until the graph first replays) instead of executed; the residual + # itself always runs out-of-graph, so its first call materializes the + # constant eagerly. + offsets_box: List[Optional[torch.Tensor]] = [None] + + def residual() -> None: + offsets = offsets_box[0] + if offsets is None: + offsets = torch.arange( + 1, next_n + 1, dtype=torch.int32, device=seq_lens.device + ) + offsets_box[0] = offsets + seq_lens_i32 = seq_lens.to(torch.int32) + if ctx_lens_written: + src = ( + (seq_lens_i32 + next_n).view(-1, 1).expand(-1, next_n).contiguous() + ) + else: + src = (seq_lens_i32.view(-1, 1) + offsets).reshape(-1, 1).contiguous() + schedule_dst.copy_(dg_get(src, 64, num_sms)) + if has_pool_schedule: + pool_seqlens_per_q = torch.div( + seq_lens_i32.view(-1, 1) + offsets, + pool_size, + rounding_mode="floor", + ).reshape(-1) + refresh_kpool_pool_schedule_from( + metadata, + pool_seqlens_per_q, + slots_per_page=slots_per_page, + ) + + return residual + def init_forward_metadata_replay_cuda_graph_from_precomputed( self, bs: int, @@ -1728,6 +2742,45 @@ def init_forward_metadata_replay_cuda_graph_from_precomputed( metadata = self.decode_cuda_graph_metadata[bs] + self._copy_base_replay_buffers(bs, metadata, precomputed, forward_mode) + + # Refresh DeepGEMM paged MQA schedule metadata for the actual seqlens of + # this replay (the captured graph holds stale data otherwise, which can + # deadlock the kernel when the runtime work decomposition diverges from + # the captured one). + if is_cuda(): + if forward_mode.is_decode_or_idle(): + seqlens_32_2d = _to_2d_context_lens(metadata.cache_seqlens_int32, bs) + else: + seqlens_32_2d = self._build_paged_mqa_schedule_2d_ctx_lens( + forward_mode, + metadata.cache_seqlens_int32, + metadata.dsa_seqlens_expanded, + bs, + ) + self._refresh_paged_mqa_schedule_metadata(metadata, seqlens_32_2d) + self._refresh_topk_v2_plan(metadata) + if metadata.paged_mqa_ctx_lens_2d is None: + object.__setattr__(metadata, "paged_mqa_ctx_lens_2d", seqlens_32_2d) + else: + metadata.paged_mqa_ctx_lens_2d.copy_(seqlens_32_2d) + + self._update_kpool_metadata_from_precomputed( + metadata, precomputed, forward_mode + ) + + self.forward_metadata = metadata + + def _copy_base_replay_buffers( + self, + bs: int, + metadata: DSAMetadata, + precomputed: PrecomputedMetadata, + forward_mode: ForwardMode, + ) -> None: + """Copy the captured base buffers of `metadata` from `precomputed` + (fused CUDA kernel with a per-tensor fallback). Shared between the + full replay path above and `_copy_replay_metadata_from_sibling`.""" # Track whether fused kernel succeeded fused_kernel_succeeded = False @@ -1848,27 +2901,143 @@ def init_forward_metadata_replay_cuda_graph_from_precomputed( flashmla_metadata = metadata.flashmla_metadata.slice(slice(0, size + 1)) flashmla_metadata.copy_(precomputed.flashmla_metadata) - # Refresh DeepGEMM paged MQA schedule metadata for the actual seqlens of - # this replay (the captured graph holds stale data otherwise, which can - # deadlock the kernel when the runtime work decomposition diverges from - # the captured one). + @staticmethod + def _sibling_replay_metadata_compatible(dst: DSAMetadata, src: DSAMetadata) -> bool: + """Structural check that every derived buffer the sibling-copy path + writes exists on both sides. Step backends of a multi-step group are + constructed and captured identically, so this always holds in + practice; a mismatch routes the caller back to the full recompute + path instead of risking stale derived metadata.""" + + def _match(a, b) -> bool: + return (a is None) == (b is None) + + if not ( + _match(dst.paged_mqa_schedule_metadata, src.paged_mqa_schedule_metadata) + and _match(dst.topk_v2_plan, src.topk_v2_plan) + and _match(dst.pooled_cache_seqlens_int32, src.pooled_cache_seqlens_int32) + and _match(dst.pooled_real_page_table, src.pooled_real_page_table) + and _match( + dst.pooled_paged_mqa_schedule_metadata, + src.pooled_paged_mqa_schedule_metadata, + ) + and _match(dst.kpool_write_plan, src.kpool_write_plan) + ): + return False + dst_plan, src_plan = dst.kpool_write_plan, src.kpool_write_plan + if dst_plan is not None and not ( + _match(dst_plan.pool_seqlens_per_q, src_plan.pool_seqlens_per_q) + and _match(dst_plan.seqlens_per_q, src_plan.seqlens_per_q) + and _match(dst_plan.pool_schedule_metadata, src_plan.pool_schedule_metadata) + and _match(dst_plan.effective_n_per_batch, src_plan.effective_n_per_batch) + ): + return False + return True + + def _copy_kpool_metadata_from_sibling( + self, metadata: DSAMetadata, src_metadata: DSAMetadata + ) -> None: + """D2D mirror of `_update_kpool_metadata_from_precomputed`: copy every + buffer that function writes (pooled seqlens div, pooled page table, + DeepGEMM pool schedule, and the kpool write plan) from a sibling + backend that just ran the real update on identical inputs.""" + if self.dsa_index_kpool <= 1 or not is_cuda(): + return + + if metadata.pooled_cache_seqlens_int32 is not None: + metadata.pooled_cache_seqlens_int32.copy_( + src_metadata.pooled_cache_seqlens_int32 + ) + if metadata.pooled_real_page_table is not None: + metadata.pooled_real_page_table.copy_(src_metadata.pooled_real_page_table) + if metadata.pooled_paged_mqa_schedule_metadata is not None: + metadata.pooled_paged_mqa_schedule_metadata.copy_( + src_metadata.pooled_paged_mqa_schedule_metadata + ) + + dst_plan = metadata.kpool_write_plan + src_plan = src_metadata.kpool_write_plan + if dst_plan is None: + return + dst_plan.req.copy_(src_plan.req) + dst_plan.write_start.copy_(src_plan.write_start) + dst_plan.tail_logical_start.copy_(src_plan.tail_logical_start) + dst_plan.write_loc.copy_(src_plan.write_loc) + if dst_plan.pool_seqlens_per_q is not None: + dst_plan.pool_seqlens_per_q.copy_(src_plan.pool_seqlens_per_q) + if dst_plan.seqlens_per_q is not None: + dst_plan.seqlens_per_q.copy_(src_plan.seqlens_per_q) + if dst_plan.pool_schedule_metadata is not None: + dst_plan.pool_schedule_metadata.copy_(src_plan.pool_schedule_metadata) + if dst_plan.effective_n_per_batch is not None: + dst_plan.effective_n_per_batch.copy_(src_plan.effective_n_per_batch) + + def _copy_replay_metadata_from_sibling( + self, + src_backend: DeepseekSparseAttnBackend, + bs: int, + precomputed: PrecomputedMetadata, + forward_mode: ForwardMode, + ) -> None: + """Replay fast path for step backends past the first in the multi-step + draft loop (engaged when SGLANG_EXPERIMENTAL_DSA_KPOOL_METADATA_FUSION + is on; internal behavior, no standalone flag). + + The base captured buffers are still copied from `precomputed` (one + fused kernel launch), but the DERIVED metadata that + `init_forward_metadata_replay_cuda_graph_from_precomputed` recomputes + per backend -- the deep_gemm.get_paged_mqa_logits_metadata schedule, + the top-k v2 plan, and everything + `_update_kpool_metadata_from_precomputed` derives (pooled seqlens div, + build_pooled_page_table_64, the DeepGEMM pool schedule and the kpool + write plan) -- is copied device-to-device from `src_backend`, which + just ran the full path on the SAME `precomputed`. Every derived + quantity is a pure function of `precomputed`, so the copy is bit-exact + with the recompute.""" + metadata = self.decode_cuda_graph_metadata.get(bs) + src_metadata = src_backend.decode_cuda_graph_metadata.get(bs) + if ( + # The derived-copy body below is CUDA-only; any other platform + # must take the full recompute, not a partial copy that would + # leave the DeepGEMM schedule / top-k plan / kpool metadata + # stale. + not is_cuda() + or _is_hip + or not forward_mode.is_decode_or_idle() + or metadata is None + or src_metadata is None + # `src_backend` must have run the full recompute path for this bs + # in this replay, so its derived buffers are fresh. + or src_backend.forward_metadata is not src_metadata + or not self._sibling_replay_metadata_compatible(metadata, src_metadata) + ): + self.init_forward_metadata_replay_cuda_graph_from_precomputed( + bs=bs, precomputed=precomputed, forward_mode=forward_mode + ) + return + + self.set_dsa_prefill_impl(forward_batch=None) + self._copy_base_replay_buffers(bs, metadata, precomputed, forward_mode) + if is_cuda(): - if forward_mode.is_decode_or_idle(): - seqlens_32_2d = _to_2d_context_lens(metadata.cache_seqlens_int32, bs) - else: - seqlens_32_2d = self._build_paged_mqa_schedule_2d_ctx_lens( - forward_mode, - metadata.cache_seqlens_int32, - metadata.dsa_seqlens_expanded, - bs, + if metadata.paged_mqa_schedule_metadata is not None: + metadata.paged_mqa_schedule_metadata.copy_( + src_metadata.paged_mqa_schedule_metadata ) - self._refresh_paged_mqa_schedule_metadata(metadata, seqlens_32_2d) - self._refresh_topk_v2_plan(metadata) + if metadata.topk_v2_plan is not None: + metadata.topk_v2_plan.copy_(src_metadata.topk_v2_plan) + # Decode: the 2D ctx lens are a (bs, 1) view of this backend's own + # cache_seqlens_int32 (just refreshed by the base copy above); keep + # the exact refresh the recompute path performs -- it is a single + # small view/copy, not part of the duplicated derived work. + seqlens_32_2d = _to_2d_context_lens(metadata.cache_seqlens_int32, bs) if metadata.paged_mqa_ctx_lens_2d is None: object.__setattr__(metadata, "paged_mqa_ctx_lens_2d", seqlens_32_2d) else: metadata.paged_mqa_ctx_lens_2d.copy_(seqlens_32_2d) + self._copy_kpool_metadata_from_sibling(metadata, src_metadata) + self.forward_metadata = metadata def forward_extend( @@ -1901,6 +3070,17 @@ def forward_extend( else self.dsa_prefill_impl ) + phase = ( + "decode" + if ( + forward_batch.forward_mode.is_target_verify() + or forward_batch.forward_mode.is_draft_extend_v2() + ) + else "prefill" + ) + dsa_impl = self._resolve_kpool_tail_backend(topk_indices, dsa_impl) + self._check_kpool_tail_backend(topk_indices, dsa_impl, phase) + if dsa_impl == "trtllm" and not self.use_mha: return self._forward_trtllm( q, @@ -1957,7 +3137,9 @@ def forward_extend( if q_rope is not None: q_nope = q.view(-1, layer.tp_q_head_num, layer.v_head_dim) q_rope = q_rope.view( - -1, layer.tp_q_head_num, layer.head_dim - layer.v_head_dim + q_nope.shape[0], + layer.tp_q_head_num, + layer.head_dim - layer.v_head_dim, ) else: q_all = q.contiguous().view(-1, layer.tp_q_head_num, layer.head_dim) @@ -2153,16 +3335,35 @@ def forward_extend( page_table_1=page_table_1, ) elif dsa_impl == "fa3": + fa3_page_table = page_table_1 + fa3_cache_seqlens = metadata.dsa_cache_seqlens_int32 + fa3_cu_seqlens_q = metadata.dsa_cu_seqlens_q + fa3_cu_seqlens_k = metadata.dsa_cu_seqlens_k + fa3_max_seqlen_q = metadata.dsa_max_seqlen_q + if ( + forward_batch.attn_cp_metadata is not None + and fa3_cache_seqlens.shape[0] > q_nope.shape[0] + ): + row_select = cp_zigzag_full_plan_rows(forward_batch, q_nope.device) + if row_select is not None: + fa3_cache_seqlens = fa3_cache_seqlens.index_select(0, row_select) + fa3_cu_seqlens_k = compute_cu_seqlens(fa3_cache_seqlens) + fa3_cu_seqlens_q = self.get_device_int32_arange( + fa3_cache_seqlens.shape[0] + 1 + ) + fa3_max_seqlen_q = 1 + if fa3_page_table.shape[0] > q_nope.shape[0]: + fa3_page_table = fa3_page_table.index_select(0, row_select) return self._forward_fa3( q_rope=q_rope, kv_cache=kv_cache, v_head_dim=layer.v_head_dim, q_nope=q_nope, - page_table=page_table_1, - cache_seqlens=metadata.dsa_cache_seqlens_int32, - cu_seqlens_q=metadata.dsa_cu_seqlens_q, - cu_seqlens_k=metadata.dsa_cu_seqlens_k, - max_seqlen_q=metadata.dsa_max_seqlen_q, + page_table=fa3_page_table, + cache_seqlens=fa3_cache_seqlens, + cu_seqlens_q=fa3_cu_seqlens_q, + cu_seqlens_k=fa3_cu_seqlens_k, + max_seqlen_q=fa3_max_seqlen_q, sm_scale=layer.scaling, logit_cap=layer.logit_cap, page_size=1, @@ -2202,7 +3403,10 @@ def forward_decode( metadata = self.forward_metadata assert causal, "DSA is causal only" - if self.dsa_decode_impl == "trtllm": + dsa_impl = self._resolve_kpool_tail_backend(topk_indices, self.dsa_decode_impl) + self._check_kpool_tail_backend(topk_indices, dsa_impl, "decode") + + if dsa_impl == "trtllm": return self._forward_trtllm( q, k, @@ -2239,7 +3443,9 @@ def forward_decode( if q_rope is not None: q_nope = q.view(-1, layer.tp_q_head_num, layer.v_head_dim) q_rope = q_rope.view( - -1, layer.tp_q_head_num, layer.head_dim - layer.v_head_dim + q_nope.shape[0], + layer.tp_q_head_num, + layer.head_dim - layer.v_head_dim, ) # Caller passed split q_nope / q_rope; we'll need to concat below if # the chosen impl wants q_all. @@ -2272,7 +3478,7 @@ def forward_decode( page_size=1, ) - if self.dsa_decode_impl == "flashmla_sparse": + if dsa_impl == "flashmla_sparse": if q_rope is not None: q_all = concat_mla_absorb_q_general(q_nope, q_rope) return self._forward_flashmla_sparse( @@ -2283,7 +3489,7 @@ def forward_decode( v_head_dim=layer.v_head_dim, topk_length=metadata.dsa_cache_seqlens_int32, ) - elif self.dsa_decode_impl == "flashinfer_sparse_mla": + elif dsa_impl == "flashinfer_sparse_mla": if q_all is None: q_all = concat_mla_absorb_q_general(q_nope, q_rope) return self._forward_flashinfer_sparse_mla( @@ -2294,7 +3500,7 @@ def forward_decode( sm_scale=layer.scaling, skip_softmax_threshold_scale_factor=envs.SGLANG_SKIP_SOFTMAX_DECODE_THRESHOLD_SCALE_FACTOR.get(), ) - elif self.dsa_decode_impl == "flashmla_kv": + elif dsa_impl == "flashmla_kv": if q_rope is not None: q_all = concat_mla_absorb_q_general(q_nope, q_rope) return self._forward_flashmla_kv( @@ -2307,7 +3513,7 @@ def forward_decode( metadata=metadata, page_table_1=page_table_1, ) - elif self.dsa_decode_impl == "tilelang": + elif dsa_impl == "tilelang": # Cat-skip (HIP-only): when caller passes q_rope=None on HIP, q_all # has already been set to a zero-copy view of q in the else branch # above and we can reuse it directly. The `not _is_hip` clause keeps @@ -2321,7 +3527,7 @@ def forward_decode( sm_scale=layer.scaling, v_head_dim=layer.v_head_dim, ) - elif self.dsa_decode_impl == "fa3": + elif dsa_impl == "fa3": return self._forward_fa3( q_rope=q_rope, kv_cache=kv_cache, @@ -2336,7 +3542,7 @@ def forward_decode( logit_cap=layer.logit_cap, page_size=1, ) - elif self.dsa_decode_impl == "aiter": + elif dsa_impl == "aiter": if q_all is None or not _is_hip: q_all = torch.cat([q_nope, q_rope], dim=-1) return self._forward_aiter( @@ -2349,7 +3555,7 @@ def forward_decode( ) else: - assert False, f"Unsupported {self.dsa_decode_impl = }" + assert False, f"Unsupported {dsa_impl = }" def _forward_fa3( self, @@ -2369,13 +3575,21 @@ def _forward_fa3( k_rope_cache = kv_cache[:, :, v_head_dim:] c_kv_cache = kv_cache[:, :, :v_head_dim] qk_rope_dim = k_rope_cache.shape[-1] - k_rope_cache = k_rope_cache.view(-1, page_size, 1, qk_rope_dim) - c_kv_cache = c_kv_cache.view(-1, page_size, 1, v_head_dim) + num_blocks = kv_cache.shape[0] // page_size + only_qv = qk_rope_dim == 0 + if only_qv: + k_rope_cache = None + else: + k_rope_cache = k_rope_cache.view(num_blocks, page_size, 1, qk_rope_dim) + c_kv_cache = c_kv_cache.view(num_blocks, page_size, 1, v_head_dim) + if self.dsa_index_kpool > 1: + page_table = page_table.clamp(min=0) o = flash_attn_with_kvcache( - q=q_rope, + q=None if only_qv else q_rope, k_cache=k_rope_cache, v_cache=c_kv_cache, qv=q_nope, + only_qv=only_qv, page_table=page_table, cache_seqlens=cache_seqlens, cu_seqlens_q=cu_seqlens_q, @@ -2930,6 +4144,19 @@ def _forward_tilelang( ) -> torch.Tensor: from sglang.kernels.ops.attention.dsa.tilelang_kernel import tilelang_sparse_fwd + # KPool appends up to index_kpool - 1 live tail tokens to the fixed + # index_topk columns. TileLang processes indices in 64-column blocks, + # so mask-pad the tail-extended table to the next complete block. + padding = (-page_table_1.shape[-1]) % 64 + if padding: + page_table_1 = torch.cat( + ( + page_table_1, + page_table_1.new_full((*page_table_1.shape[:-1], padding), -1), + ), + dim=-1, + ) + return tilelang_sparse_fwd( q=q_all, kv=kv_cache, @@ -3129,39 +4356,50 @@ def _forward_trtllm( metadata = self.forward_metadata - merge_query = q_rope is not None + # The BF16 no-RoPE path passes a zero-width q_rope tensor. + merge_query = q_rope is not None and self.qk_rope_head_dim > 0 if self.kv_cache_dtype == torch.float8_e4m3fn: # For FP8 path, we quantize the query and rope parts and merge them into a single tensor # Note: rope application in deepseek_v2.py:forward_absorb_prepare is skipped for FP8 decode path of this trtllm_mla backend assert q_rope is not None, "For FP8 path q_rope should not be None." assert k_rope is not None, "For FP8 path k_rope should not be None." - assert ( - cos_sin_cache is not None - ), "For FP8 path cos_sin_cache should not be None." - - rope_positions = forward_batch.positions - if dsa_use_prefill_cp(forward_batch): - if is_cp_v2_active(forward_batch): - rope_positions = get_cp_strategy().shard_position_ids( - rope_positions, forward_batch - ) - else: - rope_positions = cp_split_and_rebuild_position( - forward_batch, rope_positions - ) + if cos_sin_cache is None: + q, k, k_rope = mla_quantize_for_fp8_no_rope( + q, + q_rope, + k.squeeze(1), + k_rope.squeeze(1), + self.kv_lora_rank, + self.qk_rope_head_dim, + ) + else: + rope_positions = forward_batch.positions + if dsa_use_prefill_cp(forward_batch): + if is_cp_v2_active(forward_batch): + rope_positions = get_cp_strategy().shard_position_ids( + rope_positions, forward_batch + ) + else: + rope_positions = cp_split_and_rebuild_position( + forward_batch, rope_positions + ) - q, k, k_rope = mla_quantize_and_rope_for_fp8( - q, - q_rope, - k.squeeze(1), - k_rope.squeeze(1), - rope_positions, - cos_sin_cache, - is_neox, - self.kv_lora_rank, - self.qk_rope_head_dim, - ) - if save_kv_cache and dsa_use_prefill_cp(forward_batch): + q, k, k_rope = mla_quantize_and_rope_for_fp8( + q, + q_rope, + k.squeeze(1), + k_rope.squeeze(1), + rope_positions, + cos_sin_cache, + is_neox, + self.kv_lora_rank, + self.qk_rope_head_dim, + ) + if _should_all_gather_dsa_trtllm_fp8_kv( + save_kv_cache=save_kv_cache, + cos_sin_cache=cos_sin_cache, + dsa_prefill_cp=dsa_use_prefill_cp(forward_batch), + ): if is_cp_v2_active(forward_batch): k, k_rope = get_cp_strategy().all_gather_dsa_trtllm_fp8_kv( forward_batch, k, k_rope @@ -3219,6 +4457,12 @@ def _forward_trtllm( topk_indices=topk_indices, page_size=1, ) + page_table_1, sparse_mla_top_k = self._pad_trtllm_sparse_page_table( + page_table_1 + ) + sparse_mla_top_k_lens = None + if self.qk_rope_head_dim == 0: + sparse_mla_top_k_lens = prepare_trtllm_nope_sparse_metadata(page_table_1) q_scale = 1.0 k_scale = ( @@ -3264,11 +4508,16 @@ def _forward_trtllm( block_tables=block_tables, seq_lens=seq_lens, max_seq_len=metadata.max_seq_len_k, - sparse_mla_top_k=self.dsa_index_topk, + sparse_mla_top_k=sparse_mla_top_k, bmm1_scale=bmm1_scale, backend="trtllm-gen", skip_softmax_threshold_scale_factor=envs.SGLANG_SKIP_SOFTMAX_DECODE_THRESHOLD_SCALE_FACTOR.get(), + sparse_mla_top_k_lens=sparse_mla_top_k_lens, multi_ctas_kv_counter_buffer=self._multi_ctas_kv_counter_buffer, + return_lse=_should_return_dsa_trtllm_lse( + forward_mode=forward_batch.forward_mode, + dcp_enabled=get_parallel().dcp_enabled, + ), ) return out @@ -3302,13 +4551,11 @@ def set_dsa_prefill_impl(self, forward_batch: Optional[ForwardBatch] = None): """ Decide all attention prefill dispatch strategies for this batch. """ - from sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph.context import ( - is_in_breakable_cuda_graph, - ) - from sglang.srt.model_executor.runner_backend_utils.tc_piecewise_cuda_graph import ( - is_in_tc_piecewise_cuda_graph, - ) - from sglang.srt.utils import get_device_sm, is_blackwell + # Hoisted in __init__ (import cost is per-call otherwise). + is_in_breakable_cuda_graph = self._is_in_breakable_cuda_graph + is_in_tc_piecewise_cuda_graph = self._is_in_tc_piecewise_cuda_graph + get_device_sm = self._get_device_sm + is_blackwell = self._is_blackwell # Decide MHA vs MLA if is_in_tc_piecewise_cuda_graph() or is_in_breakable_cuda_graph(): @@ -3455,6 +4702,19 @@ def init_forward_metadata(self, forward_batch: ForwardBatch): for i in range(self.speculative_num_steps - 1): self.attn_backends[i].init_forward_metadata(forward_batch) + def _multistep_dedup_enabled(self) -> bool: + """Whether later step backends may sibling-copy derived replay + metadata from step 0 instead of recomputing it. + + Internal behavior of the fused metadata path (no standalone flag): + follows the step backends' effective fusion enable, which already + folds in the geometry and platform gates -- on unsupported backends + every step recomputes independently, the pre-fusion contract. + """ + return getattr( + self.attn_backends[0], "experimental_kpool_metadata_fusion", False + ) + def init_cuda_graph_state(self, max_bs: int, max_num_tokens: int): for i in range(self.speculative_num_steps - 1): self.attn_backends[i].init_cuda_graph_state(max_bs, max_num_tokens) @@ -3588,6 +4848,16 @@ def init_forward_metadata_out_graph( precomputed.seqlens_expanded_size, ) + for backend, metadata in zip( + self.attn_backends[:3], + (metadata0, metadata1, metadata2), + strict=True, + ): + backend._update_kpool_metadata_from_precomputed( + metadata, precomputed, ForwardMode.DECODE + ) + backend.forward_metadata = metadata + # Copy remaining backends one by one (if > 3 backends) for i in range(3, self.speculative_num_steps - 1): self.attn_backends[ @@ -3616,15 +4886,36 @@ def init_forward_metadata_out_graph( forward_mode=ForwardMode.DECODE, ) else: - # Less than 3 backends: copy to each backend individually - for i in range(self.speculative_num_steps - 1): - self.attn_backends[ - i - ].init_forward_metadata_replay_cuda_graph_from_precomputed( - bs=bs, - precomputed=precomputed, - forward_mode=ForwardMode.DECODE, - ) + # Less than 3 backends: copy to each backend individually. + # Backend 0 always runs the full path (base copy + derived + # recompute). When the fused metadata path is enabled, later step + # backends D2D-copy the derived metadata from backend 0 instead of + # recomputing it -- the inputs (`precomputed`) are identical across + # the step backends, so the derived quantities are too. + dedup = self._multistep_dedup_enabled() + self.attn_backends[ + 0 + ].init_forward_metadata_replay_cuda_graph_from_precomputed( + bs=bs, + precomputed=precomputed, + forward_mode=ForwardMode.DECODE, + ) + for i in range(1, self.speculative_num_steps - 1): + if dedup: + self.attn_backends[i]._copy_replay_metadata_from_sibling( + src_backend=self.attn_backends[0], + bs=bs, + precomputed=precomputed, + forward_mode=ForwardMode.DECODE, + ) + else: + self.attn_backends[ + i + ].init_forward_metadata_replay_cuda_graph_from_precomputed( + bs=bs, + precomputed=precomputed, + forward_mode=ForwardMode.DECODE, + ) def init_forward_metadata_in_graph(self, forward_batch: ForwardBatch) -> None: for i in range(self.speculative_num_steps - 1): diff --git a/python/sglang/srt/layers/attention/flashattention_backend.py b/python/sglang/srt/layers/attention/flashattention_backend.py index 48bd005225ed0..00fc8720843bc 100644 --- a/python/sglang/srt/layers/attention/flashattention_backend.py +++ b/python/sglang/srt/layers/attention/flashattention_backend.py @@ -24,6 +24,7 @@ from sglang.srt.layers.cp.utils import is_cp_v2_active from sglang.srt.layers.radix_attention import AttentionType from sglang.srt.layers.utils.cp_utils import ( + cp_all_gather_rerange_kv_cache, cp_allgather_and_save_kv_cache, cp_attn_forward_extend, ) @@ -1251,7 +1252,9 @@ def forward_extend( if score_mod is not None and self.fa_impl_ver != 4: raise RuntimeError("score_mod is only supported by the FA4 backend.") is_cp_mode = ( - forward_batch.forward_mode.is_context_parallel_extend() + forward_batch.forward_mode.is_context_parallel_extend( + include_draft_extend_v2=True + ) and forward_batch.attn_cp_metadata is not None and self.attn_cp_size > 1 ) @@ -1444,7 +1447,9 @@ def forward_extend( window_size = (-1, -1) if ( - forward_batch.forward_mode.is_context_parallel_extend() + forward_batch.forward_mode.is_context_parallel_extend( + include_draft_extend_v2=True + ) and forward_batch.attn_cp_metadata is not None and self.attn_cp_size > 1 ): @@ -1458,7 +1463,7 @@ def _fa_cp_attn( v_cache=value_cache, page_table=page_table, cache_seqlens=cache_seqlens_cp, - cu_seqlens_q=cu_seqlens_q_cp, + cu_seqlens_q=cu_seqlens_q_cp.to(torch.int32), cu_seqlens_k_new=cu_seqlens_k if not use_local_attn else None, max_seqlen_q=max_seqlen_q_cp, softmax_scale=layer.scaling, @@ -1599,6 +1604,77 @@ def _fa_cp_attn( else: o = result else: + if ( + is_cp_mode + and self.fa_impl_ver == 4 + and not any(forward_batch.extend_prefix_lens_cpu or []) + ): + # FA4 has no absorbed MLA KV-cache kernel. In the MHA fallback, + # gather the rank-local projected K/V into global token order, + # then run each zigzag Q half against its causal K/V prefix. + k_full = cp_all_gather_rerange_kv_cache( + k.contiguous(), + self.attn_cp_size, + forward_batch, + torch.cuda.current_stream(), + ) + v_full = cp_all_gather_rerange_kv_cache( + v.contiguous(), + self.attn_cp_size, + forward_batch, + torch.cuda.current_stream(), + ) + cp_meta = forward_batch.attn_cp_metadata + full_k_lens = cp_meta.kv_len_next_tensor.to(torch.int32) + full_k_lens_cpu = full_k_lens.cpu().tolist() + + def _fa4_mla_mha_cp_attn( + q_chunk, + cu_seqlens_q_cp, + cache_seqlens_cp, + max_seqlen_q_cp, + ): + cache_seqlens_cp = cache_seqlens_cp.to(torch.int32) + cache_seqlens_cpu = cache_seqlens_cp.cpu().tolist() + k_parts = [] + v_parts = [] + offset = 0 + for full_len, cache_len in zip(full_k_lens_cpu, cache_seqlens_cpu): + k_parts.append(k_full[offset : offset + cache_len]) + v_parts.append(v_full[offset : offset + cache_len]) + offset += full_len + k_chunk = torch.cat(k_parts, dim=0) + v_chunk = torch.cat(v_parts, dim=0) + cu_seqlens_k_cp = torch.nn.functional.pad( + torch.cumsum(cache_seqlens_cp, dim=0, dtype=torch.int32), + (1, 0), + ) + return flash_attn_varlen_func( + q=q_chunk.view(-1, layer.tp_q_head_num, layer.head_dim), + k=k_chunk.view(-1, layer.tp_k_head_num, layer.head_dim).to( + q.dtype + ), + v=v_chunk.view(-1, layer.tp_k_head_num, layer.v_head_dim).to( + q.dtype + ), + cu_seqlens_q=cu_seqlens_q_cp.to(torch.int32), + cu_seqlens_k=cu_seqlens_k_cp, + max_seqlen_q=max_seqlen_q_cp, + max_seqlen_k=int(cache_seqlens_cp.max().item()), + softmax_scale=layer.scaling, + causal=True, + return_softmax_lse=False, + ver=self.fa_impl_ver, + **kwargs, + ) + + return cp_attn_forward_extend( + forward_batch, + q.contiguous(), + self.device, + _fa4_mla_mha_cp_attn, + ) + if ( forward_batch.attn_attend_prefix_cache is not None and not forward_batch.forward_mode.is_target_verify() @@ -1674,20 +1750,24 @@ def _fa_cp_attn( ) k_rope = kv_cache[:, :, layer.v_head_dim :] c_kv = kv_cache[:, :, : layer.v_head_dim] - k_rope_cache = k_rope.view( - -1, - self.page_size, - layer.tp_k_head_num, - layer.head_dim - layer.v_head_dim, - ) + if k_rope.numel() == 0: + k_rope_cache = None + else: + k_rope_cache = k_rope.view( + -1, + self.page_size, + layer.tp_k_head_num, + layer.head_dim - layer.v_head_dim, + ) c_kv_cache = c_kv.view( -1, self.page_size, layer.tp_v_head_num, layer.v_head_dim ) if q_rope is not None: q_nope = q.view(-1, layer.tp_q_head_num, layer.v_head_dim) - q_rope = q_rope.view( - -1, layer.tp_q_head_num, layer.head_dim - layer.v_head_dim - ) + if q_rope.numel() > 0: + q_rope = q_rope.view( + -1, layer.tp_q_head_num, layer.head_dim - layer.v_head_dim + ) else: q_all = q.contiguous().view(-1, layer.tp_q_head_num, layer.head_dim) q_nope = q_all[:, :, : layer.v_head_dim] @@ -1714,6 +1794,8 @@ def _mla_cp_attn( ): q_nope_chunk = q_chunk[..., : layer.v_head_dim] q_rope_chunk = q_chunk[..., layer.v_head_dim :] + if q_rope_chunk.numel() == 0: + q_rope_chunk = None return flash_attn_with_kvcache( q=q_rope_chunk, qv=q_nope_chunk, @@ -1733,6 +1815,7 @@ def _mla_cp_attn( v_descale=fa_v_descale, num_splits=self.num_splits, ver=self.fa_impl_ver, + only_qv=q_rope_chunk is None, ) if is_cp_v2_active(forward_batch): @@ -1750,6 +1833,8 @@ def _mla_cp_attn( forward_batch, q_fused, self.device, _mla_cp_attn ) else: + if q_rope is not None and q_rope.numel() == 0: + q_rope = None result = flash_attn_with_kvcache( q=q_rope, k_cache=k_rope_cache, @@ -1768,6 +1853,7 @@ def _mla_cp_attn( return_softmax_lse=use_cascade_attn, num_splits=self.num_splits, ver=self.fa_impl_ver, + only_qv=q_rope is None, ) if use_cascade_attn: o, softmax_lse, *rest = result @@ -1791,6 +1877,7 @@ def _mla_cp_attn( return_softmax_lse=True, num_splits=self.num_splits, ver=self.fa_impl_ver, + only_qv=q_rope is None, ) ) o, _ = merge_state_v2_wrapper( @@ -2076,25 +2163,31 @@ def forward_decode( kv_cache = self.token_to_kv_pool.get_key_buffer(layer.layer_id).to(q.dtype) k_rope = kv_cache[:, :, layer.v_head_dim :] c_kv = kv_cache[:, :, : layer.v_head_dim] - k_rope_cache = k_rope.view( - -1, - self.page_size, - layer.tp_k_head_num, - layer.head_dim - layer.v_head_dim, - ) + if k_rope.numel() == 0: + k_rope_cache = None + else: + k_rope_cache = k_rope.view( + -1, + self.page_size, + layer.tp_k_head_num, + layer.head_dim - layer.v_head_dim, + ) c_kv_cache = c_kv.view( -1, self.page_size, layer.tp_v_head_num, layer.v_head_dim ) if q_rope is not None: q_nope = q.view(-1, layer.tp_q_head_num, layer.v_head_dim) - q_rope = q_rope.view( - -1, layer.tp_q_head_num, layer.head_dim - layer.v_head_dim - ) + if q_rope.numel() > 0: + q_rope = q_rope.view( + -1, layer.tp_q_head_num, layer.head_dim - layer.v_head_dim + ) else: q_all = q.contiguous().view(-1, layer.tp_q_head_num, layer.head_dim) q_nope = q_all[:, :, : layer.v_head_dim] q_rope = q_all[:, :, layer.v_head_dim :] + if q_rope is not None and q_rope.numel() == 0: + q_rope = None max_seqlen_q = metadata.max_seq_len_q result = flash_attn_with_kvcache( @@ -2115,6 +2208,7 @@ def forward_decode( return_softmax_lse=use_cascade_attn, # softmax_lse is needed for merge states num_splits=self.num_splits, ver=self.fa_impl_ver, + only_qv=q_rope is None, ) if use_cascade_attn: o, softmax_lse, *rest = result @@ -2137,6 +2231,7 @@ def forward_decode( return_softmax_lse=True, num_splits=self.num_splits, ver=self.fa_impl_ver, + only_qv=q_rope is None, ) o, _ = merge_state_v2( o, diff --git a/python/sglang/srt/layers/attention/flashinfer_mla_backend.py b/python/sglang/srt/layers/attention/flashinfer_mla_backend.py index ee563059adfa1..7a2934c8974fa 100644 --- a/python/sglang/srt/layers/attention/flashinfer_mla_backend.py +++ b/python/sglang/srt/layers/attention/flashinfer_mla_backend.py @@ -18,10 +18,11 @@ from dataclasses import dataclass from functools import partial -from typing import TYPE_CHECKING, Callable, Optional, Union +from typing import TYPE_CHECKING, Callable, List, Optional, Union import torch +from sglang.kernels.ops.attention.dsa.quant_k_cache import gather_dsa_kv_scales from sglang.kernels.ops.attention.utils import assert_buffer_fits from sglang.srt.environ import envs from sglang.srt.layers.attention.base_attn_backend import AttentionBackend @@ -50,6 +51,7 @@ ) from sglang.srt.utils import ( is_flashinfer_available, + is_sm90_supported, is_sm100_supported, next_power_of_2, ) @@ -75,6 +77,64 @@ ) +_MLA_BF16_DEQUANT_SCRATCH = {} + + +def _referenced_kv_to_bf16(k_fp8, kv_indices): + """Dequantize only the KV rows referenced by ``kv_indices`` (this batch's tokens) + into a persistent bf16 buffer mirroring the fp8 pool layout, so the paged wrapper + reads it with the same (unmodified) ``kv_indices``. Avoids converting the whole + pool every layer (the decode-latency bottleneck); since fa2 has no fp8 tensor + cores, feeding bf16 to the proven bf16 MLA kernel also keeps EAGLE draft acceptance + intact (the native in-kernel fp8 repack subtly degrades draft proposals). + + Keyed by shape (one buffer reused across layers, overwritten before each read) and + allocated outside inference mode so the in-place scatter is legal under cuda graph. + """ + key = (k_fp8.device, tuple(k_fp8.shape)) + scratch = _MLA_BF16_DEQUANT_SCRATCH.get(key) + if scratch is None: + with torch.inference_mode(False): + scratch = torch.empty( + k_fp8.shape, dtype=torch.bfloat16, device=k_fp8.device + ) + _MLA_BF16_DEQUANT_SCRATCH[key] = scratch + idx = kv_indices.long() + scratch[idx] = k_fp8[idx].to(torch.bfloat16) + return scratch + + +def _verify_plan_indptr_cpu(bs, draft_token_num, seq_lens_cpu): + """Build target-verify plan indptr on the host so the flashinfer plan skips its + blocking ``qo_indptr/kv_indptr/kv_len_arr.to("cpu")`` device sync (the decode + per-token bottleneck). Verify's layout is structural — ``q_len == draft_token_num`` + and ``kv_len == seq_len + draft_token_num`` — so these match + ``generate_attn_arg_prefill`` exactly while the GPU ``kv_indices`` stay unchanged. + """ + n = draft_token_num + qo_indptr = torch.arange(0, (bs + 1) * n, step=n, dtype=torch.int32) + kv_len_arr = seq_lens_cpu[:bs].to(torch.int32) + n + kv_indptr = torch.zeros(bs + 1, dtype=torch.int32) + kv_indptr[1:] = torch.cumsum(kv_len_arr, dim=0) + return qo_indptr, kv_indptr, kv_len_arr + + +def _extend_plan_indptr_cpu(bs, seq_lens_cpu, extend_seq_lens_cpu): + """Host-side plan indptr for non-spec paged extend / draft-extend, skipping the + plan's blocking ``.to("cpu")`` sync. ``kv_len == seq_len`` and + ``q_len == extend_len`` match the GPU cumsum in ``call_begin_forward`` exactly + while the GPU ``kv_indices`` stay unchanged. + """ + kv_len_arr = seq_lens_cpu[:bs].to(torch.int32) + kv_indptr = torch.zeros(bs + 1, dtype=torch.int32) + kv_indptr[1:] = torch.cumsum(kv_len_arr, dim=0) + qo_indptr = torch.zeros(bs + 1, dtype=torch.int32) + qo_indptr[1:] = torch.cumsum( + torch.tensor(extend_seq_lens_cpu[:bs], dtype=torch.int32), dim=0 + ) + return qo_indptr, kv_indptr, kv_len_arr + + @dataclass class DecodeMetadata: decode_wrapper: BatchMLAPagedAttentionWrapper @@ -245,6 +305,24 @@ def __init__( and not get_exec().kernel.flashinfer_mla_disable_ragged ) self.page_size = model_runner.page_size + self.qk_rope_head_dim = model_runner.model_config.qk_rope_head_dim + self.kv_lora_rank = model_runner.model_config.kv_lora_rank + self.dsa_scaled_kv_layout = self.token_to_kv_pool.dsa_kv_cache_store_fp8 + self.use_dsa_scaled_kv = ( + self.dsa_scaled_kv_layout and self.qk_rope_head_dim == 0 + ) + self._dsa_num_tiles = self.kv_lora_rank // 128 + self._dsa_ckv_scale_buf = None + if self.use_dsa_scaled_kv: + kv_pool = self.token_to_kv_pool + self._dsa_ckv_scale_buf = torch.empty( + (kv_pool.size + kv_pool.page_size, 1, self._dsa_num_tiles), + dtype=torch.float32, + device=model_runner.device, + ) + self.extend_scale_kv_indices = None + self.extend_scale_kv_indptr = None + self.extend_scale_kv_indptr_idx = 0 # Allocate buffers # different from flashinfer zero_init_global_workspace_buffer @@ -286,6 +364,10 @@ def __init__( self.workspace_buffer, "NHD", backend=self.fmha_backend ) + self.decode_bf16_kv_indices = None + self.extend_bf16_kv_indices = None + self.decode_fp8_native = is_sm90_supported() + if not self.skip_prefill: self.prefill_wrapper_paged = BatchMLAPagedAttentionWrapper( self.workspace_buffer, @@ -429,13 +511,19 @@ def init_forward_metadata(self, forward_batch: ForwardBatch): prefill_wrapper_paged=self.prefill_wrapper_verify, use_ragged=False, spec_info=forward_batch.spec_info, + is_verify=True, + seq_lens_cpu=forward_batch.seq_lens_cpu, ) self.forward_metadata = PrefillMetadata(self.prefill_wrapper_verify, False) + self.extend_scale_kv_indices = self.extend_bf16_kv_indices + self.extend_scale_kv_indptr = None + self.extend_scale_kv_indptr_idx = 0 else: prefix_lens = forward_batch.extend_prefix_lens extend_no_prefix = not any(forward_batch.extend_prefix_lens_cpu) use_ragged = ( not get_exec().kernel.flashinfer_mla_disable_ragged + and self.qk_rope_head_dim > 0 and extend_no_prefix # Captured prefill (tc_piecewise or breakable) must use paged # prefill: it stays compatible with prefix cache, and the ragged @@ -477,6 +565,8 @@ def init_forward_metadata(self, forward_batch: ForwardBatch): qo_indptr_cpu=qo_indptr_cpu, kv_indptr_cpu=kv_indptr_cpu, kv_len_arr_cpu=kv_len_arr_cpu, + seq_lens_cpu=forward_batch.seq_lens_cpu, + extend_seq_lens_cpu=forward_batch.extend_seq_lens_cpu, ) self.forward_metadata = PrefillMetadata( self.prefill_wrapper_paged, use_ragged @@ -586,7 +676,12 @@ def _apply_cuda_graph_metadata( qo_indptr_cpu=self.fast_plan_qo_indptr_cpu[: bs + 1], kv_indptr_cpu=self.fast_plan_kv_indptr_cpu[: bs + 1], kv_len_arr_cpu=self.fast_plan_kv_len_arr_cpu[:bs], + is_verify=True, + seq_lens_cpu=seq_lens_cpu, ) + self.extend_scale_kv_indices = self.cuda_graph_kv_indices + self.extend_scale_kv_indptr = self.cuda_graph_kv_indptr + self.extend_scale_kv_indptr_idx = bs else: raise ValueError(f"Invalid forward mode: {forward_mode=}") @@ -630,6 +725,8 @@ def forward_extend( self.token_to_kv_pool.set_mla_kv_buffer(layer, cache_loc, k, k_rope) else: self.token_to_kv_pool.set_kv_buffer(layer, cache_loc, k, v) + if self.qk_rope_head_dim == 0: + q_rope = None if q_rope is not None: q = q.view(-1, layer.tp_q_head_num, layer.v_head_dim) q_rope = q_rope.view( @@ -657,9 +754,9 @@ def forward_extend( forward_batch.attn_dcp_metadata is not None and forward_batch.attn_dcp_metadata.dcp_kv_buffer is not None ): - k_buf = forward_batch.attn_dcp_metadata.dcp_kv_buffer.to(q.dtype) + k_buf = forward_batch.attn_dcp_metadata.dcp_kv_buffer else: - k_buf = self.token_to_kv_pool.get_key_buffer(layer.layer_id).to(q.dtype) + k_buf = self.token_to_kv_pool.get_key_buffer(layer.layer_id) if q_rope is None: qall = q.view(-1, layer.tp_q_head_num, layer.head_dim) q, q_rope = ( @@ -667,16 +764,88 @@ def forward_extend( qall[:, :, layer.v_head_dim :], ) o = q.new_empty(q.shape) + fp8_run_kwargs = {} + if k_buf.dtype == torch.float8_e4m3fn: + if self.use_dsa_scaled_kv: + k_buf, fp8_run_kwargs = self._scaled_fp8_kv_kwargs( + k_buf, + ( + self.extend_scale_kv_indices + if forward_batch.forward_mode.is_target_verify() + else self.extend_bf16_kv_indices + ), + ( + self.extend_scale_kv_indptr + if forward_batch.forward_mode.is_target_verify() + else None + ), + self.extend_scale_kv_indptr_idx, + ) + elif ( + forward_batch.forward_mode.is_target_verify() + and self.decode_fp8_native + ): + kv_scale = ( + layer.k_scale_float if layer.k_scale_float is not None else 1.0 + ) + fp8_run_kwargs = {"ckv_scale": kv_scale, "kpe_scale": kv_scale} + else: + k_buf = self._dequant_referenced_kv_extend(k_buf) + elif k_buf.dtype != q.dtype: + k_buf = k_buf.to(q.dtype) o = prefill_wrapper_paged.run( q, q_rope, k_buf[:, :, : layer.v_head_dim], k_buf[:, :, layer.v_head_dim :], out=o, + **fp8_run_kwargs, ) return o.view(-1, layer.tp_q_head_num * layer.v_head_dim) + def _dequant_referenced_kv(self, k_fp8): + idx = self.decode_bf16_kv_indices + if idx is None: + return k_fp8.to(torch.bfloat16) + return _referenced_kv_to_bf16(k_fp8, idx) + + def _dequant_referenced_kv_extend(self, k_fp8): + idx = self.extend_bf16_kv_indices + if idx is None: + return k_fp8.to(torch.bfloat16) + return _referenced_kv_to_bf16(k_fp8, idx) + + def _scaled_fp8_kv_kwargs(self, k_fp8, kv_indices, kv_indptr=None, kv_indptr_idx=0): + """Split a scaled-fp8 KV row (``[ckv fp8 | per-128-group fp32 scales]``) into the + fp8 ckv view and the ``run()`` kwargs carrying the contiguous per-group scales. + Only the referenced rows are gathered into the persistent scale buffer, which + mirrors the pool layout so the kernel reads it with the same physical indices. + """ + assert self.use_dsa_scaled_kv + assert self._dsa_ckv_scale_buf is not None + scale_src = k_fp8[ + :, :, self.kv_lora_rank : self.kv_lora_rank + self._dsa_num_tiles * 4 + ].view(torch.float32) + if kv_indptr is not None: + gather_dsa_kv_scales( + scale_src, + self._dsa_ckv_scale_buf, + kv_indices, + kv_indptr, + kv_indptr_idx, + ) + elif kv_indices is None: + self._dsa_ckv_scale_buf.copy_(scale_src) + else: + idx = kv_indices.long() + self._dsa_ckv_scale_buf[idx] = scale_src[idx] + return k_fp8[:, :, : self.kv_lora_rank], { + "ckv_scale": 1.0, + "kpe_scale": 1.0, + "ckv_scale_arr": self._dsa_ckv_scale_buf, + } + def forward_decode( self, q: torch.Tensor, @@ -711,6 +880,8 @@ def forward_decode( ) # Reshape inputs + if self.qk_rope_head_dim == 0: + q_rope = None if q_rope is not None: q_nope = q.view(-1, layer.tp_q_head_num, layer.v_head_dim) q_rope = q_rope.view( @@ -721,7 +892,22 @@ def forward_decode( q_nope = reshaped_q[:, :, : layer.v_head_dim] q_rope = reshaped_q[:, :, layer.v_head_dim :] - k_buffer = self.token_to_kv_pool.get_key_buffer(layer.layer_id).to(q.dtype) + k_buffer = self.token_to_kv_pool.get_key_buffer(layer.layer_id) + fp8_run_kwargs = {} + if k_buffer.dtype == torch.float8_e4m3fn: + if self.use_dsa_scaled_kv: + k_buffer, fp8_run_kwargs = self._scaled_fp8_kv_kwargs( + k_buffer, self.decode_bf16_kv_indices + ) + elif self.decode_fp8_native: + kv_scale = ( + layer.k_scale_float if layer.k_scale_float is not None else 1.0 + ) + fp8_run_kwargs = {"ckv_scale": kv_scale, "kpe_scale": kv_scale} + else: + k_buffer = self._dequant_referenced_kv(k_buffer) + elif k_buffer.dtype != q.dtype: + k_buffer = k_buffer.to(q.dtype) o = q_nope.new_empty(q_nope.shape) # for decode and dcp_world_size > 1, lse should be returned to compute final attn_out @@ -736,6 +922,7 @@ def forward_decode( return_lse=( forward_batch.forward_mode.is_decode() and get_parallel().dcp_enabled ), + **fp8_run_kwargs, ) if isinstance(o, tuple): out, lse = o @@ -757,6 +944,11 @@ def __init__(self, model_runner: ModelRunner, attn_backend: AttentionBackend): self.qk_rope_head_dim = model_runner.model_config.qk_rope_head_dim self.scaling = model_runner.model_config.scaling self.data_type = model_runner.dtype + self.kv_data_type = ( + model_runner.kv_cache_dtype + if model_runner.kv_cache_dtype == torch.float8_e4m3fn + else model_runner.dtype + ) self.attn_backend = attn_backend # Buffers and wrappers @@ -852,6 +1044,11 @@ def call_begin_forward( else: kv_indptr, kv_indices = spec_info.kv_indptr, spec_info.kv_indices + self.attn_backend.decode_bf16_kv_indices = kv_indices + plan_kv_data_type = ( + self.kv_data_type if self.attn_backend.decode_fp8_native else self.data_type + ) + if not init_metadata_replay: wrapper.plan( q_indptr, @@ -865,7 +1062,7 @@ def call_begin_forward( False, sm_scale, self.data_type, - self.data_type, + plan_kv_data_type, ) else: wrapper.plan( @@ -880,7 +1077,7 @@ def call_begin_forward( False, sm_scale, self.data_type, - self.data_type, + plan_kv_data_type, ) @@ -897,6 +1094,11 @@ def __init__(self, model_runner: ModelRunner, attn_backend: AttentionBackend): self.scaling = model_runner.model_config.scaling self.data_type = model_runner.dtype self.q_data_type = model_runner.dtype + self.kv_data_type = ( + model_runner.kv_cache_dtype + if model_runner.kv_cache_dtype == torch.float8_e4m3fn + else model_runner.dtype + ) self.attn_backend = attn_backend # Buffers and wrappers @@ -924,6 +1126,9 @@ def update( qo_indptr_cpu: Optional[torch.Tensor] = None, kv_indptr_cpu: Optional[torch.Tensor] = None, kv_len_arr_cpu: Optional[torch.Tensor] = None, + is_verify: bool = False, + seq_lens_cpu: Optional[torch.Tensor] = None, + extend_seq_lens_cpu: Optional[List[int]] = None, ): if use_ragged: paged_kernel_lens = prefix_lens @@ -948,6 +1153,9 @@ def update( qo_indptr_cpu=qo_indptr_cpu, kv_indptr_cpu=kv_indptr_cpu, kv_len_arr_cpu=kv_len_arr_cpu, + is_verify=is_verify, + seq_lens_cpu=seq_lens_cpu, + extend_seq_lens_cpu=extend_seq_lens_cpu, ) def call_begin_forward( @@ -967,6 +1175,9 @@ def call_begin_forward( qo_indptr_cpu: Optional[torch.Tensor] = None, kv_indptr_cpu: Optional[torch.Tensor] = None, kv_len_arr_cpu: Optional[torch.Tensor] = None, + is_verify: bool = False, + seq_lens_cpu: Optional[torch.Tensor] = None, + extend_seq_lens_cpu: Optional[List[int]] = None, ): bs = len(seq_lens) sm_scale = self.scaling @@ -1010,6 +1221,7 @@ def call_begin_forward( ) ) + self.attn_backend.extend_bf16_kv_indices = kv_indices if use_ragged: # ragged prefill wrapper_ragged.begin_forward( @@ -1033,14 +1245,38 @@ def call_begin_forward( # built from full seq_lens and don't match, so fall back to GPU. qo_indptr_cpu = kv_indptr_cpu = kv_len_arr_cpu = None - plan_qo_indptr = qo_indptr if qo_indptr_cpu is None else qo_indptr_cpu - plan_kv_indptr = kv_indptr if kv_indptr_cpu is None else kv_indptr_cpu - plan_kv_len_arr = ( - kv_indptr[1:] - kv_indptr[:-1] - if kv_len_arr_cpu is None - else kv_len_arr_cpu + if qo_indptr_cpu is not None: + plan_qo_indptr = qo_indptr_cpu + plan_kv_indptr = kv_indptr_cpu + plan_kv_len_arr = kv_len_arr_cpu + elif ( + is_verify + and seq_lens_cpu is not None + and attn_dcp_metadata is None + and spec_info is not None + ): + plan_qo_indptr, plan_kv_indptr, plan_kv_len_arr = ( + _verify_plan_indptr_cpu(bs, spec_info.draft_token_num, seq_lens_cpu) + ) + elif ( + spec_info is None + and seq_lens_cpu is not None + and extend_seq_lens_cpu is not None + and attn_dcp_metadata is None + ): + plan_qo_indptr, plan_kv_indptr, plan_kv_len_arr = ( + _extend_plan_indptr_cpu(bs, seq_lens_cpu, extend_seq_lens_cpu) + ) + else: + plan_qo_indptr = qo_indptr + plan_kv_indptr = kv_indptr + plan_kv_len_arr = kv_indptr[1:] - kv_indptr[:-1] + plan_kv_data_type = ( + self.kv_data_type + if (is_verify and self.attn_backend.decode_fp8_native) + or self.attn_backend.use_dsa_scaled_kv + else self.data_type ) - wrapper_paged.plan( plan_qo_indptr, plan_kv_indptr, @@ -1053,7 +1289,7 @@ def call_begin_forward( True, sm_scale, self.q_data_type, - self.data_type, + plan_kv_data_type, ) diff --git a/python/sglang/srt/layers/attention/hybrid_linear_attn_backend.py b/python/sglang/srt/layers/attention/hybrid_linear_attn_backend.py index f842df0373519..5b7d551207de3 100644 --- a/python/sglang/srt/layers/attention/hybrid_linear_attn_backend.py +++ b/python/sglang/srt/layers/attention/hybrid_linear_attn_backend.py @@ -44,6 +44,10 @@ class MambaAttnBackendBase(AttentionBackend): + # Recurrent backends must explicitly opt in after their graph metadata + # loader is proven independent of live conv/SSM state. + supports_overlap_plan_stream_graph_load: bool = False + def __init__(self, model_runner: ModelRunner): super().__init__() self.pad_slot_id = PAD_SLOT_ID @@ -79,6 +83,9 @@ def __init__(self, model_runner: ModelRunner): self.cached_cuda_graph_decode_query_start_loc: torch.Tensor = None self.cached_cuda_graph_verify_query_start_loc: torch.Tensor = None self.conv_states_shape: tuple[int, int] = None + # Constant (== 1) for mamba-like backends; hoisted so the replay path + # skips the per-cycle method dispatch. + self._graph_seq_len_fill_value = self.get_cuda_graph_seq_len_fill_value() def _translate_mamba_indices(self, mamba_indices: torch.Tensor) -> torch.Tensor: """Virtual->physical mamba slot-id translate (identity for the non-unified @@ -182,9 +189,14 @@ def _forward_metadata(self, forward_batch: ForwardBatch): new_vals[inv] = next_for_valid.to(write_pos_buf.dtype) write_pos_buf[uniq_slots] = new_vals elif forward_batch.forward_mode.is_extend(include_draft_extend_v2=True): - if forward_batch.forward_mode.is_draft_extend_v2(): - # DRAFT_EXTEND_V2 runs only full-attn layers in the draft model; - # skip mamba metadata. + has_extend_meta = ( + forward_batch.extend_start_loc is not None + and forward_batch.extend_seq_lens is not None + ) + if forward_batch.forward_mode.is_draft_extend_v2() and not has_extend_meta: + # HybridLinearAttnBackend.init_forward_metadata calls all sub-backends + # unconditionally, but DRAFT_EXTEND_V2 only runs full-attn layers in + # the draft model, so mamba metadata can be skipped. query_start_loc = None elif forward_batch.forward_mode.is_target_verify(): ragged_layout = forward_batch.spec_info.ragged_verify_layout @@ -565,8 +577,9 @@ def _replay_metadata( num_padding = 0 else: num_padding = torch.count_nonzero( - seq_lens_cpu == self.get_cuda_graph_seq_len_fill_value() + seq_lens_cpu == self._graph_seq_len_fill_value ) + num_padding = int(num_padding) if self._fused_state_indices_ok and self.replayssm_write_pos_list is None: # Single-launch fast path: mapping gather + padding sentinel + store # into the static buffer, plus zeroing padded req_pool_indices rows — @@ -662,6 +675,7 @@ def _replay_metadata( ) new_vals[inv] = next_for_valid.to(write_pos_buf.dtype) write_pos_buf[uniq_slots] = new_vals + is_target_verify = forward_mode.is_target_verify() if forward_mode.is_decode_or_idle(): if num_padding == 0: self.query_start_loc_list[bs - 1].copy_( @@ -700,8 +714,9 @@ def _replay_metadata( ) else: raise ValueError(f"Invalid forward mode: {forward_mode=}") + qsl_buf = self.query_start_loc_list[bs - 1] - if forward_mode.is_target_verify() and self.topk > 1: + if is_target_verify and self.topk > 1: if ( spec_info is not None and getattr(spec_info, "retrieve_next_token", None) is not None @@ -714,7 +729,7 @@ def _replay_metadata( spec_info.retrieve_next_sibling ) return ForwardMetadata( - query_start_loc=self.query_start_loc_list[bs - 1], + query_start_loc=qsl_buf, mamba_cache_indices=self.state_indices_list[bs - 1], mamba_track_indices=track_buf, retrieve_next_token=self.retrieve_next_token_list[bs - 1], @@ -725,7 +740,7 @@ def _replay_metadata( ) else: return ForwardMetadata( - query_start_loc=self.query_start_loc_list[bs - 1], + query_start_loc=qsl_buf, mamba_cache_indices=self.state_indices_list[bs - 1], mamba_track_indices=track_buf, replayssm_write_pos=replayssm_write_pos, @@ -953,6 +968,8 @@ def forward_extend(self, *args, **kwargs): class HybridLinearAttnBackend(AttentionBackend): """Manages a full and linear attention backend""" + supports_overlap_plan_stream_graph_load: bool = False + def __init__( self, full_attn_backend: AttentionBackend, @@ -973,6 +990,9 @@ def __init__( self.extend_dummy_seqs_capped_by_req_pool = getattr( full_attn_backend, "extend_dummy_seqs_capped_by_req_pool", False ) or getattr(linear_attn_backend, "extend_dummy_seqs_capped_by_req_pool", False) + self.supports_overlap_plan_stream_graph_load = bool( + linear_attn_backend.supports_overlap_plan_stream_graph_load + ) @property def data_type(self): @@ -988,6 +1008,17 @@ def supports_ragged_verify_graph(self) -> bool: and self.linear_attn_backend.supports_ragged_verify_graph ) + @property + def use_mha(self) -> bool: + return getattr(self.full_attn_backend, "use_mha", False) + + @property + def kv_cache_dtype(self): + # DSA/NSA fused-rope path (forward_mla._fuse_rope_for_trtllm_mla) reads + # this off get_attn_backend(), which returns this wrapper; delegate to + # the wrapped full-attn (DSA) backend that actually owns it. + return getattr(self.full_attn_backend, "kv_cache_dtype", None) + def _is_full_attn( self, layer: Optional[RadixAttention], layer_id: Optional[int] = None ) -> bool: @@ -1053,6 +1084,9 @@ def init_mha_chunk_metadata( if init is not None: init(forward_batch, disable_flashinfer_ragged) + def get_indexer_metadata(self, layer_id, forward_batch): + return self.full_attn_backend.get_indexer_metadata(layer_id, forward_batch) + def init_cuda_graph_state(self, max_bs: int, max_num_tokens: int): for attn_backend in self.attn_backend_list: attn_backend.init_cuda_graph_state(max_bs, max_num_tokens) diff --git a/python/sglang/srt/layers/attention/linear/kda_backend.py b/python/sglang/srt/layers/attention/linear/kda_backend.py index 406d1c591f3e4..528b188344a5f 100644 --- a/python/sglang/srt/layers/attention/linear/kda_backend.py +++ b/python/sglang/srt/layers/attention/linear/kda_backend.py @@ -143,7 +143,7 @@ def __init__( ) cutedsl_kernel = CuteDSLKDAKernel() - if getattr(cutedsl_kernel, "supports_prefill", False): + if cutedsl_kernel.supports_prefill: # SM100 chunk prefill pipeline. self.extend_kernel = cutedsl_kernel else: @@ -247,8 +247,16 @@ def decode( ssm_states: torch.Tensor, cache_indices: torch.Tensor, query_start_loc: torch.Tensor, + lower_bound: Optional[float] = None, **kwargs, ) -> torch.Tensor: + if lower_bound is not None and not isinstance( + self.decode_kernel, TritonKDAKernel + ): + raise NotImplementedError( + f"lower_bound (safe gate) is only supported by TritonKDAKernel; " + f"got {self.decode_kernel.__class__.__name__}." + ) return self.decode_kernel.decode( q, k, @@ -260,6 +268,7 @@ def decode( ssm_states=ssm_states, cache_indices=cache_indices, query_start_loc=query_start_loc, + lower_bound=lower_bound, **kwargs, ) @@ -279,13 +288,20 @@ def target_verify( intermediate_states_buffer: torch.Tensor, intermediate_state_indices: torch.Tensor, cache_steps: int, - retrieve_parent_token: torch.Tensor, + retrieve_parent_token: Optional[torch.Tensor], lower_bound: Optional[float] = None, **kwargs, ) -> torch.Tensor: """MTP / speculative-decode verify, routed to ``self.verify_kernel`` (FlashInfer decode -> recurrent_kda; Triton / CuTe DSL decode -> the Triton fused KDA verify).""" + if lower_bound is not None and not isinstance( + self.verify_kernel, TritonKDAKernel + ): + raise NotImplementedError( + "lower_bound (safe gate) target verify is only supported by " + f"TritonKDAKernel; got {self.verify_kernel.__class__.__name__}." + ) return self.verify_kernel.target_verify( A_log=A_log, dt_bias=dt_bias, @@ -362,10 +378,15 @@ class KDAAttnBackend(MambaAttnBackendBase): # to its dense layout, so ragged verify graphs are supported. supports_ragged_verify_graph: bool = True - # Read by decide_needs_cpu_seq_lens. Decode/verify metadata is GPU-only - # (graph replay already passes seq_lens_cpu=None), extend reads - # extend_seq_lens_cpu from schedule, mamba track indices rebuild from req - # objects, and the replayssm seq_lens_cpu force-flush is GDN-only. + # Target graph loading snapshots request-to-state indices and fixed replay + # metadata only. Candidate conv/SSM states stay isolated until acceptance + # commits them on the main forward stream, so metadata loading is safe on + # the MTP plan stream after the draft/tree handoff event. + supports_overlap_plan_stream_graph_load: bool = True + + # KDA graph replay receives padding explicitly and does not use the generic + # ReplaySSM host-seqlen force-flush path. Keep the speculative length relay + # on device instead of synchronizing a D2H mirror every MTP cycle. needs_cpu_seq_lens: bool = False def __init__(self, model_runner: ModelRunner): @@ -531,9 +552,12 @@ def forward_decode( conv_state_indices=cache_indices, ) - # The packed kernel assumes one token per request. Assert the dispatch - # invariant before taking the fused path. - if self.kernel_dispatcher.supports_packed_decode: + # The packed kernel assumes one token per request. It does not support + # the GLM-5 lower-bound gate variant, which stays on the unfused path. + if ( + self.kernel_dispatcher.supports_packed_decode + and getattr(layer, "lower_bound", None) is None + ): assert qkv.shape[0] == cache_indices.shape[0], ( "KDA packed decode requires one token per sequence (T=1): " f"got {qkv.shape[0]} tokens for {cache_indices.shape[0]} requests." @@ -615,6 +639,13 @@ def forward_extend( ) has_initial_state = forward_batch.extend_prefix_lens > 0 + physical_num_tokens = mixed_qkv.shape[0] + logical_num_tokens = int(query_start_loc[-1]) + if logical_num_tokens < physical_num_tokens: + mixed_qkv = mixed_qkv[:logical_num_tokens] + a = a[:, :logical_num_tokens] + b = b[:, :logical_num_tokens] + if self.forward_metadata.has_mamba_track_mask: # Snapshot the conv sliding window at the last track-aligned chunk # boundary into the ping-pong track slots (the prefix-cache restore @@ -625,55 +656,30 @@ def forward_extend( self.forward_metadata.conv_states_mask_indices ] = mixed_qkv[self.forward_metadata.track_conv_indices] - splits = [layer.q_dim, layer.k_dim, layer.v_dim] - q, k, v = mixed_qkv.transpose(0, 1).split(splits, dim=0) - q_conv_weight, k_conv_weight, v_conv_weight = layer.conv_weights.split( - splits, dim=0 - ) - q_conv_state, k_conv_state, v_conv_state = conv_states.split(splits, dim=-2) - if layer.bias is not None: - q_bias, k_bias, v_bias = layer.bias.split(splits, dim=0) - else: - q_bias, k_bias, v_bias = None, None, None - - q = causal_conv1d_fn( - q, - q_conv_weight, - q_bias, - activation="silu", - conv_states=q_conv_state, - has_initial_state=has_initial_state, - cache_indices=cache_indices, - query_start_loc=query_start_loc, - seq_lens_cpu=forward_batch.extend_seq_lens_cpu, - ).transpose(0, 1) - k = causal_conv1d_fn( - k, - k_conv_weight, - k_bias, - activation="silu", - conv_states=k_conv_state, - has_initial_state=has_initial_state, - cache_indices=cache_indices, - query_start_loc=query_start_loc, - seq_lens_cpu=forward_batch.extend_seq_lens_cpu, - ).transpose(0, 1) - v = causal_conv1d_fn( - v, - v_conv_weight, - v_bias, + # Depthwise conv is channel-independent, so one packed call over the + # full qkv width matches the decode path and saves two kernel launches. + qkv = causal_conv1d_fn( + mixed_qkv.transpose(0, 1), + layer.conv_weights, + layer.bias, activation="silu", - conv_states=v_conv_state, + conv_states=conv_states, has_initial_state=has_initial_state, cache_indices=cache_indices, query_start_loc=query_start_loc, seq_lens_cpu=forward_batch.extend_seq_lens_cpu, ).transpose(0, 1) + q, k, v = qkv.split([layer.q_dim, layer.k_dim, layer.v_dim], dim=-1) q = q.unflatten(-1, (-1, layer.head_q_dim)).unsqueeze(0) # n (h d) -> 1 n h d k = k.unflatten(-1, (-1, layer.head_k_dim)).unsqueeze(0) # n (h d) -> 1 n h d v = v.unflatten(-1, (-1, layer.head_v_dim)).unsqueeze(0) # n (h d) -> 1 n h d + gate_was_flat = a.ndim == 3 + if gate_was_flat: + # Kernel backends use the explicit [B, T, H, D] gate layout. + a = a.unflatten(-1, (-1, layer.head_k_dim)) + track_ssm = self.forward_metadata.has_mamba_track_mask core_attn_out = self.kernel_dispatcher.extend( q=q, @@ -687,6 +693,7 @@ def forward_extend( A_log=layer.A_log, dt_bias=layer.dt_bias, lower_bound=layer.lower_bound, + beta_is_raw=gate_was_flat, extend_seq_lens_cpu=forward_batch.extend_seq_lens_cpu, # draft_extend_v2 must stay rollback-able, so kernels that commit state # in place (e.g. FlashKDA) must not run for it. @@ -708,6 +715,13 @@ def forward_extend( forward_batch, h, ssm_states, self.forward_metadata ) + if logical_num_tokens < physical_num_tokens: + pad = core_attn_out.new_zeros( + (1, physical_num_tokens - logical_num_tokens) + + tuple(core_attn_out.shape[2:]) + ) + core_attn_out = torch.cat((core_attn_out, pad), dim=1) + return core_attn_out def _forward_target_verify( diff --git a/python/sglang/srt/layers/attention/linear/kernels/kda_cutedsl.py b/python/sglang/srt/layers/attention/linear/kernels/kda_cutedsl.py index e2323b6ae6828..bdd8a5d8435a6 100644 --- a/python/sglang/srt/layers/attention/linear/kernels/kda_cutedsl.py +++ b/python/sglang/srt/layers/attention/linear/kernels/kda_cutedsl.py @@ -136,6 +136,8 @@ def extend( num_tokens = q_n.shape[0] g_in = g[0][:num_tokens] # raw forget gate; activated inside chunk_kda_cutedsl beta_in = beta[0][:num_tokens].to(torch.float32) + if kwargs.get("beta_is_raw"): + beta_in = beta_in.sigmoid() cu_seqlens = query_start_loc.to(torch.int32) # Pool state I/O is fused into the h kernel's TMA load/store: pass the diff --git a/python/sglang/srt/layers/attention/linear/kernels/kda_flashkda.py b/python/sglang/srt/layers/attention/linear/kernels/kda_flashkda.py index 8dd3b273f6e83..3b90607fde457 100644 --- a/python/sglang/srt/layers/attention/linear/kernels/kda_flashkda.py +++ b/python/sglang/srt/layers/attention/linear/kernels/kda_flashkda.py @@ -39,6 +39,7 @@ def _triton_fallback( A_log=None, dt_bias=None, lower_bound=None, + beta_is_raw=False, return_intermediate_states=False, ): """Fall back to the Triton chunk_kda kernel (handles all preprocessing). @@ -64,6 +65,7 @@ def _triton_fallback( A_log=A_log, dt_bias=dt_bias, lower_bound=lower_bound, + beta_is_raw=beta_is_raw, output_intermediate_states=return_intermediate_states, ) @@ -114,6 +116,7 @@ def extend( lower_bound: Optional[float] = None, extend_seq_lens_cpu: Optional[list] = None, is_spec_decode: bool = False, + beta_is_raw: bool = False, return_intermediate_states: bool = False, **kwargs, ) -> torch.Tensor: @@ -136,6 +139,7 @@ def extend( A_log=A_log, dt_bias=dt_bias, lower_bound=lower_bound, + beta_is_raw=beta_is_raw, return_intermediate_states=return_intermediate_states, ) @@ -151,6 +155,7 @@ def extend( A_log=A_log, dt_bias=dt_bias, lower_bound=lower_bound, + beta_is_raw=beta_is_raw, ) @staticmethod @@ -203,6 +208,7 @@ def _flashkda_extend( A_log: Optional[torch.Tensor] = None, dt_bias: Optional[torch.Tensor] = None, lower_bound: Optional[float] = None, + beta_is_raw: bool = False, ) -> torch.Tensor: flash_kda = _load_flash_kda() @@ -220,12 +226,12 @@ def _flashkda_extend( v = v.contiguous() g = g.contiguous() - # KimiDeltaAttention.forward already applies sigmoid to beta on the - # prefill path, but flash_kda expects beta LOGITS (it sigmoids - # internally). Invert back so the kernel recovers the intended value: - # sigmoid(logit(p)) == p. (triton/cuLA consume the post-sigmoid beta.) - beta = torch.logit(beta.float().clamp_(1e-7, 1.0 - 1e-7)).to(torch.bfloat16) - beta = beta.contiguous() + # GLM-5 passes raw beta logits. Kimi Linear currently passes an already + # activated beta, which must be inverted because FlashKDA applies + # sigmoid internally. + if not beta_is_raw: + beta = torch.logit(beta.float().clamp_(1e-7, 1.0 - 1e-7)) + beta = beta.to(torch.bfloat16).contiguous() # flash_kda wants A_log [H] fp32 and dt_bias [H, K] fp32. The model # stores A_log as [1, 1, H, 1] and dt_bias as 1D [H*K], so reshape both. diff --git a/python/sglang/srt/layers/attention/linear/kernels/kda_triton.py b/python/sglang/srt/layers/attention/linear/kernels/kda_triton.py index 85774ec3620ed..6c6c3788fd2a7 100644 --- a/python/sglang/srt/layers/attention/linear/kernels/kda_triton.py +++ b/python/sglang/srt/layers/attention/linear/kernels/kda_triton.py @@ -169,7 +169,7 @@ def target_verify( intermediate_states_buffer: torch.Tensor, intermediate_state_indices: torch.Tensor, cache_steps: int, - retrieve_parent_token: torch.Tensor, + retrieve_parent_token: Optional[torch.Tensor], lower_bound: Optional[float] = None, # fused ReplaySSM ring-write (dense verify only; off elsewhere). cache_ring: bool = False, @@ -227,9 +227,17 @@ def extend( A_log: Optional[torch.Tensor] = None, dt_bias: Optional[torch.Tensor] = None, lower_bound: Optional[float] = None, + beta_is_raw: bool = False, return_intermediate_states: bool = False, **kwargs, ) -> torch.Tensor: + # CP/DP padding marks zero-length requests with -1. The Triton state + # kernel performs raw pointer arithmetic on these indices, so route + # padding to MambaPool's trailing sentinel slot instead of indexing + # before the state pool. + ssm_cache_indices = torch.where( + cache_indices >= 0, cache_indices, ssm_states.shape[0] - 1 + ).to(torch.int32) return chunk_kda( q=q, k=k, @@ -237,11 +245,12 @@ def extend( g=g, beta=beta, initial_state=ssm_states, - initial_state_indices=cache_indices, + initial_state_indices=ssm_cache_indices, use_qk_l2norm_in_kernel=True, cu_seqlens=query_start_loc, A_log=A_log, dt_bias=dt_bias, lower_bound=lower_bound, + beta_is_raw=beta_is_raw, output_intermediate_states=return_intermediate_states, ) diff --git a/python/sglang/srt/layers/attention/vision.py b/python/sglang/srt/layers/attention/vision.py index 5e3e8c6f3aee9..52ae7f3e6a183 100644 --- a/python/sglang/srt/layers/attention/vision.py +++ b/python/sglang/srt/layers/attention/vision.py @@ -495,8 +495,7 @@ def forward( seq_lens = kwargs.get("sequence_lengths") if seq_lens is None: seq_lens = cu_seqlens_gpu[1:] - cu_seqlens_gpu[:-1] - else: - seq_lens = seq_lens.to(device=q.device, dtype=torch.int32) + seq_lens = seq_lens.to(device=q.device, dtype=torch.int32) max_seqlen = resolve_precomputed_max_seqlen( cu_seqlens_gpu, kwargs.get("max_seqlen") ) diff --git a/python/sglang/srt/layers/communicator.py b/python/sglang/srt/layers/communicator.py index b69b1a08a0e0f..084d76d23bff6 100644 --- a/python/sglang/srt/layers/communicator.py +++ b/python/sglang/srt/layers/communicator.py @@ -224,12 +224,17 @@ def __init__( hidden_states: torch.Tensor, forward_batch: ForwardBatch, qkv_latent_func: Callable, + *, + is_pre_gathered: bool = False, ): self.hidden_states_local = hidden_states self.forward_batch = forward_batch self.qkv_latent_func = qkv_latent_func self.hidden_states_ = None self.qkv_latent_ = None + # When True, hidden_states_local is already attn_tp-gathered upstream + # (e.g. by MHC's prepare_attn for DSA). fetch_* must NOT gather again. + self.is_pre_gathered = is_pre_gathered def tp_all_gather_hidden_states(self, hidden_states, forward_batch): total_tokens = forward_batch.input_ids.shape[0] @@ -244,7 +249,7 @@ def fetch_qkv_latent(self): self.qkv_latent_ = self.qkv_latent_func( self.hidden_states_local, self.forward_batch ) - if get_attn_tp_context().input_scattered: + if get_attn_tp_context().input_scattered and not self.is_pre_gathered: self.qkv_latent_ = self.tp_all_gather_hidden_states( self.qkv_latent_, self.forward_batch ) @@ -254,7 +259,7 @@ def fetch_hidden_states(self): if self.hidden_states_ is not None: return self.hidden_states_ self.hidden_states_ = self.hidden_states_local - if get_attn_tp_context().input_scattered: + if get_attn_tp_context().input_scattered and not self.is_pre_gathered: self.hidden_states_ = self.tp_all_gather_hidden_states( self.hidden_states_, self.forward_batch ) @@ -266,13 +271,16 @@ def __init__(self): self.allow_input_scattered = False self.is_dsa = False - def init_context(self, q_lora_rank, is_dsa): + def init_context(self, q_lora_rank, is_dsa, is_mhc=False): + # DSA + input_scattered requires hidden_states to be attn_tp-gathered + # before the attention call. Currently only MHC's prepare_attn does this + # pre-gather; hence is_mhc gates DSA's eligibility for input_scattered. self.is_dsa = is_dsa self.allow_input_scattered = ( get_parallel().config.enable_attn_tp_input_scattered and (_is_cuda or _is_npu) and q_lora_rank is not None - and not is_dsa + and (is_mhc or not is_dsa) and get_parallel().tp_size > 1 and not is_dp_attention_enabled() and get_moe_a2a_backend().is_none() @@ -304,6 +312,11 @@ def input_scattered(self): def set_attn_inputs(self, attn_inputs: AttentionInputs): get_forward().set("attn_inputs", attn_inputs) + def set_hidden_states_local(self, hidden_states: torch.Tensor) -> None: + attn_inputs = get_forward().attn_inputs + if attn_inputs is not None: + attn_inputs.hidden_states_local = hidden_states + def fetch_qkv_latent(self): attn_inputs = get_forward().attn_inputs assert attn_inputs is not None @@ -445,6 +458,27 @@ def enable_dwdp(): return get_parallel().config.dwdp_size > 1 +def tp_reduce_scatter( + hidden_states: torch.Tensor, + residual: Optional[torch.Tensor], + context: "CommunicateContext", +) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: + """Reduce-scatter ``hidden_states`` over the full TP group and slice + ``residual`` to this rank. Module-level so variant communicators (e.g. MHC) + can reuse it without holding a ``LayerCommunicator`` instance.""" + if hidden_states.shape[0] == 0: + return hidden_states, hidden_states + assert ( + hidden_states.shape[0] % context.tp_size == 0 + ), f"Expected total tokens {hidden_states.shape[0]} % tp_size {context.tp_size} to be 0" + local_tokens = hidden_states.shape[0] // context.tp_size + output = hidden_states.new_empty(local_tokens, *hidden_states.shape[1:]) + get_tp_group().reduce_scatter_tensor(output, hidden_states) + if residual is not None: + residual = residual.tensor_split(context.tp_size)[context.tp_rank] + return output, residual + + class LayerCommunicator: def __init__( self, @@ -742,19 +776,7 @@ def _tp_reduce_scatter( hidden_states: torch.Tensor, residual: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor]: - if hidden_states.shape[0] == 0: - return hidden_states, hidden_states - assert ( - hidden_states.shape[0] % self._context.tp_size == 0 - ), f"Expected total tokens {hidden_states.shape[0]} % tp_size {self._context.tp_size} to be 0" - local_tokens = hidden_states.shape[0] // self._context.tp_size - output = hidden_states.new_empty(local_tokens, *hidden_states.shape[1:]) - get_tp_group().reduce_scatter_tensor(output, hidden_states) - if residual is not None: - residual = residual.tensor_split(self._context.tp_size)[ - self._context.tp_rank - ] - return output, residual + return tp_reduce_scatter(hidden_states, residual, self._context) def prepare_mlp( self, @@ -774,6 +796,13 @@ def prepare_mlp( context=self._context, ) + def maybe_prefetch_next_full_attention_kv( + self, + forward_batch: ForwardBatch, + next_full_attention_layer_id: Optional[int], + ) -> None: + return + def postprocess_layer( self, hidden_states: torch.Tensor, @@ -1262,7 +1291,9 @@ def _gather_hidden_states_and_residual_moe( if ( moe_cp_size > 1 and hidden_states.shape[0] > 0 - and forward_batch.forward_mode.is_context_parallel_extend() + and forward_batch.forward_mode.is_context_parallel_extend( + include_draft_extend_v2=True + ) and forward_batch.attn_cp_metadata is not None ): # Zigzag split can produce unequal token counts across CP ranks @@ -1443,7 +1474,9 @@ def _scatter_hidden_states_moe( moe_cp_size = get_moe_cp_size() if ( moe_cp_size > 1 - and forward_batch.forward_mode.is_context_parallel_extend() + and forward_batch.forward_mode.is_context_parallel_extend( + include_draft_extend_v2=True + ) and forward_batch.attn_cp_metadata is not None ): moe_cp_rank = get_moe_cp_rank() diff --git a/python/sglang/srt/layers/communicator_dsa_cp.py b/python/sglang/srt/layers/communicator_dsa_cp.py index c55d64b3bdd00..2d3893178ead0 100644 --- a/python/sglang/srt/layers/communicator_dsa_cp.py +++ b/python/sglang/srt/layers/communicator_dsa_cp.py @@ -55,15 +55,22 @@ def maybe_prefetch_next_full_attention_kv( ) -> None: """Prefetch (owner-broadcast) the next layer's DSA KV under layer split. - No-op unless the current batch runs DSA prefill-CP and the active KV pool is - a layer-sharded pool exposing ``prefetch_kv_buffer`` (i.e. - ``LayerSplitDSATokenToKVPool``). Kicking the broadcast off one layer ahead - overlaps it with the current layer's attention compute. + Hybrid pools expose ``prefetch_full_attention_kv_buffer`` to translate the + model layer id to the compact full-attention pool id. Non-hybrid + layer-sharded pools expose ``prefetch_kv_buffer`` directly. """ if next_full_attention_layer_id is None or not dsa_use_prefill_cp(forward_batch): return - prefetch_kv_buffer = getattr(get_token_to_kv_pool(), "prefetch_kv_buffer", None) + token_to_kv_pool = get_token_to_kv_pool() + prefetch_full_attention_kv = getattr( + token_to_kv_pool, "prefetch_full_attention_kv_buffer", None + ) + if prefetch_full_attention_kv is not None: + prefetch_full_attention_kv(next_full_attention_layer_id) + return + + prefetch_kv_buffer = getattr(token_to_kv_pool, "prefetch_kv_buffer", None) if prefetch_kv_buffer is not None: prefetch_kv_buffer(next_full_attention_layer_id) @@ -137,6 +144,15 @@ def _post_init_communicate(self): context=self._context, ) + def maybe_prefetch_next_full_attention_kv( + self, + forward_batch: ForwardBatch, + next_full_attention_layer_id: Optional[int], + ) -> None: + maybe_prefetch_next_full_attention_kv( + forward_batch, next_full_attention_layer_id + ) + class DSACPCommunicateSimpleFn(CommunicateSimpleFn): @staticmethod diff --git a/python/sglang/srt/layers/communicator_mhc.py b/python/sglang/srt/layers/communicator_mhc.py new file mode 100644 index 0000000000000..b32952ae10a0d --- /dev/null +++ b/python/sglang/srt/layers/communicator_mhc.py @@ -0,0 +1,565 @@ +# Copyright 2023-2024 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""MHC (Manifold-Constrained Hyper-Connections) communicator for attention preparation. + +Adapted from the GLM reference: NSA naming -> DSA (``dsa_use_prefill_cp``, +``ctx.is_dsa``). ``hc_expand`` / ``hc_contract`` live in ``layers/mhc.py``; +the hc_mult-width local DP buffer is exposed via +``get_local_dp_buffer_mhc(get_tp_group(), n)``. +""" + +from dataclasses import dataclass +from functools import partial +from typing import Callable, Optional + +import torch + +from sglang.kernels.ops.layernorm.mhc import hc_contract, hc_expand +from sglang.srt.distributed import get_tp_group +from sglang.srt.distributed.communication_op import ( + attention_tensor_model_parallel_all_reduce, +) +from sglang.srt.distributed.device_communicators.pynccl_allocator import ( + use_symmetric_memory, +) +from sglang.srt.layers.attention.dsa.utils import dsa_use_prefill_cp +from sglang.srt.layers.communicator import ( + AttentionInputs, + CommunicateContext, + CommunicateSimpleFn, + CommunicateSummableTensorPairFn, + CommunicateWithAllReduceAndLayerNormFn, + LayerCommunicator, + LayerScatterModes, + ScatterMode, + get_attn_tp_context, + tp_reduce_scatter, +) +from sglang.srt.layers.dp_attention import ( + attn_tp_all_gather_into_tensor, + attn_tp_reduce_scatter_tensor, + dp_gather_replicate, + dp_reduce_scatter_tensor, + dp_scatter, + get_global_dp_buffer, + get_local_dp_buffer_mhc, + is_allocation_symmetric, +) +from sglang.srt.model_executor.forward_batch_info import ForwardBatch + + +def tp_all_gather_hidden_states(hidden_states, forward_batch): + assert ( + get_attn_tp_context().input_scattered + ), "Input scattered guarantees same num tokens in TP group." + total_tokens = forward_batch.input_ids.shape[0] + output = hidden_states.new_empty((total_tokens, hidden_states.shape[-1])) + get_tp_group().all_gather_into_tensor(output, hidden_states) + + return output + + +@dataclass +class MHCState: + """ + Per-layer mHC runtime scratch. + + The parameter-bearing pre/post stages live on the owning layer and + are injected here as callables (``hc_attn_pre`` / ``hc_ffn_pre`` / + ``hc_post``); this class only orchestrates the cross-stage scratch + (``h_res``, ``h_post``) and exposes the layer's ``hc_mult`` for the + few sites that need it as a raw scalar. + """ + + hc_mult: int + hc_attn_pre: Callable + hc_ffn_pre: Callable + hc_post: Callable + h_res: Optional[torch.Tensor] = None + h_post: Optional[torch.Tensor] = None + + @staticmethod + def _resolve_out_norm(out_norm): + if out_norm is None: + return None, None + return out_norm.weight.data, out_norm.variance_epsilon + + def attn_split(self, hidden_states, out_norm: Optional[torch.nn.Module] = None): + residual = hidden_states + out_norm_weight, out_norm_eps = self._resolve_out_norm(out_norm) + hidden_states, self.h_res, self.h_post, norm_fused = self.hc_attn_pre( + hidden_states, out_norm_weight, out_norm_eps + ) + if out_norm is not None and not norm_fused and hidden_states.shape[0] != 0: + hidden_states = out_norm(hidden_states) + return hidden_states, residual + + def attn_to_mlp( + self, hidden_states, residual, out_norm: Optional[torch.nn.Module] = None + ): + hidden_states = self.hc_post(hidden_states, residual, self.h_res, self.h_post) + residual = hidden_states + out_norm_weight, out_norm_eps = self._resolve_out_norm(out_norm) + hidden_states, self.h_res, self.h_post, norm_fused = self.hc_ffn_pre( + hidden_states, out_norm_weight, out_norm_eps + ) + if out_norm is not None and not norm_fused and hidden_states.shape[0] != 0: + hidden_states = out_norm(hidden_states) + return hidden_states, residual + + def mlp_combine(self, hidden_states, residual): + return self.hc_post(hidden_states, residual, self.h_res, self.h_post) + + def reset_aux(self): + self.h_res = None + self.h_post = None + + +class MHCCommunicateWithAllReduceAndLayerNormFn(CommunicateWithAllReduceAndLayerNormFn): + @staticmethod + def get_fn( + hidden_states_input_mode: ScatterMode, + residual_input_mode: ScatterMode, + hidden_states_output_mode: ScatterMode, + residual_output_mode: ScatterMode, + context: CommunicateContext, + ): + fn = CommunicateWithAllReduceAndLayerNormFn.get_fn( + hidden_states_input_mode, + residual_input_mode, + hidden_states_output_mode, + residual_output_mode, + context, + ) + replacements = { + CommunicateWithAllReduceAndLayerNormFn._simple: MHCCommunicateWithAllReduceAndLayerNormFn._simple, + CommunicateWithAllReduceAndLayerNormFn._gather_hidden_states_and_residual: MHCCommunicateWithAllReduceAndLayerNormFn._gather_hidden_states_and_residual, + CommunicateWithAllReduceAndLayerNormFn._scatter_hidden_states_and_residual: MHCCommunicateWithAllReduceAndLayerNormFn._scatter_hidden_states_and_residual, + } + if isinstance(fn, partial): + return partial( + replacements.get(fn.func, fn.func), + *fn.args, + **(fn.keywords or {}), + ) + return replacements.get(fn, fn) + + @staticmethod + def _scatter_hidden_states_and_residual( + hidden_states: torch.Tensor, + residual: torch.Tensor, + forward_batch: ForwardBatch, + layernorm: torch.nn.Module, + context: CommunicateContext, + *, + residual_input_mode, + mhc: MHCState, + ): + input_hidden_states = hidden_states + hidden_states = hidden_states.tensor_split(context.attn_tp_size)[ + context.attn_tp_rank + ] + attn_tp_reduce_scatter_tensor(hidden_states, input_hidden_states) + if residual_input_mode == ScatterMode.TP_ATTN_FULL: + residual = residual.tensor_split(context.attn_tp_size)[context.attn_tp_rank] + mhc.h_res = mhc.h_res.tensor_split(context.attn_tp_size)[ + context.attn_tp_rank + ] + mhc.h_post = mhc.h_post.tensor_split(context.attn_tp_size)[ + context.attn_tp_rank + ] + + hidden_states, residual = mhc.attn_to_mlp( + hidden_states, residual, out_norm=layernorm + ) + return hidden_states, residual + + @staticmethod + def _simple( + hidden_states: torch.Tensor, + residual: torch.Tensor, + forward_batch: ForwardBatch, + layernorm: torch.nn.Module, + context: CommunicateContext, + *, + mhc: MHCState, + ): + hidden_states, residual = mhc.attn_to_mlp( + hidden_states, residual, out_norm=layernorm + ) + return hidden_states, residual + + @staticmethod + def _tp_all_reduce_with_scattered_residual( + hidden_states: torch.Tensor, + residual: torch.Tensor, + layernorm: torch.nn.Module, + context: CommunicateContext, + *, + mhc: MHCState, + ): + if hidden_states.shape[0] == 0: + return hidden_states, hidden_states + + scatter_states = hidden_states.tensor_split(context.tp_size)[context.tp_rank] + get_tp_group().reduce_scatter_tensor(scatter_states, hidden_states) + + scatter_states, residual = mhc.attn_to_mlp( + scatter_states, residual, out_norm=layernorm + ) + + attn_tp_all_gather_into_tensor(hidden_states, scatter_states) + + return hidden_states, residual + + @staticmethod + def _gather_hidden_states_and_residual( + hidden_states: torch.Tensor, + residual: torch.Tensor, + forward_batch: ForwardBatch, + layernorm: torch.nn.Module, + context: CommunicateContext, + *, + residual_input_mode, + mhc: MHCState, + ): + if get_attn_tp_context().input_scattered: + return MHCCommunicateWithAllReduceAndLayerNormFn._tp_all_reduce_with_scattered_residual( + hidden_states, + residual, + layernorm, + context, + mhc=mhc, + ) + + if residual_input_mode == ScatterMode.SCATTERED and context.attn_tp_size > 1: + raise NotImplementedError( + "Unsupported: h_res/h_post allgather not implemented." + ) + + hidden_states = attention_tensor_model_parallel_all_reduce(hidden_states) + if context.attn_dp_size != 1: + if hidden_states.shape[0] != 0: + with use_symmetric_memory( + get_tp_group(), + disabled=not is_allocation_symmetric(), + ): + hidden_states, residual = mhc.attn_to_mlp( + hidden_states, residual, out_norm=layernorm + ) + else: + hidden_states, residual = mhc.attn_to_mlp(hidden_states, residual) + + hidden_states, local_hidden_states = ( + get_global_dp_buffer(get_tp_group()), + hidden_states, + ) + dp_gather_replicate(hidden_states, local_hidden_states, forward_batch) + else: + hidden_states, residual = mhc.attn_to_mlp( + hidden_states, residual, out_norm=layernorm + ) + return hidden_states, residual + + +class MHCCommunicateSummableTensorPairFn(CommunicateSummableTensorPairFn): + @staticmethod + def get_fn( + hidden_states_input_mode: ScatterMode, + residual_input_mode: ScatterMode, + output_mode: ScatterMode, + context: CommunicateContext, + ): + fn = CommunicateSummableTensorPairFn.get_fn( + hidden_states_input_mode, + residual_input_mode, + output_mode, + context, + ) + replacements = { + CommunicateSummableTensorPairFn._trivial: MHCCommunicateSummableTensorPairFn._trivial, + CommunicateSummableTensorPairFn._scatter_hidden_states: MHCCommunicateSummableTensorPairFn._scatter_hidden_states, + CommunicateSummableTensorPairFn._gather: MHCCommunicateSummableTensorPairFn._gather, + CommunicateSummableTensorPairFn._scatter: MHCCommunicateSummableTensorPairFn._scatter, + } + return replacements.get(fn, fn) + + @staticmethod + def _trivial( + hidden_states: torch.Tensor, + residual: torch.Tensor, + forward_batch: ForwardBatch, + context: CommunicateContext, + *, + mhc: MHCState, + is_last_layer: bool, + **kwargs, + ): + if get_attn_tp_context().input_scattered: + hidden_states, _ = tp_reduce_scatter(hidden_states, None, context) + + hidden_states = mhc.mlp_combine(hidden_states, residual) + if not is_last_layer: + return hidden_states, None + + hidden_states = hc_contract(hidden_states, mhc.hc_mult) + if get_attn_tp_context().input_scattered: + local_states = hidden_states + hidden_states = local_states.new_empty( + local_states.shape[0] * context.tp_size, *local_states.shape[1:] + ) + get_tp_group().all_gather_into_tensor(hidden_states, local_states) + + return hidden_states, None + + @staticmethod + def _scatter_hidden_states( + hidden_states: torch.Tensor, + residual: torch.Tensor, + forward_batch: ForwardBatch, + context: CommunicateContext, + allow_reduce_scatter: bool = False, + *, + mhc: MHCState, + is_last_layer: bool, + **kwargs, + ): + hidden_states, global_hidden_states = ( + get_local_dp_buffer_mhc(get_tp_group(), 1), + hidden_states, + ) + if allow_reduce_scatter and forward_batch.dp_padding_mode.is_max_len(): + dp_reduce_scatter_tensor(hidden_states, global_hidden_states) + else: + dp_scatter(hidden_states, global_hidden_states, forward_batch) + + hidden_states = mhc.mlp_combine(hidden_states, residual) + if not is_last_layer: + return hidden_states, None + + hidden_states = hc_contract(hidden_states, mhc.hc_mult) + return hidden_states, None + + @staticmethod + def _gather( + hidden_states: torch.Tensor, + residual: torch.Tensor, + forward_batch: ForwardBatch, + context: CommunicateContext, + *, + mhc: MHCState, + is_last_layer: bool, + **kwargs, + ): + hidden_states = mhc.mlp_combine(hidden_states, residual) + if is_last_layer: + hidden_states = hc_contract(hidden_states, mhc.hc_mult) + + hidden_states, local_hidden_states = ( + get_local_dp_buffer_mhc( + get_tp_group(), 1 if is_last_layer else mhc.hc_mult + ), + hidden_states, + ) + + attn_tp_all_gather_into_tensor(hidden_states, local_hidden_states) + return hidden_states, None + + @staticmethod + def _scatter( + hidden_states: torch.Tensor, + residual: torch.Tensor, + forward_batch: ForwardBatch, + context: CommunicateContext, + *, + mhc: MHCState, + is_last_layer: bool, + **kwargs, + ): + hidden_states = hidden_states.tensor_split(context.attn_tp_size)[ + context.attn_tp_rank + ] + residual = residual.tensor_split(context.attn_tp_size)[context.attn_tp_rank] + + hidden_states = mhc.mlp_combine(hidden_states, residual) + + return hidden_states, None + + +class MHCLayerCommunicator(LayerCommunicator): + def __init__( + self, + layer_scatter_modes: LayerScatterModes, + input_layernorm: torch.nn.Module, + post_attention_layernorm: torch.nn.Module, + allow_reduce_scatter: bool = False, + is_last_layer: bool = False, + qkv_latent_func: Optional[Callable] = None, + *, + is_first_layer: bool, + hc_mult: int, + hc_attn_pre: Callable, + hc_ffn_pre: Callable, + hc_post: Callable, + ): + self.is_first_layer = is_first_layer + self.mhc = MHCState( + hc_mult=hc_mult, + hc_attn_pre=hc_attn_pre, + hc_ffn_pre=hc_ffn_pre, + hc_post=hc_post, + ) + + super().__init__( + layer_scatter_modes, + input_layernorm, + post_attention_layernorm, + allow_reduce_scatter, + is_last_layer, + qkv_latent_func, + ) + + def _post_init_communicate(self): + # MOE_FULL resolves to base *_moe methods that take no `mhc`, which + # this subclass passes unconditionally -> runtime TypeError. Not wired + # for MHC yet; fail loudly at construction instead. + if self.layer_scatter_modes.mlp_mode == ScatterMode.MOE_FULL: + raise NotImplementedError( + "MHCLayerCommunicator does not support MOE_FULL " + "(moe_dp_size < attention_context_parallel_size without " + "--enable-prefill-cp). Set --enable-prefill-cp or raise " + "moe_dp_size to match attention_context_parallel_size." + ) + self._communicate_simple_fn = CommunicateSimpleFn.get_fn( + input_mode=self.layer_scatter_modes.layer_input_mode, + output_mode=self.layer_scatter_modes.attn_mode, + context=self._context, + ) + self._communicate_with_all_reduce_and_layer_norm_fn = ( + MHCCommunicateWithAllReduceAndLayerNormFn.get_fn( + hidden_states_input_mode=self.layer_scatter_modes.attn_mode, + residual_input_mode=self.layer_scatter_modes.layer_input_mode, + hidden_states_output_mode=self.layer_scatter_modes.mlp_mode, + residual_output_mode=self.layer_scatter_modes.middle_residual_mode, + context=self._context, + ) + ) + self._communicate_summable_tensor_pair_fn = ( + MHCCommunicateSummableTensorPairFn.get_fn( + hidden_states_input_mode=self.layer_scatter_modes.mlp_mode, + residual_input_mode=self.layer_scatter_modes.middle_residual_mode, + output_mode=self.layer_scatter_modes.layer_output_mode, + context=self._context, + ) + ) + + def prepare_attn( + self, + hidden_states: torch.Tensor, + residual: torch.Tensor, + forward_batch: ForwardBatch, + ): + if self.is_first_layer: + if get_attn_tp_context().input_scattered: + hidden_states, _ = tp_reduce_scatter( + hidden_states, + None, + self._context, + ) + hidden_states = hc_expand(hidden_states, self.mhc.hc_mult) + + hidden_states, residual = self.mhc.attn_split( + hidden_states, out_norm=self.input_layernorm + ) + + hidden_states = self._communicate_simple_fn( + hidden_states=hidden_states, + forward_batch=forward_batch, + context=self._context, + ) + + # Pre-gather to avoid duplicate all_gather in DSA; without a + # qkv_latent hook the attention impl reads mixed_qkv directly, so the + # full hidden_states must be materialized here. + ctx = get_attn_tp_context() + dsa_pre_gather = ctx.input_scattered and ctx.is_dsa + no_qkv_latent_pre_gather = ctx.input_scattered and self.qkv_latent_func is None + if dsa_pre_gather or no_qkv_latent_pre_gather: + hidden_states = tp_all_gather_hidden_states(hidden_states, forward_batch) + + if self.qkv_latent_func is not None: + attn_inputs = AttentionInputs( + hidden_states, + forward_batch, + self.qkv_latent_func, + is_pre_gathered=dsa_pre_gather, + ) + ctx.set_attn_inputs(attn_inputs) + + return hidden_states, residual + + def prepare_mlp( + self, + hidden_states: torch.Tensor, + residual: torch.Tensor, + forward_batch: ForwardBatch, + cache=None, + ): + if cache is not None: + self._context.cache = cache + + hidden_states, residual = self._communicate_with_all_reduce_and_layer_norm_fn( + hidden_states=hidden_states, + residual=residual, + forward_batch=forward_batch, + layernorm=self.post_attention_layernorm, + context=self._context, + mhc=self.mhc, + ) + + return hidden_states, residual + + def postprocess_layer(self, hidden_states, residual, forward_batch): + hidden_states, residual = self._communicate_summable_tensor_pair_fn( + hidden_states=hidden_states, + residual=residual, + forward_batch=forward_batch, + context=self._context, + allow_reduce_scatter=self.allow_reduce_scatter, + mhc=self.mhc, + is_last_layer=self.is_last_layer, + ) + self.mhc.reset_aux() + + return hidden_states, residual + + def should_fuse_mlp_allreduce_with_next_layer(self, forward_batch): + return False + + def should_use_reduce_scatter(self, forward_batch: ForwardBatch): + if not self.allow_reduce_scatter: + return False + if ( + self._communicate_summable_tensor_pair_fn + is MHCCommunicateSummableTensorPairFn._scatter_hidden_states + and forward_batch.dp_padding_mode.is_max_len() + ): + return True + + if dsa_use_prefill_cp(forward_batch): + return True + + if get_attn_tp_context().input_scattered: + return True + return False diff --git a/python/sglang/srt/layers/communicator_mhc_hybrid_cp.py b/python/sglang/srt/layers/communicator_mhc_hybrid_cp.py new file mode 100644 index 0000000000000..6a1d9717b6025 --- /dev/null +++ b/python/sglang/srt/layers/communicator_mhc_hybrid_cp.py @@ -0,0 +1,222 @@ +# Copyright 2023-2024 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""MHC + DSA prefill-CP hybrid communicator. + +hc_mult-width local DP buffer is routed through ``get_local_dp_buffer_mhc``. +""" + +from functools import partial +from typing import Optional + +import torch + +from sglang.kernels.ops.layernorm.mhc import hc_contract +from sglang.srt.distributed import get_tp_group +from sglang.srt.layers.attention.dsa.utils import dsa_use_prefill_cp +from sglang.srt.layers.communicator import ( + CommunicateContext, + ScatterMode, +) +from sglang.srt.layers.communicator_dsa_cp import ( + DSACPCommunicateSimpleFn, + DSACPCommunicateSummableTensorPairFn, + DSACPCommunicateWithAllReduceAndLayerNormFn, + maybe_prefetch_next_full_attention_kv, +) +from sglang.srt.layers.communicator_mhc import MHCLayerCommunicator, MHCState +from sglang.srt.layers.dp_attention import ( + attn_cp_all_gather_into_tensor, + attn_cp_reduce_scatter_tensor, + get_local_dp_buffer_mhc, +) +from sglang.srt.model_executor.forward_batch_info import ForwardBatch + + +class MHCHybridDSACPLayerCommunicator(MHCLayerCommunicator): + def _post_init_communicate(self): + # SCATTERED in attn tp is different from SCATTERED in global tp when dp_size > 1 + if self.layer_scatter_modes.mlp_mode != ScatterMode.SCATTERED: + assert ( + self._context.attn_dp_size == 1 + ), "dp_size should be 1 when moe_runner_backend is none" + self._communicate_simple_fn = DSACPCommunicateSimpleFn.get_fn( + input_mode=ScatterMode.SCATTERED, + output_mode=ScatterMode.SCATTERED, + context=self._context, + ) + self._communicate_with_all_reduce_and_layer_norm_fn = MHCHybridDSACPCommunicateWithAllReduceAndLayerNormFn.get_fn( + hidden_states_input_mode=ScatterMode.SCATTERED, + residual_input_mode=ScatterMode.SCATTERED, + hidden_states_output_mode=self.layer_scatter_modes.mlp_mode, # SCATTERED, FULL + residual_output_mode=ScatterMode.SCATTERED, + context=self._context, + ) + self._communicate_summable_tensor_pair_fn = MHCHybridDSACPCommunicateSummableTensorPairFn.get_fn( + hidden_states_input_mode=self.layer_scatter_modes.mlp_mode, # SCATTERED, FULL + residual_input_mode=ScatterMode.SCATTERED, + output_mode=ScatterMode.SCATTERED, + context=self._context, + ) + + def maybe_prefetch_next_full_attention_kv( + self, + forward_batch: ForwardBatch, + next_full_attention_layer_id: Optional[int], + ) -> None: + maybe_prefetch_next_full_attention_kv( + forward_batch, next_full_attention_layer_id + ) + + +class MHCHybridDSACPCommunicateWithAllReduceAndLayerNormFn( + DSACPCommunicateWithAllReduceAndLayerNormFn +): + @staticmethod + def get_fn( + hidden_states_input_mode: ScatterMode, + residual_input_mode: ScatterMode, + hidden_states_output_mode: ScatterMode, + residual_output_mode: ScatterMode, + context: CommunicateContext, + ): + assert hidden_states_input_mode == ScatterMode.SCATTERED + assert residual_input_mode == ScatterMode.SCATTERED + assert residual_output_mode == ScatterMode.SCATTERED + if hidden_states_output_mode == ScatterMode.SCATTERED: + return MHCHybridDSACPCommunicateWithAllReduceAndLayerNormFn._simple + + if hidden_states_output_mode == ScatterMode.FULL: + return partial( + MHCHybridDSACPCommunicateWithAllReduceAndLayerNormFn._gather_hidden_states_and_residual, + residual_input_mode=residual_input_mode, + ) + + raise NotImplementedError( + f"{hidden_states_input_mode=} {residual_input_mode=} " + f"{hidden_states_output_mode=} {residual_output_mode=}" + ) + + @staticmethod + def _simple( + hidden_states: torch.Tensor, + residual: torch.Tensor, + forward_batch: ForwardBatch, + layernorm: torch.nn.Module, + context: CommunicateContext, + *, + mhc: MHCState, + ): + hidden_states, residual = mhc.attn_to_mlp( + hidden_states, residual, out_norm=layernorm + ) + return hidden_states, residual + + @staticmethod + def _gather_hidden_states_and_residual( + hidden_states: torch.Tensor, + residual: torch.Tensor, + forward_batch: ForwardBatch, + layernorm: torch.nn.Module, + context: CommunicateContext, + *, + residual_input_mode, + mhc: MHCState, + ): + hidden_states, residual = mhc.attn_to_mlp( + hidden_states, residual, out_norm=layernorm + ) + + if dsa_use_prefill_cp(forward_batch): + assert context.attn_dp_size == 1 + hidden_states, local_hidden_states = ( + get_local_dp_buffer_mhc(get_tp_group(), 1), + hidden_states, + ) + attn_cp_all_gather_into_tensor( + hidden_states, + local_hidden_states, + ) + return hidden_states, residual + + +class MHCHybridDSACPCommunicateSummableTensorPairFn( + DSACPCommunicateSummableTensorPairFn +): + @staticmethod + def get_fn( + hidden_states_input_mode: ScatterMode, + residual_input_mode: ScatterMode, + output_mode: ScatterMode, + context: CommunicateContext, + ): + if ( + (hidden_states_input_mode == ScatterMode.FULL) + and (residual_input_mode == ScatterMode.SCATTERED) + and (output_mode == ScatterMode.SCATTERED) + ): + return MHCHybridDSACPCommunicateSummableTensorPairFn._scatter_hidden_states + + if context.is_same_group_size( + hidden_states_input_mode, output_mode + ) and context.is_same_group_size(residual_input_mode, output_mode): + return MHCHybridDSACPCommunicateSummableTensorPairFn._trivial + + raise NotImplementedError( + f"{hidden_states_input_mode=} {residual_input_mode=} {output_mode=}" + ) + + @staticmethod + def _trivial( + hidden_states: torch.Tensor, + residual: torch.Tensor, + forward_batch: ForwardBatch, + context: CommunicateContext, + *, + mhc: MHCState, + is_last_layer: bool, + **kwargs, + ): + hidden_states = mhc.mlp_combine(hidden_states, residual) + if not is_last_layer: + return hidden_states, None + + hidden_states = hc_contract(hidden_states, mhc.hc_mult) + return hidden_states, None + + @staticmethod + def _scatter_hidden_states( + hidden_states: torch.Tensor, + residual: torch.Tensor, + forward_batch: ForwardBatch, + context: CommunicateContext, + allow_reduce_scatter: bool = False, + *, + mhc: MHCState, + is_last_layer: bool, + **kwargs, + ): + if dsa_use_prefill_cp(forward_batch): + assert context.attn_dp_size == 1 + input_hidden_states = hidden_states + hidden_states = hidden_states.tensor_split(context.attn_cp_size)[ + context.attn_cp_rank + ] + attn_cp_reduce_scatter_tensor(hidden_states, input_hidden_states) + + hidden_states = mhc.mlp_combine(hidden_states, residual) + if not is_last_layer: + return hidden_states, None + + hidden_states = hc_contract(hidden_states, mhc.hc_mult) + return hidden_states, None diff --git a/python/sglang/srt/layers/dcp/comm.py b/python/sglang/srt/layers/dcp/comm.py index 915a29b7ac3f2..a89bb2a3f2e6a 100644 --- a/python/sglang/srt/layers/dcp/comm.py +++ b/python/sglang/srt/layers/dcp/comm.py @@ -305,13 +305,16 @@ def all_gather_kv_cache_for_mla_extend( # all gather kv cache and re-org to query orders def all_gather_kv_cache_for_dcp( prefix_kv_a: torch.Tensor, - prefix_k_pe: torch.Tensor, + prefix_k_pe: Optional[torch.Tensor], prefix_kv_lens_cpu: torch.Tensor, prefix_starts_cpu: torch.Tensor = None, ): """ prefix_kv_a and prefix_k_pe should have same shape, expect for last dim """ + if prefix_k_pe is None: + prefix_k_pe = prefix_kv_a.new_empty((*prefix_kv_a.shape[:-1], 0)) + parallel = get_parallel() if not parallel.dcp_enabled: return torch.cat([prefix_kv_a, prefix_k_pe], dim=-1) diff --git a/python/sglang/srt/layers/dp_attention.py b/python/sglang/srt/layers/dp_attention.py index bbbe365086179..038d41777db12 100644 --- a/python/sglang/srt/layers/dp_attention.py +++ b/python/sglang/srt/layers/dp_attention.py @@ -207,6 +207,21 @@ def get_local_dp_buffer(cls, group: GroupCoordinator) -> torch.Tensor: ) return buffer + @classmethod + def get_local_dp_buffer_mhc( + cls, group: GroupCoordinator, n: int = 1 + ) -> torch.Tensor: + from sglang.srt.runtime_context import get_flags + + dp = get_flags().dp + with use_symmetric_memory(group, disabled=not cls._dp_max_padding): + buffer = torch.empty( + (cls._local_dp_buffer_len, dp.buffer_hidden_size * n), + dtype=dp.buffer_dtype, + device=dp.buffer_device, + ) + return buffer + @classmethod def get_global_dp_buffer_len(cls) -> int: return cls._global_dp_buffer_len @@ -274,6 +289,10 @@ def get_local_dp_buffer(group: GroupCoordinator) -> torch.Tensor: return _DpGatheredBufferWrapper.get_local_dp_buffer(group=group) +def get_local_dp_buffer_mhc(group: GroupCoordinator, n: int = 1) -> torch.Tensor: + return _DpGatheredBufferWrapper.get_local_dp_buffer_mhc(group=group, n=n) + + def get_global_dp_buffer_len() -> int: return _DpGatheredBufferWrapper.get_global_dp_buffer_len() diff --git a/python/sglang/srt/layers/utils/cp_utils.py b/python/sglang/srt/layers/utils/cp_utils.py index 03500c7ad003b..06a276e753a0e 100644 --- a/python/sglang/srt/layers/utils/cp_utils.py +++ b/python/sglang/srt/layers/utils/cp_utils.py @@ -83,7 +83,9 @@ def mla_use_prefill_cp(forward_batch, mla_enable_prefill_cp=None): return ( forward_batch.attn_cp_metadata is not None and mla_enable_prefill_cp - and forward_batch.forward_mode.is_context_parallel_extend() + and forward_batch.forward_mode.is_context_parallel_extend( + include_draft_extend_v2=True + ) ) diff --git a/python/sglang/srt/managers/schedule_batch.py b/python/sglang/srt/managers/schedule_batch.py index 41513a1c4a945..1afda7c9e7206 100755 --- a/python/sglang/srt/managers/schedule_batch.py +++ b/python/sglang/srt/managers/schedule_batch.py @@ -1743,7 +1743,9 @@ def offload_kv_cache(self, req_to_token_pool, token_to_kv_pool_allocator): ) self.retraction_backup = RetractionBackup( cpu_tensors=token_to_kv_pool_allocator.get_cpu_copy( - token_indices, mamba_indices=self.mamba_pool_idx + token_indices, + mamba_indices=self.mamba_pool_idx, + req_pool_index=self.req_pool_idx, ), mamba_cpu=( mamba_pool.get_cpu_copy(self.mamba_pool_idx.unsqueeze(0)) @@ -1767,6 +1769,7 @@ def load_kv_cache(self, req_to_token_pool, token_to_kv_pool_allocator): self.retraction_backup.cpu_tensors, token_indices, mamba_indices=self.mamba_pool_idx, + req_pool_index=self.req_pool_idx, ) self.retraction_backup = None diff --git a/python/sglang/srt/managers/schedule_policy.py b/python/sglang/srt/managers/schedule_policy.py index 34472fce20c51..bce0f53ce27d7 100644 --- a/python/sglang/srt/managers/schedule_policy.py +++ b/python/sglang/srt/managers/schedule_policy.py @@ -838,6 +838,11 @@ def _mamba_gap_budget_for_req(self, req: Req) -> int: def ceil_paged_tokens(self, tokens: int) -> int: return -(-tokens // self.page_size) * self.page_size + def chunk_budget_exhausted(self) -> bool: + return ( + self.rem_chunk_tokens is not None and self.rem_chunk_tokens < self.page_size + ) + def budget_state(self): no_token = self.rem_total_tokens <= 0 or self.cur_rem_tokens <= 0 if not no_token and self.is_hybrid_swa: diff --git a/python/sglang/srt/managers/scheduler.py b/python/sglang/srt/managers/scheduler.py index fd3a27bf5b45a..45460e2e6d85a 100644 --- a/python/sglang/srt/managers/scheduler.py +++ b/python/sglang/srt/managers/scheduler.py @@ -16,6 +16,7 @@ import dataclasses import faulthandler import logging +import math import os import signal import sys @@ -631,6 +632,7 @@ def __init__( # Init prefill kv split size when deterministic inference is enabled with various attention backends self.init_deterministic_inference_config() + self.init_dsa_kpool_truncation_align() self.init_weight_updater() @@ -1563,6 +1565,29 @@ def init_deterministic_inference_config(self): get_int_env_var(env_var, default_size) if env_var else None ) + def init_dsa_kpool_truncation_align(self): + """The kpool compress-write path asserts each chunked extend starts on a + pool boundary; truncation_align_size enforces that per request. LCM with + any existing align size so deterministic inference and kpool coexist.""" + from sglang.srt.configs.model_config import ( + get_dsa_index_kpool, + is_deepseek_dsa, + ) + + if not is_deepseek_dsa(self.model_config.hf_config): + return + + dsa_index_kpool = get_dsa_index_kpool(self.model_config.hf_config) + if dsa_index_kpool <= 1: + return + + if self.truncation_align_size is None: + self.truncation_align_size = dsa_index_kpool + else: + self.truncation_align_size = math.lcm( + self.truncation_align_size, dsa_index_kpool + ) + def init_request_dispatcher(self): self._request_dispatcher = TypeBasedDispatcher( [ @@ -3015,10 +3040,13 @@ def process_pending_chunked_abort(self) -> None: if req is None: return if self.chunked_req is not req: - # Already past chunked prefill; the running-batch abort path handles - # it. Drop the marker once the request is actually gone. if req.finished() or req.req_pool_idx is None: self._pending_chunked_abort_req = None + return + # The request moved to another scheduler queue after abort_request + # deferred it, so retry against its current location. + self._pending_chunked_abort_req = None + self.abort_request(AbortReq(rid=req.rid)) return prepare_abort(req, "Aborted") @@ -3172,6 +3200,7 @@ def get_next_batch_to_run( running_batch.filter_batch() if running_batch.is_empty(): running_batch.batch_is_full = False + running_batch.is_prefill_only = False if self.dllm_config is not None: new_batch = self.get_new_batch_dllm(running_batch) @@ -3370,6 +3399,9 @@ def _get_new_batch_prefill_raw( mamba_allocator.alloc_group_begin(len(self.waiting_queue)) # Get requests from the waiting queue to a new prefill batch for req in self.waiting_queue: + if adder.chunk_budget_exhausted(): + break + if self.enable_lora and not self._can_schedule_lora_req(req, running_loras): continue @@ -4105,7 +4137,7 @@ def _record_step_counters( ) def maybe_send_health_check_signal(self): - if self.return_health_check_ipcs: + while self.return_health_check_ipcs: # Return some signal for the health check. # This is used to prevent the health check signal being blocked by long context prefill. # However, one minor issue is that this code path does not check the status of detokenizer manager. diff --git a/python/sglang/srt/managers/tokenizer_manager.py b/python/sglang/srt/managers/tokenizer_manager.py index 6ec332baa001f..d95d8e15be3ed 100644 --- a/python/sglang/srt/managers/tokenizer_manager.py +++ b/python/sglang/srt/managers/tokenizer_manager.py @@ -229,6 +229,9 @@ class ReqState: last_completion_tokens: int = 1 ttft_observed: bool = False + dispatched: bool = False + abort_sent: bool = False + # For streaming output last_output_offset: int = 0 @@ -796,6 +799,7 @@ async def generate_request( ) self._init_req_state(obj, request) + request_rids = {obj.rid} if obj.is_single else set(obj.rid) try: if get_disagg().language_only: self._handle_epd_disaggregation_encode_request(obj) @@ -819,17 +823,19 @@ async def generate_request( async for response in self._wait_one_response(obj, request): yield response else: - async for response in self._handle_batch_request(obj, request): + async for response in self._handle_batch_request( + obj, request, request_rids + ): yield response except BaseException: # _init_req_state created a rid_to_state entry per (sub-)request up # front. The normal remover is the scheduler-response path # (_handle_batch_output), so a failure *before* a request reaches the # scheduler -- e.g. input-length validation rejecting an over-context - # request -- would otherwise leak those entries forever. Drop any that - # are still pending; entries already removed on the normal completion - # path are left untouched (pop is a no-op). - self._discard_pending_req_states(obj) + # request -- would otherwise leak those entries forever. Drop + # undelivered states, but abort dispatched requests for scheduler-side + # cleanup. + self._release_req_states_on_failure(request_rids) raise def _detect_input_format( @@ -1566,6 +1572,7 @@ def _send_one_request( time_stats = tokenized_obj.time_stats tokenized_obj.wrap_pickle_fields() self._dispatch_to_scheduler(tokenized_obj) + self._mark_state_dispatched(tokenized_obj.rid) dispatched = True tokenized_obj.time_stats = time_stats tokenized_obj.time_stats.set_api_server_dispatch_finish_time() @@ -1573,6 +1580,16 @@ def _send_one_request( if not dispatched: self.cuda_vmm_feature_transport.cancel_for_dispatch(prepared_mm_items) + def _mark_state_dispatched(self, rid: str): + """Record that *rid* reached the scheduler. + + Only dispatched requests are aborted (not discarded) by the + handler-failure cleanup; see _release_req_states_on_failure. + """ + state = self.rid_to_state.get(rid) + if state is not None: + state.dispatched = True + def _send_batch_request( self, tokenized_objs: List[ @@ -1598,6 +1615,8 @@ def _send_batch_request( batch_req = BatchTokenizedEmbeddingReqInput(batch=tokenized_objs) self._dispatch_to_scheduler(batch_req) + for tokenized_obj in tokenized_objs: + self._mark_state_dispatched(tokenized_obj.rid) dispatched = True for tokenized_obj, time_stat in zip(tokenized_objs, time_stats): tokenized_obj.time_stats = time_stat @@ -1796,7 +1815,10 @@ async def _handle_batch_request( self, obj: Union[GenerateReqInput, EmbeddingReqInput], request: Optional[fastapi.Request] = None, + request_rids: Optional[set[str]] = None, ): + if request_rids is None: + request_rids = set(obj.rid) batch_size = obj.batch_size generators = [] @@ -1862,6 +1884,7 @@ async def _handle_batch_request( tokenized_obj.sampling_params.max_new_tokens = 0 tokenized_obj.stream = False self._init_req_state(tmp_obj) + request_rids.add(tmp_obj.rid) self._send_one_request(tokenized_obj) await self._wait_one_response(tmp_obj, request).__anext__() @@ -1878,6 +1901,7 @@ async def _handle_batch_request( ] tokenized_obj.rid = tmp_obj.regenerate_rid() self._init_req_state(tmp_obj) + request_rids.add(tmp_obj.rid) state = self.rid_to_state[tmp_obj.rid] tokenized_obj.time_stats = state.time_stats if tmp_obj.return_prompt_token_ids: @@ -1947,14 +1971,21 @@ def abort_request(self, rid: str = "", abort_all: bool = False): if not abort_all and not rid: logger.warning("Ignore abort_request with empty rid and abort_all=False") return - if ( - not abort_all - and get_serving().tokenizer_worker_num == 1 - and rid not in self.rid_to_state - ): - return + state = None if abort_all else self.rid_to_state.get(rid) + if not abort_all: + if state is not None: + if state.abort_sent: + return + state.abort_sent = True + elif get_serving().tokenizer_worker_num == 1: + return req = AbortReq(rid=rid, abort_all=abort_all) - self._dispatch_to_scheduler(req) + try: + self._dispatch_to_scheduler(req) + except BaseException: + if state is not None: + state.abort_sent = False + raise if self.enable_metrics: # TODO: also use custom_labels from the request self.metrics_collector.observe_one_aborted_request( @@ -2115,10 +2146,9 @@ def create_abort_task(self, obj: GenerateReqInput): # Abort the request if the client is disconnected. async def abort_request(): await asyncio.sleep(2) - if obj.is_single: - self.abort_request(obj.rid) - else: - for rid in obj.rid: + rids = [obj.rid] if obj.is_single else obj.rid + for rid in rids: + if rid in self.rid_to_state: self.abort_request(rid) background_tasks = BackgroundTasks() @@ -3415,19 +3445,23 @@ def _init_req_state( time_stats.init_trace_ctx(rid, bootstrap_room, external_trace_header) time_stats.set_created_time(created_time) - def _discard_pending_req_states(self, obj): - """Drop rid_to_state entries created by _init_req_state for *obj*. + def _release_req_states_on_failure(self, rids: Iterable[str]): + """Release rid_to_state entries created for a failed handler. - Safe to call after a partial/failed dispatch: only entries still present - are removed, and the scheduler-response path looks up state with - ``.get(...)`` so a later output for a discarded rid is ignored, not fatal. + Undelivered states are removed locally. Dispatched requests are aborted + and retained until the scheduler response removes them. """ - if not hasattr(obj, "is_single") or obj.is_single: - rids = [obj.rid] - else: - rids = obj.rid for rid in rids: - self.rid_to_state.pop(rid, None) + state = self.rid_to_state.get(rid) + if state is None: + continue + if state.dispatched: + try: + self.abort_request(rid) + except Exception: + logger.exception("Failed to abort request %s during cleanup", rid) + else: + del self.rid_to_state[rid] def _should_dispatch_to_encoder( self, obj: Union[GenerateReqInput, EmbeddingReqInput] diff --git a/python/sglang/srt/mem_cache/allocator/base.py b/python/sglang/srt/mem_cache/allocator/base.py index 103324dcde2a1..a82654faa7a6d 100644 --- a/python/sglang/srt/mem_cache/allocator/base.py +++ b/python/sglang/srt/mem_cache/allocator/base.py @@ -92,11 +92,13 @@ def translate_kv_indices_for_transfer( """ return kv_indices - def get_cpu_copy(self, indices, mamba_indices=None): + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): # FIXME: reuse the get_cpu_copy after paged allocator is implemented raise NotImplementedError() - def load_cpu_copy(self, kv_cache_cpu, indices, mamba_indices=None): + def load_cpu_copy( + self, kv_cache_cpu, indices, mamba_indices=None, req_pool_index=None + ): # FIXME: reuse the load_cpu_copy after paged allocator is implemented raise NotImplementedError() diff --git a/python/sglang/srt/mem_cache/allocator/paged.py b/python/sglang/srt/mem_cache/allocator/paged.py index b092911f29c59..7d7a650fa9605 100755 --- a/python/sglang/srt/mem_cache/allocator/paged.py +++ b/python/sglang/srt/mem_cache/allocator/paged.py @@ -338,10 +338,19 @@ def clear(self): self.free_page_reps_group = [] self.release_pages = torch.empty((0,), dtype=torch.int64, device=self.device) - def get_cpu_copy(self, indices, mamba_indices=None): - return self._kvcache.get_cpu_copy(indices, mamba_indices=mamba_indices) + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): + return self._kvcache.get_cpu_copy( + indices, + mamba_indices=mamba_indices, + req_pool_index=req_pool_index, + ) - def load_cpu_copy(self, kv_cache_cpu, indices, mamba_indices=None): + def load_cpu_copy( + self, kv_cache_cpu, indices, mamba_indices=None, req_pool_index=None + ): return self._kvcache.load_cpu_copy( - kv_cache_cpu, indices, mamba_indices=mamba_indices + kv_cache_cpu, + indices, + mamba_indices=mamba_indices, + req_pool_index=req_pool_index, ) diff --git a/python/sglang/srt/mem_cache/allocator/swa.py b/python/sglang/srt/mem_cache/allocator/swa.py index f3540340f7e6e..907adf3d2590d 100644 --- a/python/sglang/srt/mem_cache/allocator/swa.py +++ b/python/sglang/srt/mem_cache/allocator/swa.py @@ -412,12 +412,21 @@ def clear(self): self.free_group = [] self.swa_free_group = [] - def get_cpu_copy(self, indices, mamba_indices=None): - return self._kvcache.get_cpu_copy(indices, mamba_indices=mamba_indices) + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): + return self._kvcache.get_cpu_copy( + indices, + mamba_indices=mamba_indices, + req_pool_index=req_pool_index, + ) - def load_cpu_copy(self, kv_cache_cpu, indices, mamba_indices=None): + def load_cpu_copy( + self, kv_cache_cpu, indices, mamba_indices=None, req_pool_index=None + ): return self._kvcache.load_cpu_copy( - kv_cache_cpu, indices, mamba_indices=mamba_indices + kv_cache_cpu, + indices, + mamba_indices=mamba_indices, + req_pool_index=req_pool_index, ) diff --git a/python/sglang/srt/mem_cache/allocator/token.py b/python/sglang/srt/mem_cache/allocator/token.py index 06aceef120631..c816f3b47cc80 100644 --- a/python/sglang/srt/mem_cache/allocator/token.py +++ b/python/sglang/srt/mem_cache/allocator/token.py @@ -75,10 +75,19 @@ def free(self, free_index: torch.Tensor): else: self.free_group.append(self._copy_for_free_group(free_index)) - def get_cpu_copy(self, indices, mamba_indices=None): - return self._kvcache.get_cpu_copy(indices, mamba_indices=mamba_indices) + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): + return self._kvcache.get_cpu_copy( + indices, + mamba_indices=mamba_indices, + req_pool_index=req_pool_index, + ) - def load_cpu_copy(self, kv_cache_cpu, indices, mamba_indices=None): + def load_cpu_copy( + self, kv_cache_cpu, indices, mamba_indices=None, req_pool_index=None + ): return self._kvcache.load_cpu_copy( - kv_cache_cpu, indices, mamba_indices=mamba_indices + kv_cache_cpu, + indices, + mamba_indices=mamba_indices, + req_pool_index=req_pool_index, ) diff --git a/python/sglang/srt/mem_cache/deepseek_v4_memory_pool.py b/python/sglang/srt/mem_cache/deepseek_v4_memory_pool.py index 54eabcb7e8789..29c56cd012086 100644 --- a/python/sglang/srt/mem_cache/deepseek_v4_memory_pool.py +++ b/python/sglang/srt/mem_cache/deepseek_v4_memory_pool.py @@ -250,10 +250,12 @@ def set_key_buffer_fused( loc = self.translate_loc_to_hisparse_device(loc) return super().set_key_buffer_fused(layer_id, loc, cache_k) - def get_cpu_copy(self, indices, mamba_indices=None): + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): raise NotImplementedError("HiSparseC4DevicePool does not support get_cpu_copy") - def load_cpu_copy(self, kv_cache_cpu, indices, mamba_indices=None): + def load_cpu_copy( + self, kv_cache_cpu, indices, mamba_indices=None, req_pool_index=None + ): raise NotImplementedError("HiSparseC4DevicePool does not support load_cpu_copy") diff --git a/python/sglang/srt/mem_cache/dsa_cache_layer_split.py b/python/sglang/srt/mem_cache/dsa_cache_layer_split.py index ba1cd1e521552..de83e56413909 100644 --- a/python/sglang/srt/mem_cache/dsa_cache_layer_split.py +++ b/python/sglang/srt/mem_cache/dsa_cache_layer_split.py @@ -234,6 +234,11 @@ def _get_layer_owner_rank(self, layer_id: int) -> int: self._local_layer_idx(layer_id), self.layer_shard_size, self.layer_num ) + def _should_allocate_index_layer(self, local_layer_idx: int) -> bool: + return self._is_layer_owned( + self.start_layer + local_layer_idx + ) and super()._should_allocate_index_layer(local_layer_idx) + def _log_layer_shard_plan(self) -> None: partitions = [] for rank in range(self.layer_shard_size): @@ -551,7 +556,7 @@ def _get_broadcastable_index_buffer(self, layer_id: int) -> torch.Tensor: # ---- HiCache CPU offload: skip empty (non-owned) layers --------------- - def get_cpu_copy(self, indices, mamba_indices=None): + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): from sglang.srt.utils import current_platform current_platform.synchronize() @@ -569,9 +574,23 @@ def get_cpu_copy(self, indices, mamba_indices=None): kv_cache_cpu[-1].append(kv_cpu) current_platform.synchronize() - return {"kv": kv_cache_cpu, "index_k": self.index_key_cache.cpu_copy(indices)} + cpu_copy = { + "kv": kv_cache_cpu, + "index_k": self.index_key_cache.cpu_copy(indices), + } + compress_tail = self._get_compress_tail_cpu_copy(req_pool_index) + if compress_tail is not None: + cpu_copy["tail_k"], cpu_copy["tail_score"] = compress_tail + torch.cuda.synchronize() + return cpu_copy - def load_cpu_copy(self, kv_cache_cpu_dict, indices, mamba_indices=None): + def load_cpu_copy( + self, + kv_cache_cpu_dict, + indices, + mamba_indices=None, + req_pool_index=None, + ): from sglang.srt.utils import current_platform kv_cache_cpu = kv_cache_cpu_dict["kv"] @@ -589,3 +608,9 @@ def load_cpu_copy(self, kv_cache_cpu_dict, indices, mamba_indices=None): current_platform.synchronize() self.index_key_cache.load_cpu_copy(kv_cache_cpu_dict["index_k"], indices) + self._load_compress_tail_cpu_copy( + kv_cache_cpu_dict.get("tail_k"), + kv_cache_cpu_dict.get("tail_score"), + req_pool_index, + ) + torch.cuda.synchronize() diff --git a/python/sglang/srt/mem_cache/hisparse_memory_pool.py b/python/sglang/srt/mem_cache/hisparse_memory_pool.py index 1bf865ca22772..ad45ce76a1781 100644 --- a/python/sglang/srt/mem_cache/hisparse_memory_pool.py +++ b/python/sglang/srt/mem_cache/hisparse_memory_pool.py @@ -115,8 +115,10 @@ def transfer_values_on_device(self, dst_indices, src_indices): num_layers=self.layer_num, ) - def get_cpu_copy(self, indices, mamba_indices=None): + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): raise NotImplementedError("HiSparseDevicePool does not support get_cpu_copy") - def load_cpu_copy(self, kv_cache_cpu, indices, mamba_indices=None): + def load_cpu_copy( + self, kv_cache_cpu, indices, mamba_indices=None, req_pool_index=None + ): raise NotImplementedError("HiSparseDevicePool does not support load_cpu_copy") diff --git a/python/sglang/srt/mem_cache/kv_cache_builder.py b/python/sglang/srt/mem_cache/kv_cache_builder.py index 52b700bc1f0a2..788bf83ba2a5f 100644 --- a/python/sglang/srt/mem_cache/kv_cache_builder.py +++ b/python/sglang/srt/mem_cache/kv_cache_builder.py @@ -24,6 +24,7 @@ class KVCacheBuildResult: from typing import TYPE_CHECKING from sglang.srt.configs.hybrid_arch import ( + glm5_next_config, hybrid_gdn_config, hybrid_lightning_config, kimi_linear_config, @@ -31,6 +32,7 @@ class KVCacheBuildResult: mamba2_config, ) from sglang.srt.configs.model_config import ModelImpl, is_deepseek_dsa +from sglang.srt.disaggregation.utils import should_bypass_dsa_cp_prefix_cache from sglang.srt.environ import envs from sglang.srt.hardware_backend.mlx.runtime import use_mlx from sglang.srt.managers.mm_schedule import init_mm_embedding_cache @@ -104,6 +106,7 @@ def uses_ssm_state(model_config) -> bool: or mamba2_config(model_config) is not None or (spec.uses_mamba_radix_cache if spec is not None else False) or kimi_linear_config(model_config) is not None + or glm5_next_config(model_config) is not None or hybrid_lightning_config(model_config) is not None ) @@ -210,14 +213,24 @@ def build_kv_cache( retraction_backup = resolve_decode_retraction_backup(tp_worker=tp_worker) - disable_radix_cache = get_memory().disable_radix_cache or ( - model_config.is_multimodal and uses_transformers_backend + bypass_dsa_cp_prefix_cache = should_bypass_dsa_cp_prefix_cache(server_args) + disable_radix_cache = ( + get_memory().disable_radix_cache + or (model_config.is_multimodal and uses_transformers_backend) + or bypass_dsa_cp_prefix_cache ) if disable_radix_cache and not get_memory().disable_radix_cache: - logger.warning( - "Radix cache is disabled for multimodal models with the " - "Transformers backend to avoid multimodal prefix-cache mismatches." - ) + if bypass_dsa_cp_prefix_cache: + logger.warning( + "Radix cache is disabled on this PD Prefill worker because DSA " + "Prefill CP requires CP-aware KV-cache resharding. Target-model " + "CP, speculative decoding, and P-to-D transfer remain enabled." + ) + else: + logger.warning( + "Radix cache is disabled for multimodal models with the " + "Transformers backend to avoid multimodal prefix-cache mismatches." + ) # Decode-side radix cache supports SWA only through the unified tree, whose # component pools preserve the full-attention prefix while transferring the diff --git a/python/sglang/srt/mem_cache/kv_cache_configurator.py b/python/sglang/srt/mem_cache/kv_cache_configurator.py index 75821be4df430..c2830428fc3a7 100644 --- a/python/sglang/srt/mem_cache/kv_cache_configurator.py +++ b/python/sglang/srt/mem_cache/kv_cache_configurator.py @@ -18,6 +18,8 @@ ModelConfig, dsa_layer_skips_topk, get_dsa_index_head_dim, + get_dsa_index_kpool, + get_dsa_index_kpool_compress, get_minimax_sparse_attention_config, get_minimax_sparse_disable_value_layer_ids, get_minimax_sparse_layer_ids, @@ -322,6 +324,12 @@ def loc_space_scale(self) -> int: def pool_page_size(self) -> int: return get_schedule().page_size * self.loc_space_scale + def _dsa_pool_geometry(self, max_total_num_tokens: int) -> tuple[int, int]: + physical_page_size = get_schedule().page_size + # Physical page stays 64 for CUDA DSA kernels; only the token pool is grown. + pool_size = max_total_num_tokens + self.pool_page_size - physical_page_size + return pool_size, physical_page_size + def _derive_pool_sizes(self, *, config: MemoryPoolConfig) -> _PoolSizes: max_total_num_tokens = config.max_total_num_tokens max_running_requests = config.max_running_requests @@ -791,6 +799,18 @@ def _build_req_to_token_pool(self, *, max_num_reqs: int) -> ReqToTokenPool: ) return req_to_token_pool + def _get_mamba_layer_ids_for_req_pool(self) -> list: + mamba_layer_ids = [ + i + for i in self.mambaish_config.mamba2_cache_params.layers + if self.layer_info.start_layer <= i < self.layer_info.end_layer + ] + if max_speculative_num_draft_tokens(): + for layer_id in getattr(self.mambaish_config, "nextn_layer_ids", []): + if layer_id not in mamba_layer_ids: + mamba_layer_ids.append(layer_id) + return mamba_layer_ids + def _build_hybrid_mamba_decode_req_pool( self, *, @@ -808,13 +828,7 @@ def _build_hybrid_mamba_decode_req_pool( device=self.device, enable_memory_saver=get_exec().features.enable_memory_saver, cache_params=self.mambaish_config.mamba2_cache_params, - mamba_layer_ids=( - [ - i - for i in self.mambaish_config.mamba2_cache_params.layers - if self.layer_info.start_layer <= i < self.layer_info.end_layer - ] - ), + mamba_layer_ids=self._get_mamba_layer_ids_for_req_pool(), speculative_num_draft_tokens=max_speculative_num_draft_tokens(), speculative_eagle_topk=get_spec().speculative_eagle_topk, enable_mamba_extra_buffer=mamba_extra_buffer_enabled(), @@ -887,13 +901,7 @@ def _build_hybrid_req_pool( device=self.device, enable_memory_saver=get_exec().features.enable_memory_saver, cache_params=self.mambaish_config.mamba2_cache_params, - mamba_layer_ids=( - [ - i - for i in self.mambaish_config.mamba2_cache_params.layers - if self.layer_info.start_layer <= i < self.layer_info.end_layer - ] - ), + mamba_layer_ids=self._get_mamba_layer_ids_for_req_pool(), enable_mamba_extra_buffer=mamba_extra_buffer_enabled(), enable_mamba_extra_buffer_lazy=mamba_extra_buffer_lazy_enabled(), # A PD prefill server never runs TARGET_VERIFY, so skip the @@ -1022,9 +1030,10 @@ def _build_token_to_kv_pool( swa_max_total_num_tokens=sizes.swa_max_total_num_tokens, is_dsa_model=is_dsa_model, ) - elif self.use_mla_backend and is_dsa_model: + elif self.use_mla_backend and is_dsa_model and not self.mambaish_config: token_to_kv_pool = self._build_dsa_kv_pool( max_total_num_tokens=sizes.max_total_num_tokens, + max_running_requests=sizes.max_running_requests, ) elif self.use_mla_backend and not self.mambaish_config: assert not is_dsa_model @@ -1312,9 +1321,14 @@ def _build_ascend_mha_kv_pool(self, *, max_total_num_tokens: int) -> KVCache: ) return token_to_kv_pool - def _build_dsa_kv_pool(self, *, max_total_num_tokens: int) -> KVCache: + def _build_dsa_kv_pool( + self, *, max_total_num_tokens: int, max_running_requests: int + ) -> KVCache: from sglang.srt.layers.cp.utils import get_glm_dsa_cp_layer_shard_info + max_total_num_tokens, pool_page_size = self._dsa_pool_geometry( + max_total_num_tokens + ) ( dsa_cp_layer_shard_rank, dsa_cp_layer_shard_size, @@ -1347,7 +1361,7 @@ def _build_dsa_kv_pool(self, *, max_total_num_tokens: int) -> KVCache: ] token_to_kv_pool = PoolCls( max_total_num_tokens, - page_size=self.pool_page_size, + page_size=pool_page_size, dtype=self.kv_cache_dtype, kv_lora_rank=self.model_config.kv_lora_rank, qk_rope_head_dim=self.model_config.qk_rope_head_dim, @@ -1361,6 +1375,12 @@ def _build_dsa_kv_pool(self, *, max_total_num_tokens: int) -> KVCache: start_layer=self.layer_info.start_layer, end_layer=self.layer_info.end_layer, index_head_dim=get_dsa_index_head_dim(self.model_config.hf_config), + index_kpool=get_dsa_index_kpool(self.model_config.hf_config), + index_kpool_compress=get_dsa_index_kpool_compress( + self.model_config.hf_config + ), + tail_extra_slots=(max_speculative_num_draft_tokens() or 0), + max_running_requests=max_running_requests, **pool_kwargs, ) return token_to_kv_pool @@ -1559,12 +1579,6 @@ def _build_hybrid_linear_kv_pool( req_to_token_pool: ReqToTokenPool, mha_pool_class: type, ) -> KVCache: - extra_args = {} - if self.use_mla_backend: - extra_args = { - "kv_lora_rank": self.model_config.kv_lora_rank, - "qk_rope_head_dim": self.model_config.qk_rope_head_dim, - } full_attention_layer_ids = ( [0] if self.is_draft_worker @@ -1574,6 +1588,50 @@ def _build_hybrid_linear_kv_pool( if self.layer_info.start_layer <= i < self.layer_info.end_layer ] ) + extra_args = {} + if self.use_mla_backend: + extra_args = { + "kv_lora_rank": self.model_config.kv_lora_rank, + "qk_rope_head_dim": self.model_config.qk_rope_head_dim, + } + # Route DSATokenToKVPool in as the hybrid pool's full_kv_pool + # instead of a dense MLA pool. + if is_deepseek_dsa(self.model_config.hf_config): + from sglang.srt.layers.cp.utils import get_glm_dsa_cp_layer_shard_info + + ( + dsa_cp_layer_shard_rank, + dsa_cp_layer_shard_size, + ) = get_glm_dsa_cp_layer_shard_info(self) + dsa_index_kpool = get_dsa_index_kpool(self.model_config.hf_config) + extra_args.update( + use_dsa=True, + index_head_dim=get_dsa_index_head_dim(self.model_config.hf_config), + kv_cache_dim=calculate_mla_kv_cache_dim( + model_config=self.model_config, + kv_cache_dtype=self.kv_cache_dtype, + server_args=self.server_args, + ), + index_kpool=dsa_index_kpool, + index_kpool_compress=get_dsa_index_kpool_compress( + self.model_config.hf_config + ), + layer_shard_rank=dsa_cp_layer_shard_rank, + layer_shard_size=dsa_cp_layer_shard_size, + skip_topk_layers=( + None + if self.is_draft_worker + else [ + dsa_layer_skips_topk(self.model_config.hf_config, layer_id) + for layer_id in full_attention_layer_ids + ] + ), + ) + if dsa_index_kpool > 1: + extra_args.update( + tail_extra_slots=(max_speculative_num_draft_tokens() or 0), + max_running_requests=(req_to_token_pool.req_to_token.shape[0]), + ) quant_method = self._build_fp4_quant_method( num_layers=len(full_attention_layer_ids) ) @@ -2209,14 +2267,21 @@ def calculate_mla_kv_cache_dim( if not is_dsa_model: return kv_cache_dim - # TRTLLM backend does not override kv_cache_dim for MLA kv cache - # Assuming dsa prefill and decode backends are the same when using trtllm MLA backend, - # since it is not compatible for trtllm and other mla attn backend due to the different - # kv cache layout. - if ( - get_exec().kernel.dsa_prefill_backend == "trtllm" - or get_exec().kernel.dsa_decode_backend == "trtllm" - ): + # TRTLLM uses the raw MLA KV layout. In disaggregated serving only the + # backend for the local role determines the local pool layout; the + # inactive role may legitimately have a different default backend. + disaggregation_mode = get_disagg().disaggregation_mode + if disaggregation_mode == "decode": + uses_trtllm_kv_layout = get_exec().kernel.dsa_decode_backend == "trtllm" + elif disaggregation_mode == "prefill": + uses_trtllm_kv_layout = get_exec().kernel.dsa_prefill_backend == "trtllm" + else: + uses_trtllm_kv_layout = ( + get_exec().kernel.dsa_prefill_backend == "trtllm" + or get_exec().kernel.dsa_decode_backend == "trtllm" + ) + + if uses_trtllm_kv_layout: return kv_cache_dim # On HIP, TileLang and AITER DSA kernels consume the raw MLA KV layout: diff --git a/python/sglang/srt/mem_cache/memory_pool.py b/python/sglang/srt/mem_cache/memory_pool.py index 20ec41b0b40cf..16ad8c6722fe2 100644 --- a/python/sglang/srt/mem_cache/memory_pool.py +++ b/python/sglang/srt/mem_cache/memory_pool.py @@ -1417,6 +1417,19 @@ def mamba2_layer_index(self, layer_id: int) -> int: def mamba2_layer_cache(self, layer_id: int): return self.mamba_pool.mamba2_layer_cache(self.mamba2_layer_index(layer_id)) + def copy_mamba_state( + self, src_index: torch.Tensor, dst_index: torch.Tensor + ) -> None: + if src_index.numel() == 0: + return + if ( + self.layer_transfer_counter is not None + and self.layer_transfer_counter.consumer_index >= 0 + ): + last_mamba_layer = max(self.mamba_map) + self.layer_transfer_counter.wait_until(last_mamba_layer - self.start_layer) + self.mamba_pool.copy_from(src_index, dst_index) + def get_speculative_mamba2_params_all_layers(self) -> MambaPool.SpeculativeState: return self.mamba_pool.get_speculative_mamba2_params_all_layers() @@ -1561,6 +1574,10 @@ def free_mamba_cache( req.mamba_ping_pong_track_buffer = None req.mamba_next_track_idx = None req.mamba_last_track_idx = None + req.mamba_last_track_seqlen = None + req.mamba_branching_seqlen = None + req.mamba_cow_src_index = None + req.mamba_needs_clear = False def clear(self): logger.info("Reset HybridReqToTokenPool") @@ -1761,10 +1778,12 @@ def set_kv_buffer( def register_layer_transfer_counter(self, layer_transfer_counter: LayerDoneCounter): self.layer_transfer_counter = layer_transfer_counter - def get_cpu_copy(self, indices, mamba_indices=None): + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): raise NotImplementedError() - def load_cpu_copy(self, kv_cache_cpu, indices, mamba_indices=None): + def load_cpu_copy( + self, kv_cache_cpu, indices, mamba_indices=None, req_pool_index=None + ): raise NotImplementedError() def get_kv_cache_quant_method(self) -> Any: @@ -2263,7 +2282,7 @@ def get_contiguous_buf_infos(self): item_lens = [d.item_len_bytes(self.page_size) for d in self._kv_buffer_descs] return ptrs, lens, item_lens - def get_cpu_copy(self, indices, mamba_indices=None): + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): assert not self.use_hnd, ( "CPU KV offload indexes by slot (NHD); HND KV cache " "(SGLANG_USE_HND_KVCACHE) is not supported with CPU offload yet." @@ -2285,7 +2304,9 @@ def get_cpu_copy(self, indices, mamba_indices=None): current_platform.synchronize() return kv_cache_cpu - def load_cpu_copy(self, kv_cache_cpu, indices, mamba_indices=None): + def load_cpu_copy( + self, kv_cache_cpu, indices, mamba_indices=None, req_pool_index=None + ): assert not self.use_hnd, ( "CPU KV offload indexes by slot (NHD); HND KV cache " "(SGLANG_USE_HND_KVCACHE) is not supported with CPU offload yet." @@ -3304,13 +3325,15 @@ def get_contiguous_buf_infos(self): "with a page-aware transfer scheme)." ) - def get_cpu_copy(self, indices, mamba_indices=None): + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): raise NotImplementedError( "CPU offloading is unsupported under the page-major layout " "(TODO: split token ids into page/slot for the 4-D index)." ) - def load_cpu_copy(self, kv_cache_cpu, indices, mamba_indices=None): + def load_cpu_copy( + self, kv_cache_cpu, indices, mamba_indices=None, req_pool_index=None + ): raise NotImplementedError( "CPU offloading is unsupported under the page-major layout " "(TODO: split token ids into page/slot for the 4-D index)." @@ -3705,7 +3728,17 @@ def __init__( use_mla: bool = False, kv_lora_rank: int = None, qk_rope_head_dim: int = None, + use_dsa: bool = False, + index_head_dim: Optional[int] = None, + kv_cache_dim: Optional[int] = None, + index_kpool: int = 1, + index_kpool_compress: bool = False, + tail_extra_slots: int = 0, + max_running_requests: Optional[int] = None, + skip_topk_layers: Optional[List[bool]] = None, start_layer: Optional[int] = None, + layer_shard_rank: Optional[int] = None, + layer_shard_size: int = 1, full_kv_pool_class: Optional[type] = None, quant_method=None, # When provided (shared-KV-pool path), use this pool for the @@ -3731,6 +3764,7 @@ def __init__( # identity for a static pool, `translate_kv_loc_dense` for the unified pool. self._full_translate = lambda ids: ids self.use_mla = use_mla + self.use_dsa = use_dsa if full_kv_pool is not None: # Shared-KV-pool path: the caller built a UnifiedMHATokenToKVPool # aliasing the shared byte buffer. @@ -3776,6 +3810,41 @@ def __init__( **quant_method_kwarg, **post_capture_kwargs, ) + elif use_dsa: + # DSA sparse full-attention layers share the MLA latent layout and + # additionally keep a paged index_k cache. Only full-attn layer count + # is allocated here; the wrapper translates global layer_id to dense. + assert ( + index_head_dim is not None and kv_cache_dim is not None + ), "HybridLinearKVPool with use_dsa requires index_head_dim and kv_cache_dim" + pool_kwargs = {} + DSAPoolCls = DSATokenToKVPool + if layer_shard_rank is not None and layer_shard_size > 1: + from sglang.srt.mem_cache.dsa_cache_layer_split import ( + LayerSplitDSATokenToKVPool, + ) + + DSAPoolCls = LayerSplitDSATokenToKVPool + pool_kwargs["layer_shard_rank"] = layer_shard_rank + pool_kwargs["layer_shard_size"] = layer_shard_size + self.full_kv_pool = DSAPoolCls( + size=size, + page_size=self.page_size, + kv_lora_rank=kv_lora_rank, + dtype=dtype, + qk_rope_head_dim=qk_rope_head_dim, + layer_num=self.full_layer_nums, + device=device, + index_head_dim=index_head_dim, + enable_memory_saver=enable_memory_saver, + kv_cache_dim=kv_cache_dim, + index_kpool=index_kpool, + index_kpool_compress=index_kpool_compress, + tail_extra_slots=tail_extra_slots, + max_running_requests=max_running_requests, + skip_topk_layers=skip_topk_layers, + **pool_kwargs, + ) else: TokenToKVPoolClass = MLATokenToKVPool @@ -3820,6 +3889,60 @@ def finalize_backing(self, config) -> None: self.full_kv_pool._finalize_backing_tokens(config.max_total_num_tokens) self.size = int(config.max_total_num_tokens) + @property + def dsa_kv_cache_store_fp8(self) -> bool: + return getattr(self.full_kv_pool, "dsa_kv_cache_store_fp8", False) + + @property + def kv_cache_dim(self): + return getattr(self.full_kv_pool, "kv_cache_dim", None) + + @property + def index_head_dim(self) -> Optional[int]: + return getattr(self.full_kv_pool, "index_head_dim", None) + + @property + def quant_block_size(self) -> Optional[int]: + return getattr(self.full_kv_pool, "quant_block_size", None) + + @property + def index_kpool(self) -> int: + return getattr(self.full_kv_pool, "index_kpool", 1) + + @property + def index_kpool_compress(self) -> bool: + return bool(getattr(self.full_kv_pool, "index_kpool_compress", False)) + + @property + def tail_extra_slots(self) -> int: + return getattr(self.full_kv_pool, "tail_extra_slots", 0) + + @property + def slots_per_page(self) -> int: + return getattr(self.full_kv_pool, "slots_per_page", self.page_size) + + @property + def layer_shard_enabled(self) -> bool: + return bool(getattr(self.full_kv_pool, "layer_shard_enabled", False)) + + @property + def layer_shard_rank(self) -> Optional[int]: + return getattr(self.full_kv_pool, "layer_shard_rank", None) + + @property + def layer_shard_size(self) -> int: + return getattr(self.full_kv_pool, "layer_shard_size", 1) + + @property + def layer_shard_start(self) -> int: + return getattr(self.full_kv_pool, "layer_shard_start", self.start_layer) + + def _is_layer_owned(self, layer_id: int) -> bool: + if not self.layer_shard_enabled: + return True + full_layer_id = self._transfer_full_attention_id(layer_id) + return self.full_kv_pool._is_layer_owned(full_layer_id) + def get_kv_size_bytes(self): return self.full_kv_pool.get_kv_size_bytes() @@ -3984,8 +4107,8 @@ def set_kv_buffer( def move_kv_cache(self, tgt_loc: torch.Tensor, src_loc: torch.Tensor): self.full_kv_pool.move_kv_cache(tgt_loc, src_loc) - def get_cpu_copy(self, indices, mamba_indices=None): - kv_cpu = self.full_kv_pool.get_cpu_copy(indices) + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): + kv_cpu = self.full_kv_pool.get_cpu_copy(indices, req_pool_index=req_pool_index) # mamba_pool stores PHYSICAL ids; translate the (unified-pool virtual) ids first. mamba_cpu = ( self.mamba_pool.get_cpu_copy(self._mamba_translate(mamba_indices)) @@ -3994,9 +4117,11 @@ def get_cpu_copy(self, indices, mamba_indices=None): ) return kv_cpu, mamba_cpu - def load_cpu_copy(self, cache_cpu, indices, mamba_indices=None): + def load_cpu_copy( + self, cache_cpu, indices, mamba_indices=None, req_pool_index=None + ): kv_cpu, mamba_cpu = cache_cpu - self.full_kv_pool.load_cpu_copy(kv_cpu, indices) + self.full_kv_pool.load_cpu_copy(kv_cpu, indices, req_pool_index=req_pool_index) if mamba_cpu is not None and mamba_indices is not None: self.mamba_pool.load_cpu_copy( mamba_cpu, self._mamba_translate(mamba_indices) @@ -4029,6 +4154,14 @@ def set_mla_kv_buffer( with self._transfer_id_context(layer): self.full_kv_pool.set_mla_kv_buffer(layer, loc, cache_k_nope, cache_k_rope) + def prefetch_full_attention_kv_buffer(self, layer_id: int) -> None: + if not self.use_mla or not hasattr(self.full_kv_pool, "prefetch_kv_buffer"): + return + if layer_id not in self.full_attention_layer_id_mapping: + return + full_layer_id = self._transfer_full_attention_id(layer_id) + self.full_kv_pool.prefetch_kv_buffer(full_layer_id) + def get_mla_kv_buffer( self, layer: RadixAttention, @@ -4040,6 +4173,145 @@ def get_mla_kv_buffer( with self._transfer_id_context(layer): return self.full_kv_pool.get_mla_kv_buffer(layer, loc, dst_dtype) + def set_index_k_scale_buffer( + self, + layer_id: int, + loc: torch.Tensor, + index_k: torch.Tensor, + index_k_scale: torch.Tensor, + ) -> None: + assert self.use_dsa, "set_index_k_scale_buffer called when use_dsa is False" + layer_id = self._transfer_full_attention_id(layer_id) + self.full_kv_pool.set_index_k_scale_buffer( + layer_id, loc, index_k, index_k_scale + ) + + def get_index_k_with_scale_buffer(self, layer_id: int) -> torch.Tensor: + assert ( + self.use_dsa + ), "get_index_k_with_scale_buffer called when use_dsa is False" + self._wait_for_layer(layer_id) + layer_id = self._transfer_full_attention_id(layer_id) + return self.full_kv_pool.get_index_k_with_scale_buffer(layer_id) + + def get_broadcastable_index_k_with_scale_buffer( + self, layer_id: int + ) -> torch.Tensor: + assert ( + self.use_dsa + ), "get_broadcastable_index_k_with_scale_buffer called when use_dsa is False" + self._wait_for_layer(layer_id) + layer_id = self._transfer_full_attention_id(layer_id) + if hasattr(self.full_kv_pool, "_get_broadcastable_index_buffer"): + return self.full_kv_pool._get_broadcastable_index_buffer(layer_id) + return self.full_kv_pool.get_index_k_with_scale_buffer(layer_id) + + def invalidate_index_buffer_for_layer(self, layer_id: int) -> None: + if not self.use_dsa or not hasattr( + self.full_kv_pool, "invalidate_index_buffer_for_layer" + ): + return + layer_id = self._transfer_full_attention_id(layer_id) + self.full_kv_pool.invalidate_index_buffer_for_layer(layer_id) + + def get_index_k_continuous( + self, + layer_id: int, + seq_len: int, + page_indices: torch.Tensor, + ): + assert self.use_dsa, "get_index_k_continuous called when use_dsa is False" + self._wait_for_layer(layer_id) + layer_id = self._transfer_full_attention_id(layer_id) + return self.full_kv_pool.get_index_k_continuous(layer_id, seq_len, page_indices) + + def get_index_k_scale_continuous( + self, + layer_id: int, + seq_len: int, + page_indices: torch.Tensor, + ): + assert self.use_dsa, "get_index_k_scale_continuous called when use_dsa is False" + self._wait_for_layer(layer_id) + layer_id = self._transfer_full_attention_id(layer_id) + return self.full_kv_pool.get_index_k_scale_continuous( + layer_id, seq_len, page_indices + ) + + def get_index_k_scale_buffer( + self, + layer_id: int, + seq_len_tensor: torch.Tensor, + page_indices: torch.Tensor, + seq_len_sum: int, + max_seq_len: int, + ): + assert self.use_dsa, "get_index_k_scale_buffer called when use_dsa is False" + self._wait_for_layer(layer_id) + layer_id = self._transfer_full_attention_id(layer_id) + return self.full_kv_pool.get_index_k_scale_buffer( + layer_id, seq_len_tensor, page_indices, seq_len_sum, max_seq_len + ) + + def get_compress_tail_buffers( + self, layer_id: int + ) -> Tuple[torch.Tensor, torch.Tensor]: + assert self.use_dsa, "get_compress_tail_buffers called when use_dsa is False" + layer_id = self._transfer_full_attention_id(layer_id) + return self.full_kv_pool.get_compress_tail_buffers(layer_id) + + def kpool_decode_update_index_cache( + self, + layer_id: int, + key: torch.Tensor, + slot_score: torch.Tensor, + ape: torch.Tensor, + block_tables: torch.Tensor, + req_pool_indices: torch.Tensor, + positions: torch.Tensor, + seq_lens: torch.Tensor, + out_cache_loc: torch.Tensor, + round_scale: bool = False, + ) -> None: + assert ( + self.use_dsa + ), "kpool_decode_update_index_cache called when use_dsa is False" + layer_id = self._transfer_full_attention_id(layer_id) + self.full_kv_pool.kpool_decode_update_index_cache( + layer_id=layer_id, + key=key, + slot_score=slot_score, + ape=ape, + block_tables=block_tables, + req_pool_indices=req_pool_indices, + positions=positions, + seq_lens=seq_lens, + out_cache_loc=out_cache_loc, + round_scale=round_scale, + ) + + def set_compress_tail_for_request( + self, + layer_id: int, + req_pool_idx: torch.Tensor, + key_tail: torch.Tensor, + score_tail: torch.Tensor, + n_remain: int, + dst_logical_start: int, + ) -> None: + assert ( + self.use_dsa + ), "set_compress_tail_for_request called when use_dsa is False" + layer_id = self._transfer_full_attention_id(layer_id) + self.full_kv_pool.set_compress_tail_for_request( + layer_id=layer_id, + req_pool_idx=req_pool_idx, + key_tail=key_tail, + score_tail=score_tail, + n_remain=n_remain, + dst_logical_start=dst_logical_start, + ) + class MLATokenToKVPool(KVCache): def __init__( @@ -4221,10 +4493,12 @@ def _write_mla_kv_buffer( else: if cache_k_nope.dtype != self.dtype: cache_k_nope = cache_k_nope.to(self.dtype) - cache_k_rope = cache_k_rope.to(self.dtype) + if cache_k_rope is not None and cache_k_rope.numel() > 0: + cache_k_rope = cache_k_rope.to(self.dtype) if self.store_dtype != self.dtype: cache_k_nope = cache_k_nope.view(self.store_dtype) - cache_k_rope = cache_k_rope.view(self.store_dtype) + if cache_k_rope is not None and cache_k_rope.numel() > 0: + cache_k_rope = cache_k_rope.view(self.store_dtype) set_mla_kv_buffer_triton( dst_buffer, @@ -4273,11 +4547,14 @@ def get_mla_kv_buffer( dtype=dst_dtype, device=kv_buffer.device, ) - cache_k_rope = torch.empty( - (loc.shape[0], 1, self.qk_rope_head_dim), - dtype=dst_dtype, - device=kv_buffer.device, - ) + if self.qk_rope_head_dim == 0: + cache_k_rope = None + else: + cache_k_rope = torch.empty( + (loc.shape[0], 1, self.qk_rope_head_dim), + dtype=dst_dtype, + device=kv_buffer.device, + ) get_mla_kv_buffer_triton(kv_buffer, loc, cache_k_nope, cache_k_rope) return cache_k_nope, cache_k_rope @@ -4295,12 +4572,14 @@ def move_kv_cache(self, tgt_loc: torch.Tensor, src_loc: torch.Tensor): for kv_cache in self.kv_buffer: kv_cache[tgt_loc_flat] = kv_cache[src_loc_flat] - def get_cpu_copy(self, indices, mamba_indices=None): + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): current_platform.synchronize() kv_cache_cpu = [] chunk_size = self.cpu_offloading_chunk_size for layer_id in range(self.layer_num): kv_cache_cpu.append([]) + if self.kv_buffer[layer_id].shape[0] == 0: + continue for i in range(0, len(indices), chunk_size): chunk_indices = indices[i : i + chunk_size] kv_cpu = self.kv_buffer[layer_id][chunk_indices].to( @@ -4310,10 +4589,14 @@ def get_cpu_copy(self, indices, mamba_indices=None): current_platform.synchronize() return kv_cache_cpu - def load_cpu_copy(self, kv_cache_cpu, indices, mamba_indices=None): + def load_cpu_copy( + self, kv_cache_cpu, indices, mamba_indices=None, req_pool_index=None + ): current_platform.synchronize() chunk_size = self.cpu_offloading_chunk_size for layer_id in range(self.layer_num): + if self.kv_buffer[layer_id].shape[0] == 0: + continue for i in range(0, len(indices), chunk_size): chunk_indices = indices[i : i + chunk_size] kv_cpu = kv_cache_cpu[layer_id][i // chunk_size] @@ -4441,13 +4724,18 @@ def set_mla_kv_buffer( cache_k_nope_fp4, cache_k_nope_fp4_sf = ( FP4MXBlock16KVQuantizeUtil.batched_quantize(cache_k_nope) ) - cache_k_rope_fp4, cache_k_rope_fp4_sf = ( - FP4MXBlock16KVQuantizeUtil.batched_quantize(cache_k_rope) - ) + if cache_k_rope is not None and cache_k_rope.numel() > 0: + cache_k_rope_fp4, cache_k_rope_fp4_sf = ( + FP4MXBlock16KVQuantizeUtil.batched_quantize(cache_k_rope) + ) + else: + cache_k_rope_fp4 = None + cache_k_rope_fp4_sf = None if self.store_dtype != self.dtype: cache_k_nope = cache_k_nope.view(self.store_dtype) - cache_k_rope = cache_k_rope.view(self.store_dtype) + if cache_k_rope is not None and cache_k_rope.numel() > 0: + cache_k_rope = cache_k_rope.view(self.store_dtype) set_mla_kv_buffer_triton( self.kv_buffer[layer_id - self.start_layer], @@ -4483,6 +4771,10 @@ def __init__( start_layer: Optional[int] = None, end_layer: Optional[int] = None, index_buf_size: Optional[int] = None, + index_kpool: int = 1, + index_kpool_compress: bool = False, + tail_extra_slots: int = 0, + max_running_requests: Optional[int] = None, skip_topk_layers: Optional[List[bool]] = None, ): override_dim = ( @@ -4506,6 +4798,10 @@ def __init__( # self.index_k_dtype = torch.float8_e4m3fn # self.index_k_scale_dtype = torch.float32 self.index_head_dim = index_head_dim + self.index_kpool = index_kpool + self.index_kpool_compress = index_kpool_compress + self.tail_extra_slots = tail_extra_slots + self.slots_per_page = self.page_size if index_buf_size is None: index_buf_size = size self.index_buf_size = index_buf_size @@ -4531,19 +4827,181 @@ def __init__( else: assert self.page_size == 64 self.index_key_cache = self._create_index_key_cache() + self._init_kpool_compress_tail_buffers( + index_kpool=index_kpool, + index_kpool_compress=index_kpool_compress, + tail_extra_slots=tail_extra_slots, + index_head_dim=index_head_dim, + layer_num=layer_num, + device=device, + max_running_requests=max_running_requests, + ) self._finalize_allocation_log(size) def _create_index_key_cache(self) -> IndexKeyCache: return IndexKeyCache(self, self.index_buf_size) + def _should_allocate_index_layer(self, local_layer_idx: int) -> bool: + return not self.skip_topk_layers[local_layer_idx] + @property def index_k_with_scale_buffer(self): # Preserve direct HiCache access while storage lives behind the facade. return self.index_key_cache.buffer + def _init_kpool_compress_tail_buffers( + self, + index_kpool: int, + index_kpool_compress: bool, + tail_extra_slots: int, + index_head_dim: int, + layer_num: int, + device: str, + max_running_requests: Optional[int], + ) -> None: + """In-flight per-request bf16 key/score tail buffers; kept on the pool, not the Indexer, because they are part of the index cache state.""" + self.kpool_use_compress = index_kpool > 1 and index_kpool_compress + + if not self.kpool_use_compress: + self._compress_tail_k = None + self._compress_tail_score = None + return + + assert ( + max_running_requests is not None + ), "DSATokenToKVPool with kpool compress requires max_running_requests" + # +1 mirrors req_to_token_pool.size + 1 used by the indexer to + # provide an extra slot for invalid / sentinel req indices. + req_pool_size = max_running_requests + 1 + tail_dtype = torch.bfloat16 + tail_width = index_kpool + tail_extra_slots + with ( + torch.cuda.use_mem_pool(self.custom_mem_pool) + if self.custom_mem_pool + else nullcontext() + ): + self._compress_tail_k: Optional[List[torch.Tensor]] = [ + torch.zeros( + req_pool_size if self._should_allocate_index_layer(i) else 0, + tail_width, + index_head_dim, + dtype=tail_dtype, + device=device, + ) + for i in range(layer_num) + ] + self._compress_tail_score: Optional[List[torch.Tensor]] = [ + torch.zeros( + req_pool_size if self._should_allocate_index_layer(i) else 0, + tail_width, + index_head_dim, + dtype=tail_dtype, + device=device, + ) + for i in range(layer_num) + ] + + def get_compress_tail_buffers( + self, layer_id: int + ) -> Tuple[torch.Tensor, torch.Tensor]: + assert ( + self.kpool_use_compress + ), "get_compress_tail_buffers called when kpool compress is disabled" + idx = layer_id - self.start_layer + return ( + self._compress_tail_k[idx], + self._compress_tail_score[idx], + ) + + def get_compress_tail_buf_infos(self): + """Buffer infos for per-request DSA kpool compress-tail rows.""" + if not self.kpool_use_compress: + return [], [], [] + if self.layer_shard_enabled: + transfer_layer_ids = [ + i + for i in range(self.layer_num) + if self._is_layer_owned(self.start_layer + i) + ] + else: + transfer_layer_ids = list(range(self.layer_num)) + # Keep zero-row indexShare entries in the pointer list so layer offsets + # stay aligned across PD peers; item_len=0 makes transfer backends skip them. + tail_buffers = [self._compress_tail_k[i] for i in transfer_layer_ids] + [ + self._compress_tail_score[i] for i in transfer_layer_ids + ] + data_ptrs = [buf.data_ptr() for buf in tail_buffers] + data_lens = [buf.nbytes for buf in tail_buffers] + item_lens = [buf[0].nbytes if buf.shape[0] > 0 else 0 for buf in tail_buffers] + return data_ptrs, data_lens, item_lens + + def kpool_decode_update_index_cache( + self, + layer_id: int, + key: torch.Tensor, + slot_score: torch.Tensor, + ape: torch.Tensor, + block_tables: torch.Tensor, + req_pool_indices: torch.Tensor, + positions: torch.Tensor, + seq_lens: torch.Tensor, + out_cache_loc: torch.Tensor, + round_scale: bool = False, + ) -> None: + from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( + kpool_decode_update_and_maybe_write_cache, + ) + + assert ( + self.kpool_use_compress + ), "kpool_decode_update_index_cache called when kpool compress is disabled" + idx = layer_id - self.start_layer + buf = self.get_index_k_with_scale_buffer(layer_id) + kpool_decode_update_and_maybe_write_cache( + pool=self, + buf=buf, + tail_k=self._compress_tail_k[idx], + tail_score=self._compress_tail_score[idx], + key=key, + slot_score=slot_score, + ape=ape, + block_tables=block_tables, + req_pool_indices=req_pool_indices, + positions=positions, + seq_lens=seq_lens, + out_cache_loc=out_cache_loc, + round_scale=round_scale, + ) + + def set_compress_tail_for_request( + self, + layer_id: int, + req_pool_idx: torch.Tensor, + key_tail: torch.Tensor, + score_tail: torch.Tensor, + n_remain: int, + dst_logical_start: int, + ) -> None: + """Overwrite per-request tail ring rows after a chunk. ``n_remain == 0`` + means the chunk landed on a pool boundary, no tail carries over.""" + assert ( + self.kpool_use_compress + ), "set_compress_tail_for_request called when kpool compress is disabled" + idx = layer_id - self.start_layer + if n_remain > 0: + slots = ( + torch.arange(n_remain, device=key_tail.device, dtype=torch.long) + + int(dst_logical_start) + ) % self._compress_tail_k[idx].shape[1] + self._compress_tail_k[idx][req_pool_idx, slots] = key_tail + self._compress_tail_score[idx][req_pool_idx, slots] = score_tail + def _clear_buffers(self): super()._clear_buffers() self.index_key_cache.clear() + if hasattr(self, "_compress_tail_k") and self._compress_tail_k is not None: + del self._compress_tail_k + del self._compress_tail_score def move_kv_cache(self, tgt_loc: torch.Tensor, src_loc: torch.Tensor): """Move latent KV and the DSA indexer cache (key + scale) in lockstep.""" @@ -4592,15 +5050,82 @@ def set_index_k_scale_buffer( ) -> None: self.index_key_cache.store_quantized(layer_id, loc, index_k, index_k_scale) - def get_cpu_copy(self, indices, mamba_indices=None): + def _get_compress_tail_cpu_copy(self, req_pool_index): + if not self.kpool_use_compress or req_pool_index is None: + return None + + tail_k_cpu = [] + tail_score_cpu = [] + for tail_k, tail_score in zip(self._compress_tail_k, self._compress_tail_score): + if tail_k.shape[0] == 0: + tail_k_cpu.append(None) + tail_score_cpu.append(None) + continue + tail_k_cpu.append(tail_k[req_pool_index].to("cpu", non_blocking=True)) + tail_score_cpu.append( + tail_score[req_pool_index].to("cpu", non_blocking=True) + ) + return tail_k_cpu, tail_score_cpu + + def _load_compress_tail_cpu_copy(self, tail_k_cpu, tail_score_cpu, req_pool_index): + if ( + not self.kpool_use_compress + or req_pool_index is None + or tail_k_cpu is None + or tail_score_cpu is None + ): + return + + for tail_k, tail_score, saved_k, saved_score in zip( + self._compress_tail_k, + self._compress_tail_score, + tail_k_cpu, + tail_score_cpu, + ): + if tail_k.shape[0] == 0 or saved_k is None or saved_score is None: + continue + tail_k[req_pool_index] = saved_k.to(tail_k.device, non_blocking=True) + tail_score[req_pool_index] = saved_score.to( + tail_score.device, non_blocking=True + ) + + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): + # DSA keeps a page-indexed index_k_with_scale_buffer alongside kv_buffer. + # Retract frees the slots/pages and they get reused by other reqs' + # set_index_k_scale_buffer, so we must offload it here too -- otherwise + # resume restores kv_buffer but leaves foreign index/scale in place and + # DSA attention reads garbage at those token positions. kv_cache_cpu = super().get_cpu_copy(indices, mamba_indices=mamba_indices) - return {"kv": kv_cache_cpu, "index_k": self.index_key_cache.cpu_copy(indices)} + cpu_copy = { + "kv": kv_cache_cpu, + "index_k": self.index_key_cache.cpu_copy(indices), + } + compress_tail = self._get_compress_tail_cpu_copy(req_pool_index) + if compress_tail is not None: + cpu_copy["tail_k"], cpu_copy["tail_score"] = compress_tail + torch.cuda.synchronize() + return cpu_copy - def load_cpu_copy(self, kv_cache_cpu_dict, indices, mamba_indices=None): + def load_cpu_copy( + self, + kv_cache_cpu_dict, + indices, + mamba_indices=None, + req_pool_index=None, + ): super().load_cpu_copy( - kv_cache_cpu_dict["kv"], indices, mamba_indices=mamba_indices + kv_cache_cpu_dict["kv"], + indices, + mamba_indices=mamba_indices, + req_pool_index=req_pool_index, ) self.index_key_cache.load_cpu_copy(kv_cache_cpu_dict["index_k"], indices) + self._load_compress_tail_cpu_copy( + kv_cache_cpu_dict.get("tail_k"), + kv_cache_cpu_dict.get("tail_score"), + req_pool_index, + ) + torch.cuda.synchronize() def get_state_buf_infos(self): return self.index_key_cache.state_buf_infos() diff --git a/python/sglang/srt/mem_cache/radix_cache.py b/python/sglang/srt/mem_cache/radix_cache.py index 60ec95137ef5e..e2e14c0b7958f 100644 --- a/python/sglang/srt/mem_cache/radix_cache.py +++ b/python/sglang/srt/mem_cache/radix_cache.py @@ -180,10 +180,22 @@ def _check_compatible(self, other: RadixKey) -> None: def match(self, other: RadixKey, page_size: int = 1) -> int: """Logical-unit prefix length shared with ``other``. Result is rounded down to ``page_size``.""" + return self.match_at(other, offset=0, page_size=page_size) + + def match_at(self, other: RadixKey, offset: int, page_size: int = 1) -> int: + """Match this key against ``other`` starting at a logical offset. + + This is the no-copy equivalent of ``self.match(other[offset:])`` and + preserves bigram boundary-token semantics and ``limit`` handling. + """ self._check_compatible(other) + if self.is_bigram != other.is_bigram: + raise ValueError("RadixKey operations require matching bigram modes") + if offset < 0 or offset > len(other): + raise IndexError(f"RadixKey offset out of range: {offset}") t0, t1 = self.token_ids, other.token_ids assert type(t0) is type(t1), (type(t0), type(t1)) - n = min(len(t0), len(t1)) + n = min(self._raw_len(), other._raw_len() - offset) # Exponential search for the first diverging token: gallop in doubling # windows (one C-level slice compare each), then binary-search the window @@ -193,10 +205,10 @@ def match(self, other: RadixKey, page_size: int = 1) -> int: step = 1 while lo < n: hi = lo + step if lo + step < n else n - if t0[lo:hi] != t1[lo:hi]: + if t0[lo:hi] != t1[offset + lo : offset + hi]: while hi - lo > 1: mid = (lo + hi) // 2 - if t0[lo:mid] == t1[lo:mid]: + if t0[lo:mid] == t1[offset + lo : offset + mid]: lo = mid else: hi = mid @@ -206,24 +218,37 @@ def match(self, other: RadixKey, page_size: int = 1) -> int: step *= 2 if self.is_bigram: - matched = max(0, min(matched_tokens - 1, len(self), len(other))) + matched = max(0, min(matched_tokens - 1, len(self), len(other) - offset)) return (matched // page_size) * page_size if page_size > 1 else matched - matched_tokens = min(matched_tokens, len(self), len(other)) + matched_tokens = min(matched_tokens, len(self), len(other) - offset) if page_size == 1: return matched_tokens return (matched_tokens // page_size) * page_size def child_key(self, page_size: int = 1): """Hashable dict-key for the first ``page_size`` logical units, namespaced by ``extra_key``.""" + return self.child_key_at(offset=0, page_size=page_size) + + def child_key_at(self, offset: int, page_size: int = 1): + """Hashable child key at ``offset`` without slicing token storage.""" + if offset < 0 or offset + page_size > len(self): + raise IndexError( + f"RadixKey child range out of bounds: offset={offset}, " + f"page_size={page_size}, len={len(self)}" + ) t = self.token_ids if self.is_bigram: if page_size == 1: - plain = (t[0], t[1]) + plain = (t[offset], t[offset + 1]) else: - plain = tuple((t[j], t[j + 1]) for j in range(page_size)) + plain = tuple( + (t[j], t[j + 1]) for j in range(offset, offset + page_size) + ) else: - plain = t[0] if page_size == 1 else tuple(t[:page_size]) + plain = ( + t[offset] if page_size == 1 else tuple(t[offset : offset + page_size]) + ) if self.cache_salt is not None: return ((self.extra_key, self.cache_salt), plain) return plain if self.extra_key is None else (self.extra_key, plain) diff --git a/python/sglang/srt/mem_cache/swa_memory_pool.py b/python/sglang/srt/mem_cache/swa_memory_pool.py index e934baf6daf93..373e353722904 100644 --- a/python/sglang/srt/mem_cache/swa_memory_pool.py +++ b/python/sglang/srt/mem_cache/swa_memory_pool.py @@ -357,10 +357,12 @@ def _filter_swa_cpu_copy(self, swa_kv_cpu, row_mask: torch.Tensor): filtered.append(filtered_layer) return filtered - def get_cpu_copy(self, indices, mamba_indices=None): + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): # For SWA, we need to copy KV cache from both full and SWA pools # The indices are for the full pool, and we use mapping to get SWA indices - full_kv_cpu = self.full_kv_pool.get_cpu_copy(indices) + full_kv_cpu = self.full_kv_pool.get_cpu_copy( + indices, req_pool_index=req_pool_index + ) swa_mask = None if self.full_to_swa_index_mapping is not None: @@ -379,14 +381,18 @@ def get_cpu_copy(self, indices, mamba_indices=None): return {"full": full_kv_cpu, "swa": swa_kv_cpu, "swa_mask": swa_mask} - def load_cpu_copy(self, kv_cache_cpu, indices, mamba_indices=None): + def load_cpu_copy( + self, kv_cache_cpu, indices, mamba_indices=None, req_pool_index=None + ): # Load KV cache back from CPU to both full and SWA pools # Note: indices here are NEW indices (newly allocated), different from get_cpu_copy indices full_kv_cpu = kv_cache_cpu["full"] swa_kv_cpu = kv_cache_cpu["swa"] # Load full KV cache to the new indices - self.full_kv_pool.load_cpu_copy(full_kv_cpu, indices) + self.full_kv_pool.load_cpu_copy( + full_kv_cpu, indices, req_pool_index=req_pool_index + ) # Load SWA KV cache if it exists if swa_kv_cpu is not None and self.full_to_swa_index_mapping is not None: diff --git a/python/sglang/srt/mem_cache/unified_cache/unified_tree_core.py b/python/sglang/srt/mem_cache/unified_cache/unified_tree_core.py index a50d4fd27ee04..51fd934734ff6 100644 --- a/python/sglang/srt/mem_cache/unified_cache/unified_tree_core.py +++ b/python/sglang/srt/mem_cache/unified_cache/unified_tree_core.py @@ -677,7 +677,8 @@ def _match_prefix_helper(self, key: RadixKey) -> tuple[ # nodes can also match, so we separately track the best device-resident # match for scheduler prefix indices and locking. node = self.root_node - child_key = key.child_key(self.page_size) + key_offset = 0 + child_key = key.child_key_at(key_offset, self.page_size) value: list[torch.Tensor] = [] best_match_node = node best_match_device_node = node @@ -718,14 +719,14 @@ def _update_best_if_valid(node): best_match_device_value_len = len(value) best_match_device_node = node - while len(key) > 0 and child_key in node.children: + while key_offset < len(key) and child_key in node.children: child = node.children[child_key] # HiCache: dead node (evicted + not backuped) — stop traversal if child.evicted and not child.backuped: break - prefix_len = child.key.match(key, page_size=self.page_size) + prefix_len = child.key.match_at(key, key_offset, page_size=self.page_size) full_kv_hit_length += prefix_len if prefix_len < len(child.key): node, action = self._split_node(child.key, child, prefix_len) @@ -738,9 +739,9 @@ def _update_best_if_valid(node): value.append(child.component_data[BASE_COMPONENT_TYPE].value) node = child _update_best_if_valid(node) - key = key[prefix_len:] - if len(key): - child_key = key.child_key(self.page_size) + key_offset += prefix_len + if key_offset < len(key): + child_key = key.child_key_at(key_offset, self.page_size) return ( value, diff --git a/python/sglang/srt/mem_cache/unified_memory_pool.py b/python/sglang/srt/mem_cache/unified_memory_pool.py index 194a8a91d7e6e..c46bb7065ed67 100644 --- a/python/sglang/srt/mem_cache/unified_memory_pool.py +++ b/python/sglang/srt/mem_cache/unified_memory_pool.py @@ -1542,23 +1542,29 @@ def _virt_tokens_to_phys_tokens( phys_pages = allocator.virtual_to_physical[virt_pages] return phys_pages * ps + offsets - def get_cpu_copy(self, indices, mamba_indices=None): + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): assert self._full_allocator is not None assert self._swa_allocator is not None # `indices` are virtual TOKEN ids; translate per sub-pool. full_phys = self._virt_tokens_to_phys_tokens(indices, self._full_allocator) swa_phys = self._virt_tokens_to_phys_tokens(indices, self._swa_allocator) - full_cpu = self.full_kv_pool.get_cpu_copy(full_phys) + full_cpu = self.full_kv_pool.get_cpu_copy( + full_phys, req_pool_index=req_pool_index + ) valid = swa_phys >= 0 swa_cpu = None if bool(valid.any().item()): swa_cpu = self.swa_kv_pool.get_cpu_copy(swa_phys[valid]) return {"full": full_cpu, "swa": swa_cpu} - def load_cpu_copy(self, kv_cache_cpu, indices, mamba_indices=None): + def load_cpu_copy( + self, kv_cache_cpu, indices, mamba_indices=None, req_pool_index=None + ): assert self._full_allocator is not None full_phys = self._virt_tokens_to_phys_tokens(indices, self._full_allocator) - self.full_kv_pool.load_cpu_copy(kv_cache_cpu["full"], full_phys) + self.full_kv_pool.load_cpu_copy( + kv_cache_cpu["full"], full_phys, req_pool_index=req_pool_index + ) if kv_cache_cpu.get("swa") is not None: assert self._swa_allocator is not None swa_phys = self._virt_tokens_to_phys_tokens(indices, self._swa_allocator) diff --git a/python/sglang/srt/model_executor/forward_batch_info.py b/python/sglang/srt/model_executor/forward_batch_info.py index 85e8157e0e923..eca682e9093c1 100644 --- a/python/sglang/srt/model_executor/forward_batch_info.py +++ b/python/sglang/srt/model_executor/forward_batch_info.py @@ -56,6 +56,7 @@ get_lora, get_parallel, ) +from sglang.srt.speculative.spec_info import SpecInputType from sglang.srt.utils import ( is_cpu, is_cuda, @@ -1660,6 +1661,26 @@ def post_forward_mlp_sync_batch(self, logits_output: LogitsProcessorOutput): logits_output.hidden_states = logits_output.hidden_states[ :num_tokens ] + elif ( + self.spec_info.spec_input_type == SpecInputType.EAGLE_DRAFT_EXTEND + and not self.forward_mode.is_draft_extend_v2() + ): + if self.spec_info.num_correct_drafts is not None: + self.spec_info.num_correct_drafts = ( + self.spec_info.num_correct_drafts[:bs] + ) + if self.spec_info.num_accept_tokens is not None: + self.spec_info.num_accept_tokens = self.spec_info.num_accept_tokens[ + :bs + ] + if self.extend_seq_lens is not None: + self.extend_seq_lens = self.extend_seq_lens[:bs] + if logits_output.next_token_logits is not None: + logits_output.next_token_logits = logits_output.next_token_logits[ + :bs + ] + if logits_output.hidden_states is not None: + logits_output.hidden_states = logits_output.hidden_states[:bs] elif self.forward_mode.is_draft_extend_v2(): # draft extend_v2 bs = bs * self.spec_info.num_tokens_per_req if logits_output.next_token_logits is not None: diff --git a/python/sglang/srt/model_executor/model_runner.py b/python/sglang/srt/model_executor/model_runner.py index d4d6e3e54f246..610cf12edd4fd 100644 --- a/python/sglang/srt/model_executor/model_runner.py +++ b/python/sglang/srt/model_executor/model_runner.py @@ -182,6 +182,7 @@ get_spec, is_ep_joiner, is_ep_scale_joiner, + max_speculative_num_draft_tokens, remote_instance_transfer_engine_enabled, set_global_dwdp_manager, ) @@ -821,6 +822,11 @@ def max_decode_logits_rows(self) -> int: """Rows the shared logits buffer needs.""" num_tokens_per_req = self.decode_num_tokens_per_req() capture_bs, _ = get_batch_sizes_to_capture(self, num_tokens_per_req) + # Adaptive gears capture wider draft-extend/verify graphs after this + # buffer is allocated; size it for the widest gear up front. + num_tokens_per_req = max( + num_tokens_per_req, max_speculative_num_draft_tokens() or 0 + ) return max(capture_bs) * num_tokens_per_req def alloc_memory_pool(self, memory_pool_config: Optional[MemoryPoolConfig] = None): @@ -1657,7 +1663,7 @@ def _maybe_execute_deferred_mamba_cow_and_clear( ) else: # mamba_pool is a pure PHYSICAL store; translate both COW slot ids. - pool.mamba_pool.copy_from( + pool.copy_mamba_state( pool.translate_mamba_indices(forward_batch.mamba_cow_src_indices), pool.translate_mamba_indices(forward_batch.mamba_cow_dst_indices), ) diff --git a/python/sglang/srt/model_executor/model_runner_components/spec_aux_hidden_state.py b/python/sglang/srt/model_executor/model_runner_components/spec_aux_hidden_state.py index 61a2a573b4173..5da3730c25b90 100644 --- a/python/sglang/srt/model_executor/model_runner_components/spec_aux_hidden_state.py +++ b/python/sglang/srt/model_executor/model_runner_components/spec_aux_hidden_state.py @@ -57,6 +57,7 @@ def resolve_spec_aux_hidden_state_config( _resolve_eagle_aux_hidden_state( config=config, server_args=server_args, + model_config=model_config, spec_algorithm=spec_algorithm, is_draft_worker=is_draft_worker, ) @@ -74,55 +75,54 @@ def _resolve_eagle_aux_hidden_state( *, config: SpecAuxHiddenStateConfig, server_args: ServerArgs, + model_config: ModelConfig, spec_algorithm: SpeculativeAlgorithm, is_draft_worker: bool, ) -> None: - if ( + if not ( (spec_algorithm.is_eagle() or spec_algorithm.is_standalone()) and not is_draft_worker - and get_spec().speculative_draft_model_path ): - # Load draft config to get layer count for KV cache sizing + return + + draft_model_config = model_config + if get_spec().speculative_draft_model_path: draft_model_config = ModelConfig.from_server_args( server_args, model_path=get_spec().speculative_draft_model_path, model_revision=get_spec().speculative_draft_model_revision, is_draft_model=True, ) - num_nextn_predict_layers = draft_model_config.num_nextn_predict_layers - if num_nextn_predict_layers is not None: - config.eagle_draft_num_layers = int(num_nextn_predict_layers) - else: - config.eagle_draft_num_layers = int( - max( - draft_model_config.num_hidden_layers, - draft_model_config.num_attention_layers, - ) + num_nextn_predict_layers = draft_model_config.num_nextn_predict_layers + if num_nextn_predict_layers is not None: + config.eagle_draft_num_layers = int(num_nextn_predict_layers) + elif get_spec().speculative_draft_model_path: + config.eagle_draft_num_layers = int( + max( + draft_model_config.num_hidden_layers, + draft_model_config.num_attention_layers, ) + ) + else: + return - if ( - draft_model_config.is_hybrid_swa - and not draft_model_config.is_deepseek_v4_arch - ): - config.eagle_draft_swa_num_layers = len( - draft_model_config.swa_attention_layer_ids - ) + if draft_model_config.is_hybrid_swa and not draft_model_config.is_deepseek_v4_arch: + config.eagle_draft_swa_num_layers = len( + draft_model_config.swa_attention_layer_ids + ) - if spec_algorithm.is_eagle3(): - config.eagle_use_aux_hidden_state = True - try: - eagle_config = getattr( - draft_model_config.hf_config, "eagle_config", None - ) - config.eagle_use_aux_hidden_state = eagle_config.get( - "use_aux_hidden_state", True - ) - config.eagle_aux_hidden_state_layer_ids = eagle_config[ - "eagle_aux_hidden_state_layer_ids" - ] - except: - # if there is no aux layer, set to None - config.eagle_aux_hidden_state_layer_ids = None + if spec_algorithm.is_eagle3(): + config.eagle_use_aux_hidden_state = True + try: + eagle_config = getattr(draft_model_config.hf_config, "eagle_config", None) + config.eagle_use_aux_hidden_state = eagle_config.get( + "use_aux_hidden_state", True + ) + config.eagle_aux_hidden_state_layer_ids = eagle_config[ + "eagle_aux_hidden_state_layer_ids" + ] + except Exception: + config.eagle_aux_hidden_state_layer_ids = None def _resolve_dflash_aux_hidden_state( diff --git a/python/sglang/srt/model_executor/pool_configurator.py b/python/sglang/srt/model_executor/pool_configurator.py index 3f40b902b81a0..6168d37440ee6 100644 --- a/python/sglang/srt/model_executor/pool_configurator.py +++ b/python/sglang/srt/model_executor/pool_configurator.py @@ -101,6 +101,55 @@ def _dflash_draft_cell_size(kvc: KVCacheConfigurator) -> int: return int(cell_size) * get_parallel().attn_dcp_size +def _get_dsa_cache_layer_ids(kvc: KVCacheConfigurator, num_layers: int) -> list[int]: + """Global layer ids represented by the local DSA pool's dense layer slots.""" + if kvc.mambaish_config and not kvc.is_draft_worker: + layer_ids = [ + layer_id + for layer_id in kvc.mambaish_config.full_attention_layer_ids + if kvc.layer_info.start_layer <= layer_id < kvc.layer_info.end_layer + ] + else: + layer_ids = list(range(kvc.layer_info.start_layer, kvc.layer_info.end_layer)) + # Draft pools and a few platform-specific pools may expose a synthetic layer + # count. They do not use indexShare, so only the length matters for sizing. + if len(layer_ids) != num_layers: + return list(range(num_layers)) + return layer_ids + + +def _get_dsa_indexer_effective_num_layers( + kvc: KVCacheConfigurator, cache_layer_ids: list[int] +) -> int: + """Indexer buffers materialized per rank, including split remote scratch.""" + enable_hisparse = kvc.server_args.enable_hisparse + if enable_hisparse or kvc.is_draft_worker: + included_layers = [True] * len(cache_layer_ids) + else: + included_layers = [ + not dsa_layer_skips_topk(kvc.model_config.hf_config, layer_id) + for layer_id in cache_layer_ids + ] + + from sglang.srt.layers.cp.utils import ( + get_glm_dsa_cp_layer_shard_info, + get_layer_shard_range, + ) + + layer_shard_rank, shard_size = get_glm_dsa_cp_layer_shard_info(kvc) + if enable_hisparse or layer_shard_rank is None: + return sum(included_layers) + + # All ranks must derive the same token capacity. Use the maximum number of + # non-skipped owned layers across shards, then account for the one full-size + # remote indexer scratch buffer allocated by LayerSplitDSATokenToKVPool. + max_owned_layers = 0 + for rank in range(shard_size): + start, end = get_layer_shard_range(rank, shard_size, len(cache_layer_ids)) + max_owned_layers = max(max_owned_layers, sum(included_layers[start:end])) + return max(1, max_owned_layers + 1) + + def _get_dsv4_compress_state_dtype_sizes() -> tuple[int, int]: dtype_name = envs.SGLANG_DSV4_COMPRESS_STATE_DTYPE.get().strip().lower() if dtype_name in ("float32", "fp32"): @@ -199,16 +248,23 @@ def __init__(self, kvc: KVCacheConfigurator): target_kv_num_layers = get_glm_dsa_layer_split_effective_num_layers( kvc, num_layers ) - draft_kv_size = int( - target_kv_size * draft_num_layers / target_kv_num_layers + # Draft pools are DCP-replicated, not sharded: budget all copies. + dcp_size = kvc.ps.attn_dcp_size + draft_kv_size = ( + int(target_kv_size * draft_num_layers / target_kv_num_layers) + * dcp_size ) - draft_indexer_size = self._compute_dsa_indexer_cell_size( - kvc=kvc, - num_layers=draft_num_layers, - allocate_all_layers=True, + draft_indexer_size = ( + self._compute_dsa_indexer_cell_size( + kvc=kvc, + num_layers=draft_num_layers, + allocate_all_layers=True, + ) + * dcp_size ) self._cell_size += draft_kv_size + draft_indexer_size else: + draft_num_layers *= kvc.ps.attn_dcp_size self._cell_size = int( self._cell_size * (1 + draft_num_layers / int(num_layers)) ) @@ -242,8 +298,14 @@ def _compute_cell_size(self, kvc: KVCacheConfigurator, num_layers: int) -> int: get_glm_dsa_layer_split_effective_num_layers, ) - effective_num_layers = get_glm_dsa_layer_split_effective_num_layers( - kvc, num_layers + effective_num_layers = ( + num_layers + if kvc.server_args.enable_hisparse + else get_glm_dsa_layer_split_effective_num_layers(kvc, num_layers) + ) + + from sglang.srt.mem_cache.kv_cache_configurator import ( + calculate_mla_kv_cache_dim, ) kv_size = torch._utils._element_size(kv_cache_dtype) @@ -379,35 +441,10 @@ def _compute_dsa_indexer_cell_size( ): num_indexer_layers = num_layers else: - active_indexer_layers = [ - layer_id - for layer_id in range( - kvc.layer_info.start_layer, kvc.layer_info.end_layer - ) - if not dsa_layer_skips_topk(kvc.model_config.hf_config, layer_id) - ] - from sglang.srt.layers.cp.utils import ( - get_glm_dsa_cp_layer_shard_info, - get_layer_shard_range, + num_indexer_layers = _get_dsa_indexer_effective_num_layers( + kvc, _get_dsa_cache_layer_ids(kvc, num_layers) ) - _, shard_size = get_glm_dsa_cp_layer_shard_info(kvc) - if shard_size > 1: - active_set = set(active_indexer_layers) - max_owned = 0 - for rank in range(shard_size): - start, end = get_layer_shard_range(rank, shard_size, num_layers) - max_owned = max( - max_owned, - sum( - kvc.layer_info.start_layer + i in active_set - for i in range(start, end) - ), - ) - num_indexer_layers = max_owned + 1 - else: - num_indexer_layers = len(active_indexer_layers) - return int( indexer_size_per_token * num_indexer_layers * element_size * indexer_ratio ) @@ -539,6 +576,10 @@ def __init__(self, kvc: KVCacheConfigurator): - self._draft_swa_layers_num - self._draft_swa_full_layers_num ) + dcp_size = kvc.ps.attn_dcp_size + self._draft_swa_layers_num *= dcp_size + self._draft_swa_full_layers_num *= dcp_size + self._draft_full_layers_num *= dcp_size self._draft_cell_size = _dflash_draft_cell_size(kvc) diff --git a/python/sglang/srt/model_executor/runner/eager_runner.py b/python/sglang/srt/model_executor/runner/eager_runner.py index 83caa44d6de65..b05335a20bb20 100644 --- a/python/sglang/srt/model_executor/runner/eager_runner.py +++ b/python/sglang/srt/model_executor/runner/eager_runner.py @@ -281,8 +281,12 @@ def _execute_extend( or cp_v2_active or forward_batch.forward_mode.is_target_verify() ): - if model_runner.ps.attn_dcp_size > 1 and hasattr( - model_runner.model, "prepare_context_parallel_metadata_for_dcp" + if ( + model_runner.ps.attn_dcp_size > 1 + and not forward_batch.forward_mode.is_target_verify() + and hasattr( + model_runner.model, "prepare_context_parallel_metadata_for_dcp" + ) ): # prepare kv cache buffer for dcp to gather kv cache forward_batch.attn_dcp_metadata = ( diff --git a/python/sglang/srt/model_executor/runner/prefill_cuda_graph_runner.py b/python/sglang/srt/model_executor/runner/prefill_cuda_graph_runner.py index b10ca8f093c32..0f3e1961317c2 100644 --- a/python/sglang/srt/model_executor/runner/prefill_cuda_graph_runner.py +++ b/python/sglang/srt/model_executor/runner/prefill_cuda_graph_runner.py @@ -995,14 +995,17 @@ def _init_forward_metadata_for_capture( and stash the returned per-bucket metadata object; otherwise fall back to the generic eager init that BCG/TC_PIECEWISE use today.""" attn_backend = self.model_runner.attn_backend - if not self.use_captured_attn_metadata: - attn_backend.init_forward_metadata(forward_batch) - return - metadata = attn_backend.init_forward_metadata_for_breakable_cuda_graph_capture( - forward_batch - ) - assert self.attn_metadata_buffers is not None - self.attn_metadata_buffers[num_tokens] = metadata + with forward_context(ForwardContext(attn_backend=attn_backend)): + if not self.use_captured_attn_metadata: + attn_backend.init_forward_metadata(forward_batch) + return + metadata = ( + attn_backend.init_forward_metadata_for_breakable_cuda_graph_capture( + forward_batch + ) + ) + assert self.attn_metadata_buffers is not None + self.attn_metadata_buffers[num_tokens] = metadata def _prepare_forward_metadata_for_replay( self, diff --git a/python/sglang/srt/model_executor/runner_backend_utils/breakable_cuda_graph/breakable_cuda_graph.py b/python/sglang/srt/model_executor/runner_backend_utils/breakable_cuda_graph/breakable_cuda_graph.py index 59f4a2e6b4d0d..19ae1cf5d6690 100644 --- a/python/sglang/srt/model_executor/runner_backend_utils/breakable_cuda_graph/breakable_cuda_graph.py +++ b/python/sglang/srt/model_executor/runner_backend_utils/breakable_cuda_graph/breakable_cuda_graph.py @@ -153,16 +153,18 @@ def _uninstall_wait_stream_hook(): def _weak_ref_if_tensor(x): - """Return a weak-ref tensor view (shared storage, no refcount) for tensors; - recurse into tuples/lists; pass-through for non-tensors. Weak-ref'ing - captured args lets the shared mempool reclaim per-layer intermediates - between segments — storage stays alive for each segment CUDAGraph's - lifetime via its pool use_count. + """Return a weak-ref view for nonempty accelerator tensors; recurse into + tuples/lists and keep CPU, empty, and non-tensor values unchanged. + Weak-ref'ing captured args lets the shared mempool reclaim per-layer + intermediates between segments — storage stays alive for each segment + CUDAGraph's lifetime via its pool use_count. weak_ref_tensors is imported lazily because it hard-raises on platforms without a CUDA/HIP/NPU backend; we only reach this code during an active Breakable capture, which runs only on those backends.""" if torch.is_tensor(x): + if x.numel() == 0 or x.device.type == "cpu": + return x from sglang.srt.compilation.weak_ref_tensor import weak_ref_tensors return weak_ref_tensors(x) diff --git a/python/sglang/srt/model_loader/loader.py b/python/sglang/srt/model_loader/loader.py index 23481b31f5b14..a0fcd472a7fe9 100644 --- a/python/sglang/srt/model_loader/loader.py +++ b/python/sglang/srt/model_loader/loader.py @@ -261,7 +261,11 @@ def _get_quantization_config( f"method {model_config.quantization}. Supported dtypes: " f"{supported_dtypes}" ) - hf_to_sglang_mapper = getattr(model_class, "hf_to_sglang_mapper", None) + get_hf_to_sglang_mapper = getattr(model_class, "get_hf_to_sglang_mapper", None) + if get_hf_to_sglang_mapper is not None: + hf_to_sglang_mapper = get_hf_to_sglang_mapper(model_config.hf_config) + else: + hf_to_sglang_mapper = getattr(model_class, "hf_to_sglang_mapper", None) # pass mappings by reference to quant_config if hf_to_sglang_mapper is not None and quant_config is not None: quant_config.apply_weight_name_mapper(hf_to_sglang_mapper) diff --git a/python/sglang/srt/model_loader/weight_utils.py b/python/sglang/srt/model_loader/weight_utils.py index 965123fcc6b89..561f045e945bd 100644 --- a/python/sglang/srt/model_loader/weight_utils.py +++ b/python/sglang/srt/model_loader/weight_utils.py @@ -1523,11 +1523,18 @@ def row_parallel_weight_loader( LoaderFunction = Callable[[torch.Tensor, torch.Tensor], torch.Tensor] -def sharded_weight_loader(shard_axis: int) -> LoaderFunction: +def sharded_weight_loader( + shard_axis: int, + tp_rank_getter=None, +) -> LoaderFunction: """Create a weight loader that shards the weights along the given axis""" def loader(param: torch.Tensor, loaded_weight: torch.Tensor) -> None: - tp_rank = get_parallel().attn_tp_rank + tp_rank = ( + tp_rank_getter() + if tp_rank_getter is not None + else get_parallel().attn_tp_rank + ) shard_size = param.data.shape[shard_axis] start_idx = tp_rank * shard_size diff --git a/python/sglang/srt/models/deepseek_common/attention_backend_handler.py b/python/sglang/srt/models/deepseek_common/attention_backend_handler.py index 9a2a60120990f..eaae9997c73ba 100644 --- a/python/sglang/srt/models/deepseek_common/attention_backend_handler.py +++ b/python/sglang/srt/models/deepseek_common/attention_backend_handler.py @@ -110,9 +110,9 @@ def _handle_attention_backend(attn, forward_batch, backend_name): return _dispatch_mla_subtype(attn, forward_batch) sum_extend_prefix_lens = _get_sum_extend_prefix_lens(forward_batch) - disable_ragged = ( - backend_name in ["flashinfer", "flashmla"] - ) and attn.flashinfer_mla_disable_ragged + disable_ragged = (backend_name in ["flashinfer", "flashmla"]) and ( + attn.flashinfer_mla_disable_ragged or attn.qk_rope_head_dim == 0 + ) if ( not disable_ragged diff --git a/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha.py b/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha.py index 01e66499a58c7..b680fbfe5e10f 100644 --- a/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha.py +++ b/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha.py @@ -7,13 +7,16 @@ from sglang.kernels.ops.attention.dsa.dequant_k_cache import dequantize_k_cache_paged from sglang.kernels.ops.attention.utils import concat_and_cast_mha_k_triton from sglang.srt.environ import envs +from sglang.srt.layers.attention.dsa.utils import dsa_use_prefill_cp from sglang.srt.layers.attention.tbo_backend import TboAttnBackend from sglang.srt.layers.communicator import get_attn_tp_context +from sglang.srt.layers.cp.utils import is_cp_v2_active from sglang.srt.layers.dcp import ( all_gather_kv_cache_for_mha_chunk_extend, all_gather_kv_cache_for_mha_extend, filter_dcp_local_kv_indices, ) +from sglang.srt.layers.utils.cp_utils import mla_use_prefill_cp from sglang.srt.model_executor.forward_batch_info import ForwardBatch from sglang.srt.model_executor.forward_context import ( get_attn_backend, @@ -424,18 +427,34 @@ def _set_mla_kv_buffer( k_pe: torch.Tensor, forward_batch: ForwardBatch, ): + if ( + dsa_use_prefill_cp(forward_batch, self.dsa_enable_prefill_cp) + or mla_use_prefill_cp(forward_batch, self.mla_enable_prefill_cp) + ) and not is_cp_v2_active(forward_batch): + # CP-v1 keeps Q rank-local, but every rank owns a complete KV pool. + # Rebuild the zigzag-split latent KV in global token order before + # writing it with the (unsplit) out_cache_loc indices. + kv_a, k_pe = self.rebuild_cp_kv_cache( + latent_cache.squeeze(1), + forward_batch, + kv_a.unsqueeze(1), + k_pe, + ) + else: + kv_a = kv_a.unsqueeze(1) + if _is_cuda: # Save latent cache get_token_to_kv_pool().set_mla_kv_buffer( - self.attn_mha, forward_batch.out_cache_loc, kv_a.unsqueeze(1), k_pe + self.attn_mha, forward_batch.out_cache_loc, kv_a, k_pe ) elif _is_npu: # To reduce a time-costing split operation get_token_to_kv_pool().set_kv_buffer( - self.attn_mha, forward_batch.out_cache_loc, kv_a.unsqueeze(1), k_pe + self.attn_mha, forward_batch.out_cache_loc, kv_a, k_pe ) else: - latent_cache[:, :, : self.kv_lora_rank] = kv_a.unsqueeze(1) + latent_cache[:, :, : self.kv_lora_rank] = kv_a latent_cache[:, :, self.kv_lora_rank :] = k_pe.clone() # Save latent cache @@ -510,9 +529,22 @@ def _get_mla_kv_buffer_from_fp8_for_dsa( def _concat_and_cast_mha_k( self: DeepseekV2AttentionMLA, k_nope: torch.Tensor, - k_pe: torch.Tensor, + k_pe: torch.Tensor | None, forward_batch: ForwardBatch, ): + if self.qk_rope_head_dim == 0: + assert k_pe is None or k_pe.shape[-1] == 0 + k = k_nope.contiguous() + if ( + _is_cuda + and self.current_attention_backend == "fa3" + and self.kv_cache_dtype != "auto" + ): + # fa3 requires k in the pool dtype when KV cache is fp8; the + # concat branch below does the same cast for roped models. + k = k.to(get_token_to_kv_pool().dtype) + return k + # Temporary for DeepSeek V3/R1 only, but can generalize if needed k_shape = (k_nope.shape[0], self.num_local_heads, self.qk_head_dim) if ( diff --git a/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mla.py b/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mla.py index 3e02ed9de6bc7..807ee1cd45bd2 100644 --- a/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mla.py +++ b/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mla.py @@ -927,6 +927,8 @@ def _fuse_rope_for_trtllm_mla( """ Check if we should skip rope and do fused rope+quantize for TRTLLM MLA decode in fp8_e4m3 path. """ + if self.rotary_emb is None: + return False if self.current_attention_backend in ("dsa", "nsa"): return ( get_exec().kernel.dsa_decode_backend == "trtllm" diff --git a/python/sglang/srt/models/deepseek_common/deepseek_weight_loader.py b/python/sglang/srt/models/deepseek_common/deepseek_weight_loader.py index 4d17d45e9f97d..3ad60dbfccfd5 100644 --- a/python/sglang/srt/models/deepseek_common/deepseek_weight_loader.py +++ b/python/sglang/srt/models/deepseek_common/deepseek_weight_loader.py @@ -529,7 +529,7 @@ def post_load_weights( for name in weight_names: if "kv_b_proj" in name: layer_id = int(name.split(".")[2]) - if layer_id < self.config.num_hidden_layers: + if self.model.start_layer <= layer_id < self.model.end_layer: layer_ids.add(layer_id) for layer_id in layer_ids: @@ -539,6 +539,9 @@ def post_load_weights( else self.model.decoder.self_attn ) + if not hasattr(self_attn, "kv_b_proj"): + continue + if hasattr(self_attn.kv_b_proj, "qweight"): # awq compatible, dequantize the weight if supported awq_dequantize_f = awq_dequantize_func() diff --git a/python/sglang/srt/models/deepseek_nextn.py b/python/sglang/srt/models/deepseek_nextn.py index 517b37e8693b4..06976d5366c25 100644 --- a/python/sglang/srt/models/deepseek_nextn.py +++ b/python/sglang/srt/models/deepseek_nextn.py @@ -47,7 +47,7 @@ cp_all_gather_rerange_output, cp_split_and_rebuild_data, cp_split_and_rebuild_position, - is_mla_prefill_cp_enabled, + is_prefill_context_parallel_enabled, mla_use_prefill_cp, prepare_context_parallel_metadata, ) @@ -169,7 +169,7 @@ def __init__( self.quant_config = quant_config self.dsa_enable_prefill_cp = is_dsa_enable_prefill_cp() self.mla_enable_prefill_cp = ( - is_mla_prefill_cp_enabled() and not is_deepseek_dsa(config) + is_prefill_context_parallel_enabled() and not is_deepseek_dsa(config) ) if self.dsa_enable_prefill_cp or self.mla_enable_prefill_cp: self.cp_size = get_parallel().attn_cp_size @@ -183,6 +183,7 @@ def __init__( is_nextn=True, prefix=add_prefix(layer_name, prefix), alt_stream=self.alt_stream, + skip_rope=config.qk_rope_head_dim == 0, dsa_enable_prefill_cp=self.dsa_enable_prefill_cp, mla_enable_prefill_cp=self.mla_enable_prefill_cp, ) @@ -321,6 +322,10 @@ class DeepseekV3ForCausalLMNextN(DeepseekV3ForCausalLM): }, ) + @classmethod + def get_hf_to_sglang_mapper(cls, config) -> WeightsMapper: + return cls.hf_to_sglang_mapper + def _resolve_nextn_quant_config(self, config, quant_config): if quant_config is None or quant_config.get_name() != "quark": return quant_config @@ -328,7 +333,7 @@ def _resolve_nextn_quant_config(self, config, quant_config): from sglang.srt.layers.quantization.quark.utils import should_ignore_layer ckpt_prefix = f"model.layers.{config.num_hidden_layers}" - mapped_prefix = self.hf_to_sglang_mapper._map_name(ckpt_prefix) + mapped_prefix = self.get_hf_to_sglang_mapper(config)._map_name(ckpt_prefix) if should_ignore_layer(mapped_prefix, quant_config.exclude_layers): return None return quant_config @@ -348,7 +353,9 @@ def __init__( self.determine_num_fused_shared_experts() self.use_dsa = is_deepseek_dsa(config) self.dsa_enable_prefill_cp = is_dsa_enable_prefill_cp() - self.mla_enable_prefill_cp = is_mla_prefill_cp_enabled() and not self.use_dsa + self.mla_enable_prefill_cp = ( + is_prefill_context_parallel_enabled() and not self.use_dsa + ) if self.dsa_enable_prefill_cp or self.mla_enable_prefill_cp: self.cp_rank = get_parallel().attn_cp_rank self.cp_size = get_parallel().attn_cp_size diff --git a/python/sglang/srt/models/deepseek_v2.py b/python/sglang/srt/models/deepseek_v2.py index 8bafc13e0eccc..c18e0a351c16f 100644 --- a/python/sglang/srt/models/deepseek_v2.py +++ b/python/sglang/srt/models/deepseek_v2.py @@ -45,6 +45,7 @@ compute_mla_mscale_scaling, dsa_layer_skips_topk, get_dsa_index_head_dim, + get_dsa_index_kpool, get_dsa_index_n_heads, get_dsa_index_topk, is_deepseek_dsa, @@ -62,6 +63,7 @@ from sglang.srt.layers.activation import SiluAndMul from sglang.srt.layers.amx_utils import PackWeightMethod from sglang.srt.layers.attention.dsa.dsa_indexer import Indexer +from sglang.srt.layers.attention.dsa.dsa_indexer_kpool import IndexerKPool from sglang.srt.layers.attention.dsa.utils import ( can_dsa_cp_split, dsa_use_prefill_cp, @@ -1848,7 +1850,10 @@ def __init__( if not self.skip_topk or is_nextn: is_neox_style = not getattr(config, "indexer_rope_interleave", False) - self.indexer = Indexer( + indexer_cls = ( + IndexerKPool if get_dsa_index_kpool(config) > 1 else Indexer + ) + indexer_kwargs = dict( hidden_size=hidden_size, index_n_heads=get_dsa_index_n_heads(config), index_head_dim=get_dsa_index_head_dim(config), @@ -1867,6 +1872,9 @@ def __init__( alt_stream=alt_stream, config=config, ) + if indexer_cls is IndexerKPool: + indexer_kwargs["skip_rope"] = skip_rope + self.indexer = indexer_cls(**indexer_kwargs) self.kv_b_proj = ColumnParallelLinear( self.kv_lora_rank, @@ -1890,7 +1898,7 @@ def __init__( ) self.kv_a_layernorm = RMSNorm(self.kv_lora_rank, eps=config.rms_norm_eps) - if not skip_rope: + if not skip_rope and qk_rope_head_dim > 0: is_neox_style = not getattr(config, "rope_interleave", True) self.rotary_emb = get_rope_wrapper( qk_rope_head_dim, @@ -2307,6 +2315,7 @@ def __init__( is_nextn: bool = False, prefix: str = "", alt_stream: Optional[torch.cuda.Stream] = None, + skip_rope: bool = False, dsa_enable_prefill_cp: bool = False, mla_enable_prefill_cp: bool = False, ) -> None: @@ -2329,6 +2338,10 @@ def __init__( self.mla_enable_prefill_cp = mla_enable_prefill_cp self.layer_id = layer_id self.is_nextn = is_nextn + if is_nextn and getattr(config, "mla_nope", False): + # The NextN draft must match the NoPE target layers, or its Q/K + # and the KV it verifies against live in different spaces. + skip_rope = True self.self_attn = DeepseekV2AttentionMLA( config=config, hidden_size=self.hidden_size, @@ -2348,6 +2361,7 @@ def __init__( reduce_results=False, prefix=add_prefix("self_attn", prefix), alt_stream=alt_stream, + skip_rope=skip_rope, is_nextn=is_nextn, dsa_enable_prefill_cp=dsa_enable_prefill_cp, mla_enable_prefill_cp=mla_enable_prefill_cp, @@ -2678,6 +2692,7 @@ def __init__( quant_config=quant_config, prefix=prefix, alt_stream=self.alt_stream, + skip_rope=config.qk_rope_head_dim == 0, dsa_enable_prefill_cp=self.dsa_enable_prefill_cp, mla_enable_prefill_cp=self.mla_enable_prefill_cp, ), diff --git a/python/sglang/srt/models/glm5_next.py b/python/sglang/srt/models/glm5_next.py new file mode 100644 index 0000000000000..a2ef6bbf10ddd --- /dev/null +++ b/python/sglang/srt/models/glm5_next.py @@ -0,0 +1,1825 @@ +import logging +from contextlib import nullcontext +from functools import partial +from typing import Any, Dict, Iterable, List, Optional, Tuple, Union + +import torch +from torch import nn +from torch.nn import functional as F + +from sglang.kernels.ops.attention.fla.fused_norm_gate import FusedRMSNormGated +from sglang.kernels.ops.layernorm.mhc import hc_post as _hc_post_fn +from sglang.kernels.ops.layernorm.mhc import hc_pre as _hc_pre_fn +from sglang.srt.batch_overlap.two_batch_overlap import ( + model_forward_maybe_tbo, +) +from sglang.srt.configs.glm5_next import Glm5NextConfig, Glm5NextTextConfig +from sglang.srt.configs.model_config import is_deepseek_dsa +from sglang.srt.distributed.parallel_state import get_pp_group +from sglang.srt.distributed.utils import divide +from sglang.srt.environ import envs +from sglang.srt.eplb.expert_distribution import ( + get_global_expert_distribution_recorder, +) +from sglang.srt.eplb.expert_location import ModelConfigForExpertLocation +from sglang.srt.layers.attention import vision_utils +from sglang.srt.layers.attention.dsa.utils import ( + can_dsa_cp_split, + cp_plain_all_gather, + cp_plain_reduce_scatter, + cp_plain_split, + cp_plain_to_scattered, + cp_scattered_to_plain, + cp_split_and_rebuild_position, + dsa_use_prefill_cp, + is_dsa_enable_prefill_cp, +) +from sglang.srt.layers.attention.vision import VisionAttention +from sglang.srt.layers.communicator import ( + LayerCommunicator, + LayerScatterModes, + enable_moe_dense_fully_dp, + get_attn_tp_context, +) +from sglang.srt.layers.communicator_dsa_cp import DSACPLayerCommunicator +from sglang.srt.layers.communicator_mhc import MHCLayerCommunicator +from sglang.srt.layers.communicator_mhc_hybrid_cp import ( + MHCHybridDSACPLayerCommunicator, +) +from sglang.srt.layers.dcp.planner import prepare_decode_context_parallel_metadata +from sglang.srt.layers.layernorm import RMSNorm +from sglang.srt.layers.linear import ( + ColumnParallelBatchedLinear, + ColumnParallelLinear, + MergedColumnParallelLinear, + MergedColumnParallelRepeatedLinear, + QKVParallelLinear, + ReplicatedLinear, + RowParallelLinear, +) +from sglang.srt.layers.logits_processor import LogitsProcessor +from sglang.srt.layers.moe.fused_moe_triton.layer import FusedMoE +from sglang.srt.layers.moe.utils import get_moe_a2a_backend +from sglang.srt.layers.quantization.base_config import QuantizationConfig +from sglang.srt.layers.radix_linear_attention import RadixLinearAttention +from sglang.srt.layers.rotary_embedding import get_rope +from sglang.srt.layers.utils.common import PPMissingLayer +from sglang.srt.layers.utils.cp_utils import ( + can_cp_split, + is_prefill_context_parallel_enabled, + mla_use_prefill_cp, + prepare_context_parallel_metadata, +) +from sglang.srt.layers.vocab_parallel_embedding import ( + ParallelLMHead, + VocabParallelEmbedding, + get_embedding_tp_kwargs, +) +from sglang.srt.managers.mm_utils import ( + MultiModalityDataPaddingPatternMultimodalTokens, + general_mm_embed_routine, +) +from sglang.srt.managers.schedule_batch import MultimodalDataItem, MultimodalInputs +from sglang.srt.model_executor.cuda_graph_config import ( + Backend, + Phase, + check_cuda_graph_backend, +) +from sglang.srt.model_executor.forward_batch_info import ( + ForwardBatch, + PPProxyTensors, +) +from sglang.srt.model_loader.weight_utils import ( + default_weight_loader, + sharded_weight_loader, +) +from sglang.srt.models.deepseek_common.deepseek_weight_loader import ( + DeepseekV2WeightLoaderMixin, +) +from sglang.srt.models.deepseek_common.utils import ( + _device_sm, + _is_cuda, + _use_aiter_gfx95, +) +from sglang.srt.models.deepseek_v2 import DeepseekV2AttentionMLA +from sglang.srt.models.deepseek_v2 import DeepseekV2MLP as Glm5NextMLP +from sglang.srt.models.deepseek_v2 import DeepseekV2MoE as Glm5NextMoE +from sglang.srt.models.glm_ocr import ( + GlmOcrRMSNorm, + GlmOcrVisionBlock, + GlmOcrVisionMLP, + GlmOcrVisionModel, + GlmOcrVisionPatchEmbed, + GlmOcrVisionPatchMerger, +) +from sglang.srt.multimodal.mm_utils import ( + run_dp_presharded_mrope_vision_model, + run_dp_sharded_mrope_vision_model, +) +from sglang.srt.runtime_context import get_forward, get_parallel, get_server_args +from sglang.srt.speculative.spec_info import SpeculativeAlgorithm +from sglang.srt.utils.common import ( + BumpAllocator, + LazyValue, + add_prefix, + log_info_on_rank0, + make_layers, + set_weight_attrs, +) + +if _use_aiter_gfx95: + from sglang.srt.layers.rocm_linear_utils import ( + get_dsv3_gemm_output_zero_allocator_size, + ) + +logger = logging.getLogger(__name__) + + +@torch.compile +def swiglu_clamped(y: torch.Tensor, limit: float): + gate, up = torch.chunk(y, 2, dim=-1) + gate = torch.clamp(gate, max=limit) + up = torch.clamp(up, min=-limit, max=limit) + return F.silu(gate) * up + + +class Glm5NextVisionMLP(GlmOcrVisionMLP): + def __init__( + self, + in_features: int, + hidden_features: int, + swiglu_limit: float, + bias: bool = False, + quant_config: Optional[QuantizationConfig] = None, + prefix: str = "", + use_data_parallel: bool = False, + ): + super().__init__( + in_features=in_features, + hidden_features=hidden_features, + bias=bias, + quant_config=quant_config, + prefix=prefix, + use_data_parallel=use_data_parallel, + ) + self.swiglu_limit = swiglu_limit + + def forward(self, x: torch.Tensor): + gate_up, _ = self.gate_up_proj(x) + x = swiglu_clamped(gate_up, self.swiglu_limit) + x, _ = self.down_proj(x) + return x + + +class Glm5NextVisionPatchMerger(GlmOcrVisionPatchMerger): + def __init__( + self, + d_model: int, + context_dim: int, + swiglu_limit: float, + quant_config: Optional[QuantizationConfig] = None, + bias: bool = False, + prefix: str = "", + use_data_parallel: bool = False, + ) -> None: + super().__init__( + d_model=d_model, + context_dim=context_dim, + quant_config=quant_config, + bias=bias, + prefix=prefix, + use_data_parallel=use_data_parallel, + ) + self.swiglu_limit = swiglu_limit + + def forward(self, x: torch.Tensor): + x, _ = self.proj(x) + x = self.extra_activation_func(self.post_projection_norm(x)) + gate_up, _ = self.gate_up_proj(x) + x = swiglu_clamped(gate_up, self.swiglu_limit) + x, _ = self.down_proj(x) + return x + + +class Glm5NextVisionBlock(GlmOcrVisionBlock): + def __init__( + self, + dim: int, + intermediate_dim: int, + num_heads: int, + swiglu_limit: float, + quant_config: Optional[QuantizationConfig] = None, + prefix: str = "", + attn_qkv_bias: bool = True, + num_dummy_heads: int = 0, + rms_norm_eps: float = 1e-5, + use_data_parallel: bool = False, + ) -> None: + nn.Module.__init__(self) + self.norm1 = RMSNorm(dim, eps=rms_norm_eps) + self.norm2 = RMSNorm(dim, eps=rms_norm_eps) + self.attn = VisionAttention( + embed_dim=dim, + num_heads=num_heads, + projection_size=dim, + use_qkv_parallel=True, + qkv_bias=attn_qkv_bias, + proj_bias=True, + qk_normalization_by_head_size=True, + flatten_batch=True, + quant_config=quant_config, + prefix=add_prefix("attn", prefix), + num_dummy_heads=num_dummy_heads, + use_data_parallel=use_data_parallel, + ) + self.mlp = Glm5NextVisionMLP( + dim, + intermediate_dim, + bias=True, + quant_config=quant_config, + prefix=add_prefix("mlp", prefix), + use_data_parallel=use_data_parallel, + swiglu_limit=swiglu_limit, + ) + + +class Glm5NextVisionModel(GlmOcrVisionModel): + def __init__( + self, + vision_config, + quant_config: Optional[QuantizationConfig] = None, + prefix: str = "", + use_data_parallel: bool = False, + ) -> None: + nn.Module.__init__(self) + self.hidden_size = vision_config.hidden_size + self.num_heads = vision_config.num_heads + self.patch_size = vision_config.patch_size + self.spatial_merge_size = vision_config.spatial_merge_size + self.out_hidden_size = vision_config.out_hidden_size + self.intermediate_size = vision_config.intermediate_size + self.use_data_parallel = use_data_parallel + + self.patch_embed = GlmOcrVisionPatchEmbed( + patch_size=vision_config.patch_size, + temporal_patch_size=vision_config.temporal_patch_size, + in_channels=vision_config.in_channels, + hidden_size=self.hidden_size, + ) + + head_dim = self.hidden_size // self.num_heads + self.rotary_pos_emb = get_rope( + head_size=head_dim, + rotary_dim=head_dim // 2, + max_position=8192, + base=10000.0, + is_neox_style=True, + ) + + self.blocks = nn.ModuleList( + [ + Glm5NextVisionBlock( + dim=self.hidden_size, + intermediate_dim=self.intermediate_size, + num_heads=self.num_heads, + quant_config=quant_config, + prefix=add_prefix(f"blocks.{layer_idx}", prefix), + rms_norm_eps=vision_config.rms_norm_eps, + attn_qkv_bias=vision_config.attention_bias, + use_data_parallel=use_data_parallel, + swiglu_limit=vision_config.swiglu_limit, + ) + for layer_idx in range(vision_config.depth) + ] + ) + projection_intermediate_size = getattr( + vision_config, "projection_intermediate_size", None + ) + self.merger = Glm5NextVisionPatchMerger( + d_model=vision_config.out_hidden_size, + context_dim=( + projection_intermediate_size + if projection_intermediate_size is not None + else vision_config.intermediate_size + ), + quant_config=quant_config, + bias=False, + prefix=add_prefix("merger", prefix), + use_data_parallel=use_data_parallel, + swiglu_limit=vision_config.swiglu_limit, + ) + + self.downsample = nn.Conv2d( + in_channels=vision_config.hidden_size, + out_channels=vision_config.out_hidden_size, + kernel_size=vision_config.spatial_merge_size, + stride=vision_config.spatial_merge_size, + ) + self.post_layernorm = GlmOcrRMSNorm( + vision_config.hidden_size, eps=vision_config.rms_norm_eps + ) + + +class Glm5NextLinearAttention(nn.Module): + def __init__( + self, + layer_idx: int, + hidden_size: int, + config: Glm5NextTextConfig, + quant_config: Optional[QuantizationConfig] = None, + rms_norm_eps: float = 1e-5, + prefix: str = "", + reduce_results: bool = False, + enable_prefill_cp: bool = False, + **kwargs, + ) -> None: + super().__init__() + self.dsa_enable_prefill_cp = is_dsa_enable_prefill_cp() + self.enable_prefill_cp = enable_prefill_cp + self.tp_size = get_parallel().tp_size + + if self.dsa_enable_prefill_cp: + head_shard_size = get_parallel().attn_cp_size + head_shard_rank = get_parallel().attn_cp_rank + _head_shard_rank_getter = partial(getattr, get_parallel(), "attn_cp_rank") + else: + head_shard_size = get_parallel().attn_tp_size + head_shard_rank = get_parallel().attn_tp_rank + _head_shard_rank_getter = partial(getattr, get_parallel(), "attn_tp_rank") + + self.hidden_size = hidden_size + self.config = config + self.head_dim = config.linear_attn_config["head_dim"] + self.num_heads = config.linear_attn_config["num_heads"] + self.num_k_heads = config.linear_attn_config["num_heads"] + self.num_v_heads = config.linear_attn_config["num_heads"] + self.head_k_dim = config.linear_attn_config["head_dim"] + self.head_v_dim = config.linear_attn_config["head_dim"] + self.layer_idx = layer_idx + self.prefix = prefix + assert self.num_heads % head_shard_size == 0 + self.local_num_heads = divide(self.num_heads, head_shard_size) + + projection_size = self.head_dim * self.num_heads + self.conv_size = config.linear_attn_config["short_conv_kernel_size"] + + self.do_fuse_qkvbfg = quant_config is None and head_shard_size == self.tp_size + if self.do_fuse_qkvbfg: + self.qkvb_sizes = [ + projection_size, + projection_size, + projection_size, + self.num_heads, + ] + self.fg_sizes = [self.head_dim, self.head_dim] + + self.fused_qkvbfg_a_proj = MergedColumnParallelRepeatedLinear( + self.hidden_size, + self.qkvb_sizes, # column parallel: q, k, v, beta + self.fg_sizes, # replicated: f_a, g_a + quant_config=quant_config, + prefix=f"{prefix}.fused_qkvbfg_a_proj", + ) + self.split_sizes = [ + 3 * projection_size // head_shard_size, # qkv + self.num_heads // head_shard_size, # beta + 2 * self.head_dim, # f_a, g_a (replicated) + ] + fused_dtype = ( + getattr(config, "dtype", None) + or getattr(config, "torch_dtype", None) + or torch.get_default_dtype() + ) + self.fused_fg_b_proj = ColumnParallelBatchedLinear( + 2, self.head_dim, projection_size, dtype=fused_dtype + ) + else: + self.qkv_proj = QKVParallelLinear( + self.hidden_size, + self.head_dim, + self.num_heads, + self.num_k_heads, + bias=False, + quant_config=quant_config, + tp_rank=head_shard_rank, + tp_size=head_shard_size, + prefix=f"{prefix}.qkv_proj", + ) + + self.f_a_proj = ReplicatedLinear( + self.hidden_size, + self.head_dim, + bias=False, + quant_config=quant_config, + prefix=f"{prefix}.f_a_proj", + ) + + self.f_b_proj = ColumnParallelLinear( + self.head_dim, + projection_size, + bias=False, + quant_config=quant_config, + prefix=f"{prefix}.f_b_proj", + tp_rank=head_shard_rank, + tp_size=head_shard_size, + ) + + self.b_proj = ColumnParallelLinear( + self.hidden_size, + self.num_heads, + bias=False, + quant_config=quant_config, + prefix=f"{prefix}.b_proj", + tp_rank=head_shard_rank, + tp_size=head_shard_size, + ) + + self.g_a_proj = ReplicatedLinear( + self.hidden_size, + self.head_dim, + bias=False, + quant_config=quant_config, + prefix=f"{prefix}.g_a_proj", + ) + self.g_b_proj = ColumnParallelLinear( + self.head_dim, + projection_size, + bias=False, + quant_config=quant_config, + prefix=f"{prefix}.g_b_proj", + tp_rank=head_shard_rank, + tp_size=head_shard_size, + ) + + self.dt_bias = nn.Parameter( + torch.empty(divide(projection_size, head_shard_size), dtype=torch.float32) + ) + + set_weight_attrs( + self.dt_bias, + {"weight_loader": sharded_weight_loader(0, _head_shard_rank_getter)}, + ) + + self.qkv_conv1d = MergedColumnParallelLinear( + input_size=self.conv_size, + output_sizes=[projection_size, projection_size, projection_size], + bias=False, + params_dtype=torch.float32, + prefix=f"{prefix}.qkv_conv1d", + tp_rank=head_shard_rank, + tp_size=head_shard_size, + ) + # unsqueeze to fit conv1d weights shape into the linear weights shape. + # Can't do this in `weight_loader` since it already exists in + # `ColumnParallelLinear` and `set_weight_attrs` doesn't allow override. + self.qkv_conv1d.weight.data = self.qkv_conv1d.weight.data.unsqueeze(1) + + self.A_log = nn.Parameter( + torch.empty(1, 1, self.local_num_heads, 1, dtype=torch.float32) + ) + set_weight_attrs( + self.A_log, + {"weight_loader": sharded_weight_loader(2, _head_shard_rank_getter)}, + ) + + self.o_norm = FusedRMSNormGated( + self.head_dim, eps=rms_norm_eps, activation="sigmoid" + ) + self.o_proj = RowParallelLinear( + projection_size, + self.hidden_size, + bias=False, + quant_config=quant_config, + prefix=f"{prefix}.o_proj", + reduce_results=reduce_results, + tp_rank=head_shard_rank, + tp_size=head_shard_size, + ) + + conv_weights = self.qkv_conv1d.weight.squeeze(1) + bias = self.qkv_conv1d.bias + + self.attn = RadixLinearAttention( + layer_id=self.layer_idx, + num_q_heads=self.local_num_heads, + num_k_heads=self.local_num_heads, + num_v_heads=self.local_num_heads, + head_q_dim=self.head_k_dim, + head_k_dim=self.head_k_dim, + head_v_dim=self.head_v_dim, + conv_weights=conv_weights, + bias=bias, + A_log=self.A_log, + dt_bias=self.dt_bias, + ) + + self.attn.lower_bound = config.linear_attn_config.get("gate_lower_bound", None) + + def forward_qkvbfg(self, hidden_states: torch.Tensor, forward_batch: ForwardBatch): + if dsa_use_prefill_cp(forward_batch, self.enable_prefill_cp): + hidden_states = cp_plain_all_gather( + hidden_states, get_parallel().attn_cp_size + ) + + qkv, _ = self.qkv_proj(hidden_states) + + beta = self.b_proj(hidden_states)[0] + forget_gate = self.f_b_proj(self.f_a_proj(hidden_states)[0])[0] + g_proj_states = self.g_b_proj(self.g_a_proj(hidden_states)[0])[0] + + return ( + qkv, + beta, + forget_gate, + g_proj_states, + ) + + def forward_qkvbfg_fused( + self, hidden_states: torch.Tensor, forward_batch: ForwardBatch + ): + if dsa_use_prefill_cp(forward_batch, self.enable_prefill_cp): + hidden_states = cp_plain_all_gather( + hidden_states, get_parallel().attn_cp_size + ) + fused_states = self.fused_qkvbfg_a_proj(hidden_states) + + qkv, beta, fg_a_states = torch.split(fused_states, self.split_sizes, dim=-1) + + forget_gate, g_proj_states = self.fused_fg_b_proj( + fg_a_states.view(-1, 2, self.head_dim).transpose(0, 1) + ) + + return ( + qkv, + beta, + forget_gate, + g_proj_states, + ) + + def forward( + self, + hidden_states: torch.Tensor, + forward_batch: ForwardBatch, + **kwargs, + ) -> torch.Tensor: + if forward_batch.forward_mode.is_idle(): + return hidden_states + + if self.do_fuse_qkvbfg: + mixed_qkv, beta, forget_gate, g_proj_states = self.forward_qkvbfg_fused( + hidden_states, forward_batch + ) + else: + mixed_qkv, beta, forget_gate, g_proj_states = self.forward_qkvbfg( + hidden_states, forward_batch + ) + + if not forward_batch.forward_mode.is_decode(): + forget_gate = forget_gate.unsqueeze(0) + beta = beta.unsqueeze(0) + + core_attn_out = self.attn( + forward_batch, + mixed_qkv=mixed_qkv, + a=forget_gate, + b=beta, + ) + + norm_gate = g_proj_states.unflatten( + -1, (-1, self.head_dim) + ) # ... (h d) -> ... h d + core_attn_out = self.o_norm(core_attn_out, norm_gate) + core_attn_out = core_attn_out.squeeze(0).flatten(-2) # 1 n h d -> n (h d) + + output = self.o_proj(core_attn_out)[0] + if dsa_use_prefill_cp(forward_batch, self.enable_prefill_cp): + if self.dsa_enable_prefill_cp: + output = cp_plain_reduce_scatter(output, get_parallel().attn_cp_size) + else: + output = cp_plain_split(output) + elif self.dsa_enable_prefill_cp: + output = get_parallel().attn_cp_group.all_reduce(output) + return output + + +class Glm5NextDecoderLayer(nn.Module): + def __init__( + self, + config: Glm5NextTextConfig, + layer_id: int, + quant_config: Optional[QuantizationConfig] = None, + moe_quant_config_override: Optional[QuantizationConfig] = None, + is_nextn: bool = False, + prefix: str = "", + alt_stream: Optional[torch.cuda.Stream] = None, + dsa_enable_prefill_cp: bool = False, + mla_enable_prefill_cp: bool = False, + ) -> None: + super().__init__() + self.hidden_size = config.hidden_size + self.config = config + rope_theta = config.rope_theta + rope_scaling = config.rope_scaling + max_position_embeddings = config.max_position_embeddings + self.speculative_algorithm = SpeculativeAlgorithm.from_string( + get_server_args().speculative_algorithm + ) + self.dsa_enable_prefill_cp = dsa_enable_prefill_cp + self.mla_enable_prefill_cp = mla_enable_prefill_cp + self.layer_id = layer_id + self.is_nextn = is_nextn + self.is_linear_attn = config.is_kda_layer(layer_id) + + if self.is_linear_attn: + self.self_attn = Glm5NextLinearAttention( + layer_idx=layer_id, + hidden_size=config.hidden_size, + config=config, + quant_config=quant_config, + prefix=f"{prefix}.self_attn", + rms_norm_eps=config.rms_norm_eps, + reduce_results=False, + enable_prefill_cp=( + self.dsa_enable_prefill_cp or self.mla_enable_prefill_cp + ), + ) + else: + self.self_attn = DeepseekV2AttentionMLA( + config=config, + hidden_size=self.hidden_size, + num_heads=config.num_attention_heads, + qk_nope_head_dim=config.qk_nope_head_dim, + qk_rope_head_dim=config.qk_rope_head_dim, + v_head_dim=config.v_head_dim, + q_lora_rank=config.q_lora_rank, + kv_lora_rank=config.kv_lora_rank, + rope_theta=rope_theta, + rope_scaling=rope_scaling, + max_position_embeddings=max_position_embeddings, + quant_config=quant_config, + layer_id=layer_id, + reduce_results=False, + prefix=add_prefix("self_attn", prefix), + alt_stream=alt_stream, + is_nextn=is_nextn, + skip_rope=True, + dsa_enable_prefill_cp=dsa_enable_prefill_cp, + mla_enable_prefill_cp=mla_enable_prefill_cp, + ) + + if config.q_lora_rank is None and envs.SGLANG_USE_AG_AFTER_QLORA.get(): + raise ValueError( + "SGLANG_USE_AG_AFTER_QLORA only supports the model with q_lora_rank" + ) + + self.is_layer_sparse = self._is_layer_sparse(layer_id, is_nextn=is_nextn) + is_previous_layer_sparse = self._is_layer_sparse(layer_id - 1, is_nextn=False) + is_next_layer_sparse = self._is_layer_sparse(layer_id + 1, is_nextn=False) + + self.layer_scatter_modes = LayerScatterModes.init_new( + layer_id=layer_id, + num_layers=1 if is_nextn else config.num_hidden_layers, + is_layer_sparse=self.is_layer_sparse, + is_previous_layer_sparse=is_previous_layer_sparse, + is_next_layer_sparse=is_next_layer_sparse, + ) + + if self.is_layer_sparse: + self.mlp = Glm5NextMoE( + config=config, + quant_config=moe_quant_config_override or quant_config, + prefix=add_prefix("mlp", prefix), + layer_id=self.layer_id, + alt_stream=alt_stream, + is_nextn=is_nextn, + dsa_enable_prefill_cp=dsa_enable_prefill_cp, + mla_enable_prefill_cp=mla_enable_prefill_cp, + ) + else: + if enable_moe_dense_fully_dp(): + mlp_tp_rank, mlp_tp_size = 0, 1 + else: + mlp_tp_rank, mlp_tp_size = None, None + self.mlp = Glm5NextMLP( + hidden_size=config.hidden_size, + intermediate_size=config.intermediate_size, + hidden_act=config.hidden_act, + quant_config=quant_config, + prefix=add_prefix("mlp", prefix), + tp_rank=mlp_tp_rank, + tp_size=mlp_tp_size, + swiglu_limit=config.swiglu_limit, + ) + + self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_attention_layernorm = RMSNorm( + config.hidden_size, eps=config.rms_norm_eps + ) + + if self.config.mhc: + hc_mult = config.hc_mult + mix_hc = (2 + hc_mult) * hc_mult + hc_dim = hc_mult * config.hidden_size + + # mHC params live directly on the decoder layer so their names + # (hc_{attn,ffn}_{base,scale,fn}) match the ckpt verbatim and + # default_weight_loader hits them without any rename. The + # communicator reads them at runtime via MHCState(layer=self). + self.hc_attn_base = nn.Parameter(torch.empty(mix_hc, dtype=torch.float32)) + self.hc_attn_scale = nn.Parameter(torch.empty(3, dtype=torch.float32)) + self.hc_attn_fn = nn.Parameter( + torch.empty(mix_hc, hc_dim, dtype=torch.float32) + ) + + self.hc_ffn_base = nn.Parameter(torch.empty(mix_hc, dtype=torch.float32)) + self.hc_ffn_scale = nn.Parameter(torch.empty(3, dtype=torch.float32)) + self.hc_ffn_fn = nn.Parameter( + torch.empty(mix_hc, hc_dim, dtype=torch.float32) + ) + + shared_kwargs: Dict[str, Any] = dict( + layer_scatter_modes=self.layer_scatter_modes, + input_layernorm=self.input_layernorm, + post_attention_layernorm=self.post_attention_layernorm, + allow_reduce_scatter=True, + is_last_layer=( + is_nextn or (self.layer_id == self.config.num_hidden_layers - 1) + ), + qkv_latent_func=( + self.self_attn.prepare_qkv_latent if not self.is_linear_attn else None + ), + ) + + if self.config.mhc: + mhc_kwargs: Dict[str, Any] = dict( + is_first_layer=(self.layer_id == 0), + hc_mult=config.hc_mult, + hc_attn_pre=self.hc_attn_pre, + hc_ffn_pre=self.hc_ffn_pre, + hc_post=self.hc_post, + ) + if self.dsa_enable_prefill_cp: + self.layer_communicator = MHCHybridDSACPLayerCommunicator( + **shared_kwargs, + **mhc_kwargs, + ) + else: + self.layer_communicator = MHCLayerCommunicator( + **shared_kwargs, + **mhc_kwargs, + ) + elif self.dsa_enable_prefill_cp or self.mla_enable_prefill_cp: + self.layer_communicator = DSACPLayerCommunicator(**shared_kwargs) + else: + self.layer_communicator = LayerCommunicator(**shared_kwargs) + + def _hc_pre( + self, hc_fn, hc_scale, hc_base, hidden_states, out_norm_weight, out_norm_eps + ): + return _hc_pre_fn( + x=hidden_states, + hc_fn=hc_fn, + hc_scale=hc_scale, + hc_base=hc_base, + hc_mult=self.config.hc_mult, + rms_eps=self.config.rms_norm_eps, + hc_eps=self.config.hc_eps, + sinkhorn_iters=self.config.hc_sinkhorn_iters, + post_mult_value=2.0, + hc_norm_weight=None, + out_norm_weight=out_norm_weight, + out_norm_eps=out_norm_eps, + ) + + def hc_attn_pre(self, hidden_states, out_norm_weight, out_norm_eps): + """Attention-stage mHC pre: hidden_states ``[s, hc_mult*hidden]`` -> (layer_input [s,hidden], h_res [s,n*n], h_post [s,n], norm_fused).""" + return self._hc_pre( + self.hc_attn_fn, + self.hc_attn_scale, + self.hc_attn_base, + hidden_states, + out_norm_weight, + out_norm_eps, + ) + + def hc_ffn_pre(self, hidden_states, out_norm_weight, out_norm_eps): + return self._hc_pre( + self.hc_ffn_fn, + self.hc_ffn_scale, + self.hc_ffn_base, + hidden_states, + out_norm_weight, + out_norm_eps, + ) + + def hc_post(self, hidden_states, residual, h_res, h_post): + """mHC post-stage (parameter-free, scalar hc_mult only).""" + assert self.config.mhc, "hc_post is only valid when config.mhc=True" + return _hc_post_fn( + x=hidden_states, + residual=residual, + h_post=h_post, + h_res=h_res, + hc_mult=self.config.hc_mult, + ) + + def _is_layer_sparse(self, layer_id: int, is_nextn: bool) -> bool: + return is_nextn or ( + self.config.n_routed_experts is not None + and layer_id >= self.config.first_k_dense_replace + and layer_id % self.config.moe_layer_freq == 0 + ) + + def forward( + self, + positions: torch.Tensor, + hidden_states: torch.Tensor, + forward_batch: ForwardBatch, + residual: Optional[torch.Tensor], + zero_allocator: Optional[BumpAllocator] = None, + gemm_output_zero_allocator: BumpAllocator = None, + prev_topk_indices: Optional[torch.Tensor] = None, + next_full_attention_layer_id: Optional[int] = None, + ): + hidden_states_orig = hidden_states + + # Attn-input prep, MHC attn_split, and (DSA-CP) scatter all happen inside + # the communicator; it also stores the AttentionInputs for fetch_qkv_latent. + hidden_states, residual = self.layer_communicator.prepare_attn( + hidden_states, + residual, + forward_batch, + ) + + # MLA's CP attention consumes the scattered (round-robin/zigzag) + # layout while the cross-layer contract is plain (block-contiguous, + # see Glm5NextModel.forward). KDA handles its own CP gather/scatter + # inside Glm5NextLinearAttention, so only MLA layers need this wrap. + # NOTE: prepare_attn already stored an AttentionInputs referencing the + # plain hidden_states for fetch_qkv_latent(); rebind that ref to the + # scattered tensor so q/kv latent and positions stay token-aligned. + mla_cp_wrap = not self.is_linear_attn and ( + dsa_use_prefill_cp(forward_batch, self.dsa_enable_prefill_cp) + or mla_use_prefill_cp(forward_batch, self.mla_enable_prefill_cp) + ) + if mla_cp_wrap: + hidden_states = cp_plain_to_scattered( + hidden_states, forward_batch, get_parallel().attn_cp_size + ) + get_attn_tp_context().set_hidden_states_local(hidden_states) + + hidden_states = self.self_attn( + positions=positions, + hidden_states=hidden_states, + forward_batch=forward_batch, + zero_allocator=zero_allocator, + layer_scatter_modes=self.layer_scatter_modes, + prev_topk_indices=prev_topk_indices, + ) + if isinstance(hidden_states, tuple): + hidden_states, topk_indices = hidden_states + else: + topk_indices = None + get_attn_tp_context().clear_attn_inputs() + + if mla_cp_wrap: + hidden_states = cp_scattered_to_plain( + hidden_states, forward_batch, get_parallel().attn_cp_size + ) + + self.layer_communicator.maybe_prefetch_next_full_attention_kv( + forward_batch, next_full_attention_layer_id + ) + + hidden_states, residual = self.layer_communicator.prepare_mlp( + hidden_states, + residual, + forward_batch, + ) + + should_allreduce_fusion = ( + self.layer_communicator.should_fuse_mlp_allreduce_with_next_layer( + forward_batch + ) + ) + + # For DP with padding, reduce scatter can be used instead of all-reduce. + use_reduce_scatter = self.layer_communicator.should_use_reduce_scatter( + forward_batch + ) + + if isinstance(self.mlp, Glm5NextMLP): + gemm_output_zero_allocator = None + + if ( + isinstance(self.mlp, Glm5NextMoE) + and not self.mlp.experts.moe_runner_config.inplace + and not torch.compiler.is_compiling() + ): + from sglang.srt.layers.moe.moe_runner.base import moe_output_buffer_ctx + + _mlp_ctx = moe_output_buffer_ctx(hidden_states_orig) + else: + _mlp_ctx = nullcontext() + + with get_forward().scoped( + fuse_mlp_allreduce=should_allreduce_fusion, + mlp_reduce_scatter=use_reduce_scatter, + ): + with _mlp_ctx: + hidden_states = self.mlp( + hidden_states, + forward_batch, + gemm_output_zero_allocator, + ) + + if ( + not (self.dsa_enable_prefill_cp or self.mla_enable_prefill_cp) + and should_allreduce_fusion + ): + hidden_states._sglang_needs_allreduce_fusion = True + + if not should_allreduce_fusion: + hidden_states, residual = self.layer_communicator.postprocess_layer( + hidden_states, + residual, + forward_batch, + ) + + return hidden_states, residual, topk_indices + + +class Glm5NextModel(nn.Module): + fall_back_to_pt_during_load = False + + def __init__( + self, + config: Glm5NextTextConfig, + quant_config: Optional[QuantizationConfig] = None, + prefix: str = "", + ) -> None: + super().__init__() + self.padding_id = config.pad_token_id + self.vocab_size = config.vocab_size + self.first_k_dense_replace = config.first_k_dense_replace + self.pp_group = get_pp_group() + self.dsa_enable_prefill_cp = is_dsa_enable_prefill_cp() + self.mla_enable_prefill_cp = ( + is_prefill_context_parallel_enabled() and not is_deepseek_dsa(config) + ) + if self.dsa_enable_prefill_cp or self.mla_enable_prefill_cp: + self.cp_size = get_parallel().attn_cp_size + else: + self.cp_size = None + + if self.pp_group.is_first_rank: + self.embed_tokens = VocabParallelEmbedding( + config.vocab_size, + config.hidden_size, + **get_embedding_tp_kwargs(), + ) + else: + self.embed_tokens = PPMissingLayer() + + self.alt_stream = ( + torch.cuda.Stream() + if ( + _is_cuda + or envs.SGLANG_NPU_USE_MULTI_STREAM.get() + or envs.SGLANG_ROCM_USE_MULTI_STREAM.get() + ) + else None + ) + + self.layers, self.start_layer, self.end_layer = make_layers( + config.num_hidden_layers, + lambda idx, prefix: Glm5NextDecoderLayer( + config=config, + layer_id=idx, + quant_config=quant_config, + prefix=prefix, + alt_stream=self.alt_stream, + dsa_enable_prefill_cp=self.dsa_enable_prefill_cp, + mla_enable_prefill_cp=self.mla_enable_prefill_cp, + ), + pp_rank=self.pp_group.rank_in_group, + pp_size=self.pp_group.world_size, + prefix=add_prefix("layers", prefix), + ) + local_full_attention_layer_ids = [ + layer_id + for layer_id in config.full_attention_layer_ids + if self.start_layer <= layer_id < self.end_layer + ] + self.next_full_attention_layer_id = dict( + zip( + local_full_attention_layer_ids, + local_full_attention_layer_ids[1:], + ) + ) + if self.pp_group.is_last_rank: + self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + else: + self.norm = PPMissingLayer(return_tuple=True) + + self.gemm_output_zero_allocator_size = 0 + if ( + _use_aiter_gfx95 + and config.n_routed_experts == 256 + and self.embed_tokens.embedding_dim == 7168 + ): + num_moe_layers = sum( + [ + 1 + for i in range(len(self.layers)) + if isinstance(self.layers[i].mlp, Glm5NextMoE) + ] + ) + + allocate_size = 0 + for i in range(len(self.layers)): + if isinstance(self.layers[i].mlp, Glm5NextMoE): + a2a_backend = get_moe_a2a_backend() + is_a2a_moe = ( + a2a_backend.is_deepep() + or a2a_backend.is_mori() + or a2a_backend.is_mooncake() + ) + tp_size = 1 if is_a2a_moe else get_parallel().tp_size + intermediate_size = ( + config.moe_intermediate_size * config.n_shared_experts + ) + share_expert_output_size_per_partition = divide( + intermediate_size * 2, tp_size + ) + allocate_size = share_expert_output_size_per_partition + break + + self.gemm_output_zero_allocator_size = ( + get_dsv3_gemm_output_zero_allocator_size( + config.n_routed_experts, + num_moe_layers, + allocate_size, + self.embed_tokens.embedding_dim, + ) + ) + self.layers_to_capture = [] + if get_moe_a2a_backend().is_deepep() or get_moe_a2a_backend().is_mooncake(): + self.enable_a2a_moe = True + else: + self.enable_a2a_moe = False + + def get_input_embeddings(self) -> torch.Tensor: + return self.embed_tokens + + def forward( + self, + input_ids: torch.Tensor, + positions: torch.Tensor, + forward_batch: ForwardBatch, + input_embeds: torch.Tensor = None, + pp_proxy_tensors: Optional[PPProxyTensors] = None, + ) -> Union[torch.Tensor, PPProxyTensors]: + total_num_layers = self.end_layer - self.start_layer + if self.pp_group.is_first_rank: + if input_embeds is None: + hidden_states = self.embed_tokens(input_ids) + else: + hidden_states = input_embeds + residual = None + else: + assert pp_proxy_tensors is not None + hidden_states = pp_proxy_tensors["hidden_states"] + residual = pp_proxy_tensors["residual"] + device = hidden_states.device + zero_allocator = BumpAllocator( + buffer_size=total_num_layers * 2 * (2 if forward_batch.can_run_tbo else 1), + dtype=torch.float32, + device=device, + ) + + has_gemm_output_zero_allocator = hasattr( + self, "gemm_output_zero_allocator_size" + ) + + gemm_output_zero_allocator = ( + BumpAllocator( + buffer_size=self.gemm_output_zero_allocator_size, + dtype=torch.float32, + device=device, + ) + if has_gemm_output_zero_allocator + and self.gemm_output_zero_allocator_size > 0 + else None + ) + + if dsa_use_prefill_cp( + forward_batch, self.dsa_enable_prefill_cp + ) or mla_use_prefill_cp(forward_batch, self.mla_enable_prefill_cp): + if self.pp_group.is_first_rank: + hidden_states = cp_plain_split(hidden_states) + positions = cp_split_and_rebuild_position(forward_batch, positions) + + normal_start_layer = self.start_layer + normal_end_layer = self.end_layer + if forward_batch.can_run_tbo: + if ( + self.first_k_dense_replace > normal_start_layer + and self.first_k_dense_replace < normal_end_layer + ): + normal_end_layer = self.first_k_dense_replace + elif self.first_k_dense_replace < normal_start_layer: + normal_end_layer = normal_start_layer = 0 + aux_hidden_states = [] + topk_indices = None + for i in range(normal_start_layer, normal_end_layer): + # NOTE: torch dynamo does not support graph break in context manager + ctx = ( + nullcontext() + if check_cuda_graph_backend(Phase.PREFILL, Backend.TC_PIECEWISE) + else get_global_expert_distribution_recorder().with_current_layer(i) + ) + with ctx: + if i in self.layers_to_capture: + if self.enable_a2a_moe and i > self.first_k_dense_replace: + aux_hidden_state = get_parallel().attn_tp_group.all_gather( + hidden_states + residual, dim=0 + ) + aux_hidden_states.append(aux_hidden_state) + else: + aux_hidden_states.append(hidden_states + residual) + layer = self.layers[i] + hidden_states, residual, topk_indices = layer( + positions, + hidden_states, + forward_batch, + residual, + zero_allocator, + gemm_output_zero_allocator, + prev_topk_indices=topk_indices, + next_full_attention_layer_id=( + self.next_full_attention_layer_id.get(i) + ), + ) + + if normal_end_layer != self.end_layer: + hidden_states, residual = model_forward_maybe_tbo( + layers=self.layers[normal_end_layer : self.end_layer], + enable_tbo=True, + positions=positions, + forward_batch=forward_batch, + hidden_states=hidden_states, + residual=residual, + input_data_scatter_mode=self.layers[ + normal_end_layer - 1 + ].layer_scatter_modes.layer_output_mode, + zero_allocator=zero_allocator, + ) + + if not self.pp_group.is_last_rank: + return PPProxyTensors( + { + "hidden_states": hidden_states, + "residual": residual, + } + ) + else: + if not forward_batch.forward_mode.is_idle(): + if residual is None: + hidden_states = self.norm(hidden_states) + else: + hidden_states, _ = self.norm(hidden_states, residual) + + if self.pp_group.is_last_rank and ( + dsa_use_prefill_cp(forward_batch, self.dsa_enable_prefill_cp) + or mla_use_prefill_cp(forward_batch, self.mla_enable_prefill_cp) + ): + hidden_states = cp_plain_all_gather(hidden_states, self.cp_size) + if len(aux_hidden_states) == 0: + return hidden_states + return hidden_states, aux_hidden_states + + +class Glm5NextForConditionalGeneration(nn.Module): + packed_modules_mapping = { + "fused_qkv_a_proj_with_mqa": ["q_a_proj", "kv_a_proj_with_mqa"], + "fused_qkvbfg_a_proj": [ + "q_proj", + "k_proj", + "v_proj", + "b_proj", + "f_a_proj", + "g_a_proj", + ], + "fused_fg_b_proj": ["f_b_proj", "g_b_proj"], + "qkv_proj": ["q_proj", "k_proj", "v_proj"], + "qkv_conv1d": ["q_conv1d", "k_conv1d", "v_conv1d"], + "gate_up_proj": ["gate_proj", "up_proj"], + } + fall_back_to_pt_during_load = False + + def __init__( + self, + config: Glm5NextConfig, + quant_config: Optional[QuantizationConfig] = None, + prefix: str = "", + ) -> None: + super().__init__() + vision_utils.update_vit_attn_dummy_heads_config(config) + self.mm_config = config + text_config = config.text_config + self.encoder_only = bool(getattr(config, "encoder_only", False)) + self.language_only = bool(getattr(config, "language_only", False)) + + self.fuse_qkv_a_proj = ( + not self.encoder_only + and getattr(text_config, "q_lora_rank", None) is not None + ) + + self.pp_group = get_pp_group() + self.config = text_config + self.tp_size = get_parallel().tp_size + self.quant_config = quant_config + self.use_dsa = is_deepseek_dsa(text_config) + self.num_fused_shared_experts = 0 + self.model = None + self.lm_head = None + self.logits_processor = None + if not self.encoder_only: + self.determine_num_fused_shared_experts() + self.model = Glm5NextModel( + text_config, quant_config, prefix=add_prefix("model", prefix) + ) + if self.pp_group.is_last_rank: + if self.pp_group.world_size == 1 and text_config.tie_word_embeddings: + self.lm_head = self.model.embed_tokens + else: + self.lm_head = ParallelLMHead( + text_config.vocab_size, + text_config.hidden_size, + quant_config=quant_config, + prefix=add_prefix("lm_head", prefix), + use_attn_tp_group=get_server_args().enable_dp_lm_head, + ) + else: + self.lm_head = PPMissingLayer() + self.logits_processor = LogitsProcessor(text_config) + + self._routed_experts_weights_of_layer = LazyValue( + lambda: ( + { + layer_id: layer.mlp.get_moe_weights() + for layer_id, layer in enumerate(self.model.layers) + if isinstance(layer.mlp, Glm5NextMoE) + } + if self.model is not None + else {} + ) + ) + self.capture_aux_hidden_states = False + + self.dsa_enable_prefill_cp = ( + not self.encoder_only and is_dsa_enable_prefill_cp() + ) + self.mla_enable_prefill_cp = ( + not self.encoder_only + and is_prefill_context_parallel_enabled() + and not is_deepseek_dsa(text_config) + ) + if self.dsa_enable_prefill_cp or self.mla_enable_prefill_cp: + self.cp_rank = get_parallel().attn_cp_rank + self.cp_size = get_parallel().attn_cp_size + else: + self.cp_rank = self.cp_size = None + + if not self.encoder_only: + get_attn_tp_context().init_context( + getattr(text_config, "q_lora_rank", None), + self.use_dsa, + text_config.mhc, + ) + + self.use_data_parallel = get_server_args().mm_enable_dp_encoder + self.visual = None + if not self.language_only: + self.visual = Glm5NextVisionModel( + config.vision_config, + quant_config=quant_config, + prefix=add_prefix("visual", prefix), + use_data_parallel=self.use_data_parallel, + ) + self.is_mrope_enabled = not self.encoder_only and "mrope_section" in ( + self.config.rope_scaling or {} + ) + + def get_input_embeddings(self) -> nn.Embedding: + if self.model is None: + raise AttributeError( + "get_input_embeddings() is not available in encoder-only mode" + ) + return self.model.embed_tokens + + @property + def routed_experts_weights_of_layer(self): + return self._routed_experts_weights_of_layer.value + + @property + def start_layer(self): + return self.model.start_layer + + @property + def end_layer(self): + return self.model.end_layer + + def determine_num_fused_shared_experts(self): + self.num_fused_shared_experts = 0 + if get_server_args().disable_shared_experts_fusion: + return + + disable_reason = None + if not getattr(self.config, "n_shared_experts", None): + disable_reason = "No shared experts are defined in the config." + elif not _is_cuda: + disable_reason = "Shared experts fusion currently requires CUDA devices." + elif _is_cuda and (_device_sm is not None) and (_device_sm < 80): + disable_reason = "Shared experts fusion requires SM80 or newer GPUs." + elif get_parallel().moe_ep_size > 1: + disable_reason = ( + "Shared experts fusion is not supported together with expert " + "parallelism yet." + ) + elif get_moe_a2a_backend().is_deepep(): + disable_reason = ( + "Shared experts fusion is not supported when Deepep MoE backend " + "is enabled." + ) + + if disable_reason is not None: + log_info_on_rank0( + logger, + f"{disable_reason} Shared experts fusion optimization is disabled.", + ) + return + + self.num_fused_shared_experts = self.config.n_shared_experts + assert ( + self.num_fused_shared_experts == 1 + ), f"Only 1 fused shared expert is supported for {type(self).__name__}" + log_info_on_rank0(logger, "Shared experts fusion optimization enabled.") + + def set_eagle3_layers_to_capture(self, layer_ids: Optional[List[int]] = None): + if not self.pp_group.is_last_rank: + return + + if layer_ids is None: + self.capture_aux_hidden_states = True + num_layers = self.config.num_hidden_layers + self.model.layers_to_capture = [2, num_layers // 2, num_layers - 3] + else: + self.capture_aux_hidden_states = True + self.model.layers_to_capture = [val + 1 for val in layer_ids] + + def prepare_context_parallel_metadata_for_dcp( + self, + seq_lens: torch.Tensor, + extend_prefix_lens: torch.Tensor, + extend_prefix_lens_cpu: torch.Tensor, + extend_seq_lens: torch.Tensor, + req_pool_indices: torch.Tensor, + req_to_token: torch.Tensor, + seq_lens_sum: int, + kv_buffer_shape: torch.Size, + kv_cache_dtype, + kv_cache_device, + create_chunked_prefix_cache_kv_indices_fn, + ): + return prepare_decode_context_parallel_metadata( + seq_lens=seq_lens, + extend_prefix_lens=extend_prefix_lens, + extend_prefix_lens_cpu=extend_prefix_lens_cpu, + extend_seq_lens=extend_seq_lens, + req_pool_indices=req_pool_indices, + req_to_token=req_to_token, + seq_lens_sum=seq_lens_sum, + kv_buffer_shape=kv_buffer_shape, + kv_cache_dtype=kv_cache_dtype, + kv_cache_device=kv_cache_device, + create_chunked_prefix_cache_kv_indices_fn=create_chunked_prefix_cache_kv_indices_fn, + ) + + def pad_input_ids(self, input_ids: List[int], mm_inputs: MultimodalInputs): + pattern = MultiModalityDataPaddingPatternMultimodalTokens() + return pattern.pad_input_tokens(input_ids, mm_inputs) + + def get_image_feature(self, items: List[MultimodalDataItem]) -> torch.Tensor: + pixel_values = torch.cat([item.feature for item in items], dim=0).type( + self.visual.dtype + ) + image_grid_thw = torch.concat([item.image_grid_thw for item in items], dim=0) + assert pixel_values.dim() == 2, pixel_values.dim() + assert image_grid_thw.dim() == 2, image_grid_thw.dim() + + if self.use_data_parallel: + return run_dp_sharded_mrope_vision_model( + self.visual, pixel_values, image_grid_thw.tolist(), rope_type="rope_3d" + ) + image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw) + return image_embeds + + def get_video_feature(self, items: List[MultimodalDataItem]) -> torch.Tensor: + pixel_values = torch.cat([item.feature for item in items], dim=0).type( + self.visual.dtype + ) + video_grid_thw = torch.concat([item.video_grid_thw for item in items], dim=0) + + temp_frames_hw = [] + for t, h, w in video_grid_thw: + repeated_row = ( + torch.tensor([1, h.item(), w.item()]).unsqueeze(0).repeat(t, 1) + ) + temp_frames_hw.append(repeated_row) + flattened_video_grid_thw = torch.cat(temp_frames_hw, dim=0) + + assert pixel_values.dim() == 2, pixel_values.dim() + assert video_grid_thw.dim() == 2, video_grid_thw.dim() + if items and getattr(items[0], "dp_decode_sharded", False): + if len(items) != 1: + raise ValueError("DP-sharded video decode requires one video item") + dp_meta = items[0].dp_meta + height = int(video_grid_thw[0][1]) + width = int(video_grid_thw[0][2]) + global_grid = [[1, height, width]] * int(dp_meta["n_units"]) + return run_dp_presharded_mrope_vision_model( + self.visual, + pixel_values, + flattened_video_grid_thw.tolist(), + global_grid, + dp_meta["gpu_sample_counts"], + ) + + if self.use_data_parallel: + return run_dp_sharded_mrope_vision_model( + self.visual, + pixel_values, + flattened_video_grid_thw.tolist(), + rope_type="rope_3d", + ) + video_embeds = self.visual(pixel_values, grid_thw=flattened_video_grid_thw) + return video_embeds + + def _prepare_context_parallel_metadata( + self, + input_ids: torch.Tensor, + input_embeds: Optional[torch.Tensor], + forward_batch: ForwardBatch, + pp_proxy_tensors: Optional[PPProxyTensors] = None, + ) -> None: + if input_ids is not None: + len_input_ids = input_ids.shape[0] + elif input_embeds is not None: + len_input_ids = input_embeds.shape[0] + else: + len_input_ids = pp_proxy_tensors["hidden_states"].shape[0] + if self.dsa_enable_prefill_cp: + if can_dsa_cp_split( + len_input_ids, self.cp_size, self.use_dsa, forward_batch + ): + forward_batch.attn_cp_metadata = prepare_context_parallel_metadata( + len_input_ids, + self.cp_rank, + self.cp_size, + forward_batch.seq_lens_cpu.tolist(), + extend_seqs_len=forward_batch.extend_seq_lens_cpu, + ) + elif self.mla_enable_prefill_cp: + if can_cp_split(len_input_ids, self.cp_size, forward_batch): + forward_batch.attn_cp_metadata = prepare_context_parallel_metadata( + len_input_ids, + self.cp_rank, + self.cp_size, + forward_batch.seq_lens_cpu.tolist(), + extend_seqs_len=forward_batch.extend_seq_lens_cpu, + ) + + @torch.no_grad() + def forward( + self, + input_ids: torch.Tensor, + positions: torch.Tensor, + forward_batch: ForwardBatch, + input_embeds: torch.Tensor = None, + pp_proxy_tensors: Optional[PPProxyTensors] = None, + ) -> torch.Tensor: + if self.is_mrope_enabled: + positions = forward_batch.mrope_positions + + self._prepare_context_parallel_metadata( + input_ids, input_embeds, forward_batch, pp_proxy_tensors + ) + with get_attn_tp_context().maybe_input_scattered(forward_batch): + hidden_states = general_mm_embed_routine( + input_ids=input_ids, + forward_batch=forward_batch, + language_model=self.model, + multimodal_model=self, + positions=positions, + pp_proxy_tensors=pp_proxy_tensors, + ) + + aux_hidden_states = None + if self.capture_aux_hidden_states: + hidden_states, aux_hidden_states = hidden_states + + if self.pp_group.is_last_rank: + return self.logits_processor( + input_ids, hidden_states, self.lm_head, forward_batch, aux_hidden_states + ) + else: + return hidden_states + + def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]], is_nextn=False): + if is_nextn: + if hasattr(self.config, "num_nextn_predict_layers"): + num_nextn_layers = self.config.num_nextn_predict_layers + assert num_nextn_layers == 1, "Only 1 nextn layer is supported" + nextn_layer_id = ( + 0 + if self.config.num_hidden_layers == 1 + else self.config.num_hidden_layers + ) + else: + raise ValueError("num_nextn_predict_layers is not in the config") + + stacked_params_mapping = [ + # (param_name, shard_name, shard_id) + ("gate_up_proj", "gate_proj", 0), + ("gate_up_proj", "up_proj", 1), + # Fused path + (".fused_qkvbfg_a_proj", ".q_proj", 0), + (".fused_qkvbfg_a_proj", ".k_proj", 1), + (".fused_qkvbfg_a_proj", ".v_proj", 2), + (".fused_qkvbfg_a_proj", ".b_proj", 3), + (".fused_qkvbfg_a_proj", ".f_a_proj", 4), + (".fused_qkvbfg_a_proj", ".g_a_proj", 5), + (".fused_fg_b_proj", ".f_b_proj", 0), + (".fused_fg_b_proj", ".g_b_proj", 1), + # Unfused path: separate qkv_proj (when do_fuse_qkvbfg=False) + (".qkv_proj", ".q_proj", "q"), + (".qkv_proj", ".k_proj", "k"), + (".qkv_proj", ".v_proj", "v"), + # qkv conv fuse + (".qkv_conv1d", ".q_conv1d", 0), + (".qkv_conv1d", ".k_conv1d", 1), + (".qkv_conv1d", ".v_conv1d", 2), + ] + + expert_params_mapping = FusedMoE.make_expert_params_mapping( + ckpt_gate_proj_name="gate_proj", + ckpt_down_proj_name="down_proj", + ckpt_up_proj_name="up_proj", + num_experts=self.config.n_routed_experts + self.num_fused_shared_experts, + ) + + if is_nextn: + nextn_layer_prefix = f"model.layers.{nextn_layer_id}" + nextn_spec_weight_names = [ + "shared_head.norm", + "eh_proj", + "enorm", + "hnorm", + ] + + fuse_qkv_a_proj = getattr(self, "fuse_qkv_a_proj", False) + cached_a_proj: dict[str, torch.Tensor] = {} if fuse_qkv_a_proj else None + qc = self.quant_config + if qc is not None and qc.get_name() in {"awq", "awq_marlin", "moe_wna16"}: + fused_cat_dim = 1 + else: + fused_cat_dim = 0 + + params_dict = dict(self.named_parameters()) + weight_names = [] + for name, loaded_weight in weights: + is_visual_weight = "visual" in name + if getattr(self, "encoder_only", False) and not is_visual_weight: + continue + if getattr(self, "language_only", False) and is_visual_weight: + continue + + if "language_model." in name: + name = name.replace("language_model.", "") + if "model.visual." in name: + name = name.replace("model.visual.", "visual.") + + if "visual" in name: + name = name.replace("attn.qkv.", "attn.qkv_proj.") + loaded_weight = vision_utils.pad_vit_attn_dummy_heads( + self.mm_config, name, loaded_weight + ) + + weight_names.append(name) + + if self.num_fused_shared_experts > 0 and "mlp.shared_experts" in name: + name = name.replace( + "mlp.shared_experts", + f"mlp.experts.{self.config.n_routed_experts}", + ) + + if not is_nextn: + if hasattr(self.config, "num_nextn_predict_layers"): + num_nextn_layers = self.config.num_nextn_predict_layers + if num_nextn_layers > 0 and name.startswith("model.layers"): + name_list = name.split(".") + if ( + len(name_list) >= 3 + and int(name_list[2]) >= self.config.num_hidden_layers + ): + continue + else: + if not name.startswith(nextn_layer_prefix): + continue + + if "shared_head.head" in name or "embed_tokens" in name: + continue + + is_decoder = True + for weight_name in nextn_spec_weight_names: + if weight_name in name: + name = name.replace(nextn_layer_prefix, "model") + is_decoder = False + break + if is_decoder: + name = name.replace(nextn_layer_prefix, "model.decoder") + + if "rotary_emb.inv_freq" in name: + continue + if "hc_head" in name: + continue + for param_name, weight_name, shard_id in stacked_params_mapping: + if weight_name not in name: + continue + if "mlp.experts" in name: + continue + candidate = name.replace(weight_name, param_name) + if ( + param_name + in { + ".fused_qkvbfg_a_proj", + ".fused_fg_b_proj", + ".qkv_proj", + ".qkv_conv1d", + } + and candidate not in params_dict + ): + continue + name = candidate + if name.endswith(".bias") and name not in params_dict: + continue + if name not in params_dict: + continue + param = params_dict[name] + weight_loader = param.weight_loader + weight_loader(param, loaded_weight, shard_id) + break + else: + is_expert_weight = False + for mapping in expert_params_mapping: + param_name, weight_name, expert_id, shard_id = mapping + if weight_name not in name: + continue + is_expert_weight = True + name = name.replace(weight_name, param_name) + if name not in params_dict: + continue + param = params_dict[name] + weight_loader = param.weight_loader + weight_loader( + param, + loaded_weight, + name, + shard_id=shard_id, + expert_id=expert_id, + ) + break + else: + if is_expert_weight: + continue + if name.endswith(".bias") and name not in params_dict: + continue + + if fuse_qkv_a_proj and ( + "q_a_proj" in name or "kv_a_proj_with_mqa" in name + ): + cached_a_proj[name] = loaded_weight + q_a_proj_name = ( + name + if "q_a_proj" in name + else name.replace("kv_a_proj_with_mqa", "q_a_proj") + ) + kv_a_proj_name = ( + name + if "kv_a_proj_with_mqa" in name + else name.replace("q_a_proj", "kv_a_proj_with_mqa") + ) + if ( + q_a_proj_name in cached_a_proj + and kv_a_proj_name in cached_a_proj + ): + fused_weight = torch.cat( + [ + cached_a_proj[q_a_proj_name], + cached_a_proj[kv_a_proj_name], + ], + dim=fused_cat_dim, + ) + target = ( + name.replace("q_a_proj", "fused_qkv_a_proj_with_mqa") + if "q_a_proj" in name + else name.replace( + "kv_a_proj_with_mqa", + "fused_qkv_a_proj_with_mqa", + ) + ) + if target in params_dict: + param = params_dict[target] + weight_loader = getattr( + param, "weight_loader", default_weight_loader + ) + weight_loader(param, fused_weight) + cached_a_proj.pop(q_a_proj_name, None) + cached_a_proj.pop(kv_a_proj_name, None) + continue + + if name not in params_dict: + continue + + if name.endswith(".A_log") and loaded_weight.dim() == 1: + loaded_weight = loaded_weight.view(1, 1, -1, 1) + + param = params_dict[name] + weight_loader = getattr( + param, "weight_loader", default_weight_loader + ) + weight_loader(param, loaded_weight) + + if getattr(self, "encoder_only", False): + run_post = False + elif is_nextn: + decoder_attn = getattr(self.model.decoder, "self_attn", None) + run_post = decoder_attn is not None and hasattr(decoder_attn, "kv_b_proj") + else: + run_post = True + if run_post: + DeepseekV2WeightLoaderMixin.post_load_weights( + self, is_nextn=is_nextn, weight_names=weight_names + ) + + def post_load_weights(self, is_nextn: bool = False, weight_names=None): + if self.encoder_only: + return + DeepseekV2WeightLoaderMixin.post_load_weights( + self, is_nextn=is_nextn, weight_names=weight_names + ) + + def load_kv_cache_scales(self, quantization_param_path: str) -> None: + if self.model is None: + raise AttributeError( + "load_kv_cache_scales() is not available in encoder-only mode" + ) + if callable(getattr(self.model, "load_kv_cache_scales", None)): + self.model.load_kv_cache_scales(quantization_param_path) + else: + logger.warning( + f"{self.model.__class__} does not support loading scaling factors." + ) + + def get_embed_and_head(self): + if self.model is None or self.lm_head is None: + raise AttributeError( + "get_embed_and_head() is not available in encoder-only mode" + ) + return self.model.embed_tokens.weight, self.lm_head.weight + + def set_embed_and_head(self, embed, head): + if self.model is None or self.lm_head is None: + raise AttributeError( + "set_embed_and_head() is not available in encoder-only mode" + ) + del self.model.embed_tokens.weight + del self.lm_head.weight + self.model.embed_tokens.weight = embed + self.lm_head.weight = head + torch.cuda.empty_cache() + torch.cuda.synchronize() + + @classmethod + def get_model_config_for_expert_location(cls, config): + config = getattr(config, "text_config", config) + return ModelConfigForExpertLocation( + num_layers=config.num_hidden_layers, + num_logical_experts=config.n_routed_experts, + num_groups=None, + ) + + +EntryClass = [Glm5NextForConditionalGeneration] diff --git a/python/sglang/srt/models/glm5_next_nextn.py b/python/sglang/srt/models/glm5_next_nextn.py new file mode 100644 index 0000000000000..3ae3112dcb6e4 --- /dev/null +++ b/python/sglang/srt/models/glm5_next_nextn.py @@ -0,0 +1,89 @@ +# Copyright 2023-2024 SGLang Team +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Inference-only GLM5-Next Speculative Decoding.""" + +import logging + +from sglang.srt.models.deepseek_nextn import DeepseekV3ForCausalLMNextN +from sglang.srt.models.glm5_next import Glm5NextForConditionalGeneration +from sglang.srt.models.utils import WeightsMapper + +logger = logging.getLogger(__name__) + + +class Glm5NextForConditionalGenerationNextN(DeepseekV3ForCausalLMNextN): + @classmethod + def get_hf_to_sglang_mapper(cls, config) -> WeightsMapper: + text_config = getattr(config, "text_config", config) + return WeightsMapper( + orig_to_new_substr={ + f"model.layers.{text_config.num_hidden_layers}": "model.decoder", + }, + ) + + def _resolve_nextn_quant_config(self, config, quant_config): + """Keep a checkpoint-declared BF16 NextN block unquantized. + + The Hybrid FP8+NVFP4 checkpoint advertises a global FP8 quantization + method, but its full ``model.layers..*`` NextN block + is listed in ``quantization_config.ignore`` and stored as BF16. Passing + the target quant config into that block allocates FP8 parameters and + loads the BF16 payload without matching scales, corrupting the first + QKV projection. + """ + raw_quant_config = getattr(config, "quantization_config", None) or {} + if hasattr(raw_quant_config, "to_dict"): + raw_quant_config = raw_quant_config.to_dict() + ignored = ( + raw_quant_config.get("ignore", []) + if isinstance(raw_quant_config, dict) + else [] + ) + nextn_layer_pattern = f"model.layers.{config.num_hidden_layers}.*" + if nextn_layer_pattern in ignored: + logger.warning( + "GLM5 NextN layer %s is checkpoint-declared unquantized; " + "using BF16 draft modules", + nextn_layer_pattern, + ) + return None + return super()._resolve_nextn_quant_config(config, quant_config) + + def __init__(self, config, quant_config=None, prefix: str = "") -> None: + super().__init__( + getattr(config, "text_config", config), + quant_config=quant_config, + prefix=prefix, + ) + + def load_weights(self, weights): + if not hasattr(self, "fuse_qkv_a_proj"): + self.fuse_qkv_a_proj = getattr(self.config, "q_lora_rank", None) is not None + layer_id = self.config.num_hidden_layers + layer_prefixes = ( + f"model.layers.{layer_id}.", + f"model.language_model.layers.{layer_id}.", + ) + nextn_weights = ( + (name, weight) + for name, weight in weights + if name.startswith(layer_prefixes) + ) + return Glm5NextForConditionalGeneration.load_weights( + self, nextn_weights, is_nextn=True + ) + + +EntryClass = [Glm5NextForConditionalGenerationNextN] diff --git a/python/sglang/srt/models/glm_ocr.py b/python/sglang/srt/models/glm_ocr.py index dfd00f31bd3e6..15fb7d6c99e70 100644 --- a/python/sglang/srt/models/glm_ocr.py +++ b/python/sglang/srt/models/glm_ocr.py @@ -26,7 +26,6 @@ from einops import rearrange from transformers.models.glm_ocr.configuration_glm_ocr import ( GlmOcrConfig, - GlmOcrTextConfig, GlmOcrVisionConfig, ) @@ -158,7 +157,6 @@ class GlmOcrVisionModel(Glm4vVisionModel): def __init__( self, vision_config: GlmOcrVisionConfig, - text_config: GlmOcrTextConfig, quant_config: Optional[QuantizationConfig] = None, prefix: str = "", use_data_parallel: bool = False, @@ -209,9 +207,16 @@ def __init__( for layer_idx in range(depth) ] ) + projection_intermediate_size = getattr( + vision_config, "projection_intermediate_size", None + ) self.merger = GlmOcrVisionPatchMerger( d_model=vision_config.out_hidden_size, - context_dim=text_config.intermediate_size, + context_dim=( + projection_intermediate_size + if projection_intermediate_size is not None + else vision_config.intermediate_size + ), quant_config=quant_config, bias=False, prefix=add_prefix("merger", prefix), @@ -285,7 +290,6 @@ def __init__( self.use_data_parallel = get_mm().mm_enable_dp_encoder self.visual = GlmOcrVisionModel( vision_config=config.vision_config, - text_config=config.text_config, quant_config=quant_config, prefix=add_prefix("visual", prefix), use_data_parallel=self.use_data_parallel, diff --git a/python/sglang/srt/multimodal/mm_utils.py b/python/sglang/srt/multimodal/mm_utils.py index d7548ba201cf8..91526c425b6aa 100644 --- a/python/sglang/srt/multimodal/mm_utils.py +++ b/python/sglang/srt/multimodal/mm_utils.py @@ -822,3 +822,71 @@ def run_dp_sharded_mrope_vision_model( current_idx += count out_embeddings = torch.cat(original_order_embeddings, dim=0) return out_embeddings + + +def run_dp_presharded_mrope_vision_model( + vision_model: torch.nn.Module, + pixel_values_local: torch.Tensor, + local_grid_thw_list: list, + global_grid_thw_list: list, + gpu_sample_counts: list, +) -> torch.Tensor: + """Run a vision tower when video decode already sharded temporal units. + + Rank-local inputs are contiguous pieces of the global video, so stripping + all-gather padding and concatenating rank order restores global order. + """ + parallel = get_parallel() + tp_size = parallel.attn_tp_size + patches_per_unit = [math.prod(grid) for grid in global_grid_thw_list] + grouped_patch_counts = [] + offset = 0 + for rank in range(tp_size): + count = gpu_sample_counts[rank] + grouped_patch_counts.append(sum(patches_per_unit[offset : offset + count])) + offset += count + + merge_factor = vision_model.spatial_merge_size**2 + grouped_output_lengths = [ + patch_count // merge_factor for patch_count in grouped_patch_counts + ] + max_output_length = max(grouped_output_lengths) + try: + model_device = vision_model.device + model_dtype = vision_model.dtype + except AttributeError: + parameter = next(vision_model.parameters()) + model_device, model_dtype = parameter.device, parameter.dtype + + if pixel_values_local.shape[0] > 0: + pixel_values_local = pixel_values_local.to( + device=model_device, dtype=model_dtype + ) + local_embeddings = vision_model( + pixel_values_local, + grid_thw=torch.tensor(local_grid_thw_list), + ) + else: + local_embeddings = torch.empty( + (0, vision_model.out_hidden_size), + device=model_device, + dtype=model_dtype, + ) + + if local_embeddings.shape[0] < max_output_length: + padding = torch.empty( + ( + max_output_length - local_embeddings.shape[0], + local_embeddings.shape[1], + ), + device=local_embeddings.device, + dtype=local_embeddings.dtype, + ) + local_embeddings = torch.cat([local_embeddings, padding], dim=0) + + gathered = parallel.attn_tp_group.all_gather(local_embeddings, dim=0) + pieces = [] + for rank, output_length in enumerate(grouped_output_lengths): + start = rank * max_output_length + pieces.append(gathered[start : start + output_length]) + return torch.cat(pieces, dim=0) diff --git a/python/sglang/srt/multimodal/processors/base_processor.py b/python/sglang/srt/multimodal/processors/base_processor.py index ff3f60a8c7a98..9e31472f6dd6c 100644 --- a/python/sglang/srt/multimodal/processors/base_processor.py +++ b/python/sglang/srt/multimodal/processors/base_processor.py @@ -52,6 +52,7 @@ load_image, load_video, logger, + smart_to_rgb, ) _is_cpu = is_cpu() @@ -194,6 +195,7 @@ def get_combined_regex(self) -> re.Pattern: class BaseMultimodalProcessor(ABC): models = [] gpu_image_decode = True # Enable GPU decoding by default + smart_rgb_conversion = False prefer_tokenized_input = False precompute_hash_before_cpu_transfer = False # Set by processors that already build input_ids from the request's own @@ -719,6 +721,14 @@ def process_mm_data( if processor_device is not None: kwargs["device"] = processor_device + # Model families may keep video preprocessing off the GPU: the + # tokenizer process otherwise competes with the scheduler's pools for + # device memory on long videos. + if videos: + video_device = getattr(self, "video_preprocessing_device", None) + if video_device is not None: + kwargs["device"] = video_device + # Avoid double BOS when the chat template already wrote one. if self._tokenizer_auto_adds_specials and isinstance(input_text, str): bos = getattr(tokenizer, "bos_token", None) @@ -805,8 +815,11 @@ def _load_single_item( return img # JPEG already decoded on GPU by nvJPEG # PIL decodes lazily; do it here in the io worker so the decode # doesn't run later on the event-loop thread. - if discard_alpha_channel and img.mode != "RGB": - return img.convert("RGB") + if discard_alpha_channel: + if cls.smart_rgb_conversion: + return smart_to_rgb(img) + if img.mode != "RGB": + return img.convert("RGB") img.load() return img elif modality == Modality.VIDEO: diff --git a/python/sglang/srt/multimodal/processors/glm4v.py b/python/sglang/srt/multimodal/processors/glm4v.py index db684259d2f6a..7aeafc9cf5d60 100644 --- a/python/sglang/srt/multimodal/processors/glm4v.py +++ b/python/sglang/srt/multimodal/processors/glm4v.py @@ -1,5 +1,11 @@ +import asyncio +import json +import math from typing import List, Union +import numpy as np +import torch + from sglang.srt.layers.rotary_embedding import MRotaryEmbedding from sglang.srt.managers.schedule_batch import MultimodalProcessorOutput from sglang.srt.models.glm4v import Glm4vForConditionalGeneration @@ -10,19 +16,424 @@ from sglang.srt.multimodal.processors.base_processor import ( MultimodalSpecialTokens, ) +from sglang.srt.utils import GLM_MEDIA_CONFIG_KEYS +from sglang.srt.utils.video_decoder import VideoDecoderWrapper try: from sglang.srt.models.glm_ocr import GlmOcrForConditionalGeneration except ImportError: GlmOcrForConditionalGeneration = None +try: + from sglang.srt.models.glm5_next import Glm5NextForConditionalGeneration +except ImportError: + Glm5NextForConditionalGeneration = None + +GLM_VIDEO_DEFAULT_FPS = 2.0 +GLM_VIDEO_DEFAULT_MAX_FRAMES = 2048 +GLM_VIDEO_PATCH_SIZE = 14 +GLM_VIDEO_MERGE_SIZE = 2 +GLM_VIDEO_PATCH_EXPAND_FACTOR = 4 + + +def _glm_video_metadata(total_num_frames, fps, duration, frames_indices): + return { + "total_num_frames": int(total_num_frames), + "fps": float(fps), + "duration": float(duration), + "video_backend": "sglang", + "frames_indices": list(frames_indices), + } + + +def _glm_item_config(item): + config = dict(getattr(item, "preprocess_kwargs", None) or {}) + if isinstance(item, dict): + config.update(item.get("preprocess_kwargs") or {}) + config.update( + { + key: item[key] + for key in GLM_MEDIA_CONFIG_KEYS + if item.get(key) is not None + } + ) + return { + key: config[key] for key in GLM_MEDIA_CONFIG_KEYS if config.get(key) is not None + } + + +def split_glm_video_items(mm_data): + """Extract per-video controls and return sources suitable for decoding.""" + if mm_data is None: + return None, [] + items = mm_data if isinstance(mm_data, (list, tuple)) else [mm_data] + urls, configs = [], [] + for item in items: + if isinstance(item, dict) and "format" not in item and "url" in item: + urls.append(item["url"]) + elif hasattr(item, "url") and hasattr(item, "preprocess_kwargs"): + urls.append(item.url) + else: + urls.append(item) + configs.append(_glm_item_config(item)) + return urls, configs + + +def glm_budget_kwargs(processor, user_max_image_tokens=None, count=1, split=False): + """Resolve an optional per-item visual-token budget for a HF processor.""" + if processor is None: + return None + default_max = getattr(processor, "max_image_tokens", None) + if not default_max: + return None + + if user_max_image_tokens is not None: + budget = int(user_max_image_tokens) + elif split: + budget = int(default_max) + else: + return None + + count = max(int(count or 1), 1) + effective = max(1, budget // count if split and count > 1 else budget) + if effective == default_max and user_max_image_tokens is None: + return None + return {"max_image_tokens": effective} + + +def glm_max_image_tokens_from_configs(configs): + """Return the tightest max_image_tokens override across media items.""" + values = [ + int(config["max_image_tokens"]) + for config in configs or [] + if isinstance(config, dict) and config.get("max_image_tokens") is not None + ] + return min(values) if values else None + + +def glm_processor_video_config(processor): + """Read GLM video defaults exposed by the model's HF processor.""" + if processor is None: + return {} + config = { + key: value + for key in GLM_MEDIA_CONFIG_KEYS + if (value := getattr(processor, key, None)) is not None + } + budget = _glm_processor_resize_budget(processor) + if budget is not None: + config["_presize_budget"] = budget + return config + + +def _glm_processor_resize_budget(processor): + """Resize geometry inputs mirroring the HF GLM video processor. + + The budget comes from the processor's token limits, not `size`: on + Glm5NextVideoProcessor `size.longest_edge` is a sentinel (1) and the real + bound is `max_image_tokens * temporal_patch_size * (patch*merge)^2`. + """ + max_image_tokens = getattr(processor, "max_image_tokens", None) + if not max_image_tokens: + return None + patch_size = getattr(processor, "patch_size", None) or GLM_VIDEO_PATCH_SIZE + merge_size = getattr(processor, "merge_size", None) or GLM_VIDEO_MERGE_SIZE + expand_factor = getattr(processor, "patch_expand_factor", None) or 1 + temporal_factor = getattr(processor, "temporal_patch_size", None) or 2 + pixels_per_token = int(temporal_factor * (patch_size * merge_size) ** 2) + return { + "factor": int(patch_size * merge_size * expand_factor), + "temporal_factor": int(temporal_factor), + "pixels_per_token": pixels_per_token, + "min_pixels": int(getattr(processor, "min_image_tokens", None) or 0) + * pixels_per_token, + "max_pixels": int(max_image_tokens) * pixels_per_token, + "resize_mode": getattr(processor, "resize_mode", None) or "resize", + } + + +def _glm_effective_presize_budget(video_config, effective_max_image_tokens): + """Overlay the call-effective token budget onto a video's presize budget.""" + budget = video_config.get("_presize_budget") if video_config else None + if not budget or effective_max_image_tokens is None: + return video_config + config = dict(video_config) + config["_presize_budget"] = { + **budget, + "max_pixels": int(effective_max_image_tokens) * budget["pixels_per_token"], + } + return config + + +def _merge_glm_video_configs(default_config, item_configs): + """Merge server defaults with per-request overrides.""" + defaults = dict(default_config or {}) + return [{**defaults, **dict(config or {})} for config in item_configs] + + +def glm_sample_frame_indices( + total_frames, + fps, + duration, + *, + target_fps=None, + max_frame_count=None, +): + """Sample GLM video frames deterministically and keep temporal pairs. + + The algorithm mirrors the GLM/HF processor rather than treating target + timestamps as independent nearest-neighbour lookups. That keeps the + no-override EPD path byte-for-byte aligned with ordinary preprocessing. + """ + if total_frames <= 0: + return [] + target_fps = GLM_VIDEO_DEFAULT_FPS if target_fps is None else float(target_fps) + max_frame_count = ( + GLM_VIDEO_DEFAULT_MAX_FRAMES + if max_frame_count is None + else int(max_frame_count) + ) + if target_fps <= 0 or max_frame_count <= 0: + return [] + + max_frame_idx = total_frames - 1 + if not duration: + duration = round(max_frame_idx / fps) + 1 if fps else 0 + extract_t = min(int(duration * target_fps), int(max_frame_count)) + extract_t = max(1, extract_t) + + if fps: + duration_per_frame = 1 / fps + timestamps = [index * duration_per_frame for index in range(total_frames)] + max_second = int(duration) + indices = [] + current_second = 0.0 + interval = 1 / target_fps + for frame_index, timestamp in enumerate(timestamps): + if timestamp >= current_second: + current_second += interval + indices.append(frame_index) + if current_second >= max_second: + break + else: + indices = [] + + if len(indices) < extract_t: + start = indices[0] if indices else 0 + end = indices[-1] if indices else max(total_frames - 1, 0) + indices = np.linspace(start, end, extract_t, dtype=int).tolist() + elif len(indices) > extract_t: + indices = np.linspace(0, total_frames - 1, extract_t, dtype=int).tolist() + + seen = set() + unique_indices = [] + for index in indices: + index = int(index) + if index not in seen: + seen.add(index) + unique_indices.append(index) + if len(unique_indices) & 1: + unique_indices.append(unique_indices[-1]) + return unique_indices + + +def _resize_frames_to_max_tokens(frames, max_tokens_per_frame): + """Downscale NHWC frames to the GLM per-frame post-merge token budget.""" + import torchvision.transforms.functional as TF + + if not isinstance(frames, torch.Tensor): + frames = torch.from_numpy(np.asarray(frames)) + nchw = frames.permute(0, 3, 1, 2) + _, _, height, width = nchw.shape + pixels_per_token = (GLM_VIDEO_PATCH_SIZE * GLM_VIDEO_MERGE_SIZE) ** 2 + factor = GLM_VIDEO_PATCH_SIZE * GLM_VIDEO_MERGE_SIZE * GLM_VIDEO_PATCH_EXPAND_FACTOR + max_pixels = max( + int(max_tokens_per_frame) * pixels_per_token, + factor * factor, + ) + resized_height = max(factor, round(height / factor) * factor) + resized_width = max(factor, round(width / factor) * factor) + if resized_height * resized_width > max_pixels: + scale = math.sqrt((height * width) / max_pixels) + resized_height = max(factor, math.floor(height / scale / factor) * factor) + resized_width = max(factor, math.floor(width / scale / factor) * factor) + if (resized_height, resized_width) != (height, width): + nchw = TF.resize( + nchw, + [resized_height, resized_width], + interpolation=TF.InterpolationMode.BICUBIC, + antialias=True, + ) + return nchw.permute(0, 2, 3, 1).contiguous() + + +def preprocess_video_frames_sync(frame_list: List[dict]): + """Convert a client-provided GLM frame list to processor input.""" + total_num_frames = len(frame_list) + if total_num_frames == 0: + raise ValueError("GLM video frame list must not be empty") + duration = 0.0 + if frame_list[0].get("detail") is not None: + details = json.loads(frame_list[0]["detail"]) + duration = float(details.get("video_duration", 0)) + if duration == 0: + base_ts = float(frame_list[0].get("timestamp", 0) or 0) + duration = float(frame_list[-1].get("timestamp", base_ts) or base_ts) - base_ts + images = [frame["frame_image"] for frame in frame_list] + if isinstance(images[0], torch.Tensor): + images = torch.stack(images).permute(0, 2, 3, 1).contiguous() + else: + images = [np.asarray(image) for image in images] + fps = total_num_frames / duration if duration else 0 + return images, _glm_video_metadata( + total_num_frames, fps, duration, range(total_num_frames) + ) + + +GLM_VIDEO_PRE_RESIZE_CHUNK = 64 + + +def _vendor_smart_resize_canvas( + num_frames, height, width, *, temporal_factor, factor, min_pixels, max_pixels +): + """Replica of the vendor Glm5Next smart_resize (align-ceil + budget search).""" + + def align(value): + return math.ceil(value / factor) * factor + + def fit_within_budget(aligned_frames): + low, high = 1, height + best_height, best_width = factor, factor + while low <= high: + content_height = (low + high) // 2 + content_width = max(1, math.floor(width * content_height / height)) + candidate_height = align(content_height) + candidate_width = align(content_width) + if aligned_frames * candidate_height * candidate_width <= max_pixels: + best_height, best_width = candidate_height, candidate_width + low = content_height + 1 + else: + high = content_height - 1 + return best_height, best_width + + aligned_frames = max( + temporal_factor, round(num_frames / temporal_factor) * temporal_factor + ) + canvas_height, canvas_width = align(height), align(width) + if aligned_frames * canvas_height * canvas_width > max_pixels: + canvas_height, canvas_width = fit_within_budget(aligned_frames) + elif aligned_frames * canvas_height * canvas_width < min_pixels: + scale = math.sqrt(min_pixels / (num_frames * height * width)) + canvas_height = align(max(1, math.ceil(height * scale))) + canvas_width = align(max(1, math.ceil(width * scale))) + if aligned_frames * canvas_height * canvas_width > max_pixels: + canvas_height, canvas_width = fit_within_budget(aligned_frames) + return canvas_height, canvas_width + + +def _pre_resize_frames_for_processor( + frames, + *, + factor, + temporal_factor, + pixels_per_token, + min_pixels, + max_pixels, + resize_mode, +): + """Reproduce the HF GLM video processor's resize+pad output ahead of time. + + The HF Glm5Next video processor converts the full stacked tensor to + float32 at native resolution before resizing; handing it an exact copy of + its own output makes its resize a no-op, keeping the final grid identical + while bounding the allocation. The resize runs in chunks because + torchvision materializes float32 intermediates. + """ + import torchvision.transforms.functional as TF + + if not isinstance(frames, torch.Tensor): + frames = torch.from_numpy(np.asarray(frames)) + nchw = frames.permute(0, 3, 1, 2) + num_frames, _, height, width = nchw.shape + canvas_height, canvas_width = _vendor_smart_resize_canvas( + num_frames, + height, + width, + temporal_factor=temporal_factor, + factor=factor, + min_pixels=min_pixels, + max_pixels=max_pixels, + ) + if resize_mode == "resize": + content_height, content_width = canvas_height, canvas_width + else: + scale = min(canvas_height / height, canvas_width / width) + if num_frames * height * width >= min_pixels: + scale = min(1.0, scale) + content_height = max(1, min(canvas_height, math.floor(height * scale))) + content_width = max(1, min(canvas_width, math.floor(width * scale))) + if (content_height, content_width) != (height, width): + nchw = torch.cat( + [ + TF.resize( + chunk, + [content_height, content_width], + interpolation=TF.InterpolationMode.BICUBIC, + antialias=True, + ) + for chunk in nchw.split(GLM_VIDEO_PRE_RESIZE_CHUNK) + ] + ) + if (content_height, content_width) != (canvas_height, canvas_width): + nchw = torch.nn.functional.pad( + nchw, (0, canvas_width - content_width, 0, canvas_height - content_height) + ) + return nchw.permute(0, 2, 3, 1).contiguous() + + +def glm_decode_frames_at(vr, indices, video_config=None): + """Decode only an explicitly assigned frame subset for one encoder rank.""" + indices = list(indices) + if not indices: + return None + video_config = video_config or {} + # VideoDecoderWrapper already uses parallel extraction where supported. + if hasattr(vr, "get_frames_as_tensor"): + frames = vr.get_frames_as_tensor(indices) + else: + frames = vr.get_frames_at(indices) + max_tokens_per_frame = video_config.get("max_tokens_per_frame") + if max_tokens_per_frame is not None: + frames = _resize_frames_to_max_tokens(frames, max_tokens_per_frame) + elif budget := video_config.get("_presize_budget"): + frames = _pre_resize_frames_for_processor(frames, **budget) + return frames + + +def glm_sample_and_decode_sync(vr, video_config=None): + video_config = video_config or {} + fps = vr.avg_fps + duration = len(vr) / fps if fps else 0 + indices = glm_sample_frame_indices( + len(vr), + fps, + duration, + target_fps=video_config.get("fps"), + max_frame_count=video_config.get("max_frames"), + ) + frames = glm_decode_frames_at(vr, indices, video_config) + return frames, _glm_video_metadata(len(vr), fps, duration, indices) + class Glm4vImageProcessor(SGLangBaseProcessor): + smart_rgb_conversion = True + video_preprocessing_device = "cpu" models = [ m for m in [ Glm4vForConditionalGeneration, Glm4vMoeForConditionalGeneration, + Glm5NextForConditionalGeneration, GlmOcrForConditionalGeneration, ] if m is not None @@ -46,6 +457,8 @@ def __init__(self, hf_config, server_args, _processor, *args, **kwargs): self.IMAGE_END_TOKEN_ID = hf_config.image_end_token_id self.VIDEO_START_TOKEN_ID = hf_config.video_start_token_id self.VIDEO_END_TOKEN_ID = hf_config.video_end_token_id + self.IM_START_TOKEN_ID = self.IMAGE_START_TOKEN_ID + self.IM_END_TOKEN_ID = self.IMAGE_END_TOKEN_ID # Vision config self.IMAGE_FACTOR = 28 @@ -90,17 +503,85 @@ async def process_mm_data_async( *args, **kwargs, ): + # Normalize inline media dictionaries before loading. In particular, a + # bare base64 video must go through SGLang's decoder rather than being + # forwarded to the HF video loader as a path-like string. + video_urls, video_configs = split_glm_video_items(request_obj.video_data) + video_processor = getattr(self._processor, "video_processor", None) + default_video_config = glm_processor_video_config(video_processor) + default_video_config.update(self.video_config) + video_configs = _merge_glm_video_configs(default_video_config, video_configs) + base_output = await self.load_mm_data( prompt=input_text, image_data=image_data, - video_data=request_obj.video_data, + video_data=video_urls, multimodal_tokens=self.mm_tokens, ) - if base_output.videos: - base_output.videos = request_obj.video_data + video_metadata = None + videos_kwargs = None + if base_output.videos and not isinstance(base_output.videos[0], dict): + videos_kwargs = glm_budget_kwargs( + video_processor, + user_max_image_tokens=glm_max_image_tokens_from_configs(video_configs), + count=len(base_output.videos), + split=True, + ) + effective_max_image_tokens = (videos_kwargs or {}).get("max_image_tokens") + loop = asyncio.get_running_loop() + decode_tasks = [] + for index, video in enumerate(base_output.videos): + video_config = _glm_effective_presize_budget( + video_configs[index] if index < len(video_configs) else {}, + effective_max_image_tokens, + ) + if isinstance(video, VideoDecoderWrapper): + decode_tasks.append( + loop.run_in_executor( + self.io_executor, + glm_sample_and_decode_sync, + video, + video_config, + ) + ) + elif isinstance(video, list) and ( + not video or isinstance(video[0], dict) + ): + decode_tasks.append( + loop.run_in_executor( + self.io_executor, preprocess_video_frames_sync, video + ) + ) + else: + decode_tasks.append(asyncio.sleep(0, result=(video, None))) + + videos_processed = await asyncio.gather(*decode_tasks) + for video in base_output.videos: + close = getattr(video, "close", None) + if callable(close): + close() + base_output.videos, metadata = map(list, zip(*videos_processed)) + if metadata and all(item is not None for item in metadata): + video_metadata = metadata + + combine_kwargs = {} + if video_metadata is not None: + # Frames were already sampled by SGLang. Preserve the original + # indices for timestamps and prevent a second HF sampling pass. + combine_kwargs["video_metadata"] = video_metadata + combine_kwargs["do_sample_frames"] = False + processor_video_config = { + key: value + for key, value in self.video_config.items() + if key not in {"fps", "max_frames", "max_tokens_per_frame"} + } + if videos_kwargs is not None: + processor_video_config.update(videos_kwargs) + combine_kwargs["processor_video_config"] = processor_video_config + mm_items, input_ids, ret = self.process_and_combine_mm_data( - base_output, self.mm_tokens + base_output, self.mm_tokens, **combine_kwargs ) input_ids = input_ids.flatten() diff --git a/python/sglang/srt/observability/metrics_collector.py b/python/sglang/srt/observability/metrics_collector.py index c47d5ff3c06d9..aeb45bfa50e42 100644 --- a/python/sglang/srt/observability/metrics_collector.py +++ b/python/sglang/srt/observability/metrics_collector.py @@ -536,6 +536,11 @@ def __init__( documentation="The number of bootstrap failed requests.", labelnames=labels.keys(), ) + self.num_prealloc_failed_reqs = Counter( + name="sglang:num_prealloc_failed_reqs_total", + documentation="The number of decode preallocation requests that timed out.", + labelnames=labels.keys(), + ) self.num_transfer_failed_reqs = Counter( name="sglang:num_transfer_failed_reqs_total", documentation="The number of transfer failed requests.", @@ -1155,6 +1160,9 @@ def _log_histogram(self, histogram, data: Union[int, float]) -> None: def increment_bootstrap_failed_reqs(self) -> None: self.num_bootstrap_failed_reqs.labels(**self.labels).inc(1) + def increment_prealloc_failed_reqs(self) -> None: + self.num_prealloc_failed_reqs.labels(**self.labels).inc(1) + def increment_transfer_failed_reqs(self) -> None: self.num_transfer_failed_reqs.labels(**self.labels).inc(1) diff --git a/python/sglang/srt/parser/conversation.py b/python/sglang/srt/parser/conversation.py index 920ac33e3adf9..96d3a8fa93148 100644 --- a/python/sglang/srt/parser/conversation.py +++ b/python/sglang/srt/parser/conversation.py @@ -35,7 +35,12 @@ from typing_extensions import Literal from sglang.srt.entrypoints.openai.protocol import ChatCompletionRequest -from sglang.srt.utils import ImageData, VideoData, read_system_prompt_from_file +from sglang.srt.utils import ( + GLM_MEDIA_CONFIG_KEYS, + ImageData, + VideoData, + read_system_prompt_from_file, +) class SeparatorStyle(IntEnum): @@ -681,7 +686,16 @@ def generate_chat_conv( ) elif content.type == "video_url": real_content += video_token - conv.append_video(content.video_url.url) + preprocess_kwargs = { + key: value + for key in GLM_MEDIA_CONFIG_KEYS + if (value := getattr(content.video_url, key, None)) + is not None + } + conv.append_video( + content.video_url.url, + preprocess_kwargs=preprocess_kwargs or None, + ) elif content.type == "audio_url": real_content += audio_token conv.append_audio(content.audio_url.url) diff --git a/python/sglang/srt/parser/jinja_template_utils.py b/python/sglang/srt/parser/jinja_template_utils.py index f22222fd90038..fee4d9d823ae8 100644 --- a/python/sglang/srt/parser/jinja_template_utils.py +++ b/python/sglang/srt/parser/jinja_template_utils.py @@ -9,7 +9,7 @@ import jinja2 import transformers.utils.chat_template_utils as hf_chat_utils -from sglang.srt.utils import ImageData +from sglang.srt.utils import GLM_MEDIA_CONFIG_KEYS, ImageData logger = logging.getLogger(__name__) @@ -120,6 +120,68 @@ def detect_jinja_template_content_format(chat_template: str) -> str: return "string" +def jinja_template_may_reorder_tool_results(chat_template: str) -> bool: + """Return whether a template associates tool results by call ID. + + A template that reads ``tool_call_id`` can emit tool results in an order + other than the request's message order (for example, by iterating the + assistant's ``tool_calls`` and looking up each matching result). Media is + collected from the request in message order, so those templates need a + rendered-order recovery pass to keep media and placeholders aligned. + + Inspecting the parsed template is deliberately model-agnostic: custom and + future templates get the same behavior without a model-name allowlist or a + runtime environment switch, while templates that simply stream messages in + request order pay no per-request recovery cost. + """ + if not isinstance(chat_template, str): + return False + + jinja_ast = _try_extract_ast(chat_template) + if jinja_ast is None: + return False + + def is_tool_call_id(node: jinja2.nodes.Node) -> bool: + return isinstance(node, jinja2.nodes.Const) and node.value == "tool_call_id" + + if any( + node.attr == "tool_call_id" for node in jinja_ast.find_all(jinja2.nodes.Getattr) + ): + return True + + if any( + is_tool_call_id(node.arg) for node in jinja_ast.find_all(jinja2.nodes.Getitem) + ): + return True + + # ``message.get('tool_call_id')`` is another common spelling. + for call in jinja_ast.find_all(jinja2.nodes.Call): + if ( + isinstance(call.node, jinja2.nodes.Getattr) + and call.node.attr == "get" + and call.args + and is_tool_call_id(call.args[0]) + ): + return True + + # Templates can look up or sort result messages without a direct field + # access, e.g. ``messages | selectattr('tool_call_id', 'equalto', id)`` or + # ``messages | sort(attribute='tool_call_id')``. + attribute_filters = {"groupby", "map", "rejectattr", "selectattr", "sort"} + for filter_node in jinja_ast.find_all(jinja2.nodes.Filter): + if filter_node.name not in attribute_filters: + continue + if filter_node.args and is_tool_call_id(filter_node.args[0]): + return True + if any( + keyword.key == "attribute" and is_tool_call_id(keyword.value) + for keyword in filter_node.kwargs + ): + return True + + return False + + def process_content_for_template_format( msg_dict: dict, content_format: str, @@ -179,16 +241,21 @@ def process_content_for_template_format( elif chunk_type == "video_url": video_obj = chunk.get("video_url") or {} mdp = video_obj.get("max_dynamic_patch", None) - if mdp is None: + preprocess_kwargs = { + key: video_obj[key] + for key in GLM_MEDIA_CONFIG_KEYS + if video_obj.get(key) is not None + } + if not preprocess_kwargs and mdp is None: video_data.append(chunk["video_url"]["url"]) else: # Keep structured info for backend, but template only sees {"type":"video"} - video_data.append( - { - "url": video_obj["url"], - "max_dynamic_patch": mdp, - } - ) + item = {"url": video_obj["url"]} + if mdp is not None: + item["max_dynamic_patch"] = mdp + if preprocess_kwargs: + item["preprocess_kwargs"] = preprocess_kwargs + video_data.append(item) if chunk.get("modalities"): modalities.append(chunk.get("modalities")) # Normalize to simple 'video' type for template compatibility diff --git a/python/sglang/srt/parser/template_manager.py b/python/sglang/srt/parser/template_manager.py index f8faabc7c507c..84db5a8265529 100644 --- a/python/sglang/srt/parser/template_manager.py +++ b/python/sglang/srt/parser/template_manager.py @@ -38,7 +38,10 @@ get_conv_template_by_model_path, register_conv_template, ) -from sglang.srt.parser.jinja_template_utils import detect_jinja_template_content_format +from sglang.srt.parser.jinja_template_utils import ( + detect_jinja_template_content_format, + jinja_template_may_reorder_tool_results, +) from sglang.srt.parser.template_detection import ( REASONING_PARSER_RULES, TOOL_CALL_PARSER_RULES, @@ -68,6 +71,7 @@ def __init__(self): self._reasoning_config: Optional[ReasoningToggleConfig] = None self._suggested_reasoning_parser: Optional[str] = None self._suggested_tool_call_parser: Optional[str] = None + self._jinja_template_may_reorder_tool_results: bool = False @property def chat_template_name(self) -> Optional[str]: @@ -109,8 +113,16 @@ def suggested_tool_call_parser(self) -> Optional[str]: """Get the auto-detected tool-call parser name, or None.""" return self._suggested_tool_call_parser + @property + def jinja_template_may_reorder_tool_results(self) -> bool: + """Whether the active Jinja template associates results by call ID.""" + return self._jinja_template_may_reorder_tool_results + def _run_template_detection(self, template, tokenizer) -> None: """Run reasoning pattern and parser detection on a template.""" + self._jinja_template_may_reorder_tool_results = ( + jinja_template_may_reorder_tool_results(template) + ) self._force_reasoning, self._reasoning_config = detect_reasoning_pattern( template ) diff --git a/python/sglang/srt/server_args.py b/python/sglang/srt/server_args.py index a90733df68a82..c9c77addd6aea 100644 --- a/python/sglang/srt/server_args.py +++ b/python/sglang/srt/server_args.py @@ -5058,10 +5058,17 @@ def _disable_breakable_cudagraph_if_incompatible(self): added here as they're discovered. """ cfg = resolving_view(self) - from sglang.srt.configs.model_config import is_deepseek_v4 + from sglang.srt.configs.model_config import ( + is_deepseek_v4, + uses_kda_attention, + ) from sglang.srt.layers.cp.bcg import supports_prefill_cp_bcg rules = [ + ( + "KDA hybrid linear attention", + lambda: uses_kda_attention(self.get_model_config().hf_config), + ), # DSV4 is BCG-compatible but introduces heavy memory pressure: the # c4 indexer scratch is pinned in the capture pool and OOMs. Disable. ( @@ -5770,6 +5777,7 @@ def _handle_model_specific_adjustments(self): "MistralLarge3ForCausalLM", "PixtralForConditionalGeneration", "GlmMoeDsaForCausalLM", + "Glm5NextForConditionalGeneration", "LongcatFlashForCausalLM", "Dots3NoteForCausalLM", ]: @@ -8472,11 +8480,12 @@ def _handle_encoder_disaggregation(self): "KimiK25ForConditionalGeneration", "KimiK3ForConditionalGeneration", "MiMoV2ForCausalLM", + "Glm5NextForConditionalGeneration", ]: raise ValueError( f"Model type {model_arch} is not supported for encoder disaggregation. " f"Supported architectures: Qwen2VL, Qwen3VL, Qwen3.5, InternS2, " - f"Qwen2Audio, Qwen2.5Omni, Dots3-Note, Kimi, MiMoV2." + f"Qwen2Audio, Qwen2.5Omni, Dots3-Note, Kimi, MiMoV2, GLM5Next." ) def _validate_ib_devices(self, device_str: Optional[str]) -> Optional[str]: @@ -8910,6 +8919,16 @@ def _handle_deterministic_inference(self): enable_aiter_allreduce_fusion=False, ) + if ( + "SGLANG_DSA_FUSE_TOPK" not in os.environ + and "SGLANG_NSA_FUSE_TOPK" not in os.environ + ): + os.environ["SGLANG_DSA_FUSE_TOPK"] = "0" + logger.warning( + "SGLANG_DSA_FUSE_TOPK=0 forced for deterministic inference " + "(avoids _append_kpool_tail_to_topk_kernel crash)." + ) + # Moved to the resolution pipeline (arg_groups/overrides.py: # _deterministic_allreduce_fusion_disable), invoked here at its # legacy slot. @@ -8943,6 +8962,7 @@ def _handle_deterministic_inference(self): "PixtralForConditionalGeneration", "GlmMoeDsaForCausalLM", "Glm4MoeLiteForCausalLM", + "Glm5NextForConditionalGeneration", ] except Exception: pass diff --git a/python/sglang/srt/speculative/adaptive_spec_params.py b/python/sglang/srt/speculative/adaptive_spec_params.py index c3c252f82310f..6416b8eb932f8 100644 --- a/python/sglang/srt/speculative/adaptive_spec_params.py +++ b/python/sglang/srt/speculative/adaptive_spec_params.py @@ -21,7 +21,7 @@ DEFAULT_ADAPTIVE_CONFIG: dict[str, dict] = { "1": { - "candidate_steps": [1, 3, 7], + "candidate_steps": [1, 3, 5, 7], "up_hysteresis": 0.0, "down_hysteresis": -0.25, "ceiling_coeff": 0, diff --git a/python/sglang/srt/speculative/eagle_draft_cuda_graph_runner.py b/python/sglang/srt/speculative/eagle_draft_cuda_graph_runner.py index ab2f5ce2758ca..aae5927c3d8bf 100644 --- a/python/sglang/srt/speculative/eagle_draft_cuda_graph_runner.py +++ b/python/sglang/srt/speculative/eagle_draft_cuda_graph_runner.py @@ -237,7 +237,7 @@ def __init__( dsa_seed_topk = ( torch.zeros( - (self.max_bs, self.eagle_worker.dsa_index_topk), + (self.max_bs, self.eagle_worker.dsa_seed_topk_width), dtype=torch.int32, device=model_runner.device, ) diff --git a/python/sglang/srt/speculative/eagle_draft_extend_cuda_graph_runner.py b/python/sglang/srt/speculative/eagle_draft_extend_cuda_graph_runner.py index 2ee2f7c2805dc..e85a552ecb5e6 100644 --- a/python/sglang/srt/speculative/eagle_draft_extend_cuda_graph_runner.py +++ b/python/sglang/srt/speculative/eagle_draft_extend_cuda_graph_runner.py @@ -55,6 +55,20 @@ from sglang.srt.speculative.eagle_worker_v2 import EagleDraftWorker +def resolve_draft_extend_seq_len_fill_value( + attn_backend, captured_req_width: int +) -> int: + """DRAFT_EXTEND_V2 subtracts the fixed draft width when building the KPool + write plan; padding rows need enough synthetic history for that subtraction + plus the KPool offset.""" + fill_value = attn_backend.get_cuda_graph_seq_len_fill_value() + full_attn_backend = getattr(attn_backend, "full_attn_backend", attn_backend) + dsa_index_kpool = getattr(full_attn_backend, "dsa_index_kpool", 1) + if dsa_index_kpool > 1: + fill_value = max(fill_value, captured_req_width + dsa_index_kpool) + return fill_value + + @dataclass class EagleDraftExtendInputBuffers(ForwardInputBuffers): input_ids: torch.Tensor @@ -141,8 +155,8 @@ def __init__( self.draft_extend_attn_backend.init_cuda_graph_state( self.max_bs, self.max_num_token ) - self.seq_len_fill_value = ( - self.draft_extend_attn_backend.get_cuda_graph_seq_len_fill_value() + self.seq_len_fill_value = resolve_draft_extend_seq_len_fill_value( + self.draft_extend_attn_backend, self.captured_req_width ) self.extend_seq_lens_cpu = [self.captured_req_width] * self.max_bs @@ -175,8 +189,8 @@ def __init__( if _hidden_size is not None else None ) - self.seq_len_fill_value = ( - self.draft_extend_attn_backend.get_cuda_graph_seq_len_fill_value() + self.seq_len_fill_value = resolve_draft_extend_seq_len_fill_value( + self.draft_extend_attn_backend, self.captured_req_width ) seq_lens = torch.full( (self.max_bs,), self.seq_len_fill_value, dtype=torch.int64 @@ -237,7 +251,7 @@ def __init__( dsa_seed_topk_capture = ( torch.full( - (self.max_num_token, self.eagle_worker.dsa_index_topk), + (self.max_num_token, self.eagle_worker.dsa_seed_topk_width), -1, dtype=torch.int32, device=model_runner.device, diff --git a/python/sglang/srt/speculative/eagle_utils.py b/python/sglang/srt/speculative/eagle_utils.py index 28cf4610c791a..4d6468a039e6f 100644 --- a/python/sglang/srt/speculative/eagle_utils.py +++ b/python/sglang/srt/speculative/eagle_utils.py @@ -494,21 +494,44 @@ def get_draft_recurrent_hidden_state_spec( return model_runner.model_config.spec_hidden_size, model_runner.model_config.dtype +_PREPARE_FOR_VERIFY_DEPS = None + + def eagle_prepare_for_verify( verify_input: EagleVerifyInput, req_to_token_pool: ReqToTokenPool, batch: ScheduleBatch, target_worker: TpModelWorker, + overlap_plan_stream: bool = False, ): - from sglang.kernels.ops.speculative.cache_locs import ( + # Imports must stay lazy (import-cycle safety) but only need to resolve + # once, not on every decode cycle of this hot path. + global _PREPARE_FOR_VERIFY_DEPS + if _PREPARE_FOR_VERIFY_DEPS is None: + from sglang.kernels.ops.speculative.cache_locs import ( + assign_extend_cache_locs_uniform_func, + ) + from sglang.srt.model_executor.forward_batch_info import ( + CaptureHiddenMode, + ForwardBatch, + ForwardMode, + ) + from sglang.srt.speculative.spec_utils import prepare_mamba_track_for_verify + + _PREPARE_FOR_VERIFY_DEPS = ( + assign_extend_cache_locs_uniform_func, + CaptureHiddenMode, + ForwardBatch, + ForwardMode, + prepare_mamba_track_for_verify, + ) + ( assign_extend_cache_locs_uniform_func, - ) - from sglang.srt.model_executor.forward_batch_info import ( CaptureHiddenMode, ForwardBatch, ForwardMode, - ) - from sglang.srt.speculative.spec_utils import prepare_mamba_track_for_verify + prepare_mamba_track_for_verify, + ) = _PREPARE_FOR_VERIFY_DEPS if not batch.forward_mode.is_idle(): # Assign cache locations @@ -568,7 +591,15 @@ def eagle_prepare_for_verify( verify_forward_batch ) ) - if can_run_cuda_graph: + # Pure full-attention backends can preload graph metadata on the plan + # stream. Recurrent backends opt in only after their metadata path has + # been audited not to touch state still used by the preceding draft. + defer_graph_load = overlap_plan_stream and not getattr( + target_worker.model_runner.attn_backend, + "supports_overlap_plan_stream_graph_load", + True, + ) + if can_run_cuda_graph and not defer_graph_load: target_worker.model_runner.decode_cuda_graph_runner.load_batch( verify_forward_batch ) diff --git a/python/sglang/srt/speculative/eagle_worker_common.py b/python/sglang/srt/speculative/eagle_worker_common.py index 91ce8a1476955..acd9de705de27 100644 --- a/python/sglang/srt/speculative/eagle_worker_common.py +++ b/python/sglang/srt/speculative/eagle_worker_common.py @@ -472,6 +472,7 @@ def run_eagle_verify( metadata_ready_pre_pad: bool, finalize_tree_path: bool, grammar_barrier=None, + verify_handoff_event: Any = None, ) -> GenerationBatchResult: """Shared verify step: target-verify forward, sampling, acceptance bookkeeping. @@ -484,6 +485,10 @@ def run_eagle_verify( - ``finalize_tree_path``: single-layer compacts the accepted tree path to the front of each per-req block for topk > 1; multi-layer has never run this compaction. + - ``verify_handoff_event``: forward-stream event recorded at the + draft/tree frontier; when set, the plan stream waits on it (letting host + planning run ahead) instead of the full ``wait_stream(fwd_stream)``, + which remains the fallback when None. """ fwd_stream = torch.get_device_module(device).current_stream() verify_input: EagleVerifyInput = batch.spec_info @@ -494,11 +499,19 @@ def run_eagle_verify( # Batch 1: Target verify # Prepare for target verify in a separate stream with plan_stream_ctx: + if plan_stream is not None: + if verify_handoff_event is not None: + plan_stream.wait_event(verify_handoff_event) + else: + # Workers without an explicit event ring still need a correct + # draft/tree frontier before plan-stream GPU work can start. + plan_stream.wait_stream(fwd_stream) verify_forward_batch, can_run_cuda_graph = eagle_prepare_for_verify( verify_input, req_to_token_pool, batch, target_worker, + overlap_plan_stream=plan_stream is not None, ) # Cover post-prepare rebinds: draft_token, plan_stream-allocated out_cache_loc. diff --git a/python/sglang/srt/speculative/eagle_worker_v2.py b/python/sglang/srt/speculative/eagle_worker_v2.py index 17233ede844bf..197bf8c2c3960 100644 --- a/python/sglang/srt/speculative/eagle_worker_v2.py +++ b/python/sglang/srt/speculative/eagle_worker_v2.py @@ -7,6 +7,7 @@ import torch from sglang.kernels.ops.speculative.topk1 import draft_topk1_postprocess +from sglang.srt.configs.model_config import get_dsa_mtp_topk_width from sglang.srt.distributed.parallel_state_wrapper import ParallelState from sglang.srt.environ import envs from sglang.srt.hardware_backend.npu.graph_runner.eagle_draft_extend_npu_graph_runner import ( @@ -91,6 +92,7 @@ fast_sample, get_plan_stream, load_token_map, + record_stream_each, renorm_draft_probs, sample_draft_proposal, select_top_k_tokens, @@ -193,6 +195,50 @@ def __init__( self.tree_mask_mode = default_tree_mask_mode() self.plan_stream, self.plan_stream_ctx = get_plan_stream(self.device) + # Keep phase handoffs outside replayed CUDA graphs. The ring prevents + # a later speculative iteration from re-recording an event that an + # earlier plan-stream wait may still reference. One event per kind + # (verify / draft-extend) is recorded per scheduler cycle and only a + # couple of speculative cycles can be in flight, so a small ring is + # ample. + handoff_ring_size = 8 + if self.plan_stream is not None: + event_cls = torch.get_device_module(self.device).Event + self._verify_handoff_events = [ + event_cls() for _ in range(handoff_ring_size) + ] + self._draft_extend_handoff_events = [ + event_cls() for _ in range(handoff_ring_size) + ] + else: + self._verify_handoff_events = [] + self._draft_extend_handoff_events = [] + self._verify_handoff_index = 0 + self._draft_extend_handoff_index = 0 + self._pending_verify_handoff_event = None + + def _record_handoff_event(self, kind: str, stream): + """Record a phase-handoff event on ``stream`` and return it. + + Returns None when no plan stream exists (single-stream mode). Events + come from a fixed per-kind ring; the ring size must exceed the maximum + number of in-flight speculative iterations so an event is never + re-recorded while a plan-stream wait on it is still pending. + """ + if self.plan_stream is None: + return None + if kind == "verify": + events = self._verify_handoff_events + index = self._verify_handoff_index + self._verify_handoff_index += 1 + else: + assert kind == "draft_extend" + events = self._draft_extend_handoff_events + index = self._draft_extend_handoff_index + self._draft_extend_handoff_index += 1 + event = events[index % len(events)] + event.record(stream) + return event def alloc_memory_pool( self, @@ -263,8 +309,13 @@ def _init_dsa_index_share_state(self) -> None: # GLM-5.2 MTP IndexShare: seed reused indexer top-k from draft-extend # (last verified token), not draft-decode step 0. self.dsa_index_topk = getattr(hf_config, "index_topk", None) + self.dsa_seed_topk_width = ( + get_dsa_mtp_topk_width(hf_config) + if self.dsa_index_topk is not None + else None + ) self.seed_dsa_topk_from_draft_extend = ( - self.index_share_for_mtp_iteration and self.dsa_index_topk is not None + self.index_share_for_mtp_iteration and self.dsa_seed_topk_width is not None ) def init_token_map(self): @@ -554,7 +605,7 @@ def draft(self, batch: ScheduleBatch): self.draft_forward(forward_batch) ) - return build_eagle_verify_input( + verify_input = build_eagle_verify_input( batch, draft_input, parent_list, @@ -568,6 +619,13 @@ def draft(self, batch: ScheduleBatch): tree_mask_mode=self.tree_mask_mode, device=self.device, ) + # Publish the exact forward-stream frontier that produced the tree and + # verify inputs. Host planning can run ahead, while dependent GPU work + # on the plan stream waits for this event. + self._pending_verify_handoff_event = self._record_handoff_event( + "verify", torch.get_device_module(self.device).current_stream() + ) + return verify_input def draft_forward(self, forward_batch: ForwardBatch): # Parse args @@ -891,11 +949,11 @@ def _draft_extend_for_prefill( ) def _get_dsa_extend_topk_buf(self, num_tokens: int) -> torch.Tensor: - """Lazily-grown int32 [num_tokens, index_topk] eager draft-extend seed buffer.""" + """Lazily grow the eager draft-extend MTP seed buffer.""" buf = self.dsa_extend_topk_buf if buf is None or buf.shape[0] < num_tokens: buf = torch.full( - (num_tokens, self.dsa_index_topk), + (num_tokens, self.dsa_seed_topk_width), -1, dtype=torch.int32, device=self.device, @@ -906,6 +964,7 @@ def _get_dsa_extend_topk_buf(self, num_tokens: int) -> torch.Tensor: def _draft_extend_for_decode( self, batch: ScheduleBatch, batch_result: GenerationBatchResult ): + fwd_stream = torch.get_device_module(self.device).current_stream() # Batch 2: Draft extend draft_extend_input = EagleDraftExtendInput( hidden_states=batch_result.logits_output.hidden_states, @@ -931,9 +990,14 @@ def _draft_extend_for_decode( # Cast to int64 before entering plan stream to avoid cross-stream # synchronization issues with .to() inside the plan stream context. next_token_ids = batch_result.next_token_ids.to(torch.int64) + draft_extend_handoff_event = self._record_handoff_event( + "draft_extend", fwd_stream + ) # Prepare for draft extend in a separate stream with self.plan_stream_ctx: + if self.plan_stream is not None: + self.plan_stream.wait_event(draft_extend_handoff_event) forward_batch = prepare_for_draft_extend( draft_extend_input, batch, @@ -944,10 +1008,27 @@ def _draft_extend_for_decode( return_hidden_states_before_norm=False, ) + # These tensors are allocated/prepared on the plan stream and consumed + # asynchronously by copies and graph replay on the forward stream. + record_stream_each( + ( + forward_batch.input_ids, + forward_batch.req_pool_indices, + forward_batch.seq_lens, + forward_batch.out_cache_loc, + forward_batch.positions, + forward_batch.extend_seq_lens, + forward_batch.extend_prefix_lens, + forward_batch.extend_start_loc, + forward_batch.spec_info.hidden_states, + forward_batch.spec_info.num_correct_drafts, + forward_batch.spec_info.num_accept_tokens, + ), + fwd_stream, + ) + if self.plan_stream: - torch.get_device_module(self.device).current_stream().wait_stream( - self.plan_stream - ) + fwd_stream.wait_stream(self.plan_stream) # Run draft extend batch in the main compute stream can_run_decode_cuda_graph = ( @@ -1215,6 +1296,18 @@ def forward_batch_generation( # Drafting disabled (high batch size). _draft_extend below still # runs, keeping draft KV warm for when the batch shrinks. verify_input = self._build_trivial_verify_input(batch) + # The trivial input is produced on the current forward stream + # just like a drafted one, but this path bypasses draft() -- + # the only other site recording the verify handoff event. + # Record this cycle's frontier here so the plan-stream verify + # wait neither asserts on a first zero-step cycle nor reuses + # a stale event after an adaptive downshift. + self.draft_worker._pending_verify_handoff_event = ( + self.draft_worker._record_handoff_event( + "verify", + torch.get_device_module(self.device).current_stream(), + ) + ) else: with ( self.draft_worker.draft_tp_context( @@ -1545,6 +1638,9 @@ def _override_worker_state( dw._rebuild_topk1_chain_buffers() def verify(self, batch: ScheduleBatch, grammar_barrier=None): + verify_handoff_event = self.draft_worker._pending_verify_handoff_event + if self.plan_stream is not None: + assert verify_handoff_event is not None return run_eagle_verify( batch, target_worker=self.target_worker, @@ -1558,6 +1654,7 @@ def verify(self, batch: ScheduleBatch, grammar_barrier=None): metadata_ready_pre_pad=False, finalize_tree_path=True, grammar_barrier=grammar_barrier, + verify_handoff_event=verify_handoff_event, ) def update_weights_from_tensor(self, recv_req: UpdateWeightsFromTensorReqInput): diff --git a/python/sglang/srt/speculative/spec_utils.py b/python/sglang/srt/speculative/spec_utils.py index b0fb39c539155..18d48bf3107cc 100644 --- a/python/sglang/srt/speculative/spec_utils.py +++ b/python/sglang/srt/speculative/spec_utils.py @@ -213,13 +213,23 @@ def draft_kv_indices_used_len( def record_stream_each(tensors, stream): - """Call record_stream(stream) on each cuda tensor in `tensors`, skipping - non-tensor / non-cuda entries. Tells the caching allocator that the + """Call record_stream(stream) on each accelerator tensor in `tensors`, + skipping non-tensor / host entries. Tells the caching allocator that the tensors are also used on `stream`, so memory is not recycled while queued work is still in flight after Python refs drop. + + Guarded by device type, not ``is_cuda``: the overlap plan stream runs on + every accelerator with a stream module (NPU/MUSA/XPU included, HIP + reports as cuda), and their caching allocators need the same + cross-stream lifetime hint. """ for t in tensors: - if isinstance(t, torch.Tensor) and t.is_cuda: + if isinstance(t, torch.Tensor) and t.device.type in ( + "cuda", + "npu", + "musa", + "xpu", + ): t.record_stream(stream) @@ -1012,17 +1022,106 @@ def commit_mamba_states_after_verify( bs = accept_lens.shape[0] # `accept_lens` already includes the bonus token (drafts + 1 per req). if not batch.forward_mode.is_idle() and accept_index.numel() > 0: - last_correct_step_indices, mamba_steps_to_track = _verify_commit_step_indices( - batch=batch, - accept_index=accept_index, - accept_lens=accept_lens, - draft_token_num=draft_token_num, - ) + speculative_eagle_topk = get_spec().speculative_eagle_topk + mamba_track_interval = mamba_track_grid(batch.tree_cache.page_size) + track_indices_to_pass = batch.mamba_track_indices + if _is_cuda and not _is_hip and speculative_eagle_topk in (None, 1): + # Chain spec: accept_index[i, j] == i*draft + j on accepted slots, + # so both gathers below are identities (last step = accept_lens-1, + # candidate step = its own index). One fused launch replaces the + # ~21-op eager prologue. + from sglang.kernels.ops.speculative.eagle import ( + nextn_mamba_commit_prologue_func, + ) + + has_track = track_indices_to_pass is not None + if has_track: + # Host-side sufficient no-crossing test: post-verify length is + # at most pre + draft_token_num (accept_lens includes the + # bonus and is capped at draft_token_num), so identical + # interval buckets for pre and pre+draft rule out any + # interval crossing this cycle — the whole track commit + # (two scatter launches + wrappers) can be skipped. + seq_lens_cpu = getattr(batch, "seq_lens_cpu", None) + interval = mamba_track_interval + if seq_lens_cpu is not None and seq_lens_cpu.numel() == bs: + if bool( + torch.all( + seq_lens_cpu // interval + == (seq_lens_cpu + draft_token_num) // interval + ) + ): + has_track = False + track_indices_to_pass = None + elif interval > 0: + # GPU-only seq_lens (a backend that sets + # needs_cpu_seq_lens = False, e.g. KDA): no CPU + # mirror, so bound the true pre-verify length with the + # scheduler's host counter instead of reading it. + # req.kv_committed_len only advances when a verify + # result is resolved (batch_result_processor), so it is + # a LOWER bound on the device seq_lens, lagging by at + # most one in-flight verify in overlap mode — the same + # lag the doubled alloc reserve absorbs (see + # eagle_prepare_for_decode / get_alloc_reserve_per_decode). + # A verify commits at most the draft size's tokens + # (accept_lens includes the bonus), so with the matching + # 2x safety margin: + # pre_verify_len in [lb, lb + 2 * max_draft] + # and post-verify adds at most max_draft more. + # max_draft must be the CONFIGURED maximum, not this + # cycle's draft_token_num: with adaptive speculation the + # in-flight verify the counter lags behind may have used + # a larger draft than the current (downshifted) cycle, + # and the alloc reserve this lag argument leans on is + # sized by the configured value. Note the plain + # speculative_num_draft_tokens field is NOT that maximum: + # adaptive gear switches sync it to the current gear + # (server_args.override in _restore_worker_state); the + # max_ property is derived from the immutable candidate + # config. floor(x / interval) is monotone, so if lb and + # lb + 3 * max_draft share a bucket, every length + # reachable this cycle does too — no crossing is + # possible and the track commit can be skipped. Any + # uncertainty (missing counter, req/row mismatch) keeps + # the exact full path. + reqs = getattr(batch, "reqs", None) + if reqs is not None and len(reqs) == bs: + max_draft = ( + max_speculative_num_draft_tokens() or draft_token_num + ) + reach = 3 * max_draft + skip_track = True + for req in reqs: + lb = getattr(req, "kv_committed_len", None) + if lb is None or lb // interval != (lb + reach) // interval: + skip_track = False + break + if skip_track: + has_track = False + track_indices_to_pass = None + last_correct_step_indices, mamba_steps_to_track = ( + nextn_mamba_commit_prologue_func( + accept_lens, + batch.seq_lens, + mamba_track_interval if has_track else 0, + has_track, + ) + ) + else: + last_correct_step_indices, mamba_steps_to_track = ( + _verify_commit_step_indices( + batch=batch, + accept_index=accept_index, + accept_lens=accept_lens, + draft_token_num=draft_token_num, + ) + ) if hasattr(attn_backend, "update_mamba_state_after_mtp_verify"): attn_backend.update_mamba_state_after_mtp_verify( last_correct_step_indices=last_correct_step_indices, - mamba_track_indices=batch.mamba_track_indices, + mamba_track_indices=track_indices_to_pass, mamba_steps_to_track=mamba_steps_to_track, model=model_runner.model, req_pool_indices=batch.req_pool_indices[:bs], @@ -1050,6 +1149,12 @@ def spec_prepare_for_decode(batch: ScheduleBatch) -> None: def get_plan_stream( device: str, ) -> Tuple[Any, contextlib.AbstractContextManager]: + """Return (plan_stream, ctx) when SGLANG_ENABLE_OVERLAP_PLAN_STREAM is on. + + With the flag off this returns (None, nullcontext()), so callers can + unconditionally enter the context and check ``plan_stream is None`` to + detect the single-stream fallback. + """ if envs.SGLANG_ENABLE_OVERLAP_PLAN_STREAM.get(): plan_stream = torch.get_device_module(device).Stream() plan_stream_ctx = torch.get_device_module(device).stream(plan_stream) diff --git a/python/sglang/srt/speculative/standalone_worker_v2.py b/python/sglang/srt/speculative/standalone_worker_v2.py index 82dd49fc5ac97..9b6c591045649 100644 --- a/python/sglang/srt/speculative/standalone_worker_v2.py +++ b/python/sglang/srt/speculative/standalone_worker_v2.py @@ -110,6 +110,7 @@ def __init__( and self.topk == 1 ) self.dsa_index_topk = None + self.dsa_seed_topk_width = None self.seed_dsa_topk_from_draft_extend = False self.dsa_extend_topk_buf = None diff --git a/python/sglang/srt/utils/common.py b/python/sglang/srt/utils/common.py index 8f826768e8f3c..4b303e4f5e01f 100644 --- a/python/sglang/srt/utils/common.py +++ b/python/sglang/srt/utils/common.py @@ -87,7 +87,7 @@ import torch.distributed as dist import triton from packaging import version as pkg_version -from PIL import Image, UnidentifiedImageError +from PIL import Image, ImageOps, UnidentifiedImageError from starlette.routing import Mount from torch import nn from torch.library import Library @@ -1792,6 +1792,14 @@ class ImageData: content_hash: Optional[str] = None +GLM_MEDIA_CONFIG_KEYS = ( + "fps", + "max_frames", + "max_tokens_per_frame", + "max_image_tokens", +) + + @dataclass class VideoData: url: str @@ -1802,6 +1810,45 @@ class VideoData: GPUImageDecodeMode = Union[bool, Literal["nvjpeg_fancy"]] +def smart_to_rgb( + image: Union[torch.Tensor, Image.Image], +) -> Union[torch.Tensor, Image.Image]: + if not isinstance(image, Image.Image): + return image + + image = ImageOps.exif_transpose(image) + if image.mode in ("RGBA", "LA") or "transparency" in image.info: + image = image.convert("RGBA") + width, height = image.size + edge_pixels = [] + + for x in range(0, width, max(1, width // 20)): + for y in (0, height - 1): + pixel = image.getpixel((x, y)) + if pixel[3] > 128: + edge_pixels.append(pixel[:3]) + + for y in range(0, height, max(1, height // 20)): + for x in (0, width - 1): + pixel = image.getpixel((x, y)) + if pixel[3] > 128: + edge_pixels.append(pixel[:3]) + + if edge_pixels: + avg_brightness = sum(sum(pixel) for pixel in edge_pixels) / ( + len(edge_pixels) * 3 + ) + background_color = (32, 32, 32) if avg_brightness > 128 else (240, 240, 240) + else: + background_color = (255, 255, 255) + + background = Image.new("RGB", image.size, background_color) + background.paste(image, mask=image.getchannel("A")) + return background + + return image.convert("RGB") + + def is_jpeg_with_cuda( image_bytes: bytes = b"", gpu_image_decode: GPUImageDecodeMode = True ) -> bool: @@ -1898,6 +1945,8 @@ def load_image( image = _load_image(image_file=image_file, gpu_image_decode=gpu_image_decode) else: raise ValueError(f"Invalid image: {image_file}") + if image_size is not None and isinstance(image, Image.Image): + image_size = (image.width, image.height) return image, image_size diff --git a/python/sglang/srt/utils/hf_transformers/common.py b/python/sglang/srt/utils/hf_transformers/common.py index 5ffa8530c4d70..77fd3675c3bcf 100644 --- a/python/sglang/srt/utils/hf_transformers/common.py +++ b/python/sglang/srt/utils/hf_transformers/common.py @@ -32,6 +32,8 @@ DotsVLMConfig, ExaoneConfig, FalconH1Config, + Glm5NextConfig, + Glm5NextTextConfig, GraniteMoeHybridConfig, InklingAudioConfig, InklingMMConfig, @@ -110,6 +112,8 @@ MuseGlimmerConfig, MuseGlimmerAssistantConfig, KimiK3Config, + Glm5NextConfig, + Glm5NextTextConfig, KimiLinearConfig, Qwen3NextConfig, FalconH1Config, diff --git a/python/sglang/srt/utils/video_decoder.py b/python/sglang/srt/utils/video_decoder.py index 0dfec642f0eb5..48277187fd9e5 100644 --- a/python/sglang/srt/utils/video_decoder.py +++ b/python/sglang/srt/utils/video_decoder.py @@ -87,9 +87,11 @@ def __len__(self): return len(self._decoder) def __getitem__(self, idx): - """Return single frame as numpy NHWC uint8.""" + """Return one NHWC uint8 frame (numpy on CPU, tensor on CUDA).""" if _BACKEND == "torchcodec": - return self._decoder[idx].numpy() + frame = self._decoder[idx] + data = frame.data if hasattr(frame, "data") else frame + return data if data.is_cuda else data.numpy() else: frame = self._decoder[idx] return frame.asnumpy() if hasattr(frame, "asnumpy") else np.array(frame) @@ -101,11 +103,22 @@ def avg_fps(self) -> float: else: return self._decoder.get_avg_fps() - def get_frames_at(self, indices: list) -> np.ndarray: - """Return frames at given indices as numpy array with shape (N, H, W, C).""" + @property + def frame_shape(self) -> tuple[int, int]: + if _BACKEND == "torchcodec": + metadata = self._decoder.metadata + height = getattr(metadata, "height", None) + width = getattr(metadata, "width", None) + if height and width: + return int(height), int(width) + shape = self[0].shape + return int(shape[-3]), int(shape[-2]) + + def get_frames_at(self, indices: list): + """Return NHWC uint8 frames (numpy on CPU, tensor on CUDA).""" if _BACKEND == "torchcodec": batch = self._decoder.get_frames_at(indices) - return batch.data.numpy() + return batch.data if batch.data.is_cuda else batch.data.numpy() else: return self._decoder.get_batch(indices).asnumpy() @@ -127,7 +140,7 @@ def get_frames_as_tensor(self, indices: list): if _BACKEND == "torchcodec": batch = self._decoder.get_frames_at(indices) - return batch.data.pin_memory() + return batch.data if batch.data.is_cuda else batch.data.pin_memory() else: arr = self._decoder.get_batch(indices).asnumpy() return torch.from_numpy(arr).pin_memory() @@ -141,8 +154,15 @@ def _parallel_decode(self, indices, num_threads): chunks = [list(c) for c in np.array_split(indices, num_threads) if len(c) > 0] source = self._source kwargs = self._tc_kwargs + cuda_device = None + if kwargs.get("device") == "cuda": + cuda_device = torch.cuda.current_device() def _decode_chunk(chunk): + # CUDA's current device is thread-local. Without this, decoder + # workers created by TP rank > 0 silently default to GPU 0. + if cuda_device is not None: + torch.cuda.set_device(cuda_device) d = VideoDecoder(source, **kwargs) return d.get_frames_at(chunk).data @@ -156,7 +176,8 @@ def _decode_chunk(chunk): idx = future_to_idx[future] results[idx] = future.result() - return torch.cat(results, dim=0).pin_memory() + output = torch.cat(results, dim=0) + return output if output.is_cuda else output.pin_memory() @property def source_bytes(self) -> bytes | None: @@ -171,8 +192,12 @@ def source_bytes(self) -> bytes | None: return None def close(self): - """Explicitly clean up temporary files.""" - if self._tmp_path is not None: + """Release decoder state, retained source bytes, and temporary files.""" + self._decoder = None + self._source = None + self._source_bytes = None + self._source_path = None + if getattr(self, "_tmp_path", None) is not None: if os.path.exists(self._tmp_path): os.unlink(self._tmp_path) self._tmp_path = None diff --git a/test/registered/dcp/test_dcp_layout_unit.py b/test/registered/dcp/test_dcp_layout_unit.py index 53242ec0f3916..84a174e50f4c7 100644 --- a/test/registered/dcp/test_dcp_layout_unit.py +++ b/test/registered/dcp/test_dcp_layout_unit.py @@ -435,6 +435,30 @@ def test_configurator_scales_only_the_virtual_dcp_allocator(self): self.assertEqual(dcp4_allocator.page_size, 256) self.assertEqual(dcp4_allocator.num_pages, 16) + def test_dsa_draft_pool_preserves_physical_page_and_backs_virtual_tail(self): + physical_page_size = 64 + max_total_num_tokens = 4096 + self._sa_override = rc.get_context().override_server_args( + page_size=physical_page_size + ) + self._sa_override.install() + self.addCleanup(self._sa_override.restore) + + dcp1 = SimpleNamespace(pool_page_size=physical_page_size) + dcp4_draft = SimpleNamespace(pool_page_size=physical_page_size * 4) + + self.assertEqual( + KVCacheConfigurator._dsa_pool_geometry(dcp1, max_total_num_tokens), + (max_total_num_tokens, physical_page_size), + ) + self.assertEqual( + KVCacheConfigurator._dsa_pool_geometry(dcp4_draft, max_total_num_tokens), + ( + max_total_num_tokens + physical_page_size * 3, + physical_page_size, + ), + ) + def test_live_cell_and_page_ownership_formulas(self): dcp_size = 4 physical_page_size = 64 diff --git a/test/registered/kernels/ops/attention/test_dsa_indexer.py b/test/registered/kernels/ops/attention/test_dsa_indexer.py index 25f014347f5e2..3948629ae0725 100644 --- a/test/registered/kernels/ops/attention/test_dsa_indexer.py +++ b/test/registered/kernels/ops/attention/test_dsa_indexer.py @@ -217,6 +217,7 @@ def __init__(self, config=None): self.sliding_window_size = None self.page_size = self.config["page_size"] + self.max_running_requests = max_batch_size # Create req_to_token_pool self.req_to_token_pool = type( @@ -1093,6 +1094,7 @@ def test_topk_v2_respects_topk_backend(self): backend.use_fused_topk = True backend.dsa_topk_backend = topk_backend backend.dsa_index_topk = 2048 + backend.dsa_index_kpool = 1 backend.dsa_decode_impl = "fa3" backend.req_to_token = torch.empty( 2, 4096, dtype=torch.int32, device=self.device diff --git a/test/registered/kernels/ops/attention/test_fused_verify_triton_gdn.py b/test/registered/kernels/ops/attention/test_fused_verify_triton_gdn.py index 30e89f8d52d47..fd5791f85fb2c 100644 --- a/test/registered/kernels/ops/attention/test_fused_verify_triton_gdn.py +++ b/test/registered/kernels/ops/attention/test_fused_verify_triton_gdn.py @@ -26,7 +26,7 @@ except ImportError: KERNELS_AVAILABLE = False -register_cuda_ci(est_time=6, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=20, stage="base-b-kernel-unit", runner_config="1-gpu-large") register_amd_ci(est_time=10, suite="nightly-amd-kernel-1-gpu", nightly=True) @@ -234,5 +234,40 @@ def test_mtp_single_step_decode(N: int): assert state_fail_rate < 0.01, f"State mismatch: fail_rate={state_fail_rate:.2f}%" +@pytest.mark.skipif(not KERNELS_AVAILABLE, reason="Kernels not available") +def test_verify_scratch_pitch_uses_allocated_steps(): + # Gear below the allocated step dim must not spill into the neighbor block. + N, T, ALLOCATED = 2, 4, 8 + H, HV, K, V = 16, 32, 128, 128 + + A_log, dt_bias, a, b, q, k, v, state, indices, cu_seqlens = _make_tensors( + N, T, H, HV, K, V + ) + buffer = torch.full( + (N + 1, ALLOCATED, HV, V, K), float("nan"), dtype=torch.float32, device="cuda" + ) + + run_fused_mtp( + A_log, + dt_bias, + q, + k, + v, + a, + b, + state, + indices, + cu_seqlens, + disable_state_update=True, + intermediate_states_buffer=buffer, + intermediate_state_indices=indices, + cache_steps=T, + ) + + assert not torch.isnan(buffer[:N, :T]).any() + assert torch.isnan(buffer[N:]).all() + assert torch.isnan(buffer[:N, T:]).all() + + if __name__ == "__main__": sys.exit(pytest.main([__file__, "-v", "-s"])) diff --git a/test/registered/kernels/ops/attention/test_silu_and_mul_clamp.py b/test/registered/kernels/ops/attention/test_silu_and_mul_clamp.py new file mode 100644 index 0000000000000..6e81fa7173505 --- /dev/null +++ b/test/registered/kernels/ops/attention/test_silu_and_mul_clamp.py @@ -0,0 +1,90 @@ +import sys + +import pytest +import torch +import torch.nn.functional as F + +from sglang.kernels.ops.attention.dsv4 import silu_and_mul_clamp +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available() or torch.version.cuda is None, + reason="silu_and_mul_clamp requires CUDA", +) + + +def _reference(input: torch.Tensor, limit: float) -> torch.Tensor: + gate, up = input.chunk(2, dim=-1) + limit_tensor = torch.tensor(limit, dtype=input.dtype, device=input.device) + gate = torch.minimum(gate, limit_tensor) + up = torch.minimum(torch.maximum(up, -limit_tensor), limit_tensor) + return (F.silu(gate.float()) * up.float()).to(input.dtype) + + +@pytest.mark.parametrize("num_tokens", [1, 4]) +@pytest.mark.parametrize("hidden_size", [4096, 8192, 16384]) +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16]) +def test_silu_and_mul_clamp_matches_reference( + num_tokens: int, hidden_size: int, dtype: torch.dtype +) -> None: + generator = torch.Generator(device="cuda").manual_seed(hidden_size + num_tokens) + input = ( + torch.randn( + num_tokens, + hidden_size * 2, + generator=generator, + device="cuda", + dtype=torch.float32, + ) + * 8 + ).to(dtype) + output = torch.full( + (num_tokens, hidden_size), + float("nan"), + device="cuda", + dtype=dtype, + ) + + silu_and_mul_clamp(input, output, 7.0) + torch.cuda.synchronize() + + assert torch.isfinite(output).all() + torch.testing.assert_close(output, _reference(input, 7.0), rtol=2e-2, atol=5e-2) + + +def test_silu_and_mul_clamp_rejects_mismatched_width() -> None: + input = torch.randn(1, 8192, device="cuda", dtype=torch.bfloat16) + output = torch.empty(1, 4104, device="cuda", dtype=torch.bfloat16) + + with pytest.raises(RuntimeError, match="input last dim must be 2"): + silu_and_mul_clamp(input, output, 7.0) + + +def test_silu_and_mul_clamp_rejects_unaligned_width() -> None: + input = torch.randn(1, 8200, device="cuda", dtype=torch.bfloat16) + output = torch.empty(1, 4100, device="cuda", dtype=torch.bfloat16) + + with pytest.raises(RuntimeError, match="out_dim must be divisible by vector size"): + silu_and_mul_clamp(input, output, 7.0) + + +def test_silu_and_mul_clamp_rejects_empty_width() -> None: + input = torch.empty(1, 0, device="cuda", dtype=torch.bfloat16) + output = torch.empty_like(input) + + with pytest.raises(RuntimeError, match="out_dim must be positive"): + silu_and_mul_clamp(input, output, 7.0) + + +def test_silu_and_mul_clamp_rejects_output_dtype_mismatch() -> None: + input = torch.randn(1, 8192, device="cuda", dtype=torch.bfloat16) + output = torch.empty(1, 4096, device="cuda", dtype=torch.float16) + + with pytest.raises(RuntimeError, match="Dtype value.*not in the allowed options"): + silu_and_mul_clamp(input, output, 7.0) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/test/registered/kernels/ops/moe/test_minimax_quant_scatter.py b/test/registered/kernels/ops/moe/test_minimax_quant_scatter.py index 99ecf1a0b2293..436036b0cdff1 100644 --- a/test/registered/kernels/ops/moe/test_minimax_quant_scatter.py +++ b/test/registered/kernels/ops/moe/test_minimax_quant_scatter.py @@ -7,6 +7,7 @@ import sglang.srt.layers.moe.moe_runner.deep_gemm as deep_gemm_runner from sglang.kernels.ops.moe.ep_moe_kernels import ( + ep_scatter, fill_gateup_input_triton_kernel, moe_ep_deepgemm_preprocess, ) @@ -139,6 +140,44 @@ def test_standard_deepgemm_preprocess_quantizes_with_ue8m0_scale(): ) +def test_ep_scatter_initializes_compact_expert_offsets(): + hidden_states = torch.arange(3 * 128, device=dev, dtype=torch.bfloat16).reshape( + 3, 128 + ) + topk_ids = torch.tensor([[0], [1], [0]], device=dev, dtype=torch.int32) + padded_tokens_per_expert = torch.tensor([128, 128], device=dev, dtype=torch.int32) + valid_tokens_per_expert = torch.tensor([2, 1], device=dev, dtype=torch.int32) + expert_start_loc = torch.zeros(2, device=dev, dtype=torch.int32) + packed_hidden_states = torch.zeros(256, 128, device=dev, dtype=torch.bfloat16) + m_indices = torch.full((256,), -2, device=dev, dtype=torch.int32) + src2dst = torch.full((3, 1), -1, device=dev, dtype=torch.int32) + + ep_scatter( + hidden_states, + None, + topk_ids, + padded_tokens_per_expert, + valid_tokens_per_expert, + expert_start_loc, + packed_hidden_states, + torch.empty(0, device=dev), + m_indices, + src2dst, + ) + torch.cuda.synchronize() + + assert torch.equal( + expert_start_loc.cpu(), torch.tensor([2, 129], dtype=torch.int32) + ) + src2dst_cpu = src2dst.cpu().flatten() + assert set(src2dst_cpu[[0, 2]].tolist()) == {0, 1} + assert src2dst_cpu[1].item() == 128 + assert torch.equal(m_indices[:2].cpu(), torch.tensor([0, 0], dtype=torch.int32)) + assert torch.equal(m_indices[128:129].cpu(), torch.tensor([1], dtype=torch.int32)) + for token_id, dst in enumerate(src2dst_cpu.tolist()): + assert torch.equal(packed_hidden_states[dst], hidden_states[token_id]) + + @pytest.mark.parametrize( "num_assignments,num_experts,expected", [ diff --git a/test/registered/kernels/test_dsa_kpool_multi_pool.py b/test/registered/kernels/test_dsa_kpool_multi_pool.py new file mode 100644 index 0000000000000..26ce445333f00 --- /dev/null +++ b/test/registered/kernels/test_dsa_kpool_multi_pool.py @@ -0,0 +1,213 @@ +"""CUDA regressions for DSA kpool speculative writes spanning multiple pools.""" + +import unittest +from types import SimpleNamespace + +import torch + +from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( + INDEX_HEAD_DIM, + kpool_assemble_softmax_rotate_write_cache, + kpool_max_closed_pools, + kpool_write_tail_and_maybe_compress, + update_kpool_write_plan_cuda_graph, +) +from sglang.srt.layers.attention.dsa.kpool_plan import ( + _alloc_kpool_write_plan_buffers, +) +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=15, stage="base-b-kernel-unit", runner_config="1-gpu-large") + + +@unittest.skipUnless(torch.cuda.is_available(), "Test requires CUDA") +class TestDsaKpoolMultiPool(CustomTestCase): + POOL_SIZE = 4 + PAGE_SIZE = 64 + SLOTS_PER_PAGE = 64 + NUM_DRAFT_TOKENS = 6 + + def _pool(self) -> SimpleNamespace: + return SimpleNamespace( + page_size=self.PAGE_SIZE, + index_head_dim=INDEX_HEAD_DIM, + slots_per_page=self.SLOTS_PER_PAGE, + index_kpool=self.POOL_SIZE, + tail_extra_slots=self.NUM_DRAFT_TOKENS, + quant_block_size=128, + ) + + def _empty_cache(self) -> torch.Tensor: + page_nbytes = self.SLOTS_PER_PAGE * INDEX_HEAD_DIM + self.SLOTS_PER_PAGE * 4 + return torch.zeros((1, page_nbytes), dtype=torch.uint8, device="cuda") + + def test_write_plan_records_every_candidate_pool(self): + batch_size = 2 + num_draft_tokens = self.NUM_DRAFT_TOKENS + max_closed_pools = kpool_max_closed_pools(num_draft_tokens, self.POOL_SIZE) + self.assertEqual(max_closed_pools, 2) + + plan = _alloc_kpool_write_plan_buffers( + max_bs=batch_size, + num_draft_tokens=num_draft_tokens, + pool_size=self.POOL_SIZE, + device=torch.device("cuda"), + is_verify=True, + ) + self.assertEqual(plan.write_loc.shape, (batch_size, max_closed_pools)) + + write_start = torch.tensor([3, 255], dtype=torch.int32, device="cuda") + req_pool_indices = torch.tensor([7, 11], dtype=torch.int64, device="cuda") + real_page_table = torch.zeros( + (batch_size * num_draft_tokens, 8), + dtype=torch.int32, + device="cuda", + ) + real_page_table[:num_draft_tokens, 0] = 2 + real_page_table[:num_draft_tokens, 4] = 3 + real_page_table[num_draft_tokens:, 0] = 5 + real_page_table[num_draft_tokens:, 4] = 6 + + update_kpool_write_plan_cuda_graph( + write_start=write_start, + req_pool_indices=req_pool_indices, + real_page_table=real_page_table, + req_out=plan.req, + write_start_out=plan.write_start, + tail_logical_start_out=plan.tail_logical_start, + write_loc_out=plan.write_loc, + pool_seqlens_per_q_out=plan.pool_seqlens_per_q, + seqlens_per_q_out=plan.seqlens_per_q, + pool_size=self.POOL_SIZE, + num_draft_tokens=num_draft_tokens, + slots_per_page=self.SLOTS_PER_PAGE, + ) + + torch.testing.assert_close(plan.req, req_pool_indices) + torch.testing.assert_close(plan.write_start, write_start) + torch.testing.assert_close( + plan.tail_logical_start, + torch.tensor([0, 252], dtype=torch.int32, device="cuda"), + ) + torch.testing.assert_close( + plan.write_loc, + torch.tensor( + [ + [2 * self.SLOTS_PER_PAGE, 2 * self.SLOTS_PER_PAGE + 1], + [ + 5 * self.SLOTS_PER_PAGE + 63, + 6 * self.SLOTS_PER_PAGE, + ], + ], + dtype=torch.int64, + device="cuda", + ), + ) + + def _run_compress_case(self, effective_n: int, expected_closed_pools: int): + torch.manual_seed(42) + pool = self._pool() + num_draft_tokens = self.NUM_DRAFT_TOKENS + tail_size = self.POOL_SIZE + num_draft_tokens + write_start_value = 3 + + key = torch.randn( + num_draft_tokens, INDEX_HEAD_DIM, dtype=torch.bfloat16, device="cuda" + ) + score = torch.randn_like(key) + ape = torch.randn( + self.POOL_SIZE, INDEX_HEAD_DIM, dtype=torch.float32, device="cuda" + ) + tail_k_initial = torch.randn( + 1, tail_size, INDEX_HEAD_DIM, dtype=torch.bfloat16, device="cuda" + ) + tail_score_initial = torch.randn_like(tail_k_initial) + + tail_k_expected = tail_k_initial.clone() + tail_score_expected = tail_score_initial.clone() + for i in range(num_draft_tokens): + physical_slot = (write_start_value + i) % tail_size + tail_k_expected[0, physical_slot] = key[i] + tail_score_expected[0, physical_slot] = score[i] + + expected_cache = self._empty_cache() + dummy_chunk = torch.zeros( + 1, INDEX_HEAD_DIM, dtype=torch.bfloat16, device="cuda" + ) + kpool_assemble_softmax_rotate_write_cache( + pool=pool, + buf=expected_cache, + chunk_k=dummy_chunk, + chunk_score=dummy_chunk, + tail_k=tail_k_expected, + tail_score=tail_score_expected, + req_pool_idx=torch.zeros( + expected_closed_pools, dtype=torch.int64, device="cuda" + ), + n_from_tail=torch.full( + (expected_closed_pools,), + self.POOL_SIZE, + dtype=torch.int32, + device="cuda", + ), + chunk_src_start=torch.zeros( + expected_closed_pools, dtype=torch.int64, device="cuda" + ), + tail_logical_base=torch.arange( + 0, + expected_closed_pools * self.POOL_SIZE, + self.POOL_SIZE, + dtype=torch.int32, + device="cuda", + ), + ape=ape, + loc=torch.arange(expected_closed_pools, dtype=torch.int64, device="cuda"), + round_scale=False, + ) + + actual_cache = self._empty_cache() + tail_k_actual = tail_k_initial.clone() + tail_score_actual = tail_score_initial.clone() + kpool_write_tail_and_maybe_compress( + pool=pool, + buf=actual_cache, + key=key, + score=score, + tail_k=tail_k_actual, + tail_score=tail_score_actual, + ape=ape, + req_pool_indices=torch.zeros(1, dtype=torch.int64, device="cuda"), + write_start=torch.tensor( + [write_start_value], dtype=torch.int32, device="cuda" + ), + tail_logical_start=torch.zeros(1, dtype=torch.int32, device="cuda"), + write_loc=torch.tensor([[0, 1]], dtype=torch.int64, device="cuda"), + out_cache_loc=torch.arange( + 1, num_draft_tokens + 1, dtype=torch.int64, device="cuda" + ), + num_draft_tokens=num_draft_tokens, + round_scale=False, + effective_n_per_batch=torch.tensor( + [effective_n], dtype=torch.int32, device="cuda" + ), + ) + + torch.testing.assert_close(tail_k_actual, tail_k_expected, atol=0, rtol=0) + torch.testing.assert_close( + tail_score_actual, tail_score_expected, atol=0, rtol=0 + ) + torch.testing.assert_close(actual_cache, expected_cache, atol=0, rtol=0) + + def test_compresses_two_pools_when_draft_window_closes_two(self): + self._run_compress_case( + effective_n=self.NUM_DRAFT_TOKENS, + expected_closed_pools=2, + ) + + def test_effective_n_only_compresses_accepted_pools(self): + self._run_compress_case(effective_n=2, expected_closed_pools=1) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/unit/attention/test_dsa_multistep_dedup.py b/test/registered/unit/attention/test_dsa_multistep_dedup.py new file mode 100644 index 0000000000000..7378ed6f9f01d --- /dev/null +++ b/test/registered/unit/attention/test_dsa_multistep_dedup.py @@ -0,0 +1,144 @@ +import unittest +from unittest.mock import MagicMock, patch + +from sglang.srt.layers.attention.dsa_backend import ( + DeepseekSparseAttnBackend, + DeepseekSparseAttnMultiStepBackend, + _is_kpool_metadata_fusion_supported, +) +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=10, suite="base-a-test-cpu") + + +class TestMultiStepDedupGate(CustomTestCase): + """The multi-step sibling-copy dedup is internal behavior of the fused + metadata path: it must follow the step backends' effective fusion enable + (which folds in the geometry and platform gates), with no standalone + knob.""" + + def _wrapper_with_backend_flag(self, value): + wrapper = MagicMock(spec=DeepseekSparseAttnMultiStepBackend) + backend0 = MagicMock() + backend0.experimental_kpool_metadata_fusion = value + wrapper.attn_backends = [backend0, MagicMock(), MagicMock()] + return wrapper + + def test_dedup_follows_fusion_enable(self): + wrapper = self._wrapper_with_backend_flag(True) + self.assertTrue( + DeepseekSparseAttnMultiStepBackend._multistep_dedup_enabled(wrapper) + ) + + def test_dedup_off_when_fusion_off(self): + wrapper = self._wrapper_with_backend_flag(False) + self.assertFalse( + DeepseekSparseAttnMultiStepBackend._multistep_dedup_enabled(wrapper) + ) + + def test_dedup_off_when_backend_predates_flag(self): + wrapper = MagicMock(spec=DeepseekSparseAttnMultiStepBackend) + backend0 = MagicMock(spec=[]) # no fusion attribute at all + wrapper.attn_backends = [backend0] + self.assertFalse( + DeepseekSparseAttnMultiStepBackend._multistep_dedup_enabled(wrapper) + ) + + +class TestSiblingCopyFallback(CustomTestCase): + """_copy_replay_metadata_from_sibling must take the FULL recompute path + whenever the CUDA-only derived-copy body cannot run bit-exactly: + non-CUDA platforms, missing metadata, or a stale/incompatible sibling.""" + + def _mock_backend(self, bs=4, with_metadata=True): + be = MagicMock(spec=DeepseekSparseAttnBackend) + metadata = MagicMock() + be.decode_cuda_graph_metadata = {bs: metadata} if with_metadata else {} + be.forward_metadata = metadata + return be, metadata + + def _run(self, is_cuda_val, is_hip_val=False, self_has_metadata=True): + bs = 4 + dst, dst_meta = self._mock_backend(bs, with_metadata=self_has_metadata) + src, src_meta = self._mock_backend(bs) + src.forward_metadata = src_meta # fresh sibling + dst._sibling_replay_metadata_compatible = MagicMock(return_value=True) + precomputed = MagicMock() + + with patch( + "sglang.srt.layers.attention.dsa_backend.is_cuda", + return_value=is_cuda_val, + ), patch("sglang.srt.layers.attention.dsa_backend._is_hip", is_hip_val): + DeepseekSparseAttnBackend._copy_replay_metadata_from_sibling( + dst, + src_backend=src, + bs=bs, + precomputed=precomputed, + forward_mode=ForwardMode.DECODE, + ) + return dst + + def test_non_cuda_platform_recomputes_in_full(self): + dst = self._run(is_cuda_val=False) + dst.init_forward_metadata_replay_cuda_graph_from_precomputed.assert_called_once() + dst._copy_base_replay_buffers.assert_not_called() + + def test_hip_platform_recomputes_in_full(self): + dst = self._run(is_cuda_val=True, is_hip_val=True) + dst.init_forward_metadata_replay_cuda_graph_from_precomputed.assert_called_once() + dst._copy_base_replay_buffers.assert_not_called() + + def test_missing_metadata_recomputes_in_full(self): + dst = self._run(is_cuda_val=True, self_has_metadata=False) + dst.init_forward_metadata_replay_cuda_graph_from_precomputed.assert_called_once() + dst._copy_base_replay_buffers.assert_not_called() + + def test_cuda_compatible_sibling_takes_copy_path(self): + dst = self._run(is_cuda_val=True) + dst.init_forward_metadata_replay_cuda_graph_from_precomputed.assert_not_called() + dst._copy_base_replay_buffers.assert_called_once() + dst._copy_kpool_metadata_from_sibling.assert_called_once() + + +class TestInGraphVerifyEligibility(CustomTestCase): + def _eligible(self, dcp_enabled): + backend = MagicMock(spec=DeepseekSparseAttnBackend) + backend.ingraph_verify_metadata_enabled = True + backend.dsa_index_kpool = 16 + backend.experimental_kpool_metadata_fusion = True + backend.dsa_decode_impl = "trtllm" + parallel = MagicMock(dcp_enabled=dcp_enabled) + + with patch( + "sglang.srt.layers.attention.dsa_backend.is_cuda", return_value=True + ), patch("sglang.srt.layers.attention.dsa_backend._is_hip", False), patch( + "sglang.srt.layers.attention.dsa_backend.get_parallel", + return_value=parallel, + ): + return DeepseekSparseAttnBackend._ingraph_verify_metadata_eligible(backend) + + def test_uninitialized_dcp_group_is_eligible(self): + self.assertTrue(self._eligible(dcp_enabled=False)) + + def test_dcp_is_not_eligible(self): + self.assertFalse(self._eligible(dcp_enabled=True)) + + +class TestKPoolMetadataFusionGeometry(CustomTestCase): + def test_final_checkpoint_geometry_is_supported(self): + self.assertTrue(_is_kpool_metadata_fusion_supported(4, 64, 2048)) + + def test_legacy_checkpoint_geometry_is_supported(self): + self.assertTrue(_is_kpool_metadata_fusion_supported(16, 64, 2048)) + + def test_non_page_aligned_pool_is_not_supported(self): + self.assertFalse(_is_kpool_metadata_fusion_supported(6, 64, 2048)) + + def test_non_pool_aligned_topk_is_not_supported(self): + self.assertFalse(_is_kpool_metadata_fusion_supported(4, 64, 2049)) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/unit/configs/test_glm5_next_config.py b/test/registered/unit/configs/test_glm5_next_config.py new file mode 100644 index 0000000000000..a3a68d527ea89 --- /dev/null +++ b/test/registered/unit/configs/test_glm5_next_config.py @@ -0,0 +1,107 @@ +"""Unit tests for GLM-5 Next configuration compatibility.""" + +import unittest + +from sglang.srt.configs.glm5_next import Glm5NextTextConfig +from sglang.srt.configs.mamba_utils import KimiLinearStateShape +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=5, suite="base-a-test-cpu") + + +class TestGlm5NextTextConfig(CustomTestCase): + def test_kimi_linear_state_shape_preserves_channel_slice_axis(self): + shape = KimiLinearStateShape.create( + tp_world_size=8, + num_heads=32, + head_dim=96, + conv_kernel_size=3, + ) + + self.assertEqual(shape.conv, [(2, 1152)]) + self.assertEqual(shape.temporal, (4, 96, 96)) + self.assertEqual(shape.conv_slice_axis, 1) + self.assertEqual(shape.conv_shard_groups, [3072, 3072, 3072]) + + def test_transformers_format_builds_legacy_linear_attention_config(self): + config = Glm5NextTextConfig( + num_hidden_layers=4, + layer_types=[ + "linear_attention", + "linear_attention", + "deepseek_sparse_attention", + "linear_attention", + ], + linear_head_dim=96, + linear_num_heads=32, + linear_conv_kernel_dim=3, + gate_lower_bound=-5.0, + ) + + self.assertEqual( + config.linear_attn_config, + { + "full_attn_layers": [2], + "head_dim": 96, + "kda_layers": [0, 1, 3], + "num_heads": 32, + "short_conv_kernel_size": 3, + "gate_lower_bound": -5.0, + }, + ) + self.assertEqual(config.linear_layer_ids, [0, 1, 3]) + self.assertEqual(config.full_attention_layer_ids, [2]) + + def test_transformers_format_without_lower_bound(self): + config = Glm5NextTextConfig( + num_hidden_layers=2, + layer_types=["linear_attention", "deepseek_sparse_attention"], + ) + + self.assertIsNone(config.linear_attn_config["gate_lower_bound"]) + + def test_legacy_linear_lower_bound_is_normalized(self): + config = Glm5NextTextConfig( + num_hidden_layers=2, + layer_types=["linear_attention", "deepseek_sparse_attention"], + linear_lower_bound=-4.0, + ) + + self.assertEqual(config.linear_attn_config["gate_lower_bound"], -4.0) + + def test_gate_lower_bound_takes_precedence(self): + config = Glm5NextTextConfig( + num_hidden_layers=2, + layer_types=["linear_attention", "deepseek_sparse_attention"], + linear_lower_bound=-4.0, + gate_lower_bound=-5.0, + ) + + self.assertEqual(config.linear_attn_config["gate_lower_bound"], -5.0) + + def test_legacy_linear_attention_config_takes_precedence(self): + linear_attn_config = { + "full_attn_layers": [1], + "head_dim": 64, + "kda_layers": [0], + "num_heads": 16, + "short_conv_kernel_size": 2, + "gate_lower_bound": -4.0, + } + + config = Glm5NextTextConfig( + num_hidden_layers=2, + linear_attn_config=linear_attn_config, + layer_types=["deepseek_sparse_attention", "linear_attention"], + linear_head_dim=96, + linear_num_heads=32, + linear_conv_kernel_dim=3, + gate_lower_bound=-5.0, + ) + + self.assertIs(config.linear_attn_config, linear_attn_config) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/unit/disaggregation/test_decode_queue_cleanup.py b/test/registered/unit/disaggregation/test_decode_queue_cleanup.py index 7b5b9f8a06a0e..79d45ac911bb3 100644 --- a/test/registered/unit/disaggregation/test_decode_queue_cleanup.py +++ b/test/registered/unit/disaggregation/test_decode_queue_cleanup.py @@ -23,6 +23,10 @@ class FakeReceiver: def __init__(self): self.clear_called = False + self.abort_called = False + + def abort(self): + self.abort_called = True def clear(self): self.clear_called = True @@ -173,6 +177,66 @@ def __eq__(self, other): self.assertTrue(all(r is not decode_req for r in queue.pending_reqs)) self.assertIsNone(decode_req.kv_receiver) + @patch("sglang.srt.disaggregation.decode.prepare_abort") + @patch("sglang.srt.disaggregation.decode.time.perf_counter", return_value=111.0) + def test_prealloc_timeout_aborts_and_clears_receiver( + self, _mock_now, mock_prepare_abort + ): + receiver = FakeReceiver() + req = SimpleNamespace( + rid="timed-out-prealloc", + bootstrap_room=17, + finished_reason=None, + finished_output=False, + return_logprob=False, + time_stats=SimpleNamespace(bootstrap_done_time=100.0), + ) + decode_req = SimpleNamespace( + req=req, + kv_receiver=receiver, + waiting_for_input=True, + ) + + def mark_aborted(aborted_req, *_args, **_kwargs): + aborted_req.finished_reason = FINISH_ABORT("preallocation timeout") + + mock_prepare_abort.side_effect = mark_aborted + + queue = DecodePreallocQueue.__new__(DecodePreallocQueue) + queue.tp_rank = 0 + queue.pp_size = 1 + queue.queue = [decode_req] + queue.pending_reqs = [decode_req] + queue.retracted_queue = [] + queue.kv_manager = SimpleNamespace(waiting_timeout=10.0) + queue._resolve_pending_reqs = MagicMock() + queue._update_handshake_waiters = MagicMock() + queue._uses_swa_tail_prealloc = MagicMock(return_value=False) + queue._allocatable_token_budgets = MagicMock(return_value=0) + queue._hicache_pending_restore_tokens = MagicMock(return_value=0) + + scheduler = MagicMock() + scheduler.running_batch.reqs = [] + scheduler.enable_priority_scheduling = False + scheduler.enable_hisparse = False + scheduler.metrics_reporter.enable_metrics = True + queue.scheduler = scheduler + + preallocated, failed = queue.pop_preallocated() + + self.assertEqual(preallocated, []) + self.assertEqual(failed, [decode_req]) + self.assertEqual(queue.queue, []) + self.assertEqual(queue.pending_reqs, []) + self.assertTrue(receiver.abort_called) + self.assertTrue(receiver.clear_called) + self.assertIsNone(decode_req.kv_receiver) + scheduler.output_streamer.stream_output.assert_called_once_with( + [req], req.return_logprob + ) + scheduler.metrics_collector.increment_prealloc_failed_reqs.assert_called_once_with() + mock_prepare_abort.assert_called_once() + def test_swa_reclaim_failure_rejects_only_request(self): receiver = FakeReceiver() req = SimpleNamespace( diff --git a/test/registered/unit/entrypoints/openai/test_serving_chat.py b/test/registered/unit/entrypoints/openai/test_serving_chat.py index 033a14761fd58..8394760a0aec5 100644 --- a/test/registered/unit/entrypoints/openai/test_serving_chat.py +++ b/test/registered/unit/entrypoints/openai/test_serving_chat.py @@ -20,6 +20,7 @@ from typing import Optional from unittest.mock import Mock, patch +import jinja2 from fastapi import Request from sglang.srt.entrypoints.openai import chat_encoding @@ -39,6 +40,9 @@ from sglang.srt.environ import envs from sglang.srt.function_call.kimik3_format import TOOLS_CLOSE, TOOLS_OPEN from sglang.srt.managers.io_struct import GenerateReqInput +from sglang.srt.parser.jinja_template_utils import ( + jinja_template_may_reorder_tool_results, +) from sglang.srt.parser.template_detection import ReasoningToggleConfig from sglang.srt.utils import get_or_create_event_loop from sglang.test.ci.ci_register import register_cpu_ci @@ -80,6 +84,24 @@ def _spec_result(index): 'DEFAULT_REASONING_EFFORT = "low"\n' ) +_TOOL_RESULT_REORDER_TEMPLATE = """ +{%- for assistant in messages + if assistant.role == 'assistant' and assistant.tool_calls -%} + {%- for tool_call in assistant.tool_calls -%} + {%- for result in messages + if result.role == 'tool' and result.tool_call_id == tool_call.id -%} + {%- for part in result.content -%} + {%- if part.type == 'text' -%} + {{- part.text -}} + {%- else -%} + {{- '<' + part.type + '>' -}} + {%- endif -%} + {%- endfor -%} + {%- endfor -%} + {%- endfor -%} +{%- endfor -%} +""" + def _create_dsv4_checkpoint(test_case: unittest.TestCase, source: str) -> str: model_dir = tempfile.TemporaryDirectory() @@ -192,6 +214,117 @@ def setUp(self): self.fastapi_request = Mock(spec=Request) self.fastapi_request.headers = {} + @staticmethod + def _render_tool_results_in_call_order(messages, **kwargs): + del kwargs + return jinja2.Template(_TOOL_RESULT_REORDER_TEMPLATE).render(messages=messages) + + def test_media_order_recovery_follows_tool_call_order_for_all_modalities(self): + self.tm.tokenizer.apply_chat_template.side_effect = ( + self._render_tool_results_in_call_order + ) + messages = [ + { + "role": "assistant", + "content": "", + "tool_calls": [ + {"id": "call-a", "function": {"name": "a", "arguments": {}}}, + {"id": "call-b", "function": {"name": "b", "arguments": {}}}, + ], + }, + { + "role": "tool", + "tool_call_id": "call-b", + "content": [ + {"type": "image"}, + {"type": "video"}, + {"type": "audio"}, + ], + }, + { + "role": "tool", + "tool_call_id": "call-a", + "content": [ + {"type": "image"}, + {"type": "video"}, + {"type": "audio"}, + ], + }, + ] + + image_data, video_data, audio_data = ( + self.chat._recover_media_order_from_chat_template( + messages, + tools=None, + extra_template_kwargs={}, + image_data=["image-b", "image-a"], + video_data=["video-b", "video-a"], + audio_data=["audio-b", "audio-a"], + ) + ) + + self.assertEqual(image_data, ["image-a", "image-b"]) + self.assertEqual(video_data, ["video-a", "video-b"]) + self.assertEqual(audio_data, ["audio-a", "audio-b"]) + + def test_jinja_path_recovers_tool_result_images_only_when_template_needs_it(self): + self.template_manager.chat_template_name = None + self.template_manager.jinja_template_content_format = "openai" + self.template_manager.jinja_template_may_reorder_tool_results = ( + jinja_template_may_reorder_tool_results(_TOOL_RESULT_REORDER_TEMPLATE) + ) + self.assertTrue(self.template_manager.jinja_template_may_reorder_tool_results) + self.tm.tokenizer.apply_chat_template.side_effect = ( + self._render_tool_results_in_call_order + ) + request = ChatCompletionRequest( + model="x", + messages=[ + {"role": "user", "content": "inspect"}, + { + "role": "assistant", + "content": "", + "tool_calls": [ + { + "id": "call-a", + "type": "function", + "function": {"name": "a", "arguments": {}}, + }, + { + "id": "call-b", + "type": "function", + "function": {"name": "b", "arguments": {}}, + }, + ], + }, + { + "role": "tool", + "tool_call_id": "call-b", + "content": [{"type": "image_url", "image_url": {"url": "image-b"}}], + }, + { + "role": "tool", + "tool_call_id": "call-a", + "content": [{"type": "image_url", "image_url": {"url": "image-a"}}], + }, + ], + ) + + result = self.chat._apply_jinja_template(request, None, is_multimodal=True) + + self.assertEqual( + [item.url for item in result.image_data], ["image-a", "image-b"] + ) + self.assertEqual(self.tm.tokenizer.apply_chat_template.call_count, 2) + + self.template_manager.jinja_template_may_reorder_tool_results = False + self.tm.tokenizer.apply_chat_template.reset_mock() + result = self.chat._apply_jinja_template(request, None, is_multimodal=True) + self.assertEqual( + [item.url for item in result.image_data], ["image-b", "image-a"] + ) + self.assertEqual(self.tm.tokenizer.apply_chat_template.call_count, 1) + def test_parsers_follow_the_control_plane_overlay(self): """Template detection records the parsers through `override`, so they answer from the bags; `ServerArgs` keeps the launcher's seed.""" diff --git a/test/registered/unit/layers/test_dcp_comm.py b/test/registered/unit/layers/test_dcp_comm.py new file mode 100644 index 0000000000000..87acadc3a3340 --- /dev/null +++ b/test/registered/unit/layers/test_dcp_comm.py @@ -0,0 +1,42 @@ +import sys +from types import SimpleNamespace +from unittest.mock import patch + +import pytest +import torch + +from sglang.srt.layers.dcp.comm import all_gather_kv_cache_for_dcp +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci( + est_time=5, + suite="base-a-test-cpu", + nightly=False, + disabled=None, +) + + +def test_nope_prefix_kv_gather_accepts_missing_rope_cache(): + """NoPE DCP prefix reuse must not require a rope-cache tensor.""" + prefix_kv_a = torch.arange(12, dtype=torch.float32).reshape(3, 1, 4) + prefix_kv_lens_cpu = torch.tensor([3], dtype=torch.int32) + parallel = SimpleNamespace(dcp_enabled=True, dcp_size=1, dcp_rank=0) + + with ( + patch("sglang.srt.layers.dcp.comm.get_parallel", return_value=parallel), + patch( + "sglang.srt.layers.dcp.comm._all_gather_dcp_kv_cache", + side_effect=lambda tensor: tensor, + ), + ): + result = all_gather_kv_cache_for_dcp( + prefix_kv_a, + None, + prefix_kv_lens_cpu, + ) + + assert torch.equal(result, prefix_kv_a) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/test/registered/unit/managers/test_scheduler_chunked_abort_race.py b/test/registered/unit/managers/test_scheduler_chunked_abort_race.py new file mode 100644 index 0000000000000..b7f0a82941512 --- /dev/null +++ b/test/registered/unit/managers/test_scheduler_chunked_abort_race.py @@ -0,0 +1,68 @@ +"""Tests for deferred chunked-prefill aborts.""" + +import unittest +from types import SimpleNamespace +from unittest.mock import Mock + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase, maybe_stub_sgl_kernel + +maybe_stub_sgl_kernel() + +from sglang.srt.managers.scheduler import Scheduler # noqa: E402 + +register_cpu_ci(est_time=10, suite="base-a-test-cpu") + + +class _FakeReq: + """Minimal stand-in for Req: only the fields the abort paths touch.""" + + def __init__(self, rid: str): + self.rid = rid + self.req_pool_idx = 1 + self.mamba_pool_idx = None + self.to_finish = None + self._finished = False + + def finished(self): + return self._finished + + +def _make_scheduler(pending_req, *, chunked_req, running_reqs) -> Scheduler: + sched = Scheduler.__new__(Scheduler) + sched.chunked_req = chunked_req + sched._pending_chunked_abort_req = pending_req + sched.waiting_queue = [] + sched.dllm_config = None + sched.grammar_manager = Mock() + sched.disaggregation_mode = None + sched.enable_hicache_storage = False + sched.ps = SimpleNamespace(pp_size=1) + sched.running_batch = SimpleNamespace(reqs=running_reqs) + sched.last_batch = None + return sched + + +class TestPendingChunkedAbortRace(CustomTestCase): + def test_req_left_chunked_slot_is_aborted(self): + req = _FakeReq("zombie_rid") + sched = _make_scheduler(req, chunked_req=None, running_reqs=[req]) + + sched.process_pending_chunked_abort() + + self.assertIsNotNone(req.to_finish, "recorded abort was never applied") + self.assertIsNone(sched._pending_chunked_abort_req) + + def test_finished_req_only_clears_marker(self): + req = _FakeReq("done_rid") + req._finished = True + sched = _make_scheduler(req, chunked_req=None, running_reqs=[]) + + sched.process_pending_chunked_abort() + + self.assertIsNone(req.to_finish) + self.assertIsNone(sched._pending_chunked_abort_req) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/test/registered/unit/managers/test_tokenizer_manager_rid_cleanup.py b/test/registered/unit/managers/test_tokenizer_manager_rid_cleanup.py index b44f172e8e29e..5feeee2a7200c 100644 --- a/test/registered/unit/managers/test_tokenizer_manager_rid_cleanup.py +++ b/test/registered/unit/managers/test_tokenizer_manager_rid_cleanup.py @@ -10,11 +10,12 @@ - _handle_batch_output cleans up rid_to_state on finished requests - _init_req_state rejects duplicate rids - Resubmission succeeds after cleanup + - Handler failures clean up pending and dispatched requests """ import asyncio import unittest -from unittest.mock import AsyncMock, MagicMock, Mock +from unittest.mock import AsyncMock, MagicMock, Mock, patch import msgspec @@ -454,41 +455,88 @@ def _make_generate_obj(rid, is_single): return obj -class TestDiscardPendingReqStates(CustomTestCase): - """Direct tests for _discard_pending_req_states.""" +class TestReleaseReqStatesOnFailure(CustomTestCase): + """Direct tests for _release_req_states_on_failure.""" - def test_discard_single(self): + def test_undelivered_single_is_dropped(self): tm = _make_tokenizer_manager(self) rid = "d_single" tm.rid_to_state[rid] = _make_req_state(rid) - obj = Mock(spec=GenerateReqInput) - obj.is_single = True - obj.rid = rid - tm._discard_pending_req_states(obj) + tm._release_req_states_on_failure([rid]) self.assertNotIn(rid, tm.rid_to_state) - def test_discard_batch_removes_all(self): + def test_undelivered_batch_removes_all(self): tm = _make_tokenizer_manager(self) rids = ["d0", "d1", "d2"] for r in rids: tm.rid_to_state[r] = _make_req_state(r) - obj = Mock(spec=GenerateReqInput) - obj.is_single = False - obj.rid = list(rids) - tm._discard_pending_req_states(obj) + tm._release_req_states_on_failure(rids) for r in rids: self.assertNotIn(r, tm.rid_to_state) - def test_discard_ignores_already_removed(self): - """Popping a rid that is no longer present must not raise.""" + def test_ignores_already_removed(self): + """A rid that is no longer present must not raise.""" tm = _make_tokenizer_manager(self) tm.rid_to_state["p1"] = _make_req_state("p1") - obj = Mock(spec=GenerateReqInput) - obj.is_single = False - obj.rid = ["p1", "already_gone"] - tm._discard_pending_req_states(obj) # must not raise + tm._release_req_states_on_failure(["p1", "already_gone"]) self.assertNotIn("p1", tm.rid_to_state) + def test_dispatched_single_is_aborted_and_state_kept(self): + tm = _make_tokenizer_manager(self) + tm.server_args.tokenizer_worker_num = 1 + tm._dispatch_to_scheduler = Mock() + tm.enable_metrics = True + tm.metrics_collector = MagicMock() + rid = "d_live" + state = _make_req_state(rid) + state.dispatched = True + tm.rid_to_state[rid] = state + tm._release_req_states_on_failure([rid]) + tm._release_req_states_on_failure([rid]) + + sent = [c.args[0] for c in tm._dispatch_to_scheduler.call_args_list] + self.assertEqual( + [type(m) for m in sent], [AbortReq], "expected exactly one AbortReq" + ) + self.assertEqual(sent[0].rid, rid) + self.assertIn(rid, tm.rid_to_state) + self.assertTrue(state.abort_sent) + tm.metrics_collector.observe_one_aborted_request.assert_called_once() + + def test_dispatched_batch_aborts_delivered_and_drops_rest(self): + tm = _make_tokenizer_manager(self) + tm.server_args.tokenizer_worker_num = 1 + tm._dispatch_to_scheduler = Mock() + delivered, undelivered = "d_delivered", "d_undelivered" + live = _make_req_state(delivered) + live.dispatched = True + tm.rid_to_state[delivered] = live + tm.rid_to_state[undelivered] = _make_req_state(undelivered) + tm._release_req_states_on_failure([delivered, undelivered]) + + sent = [c.args[0] for c in tm._dispatch_to_scheduler.call_args_list] + self.assertEqual([type(m) for m in sent], [AbortReq]) + self.assertEqual(sent[0].rid, delivered) + self.assertIn(delivered, tm.rid_to_state) + self.assertNotIn(undelivered, tm.rid_to_state) + + def test_abort_failure_does_not_stop_cleanup(self): + tm = _make_tokenizer_manager(self) + tm.server_args.tokenizer_worker_num = 1 + tm._dispatch_to_scheduler = Mock(side_effect=RuntimeError("send failed")) + delivered, undelivered = "live", "pending" + live = _make_req_state(delivered) + live.dispatched = True + tm.rid_to_state[delivered] = live + tm.rid_to_state[undelivered] = _make_req_state(undelivered) + + with self.assertLogs(level="ERROR"): + tm._release_req_states_on_failure([delivered, undelivered]) + + self.assertIn(delivered, tm.rid_to_state) + self.assertFalse(live.abort_sent) + self.assertNotIn(undelivered, tm.rid_to_state) + class TestParallelStreamTaskCleanup(CustomTestCase): def test_failing_choice_cancels_and_closes_sibling_waiters(self): @@ -595,6 +643,27 @@ async def drive(): for r in rids: self.assertNotIn(r, tm.rid_to_state) + def test_parallel_sampling_failure_cleans_generated_rid(self): + tm = _make_tm_for_generate(self) + obj = GenerateReqInput( + text=["hello"], + rid=["base"], + sampling_params={"n": 2}, + ) + tokenized = MagicMock() + tokenized.mm_inputs = None + tokenized.sampling_params = MagicMock() + tm._tokenize_one_request = AsyncMock(return_value=tokenized) + tm._send_one_request = Mock(side_effect=RuntimeError("dispatch failed")) + + async def drive(): + await tm.generate_request(obj).__anext__() + + with self.assertRaisesRegex(RuntimeError, "dispatch failed"): + asyncio.run(drive()) + + self.assertFalse(tm.rid_to_state) + def test_thinking_budget_rejects_runtime_without_strict_thinking(self): tm = _make_tm_for_generate(self) obj = GenerateReqInput( @@ -613,5 +682,49 @@ async def drive(): self.assertFalse(tm.rid_to_state) +class TestDisconnectAfterDispatchAbortsRequest(CustomTestCase): + """Cancellation after dispatch must stop the scheduler request.""" + + @patch( + "sglang.srt.managers.tokenizer_manager.wrap_shm_features", + side_effect=lambda obj: obj, + ) + def test_cancel_after_dispatch_sends_abort_and_keeps_state(self, _wrap_shm): + tm = _make_tm_for_generate(self) + tm.cuda_vmm_feature_transport = Mock() + tm._dispatch_to_scheduler = Mock() + rid = "disconnect_zombie" + obj = _make_generate_obj(rid, is_single=True) + obj.return_prompt_token_ids = False + tokenized = MagicMock() + tokenized.rid = rid + tokenized.mm_inputs = None + tm._tokenize_one_request = AsyncMock(return_value=tokenized) + + async def drive(): + task = asyncio.create_task(tm.generate_request(obj).__anext__()) + for _ in range(100): + await asyncio.sleep(0) + if tm._dispatch_to_scheduler.called: + break + self.assertTrue( + tm._dispatch_to_scheduler.called, "request never dispatched" + ) + state = tm.rid_to_state.get(rid) + self.assertIsNotNone(state) + self.assertTrue(state.dispatched) + + task.cancel() + with self.assertRaises(asyncio.CancelledError): + await task + + asyncio.run(drive()) + + sent = [c.args[0] for c in tm._dispatch_to_scheduler.call_args_list] + aborts = [m for m in sent if isinstance(m, AbortReq) and m.rid == rid] + self.assertTrue(aborts, "disconnect must send an AbortReq to the scheduler") + self.assertIn(rid, tm.rid_to_state) + + if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/test/registered/unit/mem_cache/test_retraction_mamba_backup.py b/test/registered/unit/mem_cache/test_retraction_mamba_backup.py index 7b678f35acbbe..093f609954168 100644 --- a/test/registered/unit/mem_cache/test_retraction_mamba_backup.py +++ b/test/registered/unit/mem_cache/test_retraction_mamba_backup.py @@ -30,10 +30,12 @@ def __init__(self, carries_mamba: bool): def get_kvcache(self): return self._kv - def get_cpu_copy(self, indices, mamba_indices=None): + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): return "kv" - def load_cpu_copy(self, cpu_tensors, indices, mamba_indices=None): + def load_cpu_copy( + self, cpu_tensors, indices, mamba_indices=None, req_pool_index=None + ): self.loaded_kv = cpu_tensors diff --git a/test/registered/unit/model_executor/model_runner_components/test_spec_aux_hidden_state.py b/test/registered/unit/model_executor/model_runner_components/test_spec_aux_hidden_state.py index a04db980982c9..4f75d8015c337 100644 --- a/test/registered/unit/model_executor/model_runner_components/test_spec_aux_hidden_state.py +++ b/test/registered/unit/model_executor/model_runner_components/test_spec_aux_hidden_state.py @@ -1,14 +1,69 @@ import sys from types import SimpleNamespace +from unittest.mock import MagicMock import pytest -from sglang.srt.model_executor.model_runner_components.spec_aux_hidden_state import ( - _map_muse_target_layer_ids, -) +from sglang.srt.model_executor.model_runner_components import spec_aux_hidden_state +from sglang.srt.runtime_context import get_context from sglang.test.ci.ci_register import register_cpu_ci -register_cpu_ci(est_time=1, suite="base-a-test-cpu") +register_cpu_ci( + est_time=1, + suite="base-a-test-cpu", + nightly=False, + disabled=None, +) + + +@pytest.fixture(autouse=True) +def _published_config(): + with get_context().override_server_args( + speculative_draft_model_path=None, + speculative_draft_model_revision=None, + ): + yield + + +def _resolve_kwargs(): + spec_algorithm = MagicMock() + spec_algorithm.is_eagle.return_value = True + spec_algorithm.is_standalone.return_value = False + spec_algorithm.is_eagle3.return_value = False + spec_algorithm.is_dflash_family.return_value = False + return dict( + server_args=SimpleNamespace( + speculative_draft_model_path=None, + speculative_draft_model_revision=None, + ), + model_config=SimpleNamespace( + num_nextn_predict_layers=1, + hf_config=SimpleNamespace(eagle_config=None), + is_hybrid_swa=False, + is_deepseek_v4_arch=False, + swa_attention_layer_ids=[], + ), + spec_algorithm=spec_algorithm, + ) + + +def test_native_mtp_uses_target_nextn_layer_count(monkeypatch): + from_server_args = MagicMock() + monkeypatch.setattr( + spec_aux_hidden_state.ModelConfig, "from_server_args", from_server_args + ) + config = spec_aux_hidden_state.resolve_spec_aux_hidden_state_config( + **_resolve_kwargs(), is_draft_worker=False + ) + assert config.eagle_draft_num_layers == 1 + from_server_args.assert_not_called() + + +def test_draft_worker_does_not_budget_itself(): + config = spec_aux_hidden_state.resolve_spec_aux_hidden_state_config( + **_resolve_kwargs(), is_draft_worker=True + ) + assert config.eagle_draft_num_layers is None @pytest.mark.parametrize( @@ -25,7 +80,7 @@ def test_muse_target_layer_id_mapping(target_model_type, draft_architecture, exp """The +1 belongs to Muse targets, which report layer outputs where the rest report layer inputs. The draft architecture alone does not earn it.""" assert ( - _map_muse_target_layer_ids( + spec_aux_hidden_state._map_muse_target_layer_ids( target_hf_config=SimpleNamespace(model_type=target_model_type), draft_hf_config=SimpleNamespace(architectures=[draft_architecture]), layer_ids=[1, 13, 25, 37, 49], @@ -35,4 +90,4 @@ def test_muse_target_layer_id_mapping(target_model_type, draft_architecture, exp if __name__ == "__main__": - sys.exit(pytest.main([__file__, "-v"])) + sys.exit(pytest.main([__file__])) diff --git a/test/registered/unit/model_executor/runner/test_eager_runner_dcp_metadata.py b/test/registered/unit/model_executor/runner/test_eager_runner_dcp_metadata.py new file mode 100644 index 0000000000000..414623fc5c14e --- /dev/null +++ b/test/registered/unit/model_executor/runner/test_eager_runner_dcp_metadata.py @@ -0,0 +1,74 @@ +from types import SimpleNamespace +from unittest.mock import Mock, patch + +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.srt.model_executor.runner.eager_runner import EagerRunner +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=1, suite="base-a-test-cpu") + + +def test_target_verify_skips_dcp_extend_metadata(): + runner = EagerRunner.__new__(EagerRunner) + runner.enable_pdmux = False + runner.load_batch = lambda batch, _proxy: batch + + model = Mock() + model.forward.return_value = object() + model_runner = SimpleNamespace( + _extend_forward_kwargs=lambda *_args: {}, + _pp_kwargs=lambda *_args: {}, + ps=SimpleNamespace(attn_dcp_size=4), + model=model, + attn_backend=Mock(), + device_timer=None, + prefill_cuda_graph_runner=None, + ) + runner.model_runner = model_runner + batch = SimpleNamespace( + forward_mode=ForwardMode.TARGET_VERIFY, + needs_forward_metadata_init=lambda: True, + input_ids=object(), + positions=object(), + ) + + runner._execute_extend(batch) + + model.prepare_context_parallel_metadata_for_dcp.assert_not_called() + model_runner.attn_backend.init_forward_metadata.assert_called_once_with(batch) + + +@patch("sglang.srt.model_executor.runner.eager_runner.prepare_cp_forward") +@patch( + "sglang.srt.model_executor.runner.eager_runner.is_cp_v2_active", return_value=True +) +def test_cp_v2_metadata_is_prepared_once(_is_cp_v2_active, prepare_cp_forward): + runner = EagerRunner.__new__(EagerRunner) + runner.enable_pdmux = False + runner.load_batch = lambda batch, _proxy: batch + runner._execute_extend_cp_v2 = Mock(return_value=object()) + + model = Mock() + model.forward.return_value = object() + model_runner = SimpleNamespace( + _extend_forward_kwargs=lambda *_args: {}, + _pp_kwargs=lambda *_args: {}, + ps=SimpleNamespace(attn_dcp_size=1), + model=model, + attn_backend=Mock(), + device_timer=None, + prefill_cuda_graph_runner=None, + ) + runner.model_runner = model_runner + batch = SimpleNamespace( + forward_mode=ForwardMode.EXTEND, + needs_forward_metadata_init=lambda: True, + input_ids=object(), + positions=object(), + ) + + runner._execute_extend(batch) + + prepare_cp_forward.assert_called_once_with(batch) + model_runner.attn_backend.init_forward_metadata.assert_called_once_with(batch) + runner._execute_extend_cp_v2.assert_called_once() diff --git a/test/registered/unit/model_executor/test_pool_configurator.py b/test/registered/unit/model_executor/test_pool_configurator.py index 2525a676fe74e..3594a4e7810f1 100644 --- a/test/registered/unit/model_executor/test_pool_configurator.py +++ b/test/registered/unit/model_executor/test_pool_configurator.py @@ -119,9 +119,11 @@ def _make_model_runner( mc.get_num_kv_heads = lambda tp_size, dcp_size=1: num_kv_heads mc.get_swa_num_kv_heads = lambda tp_size: swa_num_kv_heads or num_kv_heads mc.hf_config = SimpleNamespace(architectures=["LlamaForCausalLM"]) + mc.hf_config.model_type = "llama" mc.hf_config.get_text_config = lambda: mc.hf_config mc.linear_attn_registry_result = None mc.context_len = 8192 + mc.is_draft_model = False mr.model_config = mc mr.kv_cache_dtype = "fake_bf16" @@ -697,18 +699,51 @@ def test_eagle_does_not_exceed_budget(self): mr.spec_algorithm.is_none.return_value = False mr.spec_aux_config.eagle_draft_num_layers = eagle_draft_num_layers - with mock_cpu_env(): - from sglang.srt.model_executor.pool_configurator import ( - create_memory_pool_configurator, - ) + full_pt = _full_per_token(mr) + for dcp_size in (1, 4): + with self.subTest(dcp_size=dcp_size): + mr.ps = ParallelState.trivial(attn_dcp_size=dcp_size) + with mock_cpu_env(): + from sglang.srt.model_executor.pool_configurator import ( + create_memory_pool_configurator, + ) - cfg = create_memory_pool_configurator(mr) - config = cfg.calculate_pool_sizes(available, 1) + cfg = create_memory_pool_configurator(mr) + config = cfg.calculate_pool_sizes(available, 1) + + total_layers = num_layers + eagle_draft_num_layers * dcp_size + used = config.max_total_num_tokens * full_pt * total_layers + self.assertLessEqual(used, available) + + def test_hybrid_swa_scales_draft_budget_with_dcp(self): + mr = _make_model_runner( + self, + is_hybrid_swa=True, + full_attention_layer_ids=list(range(16)), + swa_attention_layer_ids=list(range(16, 32)), + swa_num_kv_heads=4, + ) + mr.spec_algorithm.is_eagle.return_value = True + mr.spec_algorithm.is_none.return_value = False + mr.spec_aux_config.eagle_draft_num_layers = 4 full_pt = _full_per_token(mr) - total_layers = num_layers + eagle_draft_num_layers - used = config.max_total_num_tokens * full_pt * total_layers - self.assertLessEqual(used, available) + swa_pt = _swa_per_token(mr) + for dcp_size in (1, 4): + with self.subTest(dcp_size=dcp_size): + mr.ps = ParallelState.trivial(attn_dcp_size=dcp_size) + with mock_cpu_env(): + from sglang.srt.model_executor.pool_configurator import ( + create_memory_pool_configurator, + ) + + cfg = create_memory_pool_configurator(mr) + + expected = ( + full_pt * (16 + 4 * dcp_size) + + mr.server_args.swa_full_tokens_ratio * swa_pt * 16 + ) + self.assertEqual(cfg._cell_size, expected) @patch( "sglang.srt.mem_cache.kv_cache_configurator.calculate_mla_kv_cache_dim", diff --git a/test/registered/unit/model_executor/test_prefill_cuda_graph_runner.py b/test/registered/unit/model_executor/test_prefill_cuda_graph_runner.py index 030aca10c06be..c449df2c025e0 100644 --- a/test/registered/unit/model_executor/test_prefill_cuda_graph_runner.py +++ b/test/registered/unit/model_executor/test_prefill_cuda_graph_runner.py @@ -10,6 +10,7 @@ import sglang.srt.model_executor.runner.prefill_cuda_graph_runner as runner_module from sglang.srt.model_executor.cuda_graph_config import Backend from sglang.srt.model_executor.forward_batch_info import CaptureHiddenMode +from sglang.srt.model_executor.forward_context import get_req_to_token_pool from sglang.srt.model_executor.model_runner_components.cuda_graph_setup import ( capture_prefill_graph, ) @@ -17,6 +18,9 @@ PrefillCudaGraphRunner, ) from sglang.srt.model_executor.runner.shape_key import ShapeKey +from sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph.breakable_cuda_graph import ( + _weak_ref_if_tensor, +) from sglang.srt.runtime_context import get_context from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import CustomTestCase @@ -34,6 +38,16 @@ def prepare_full_cuda_graph_chunked_prefix(self, forward_batch, *, in_capture): self.calls.append((forward_batch, in_capture)) +class _ContextReadingAttentionBackend: + def __init__(self): + self.req_to_token_pool = object() + self.observed_req_to_token_pool = None + + def init_forward_metadata(self, forward_batch): + del forward_batch + self.observed_req_to_token_pool = get_req_to_token_pool() + + class _FakeKVIndexKernel: def __getitem__(self, grid): del grid @@ -118,6 +132,26 @@ def test_low_free_memory_still_captures_prefill_graph(self): self.assertIs(capture.runner, prefill_runner) + def test_breakable_graph_keeps_cpu_tensor_reference(self): + tensor = torch.zeros(1) + + self.assertIs(_weak_ref_if_tensor(tensor), tensor) + + def test_breakable_graph_keeps_empty_tensor_reference(self): + tensor = torch.empty(0, device="meta") + + self.assertIs(_weak_ref_if_tensor(tensor), tensor) + + def test_capture_metadata_initialization_has_forward_context(self): + backend = _ContextReadingAttentionBackend() + runner = PrefillCudaGraphRunner.__new__(PrefillCudaGraphRunner) + runner.model_runner = SimpleNamespace(attn_backend=backend) + runner.use_captured_attn_metadata = False + + runner._init_forward_metadata_for_capture(SimpleNamespace(), 4) + + self.assertIs(backend.observed_req_to_token_pool, backend.req_to_token_pool) + def test_eagle_target_tc_piecewise_skips_last_mode_capture(self): eager_runner = object() # The server-side hidden-state ceiling is a bag leaf. diff --git a/test/registered/unit/models/test_glm5_next_dcp.py b/test/registered/unit/models/test_glm5_next_dcp.py new file mode 100644 index 0000000000000..6802395e48352 --- /dev/null +++ b/test/registered/unit/models/test_glm5_next_dcp.py @@ -0,0 +1,49 @@ +import sys +from types import SimpleNamespace +from unittest.mock import patch, sentinel + +import pytest + +from sglang.srt.models.glm5_next import Glm5NextForConditionalGeneration +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci( + est_time=5, + suite="base-a-test-cpu", + nightly=False, + disabled=None, +) + + +def test_multimodal_wrapper_builds_dcp_extend_metadata(): + """The top-level model must publish DCP metadata before prefix KV gather.""" + kwargs = { + "seq_lens": sentinel.seq_lens, + "extend_prefix_lens": sentinel.extend_prefix_lens, + "extend_prefix_lens_cpu": sentinel.extend_prefix_lens_cpu, + "extend_seq_lens": sentinel.extend_seq_lens, + "req_pool_indices": sentinel.req_pool_indices, + "req_to_token": sentinel.req_to_token, + "seq_lens_sum": 17, + "kv_buffer_shape": sentinel.kv_buffer_shape, + "kv_cache_dtype": sentinel.kv_cache_dtype, + "kv_cache_device": sentinel.kv_cache_device, + "create_chunked_prefix_cache_kv_indices_fn": sentinel.create_indices, + } + + with patch( + "sglang.srt.models.glm5_next.prepare_decode_context_parallel_metadata", + return_value=sentinel.metadata, + ) as planner: + result = ( + Glm5NextForConditionalGeneration.prepare_context_parallel_metadata_for_dcp( + SimpleNamespace(), **kwargs + ) + ) + + assert result is sentinel.metadata + planner.assert_called_once_with(**kwargs) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/test/registered/unit/models/test_glm5_next_nextn_weight_loading.py b/test/registered/unit/models/test_glm5_next_nextn_weight_loading.py new file mode 100644 index 0000000000000..bc043a0ecd5a7 --- /dev/null +++ b/test/registered/unit/models/test_glm5_next_nextn_weight_loading.py @@ -0,0 +1,68 @@ +import unittest +from types import SimpleNamespace + +import torch + +from sglang.srt.models.glm5_next_nextn import ( + Glm5NextForConditionalGenerationNextN, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="base-a-test-cpu") + + +class _FakeParam: + def __init__(self): + self.loaded = None + + def weight_loader(self, param, loaded_weight): + self.loaded = loaded_weight + + +class TestGlm5NextNextNWeightLoading(unittest.TestCase): + def test_checkpoint_qkv_sources_load_fused_projection(self): + fused_param = _FakeParam() + model = SimpleNamespace( + config=SimpleNamespace( + num_hidden_layers=45, + num_nextn_predict_layers=1, + n_routed_experts=0, + q_lora_rank=1536, + ), + model=SimpleNamespace( + decoder=SimpleNamespace(self_attn=None), + ), + named_parameters=lambda: iter( + [ + ( + "model.decoder.self_attn.fused_qkv_a_proj_with_mqa.weight", + fused_param, + ) + ] + ), + num_fused_shared_experts=0, + quant_config=None, + ) + q_weight = torch.arange(6, dtype=torch.float32).reshape(2, 3) + kv_weight = torch.arange(3, dtype=torch.float32).reshape(1, 3) + 10 + + Glm5NextForConditionalGenerationNextN.load_weights( + model, + [ + ("model.layers.45.self_attn.q_a_proj.weight", q_weight), + ( + "model.layers.45.self_attn.kv_a_proj_with_mqa.weight", + kv_weight, + ), + ], + ) + + self.assertTrue(model.fuse_qkv_a_proj) + torch.testing.assert_close( + fused_param.loaded, + torch.cat([q_weight, kv_weight], dim=0), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/unit/models/test_glm5_next_pp_metadata.py b/test/registered/unit/models/test_glm5_next_pp_metadata.py new file mode 100644 index 0000000000000..257168908207f --- /dev/null +++ b/test/registered/unit/models/test_glm5_next_pp_metadata.py @@ -0,0 +1,39 @@ +import sys +from types import SimpleNamespace + +import pytest +import torch + +from sglang.srt.model_executor.forward_batch_info import PPProxyTensors +from sglang.srt.models.glm5_next import Glm5NextForConditionalGeneration +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci( + est_time=10, + suite="base-a-test-cpu", + nightly=False, + disabled=None, +) + + +def _make_self(): + return SimpleNamespace( + dsa_enable_prefill_cp=False, + mla_enable_prefill_cp=False, + cp_rank=1, + cp_size=2, + use_dsa=True, + ) + + +def test_pp_nonfirst_rank_both_inputs_none_does_not_crash(): + hidden = torch.zeros((8, 4096)) + proxy = PPProxyTensors({"hidden_states": hidden}) + self = _make_self() + Glm5NextForConditionalGeneration._prepare_context_parallel_metadata( + self, None, None, SimpleNamespace(), proxy + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/test/registered/unit/models/test_nextn_hf_to_sglang_mapper.py b/test/registered/unit/models/test_nextn_hf_to_sglang_mapper.py new file mode 100644 index 0000000000000..cb0970f976963 --- /dev/null +++ b/test/registered/unit/models/test_nextn_hf_to_sglang_mapper.py @@ -0,0 +1,73 @@ +import sys +from types import SimpleNamespace + +import pytest + +from sglang.srt.model_loader.loader import _get_quantization_config +from sglang.srt.models.glm5_next_nextn import Glm5NextForConditionalGenerationNextN +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci( + est_time=10, + suite="base-a-test-cpu", + nightly=False, + disabled=None, +) + + +class _FakeQuarkConfig: + def __init__(self): + self.exclude_layers = ["model.layers.46"] + + def get_name(self): + return "quark" + + def get_min_capability(self): + return 75 + + def get_supported_act_dtypes(self): + return ["auto"] + + def apply_weight_name_mapper(self, mapper): + self.exclude_layers = mapper.apply_list(self.exclude_layers) + + +def test_loader_mapper_hook_flows_into_quark_nextn_exclusion(monkeypatch): + monkeypatch.setattr( + Glm5NextForConditionalGenerationNextN, "packed_modules_mapping", {} + ) + monkeypatch.setattr( + "sglang.srt.model_loader.loader.get_model_architecture", + lambda mc: (Glm5NextForConditionalGenerationNextN, None), + ) + fake = _FakeQuarkConfig() + monkeypatch.setattr( + "sglang.srt.model_loader.loader.get_quant_config", + lambda *a, **k: fake, + ) + monkeypatch.setattr( + "sglang.srt.model_loader.loader.get_device_capability", + lambda: (None, None), + ) + + model_config = SimpleNamespace( + hf_config=SimpleNamespace(text_config=SimpleNamespace(num_hidden_layers=46)), + quantization="quark", + dtype="auto", + is_fp4_experts=False, + dequant_fp4_to_fp8=False, + nvfp4_moe_meta=None, + packed_modules_mapping={}, + ) + quant_config = _get_quantization_config(model_config, SimpleNamespace()) + + assert quant_config.exclude_layers == ["model.decoder"] + + resolved = Glm5NextForConditionalGenerationNextN.__new__( + Glm5NextForConditionalGenerationNextN + )._resolve_nextn_quant_config(SimpleNamespace(num_hidden_layers=46), quant_config) + assert resolved is None + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/test/registered/unit/models/test_nope_mha_k_cast.py b/test/registered/unit/models/test_nope_mha_k_cast.py new file mode 100644 index 0000000000000..5e9cfef4f908f --- /dev/null +++ b/test/registered/unit/models/test_nope_mha_k_cast.py @@ -0,0 +1,52 @@ +import sys +from types import SimpleNamespace +from unittest import mock + +import pytest +import torch + +from sglang.srt.models.deepseek_common.attention_forward_methods import forward_mha +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci( + est_time=10, + suite="base-a-test-cpu", + nightly=False, + disabled=None, +) + + +def _run_nope_concat(backend: str, kv_cache_dtype: str, pool_dtype: torch.dtype): + fake_self = SimpleNamespace( + qk_rope_head_dim=0, + current_attention_backend=backend, + kv_cache_dtype=kv_cache_dtype, + ) + fake_pool = SimpleNamespace(dtype=pool_dtype) + with ( + mock.patch.object(forward_mha, "_is_cuda", True), + mock.patch.object(forward_mha, "get_token_to_kv_pool", return_value=fake_pool), + ): + return forward_mha.DeepseekMHAForwardMixin._concat_and_cast_mha_k( + fake_self, + torch.randn(4, 2, 128, dtype=torch.bfloat16), + None, + None, + ) + + +@pytest.mark.parametrize( + "backend,kv_cache_dtype,pool_dtype,expected_dtype", + [ + ("fa3", "fp8_e4m3", torch.float8_e4m3fn, torch.float8_e4m3fn), + ("fa3", "auto", torch.float8_e4m3fn, torch.bfloat16), + ("trtllm_gen", "fp8_e4m3", torch.float8_e4m3fn, torch.bfloat16), + ], +) +def test_nope_mha_k_cast(backend, kv_cache_dtype, pool_dtype, expected_dtype): + out = _run_nope_concat(backend, kv_cache_dtype, pool_dtype) + assert out.dtype == expected_dtype + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/test/registered/unit/multimodal/test_alpha_channel_gating.py b/test/registered/unit/multimodal/test_alpha_channel_gating.py new file mode 100644 index 0000000000000..d4f13c3f8221b --- /dev/null +++ b/test/registered/unit/multimodal/test_alpha_channel_gating.py @@ -0,0 +1,72 @@ +import sys +from io import BytesIO + +import pytest +from PIL import Image + +from sglang.srt.managers.schedule_batch import Modality +from sglang.srt.multimodal.processors.base_processor import BaseMultimodalProcessor +from sglang.srt.multimodal.processors.glm4v import Glm4vImageProcessor +from sglang.srt.multimodal.processors.kimi_k3 import KimiK3ImageProcessor +from sglang.srt.utils.common import load_image, smart_to_rgb +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci( + est_time=10, + suite="base-a-test-cpu", + nightly=False, + disabled=None, +) + +_RGBA_PIXEL = (10, 20, 30, 200) + + +def _rgba_png_bytes() -> bytes: + img = Image.new("RGBA", (4, 4), _RGBA_PIXEL) + buf = BytesIO() + img.save(buf, "PNG") + return buf.getvalue() + + +def test_load_image_preserves_rgba_fidelity(): + img, _ = load_image(_rgba_png_bytes()) + assert img.mode == "RGBA" + assert img.getpixel((0, 0)) == _RGBA_PIXEL + + +def test_kimi_k3_no_discard_keeps_rgba(): + out = KimiK3ImageProcessor._load_single_item( + _rgba_png_bytes(), + modality=Modality.IMAGE, + discard_alpha_channel=False, + ) + assert out.mode == "RGBA" + assert out.getpixel((0, 0)) == _RGBA_PIXEL + + +def test_default_processor_plain_convert_drops_alpha_only(): + out = BaseMultimodalProcessor._load_single_item( + _rgba_png_bytes(), + modality=Modality.IMAGE, + discard_alpha_channel=True, + ) + assert out.mode == "RGB" + assert out.getpixel((0, 0)) == _RGBA_PIXEL[:3] + + +def test_glm4v_optin_smart_composite_matches_reference(): + rgba = Image.open(BytesIO(_rgba_png_bytes())) + reference = smart_to_rgb(rgba.copy()) + out = Glm4vImageProcessor._load_single_item( + _rgba_png_bytes(), + modality=Modality.IMAGE, + discard_alpha_channel=True, + ) + assert out.mode == "RGB" + assert out.getpixel((0, 0)) == reference.getpixel((0, 0)) + plain = rgba.convert("RGB") + assert out.getpixel((0, 0)) != plain.getpixel((0, 0)) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/test/registered/unit/parser/test_jinja_template_utils.py b/test/registered/unit/parser/test_jinja_template_utils.py index d23b88fc36736..b7145f71c0192 100644 --- a/test/registered/unit/parser/test_jinja_template_utils.py +++ b/test/registered/unit/parser/test_jinja_template_utils.py @@ -4,6 +4,7 @@ from sglang.srt.parser.jinja_template_utils import ( detect_jinja_template_content_format, + jinja_template_may_reorder_tool_results, process_content_for_template_format, ) from sglang.test.ci.ci_register import register_cpu_ci @@ -16,6 +17,34 @@ class TestTemplateContentFormatDetection(CustomTestCase): """Test template content format detection functionality.""" + def test_detect_tool_result_id_association(self): + attribute_template = """ + {% for message in messages %} + {{ message.tool_call_id }} + {% endfor %} + """ + item_template = "{{ messages[0]['tool_call_id'] }}" + get_template = "{{ messages[0].get('tool_call_id') }}" + select_template = ( + "{{ messages | selectattr('tool_call_id', 'equalto', 'call-a') | list }}" + ) + sort_template = "{{ messages | sort(attribute='tool_call_id') }}" + + self.assertTrue(jinja_template_may_reorder_tool_results(attribute_template)) + self.assertTrue(jinja_template_may_reorder_tool_results(item_template)) + self.assertTrue(jinja_template_may_reorder_tool_results(get_template)) + self.assertTrue(jinja_template_may_reorder_tool_results(select_template)) + self.assertTrue(jinja_template_may_reorder_tool_results(sort_template)) + + def test_tool_call_id_text_does_not_enable_order_recovery(self): + self.assertFalse( + jinja_template_may_reorder_tool_results( + "{# tool_call_id is mentioned only in a comment #}{{ messages }}" + ) + ) + self.assertFalse(jinja_template_may_reorder_tool_results("{{{{ invalid")) + self.assertFalse(jinja_template_may_reorder_tool_results(None)) + def test_detect_llama4_openai_format(self): """Test detection of llama4-style template (should be 'openai' format).""" llama4_pattern = """ diff --git a/test/registered/unit/server_args/test_server_args.py b/test/registered/unit/server_args/test_server_args.py index 9407f3b57eaa4..252e2234ef472 100644 --- a/test/registered/unit/server_args/test_server_args.py +++ b/test/registered/unit/server_args/test_server_args.py @@ -1928,6 +1928,50 @@ def test_lora_still_disables_tc_piecewise_prefill_graph(self): ) +class TestBreakableCudaGraphKDACompatibility(CustomTestCase): + def _handled_args(self, **overrides): + args = ServerArgs(model_path="dummy", **overrides) + text_config = SimpleNamespace( + layer_types=["linear_attention", "deepseek_sparse_attention"], + linear_num_heads=64, + linear_head_dim=128, + ) + args.model_config = SimpleNamespace( + hf_config=SimpleNamespace( + architectures=["KimiLinearForCausalLM"], + get_text_config=lambda: text_config, + ), + is_piecewise_cuda_graph_disabled_model=False, + is_multimodal=False, + is_multimodal_piecewise_cuda_graph_supported=False, + is_multimodal_breakable_cuda_graph_supported=False, + ) + with ( + patch("sglang.srt.utils.is_cuda", return_value=True), + patch.object(ServerArgs, "use_mla_backend", return_value=False), + ): + args._handle_cuda_graph_config() + return args + + def test_default_breakable_prefill_graph_is_disabled(self): + args = self._handled_args() + + self.assertEqual(args.cuda_graph_config.prefill.backend, Backend.DISABLED) + self.assertNotEqual(args.cuda_graph_config.decode.backend, Backend.DISABLED) + + def test_explicit_breakable_prefill_graph_is_preserved(self): + args = self._handled_args(cuda_graph_backend_prefill=Backend.BREAKABLE) + + self.assertEqual(args.cuda_graph_config.prefill.backend, Backend.BREAKABLE) + + def test_legacy_kda_layer_list_is_detected(self): + from sglang.srt.configs.model_config import uses_kda_attention + + config = SimpleNamespace(linear_attn_config={"kda_layers": [0, 2]}) + + self.assertTrue(uses_kda_attention(config)) + + class TestBreakableCudaGraphMultimodalAllowlist(CustomTestCase): """The BCG "multimodal model" rule exempts archs on the BCG multimodal opt-in allowlist (multimodal_breakable_cuda_graph_supported_model_archs).""" diff --git a/test/registered/unit/spec/test_ngram_mamba_verify_update.py b/test/registered/unit/spec/test_ngram_mamba_verify_update.py index a620b5f2ff6b2..f67cf3bc3cd24 100644 --- a/test/registered/unit/spec/test_ngram_mamba_verify_update.py +++ b/test/registered/unit/spec/test_ngram_mamba_verify_update.py @@ -126,6 +126,12 @@ def test_mamba_verify_update_called_with_correct_indices(self): with patch( "sglang.srt.speculative.spec_utils.mambaish_config", return_value={"some": "config"}, + ), patch( + "sglang.srt.speculative.spec_utils.get_spec", + return_value=MagicMock(speculative_eagle_topk=2), + ), patch( + "sglang.srt.speculative.spec_utils.mamba_track_grid", + return_value=256, ): commit_mamba_states_after_verify( target_worker, @@ -200,6 +206,9 @@ def test_mamba_verify_update_with_track_indices(self): ), patch( "sglang.srt.speculative.spec_utils.mamba_track_grid", return_value=256, + ), patch( + "sglang.srt.speculative.spec_utils.get_spec", + return_value=MagicMock(speculative_eagle_topk=2), ): commit_mamba_states_after_verify( target_worker, @@ -422,5 +431,91 @@ def test_all_overrides_accept_the_call_kwargs(self): ) +class TestMambaTrackSkipAdaptiveBound(CustomTestCase): + """The interval-crossing skip must bound its reach by the CONFIGURED + maximum draft size: adaptive gear switches overwrite + server_args.speculative_num_draft_tokens with the current gear, while the + in-flight verify the host counter lags behind may still be from a larger + gear. Regression for the downshift-near-boundary case. + """ + + def _run_commit(self, kv_committed_len, current_draft=2, max_draft=8, interval=256): + from sglang.srt.speculative.spec_utils import commit_mamba_states_after_verify + + target_worker = MagicMock() + target_worker.model_runner.model = MagicMock() + # This test isolates the generic Mamba commit path. A bare MagicMock + # would make the upstream ReplaySSM feature flags truthy and divert the + # call into the unrelated KDA fold path. + target_worker.model_runner.req_to_token_pool.mamba_pool = None + + batch = MagicMock() + batch.forward_mode.is_idle.return_value = False + batch.mamba_track_indices = torch.tensor([100], dtype=torch.int64) + batch.seq_lens = torch.tensor([kv_committed_len + 4], dtype=torch.int32) + # GPU-only backend (no CPU mirror): force the host-counter bound. + batch.seq_lens_cpu = None + req = MagicMock() + req.kv_committed_len = kv_committed_len + batch.reqs = [req] + accept_lens = torch.tensor([current_draft], dtype=torch.int32) + accept_index = torch.tensor([[0, 1, -1, -1]], dtype=torch.int32) + + prologue = MagicMock( + return_value=( + torch.tensor([1], dtype=torch.int32), + torch.tensor([-1], dtype=torch.int32), + ) + ) + with patch( + "sglang.srt.speculative.spec_utils.mambaish_config", + return_value={"some": "config"}, + ), patch( + "sglang.srt.speculative.spec_utils.get_spec", + return_value=MagicMock(speculative_eagle_topk=1), + ), patch( + "sglang.srt.speculative.spec_utils.mamba_track_grid", + return_value=interval, + ), patch( + "sglang.srt.speculative.spec_utils.max_speculative_num_draft_tokens", + return_value=max_draft, + ), patch( + "sglang.srt.speculative.spec_utils._is_cuda", True + ), patch( + "sglang.srt.speculative.spec_utils._is_hip", False + ), patch( + "sglang.kernels.ops.speculative.eagle.nextn_mamba_commit_prologue_func", + prologue, + ): + commit_mamba_states_after_verify( + target_worker, + batch, + accept_lens, + accept_index, + draft_token_num=current_draft, + ) + return prologue + + def test_downshift_near_boundary_keeps_track_commit(self): + # lb=249, interval=256: a current-gear reach (3*2=6) would stay in + # bucket 0 (249 -> 255) and wrongly skip, but the in-flight verify may + # have used the configured gear; the configured-max reach (3*8=24) + # crosses (249 -> 273), so the exact tracked path must be kept. + prologue = self._run_commit(kv_committed_len=249) + prologue.assert_called_once() + args = prologue.call_args[0] + self.assertEqual(args[2], 256, "track interval must be passed through") + self.assertTrue(args[3], "has_track must stay True near the boundary") + + def test_far_from_boundary_skips_track_commit(self): + # lb=10: even the configured-max reach (3*8=24) stays inside bucket 0, + # so skipping the track commit is provably safe. + prologue = self._run_commit(kv_committed_len=10) + prologue.assert_called_once() + args = prologue.call_args[0] + self.assertEqual(args[2], 0, "skip must disable interval tracking") + self.assertFalse(args[3]) + + if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/spec/test_spec_cpu_overlap_constraint.py b/test/registered/unit/spec/test_spec_cpu_overlap_constraint.py index 68ef5eac9c9a0..16dfab58a86c9 100644 --- a/test/registered/unit/spec/test_spec_cpu_overlap_constraint.py +++ b/test/registered/unit/spec/test_spec_cpu_overlap_constraint.py @@ -1,5 +1,6 @@ import unittest from types import SimpleNamespace +from unittest.mock import Mock from sglang.srt.arg_groups.overrides import resolution_result from sglang.srt.arg_groups.speculative_hook import handle_speculative_decoding @@ -71,6 +72,55 @@ def test_cuda_eagle_keeps_overlap_schedule(self): self.assertFalse(resolution_result(args, "disable_overlap_schedule")) + def test_hybrid_kda_allows_plan_stream_graph_load(self): + from sglang.srt.layers.attention.hybrid_linear_attn_backend import ( + HybridLinearAttnBackend, + ) + from sglang.srt.layers.attention.linear.kda_backend import KDAAttnBackend + + full_backend = Mock( + token_to_kv_pool=object(), + req_to_token_pool=object(), + max_context_len=4096, + needs_cpu_seq_lens=False, + ) + linear_backend = Mock( + spec=KDAAttnBackend, + needs_cpu_seq_lens=False, + supports_overlap_plan_stream_graph_load=( + KDAAttnBackend.supports_overlap_plan_stream_graph_load + ), + ) + + backend = HybridLinearAttnBackend(full_backend, linear_backend, []) + + self.assertTrue(backend.supports_overlap_plan_stream_graph_load) + self.assertFalse(backend.needs_cpu_seq_lens) + + def test_unaudited_linear_backend_defers_plan_stream_graph_load(self): + from sglang.srt.layers.attention.hybrid_linear_attn_backend import ( + HybridLinearAttnBackend, + MambaAttnBackendBase, + ) + + full_backend = Mock( + token_to_kv_pool=object(), + req_to_token_pool=object(), + max_context_len=4096, + needs_cpu_seq_lens=False, + ) + linear_backend = Mock( + spec=MambaAttnBackendBase, + needs_cpu_seq_lens=False, + supports_overlap_plan_stream_graph_load=( + MambaAttnBackendBase.supports_overlap_plan_stream_graph_load + ), + ) + + backend = HybridLinearAttnBackend(full_backend, linear_backend, []) + + self.assertFalse(backend.supports_overlap_plan_stream_graph_load) + if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/test_dsa_trtllm_fp8_cp.py b/test/registered/unit/test_dsa_trtllm_fp8_cp.py new file mode 100644 index 0000000000000..134a7a462a777 --- /dev/null +++ b/test/registered/unit/test_dsa_trtllm_fp8_cp.py @@ -0,0 +1,81 @@ +import unittest + +import torch + +from sglang.srt.layers.attention.dsa_backend import ( + _should_all_gather_dsa_trtllm_fp8_kv, + _should_return_dsa_trtllm_lse, +) +from sglang.srt.model_executor.forward_batch_info import ForwardMode +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=1, suite="base-a-test-cpu") + + +class TestDSATRTLLMFP8CP(unittest.TestCase): + def test_nope_kv_is_not_gathered_again(self): + self.assertFalse( + _should_all_gather_dsa_trtllm_fp8_kv( + save_kv_cache=True, + cos_sin_cache=None, + dsa_prefill_cp=True, + ) + ) + + def test_fused_rope_kv_is_gathered_after_rope(self): + self.assertTrue( + _should_all_gather_dsa_trtllm_fp8_kv( + save_kv_cache=True, + cos_sin_cache=torch.empty(0), + dsa_prefill_cp=True, + ) + ) + + def test_non_cp_and_no_cache_paths_do_not_gather(self): + cos_sin_cache = torch.empty(0) + self.assertFalse( + _should_all_gather_dsa_trtllm_fp8_kv( + save_kv_cache=True, + cos_sin_cache=cos_sin_cache, + dsa_prefill_cp=False, + ) + ) + self.assertFalse( + _should_all_gather_dsa_trtllm_fp8_kv( + save_kv_cache=False, + cos_sin_cache=cos_sin_cache, + dsa_prefill_cp=True, + ) + ) + + def test_dcp_decode_and_verify_request_lse(self): + self.assertTrue( + _should_return_dsa_trtllm_lse( + forward_mode=ForwardMode.DECODE, + dcp_enabled=True, + ) + ) + self.assertTrue( + _should_return_dsa_trtllm_lse( + forward_mode=ForwardMode.TARGET_VERIFY, + dcp_enabled=True, + ) + ) + + def test_non_dcp_and_prefill_do_not_request_lse(self): + self.assertFalse( + _should_return_dsa_trtllm_lse( + forward_mode=ForwardMode.DECODE, + dcp_enabled=False, + ) + ) + self.assertFalse( + _should_return_dsa_trtllm_lse( + forward_mode=ForwardMode.EXTEND, + dcp_enabled=True, + ) + ) + + +if __name__ == "__main__": + unittest.main() From 8b8676ba3332c5db53e08533724ac84cefad2c78 Mon Sep 17 00:00:00 2001 From: Xinyuan Tong Date: Wed, 26 Aug 2026 17:00:52 +0000 Subject: [PATCH 02/44] Fix HiCache + MTP startup and unify the shared-experts fusion gate Two model-serving fixes validated on 4x GB300 with the final GLM-5.3-Flash weights: - build_hybrid_mamba_stack unwrapped .full_kv_pool from every MTP draft pool, which only holds for HybridLinearKVPool-wrapped drafts; bare DSA draft pools (GLM-5.3-Flash NEXTN) crashed HiCache+MTP startup with AttributeError. Unwrap only the wrapper, pass bare pools through. Validated: startup passes pool assembly, L2 host pool packs target 11 + draft 1 layers, GSM8K-20 95% with 100% stop rate. - The installed fusion decision and the glm5_next wrapper gate diverged at EP>1: layers were built fused (router feeds expert 288 at ~1.0) while the weight remap into slot 288 was skipped, leaving the slot uninitialized and the output degenerate. Add shared_experts_fusion_disable_reason mirroring the wrapper gate so both resolve OFF at EP>1/DeepEP. Validated: unfused build without the disable flag, GSM8K-20 20/20 with 100% stop rate. --- .../hybrid_cache/hybrid_pool_assembler.py | 6 ++- python/sglang/srt/models/glm5_next.py | 41 +++++++++++-------- 2 files changed, 30 insertions(+), 17 deletions(-) diff --git a/python/sglang/srt/mem_cache/hybrid_cache/hybrid_pool_assembler.py b/python/sglang/srt/mem_cache/hybrid_cache/hybrid_pool_assembler.py index 2b38326b01119..01672d854b9c3 100644 --- a/python/sglang/srt/mem_cache/hybrid_cache/hybrid_pool_assembler.py +++ b/python/sglang/srt/mem_cache/hybrid_cache/hybrid_pool_assembler.py @@ -712,8 +712,12 @@ def build_hybrid_mamba_stack( ) -> tuple[HostPoolGroup, HybridCacheController]: transfer_layer_num = len(full_layer_mapping | mamba_layer_mapping) mamba_allocator = params.req_to_token_pool.mamba_allocator + from sglang.srt.mem_cache.memory_pool import HybridLinearKVPool + + # Hybrid drafts wrap attention KV in HybridLinearKVPool; DSA drafts are bare pools. mtp_draft_device_pools = tuple( - pool.full_kv_pool for pool in params.mtp_draft_device_pools + pool.full_kv_pool if isinstance(pool, HybridLinearKVPool) else pool + for pool in params.mtp_draft_device_pools ) kv_host_size, mamba_host_size = None, 0 if get_memory().hicache_size > 0: diff --git a/python/sglang/srt/models/glm5_next.py b/python/sglang/srt/models/glm5_next.py index a2ef6bbf10ddd..c50a204b9a86f 100644 --- a/python/sglang/srt/models/glm5_next.py +++ b/python/sglang/srt/models/glm5_next.py @@ -1331,28 +1331,37 @@ def start_layer(self): def end_layer(self): return self.model.end_layer - def determine_num_fused_shared_experts(self): - self.num_fused_shared_experts = 0 - if get_server_args().disable_shared_experts_fusion: - return - - disable_reason = None - if not getattr(self.config, "n_shared_experts", None): - disable_reason = "No shared experts are defined in the config." - elif not _is_cuda: - disable_reason = "Shared experts fusion currently requires CUDA devices." - elif _is_cuda and (_device_sm is not None) and (_device_sm < 80): - disable_reason = "Shared experts fusion requires SM80 or newer GPUs." - elif get_parallel().moe_ep_size > 1: - disable_reason = ( + @classmethod + def shared_experts_fusion_disable_reason(cls, hf_config, quant_config): + # Kept in lockstep with the wrapper gate below: a divergence drops the + # shared-expert weights and runs the fused slot uninitialized. + text_config = getattr(hf_config, "text_config", hf_config) + if not getattr(text_config, "n_shared_experts", None): + return "No shared experts are defined in the config." + if not _is_cuda: + return "Shared experts fusion currently requires CUDA devices." + if _device_sm is not None and _device_sm < 80: + return "Shared experts fusion requires SM80 or newer GPUs." + if get_parallel().moe_ep_size > 1: + return ( "Shared experts fusion is not supported together with expert " "parallelism yet." ) - elif get_moe_a2a_backend().is_deepep(): - disable_reason = ( + if get_moe_a2a_backend().is_deepep(): + return ( "Shared experts fusion is not supported when Deepep MoE backend " "is enabled." ) + return None + + def determine_num_fused_shared_experts(self): + self.num_fused_shared_experts = 0 + if get_server_args().disable_shared_experts_fusion: + return + + disable_reason = type(self).shared_experts_fusion_disable_reason( + self.config, self.quant_config + ) if disable_reason is not None: log_info_on_rank0( From d6ab04bdf157d80aff9e850535921c58adace116 Mon Sep 17 00:00:00 2001 From: Xinyuan Tong Date: Wed, 26 Aug 2026 17:37:41 +0000 Subject: [PATCH 03/44] Fix stray server_args kwarg in the hybrid linear KV pool builder calculate_mla_kv_cache_dim takes only model_config and kv_cache_dtype; the extra kwarg crashed every hybrid-linear (KDA) model at KV-pool init with TypeError before weights loaded. --- python/sglang/srt/mem_cache/kv_cache_configurator.py | 1 - 1 file changed, 1 deletion(-) diff --git a/python/sglang/srt/mem_cache/kv_cache_configurator.py b/python/sglang/srt/mem_cache/kv_cache_configurator.py index c2830428fc3a7..7f369e4c6c4fd 100644 --- a/python/sglang/srt/mem_cache/kv_cache_configurator.py +++ b/python/sglang/srt/mem_cache/kv_cache_configurator.py @@ -1610,7 +1610,6 @@ def _build_hybrid_linear_kv_pool( kv_cache_dim=calculate_mla_kv_cache_dim( model_config=self.model_config, kv_cache_dtype=self.kv_cache_dtype, - server_args=self.server_args, ), index_kpool=dsa_index_kpool, index_kpool_compress=get_dsa_index_kpool_compress( From f040cc72e682ff3b235eb0261abaa8a8d79eda67 Mon Sep 17 00:00:00 2001 From: Xinyuan Tong Date: Wed, 26 Aug 2026 19:02:16 +0000 Subject: [PATCH 04/44] fix(dsa): return LSE from the tilelang DSA decode/verify path under DCP The DCP decode contract (forward_mla.py attn_mqa_for_dcp_decode) requires the attention backend to return (attn_output, lse) so partials can be merged across DCP ranks. Only the trtllm DSA impl satisfied it; the tilelang impl returned a single tensor and target-verify full-graph capture died with 'not enough values to unpack (expected 2, got 1)'. The tilelang v1/v2 sparse kernels already compute the base-2 LSE in their epilogue but discard it. Expose it behind a return_lse factory flag (compiled out otherwise, keeping the non-DCP hot path unchanged) and plumb it through tilelang_sparse_fwd / _forward_tilelang, gated on the same dcp_enabled + decode/target_verify predicate as trtllm. Validation (GB300, GLM-5.3-Flash): tilelang DCP4 target-verify full-graph capture passes; kernel LSE max abs err 1.9e-6 vs reference; attention output bit-identical with DCP off. --- .../ops/attention/dsa/tilelang_kernel.py | 25 ++++++++++++++++-- .../srt/layers/attention/dsa_backend.py | 26 ++++++++++++++++--- 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py b/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py index 4bd96eecccac7..2c1eff2e2e3c9 100644 --- a/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py +++ b/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py @@ -271,6 +271,7 @@ def sparse_attention_fwd_kernel_v1( block_I=64, num_stages=2, threads=256, + return_lse=False, ): assert ( dim == tilelang.math.next_power_of_2(dim) or dim % 64 == 0 @@ -296,6 +297,7 @@ def sparse_attention_fwd_kernel_v1( q_shape = [batch, seq_len, num_heads, dim + tail_dim] kv_shape = [batch, seq_len_kv, kv_group, dim + tail_dim] o_shape = [batch, seq_len, num_heads, dim] + lse_shape = [batch, seq_len, num_heads] indices_shape = [batch, seq_len, kv_group, topk] indices_dtype = "int32" dtype = "bfloat16" @@ -323,6 +325,7 @@ def main( Q: T.Tensor(q_shape, dtype), # type: ignore KV: T.Tensor(kv_shape, dtype), # type: ignore Indices: T.Tensor(indices_shape, indices_dtype), # type: ignore + LSE: T.Tensor(lse_shape, accum_dtype), # type: ignore Output: T.Tensor(o_shape, dtype), # type: ignore ): with T.Kernel(seq_len * REPLICATE_H, batch, kv_group, threads=threads) as ( @@ -423,6 +426,8 @@ def main( acc_o[h_i, d_i] /= sumexp[h_i] for h_i in T.Parallel(H_per_block): sumexp[h_i] = T.log2(sumexp[h_i]) + m_i[h_i] * sm_scale + if return_lse: + T.copy(sumexp, LSE[b_i, s_i, H0:H1]) T.copy(acc_o, O_shared) T.copy(acc_o, Output[b_i, s_i, H0:H1, :]) @@ -454,6 +459,7 @@ def sparse_attention_fwd_kernel_v2( kv_group: int = 1, sm_scale: Optional[float] = None, block_I: int = 64, + return_lse: bool = False, ): assert dim == tilelang.math.next_power_of_2( dim @@ -477,6 +483,7 @@ def sparse_attention_fwd_kernel_v2( q_shape = [batch, qo_len, num_heads, dim + tail_dim] kv_shape = [batch, num_pages, kv_group, dim + tail_dim] o_shape = [batch, qo_len, num_heads, dim] + lse_shape = [batch, qo_len, num_heads] indices_shape = [batch, qo_len, kv_group, topk] indices_dtype = "int32" @@ -505,6 +512,7 @@ def main( Q: T.Tensor(q_shape, dtype), # type: ignore KV: T.Tensor(kv_shape, dtype), # type: ignore Indices: T.Tensor(indices_shape, indices_dtype), # type: ignore + LSE: T.Tensor(lse_shape, accum_dtype), # type: ignore Output: T.Tensor(o_shape, dtype), # type: ignore ): """ @@ -672,6 +680,8 @@ def main( acc_o_l[h_i, d_i] /= sumexp[h_i] for h_i in T.Parallel(H_per_block): sumexp[h_i] = T.log2(sumexp[h_i]) + m_i[h_i] * sm_scale + if return_lse: + T.copy(sumexp, LSE[b_i, s_i, H0:H1]) T.copy(acc_o_l, O_shared_l) T.copy(O_shared_l, Output[b_i, s_i, H0:H1, 0 : D // 2]) elif tx >= 128 and tx < 256: @@ -1329,6 +1339,7 @@ def tilelang_sparse_fwd( indices: torch.Tensor, sm_scale: float, d_v: int = 512, + return_lse: bool = False, ) -> torch.Tensor: assert q.dim() == 3 and kv.dim() == 3 and indices.dim() == 3 num_heads = q.shape[1] @@ -1338,6 +1349,7 @@ def tilelang_sparse_fwd( assert topk % 64 == 0, "topk must be padded to a multiple of 64" if _is_hip: + assert not return_lse, "tilelang HIP sparse fwd does not return LSE" is_fp8_kv = kv.dtype in (torch.float8_e4m3fn, torch.float8_e4m3fnuz) if is_fp8_kv: if q.dtype != kv.dtype: @@ -1394,8 +1406,17 @@ def tilelang_sparse_fwd( if tail_dim == 0 else sparse_attention_fwd_kernel_v2 ) - kernel = kernel_factory(num_heads, d_v, tail_dim, topk, sm_scale=sm_scale) - out = kernel(q.unsqueeze(0), kv.unsqueeze(0), indices.unsqueeze(0)) # type: ignore + kernel = kernel_factory( + num_heads, d_v, tail_dim, topk, sm_scale=sm_scale, return_lse=return_lse + ) + # Caller-allocated LSE (in-place kernel arg): written only by kernels + # traced with return_lse=True, but the prim_func signature always has it. + lse = torch.empty( + (1, q.shape[0], num_heads), dtype=torch.float32, device=q.device + ) + out = kernel(q.unsqueeze(0), kv.unsqueeze(0), indices.unsqueeze(0), lse) # type: ignore + if return_lse: + return out, lse return out diff --git a/python/sglang/srt/layers/attention/dsa_backend.py b/python/sglang/srt/layers/attention/dsa_backend.py index d4f24a207d5cb..b6055c2d4dd4b 100644 --- a/python/sglang/srt/layers/attention/dsa_backend.py +++ b/python/sglang/srt/layers/attention/dsa_backend.py @@ -145,9 +145,7 @@ def _should_all_gather_dsa_trtllm_fp8_kv( return save_kv_cache and cos_sin_cache is not None and dsa_prefill_cp -def _should_return_dsa_trtllm_lse( - *, forward_mode: ForwardMode, dcp_enabled: bool -) -> bool: +def _should_return_dsa_dcp_lse(*, forward_mode: ForwardMode, dcp_enabled: bool) -> bool: return dcp_enabled and (forward_mode.is_decode() or forward_mode.is_target_verify()) @@ -3228,6 +3226,10 @@ def forward_extend( page_table_1=page_table_1, sm_scale=layer.scaling, v_head_dim=layer.v_head_dim, + return_lse=_should_return_dsa_dcp_lse( + forward_mode=forward_batch.forward_mode, + dcp_enabled=get_parallel().dcp_enabled, + ), ) elif dsa_impl in ("flashmla_sparse", "flashmla_sparse_q8"): if topk_transform_method == TopkTransformMethod.RAGGED: @@ -3526,6 +3528,10 @@ def forward_decode( page_table_1=page_table_1, sm_scale=layer.scaling, v_head_dim=layer.v_head_dim, + return_lse=_should_return_dsa_dcp_lse( + forward_mode=forward_batch.forward_mode, + dcp_enabled=get_parallel().dcp_enabled, + ), ) elif dsa_impl == "fa3": return self._forward_fa3( @@ -4141,6 +4147,7 @@ def _forward_tilelang( v_head_dim: int, page_table_1: torch.Tensor, sm_scale: float, + return_lse: bool = False, ) -> torch.Tensor: from sglang.kernels.ops.attention.dsa.tilelang_kernel import tilelang_sparse_fwd @@ -4157,6 +4164,17 @@ def _forward_tilelang( dim=-1, ) + if return_lse: + out, lse = tilelang_sparse_fwd( + q=q_all, + kv=kv_cache, + indices=page_table_1.unsqueeze(1), + sm_scale=sm_scale, + d_v=v_head_dim, + return_lse=True, + ) + # [1, tokens, H] -> [tokens, H], the [B, H] dcp_pack_a2a_send expects. + return out, lse.squeeze(0) return tilelang_sparse_fwd( q=q_all, kv=kv_cache, @@ -4514,7 +4532,7 @@ def _forward_trtllm( skip_softmax_threshold_scale_factor=envs.SGLANG_SKIP_SOFTMAX_DECODE_THRESHOLD_SCALE_FACTOR.get(), sparse_mla_top_k_lens=sparse_mla_top_k_lens, multi_ctas_kv_counter_buffer=self._multi_ctas_kv_counter_buffer, - return_lse=_should_return_dsa_trtllm_lse( + return_lse=_should_return_dsa_dcp_lse( forward_mode=forward_batch.forward_mode, dcp_enabled=get_parallel().dcp_enabled, ), From 033446bb05f35c0943aed2750c443077ffc0b92c Mon Sep 17 00:00:00 2001 From: Xinyuan Tong Date: Thu, 27 Aug 2026 04:43:00 +0000 Subject: [PATCH 05/44] Fix NEXTN speculative-algorithm resolution after the enum collapse The upstream enum refactor reserved NEXTN as an alias name (spec_registry._RESERVED_ALIASES) but from_string never consulted it, so --speculative-algorithm NEXTN crashed at scheduler init with ValueError: Unknown speculative algorithm name. Resolve reserved alias spellings to their builtin (NEXTN -> EAGLE) before the plugin lookup. --- python/sglang/srt/speculative/spec_info.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/python/sglang/srt/speculative/spec_info.py b/python/sglang/srt/speculative/spec_info.py index 97ca92d31f0f3..6b3645362b630 100644 --- a/python/sglang/srt/speculative/spec_info.py +++ b/python/sglang/srt/speculative/spec_info.py @@ -9,6 +9,7 @@ from sglang.srt.runtime_context import get_spec as get_spec_config from sglang.srt.speculative.spec_registry import ( + _RESERVED_ALIASES, CustomSpecAlgo, ServerArgsValidator, WorkerFactory, @@ -55,6 +56,8 @@ def from_string( return cls[upper] except KeyError: pass + if upper in _RESERVED_ALIASES: + return cls.EAGLE spec = _get_registered_spec(upper) if spec is not None: return spec From c4d5d45e506dcd978a65661a503eda1a272c39a4 Mon Sep 17 00:00:00 2001 From: Jian Chen Date: Thu, 27 Aug 2026 11:23:29 -0700 Subject: [PATCH 06/44] [DFLASH] Support GLM-5.3-Flash hidden-state capture (#36708) --- python/sglang/srt/models/glm5_next.py | 36 +++++++++++-- .../models/test_glm5_next_dflash_capture.py | 53 +++++++++++++++++++ 2 files changed, 84 insertions(+), 5 deletions(-) create mode 100644 test/registered/unit/models/test_glm5_next_dflash_capture.py diff --git a/python/sglang/srt/models/glm5_next.py b/python/sglang/srt/models/glm5_next.py index c50a204b9a86f..66ab83466d77b 100644 --- a/python/sglang/srt/models/glm5_next.py +++ b/python/sglang/srt/models/glm5_next.py @@ -8,6 +8,7 @@ from torch.nn import functional as F from sglang.kernels.ops.attention.fla.fused_norm_gate import FusedRMSNormGated +from sglang.kernels.ops.layernorm.mhc import hc_contract from sglang.kernels.ops.layernorm.mhc import hc_post as _hc_post_fn from sglang.kernels.ops.layernorm.mhc import hc_pre as _hc_pre_fn from sglang.srt.batch_overlap.two_batch_overlap import ( @@ -959,6 +960,7 @@ def __init__( prefix: str = "", ) -> None: super().__init__() + self.config = config self.padding_id = config.pad_token_id self.vocab_size = config.vocab_size self.first_k_dense_replace = config.first_k_dense_replace @@ -1064,6 +1066,7 @@ def __init__( ) ) self.layers_to_capture = [] + self.dflash_capture = False if get_moe_a2a_backend().is_deepep() or get_moe_a2a_backend().is_mooncake(): self.enable_a2a_moe = True else: @@ -1072,6 +1075,14 @@ def __init__( def get_input_embeddings(self) -> torch.Tensor: return self.embed_tokens + def _prepare_aux_hidden_state( + self, hidden_states: torch.Tensor, residual: torch.Tensor + ) -> torch.Tensor: + aux_hidden_state = hidden_states + residual + if self.dflash_capture and self.config.mhc: + aux_hidden_state = hc_contract(aux_hidden_state, self.config.hc_mult) + return aux_hidden_state + def forward( self, input_ids: torch.Tensor, @@ -1122,7 +1133,7 @@ def forward( normal_start_layer = self.start_layer normal_end_layer = self.end_layer - if forward_batch.can_run_tbo: + if forward_batch.can_run_tbo and not self.dflash_capture: if ( self.first_k_dense_replace > normal_start_layer and self.first_k_dense_replace < normal_end_layer @@ -1141,13 +1152,14 @@ def forward( ) with ctx: if i in self.layers_to_capture: + aux_hidden_state = self._prepare_aux_hidden_state( + hidden_states, residual + ) if self.enable_a2a_moe and i > self.first_k_dense_replace: aux_hidden_state = get_parallel().attn_tp_group.all_gather( - hidden_states + residual, dim=0 + aux_hidden_state, dim=0 ) - aux_hidden_states.append(aux_hidden_state) - else: - aux_hidden_states.append(hidden_states + residual) + aux_hidden_states.append(aux_hidden_state) layer = self.layers[i] hidden_states, residual, topk_indices = layer( positions, @@ -1388,6 +1400,20 @@ def set_eagle3_layers_to_capture(self, layer_ids: Optional[List[int]] = None): self.capture_aux_hidden_states = True self.model.layers_to_capture = [val + 1 for val in layer_ids] + def set_dflash_layers_to_capture(self, layer_ids: List[int]): + if not self.pp_group.is_last_rank: + return + + if layer_ids is None: + raise ValueError( + "DFLASH requires explicit layer_ids for aux hidden capture." + ) + + self.capture_aux_hidden_states = True + self.model.dflash_capture = True + # Capturing before layer k + 1 gives the completed output of layer k. + self.model.layers_to_capture = [val + 1 for val in layer_ids] + def prepare_context_parallel_metadata_for_dcp( self, seq_lens: torch.Tensor, diff --git a/test/registered/unit/models/test_glm5_next_dflash_capture.py b/test/registered/unit/models/test_glm5_next_dflash_capture.py new file mode 100644 index 0000000000000..d1da40f8ec465 --- /dev/null +++ b/test/registered/unit/models/test_glm5_next_dflash_capture.py @@ -0,0 +1,53 @@ +from types import SimpleNamespace + +import torch +from torch import nn + +from sglang.srt.models.glm5_next import ( + Glm5NextForConditionalGeneration, + Glm5NextModel, +) + + +def test_glm5_next_dflash_contracts_mhc_hidden_state(): + model = Glm5NextModel.__new__(Glm5NextModel) + nn.Module.__init__(model) + model.config = SimpleNamespace(mhc=True, hc_mult=4) + model.dflash_capture = True + + hidden_states = torch.arange(24, dtype=torch.float32).reshape(2, 12) + residual = torch.full_like(hidden_states, 2) + + actual = model._prepare_aux_hidden_state(hidden_states, residual) + expected = (hidden_states + residual).unflatten(-1, (4, -1)).mean(dim=-2) + + torch.testing.assert_close(actual, expected) + assert actual.shape == (2, 3) + + +def test_glm5_next_eagle_capture_keeps_mhc_hidden_state(): + model = Glm5NextModel.__new__(Glm5NextModel) + nn.Module.__init__(model) + model.config = SimpleNamespace(mhc=True, hc_mult=4) + model.dflash_capture = False + + hidden_states = torch.arange(24, dtype=torch.float32).reshape(2, 12) + residual = torch.full_like(hidden_states, 2) + + actual = model._prepare_aux_hidden_state(hidden_states, residual) + + torch.testing.assert_close(actual, hidden_states + residual) + + +def test_glm5_next_dflash_maps_target_layers_to_capture_points(): + model = Glm5NextForConditionalGeneration.__new__(Glm5NextForConditionalGeneration) + nn.Module.__init__(model) + model.pp_group = SimpleNamespace(is_last_rank=True) + model.model = SimpleNamespace(dflash_capture=False, layers_to_capture=[]) + model.capture_aux_hidden_states = False + + model.set_dflash_layers_to_capture([5, 14, 24, 33, 42]) + + assert model.capture_aux_hidden_states + assert model.model.dflash_capture + assert model.model.layers_to_capture == [6, 15, 25, 34, 43] From 92831e5ec1e109b1be6d7071281557cd6481f4f5 Mon Sep 17 00:00:00 2001 From: zijiexia <37504505+zijiexia@users.noreply.github.com> Date: Thu, 27 Aug 2026 17:24:34 -0700 Subject: [PATCH 07/44] Fix DFLASH aux hidden-state capture on mHC models (#36755) Co-authored-by: Claude Opus 5 --- python/sglang/srt/models/glm5_next.py | 9 ++++- .../models/test_glm5_next_dflash_capture.py | 39 +++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/python/sglang/srt/models/glm5_next.py b/python/sglang/srt/models/glm5_next.py index 66ab83466d77b..c931892e17562 100644 --- a/python/sglang/srt/models/glm5_next.py +++ b/python/sglang/srt/models/glm5_next.py @@ -1076,9 +1076,14 @@ def get_input_embeddings(self) -> torch.Tensor: return self.embed_tokens def _prepare_aux_hidden_state( - self, hidden_states: torch.Tensor, residual: torch.Tensor + self, hidden_states: torch.Tensor, residual: Optional[torch.Tensor] ) -> torch.Tensor: - aux_hidden_state = hidden_states + residual + # Under mHC the residual is folded into the widened hidden state, so the + # layer communicator hands back residual=None and hc_contract below does + # the merge. Only the plain residual-stream path has a tensor to add. + aux_hidden_state = ( + hidden_states if residual is None else hidden_states + residual + ) if self.dflash_capture and self.config.mhc: aux_hidden_state = hc_contract(aux_hidden_state, self.config.hc_mult) return aux_hidden_state diff --git a/test/registered/unit/models/test_glm5_next_dflash_capture.py b/test/registered/unit/models/test_glm5_next_dflash_capture.py index d1da40f8ec465..2d8d9fef91fc1 100644 --- a/test/registered/unit/models/test_glm5_next_dflash_capture.py +++ b/test/registered/unit/models/test_glm5_next_dflash_capture.py @@ -1,5 +1,7 @@ +import sys from types import SimpleNamespace +import pytest import torch from torch import nn @@ -7,6 +9,9 @@ Glm5NextForConditionalGeneration, Glm5NextModel, ) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="base-a-test-cpu") def test_glm5_next_dflash_contracts_mhc_hidden_state(): @@ -39,6 +44,36 @@ def test_glm5_next_eagle_capture_keeps_mhc_hidden_state(): torch.testing.assert_close(actual, hidden_states + residual) +def test_glm5_next_dflash_contracts_mhc_hidden_state_without_residual(): + # GLM-5.3-Flash runs with mhc=True, where MHCLayerCommunicator folds the + # residual into the widened hidden state and returns residual=None. + model = Glm5NextModel.__new__(Glm5NextModel) + nn.Module.__init__(model) + model.config = SimpleNamespace(mhc=True, hc_mult=4) + model.dflash_capture = True + + hidden_states = torch.arange(24, dtype=torch.float32).reshape(2, 12) + + actual = model._prepare_aux_hidden_state(hidden_states, None) + expected = hidden_states.unflatten(-1, (4, -1)).mean(dim=-2) + + torch.testing.assert_close(actual, expected) + assert actual.shape == (2, 3) + + +def test_glm5_next_eagle_capture_without_residual(): + model = Glm5NextModel.__new__(Glm5NextModel) + nn.Module.__init__(model) + model.config = SimpleNamespace(mhc=False, hc_mult=1) + model.dflash_capture = False + + hidden_states = torch.arange(24, dtype=torch.float32).reshape(2, 12) + + actual = model._prepare_aux_hidden_state(hidden_states, None) + + torch.testing.assert_close(actual, hidden_states) + + def test_glm5_next_dflash_maps_target_layers_to_capture_points(): model = Glm5NextForConditionalGeneration.__new__(Glm5NextForConditionalGeneration) nn.Module.__init__(model) @@ -51,3 +86,7 @@ def test_glm5_next_dflash_maps_target_layers_to_capture_points(): assert model.capture_aux_hidden_states assert model.model.dflash_capture assert model.model.layers_to_capture == [6, 15, 25, 34, 43] + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) From aa8c950a3df62b6642c4ea60a93a5e3eb1a1450e Mon Sep 17 00:00:00 2001 From: andyluo7 <43718156+andyluo7@users.noreply.github.com> Date: Thu, 27 Aug 2026 20:51:00 -0700 Subject: [PATCH 08/44] [AMD] Enable GLM-5.3-Flash on gfx942 and gfx950 (#36607) --- .../jit/csrc/dsa/kpool_topk_transform.cuh | 8 + .../ops/attention/dsa/tilelang_kernel.py | 70 +++-- .../ops/attention/dsa/transform_index.py | 77 +++++- python/sglang/kernels/ops/layernorm/mhc.py | 144 +++++++++- .../layers/attention/dsa/dsa_indexer_kpool.py | 87 +++++- .../layers/attention/dsa/kpool_fp8_index.py | 196 +++++++++++-- python/sglang/srt/layers/communicator_mhc.py | 30 +- .../moe/moe_runner/triton_utils/fused_moe.py | 10 + python/sglang/srt/layers/quantization/fp8.py | 14 +- .../srt/layers/quantization/quark/quark.py | 89 +++++- .../srt/layers/quantization/quark/utils.py | 6 + .../forward_mha_rocm.py | 6 +- python/sglang/srt/models/glm5_next.py | 83 +++++- python/sglang/srt/server_args.py | 21 +- .../ops/attention/test_dsa_transform_index.py | 26 +- .../kernels/test_dsa_kpool_multi_pool.py | 257 +++++++++++++++++- .../layers/moe/test_fused_moe_swiglu_clamp.py | 38 +++ .../test_fp8_moe_runner_ownership.py | 84 +++++- .../layers/quantization/test_quark_config.py | 114 ++++++++ .../layers/quantization/test_quark_utils.py | 16 +- .../layers/test_dsa_indexer_kpool_backend.py | 196 +++++++++++++ .../unit/layers/test_mhc_deep_gemm_gate.py | 89 ++++++ .../mem_cache/test_glm5_next_hybrid_pool.py | 121 +++++++++ .../unit/models/test_glm5_next_aiter_mhc.py | 238 ++++++++++++++++ .../models/test_glm5_next_weight_loading.py | 54 ++++ .../unit/models/test_nope_mha_k_cast.py | 20 +- .../test_shared_experts_fusion_gates.py | 56 ++++ .../unit/server_args/test_server_args.py | 68 +++++ 28 files changed, 2107 insertions(+), 111 deletions(-) create mode 100644 test/registered/unit/layers/moe/test_fused_moe_swiglu_clamp.py create mode 100644 test/registered/unit/layers/test_dsa_indexer_kpool_backend.py create mode 100644 test/registered/unit/layers/test_mhc_deep_gemm_gate.py create mode 100644 test/registered/unit/mem_cache/test_glm5_next_hybrid_pool.py create mode 100644 test/registered/unit/models/test_glm5_next_aiter_mhc.py create mode 100644 test/registered/unit/models/test_glm5_next_weight_loading.py diff --git a/python/sglang/kernels/jit/csrc/dsa/kpool_topk_transform.cuh b/python/sglang/kernels/jit/csrc/dsa/kpool_topk_transform.cuh index 2accb0f699628..f49d4ac0d4af9 100644 --- a/python/sglang/kernels/jit/csrc/dsa/kpool_topk_transform.cuh +++ b/python/sglang/kernels/jit/csrc/dsa/kpool_topk_transform.cuh @@ -19,7 +19,11 @@ #include #include #include +#if defined(__HIP_PLATFORM_AMD__) +#include +#else #include +#endif namespace sglang { namespace { @@ -309,7 +313,11 @@ void setup_kernel_smem_once(host::DebugInfo where = {}) { [[maybe_unused]] static const auto result = [] { const auto fptr = std::bit_cast(f); +#if defined(__HIP_PLATFORM_AMD__) + return ::hipFuncSetAttribute(fptr, ::hipFuncAttributeMaxDynamicSharedMemorySize, kMaxDynamicSMEM); +#else return ::cudaFuncSetAttribute(fptr, ::cudaFuncAttributeMaxDynamicSharedMemorySize, kMaxDynamicSMEM); +#endif }(); host::RuntimeDeviceCheck(result, where); } diff --git a/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py b/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py index 2c1eff2e2e3c9..a49852cb0219b 100644 --- a/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py +++ b/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py @@ -895,13 +895,16 @@ def main( with T.Kernel(seq_len * REPLICATE_H, N_GROUPS, threads=threads) as (bx, by): if _q_in_shared: Q_buf = T.alloc_shared([H_per_block, D], dtype) - Q_tail_buf = T.alloc_shared([H_per_block, D_tail], dtype) + if D_tail > 0: + Q_tail_buf = T.alloc_shared([H_per_block, D_tail], dtype) else: Q_buf = T.alloc_fragment([H_per_block, D], dtype) - Q_tail_buf = T.alloc_fragment([H_per_block, D_tail], dtype) + if D_tail > 0: + Q_tail_buf = T.alloc_fragment([H_per_block, D_tail], dtype) KV_shared = T.alloc_shared([BI, D], dtype) - K_tail_shared = T.alloc_shared([BI, D_tail], dtype) + if D_tail > 0: + K_tail_shared = T.alloc_shared([BI, D_tail], dtype) S_shared = T.alloc_shared([H_per_block, BI], dtype) mask = T.alloc_fragment([BI], T.bool) @@ -924,7 +927,8 @@ def main( H1 = H0 + H_per_block T.copy(Q[b_i, s_i, H0:H1, :D], Q_buf) - T.copy(Q[b_i, s_i, H0:H1, D:], Q_tail_buf) + if D_tail > 0: + T.copy(Q[b_i, s_i, H0:H1, D:], Q_tail_buf) for k_i in T.Pipelined(inner_iter, num_stages=num_stages): topk_block_i = group_i * inner_iter + k_i @@ -936,11 +940,12 @@ def main( KV_shared[bi_i, d_i] = KV[ b_i, T.if_then_else(idx >= 0, idx, 0), g_i, d_i ] - for bi_i, d_i in T.Parallel(BI, D_tail): - idx = Indices[b_i, s_i, g_i, topk_block_i * BI + bi_i] - K_tail_shared[bi_i, d_i] = KV[ - b_i, T.if_then_else(idx >= 0, idx, 0), g_i, D + d_i - ] + if D_tail > 0: + for bi_i, d_i in T.Parallel(BI, D_tail): + idx = Indices[b_i, s_i, g_i, topk_block_i * BI + bi_i] + K_tail_shared[bi_i, d_i] = KV[ + b_i, T.if_then_else(idx >= 0, idx, 0), g_i, D + d_i + ] for h_i, bi_i in T.Parallel(H_per_block, BI): acc_s[h_i, bi_i] = T.if_then_else( @@ -954,13 +959,14 @@ def main( transpose_B=True, policy=T.GemmWarpPolicy.FullCol, ) - T.gemm( - Q_tail_buf, - K_tail_shared, - acc_s, - transpose_B=True, - policy=T.GemmWarpPolicy.FullCol, - ) + if D_tail > 0: + T.gemm( + Q_tail_buf, + K_tail_shared, + acc_s, + transpose_B=True, + policy=T.GemmWarpPolicy.FullCol, + ) T.copy(m_i, m_i_prev) T.reduce_max(acc_s, m_i, dim=1, clear=False) @@ -1171,8 +1177,9 @@ def main( kv_tile1 = T.alloc_shared([BI, group_size], fp8_dtype) kv_tile2 = T.alloc_shared([BI, group_size], fp8_dtype) kv_tile3 = T.alloc_shared([BI, group_size], fp8_dtype) - q_tail_buf = T.alloc_shared([h_per_block, d_tail], fp8_dtype) - k_tail_shared = T.alloc_shared([BI, d_tail], fp8_dtype) + if d_tail > 0: + q_tail_buf = T.alloc_shared([h_per_block, d_tail], fp8_dtype) + k_tail_shared = T.alloc_shared([BI, d_tail], fp8_dtype) s_fp8_shared = T.alloc_shared([h_per_block, BI], fp8_dtype) page_idx_shared = T.alloc_shared([BI], T.int32) @@ -1199,7 +1206,8 @@ def main( T.fill(sumexp, 0) T.fill(m_i, -(2**30)) - T.copy(q_fp8[b_i, s_i, H0:H1, d_v:], q_tail_buf) + if d_tail > 0: + T.copy(q_fp8[b_i, s_i, H0:H1, d_v:], q_tail_buf) T.copy(q_fp8[b_i, s_i, H0:H1, 0 * group_size : 1 * group_size], q_tile0) T.copy(q_fp8[b_i, s_i, H0:H1, 1 * group_size : 2 * group_size], q_tile1) T.copy(q_fp8[b_i, s_i, H0:H1, 2 * group_size : 3 * group_size], q_tile2) @@ -1221,9 +1229,12 @@ def main( kv_tile2[bi_i, j] = kv_fp8[b_i, page, g_i, 2 * group_size + j] kv_tile3[bi_i, j] = kv_fp8[b_i, page, g_i, 3 * group_size + j] - for bi_i, j in T.Parallel(BI, d_tail): - page = page_idx_shared[bi_i] - k_tail_shared[bi_i, j] = kv_fp8[b_i, page, g_i, rope_offset_fp8 + j] + if d_tail > 0: + for bi_i, j in T.Parallel(BI, d_tail): + page = page_idx_shared[bi_i] + k_tail_shared[bi_i, j] = kv_fp8[ + b_i, page, g_i, rope_offset_fp8 + j + ] for h_i, bi_i in T.Parallel(h_per_block, BI): acc_s[h_i, bi_i] = T.if_then_else( @@ -1240,13 +1251,14 @@ def main( T.gemm(q_tile3, kv_tile3, acc_tile, transpose_B=True, clear_accum=True) for h_i, bi_i in T.Parallel(h_per_block, BI): acc_s[h_i, bi_i] += acc_tile[h_i, bi_i] - T.gemm( - q_tail_buf, - k_tail_shared, - acc_s, - transpose_B=True, - policy=T.GemmWarpPolicy.FullCol, - ) + if d_tail > 0: + T.gemm( + q_tail_buf, + k_tail_shared, + acc_s, + transpose_B=True, + policy=T.GemmWarpPolicy.FullCol, + ) T.copy(m_i, m_i_prev) T.reduce_max(acc_s, m_i, dim=1, clear=False) diff --git a/python/sglang/kernels/ops/attention/dsa/transform_index.py b/python/sglang/kernels/ops/attention/dsa/transform_index.py index 8fbfa190f5b97..f30c357c06b77 100644 --- a/python/sglang/kernels/ops/attention/dsa/transform_index.py +++ b/python/sglang/kernels/ops/attention/dsa/transform_index.py @@ -116,6 +116,43 @@ def transform_index_page_table_decode_kernel( tl.store(result_ptr + offset, -1, mask=~mask) +@triton.jit +def transform_index_page_table_decode_tiled_kernel( + page_table_ptr: torch.Tensor, + topk_indices_ptr: torch.Tensor, + result_ptr: torch.Tensor, + page_table_row_stride: tl.constexpr, + topk_indices_stride_0: tl.constexpr, + topk_indices_stride_1: tl.constexpr, + result_stride_0: tl.constexpr, + result_stride_1: tl.constexpr, + TOPK: tl.constexpr, + BLOCK_TOPK: tl.constexpr, +): + req_id = tl.program_id(0) + topk_offsets = tl.program_id(1) * BLOCK_TOPK + tl.arange(0, BLOCK_TOPK) + mask = topk_offsets < TOPK + + loaded_topk_indices = tl.load( + topk_indices_ptr + + req_id * topk_indices_stride_0 + + topk_offsets * topk_indices_stride_1, + mask=mask, + other=-1, + ) + valid_topk_mask = mask & (loaded_topk_indices >= 0) + loaded_kv_indices = tl.load( + page_table_ptr + req_id * page_table_row_stride + loaded_topk_indices, + mask=valid_topk_mask, + other=-1, + ) + tl.store( + result_ptr + req_id * result_stride_0 + topk_offsets * result_stride_1, + loaded_kv_indices, + mask=mask, + ) + + @triton.jit def transform_index_page_table_prefill_kernel( page_table_ptr: torch.Tensor, @@ -191,19 +228,38 @@ def transform_index_page_table_decode_fast( """ assert page_size == 1 assert page_table.shape[0] == topk_indices.shape[0] - assert topk_indices.shape[1] == 2048 qo_len = topk_indices.shape[0] if result is None: result = torch.empty_like(topk_indices, dtype=torch.int32) - # Launch triton kernel - grid = (qo_len,) - transform_index_page_table_decode_kernel[grid]( - page_table, - topk_indices, - result, - page_size, - page_table_row_stride=page_table.stride(0), - ) + topk = topk_indices.shape[1] + if topk == 2048: + # Preserve the existing single-program fast path for the standard DSA + # width. KPool can append a live partial-pool tail, which is handled by + # the generic tiled path below without changing this common path. + transform_index_page_table_decode_kernel[(qo_len,)]( + page_table, + topk_indices, + result, + page_size, + page_table_row_stride=page_table.stride(0), + ) + else: + block_topk = 256 + transform_index_page_table_decode_tiled_kernel[ + (qo_len, triton.cdiv(topk, block_topk)) + ]( + page_table, + topk_indices, + result, + page_table.stride(0), + topk_indices.stride(0), + topk_indices.stride(1), + result.stride(0), + result.stride(1), + TOPK=topk, + BLOCK_TOPK=block_topk, + num_warps=4, + ) return result @@ -217,7 +273,6 @@ def transform_index_page_table_prefill_fast( cu_seqlens_q: Optional[torch.Tensor] = None, ) -> torch.Tensor: assert page_size == 1 - assert topk_indices.shape[1] == 2048 real_num_tokens = sum(extend_lens_cpu) result = _allocate_prefill_result(topk_indices, real_num_tokens, output_num_tokens) if real_num_tokens == 0: diff --git a/python/sglang/kernels/ops/layernorm/mhc.py b/python/sglang/kernels/ops/layernorm/mhc.py index b4a00c4419f7e..870875b108c62 100644 --- a/python/sglang/kernels/ops/layernorm/mhc.py +++ b/python/sglang/kernels/ops/layernorm/mhc.py @@ -16,9 +16,99 @@ from sglang.srt.layers.attention.dsa.utils import is_dsa_prefill_cp_round_robin_split from sglang.srt.layers.dp_attention import is_allocation_symmetric from sglang.srt.layers.utils.common import strict_contiguous +from sglang.srt.utils import is_gfx95_supported, is_hip +from sglang.srt.utils.common import get_bool_env_var logger = logging.getLogger(__name__) +_AITER_MHC_RUNTIME_DISABLED = False +_AITER_MHC_IMPORT_WARNED = False +_AITER_MHC_ACTIVE_LOGGED = False + + +def _use_aiter_mhc() -> bool: + return ( + not _AITER_MHC_RUNTIME_DISABLED + and is_hip() + and is_gfx95_supported() + and get_bool_env_var("SGLANG_USE_AITER") + ) + + +def _try_aiter_mhc_pre( + residual: torch.Tensor, + fn: torch.Tensor, + hc_scale: torch.Tensor, + hc_base: torch.Tensor, + rms_eps: float, + hc_pre_eps: float, + hc_sinkhorn_eps: float, + hc_post_mult_value: float, + sinkhorn_repeat: int, + norm_weight: torch.Tensor | None, + norm_eps: float | None, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor] | None: + global _AITER_MHC_RUNTIME_DISABLED, _AITER_MHC_IMPORT_WARNED + global _AITER_MHC_ACTIVE_LOGGED + + try: + from aiter.ops.mhc import mhc_pre as aiter_mhc_pre + except Exception as err: + if not _AITER_MHC_IMPORT_WARNED: + logger.warning("AITER mHC pre is unavailable, falling back: %s", err) + _AITER_MHC_IMPORT_WARNED = True + _AITER_MHC_RUNTIME_DISABLED = True + return None + + kwargs = {} + if norm_weight is not None: + kwargs["norm_weight"] = norm_weight + kwargs["norm_eps"] = norm_eps if norm_eps is not None else rms_eps + + try: + result = aiter_mhc_pre( + residual, + fn, + hc_scale, + hc_base, + rms_eps, + hc_pre_eps, + hc_sinkhorn_eps, + hc_post_mult_value, + sinkhorn_repeat, + **kwargs, + ) + except Exception as err: + logger.warning("AITER mHC pre failed, disabling fast path: %s", err) + _AITER_MHC_RUNTIME_DISABLED = True + return None + + if not _AITER_MHC_ACTIVE_LOGGED: + logger.info("Using AITER gfx950 mHC pre/post kernels") + _AITER_MHC_ACTIVE_LOGGED = True + return result + + +def _try_aiter_mhc_post( + x: torch.Tensor, + residual: torch.Tensor, + post_layer_mix: torch.Tensor, + comb_res_mix: torch.Tensor, +) -> torch.Tensor | None: + global _AITER_MHC_RUNTIME_DISABLED + + try: + from aiter.ops.mhc import mhc_post as aiter_mhc_post + + out = torch.empty_like(residual) + aiter_mhc_post(out, x, residual, post_layer_mix, comb_res_mix) + return out + except Exception as err: + logger.warning("AITER mHC post failed, disabling fast path: %s", err) + _AITER_MHC_RUNTIME_DISABLED = True + return None + + # This module is imported during model-registry discovery. Do not import the real # TileLang package here: it loads native CUDA stubs. The proxy below lets # module-level @tilelang.jit declarations parse, then imports and applies real @@ -116,6 +206,24 @@ def __getattr__(self, name): tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True, } + +def _use_deep_gemm_hc_prenorm() -> bool: + if not envs.SGLANG_OPT_DEEPGEMM_HC_PRENORM.get(): + return False + + from sglang.srt.layers.deep_gemm_wrapper.configurer import ENABLE_JIT_DEEPGEMM + + return ENABLE_JIT_DEEPGEMM + + +def _use_tilelang_mhc_pre() -> bool: + return envs.SGLANG_OPT_USE_TILELANG_MHC_PRE.get() and not is_hip() + + +def _use_tilelang_mhc_post() -> bool: + return envs.SGLANG_OPT_USE_TILELANG_MHC_POST.get() and not is_hip() + + FP8 = "float8_e4m3" BF16 = "bfloat16" FP32 = "float32" @@ -835,7 +943,7 @@ def mhc_pre( num_tokens, hidden_size, dtype=torch.bfloat16, device=residual.device ) - if envs.SGLANG_OPT_DEEPGEMM_HC_PRENORM.get(): + if _use_deep_gemm_hc_prenorm(): n_splits = _compute_num_split_for_mhc_pre(num_tokens, hc_hidden_size) gemm_out_mul = torch.empty( @@ -1447,7 +1555,7 @@ def mhc_fused_post_pre( hidden_size, ) - if envs.SGLANG_OPT_DEEPGEMM_HC_PRENORM.get(): + if _use_deep_gemm_hc_prenorm(): import deep_gemm deep_gemm.tf32_hc_prenorm_gemm( @@ -1659,7 +1767,25 @@ def _mhc_pre_dispatch( Returns (post_mix=(s,n,1), comb_mix=(s,n,n), layer_input=(s,h), norm_fused). """ assert residual.dim() == 3, f"residual must be (s, n, h); got {residual.shape}" - if not envs.SGLANG_OPT_USE_TILELANG_MHC_PRE.get(): + if _use_aiter_mhc(): + result = _try_aiter_mhc_pre( + residual=residual, + fn=fn, + hc_scale=hc_scale, + hc_base=hc_base, + rms_eps=rms_eps, + hc_pre_eps=hc_pre_eps, + hc_sinkhorn_eps=hc_sinkhorn_eps, + hc_post_mult_value=hc_post_mult_value, + sinkhorn_repeat=sinkhorn_repeat, + norm_weight=norm_weight, + norm_eps=norm_eps, + ) + if result is not None: + post_mix, comb_mix, layer_input = result + return post_mix, comb_mix, layer_input, norm_weight is not None + + if not _use_tilelang_mhc_pre(): post_mix, comb_mix, layer_input = _mhc_pre_torch( residual=residual, fn=fn, @@ -1698,7 +1824,17 @@ def _mhc_post_dispatch( ) -> torch.Tensor: assert x.dim() == 2 and residual.dim() == 3 assert post_layer_mix.dim() == 3 and comb_res_mix.dim() == 3 - if not envs.SGLANG_OPT_USE_TILELANG_MHC_POST.get(): + if _use_aiter_mhc(): + result = _try_aiter_mhc_post( + x=x, + residual=residual, + post_layer_mix=post_layer_mix, + comb_res_mix=comb_res_mix, + ) + if result is not None: + return result + + if not _use_tilelang_mhc_post(): return _mhc_post_torch(x, residual, post_layer_mix, comb_res_mix) return mhc_post(x, residual, post_layer_mix, comb_res_mix) diff --git a/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py b/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py index 2cc6a6c477cde..b466a8b5b3334 100644 --- a/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py +++ b/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py @@ -30,6 +30,7 @@ from sglang.srt.environ import envs from sglang.srt.layers import deep_gemm_wrapper from sglang.srt.layers.attention.dsa.utils import ( + aiter_can_use_preshuffle_paged_mqa, cp_zigzag_full_plan_rows, dsa_use_prefill_cp, is_dsa_enable_prefill_cp, @@ -165,6 +166,39 @@ def _get_logits_head_gate(self, x: torch.Tensor, q_scale: torch.Tensor): weights = weights.unsqueeze(-1) * q_scale * self.softmax_scale return weights + @staticmethod + def _fp8_mqa_logits( + q_fp8: torch.Tensor, + k_fp8: torch.Tensor, + k_scale: torch.Tensor, + weights: torch.Tensor, + starts: torch.Tensor, + ends: torch.Tensor, + *, + clean_logits: bool, + ) -> torch.Tensor: + if is_hip(): + from aiter.ops.triton.fp8_mqa_logits import fp8_mqa_logits + + return fp8_mqa_logits( + q_fp8, + k_fp8, + k_scale, + weights, + starts, + ends, + clean_logits=clean_logits, + ) + + return deep_gemm.fp8_mqa_logits( + q_fp8, + (k_fp8, k_scale), + weights, + starts, + ends, + clean_logits=clean_logits, + ) + @staticmethod def _cp_gather_concat( tensors: List[torch.Tensor], @@ -831,7 +865,7 @@ def _should_use_tilelang_paged_mqa_logits(q_fp8: torch.Tensor) -> bool: if not is_cuda(): return False arch_major, _ = torch.cuda.get_device_capability(q_fp8.device) - num_heads = q_fp8.shape[2] + num_heads = q_fp8.shape[1] return arch_major == 9 and num_heads not in (32, 64) def _get_topk_paged( @@ -869,7 +903,6 @@ def _get_topk_paged( if n_real < num_q_padded: q_fp8 = q_fp8[:n_real] weights = weights[:n_real] - q_fp8 = q_fp8.unsqueeze(1) # the next_n dim is 1 now assert len(kv_cache_fp8.shape) == 2 block_kv = 64 num_heads_kv = 1 @@ -879,7 +912,11 @@ def _get_topk_paged( ) assert len(weights.shape) == 3 weights = weights.squeeze(2) - use_tilelang_paged_mqa = self._should_use_tilelang_paged_mqa_logits(q_fp8) + use_aiter_paged_mqa = is_hip() + use_tilelang_paged_mqa = ( + not use_aiter_paged_mqa + and self._should_use_tilelang_paged_mqa_logits(q_fp8) + ) pool_seqlens, pool_context_lens, pool_block_tables, pool_schedule_metadata = ( self._get_kpool_decode_metadata( @@ -887,17 +924,36 @@ def _get_topk_paged( block_tables, seqlens_32, blocksize, - build_schedule_metadata=not use_tilelang_paged_mqa, + build_schedule_metadata=not ( + use_aiter_paged_mqa or use_tilelang_paged_mqa + ), ) ) pool_max_seq_len = pool_block_tables.shape[1] * blocksize - if use_tilelang_paged_mqa: + if use_aiter_paged_mqa: + if not aiter_can_use_preshuffle_paged_mqa(): + raise RuntimeError( + "ROCm kpool indexer requires the AITER preshuffle paged-MQA kernel" + ) + from sglang.kernels.ops.attention.dsa import aiter_paged_mqa_logits + + logits = aiter_paged_mqa_logits( + q_fp8, + kv_cache_fp8, + weights, + pool_seqlens, + pool_block_tables, + pool_max_seq_len, + preshuffle=True, + kv_block_size=block_kv, + ) + elif use_tilelang_paged_mqa: from sglang.kernels.ops.attention.dsa.tilelang_kernel import ( tilelang_fp8_paged_mqa_logits, ) logits = tilelang_fp8_paged_mqa_logits( - q_fp8, + q_fp8.unsqueeze(1), kv_cache_fp8, weights, pool_seqlens, @@ -908,7 +964,7 @@ def _get_topk_paged( ) else: logits = deep_gemm.fp8_paged_mqa_logits( - q_fp8, + q_fp8.unsqueeze(1), kv_cache_fp8, weights, pool_context_lens, @@ -1001,9 +1057,10 @@ def _get_topk_ragged_kpool_plan( scale_out=k_scale, ) k_fp8 = k_u8.view(torch.float8_e4m3fn) - logits = deep_gemm.fp8_mqa_logits( + logits = self._fp8_mqa_logits( q_fp8[:n_real].contiguous(), - (k_fp8.contiguous(), k_scale.contiguous()), + k_fp8.contiguous(), + k_scale.contiguous(), weights[:n_real].contiguous(), ks_per_q, ke_per_q, @@ -1115,9 +1172,10 @@ def _get_topk_ragged_with_cp( ke = torch.div(tail_tokens, pool_size, rounding_mode="floor").to( torch.int32 ) - logits = deep_gemm.fp8_mqa_logits( + logits = self._fp8_mqa_logits( q_work, - (k_fp8.contiguous(), k_scale.contiguous()), + k_fp8.contiguous(), + k_scale.contiguous(), weights_work, ks, ke, @@ -1349,9 +1407,10 @@ def _get_topk_ragged_kpool( and zero_starts_by_batch[i] is not None else torch.zeros((q_len,), dtype=torch.int32, device=q_fp8.device) ) - local_logits = deep_gemm.fp8_mqa_logits( + local_logits = self._fp8_mqa_logits( q_fp8[q_slice].contiguous(), - (k_fp8.contiguous(), k_scale.contiguous()), + k_fp8.contiguous(), + k_scale.contiguous(), weights[q_slice].contiguous(), row_starts, local_pool_lens, @@ -1697,7 +1756,7 @@ def forward_cuda( if weights is None: weights = self._get_logits_head_gate(x, q_scale) - if is_cuda(): + if is_cuda() or is_hip(): if ( forward_batch.forward_mode.is_decode_or_idle() or forward_batch.forward_mode.is_target_verify() diff --git a/python/sglang/srt/layers/attention/dsa/kpool_fp8_index.py b/python/sglang/srt/layers/attention/dsa/kpool_fp8_index.py index 6d290a091c528..9a0b8fe3ba8bc 100644 --- a/python/sglang/srt/layers/attention/dsa/kpool_fp8_index.py +++ b/python/sglang/srt/layers/attention/dsa/kpool_fp8_index.py @@ -4,11 +4,47 @@ import triton import triton.language as tl +from sglang.srt.layers.attention.dsa.utils import ( + INDEXER_K_CACHE_PRESHUFFLE_TILE, + aiter_can_use_preshuffle_paged_mqa, +) +from sglang.srt.utils import is_hip + BLOCK_SIZE_K = 64 INDEX_HEAD_DIM = 128 KPOOL_SCORE_DTYPES = (torch.float16, torch.bfloat16, torch.float32) +def _preshuffle_tile() -> int: + return ( + INDEXER_K_CACHE_PRESHUFFLE_TILE if aiter_can_use_preshuffle_paged_mqa() else 0 + ) + + +@triton.jit +def _kpool_cache_k_offsets( + page, + slot, + cols, + PAGE_BYTES: tl.constexpr, + HEAD_DIM: tl.constexpr, + PRESHUFFLE_TILE: tl.constexpr, +): + if PRESHUFFLE_TILE: + token_tile_id = slot // PRESHUFFLE_TILE + token_in_tile = slot % PRESHUFFLE_TILE + col_tile_id = cols // PRESHUFFLE_TILE + col_in_tile = cols % PRESHUFFLE_TILE + return ( + page * PAGE_BYTES + + token_tile_id * (PRESHUFFLE_TILE * HEAD_DIM) + + col_tile_id * (PRESHUFFLE_TILE * PRESHUFFLE_TILE) + + token_in_tile * PRESHUFFLE_TILE + + col_in_tile + ) + return page * PAGE_BYTES + slot * HEAD_DIM + cols + + def kpool_max_closed_pools(num_draft_tokens: int, pool_size: int) -> int: """Return the most pools an N-token write can close at any start offset.""" return (num_draft_tokens + pool_size - 1) // pool_size @@ -68,6 +104,7 @@ def gather_index_k_scale_prefix_into( BUF_NUMEL_PER_PAGE=buf.shape[1], HEAD_DIM=INDEX_HEAD_DIM, S_OFFSET_NBYTES_IN_PAGE=pool.page_size * INDEX_HEAD_DIM, + PRESHUFFLE_TILE=_preshuffle_tile(), BLOCK_D=triton.next_power_of_2(INDEX_HEAD_DIM), ) @@ -83,6 +120,7 @@ def _gather_index_k_scale_prefix_into_kernel( BUF_NUMEL_PER_PAGE: tl.constexpr, HEAD_DIM: tl.constexpr, S_OFFSET_NBYTES_IN_PAGE: tl.constexpr, + PRESHUFFLE_TILE: tl.constexpr, BLOCK_D: tl.constexpr, ): token_id = tl.program_id(0) @@ -92,7 +130,14 @@ def _gather_index_k_scale_prefix_into_kernel( offs = tl.arange(0, BLOCK_D) mask = offs < HEAD_DIM - src_k_offsets = page * BUF_NUMEL_PER_PAGE + token_offset_in_page * HEAD_DIM + offs + src_k_offsets = _kpool_cache_k_offsets( + page, + token_offset_in_page, + offs, + BUF_NUMEL_PER_PAGE, + HEAD_DIM, + PRESHUFFLE_TILE, + ) dst_k_offsets = token_id * HEAD_DIM + offs k = tl.load(buf_u8_ptr + src_k_offsets, mask=mask) tl.store(k_out_ptr + dst_k_offsets, k, mask=mask) @@ -591,6 +636,23 @@ def topk_from_pooled_history_logits( f"is disabled. Got device={logits.device}, dtype={logits.dtype}." ) + # The JIT fused path supports the dedicated 128..512 group-topk kernels on + # both CUDA and HIP. Keep the legacy HIP fallback only for the separate + # 2048-group AOT path, which is not covered by the JIT implementation. + if is_hip() and group_topk == 2048: + return _topk_from_pooled_history_logits_unfused( + logits=logits, + group_lengths=group_lengths, + pool_size=pool_size, + topk=topk, + page_table=page_table, + topk_offsets=topk_offsets, + seq_lens=seq_lens, + row_starts=row_starts, + out_rows=out_rows, + page_table_row_index=page_table_row_index, + ) + if group_topk in (128, 160, 192, 224, 256, 512): from sglang.kernels.ops.moe.kpool_topk_transform import ( fast_kpool_topk_transform_fused, @@ -663,6 +725,66 @@ def topk_from_pooled_history_logits( return padded +def _topk_from_pooled_history_logits_unfused( + logits: torch.Tensor, + group_lengths: torch.Tensor, + pool_size: int, + topk: int, + page_table: torch.Tensor | None = None, + topk_offsets: torch.Tensor | None = None, + seq_lens: torch.Tensor | None = None, + row_starts: torch.Tensor | None = None, + out_rows: int | None = None, + page_table_row_index: torch.Tensor | None = None, +) -> torch.Tensor: + from sglang.srt.layers.attention.dsa.dsa_topk_backend import _topk_unfused + + group_topk = history_group_budget_for_topk(topk, pool_size) + selected_groups = _topk_unfused( + logits, + group_lengths, + group_topk, + row_starts=row_starts, + topk_op=torch.topk, + topk_op_kwargs={"dim": -1}, + ) + group_valid = selected_groups >= 0 + + page_table_for_rows = page_table + if page_table_row_index is not None: + assert page_table is not None + page_table_for_rows = page_table.index_select( + 0, page_table_row_index.to(dtype=torch.int64, device=page_table.device) + ) + + expanded = expand_pooled_groups_to_topk( + selected_groups.contiguous(), + group_valid, + topk=topk, + pool_size=pool_size, + page_table=page_table_for_rows, + topk_offsets=topk_offsets, + ) + if seq_lens is None: + result = expanded + else: + result = append_kpool_tail_to_topk( + expanded, + seq_lens=seq_lens, + pool_lens=group_lengths, + pool_size=pool_size, + page_table=page_table_for_rows, + topk_offsets=topk_offsets, + ) + if out_rows is None or out_rows == result.shape[0]: + return result + padded = torch.full( + (out_rows, result.shape[1]), -1, dtype=result.dtype, device=result.device + ) + padded[: result.shape[0]] = result + return padded + + def kpool_softmax_rotate_write_cache( pool, buf: torch.Tensor, @@ -747,6 +869,7 @@ def kpool_softmax_rotate_write_cache( POOL_SIZE=slot_k.shape[1], HEAD_DIM=slot_k.shape[2], S_OFFSET_NBYTES_IN_PAGE=pool.page_size * pool.index_head_dim, + PRESHUFFLE_TILE=_preshuffle_tile(), ROUND_SCALE=round_scale, HAS_WRITE_MASK=has_write_mask, RETURN_COMPRESSED=return_compressed, @@ -842,6 +965,7 @@ def kpool_decode_update_and_maybe_write_cache( HEAD_DIM=tail_k.shape[2], BLOCK_TABLE_COLS=block_tables.shape[1], S_OFFSET_NBYTES_IN_PAGE=pool.slots_per_page * pool.index_head_dim, + PRESHUFFLE_TILE=_preshuffle_tile(), ROUND_SCALE=round_scale, BLOCK_D=triton.next_power_of_2(tail_k.shape[2]), SLOTS_PER_PAGE=pool.slots_per_page, @@ -891,6 +1015,7 @@ def _kpool_softmax_rotate_write_cache_kernel( POOL_SIZE: tl.constexpr, HEAD_DIM: tl.constexpr, S_OFFSET_NBYTES_IN_PAGE: tl.constexpr, + PRESHUFFLE_TILE: tl.constexpr, ROUND_SCALE: tl.constexpr, HAS_WRITE_MASK: tl.constexpr, RETURN_COMPRESSED: tl.constexpr, @@ -966,10 +1091,13 @@ def _kpool_softmax_rotate_write_cache_kernel( loc = tl.load(loc_ptr + row, mask=do_write, other=0) loc_page_index = loc // PAGE_SIZE loc_token_offset_in_page = loc % PAGE_SIZE - out_k_offsets = ( - loc_page_index * BUF_NUMEL_PER_PAGE - + loc_token_offset_in_page * HEAD_DIM - + offs + out_k_offsets = _kpool_cache_k_offsets( + loc_page_index, + loc_token_offset_in_page, + offs, + BUF_NUMEL_PER_PAGE, + HEAD_DIM, + PRESHUFFLE_TILE, ) out_s_offset = ( loc_page_index * BUF_NUMEL_PER_PAGE // 4 @@ -1019,6 +1147,7 @@ def _kpool_decode_update_and_maybe_write_cache_kernel( HEAD_DIM: tl.constexpr, BLOCK_TABLE_COLS: tl.constexpr, S_OFFSET_NBYTES_IN_PAGE: tl.constexpr, + PRESHUFFLE_TILE: tl.constexpr, ROUND_SCALE: tl.constexpr, BLOCK_D: tl.constexpr, SLOTS_PER_PAGE: tl.constexpr, @@ -1131,10 +1260,13 @@ def _kpool_decode_update_and_maybe_write_cache_kernel( ) loc_page_index = packed_page.to(tl.int64) loc_token_offset_in_page = pool_id % SLOTS_PER_PAGE - out_k_offsets = ( - loc_page_index * BUF_NUMEL_PER_PAGE - + loc_token_offset_in_page * HEAD_DIM - + offs + out_k_offsets = _kpool_cache_k_offsets( + loc_page_index, + loc_token_offset_in_page, + offs, + BUF_NUMEL_PER_PAGE, + HEAD_DIM, + PRESHUFFLE_TILE, ) out_s_offset = ( loc_page_index * BUF_NUMEL_PER_PAGE // 4 @@ -1194,6 +1326,7 @@ def _kpool_assemble_softmax_rotate_write_cache_kernel( TAIL_SIZE: tl.constexpr, HEAD_DIM: tl.constexpr, S_OFFSET_NBYTES_IN_PAGE: tl.constexpr, + PRESHUFFLE_TILE: tl.constexpr, ROUND_SCALE: tl.constexpr, HAS_WRITE_MASK: tl.constexpr, BLOCK_D: tl.constexpr, @@ -1241,8 +1374,13 @@ def _kpool_assemble_softmax_rotate_write_cache_kernel( loc = tl.load(loc_ptr + row) loc_page_index = loc // SLOTS_PER_PAGE loc_token_offset_in_page = loc % SLOTS_PER_PAGE - out_k_offsets = ( - loc_page_index * BUF_NUMEL_PER_PAGE + loc_token_offset_in_page * HEAD_DIM + offs + out_k_offsets = _kpool_cache_k_offsets( + loc_page_index, + loc_token_offset_in_page, + offs, + BUF_NUMEL_PER_PAGE, + HEAD_DIM, + PRESHUFFLE_TILE, ) out_s_offset = ( loc_page_index * BUF_NUMEL_PER_PAGE // 4 @@ -1313,6 +1451,7 @@ def kpool_assemble_softmax_rotate_write_cache( TAIL_SIZE=tail_k.shape[1], HEAD_DIM=INDEX_HEAD_DIM, S_OFFSET_NBYTES_IN_PAGE=slots_per_page * INDEX_HEAD_DIM, + PRESHUFFLE_TILE=_preshuffle_tile(), ROUND_SCALE=round_scale, HAS_WRITE_MASK=has_write_mask, BLOCK_D=triton.next_power_of_2(INDEX_HEAD_DIM), @@ -1410,6 +1549,7 @@ def _pack_pool_slots_to_payload_kernel( head_dim: tl.constexpr, page_bytes: tl.constexpr, scale_region_off: tl.constexpr, + PRESHUFFLE_TILE: tl.constexpr, BLOCK_D: tl.constexpr, ): row = tl.program_id(0) @@ -1420,7 +1560,14 @@ def _pack_pool_slots_to_payload_kernel( offs = tl.arange(0, BLOCK_D) mask = offs < head_dim - src = page_base + slot * head_dim + offs + src = _kpool_cache_k_offsets( + page, + slot, + offs, + page_bytes, + head_dim, + PRESHUFFLE_TILE, + ) val = tl.load(buf_ptr + src, mask=mask, other=0).to(tl.uint8) tl.store(payload_ptr + row * payload_bytes + offs, val, mask=mask) @@ -1443,6 +1590,7 @@ def _select_and_scatter_pool_slots_kernel( page_bytes: tl.constexpr, scale_region_off: tl.constexpr, n_total: tl.constexpr, + PRESHUFFLE_TILE: tl.constexpr, BLOCK_D: tl.constexpr, ): row = tl.program_id(0) @@ -1459,7 +1607,14 @@ def _select_and_scatter_pool_slots_kernel( offs = tl.arange(0, BLOCK_D) mask = offs < head_dim val = tl.load(recv_ptr + recv_row_base + offs, mask=mask, other=0).to(tl.uint8) - dst = page_base + slot * head_dim + offs + dst = _kpool_cache_k_offsets( + page, + slot, + offs, + page_bytes, + head_dim, + PRESHUFFLE_TILE, + ) tl.store(buf_ptr + dst, val, mask=mask) s_offs = tl.arange(0, 4) @@ -1501,6 +1656,7 @@ def all_gather_and_scatter_pool_slots( head_dim=head_dim, page_bytes=page_bytes, scale_region_off=scale_region_off, + PRESHUFFLE_TILE=_preshuffle_tile(), BLOCK_D=triton.next_power_of_2(head_dim), ) @@ -1523,6 +1679,7 @@ def all_gather_and_scatter_pool_slots( page_bytes=page_bytes, scale_region_off=scale_region_off, n_total=n_total, + PRESHUFFLE_TILE=_preshuffle_tile(), BLOCK_D=triton.next_power_of_2(head_dim), ) @@ -1556,6 +1713,7 @@ def _kpool_write_tail_and_maybe_compress_kernel( SLOTS_PER_PAGE: tl.constexpr, BUF_NUMEL_PER_PAGE: tl.constexpr, S_OFFSET_NBYTES_IN_PAGE: tl.constexpr, + PRESHUFFLE_TILE: tl.constexpr, ROUND_SCALE: tl.constexpr, HAS_EFFECTIVE_N: tl.constexpr, MAX_CLOSED_POOLS: tl.constexpr, @@ -1620,10 +1778,13 @@ def _kpool_write_tail_and_maybe_compress_kernel( loc = tl.load(write_loc_ptr + b * write_loc_stride_0 + p) loc_page_index = loc // SLOTS_PER_PAGE loc_token_offset_in_page = loc % SLOTS_PER_PAGE - out_k_offsets = ( - loc_page_index * BUF_NUMEL_PER_PAGE - + loc_token_offset_in_page * HEAD_DIM - + offs + out_k_offsets = _kpool_cache_k_offsets( + loc_page_index, + loc_token_offset_in_page, + offs, + BUF_NUMEL_PER_PAGE, + HEAD_DIM, + PRESHUFFLE_TILE, ) out_s_offset = ( loc_page_index * BUF_NUMEL_PER_PAGE // 4 @@ -1714,6 +1875,7 @@ def kpool_write_tail_and_maybe_compress( SLOTS_PER_PAGE=slots_per_page, BUF_NUMEL_PER_PAGE=buf.shape[1], S_OFFSET_NBYTES_IN_PAGE=slots_per_page * pool.index_head_dim, + PRESHUFFLE_TILE=_preshuffle_tile(), ROUND_SCALE=round_scale, HAS_EFFECTIVE_N=effective_n_per_batch is not None, MAX_CLOSED_POOLS=max_closed_pools, diff --git a/python/sglang/srt/layers/communicator_mhc.py b/python/sglang/srt/layers/communicator_mhc.py index b32952ae10a0d..228292dbfa6dd 100644 --- a/python/sglang/srt/layers/communicator_mhc.py +++ b/python/sglang/srt/layers/communicator_mhc.py @@ -86,6 +86,7 @@ class MHCState: hc_attn_pre: Callable hc_ffn_pre: Callable hc_post: Callable + hc_attn_to_mlp: Optional[Callable] = None h_res: Optional[torch.Tensor] = None h_post: Optional[torch.Tensor] = None @@ -108,9 +109,34 @@ def attn_split(self, hidden_states, out_norm: Optional[torch.nn.Module] = None): def attn_to_mlp( self, hidden_states, residual, out_norm: Optional[torch.nn.Module] = None ): + out_norm_weight, out_norm_eps = self._resolve_out_norm(out_norm) + if self.hc_attn_to_mlp is not None: + fused = self.hc_attn_to_mlp( + hidden_states, + residual, + self.h_res, + self.h_post, + out_norm_weight, + out_norm_eps, + ) + if fused is not None: + ( + hidden_states, + residual, + self.h_res, + self.h_post, + norm_fused, + ) = fused + if ( + out_norm is not None + and not norm_fused + and hidden_states.shape[0] != 0 + ): + hidden_states = out_norm(hidden_states) + return hidden_states, residual + hidden_states = self.hc_post(hidden_states, residual, self.h_res, self.h_post) residual = hidden_states - out_norm_weight, out_norm_eps = self._resolve_out_norm(out_norm) hidden_states, self.h_res, self.h_post, norm_fused = self.hc_ffn_pre( hidden_states, out_norm_weight, out_norm_eps ) @@ -412,6 +438,7 @@ def __init__( hc_attn_pre: Callable, hc_ffn_pre: Callable, hc_post: Callable, + hc_attn_to_mlp: Optional[Callable] = None, ): self.is_first_layer = is_first_layer self.mhc = MHCState( @@ -419,6 +446,7 @@ def __init__( hc_attn_pre=hc_attn_pre, hc_ffn_pre=hc_ffn_pre, hc_post=hc_post, + hc_attn_to_mlp=hc_attn_to_mlp, ) super().__init__( diff --git a/python/sglang/srt/layers/moe/moe_runner/triton_utils/fused_moe.py b/python/sglang/srt/layers/moe/moe_runner/triton_utils/fused_moe.py index f503fd1be1b64..cf1553eab4203 100644 --- a/python/sglang/srt/layers/moe/moe_runner/triton_utils/fused_moe.py +++ b/python/sglang/srt/layers/moe/moe_runner/triton_utils/fused_moe.py @@ -96,6 +96,12 @@ logger = logging.getLogger(__name__) +def _clamp_swiglu_inputs_(x: torch.Tensor, limit: float) -> None: + half = x.shape[-1] // 2 + x[..., :half].clamp_(max=limit) + x[..., half:].clamp_(min=-limit, max=limit) + + def _use_moe_sum_reduce_torch_compile(num_tokens: int) -> bool: return num_tokens <= 32 and not is_batch_invariant_mode_enabled() @@ -690,6 +696,10 @@ def _fused_moe_kernel_sequence( if filter_expert: swiglu_limit_for_triton = swiglu_limit + elif _is_hip: + # The fused clamp kernel is CUDA/XPU-only; apply its gate/up + # contract before the regular HIP silu_and_mul kernel. + _clamp_swiglu_inputs_(intermediate_cache1, swiglu_limit) else: assert ( _is_cuda or _is_xpu diff --git a/python/sglang/srt/layers/quantization/fp8.py b/python/sglang/srt/layers/quantization/fp8.py index be46c496058b9..60f751b2742c9 100644 --- a/python/sglang/srt/layers/quantization/fp8.py +++ b/python/sglang/srt/layers/quantization/fp8.py @@ -1574,8 +1574,7 @@ def process_weights_after_loading_block_quant(self, layer: Module) -> None: layer.w13_input_scale = None layer.w2_input_scale = None runner_is_aiter = ( - getattr(self, "runner", None) is not None - and self.runner.runner_backend.is_aiter() + self._owns_moe_runner and self.runner.runner_backend.is_aiter() ) if _use_aiter and runner_is_aiter: layer.w13_weight.data = shuffle_weight( @@ -1615,14 +1614,21 @@ def process_weights_after_loading_block_quant(self, layer: Module) -> None: w2_weight_scale, requires_grad=False ) layer.w2_input_scale = None - if _use_aiter: + runner_is_aiter = ( + self._owns_moe_runner and self.runner.runner_backend.is_aiter() + ) + if _use_aiter and runner_is_aiter: layer.w13_weight.data = shuffle_weight( layer.w13_weight.contiguous(), (16, 16) ) layer.w2_weight.data = shuffle_weight( layer.w2_weight.contiguous(), (16, 16) ) - elif _use_aiter: + elif ( + _use_aiter + and self._owns_moe_runner + and self.runner.runner_backend.is_aiter() + ): # Pre-shuffle weights t = shuffle_weight(layer.w13_weight, (16, 16)) layer.w13_weight.copy_(t) diff --git a/python/sglang/srt/layers/quantization/quark/quark.py b/python/sglang/srt/layers/quantization/quark/quark.py index 60db3f52b59e0..41b5321765636 100644 --- a/python/sglang/srt/layers/quantization/quark/quark.py +++ b/python/sglang/srt/layers/quantization/quark/quark.py @@ -15,7 +15,11 @@ QuantizationConfig, QuantizeMethodBase, ) -from sglang.srt.layers.quantization.fp8 import Fp8Config, Fp8LinearMethod +from sglang.srt.layers.quantization.fp8 import ( + Fp8Config, + Fp8LinearMethod, + Fp8MoEMethod, +) from sglang.srt.layers.quantization.kv_cache import BaseKVCacheMethod from sglang.srt.layers.quantization.quark.schemes import ( QuarkLinearScheme, @@ -376,9 +380,59 @@ def apply_weight_name_mapper(self, hf_to_sglang_mapper): expanded.append(name.removeprefix("language_model.")) self.exclude_layers = list(dict.fromkeys(expanded)) + layer_quant_config = self.quant_config.get("layer_quant_config") + if layer_quant_config: + self.quant_config["layer_quant_config"] = hf_to_sglang_mapper.apply_dict( + layer_quant_config + ) + + if self.kv_cache_group: + self.kv_cache_group = hf_to_sglang_mapper.apply_list(self.kv_cache_group) + + @staticmethod + def _get_block_fp8_config( + layer_quant_config: Optional[dict[str, Any]], + packed_modules_mapping: dict[str, list[str]], + ) -> Optional[Fp8Config]: + if layer_quant_config is None: + return None + + weight_config = layer_quant_config.get("weight") or {} + input_config = layer_quant_config.get("input_tensors") or {} + block_size = weight_config.get("block_size") + if not ( + weight_config.get("dtype") in {"fp8_e4m3", "fp8_e4m3fn"} + and weight_config.get("qscheme") == "per_block" + and weight_config.get("is_dynamic") is False + and isinstance(block_size, list) + and len(block_size) == 2 + and input_config.get("dtype") in {"fp8_e4m3", "fp8_e4m3fn"} + and input_config.get("is_dynamic") is True + ): + return None + + return Fp8Config( + is_checkpoint_fp8_serialized=True, + activation_scheme="dynamic", + weight_block_size=block_size, + packed_modules_mapping=packed_modules_mapping, + ) + def get_quant_method( self, layer: torch.nn.Module, prefix: str ) -> Optional["QuantizeMethodBase"]: + from sglang.srt.layers.moe.fused_moe_triton.layer import FusedMoE + + explicit_layer_config = self._find_matched_layer_config(prefix, layer) + block_fp8_config = self._get_block_fp8_config( + explicit_layer_config, self.packed_modules_mapping + ) + if block_fp8_config is not None: + if isinstance(layer, LinearBase): + return Fp8LinearMethod(block_fp8_config) + if isinstance(layer, FusedMoE): + return Fp8MoEMethod(block_fp8_config) + # Check if the layer is skipped for quantization. if should_ignore_layer( prefix, @@ -407,8 +461,6 @@ def get_quant_method( self._online_quantized_layers.add(prefix) return QuarkKVCacheMethod(self) - from sglang.srt.layers.moe.fused_moe_triton.layer import FusedMoE - if isinstance(layer, FusedMoE): self._online_quantized_layers.add(prefix) layer.scheme = self.get_moe_scheme(layer, prefix) @@ -783,9 +835,9 @@ def _is_mx_w4a8( ) return is_mx_fp4_weight and is_static_fp8_activation - def _find_matched_config( + def _find_matched_layer_config( self, layer_name: str, module: torch.nn.Module - ) -> dict[str, Any]: + ) -> Optional[dict[str, Any]]: proj_name = layer_name.split(".")[-1] if proj_name in self.packed_modules_mapping: @@ -797,9 +849,17 @@ def _find_matched_config( for shard_proj_name in shard_proj_names ] shard_configs = [ - self._find_matched_config(shard_name, module) + self._find_matched_layer_config(shard_name, module) for shard_name in shard_names ] + if all(q_config is None for q_config in shard_configs): + return None + if any(q_config is None for q_config in shard_configs): + raise ValueError( + f"Found a partially specified quantization configuration for " + f"{shard_proj_names} in {layer_name}. SGLang requires all " + "fused shards to use the same scheme." + ) if not all( deep_compare(q_config, shard_configs[0]) for q_config in shard_configs ): @@ -824,10 +884,19 @@ def _find_matched_config( if layer_type in layer_type_quant_config: return layer_type_quant_config[layer_type] - global_quant_config = cast( - dict[str, Any], self.quant_config.get("global_quant_config") - ) - return global_quant_config + return None + + def _find_matched_config( + self, layer_name: str, module: torch.nn.Module + ) -> dict[str, Any]: + layer_config = self._find_matched_layer_config(layer_name, module) + if layer_config is not None: + return layer_config + + global_quant_config = cast( + dict[str, Any], self.quant_config.get("global_quant_config") + ) + return global_quant_config def _get_scheme_from_config(self, config: dict[str, Any]) -> "QuarkLinearScheme": if config.get("output_tensors") or config.get("bias"): diff --git a/python/sglang/srt/layers/quantization/quark/utils.py b/python/sglang/srt/layers/quantization/quark/utils.py index dcd3aeb5993dd..1cdf8d4e70d63 100644 --- a/python/sglang/srt/layers/quantization/quark/utils.py +++ b/python/sglang/srt/layers/quantization/quark/utils.py @@ -55,6 +55,12 @@ def should_ignore_layer( # proj_name = qkv_proj proj_name = layer_name.split(".")[-1] + # Some checkpoints serialize an already-fused module (for example a + # vision ``qkv`` projection) and list that fused name in ``exclude``. + # Honor the direct match before expanding model-level packed mappings. + if check_equal_or_regex_match(layer_name=layer_name, targets=ignore): + return True + # Fused layers like gate_up_proj or qkv_proj will not be fused # in the safetensors checkpoint. So, we convert the name # from the fused version to unfused + check to make sure that diff --git a/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha_rocm.py b/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha_rocm.py index 39fc8ab092306..1dab68c7d6f58 100644 --- a/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha_rocm.py +++ b/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha_rocm.py @@ -269,8 +269,12 @@ def forward_normal_one_shot_rocm_prepare( def _concat_and_cast_mha_k_rocm( self: DeepseekV2AttentionMLA, k_nope: torch.Tensor, - k_pe: torch.Tensor, + k_pe: torch.Tensor | None, ): + if self.qk_rope_head_dim == 0: + assert k_pe is None or k_pe.shape[-1] == 0 + return k_nope.contiguous() + k_shape = (k_nope.shape[0], self.num_local_heads, self.qk_head_dim) k = k_nope.new_empty(*k_shape) if self.current_attention_backend == "aiter": diff --git a/python/sglang/srt/models/glm5_next.py b/python/sglang/srt/models/glm5_next.py index c931892e17562..c4b1566fd7e65 100644 --- a/python/sglang/srt/models/glm5_next.py +++ b/python/sglang/srt/models/glm5_next.py @@ -113,6 +113,7 @@ GlmOcrVisionPatchEmbed, GlmOcrVisionPatchMerger, ) +from sglang.srt.models.utils import WeightsMapper from sglang.srt.multimodal.mm_utils import ( run_dp_presharded_mrope_vision_model, run_dp_sharded_mrope_vision_model, @@ -134,6 +135,7 @@ ) logger = logging.getLogger(__name__) +_GLM_AITER_FUSED_MHC_LOGGED = False @torch.compile @@ -758,6 +760,7 @@ def __init__( hc_attn_pre=self.hc_attn_pre, hc_ffn_pre=self.hc_ffn_pre, hc_post=self.hc_post, + hc_attn_to_mlp=(self.hc_attn_to_mlp if _use_aiter_gfx95 else None), ) if self.dsa_enable_prefill_cp: self.layer_communicator = MHCHybridDSACPLayerCommunicator( @@ -824,6 +827,58 @@ def hc_post(self, hidden_states, residual, h_res, h_post): hc_mult=self.config.hc_mult, ) + def hc_attn_to_mlp( + self, + hidden_states, + residual, + h_res, + h_post, + out_norm_weight, + out_norm_eps, + ): + """Fuse attention mHC post with FFN mHC pre on AITER gfx95.""" + global _GLM_AITER_FUSED_MHC_LOGGED + + from sglang.srt.models.deepseek_common.amd.deepseek_v4_fused_mhc import ( + apply_mhc_post_pre_boundary, + ) + + num_tokens, hidden_size = hidden_states.shape + if num_tokens == 0: + return None + hc_mult = self.config.hc_mult + fused = apply_mhc_post_pre_boundary( + layer_input=hidden_states, + residual=residual.view(num_tokens, hc_mult, hidden_size), + post=h_post.view(num_tokens, hc_mult), + comb=h_res.view(num_tokens, hc_mult, hc_mult), + hc_fn=self.hc_ffn_fn, + hc_scale=self.hc_ffn_scale, + hc_base=self.hc_ffn_base, + hc_mult=hc_mult, + rms_eps=self.config.rms_norm_eps, + hc_eps=self.config.hc_eps, + hc_post_mult=2.0, + sinkhorn_iters=self.config.hc_sinkhorn_iters, + norm_weight=out_norm_weight, + norm_eps=out_norm_eps, + fn_transpose=True, + ) + if fused is None: + return None + if not _GLM_AITER_FUSED_MHC_LOGGED: + logger.info("Using fused AITER mHC attention-to-FFN boundary") + _GLM_AITER_FUSED_MHC_LOGGED = True + + next_residual, layer_input, next_h_post, next_h_res, norm_fused = fused + return ( + layer_input, + next_residual.view(num_tokens, -1), + next_h_res.reshape(num_tokens, hc_mult * hc_mult), + next_h_post.reshape(num_tokens, hc_mult), + norm_fused, + ) + def _is_layer_sparse(self, layer_id: int, is_nextn: bool) -> bool: return is_nextn or ( self.config.n_routed_experts is not None @@ -1218,6 +1273,13 @@ def forward( class Glm5NextForConditionalGeneration(nn.Module): + hf_to_sglang_mapper = WeightsMapper( + orig_to_new_prefix={ + "model.language_model.": "model.", + "model.visual.": "visual.", + }, + orig_to_new_suffix={".attn.qkv": ".attn.qkv_proj"}, + ) packed_modules_mapping = { "fused_qkv_a_proj_with_mqa": ["q_a_proj", "kv_a_proj_with_mqa"], "fused_qkvbfg_a_proj": [ @@ -1355,9 +1417,12 @@ def shared_experts_fusion_disable_reason(cls, hf_config, quant_config): text_config = getattr(hf_config, "text_config", hf_config) if not getattr(text_config, "n_shared_experts", None): return "No shared experts are defined in the config." - if not _is_cuda: - return "Shared experts fusion currently requires CUDA devices." - if _device_sm is not None and _device_sm < 80: + if not (_is_cuda or _use_aiter_gfx95): + return ( + "Shared experts fusion requires CUDA or the supported " + "AITER ROCm path." + ) + if _is_cuda and _device_sm is not None and _device_sm < 80: return "Shared experts fusion requires SM80 or newer GPUs." if get_parallel().moe_ep_size > 1: return ( @@ -1638,6 +1703,14 @@ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]], is_nextn=Fal fused_cat_dim = 0 params_dict = dict(self.named_parameters()) + + def maybe_map_fp8_block_scale_name(name: str) -> str: + if name.endswith(".weight_scale"): + candidate = name.removesuffix(".weight_scale") + ".weight_scale_inv" + if candidate in params_dict: + return candidate + return name + weight_names = [] for name, loaded_weight in weights: is_visual_weight = "visual" in name @@ -1701,6 +1774,7 @@ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]], is_nextn=Fal if "mlp.experts" in name: continue candidate = name.replace(weight_name, param_name) + candidate = maybe_map_fp8_block_scale_name(candidate) if ( param_name in { @@ -1729,6 +1803,7 @@ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]], is_nextn=Fal continue is_expert_weight = True name = name.replace(weight_name, param_name) + name = maybe_map_fp8_block_scale_name(name) if name not in params_dict: continue param = params_dict[name] @@ -1780,6 +1855,7 @@ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]], is_nextn=Fal "fused_qkv_a_proj_with_mqa", ) ) + target = maybe_map_fp8_block_scale_name(target) if target in params_dict: param = params_dict[target] weight_loader = getattr( @@ -1790,6 +1866,7 @@ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]], is_nextn=Fal cached_a_proj.pop(kv_a_proj_name, None) continue + name = maybe_map_fp8_block_scale_name(name) if name not in params_dict: continue diff --git a/python/sglang/srt/server_args.py b/python/sglang/srt/server_args.py index dbe3e65269335..ba4b75dd5940a 100644 --- a/python/sglang/srt/server_args.py +++ b/python/sglang/srt/server_args.py @@ -84,6 +84,7 @@ is_cpu, is_cuda, is_flashinfer_available, + is_gfx95_supported, is_hip, is_hopper_with_cuda_12_3, is_host_cpu_arm64, @@ -1898,7 +1899,7 @@ class ServerArgs: dsa_topk_backend: A[ str, Arg( - help="DSA indexer top-k backend for the target model. Options: 'sgl-kernel', 'torch', 'flashinfer'. The 'torch' backend currently requires SGLANG_DSA_FUSE_TOPK=false.", + help="DSA indexer top-k backend for the target model. Options: 'sgl-kernel', 'torch', 'flashinfer'. On non-gfx95 ROCm GPUs, 'sgl-kernel' falls back to the portable 'torch' backend with fused top-k disabled. The 'torch' backend otherwise requires SGLANG_DSA_FUSE_TOPK=false.", choices=DSA_TOPK_BACKEND_CHOICES, ), NS("exec.kernel"), @@ -5655,6 +5656,23 @@ def _set_default_dsa_backends(self, major: int) -> None: run_post_process_pass(self, _dsa_split_backend_resolution) + def _handle_rocm_dsa_topk_compatibility(self) -> None: + if not is_hip() or is_gfx95_supported(): + return + + cfg = resolving_view(self) + if cfg.dsa_topk_backend != "sgl-kernel": + return + + # The fused SGL transform requires gfx95 on ROCm. Torch returns raw + # indices, so it must use the unfused PAGED/RAGGED transform path. + envs.SGLANG_DSA_FUSE_TOPK.set(False) + self._declare("_handle_rocm_dsa_topk_compatibility", dsa_topk_backend="torch") + logger.warning( + "Use the portable Torch DSA top-k backend with fused top-k disabled " + "on non-gfx95 ROCm GPUs." + ) + def _validate_hisparse_dsa_backend(self, attr: str, label: str): from sglang.srt.arg_groups.hisparse_hook import validate_hisparse_dsa_backend @@ -5919,6 +5937,7 @@ def _handle_model_specific_adjustments(self): # here for the rest of the DSA family (DeepSeek-V3.2 / # GLM-5.x) that shares the same decode top-k path. envs.SGLANG_OPT_USE_TOPK_V2.set(False) + self._handle_rocm_dsa_topk_compatibility() if not self._resolved().enable_dp_attention and cfg.nnodes == 1: # TODO (Hubert): Put this back later # self.enable_aiter_allreduce_fusion = True diff --git a/test/registered/kernels/ops/attention/test_dsa_transform_index.py b/test/registered/kernels/ops/attention/test_dsa_transform_index.py index e4c32e3593c39..a9a7f63378ca0 100644 --- a/test/registered/kernels/ops/attention/test_dsa_transform_index.py +++ b/test/registered/kernels/ops/attention/test_dsa_transform_index.py @@ -33,9 +33,11 @@ def _make_page_table(self, rows: int, context_length: int) -> torch.Tensor: ) return columns.unsqueeze(0) + row_bias - def _make_topk(self, rows: int, context_length: int) -> torch.Tensor: + def _make_topk( + self, rows: int, context_length: int, topk: int = TOPK + ) -> torch.Tensor: topk = ( - torch.arange(TOPK, dtype=torch.int64, device=self.device) + torch.arange(topk, dtype=torch.int64, device=self.device) .remainder(context_length) .repeat(rows, 1) ) @@ -55,7 +57,7 @@ def _expected( ) -> torch.Tensor: real_num_tokens = sum(extend_lens_cpu) expected = torch.full( - (output_num_tokens, TOPK), + (output_num_tokens, topk_indices.shape[1]), -1, dtype=torch.int32, device=self.device, @@ -91,14 +93,15 @@ def _check_decode_case( *, zero_row_stride: bool = False, provide_result: bool = False, + topk: int = TOPK, ) -> None: if zero_row_stride: page_table = self._make_page_table(1, context_length).expand(batch_size, -1) else: page_table = self._make_page_table(batch_size, context_length) - topk_indices = self._make_topk(batch_size, context_length) + topk_indices = self._make_topk(batch_size, context_length, topk) expected = torch.empty( - (batch_size, TOPK), dtype=torch.int32, device=self.device + (batch_size, topk), dtype=torch.int32, device=self.device ) torch.gather( page_table, @@ -127,6 +130,7 @@ def _check_case( page_table_is_expanded: bool, topk_padding: int = 0, output_padding: int = 0, + topk: int = TOPK, ) -> None: real_num_tokens = sum(extend_lens_cpu) page_table_rows = ( @@ -135,7 +139,7 @@ def _check_case( topk_num_tokens = real_num_tokens + topk_padding output_num_tokens = topk_num_tokens + output_padding page_table = self._make_page_table(page_table_rows, context_length) - topk_indices = self._make_topk(topk_num_tokens, context_length) + topk_indices = self._make_topk(topk_num_tokens, context_length, topk) expected = self._expected( page_table, topk_indices, @@ -235,6 +239,16 @@ def test_decode_fast_extreme_shapes(self): self._check_decode_case(8192, 4096) self._check_decode_case(2, 1_000_000) + def test_kpool_tail_extended_width(self): + kpool_topk = TOPK + 15 + self._check_decode_case(17, 8192, topk=kpool_topk) + self._check_case( + [2, 1], + 8192, + page_table_is_expanded=False, + topk=kpool_topk, + ) + if __name__ == "__main__": unittest.main() diff --git a/test/registered/kernels/test_dsa_kpool_multi_pool.py b/test/registered/kernels/test_dsa_kpool_multi_pool.py index 26ce445333f00..18bf35845c5e2 100644 --- a/test/registered/kernels/test_dsa_kpool_multi_pool.py +++ b/test/registered/kernels/test_dsa_kpool_multi_pool.py @@ -1,32 +1,46 @@ -"""CUDA regressions for DSA kpool speculative writes spanning multiple pools.""" +"""GPU regressions for DSA kpool speculative writes and cache layout.""" import unittest from types import SimpleNamespace +from unittest.mock import patch import torch +from sglang.kernels.ops.attention.dsa import aiter_paged_mqa_logits +from sglang.kernels.ops.quantization.fp8_kernel import fp8_dtype +from sglang.srt.layers.attention.dsa import kpool_fp8_index from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( INDEX_HEAD_DIM, + _topk_from_pooled_history_logits_unfused, + gather_index_k_scale_prefix_into, kpool_assemble_softmax_rotate_write_cache, kpool_max_closed_pools, + kpool_softmax_rotate_write_cache, kpool_write_tail_and_maybe_compress, + topk_from_pooled_history_logits, update_kpool_write_plan_cuda_graph, ) from sglang.srt.layers.attention.dsa.kpool_plan import ( _alloc_kpool_write_plan_buffers, ) -from sglang.test.ci.ci_register import register_cuda_ci +from sglang.srt.layers.attention.dsa.utils import ( + aiter_can_use_preshuffle_paged_mqa, +) +from sglang.srt.utils import is_hip +from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci from sglang.test.test_utils import CustomTestCase register_cuda_ci(est_time=15, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_amd_ci(est_time=20, stage="jit-kernel-unit", runner_config="amd") -@unittest.skipUnless(torch.cuda.is_available(), "Test requires CUDA") +@unittest.skipUnless(torch.cuda.is_available(), "Test requires a GPU") class TestDsaKpoolMultiPool(CustomTestCase): POOL_SIZE = 4 PAGE_SIZE = 64 SLOTS_PER_PAGE = 64 NUM_DRAFT_TOKENS = 6 + NUM_INDEX_HEADS = 32 def _pool(self) -> SimpleNamespace: return SimpleNamespace( @@ -42,6 +56,47 @@ def _empty_cache(self) -> torch.Tensor: page_nbytes = self.SLOTS_PER_PAGE * INDEX_HEAD_DIM + self.SLOTS_PER_PAGE * 4 return torch.zeros((1, page_nbytes), dtype=torch.uint8, device="cuda") + def test_fused_topk_matches_unfused_physical_token_sets(self): + torch.manual_seed(45) + batch_size = 2 + score_cols = 4096 + pool_size = self.POOL_SIZE + topk = 2048 + logits = torch.randn(batch_size, score_cols, dtype=torch.float32, device="cuda") + group_lengths = torch.tensor([256, 511], dtype=torch.int32, device="cuda") + seq_lens = group_lengths * pool_size + torch.tensor( + [0, 3], dtype=torch.int32, device="cuda" + ) + page_table = torch.arange( + batch_size * score_cols * pool_size, + dtype=torch.int32, + device="cuda", + ).view(batch_size, score_cols * pool_size) + + actual = topk_from_pooled_history_logits( + logits=logits, + group_lengths=group_lengths, + pool_size=pool_size, + topk=topk, + page_table=page_table, + seq_lens=seq_lens, + ) + expected = _topk_from_pooled_history_logits_unfused( + logits=logits, + group_lengths=group_lengths, + pool_size=pool_size, + topk=topk, + page_table=page_table, + seq_lens=seq_lens, + ) + + torch.testing.assert_close( + torch.sort(actual, dim=1).values, + torch.sort(expected, dim=1).values, + atol=0, + rtol=0, + ) + def test_write_plan_records_every_candidate_pool(self): batch_size = 2 num_draft_tokens = self.NUM_DRAFT_TOKENS @@ -208,6 +263,202 @@ def test_compresses_two_pools_when_draft_window_closes_two(self): def test_effective_n_only_compresses_accepted_pools(self): self._run_compress_case(effective_n=2, expected_closed_pools=1) + def test_preshuffled_cache_round_trip_and_raw_layout(self): + torch.manual_seed(43) + pool = self._pool() + num_slots = self.SLOTS_PER_PAGE + tile = 16 + num_col_tiles = INDEX_HEAD_DIM // tile + + slot_k = torch.randn( + num_slots, + self.POOL_SIZE, + INDEX_HEAD_DIM, + dtype=torch.bfloat16, + device="cuda", + ) + slot_score = torch.zeros_like(slot_k) + ape = torch.zeros( + self.POOL_SIZE, + INDEX_HEAD_DIM, + dtype=torch.float32, + device="cuda", + ) + loc = torch.arange(num_slots, dtype=torch.int64, device="cuda") + cache = self._empty_cache() + + with patch.object(kpool_fp8_index, "_preshuffle_tile", return_value=tile): + compressed_k, compressed_scale = kpool_softmax_rotate_write_cache( + pool=pool, + buf=cache, + slot_k=slot_k, + slot_score=slot_score, + ape=ape, + loc=loc, + return_compressed=True, + ) + + gathered_k = torch.empty( + (num_slots, INDEX_HEAD_DIM), dtype=torch.uint8, device="cuda" + ) + gathered_scale = torch.empty( + (num_slots,), dtype=torch.float32, device="cuda" + ) + gather_index_k_scale_prefix_into( + pool=pool, + buf=cache, + page_indices=torch.zeros(1, dtype=torch.int32, device="cuda"), + seq_len=num_slots, + k_out=gathered_k, + scale_out=gathered_scale, + ) + + compressed_k_u8 = compressed_k.view(torch.uint8) + torch.testing.assert_close(gathered_k, compressed_k_u8, atol=0, rtol=0) + torch.testing.assert_close(gathered_scale, compressed_scale, atol=0, rtol=0) + + raw_k = cache[0, : num_slots * INDEX_HEAD_DIM].view( + num_slots // tile, num_col_tiles, tile, tile + ) + expected_raw_k = ( + compressed_k_u8.view(num_slots // tile, tile, num_col_tiles, tile) + .permute(0, 2, 1, 3) + .contiguous() + ) + torch.testing.assert_close(raw_k, expected_raw_k, atol=0, rtol=0) + + @unittest.skipUnless( + is_hip() and aiter_can_use_preshuffle_paged_mqa(), + "requires the ROCm AITER preshuffle paged-MQA path", + ) + def test_preshuffled_paged_mqa_matches_gathered_mqa(self): + from aiter.ops.triton.fp8_mqa_logits import fp8_mqa_logits + + torch.manual_seed(44) + pool = self._pool() + page_nbytes = self.SLOTS_PER_PAGE * (INDEX_HEAD_DIM + 4) + tile = 16 + num_token_tiles = self.SLOTS_PER_PAGE // tile + num_col_tiles = INDEX_HEAD_DIM // tile + + for batch_size in (1, 8): + with self.subTest(batch_size=batch_size): + cache = torch.zeros( + (batch_size, page_nbytes), dtype=torch.uint8, device="cuda" + ) + k = ( + torch.randn( + batch_size, + self.SLOTS_PER_PAGE, + INDEX_HEAD_DIM, + device="cuda", + ) + * 2 + ).to(fp8_dtype) + k_scale = ( + torch.rand(batch_size, self.SLOTS_PER_PAGE, device="cuda") + 0.25 + ) + + preshuffled = ( + k.view( + batch_size, + num_token_tiles, + tile, + num_col_tiles, + tile, + ) + .permute(0, 1, 3, 2, 4) + .contiguous() + .view(batch_size, -1) + .view(torch.uint8) + ) + k_region_bytes = self.SLOTS_PER_PAGE * INDEX_HEAD_DIM + cache[:, :k_region_bytes].copy_(preshuffled) + cache[:, k_region_bytes:].view(torch.float32).copy_(k_scale) + + q = ( + torch.randn( + batch_size, + self.NUM_INDEX_HEADS, + INDEX_HEAD_DIM, + device="cuda", + ) + * 2 + ).to(fp8_dtype) + weights = torch.randn( + batch_size, + self.NUM_INDEX_HEADS, + dtype=torch.float32, + device="cuda", + ) + if batch_size == 1: + seq_lens = torch.tensor([53], dtype=torch.int32, device="cuda") + else: + seq_lens = torch.tensor( + [1, 7, 16, 31, 32, 47, 63, 64], + dtype=torch.int32, + device="cuda", + ) + block_tables = torch.arange( + batch_size, dtype=torch.int32, device="cuda" + ).view(batch_size, 1) + + paged_logits = aiter_paged_mqa_logits( + q, + cache.view(batch_size, self.SLOTS_PER_PAGE, 1, INDEX_HEAD_DIM + 4), + weights, + seq_lens, + block_tables, + self.SLOTS_PER_PAGE, + preshuffle=True, + kv_block_size=self.SLOTS_PER_PAGE, + ) + + gathered_k = [] + gathered_scale = [] + for batch_idx, seq_len in enumerate(seq_lens.tolist()): + k_out = torch.empty( + (seq_len, INDEX_HEAD_DIM), dtype=torch.uint8, device="cuda" + ) + scale_out = torch.empty( + (seq_len,), dtype=torch.float32, device="cuda" + ) + gather_index_k_scale_prefix_into( + pool=pool, + buf=cache, + page_indices=torch.tensor( + [batch_idx], dtype=torch.int32, device="cuda" + ), + seq_len=seq_len, + k_out=k_out, + scale_out=scale_out, + ) + gathered_k.append(k_out.view(fp8_dtype)) + gathered_scale.append(scale_out) + + flat_k = torch.cat(gathered_k) + flat_scale = torch.cat(gathered_scale) + ends = seq_lens.cumsum(0) + starts = ends - seq_lens + gathered_logits = fp8_mqa_logits( + q, + flat_k, + flat_scale, + weights, + starts, + ends, + clean_logits=True, + ) + + for batch_idx, seq_len in enumerate(seq_lens.tolist()): + start = starts[batch_idx].item() + torch.testing.assert_close( + paged_logits[batch_idx, :seq_len], + gathered_logits[batch_idx, start : start + seq_len], + atol=2e-2, + rtol=2e-2, + ) + if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/layers/moe/test_fused_moe_swiglu_clamp.py b/test/registered/unit/layers/moe/test_fused_moe_swiglu_clamp.py new file mode 100644 index 0000000000000..fd37950c87daa --- /dev/null +++ b/test/registered/unit/layers/moe/test_fused_moe_swiglu_clamp.py @@ -0,0 +1,38 @@ +import unittest + +import torch +import torch.nn.functional as F + +from sglang.srt.layers.moe.moe_runner.triton_utils.fused_moe import ( + _clamp_swiglu_inputs_, +) +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=1, suite="base-a-test-cpu") + + +class TestFusedMoeSwigluClamp(CustomTestCase): + def test_clamps_gate_and_up_with_the_deepseek_contract(self): + inputs = torch.tensor([[-20.0, 20.0, -20.0, 20.0], [3.0, 11.0, -4.0, 5.0]]) + + _clamp_swiglu_inputs_(inputs, limit=10.0) + + torch.testing.assert_close( + inputs, + torch.tensor([[-20.0, 10.0, -10.0, 10.0], [3.0, 10.0, -4.0, 5.0]]), + ) + + def test_clamped_inputs_match_reference_swiglu(self): + inputs = torch.tensor([[-12.0, 14.0, -13.0, 15.0]]) + + _clamp_swiglu_inputs_(inputs, limit=10.0) + output = F.silu(inputs[..., :2]) * inputs[..., 2:] + + expected_gate = torch.tensor([[-12.0, 10.0]]) + expected_up = torch.tensor([[-10.0, 10.0]]) + torch.testing.assert_close(output, F.silu(expected_gate) * expected_up) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/unit/layers/quantization/test_fp8_moe_runner_ownership.py b/test/registered/unit/layers/quantization/test_fp8_moe_runner_ownership.py index 08316b4f57aed..3e5f5787c18c4 100644 --- a/test/registered/unit/layers/quantization/test_fp8_moe_runner_ownership.py +++ b/test/registered/unit/layers/quantization/test_fp8_moe_runner_ownership.py @@ -1,10 +1,9 @@ """Unit tests for srt/layers/quantization/fp8.py MoE runner ownership. -`--moe-runner-backend flashinfer_trtllm[_routed]` is a global setting, so -`Fp8MoEMethod.process_weights_after_loading` must also require that this -instance owns a MoeRunner before materializing the TRT-LLM SwiGLU params: -the MxFP4 wrapper methods borrow an `Fp8MoEMethod` for weight loading only -and never give it a `moe_runner_config` (issue #36264). +MoE backend flags are global, so `Fp8MoEMethod.process_weights_after_loading` +must require that this instance owns a MoeRunner before materializing +backend-specific parameters or layouts. MxFP4 wrappers borrow an `Fp8MoEMethod` +for weight loading without giving it a runner (issue #36264). """ import unittest @@ -113,6 +112,81 @@ def test_owning_method_skips_params_on_non_trtllm_backend(self): self._assert_activation_params_absent(layer) + def test_global_aiter_does_not_shuffle_triton_runner_weights(self): + """SGLANG_USE_AITER also enables non-MoE kernels, so the selected MoE + runner must own the preshuffled layout before weights are rewritten.""" + method = self._make_block_fp8_method() + method.convert_mxfp8_to_block = True + method.use_mxfp8 = True + method.runner = SimpleNamespace(runner_backend=MoeRunnerBackend.TRITON) + method._owns_moe_runner = True + layer = SimpleNamespace( + w13_weight=torch.nn.Parameter(torch.arange(16.0).reshape(1, 4, 4)), + w2_weight=torch.nn.Parameter(torch.arange(16.0).reshape(1, 4, 4)), + ) + + with ( + patch("sglang.srt.layers.quantization.fp8._use_aiter", True), + patch("sglang.srt.layers.quantization.fp8._is_fp8_fnuz", False), + patch.object(method, "_convert_mxfp8_moe_to_block_fp8"), + patch("sglang.srt.layers.quantization.fp8.shuffle_weight") as shuffle, + ): + method.process_weights_after_loading_block_quant(layer) + + shuffle.assert_not_called() + + def test_borrowed_delegate_skips_aiter_weight_shuffle(self): + """MxFP4 delegates do not own a runner, so global AITER enablement must + not make weight loading dereference or prepare an absent runner.""" + method = self._make_block_fp8_method() + method.convert_mxfp8_to_block = True + method.use_mxfp8 = True + layer = SimpleNamespace( + w13_weight=torch.nn.Parameter(torch.arange(16.0).reshape(1, 4, 4)), + w2_weight=torch.nn.Parameter(torch.arange(16.0).reshape(1, 4, 4)), + ) + + with ( + patch("sglang.srt.layers.quantization.fp8._use_aiter", True), + patch("sglang.srt.layers.quantization.fp8._is_fp8_fnuz", False), + patch.object(method, "_convert_mxfp8_moe_to_block_fp8"), + patch("sglang.srt.layers.quantization.fp8.shuffle_weight") as shuffle, + ): + method.process_weights_after_loading_block_quant(layer) + + shuffle.assert_not_called() + + def test_aiter_runner_keeps_preshuffled_weight_layout(self): + method = self._make_block_fp8_method() + method.convert_mxfp8_to_block = True + method.use_mxfp8 = True + method.runner = SimpleNamespace(runner_backend=MoeRunnerBackend.AITER) + method._owns_moe_runner = True + original_w13 = torch.arange(16.0).reshape(1, 4, 4) + original_w2 = torch.arange(16.0, 32.0).reshape(1, 4, 4) + layer = SimpleNamespace( + w13_weight=torch.nn.Parameter(original_w13.clone()), + w2_weight=torch.nn.Parameter(original_w2.clone()), + ) + + def add_one(weight, _tile): + return weight + 1 + + with ( + patch("sglang.srt.layers.quantization.fp8._use_aiter", True), + patch("sglang.srt.layers.quantization.fp8._is_fp8_fnuz", False), + patch.object(method, "_convert_mxfp8_moe_to_block_fp8"), + patch( + "sglang.srt.layers.quantization.fp8.shuffle_weight", + side_effect=add_one, + ) as shuffle, + ): + method.process_weights_after_loading_block_quant(layer) + + self.assertEqual(shuffle.call_count, 2) + torch.testing.assert_close(layer.w13_weight, original_w13 + 1) + torch.testing.assert_close(layer.w2_weight, original_w2 + 1) + if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/layers/quantization/test_quark_config.py b/test/registered/unit/layers/quantization/test_quark_config.py index c2990d79bf10f..db59bb4e53eb3 100644 --- a/test/registered/unit/layers/quantization/test_quark_config.py +++ b/test/registered/unit/layers/quantization/test_quark_config.py @@ -5,10 +5,13 @@ register_cpu_ci(est_time=5, suite="base-a-test-cpu") import unittest +from copy import deepcopy from unittest.mock import patch import torch +from sglang.srt.layers.linear import LinearBase +from sglang.srt.layers.quantization.fp8 import Fp8LinearMethod from sglang.srt.layers.quantization.quark.quark import ( QuarkConfig, _build_mixed_precision_layer_quant_config, @@ -16,6 +19,7 @@ _parse_nvfp4_excludes, ) from sglang.srt.layers.quantization.quark.utils import check_equal_or_regex_match +from sglang.srt.models.glm5_next import Glm5NextForConditionalGeneration from sglang.test.test_utils import CustomTestCase _GET_CAP = "sglang.srt.layers.quantization.quark.quark.get_device_capability" @@ -207,5 +211,115 @@ def test_already_regex_entries_pass_through_and_match(self): ) +class TestQuarkPerLayerBlockFp8(CustomTestCase): + _BLOCK_FP8_CONFIG = { + "weight": { + "dtype": "fp8_e4m3", + "qscheme": "per_block", + "block_size": [128, 128], + "is_dynamic": False, + }, + "input_tensors": { + "dtype": "fp8_e4m3", + "qscheme": "per_group", + "group_size": 128, + "is_dynamic": True, + }, + "output_tensors": None, + "bias": None, + } + + def _build_bare_config(self) -> QuarkConfig: + config = _bare_config() + config.quant_config = { + "layer_quant_config": { + "model.language_model.layers.0.mlp.down_proj": self._BLOCK_FP8_CONFIG + }, + "layer_type_quant_config": {}, + "global_quant_config": { + "weight": { + "dtype": "fp4", + "qscheme": "per_group", + "group_size": 32, + "is_dynamic": False, + "scale_format": "e8m0", + }, + "input_tensors": { + "dtype": "fp4", + "qscheme": "per_group", + "group_size": 32, + "is_dynamic": True, + "scale_format": "e8m0", + }, + }, + } + config.exclude_layers = [] + config.kv_cache_group = [] + config.packed_modules_mapping = {} + config.excluded_fp8_config = None + config._online_quantized_layers = set() + return config + + def test_model_mapper_rewrites_explicit_layer_config(self): + config = self._build_bare_config() + + config.apply_weight_name_mapper( + Glm5NextForConditionalGeneration.hf_to_sglang_mapper + ) + + self.assertIn( + "model.layers.0.mlp.down_proj", + config.quant_config["layer_quant_config"], + ) + + def test_model_mapper_rewrites_fused_visual_exclusion(self): + config = self._build_bare_config() + config.exclude_layers = ["model.visual.blocks.0.attn.qkv"] + + config.apply_weight_name_mapper( + Glm5NextForConditionalGeneration.hf_to_sglang_mapper + ) + + self.assertEqual( + config.exclude_layers, + ["visual.blocks.0.attn.qkv_proj"], + ) + self.assertNotIn( + "model.language_model.layers.0.mlp.down_proj", + config.quant_config["layer_quant_config"], + ) + + def test_explicit_block_fp8_linear_uses_fp8_method(self): + config = self._build_bare_config() + config.apply_weight_name_mapper( + Glm5NextForConditionalGeneration.hf_to_sglang_mapper + ) + layer = LinearBase.__new__(LinearBase) + + method = config.get_quant_method(layer, "model.layers.0.mlp.down_proj") + + self.assertIsInstance(method, Fp8LinearMethod) + self.assertTrue(method.quant_config.is_checkpoint_fp8_serialized) + self.assertEqual(method.quant_config.weight_block_size, [128, 128]) + + def test_dynamic_block_fp8_weight_is_not_treated_as_serialized(self): + layer_config = deepcopy(self._BLOCK_FP8_CONFIG) + layer_config["weight"]["is_dynamic"] = True + + self.assertIsNone(QuarkConfig._get_block_fp8_config(layer_config, {})) + + def test_unmatched_layer_still_uses_global_quark_config(self): + config = self._build_bare_config() + config.apply_weight_name_mapper( + Glm5NextForConditionalGeneration.hf_to_sglang_mapper + ) + + matched = config._find_matched_config( + "model.layers.4.mlp.down_proj", torch.nn.Module() + ) + + self.assertEqual(matched["weight"]["dtype"], "fp4") + + if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/layers/quantization/test_quark_utils.py b/test/registered/unit/layers/quantization/test_quark_utils.py index 606dd346d12db..cc027a743e163 100644 --- a/test/registered/unit/layers/quantization/test_quark_utils.py +++ b/test/registered/unit/layers/quantization/test_quark_utils.py @@ -8,7 +8,10 @@ import torch -from sglang.srt.layers.quantization.quark.utils import e8m0_to_f32 +from sglang.srt.layers.quantization.quark.utils import ( + e8m0_to_f32, + should_ignore_layer, +) from sglang.test.test_utils import CustomTestCase @@ -66,5 +69,16 @@ def test_cuda_parity(self): self.assertTrue(torch.isnan(out[2]).item()) +class TestShouldIgnoreLayer(CustomTestCase): + def test_direct_fused_module_exclusion_takes_precedence(self): + self.assertTrue( + should_ignore_layer( + "visual.blocks.0.attn.qkv_proj", + ["visual.blocks.0.attn.qkv_proj"], + {"qkv_proj": ["q_proj", "k_proj", "v_proj"]}, + ) + ) + + if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/layers/test_dsa_indexer_kpool_backend.py b/test/registered/unit/layers/test_dsa_indexer_kpool_backend.py new file mode 100644 index 0000000000000..8f75c9b8ba934 --- /dev/null +++ b/test/registered/unit/layers/test_dsa_indexer_kpool_backend.py @@ -0,0 +1,196 @@ +import sys +import unittest +from types import ModuleType +from unittest.mock import MagicMock, patch + +import torch + +from sglang.srt.layers.attention.dsa import dsa_indexer_kpool +from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( + _topk_from_pooled_history_logits_unfused, + topk_from_pooled_history_logits, +) +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=1, suite="base-a-test-cpu") + + +class TestKPoolMqaBackend(CustomTestCase): + def test_cuda_tilelang_selector_reads_heads_from_unexpanded_query(self): + with ( + patch.object(dsa_indexer_kpool, "is_cuda", return_value=True), + patch("torch.cuda.get_device_capability", return_value=(9, 0)), + ): + self.assertFalse( + dsa_indexer_kpool.IndexerKPool._should_use_tilelang_paged_mqa_logits( + torch.empty(1, 32, 128) + ) + ) + self.assertTrue( + dsa_indexer_kpool.IndexerKPool._should_use_tilelang_paged_mqa_logits( + torch.empty(1, 16, 128) + ) + ) + + def test_rocm_uses_aiter_mqa_logits(self): + marker = object() + aiter_impl = MagicMock(return_value=marker) + module = ModuleType("aiter.ops.triton.fp8_mqa_logits") + module.fp8_mqa_logits = aiter_impl + + args = tuple(object() for _ in range(6)) + with ( + patch.object(dsa_indexer_kpool, "is_hip", return_value=True), + patch.dict( + sys.modules, + {"aiter.ops.triton.fp8_mqa_logits": module}, + ), + ): + result = dsa_indexer_kpool.IndexerKPool._fp8_mqa_logits( + *args, clean_logits=False + ) + + self.assertIs(result, marker) + aiter_impl.assert_called_once_with(*args, clean_logits=False) + + def test_cuda_keeps_deep_gemm_mqa_logits(self): + marker = object() + deep_gemm = MagicMock() + deep_gemm.fp8_mqa_logits.return_value = marker + q_fp8, k_fp8, k_scale, weights, starts, ends = (object() for _ in range(6)) + + with ( + patch.object(dsa_indexer_kpool, "is_hip", return_value=False), + patch.object(dsa_indexer_kpool, "deep_gemm", deep_gemm, create=True), + ): + result = dsa_indexer_kpool.IndexerKPool._fp8_mqa_logits( + q_fp8, + k_fp8, + k_scale, + weights, + starts, + ends, + clean_logits=True, + ) + + self.assertIs(result, marker) + deep_gemm.fp8_mqa_logits.assert_called_once_with( + q_fp8, + (k_fp8, k_scale), + weights, + starts, + ends, + clean_logits=True, + ) + + def test_portable_topk_masks_invalid_groups_and_expands(self): + logits = torch.tensor([[0.1, 0.9, 0.8, 50.0]], dtype=torch.float32) + result = _topk_from_pooled_history_logits_unfused( + logits=logits, + group_lengths=torch.tensor([3], dtype=torch.int32), + pool_size=2, + topk=4, + ) + + torch.testing.assert_close( + result, + torch.tensor([[2, 3, 4, 5]], dtype=torch.int32), + ) + + def test_rocm_uses_fused_kpool_topk_for_supported_group_count(self): + logits = MagicMock() + logits.ndim = 2 + logits.shape = (1, 512) + logits.is_cuda = True + logits.dtype = torch.float32 + group_lengths = torch.tensor([256], dtype=torch.int32) + marker = MagicMock() + marker.shape = (1, 2048) + + with ( + patch( + "sglang.srt.layers.attention.dsa.kpool_fp8_index.is_hip", + return_value=True, + ), + patch( + "sglang.kernels.ops.moe.kpool_topk_transform.fast_kpool_topk_transform_fused", + return_value=marker, + ) as fused, + patch( + "sglang.srt.layers.attention.dsa.kpool_fp8_index._topk_from_pooled_history_logits_unfused" + ) as unfused, + ): + result = topk_from_pooled_history_logits( + logits=logits, + group_lengths=group_lengths, + pool_size=4, + topk=2048, + ) + + self.assertIs(result, marker) + fused.assert_called_once() + unfused.assert_not_called() + + def test_rocm_keeps_2048_group_topk_on_unfused_path(self): + logits = MagicMock() + logits.ndim = 2 + logits.shape = (1, 2048) + logits.is_cuda = True + logits.dtype = torch.float32 + group_lengths = torch.tensor([2048], dtype=torch.int32) + marker = object() + + with ( + patch( + "sglang.srt.layers.attention.dsa.kpool_fp8_index.is_hip", + return_value=True, + ), + patch( + "sglang.srt.layers.attention.dsa.kpool_fp8_index._topk_from_pooled_history_logits_unfused", + return_value=marker, + ) as unfused, + ): + result = topk_from_pooled_history_logits( + logits=logits, + group_lengths=group_lengths, + pool_size=4, + topk=8192, + ) + + self.assertIs(result, marker) + unfused.assert_called_once() + + def test_cuda_keeps_supported_group_count_on_fused_path(self): + logits = MagicMock() + logits.ndim = 2 + logits.shape = (1, 512) + logits.is_cuda = True + logits.dtype = torch.float32 + group_lengths = torch.tensor([256], dtype=torch.int32) + marker = MagicMock() + marker.shape = (1, 2048) + + with ( + patch( + "sglang.srt.layers.attention.dsa.kpool_fp8_index.is_hip", + return_value=False, + ), + patch( + "sglang.kernels.ops.moe.kpool_topk_transform.fast_kpool_topk_transform_fused", + return_value=marker, + ) as fused, + ): + result = topk_from_pooled_history_logits( + logits=logits, + group_lengths=group_lengths, + pool_size=4, + topk=2048, + ) + + self.assertIs(result, marker) + fused.assert_called_once() + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/unit/layers/test_mhc_deep_gemm_gate.py b/test/registered/unit/layers/test_mhc_deep_gemm_gate.py new file mode 100644 index 0000000000000..055e3709b1e7c --- /dev/null +++ b/test/registered/unit/layers/test_mhc_deep_gemm_gate.py @@ -0,0 +1,89 @@ +import unittest +from unittest.mock import patch + +from sglang.kernels.ops.layernorm import mhc +from sglang.srt.environ import envs +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=1, suite="base-a-test-cpu") + + +class TestMhcDeepGemmGate(CustomTestCase): + def test_falls_back_when_deep_gemm_is_unavailable(self): + with ( + envs.SGLANG_OPT_DEEPGEMM_HC_PRENORM.override(True), + patch( + "sglang.srt.layers.deep_gemm_wrapper.configurer.ENABLE_JIT_DEEPGEMM", + False, + ), + ): + self.assertFalse(mhc._use_deep_gemm_hc_prenorm()) + + def test_preserves_deep_gemm_path_when_available(self): + with ( + envs.SGLANG_OPT_DEEPGEMM_HC_PRENORM.override(True), + patch( + "sglang.srt.layers.deep_gemm_wrapper.configurer.ENABLE_JIT_DEEPGEMM", + True, + ), + ): + self.assertTrue(mhc._use_deep_gemm_hc_prenorm()) + + def test_explicit_disable_takes_precedence(self): + with ( + envs.SGLANG_OPT_DEEPGEMM_HC_PRENORM.override(False), + patch( + "sglang.srt.layers.deep_gemm_wrapper.configurer.ENABLE_JIT_DEEPGEMM", + True, + ), + ): + self.assertFalse(mhc._use_deep_gemm_hc_prenorm()) + + +class TestMhcTilelangBackendGate(CustomTestCase): + def test_cuda_keeps_env_selected_tilelang_pre_path(self): + with ( + envs.SGLANG_OPT_USE_TILELANG_MHC_PRE.override(True), + patch.object(mhc, "is_hip", return_value=False), + ): + self.assertTrue(mhc._use_tilelang_mhc_pre()) + + def test_hip_always_uses_torch_pre_path(self): + with ( + envs.SGLANG_OPT_USE_TILELANG_MHC_PRE.override(True), + patch.object(mhc, "is_hip", return_value=True), + ): + self.assertFalse(mhc._use_tilelang_mhc_pre()) + + def test_explicit_tilelang_pre_disable_takes_precedence(self): + with ( + envs.SGLANG_OPT_USE_TILELANG_MHC_PRE.override(False), + patch.object(mhc, "is_hip", return_value=False), + ): + self.assertFalse(mhc._use_tilelang_mhc_pre()) + + def test_cuda_keeps_env_selected_tilelang_post_path(self): + with ( + envs.SGLANG_OPT_USE_TILELANG_MHC_POST.override(True), + patch.object(mhc, "is_hip", return_value=False), + ): + self.assertTrue(mhc._use_tilelang_mhc_post()) + + def test_hip_always_uses_torch_post_path(self): + with ( + envs.SGLANG_OPT_USE_TILELANG_MHC_POST.override(True), + patch.object(mhc, "is_hip", return_value=True), + ): + self.assertFalse(mhc._use_tilelang_mhc_post()) + + def test_explicit_tilelang_post_disable_takes_precedence(self): + with ( + envs.SGLANG_OPT_USE_TILELANG_MHC_POST.override(False), + patch.object(mhc, "is_hip", return_value=False), + ): + self.assertFalse(mhc._use_tilelang_mhc_post()) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/unit/mem_cache/test_glm5_next_hybrid_pool.py b/test/registered/unit/mem_cache/test_glm5_next_hybrid_pool.py new file mode 100644 index 0000000000000..6a9a7edf44a36 --- /dev/null +++ b/test/registered/unit/mem_cache/test_glm5_next_hybrid_pool.py @@ -0,0 +1,121 @@ +"""Regression coverage for GLM-5.3's hybrid DSA/KDA KV pool.""" + +import sys +import unittest +from types import ModuleType, SimpleNamespace +from unittest.mock import patch + +import torch + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=1, suite="base-a-test-cpu") + + +class TestGlm5NextHybridPool(CustomTestCase): + @patch( + "sglang.srt.mem_cache.kv_cache_configurator.HybridLinearKVPool", + autospec=True, + ) + @patch( + "sglang.srt.mem_cache.kv_cache_configurator.calculate_mla_kv_cache_dim", + autospec=True, + return_value=576, + ) + @patch( + "sglang.srt.mem_cache.kv_cache_configurator.get_dsa_index_kpool_compress", + return_value=True, + ) + @patch( + "sglang.srt.mem_cache.kv_cache_configurator.get_dsa_index_kpool", + return_value=1, + ) + @patch( + "sglang.srt.mem_cache.kv_cache_configurator.get_dsa_index_head_dim", + return_value=128, + ) + @patch( + "sglang.srt.mem_cache.kv_cache_configurator.dsa_layer_skips_topk", + return_value=False, + ) + @patch( + "sglang.srt.mem_cache.kv_cache_configurator.is_deepseek_dsa", + return_value=True, + ) + def test_dsa_kv_dimension_uses_current_calculator_contract( + self, + _mock_is_deepseek_dsa, + _mock_dsa_layer_skips_topk, + _mock_index_head_dim, + _mock_index_kpool, + _mock_index_kpool_compress, + mock_calculate_mla_kv_cache_dim, + mock_hybrid_pool, + ): + from sglang.srt.mem_cache.kv_cache_configurator import KVCacheConfigurator + + configurator = object.__new__(KVCacheConfigurator) + configurator.is_draft_worker = False + configurator.mambaish_config = SimpleNamespace(full_attention_layer_ids=[3]) + configurator.layer_info = SimpleNamespace(start_layer=0, end_layer=4) + configurator.use_mla_backend = True + configurator.model_config = SimpleNamespace( + hf_config=SimpleNamespace(), + kv_lora_rank=512, + qk_rope_head_dim=64, + head_dim=128, + get_num_kv_heads=lambda _tp_size, _dcp_size: 1, + ) + configurator.kv_cache_dtype = torch.bfloat16 + configurator.kv_cache_dtype_str = "bfloat16" + configurator.device = "cuda" + configurator.post_capture_kv_active = False + + req_to_token_pool = SimpleNamespace(mamba_pool=object()) + fake_cp_utils = ModuleType("sglang.srt.layers.cp.utils") + fake_cp_utils.get_glm_dsa_cp_layer_shard_info = lambda _configurator: (0, 1) + with ( + patch.dict( + sys.modules, + {"sglang.srt.layers.cp.utils": fake_cp_utils}, + ), + patch.object( + KVCacheConfigurator, + "_build_fp4_quant_method", + return_value=None, + ), + patch( + "sglang.srt.mem_cache.kv_cache_configurator.get_parallel", + return_value=SimpleNamespace(attn_tp_size=8, attn_dcp_size=1), + ), + patch( + "sglang.srt.mem_cache.kv_cache_configurator.get_exec", + return_value=SimpleNamespace( + features=SimpleNamespace(enable_memory_saver=False) + ), + ), + patch( + "sglang.srt.mem_cache.kv_cache_configurator.get_schedule", + return_value=SimpleNamespace(page_size=64), + ), + patch( + "sglang.srt.mem_cache.kv_cache_configurator.get_spec", + return_value=SimpleNamespace(speculative_algorithm=None), + ), + ): + configurator._build_hybrid_linear_kv_pool( + max_total_num_tokens=1024, + req_to_token_pool=req_to_token_pool, + mha_pool_class=object, + ) + + mock_calculate_mla_kv_cache_dim.assert_called_once_with( + model_config=configurator.model_config, + kv_cache_dtype=torch.bfloat16, + ) + self.assertEqual(mock_hybrid_pool.call_args.kwargs["kv_cache_dim"], 576) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/unit/models/test_glm5_next_aiter_mhc.py b/test/registered/unit/models/test_glm5_next_aiter_mhc.py new file mode 100644 index 0000000000000..4a1438e598c7a --- /dev/null +++ b/test/registered/unit/models/test_glm5_next_aiter_mhc.py @@ -0,0 +1,238 @@ +import sys +from types import ModuleType, SimpleNamespace +from unittest.mock import MagicMock, patch + +import torch +from torch import nn + +from sglang.kernels.ops.layernorm import mhc +from sglang.srt.layers.communicator_mhc import MHCState +from sglang.srt.models import glm5_next +from sglang.srt.models.glm5_next import Glm5NextDecoderLayer +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=6, suite="base-a-test-cpu") + + +def _fake_aiter_mhc_module(*, mhc_pre=None, mhc_post=None): + aiter_module = ModuleType("aiter") + ops_module = ModuleType("aiter.ops") + mhc_module = ModuleType("aiter.ops.mhc") + if mhc_pre is not None: + mhc_module.mhc_pre = mhc_pre + if mhc_post is not None: + mhc_module.mhc_post = mhc_post + aiter_module.ops = ops_module + ops_module.mhc = mhc_module + return { + "aiter": aiter_module, + "aiter.ops": ops_module, + "aiter.ops.mhc": mhc_module, + } + + +def test_aiter_mhc_gate_is_rocm_gfx95_only(): + with ( + patch.object(mhc, "is_hip", return_value=True), + patch.object(mhc, "is_gfx95_supported", return_value=True), + patch.object(mhc, "get_bool_env_var", return_value=True), + patch.object(mhc, "_AITER_MHC_RUNTIME_DISABLED", False), + ): + assert mhc._use_aiter_mhc() + + for is_hip, is_gfx95, use_aiter in ( + (False, True, True), + (True, False, True), + (True, True, False), + ): + with ( + patch.object(mhc, "is_hip", return_value=is_hip), + patch.object(mhc, "is_gfx95_supported", return_value=is_gfx95), + patch.object(mhc, "get_bool_env_var", return_value=use_aiter), + patch.object(mhc, "_AITER_MHC_RUNTIME_DISABLED", False), + ): + assert not mhc._use_aiter_mhc() + + +def test_aiter_mhc_pre_dispatch_forwards_norm_contract(): + residual = torch.randn(2, 4, 8) + fn = torch.randn(24, 32) + hc_scale = torch.randn(3) + hc_base = torch.randn(24) + norm_weight = torch.randn(8) + expected = ( + torch.randn(2, 4, 1), + torch.randn(2, 4, 4), + torch.randn(2, 8), + ) + fake_pre = MagicMock(return_value=expected) + + with ( + patch.dict(sys.modules, _fake_aiter_mhc_module(mhc_pre=fake_pre)), + patch.object(mhc, "_use_aiter_mhc", return_value=True), + patch.object(mhc, "_AITER_MHC_ACTIVE_LOGGED", False), + ): + actual = mhc._mhc_pre_dispatch( + residual=residual, + fn=fn, + hc_scale=hc_scale, + hc_base=hc_base, + rms_eps=1e-6, + hc_pre_eps=1e-5, + hc_sinkhorn_eps=1e-5, + hc_post_mult_value=2.0, + sinkhorn_repeat=20, + norm_weight=norm_weight, + norm_eps=1e-4, + ) + + assert actual[0] is expected[0] + assert actual[1] is expected[1] + assert actual[2] is expected[2] + assert actual[3] is True + fake_pre.assert_called_once_with( + residual, + fn, + hc_scale, + hc_base, + 1e-6, + 1e-5, + 1e-5, + 2.0, + 20, + norm_weight=norm_weight, + norm_eps=1e-4, + ) + + +def test_aiter_mhc_post_dispatch_uses_preallocated_output(): + x = torch.randn(2, 8) + residual = torch.randn(2, 4, 8) + post = torch.randn(2, 4, 1) + comb = torch.randn(2, 4, 4) + + def fake_post(out, x_arg, residual_arg, post_arg, comb_arg): + assert x_arg is x + assert residual_arg is residual + assert post_arg is post + assert comb_arg is comb + out.copy_(residual + 1) + + with ( + patch.dict(sys.modules, _fake_aiter_mhc_module(mhc_post=fake_post)), + patch.object(mhc, "_use_aiter_mhc", return_value=True), + ): + actual = mhc._mhc_post_dispatch(x, residual, post, comb) + + torch.testing.assert_close(actual, residual + 1) + + +class _AddOneNorm(nn.Module): + def __init__(self, hidden_size): + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.variance_epsilon = 1e-6 + + def forward(self, x): + return x + 1 + + +def test_mhc_state_uses_optional_fused_attention_to_mlp_boundary(): + hidden_states = torch.randn(2, 8) + residual = torch.randn(2, 32) + next_hidden_states = torch.randn(2, 8) + next_residual = torch.randn(2, 32) + next_h_res = torch.randn(2, 16) + next_h_post = torch.randn(2, 4) + fused = MagicMock( + return_value=( + next_hidden_states, + next_residual, + next_h_res, + next_h_post, + False, + ) + ) + initial_h_res = torch.randn(2, 16) + initial_h_post = torch.randn(2, 4) + state = MHCState( + hc_mult=4, + hc_attn_pre=MagicMock(), + hc_ffn_pre=MagicMock(side_effect=AssertionError("unfused pre called")), + hc_post=MagicMock(side_effect=AssertionError("unfused post called")), + hc_attn_to_mlp=fused, + h_res=initial_h_res, + h_post=initial_h_post, + ) + norm = _AddOneNorm(8) + + actual_hidden_states, actual_residual = state.attn_to_mlp( + hidden_states, residual, norm + ) + + torch.testing.assert_close(actual_hidden_states, next_hidden_states + 1) + assert actual_residual is next_residual + assert state.h_res is next_h_res + assert state.h_post is next_h_post + fused.assert_called_once() + call_args = fused.call_args.args + assert call_args[0] is hidden_states + assert call_args[1] is residual + assert call_args[2] is initial_h_res + assert call_args[3] is initial_h_post + torch.testing.assert_close(call_args[4], norm.weight) + assert call_args[5] == norm.variance_epsilon + + +def test_glm_aiter_mhc_boundary_preserves_communicator_shapes(): + layer = Glm5NextDecoderLayer.__new__(Glm5NextDecoderLayer) + nn.Module.__init__(layer) + layer.config = SimpleNamespace( + hc_mult=4, + rms_norm_eps=1e-6, + hc_eps=1e-5, + hc_sinkhorn_iters=20, + ) + layer.hc_ffn_fn = nn.Parameter(torch.randn(24, 32)) + layer.hc_ffn_scale = nn.Parameter(torch.randn(3)) + layer.hc_ffn_base = nn.Parameter(torch.randn(24)) + + hidden_states = torch.randn(2, 8) + residual = torch.randn(2, 32) + h_res = torch.randn(2, 16) + h_post = torch.randn(2, 4) + next_residual = torch.randn(2, 4, 8) + next_hidden_states = torch.randn(2, 8) + next_h_post = torch.randn(2, 4) + next_h_res = torch.randn(2, 4, 4) + + with ( + patch( + "sglang.srt.models.deepseek_common.amd.deepseek_v4_fused_mhc.apply_mhc_post_pre_boundary", + return_value=( + next_residual, + next_hidden_states, + next_h_post, + next_h_res, + True, + ), + ) as fused, + patch.object(glm5_next, "_GLM_AITER_FUSED_MHC_LOGGED", False), + ): + actual = layer.hc_attn_to_mlp( + hidden_states, + residual, + h_res, + h_post, + torch.ones(8), + 1e-6, + ) + + actual_hidden, actual_residual, actual_h_res, actual_h_post, norm_fused = actual + assert actual_hidden is next_hidden_states + torch.testing.assert_close(actual_residual, next_residual.reshape(2, 32)) + torch.testing.assert_close(actual_h_res, next_h_res.reshape(2, 16)) + torch.testing.assert_close(actual_h_post, next_h_post) + assert norm_fused + assert fused.call_args.kwargs["fn_transpose"] is True + assert fused.call_args.kwargs["residual"].shape == (2, 4, 8) diff --git a/test/registered/unit/models/test_glm5_next_weight_loading.py b/test/registered/unit/models/test_glm5_next_weight_loading.py new file mode 100644 index 0000000000000..b6d90b5b4ce8a --- /dev/null +++ b/test/registered/unit/models/test_glm5_next_weight_loading.py @@ -0,0 +1,54 @@ +import unittest +from types import SimpleNamespace +from unittest.mock import patch + +import torch + +from sglang.srt.models.glm5_next import Glm5NextForConditionalGeneration +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="base-a-test-cpu") + + +class _FakeParam: + def __init__(self): + self.loaded = None + + def weight_loader(self, param, loaded_weight): + self.loaded = loaded_weight + + +class TestGlm5NextWeightLoading(unittest.TestCase): + @patch("sglang.srt.models.glm5_next.DeepseekV2WeightLoaderMixin.post_load_weights") + def test_quark_block_fp8_weight_scale_loads_scale_inv(self, post_load): + scale_param = _FakeParam() + model = SimpleNamespace( + config=SimpleNamespace( + n_routed_experts=0, + num_hidden_layers=45, + num_nextn_predict_layers=1, + ), + num_fused_shared_experts=0, + quant_config=None, + named_parameters=lambda: iter( + [("model.layers.0.mlp.down_proj.weight_scale_inv", scale_param)] + ), + ) + loaded_scale = torch.arange(6, dtype=torch.float32).reshape(2, 3) + + Glm5NextForConditionalGeneration.load_weights( + model, + [ + ( + "model.language_model.layers.0.mlp.down_proj.weight_scale", + loaded_scale, + ) + ], + ) + + self.assertIs(scale_param.loaded, loaded_scale) + post_load.assert_called_once() + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/unit/models/test_nope_mha_k_cast.py b/test/registered/unit/models/test_nope_mha_k_cast.py index 5e9cfef4f908f..7b5c6748327c0 100644 --- a/test/registered/unit/models/test_nope_mha_k_cast.py +++ b/test/registered/unit/models/test_nope_mha_k_cast.py @@ -5,7 +5,10 @@ import pytest import torch -from sglang.srt.models.deepseek_common.attention_forward_methods import forward_mha +from sglang.srt.models.deepseek_common.attention_forward_methods import ( + forward_mha, + forward_mha_rocm, +) from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci( @@ -48,5 +51,20 @@ def test_nope_mha_k_cast(backend, kv_cache_dtype, pool_dtype, expected_dtype): assert out.dtype == expected_dtype +@pytest.mark.parametrize("k_pe", [None, torch.empty(4, 1, 0)]) +def test_nope_mha_k_rocm_skips_empty_rope_tail(k_pe): + fake_self = SimpleNamespace(qk_rope_head_dim=0) + k_nope = torch.randn(4, 2, 128, dtype=torch.bfloat16) + + out = forward_mha_rocm.DeepseekMHARocmForwardMixin._concat_and_cast_mha_k_rocm( + fake_self, + k_nope, + k_pe, + ) + + torch.testing.assert_close(out, k_nope) + assert out.is_contiguous() + + if __name__ == "__main__": sys.exit(pytest.main([__file__])) diff --git a/test/registered/unit/models/test_shared_experts_fusion_gates.py b/test/registered/unit/models/test_shared_experts_fusion_gates.py index 65d06092ad73a..d4723ad005101 100644 --- a/test/registered/unit/models/test_shared_experts_fusion_gates.py +++ b/test/registered/unit/models/test_shared_experts_fusion_gates.py @@ -192,6 +192,62 @@ def test_the_dsa_variant_declares_its_own_architecture(self): ) +class TestGlm5NextGate(_FusionGateCase): + def _config(self): + return SimpleNamespace(n_shared_experts=1) + + def _reason_for_backend( + self, + *, + is_cuda=False, + use_aiter_gfx95=False, + device_sm=None, + moe_ep_size=1, + deepep=False, + ): + import sglang.srt.models.glm5_next as glm5_next + + backend = SimpleNamespace(is_deepep=lambda: deepep) + with ( + unittest.mock.patch.object(glm5_next, "_is_cuda", is_cuda), + unittest.mock.patch.object(glm5_next, "_use_aiter_gfx95", use_aiter_gfx95), + unittest.mock.patch.object(glm5_next, "_device_sm", device_sm), + unittest.mock.patch.object( + glm5_next, "get_moe_a2a_backend", return_value=backend + ), + ): + return self._reason( + glm5_next.Glm5NextForConditionalGeneration, + self._config(), + moe_ep_size=moe_ep_size, + ) + + def test_aiter_gfx95_enables_shared_expert_fusion(self): + self.assertIsNone(self._reason_for_backend(use_aiter_gfx95=True)) + + def test_unsupported_non_cuda_backend_disables_shared_expert_fusion(self): + self.assertIn("requires CUDA", self._reason_for_backend()) + + def test_cuda_sm80_path_is_unchanged(self): + self.assertIsNone(self._reason_for_backend(is_cuda=True, device_sm=80)) + self.assertIn( + "SM80 or newer", + self._reason_for_backend(is_cuda=True, device_sm=75), + ) + + def test_expert_parallelism_still_disables_shared_expert_fusion(self): + self.assertIn( + "expert parallelism", + self._reason_for_backend(use_aiter_gfx95=True, moe_ep_size=2), + ) + + def test_deepep_still_disables_shared_expert_fusion(self): + self.assertIn( + "Deepep", + self._reason_for_backend(use_aiter_gfx95=True, deepep=True), + ) + + class TestMiniMaxGates(_FusionGateCase): def test_a_config_without_shared_experts_cannot_fuse(self): from sglang.srt.models.minimax_m3 import MiniMaxM3SparseForCausalLM diff --git a/test/registered/unit/server_args/test_server_args.py b/test/registered/unit/server_args/test_server_args.py index 252e2234ef472..b07eb6f55e789 100644 --- a/test/registered/unit/server_args/test_server_args.py +++ b/test/registered/unit/server_args/test_server_args.py @@ -740,6 +740,74 @@ def test_skip_tokenizer_worker_counts(self): self.assertEqual(resolution_result(server_args, "detokenizer_worker_num"), 1) +class TestRocmDsaTopKCompatibility(CustomTestCase): + def test_gfx942_defaults_to_torch_unfused_topk(self): + args = ServerArgs(model_path="dummy") + + with ( + envs.SGLANG_DSA_FUSE_TOPK.override(True), + patch.object(server_args_module, "is_hip", return_value=True), + patch.object(server_args_module, "is_gfx95_supported", return_value=False), + ): + args._handle_rocm_dsa_topk_compatibility() + + self.assertEqual(resolution_result(args, "dsa_topk_backend"), "torch") + self.assertEqual( + resolution_result(args, "speculative_dsa_topk_backend"), + "sgl-kernel", + ) + self.assertFalse(envs.SGLANG_DSA_FUSE_TOPK.get()) + + def test_gfx950_keeps_sgl_kernel_fused_topk(self): + args = ServerArgs(model_path="dummy") + + with ( + envs.SGLANG_DSA_FUSE_TOPK.override(True), + patch.object(server_args_module, "is_hip", return_value=True), + patch.object(server_args_module, "is_gfx95_supported", return_value=True), + ): + args._handle_rocm_dsa_topk_compatibility() + + self.assertEqual(resolution_result(args, "dsa_topk_backend"), "sgl-kernel") + self.assertEqual( + resolution_result(args, "speculative_dsa_topk_backend"), + "sgl-kernel", + ) + self.assertTrue(envs.SGLANG_DSA_FUSE_TOPK.get()) + + def test_cuda_and_explicit_backends_are_unchanged(self): + cuda_args = ServerArgs(model_path="dummy") + explicit_args = ServerArgs( + model_path="dummy", + dsa_topk_backend="torch", + speculative_dsa_topk_backend="flashinfer", + ) + + with envs.SGLANG_DSA_FUSE_TOPK.override(True): + with patch.object(server_args_module, "is_hip", return_value=False): + cuda_args._handle_rocm_dsa_topk_compatibility() + self.assertEqual( + resolution_result(cuda_args, "dsa_topk_backend"), "sgl-kernel" + ) + self.assertTrue(envs.SGLANG_DSA_FUSE_TOPK.get()) + + with ( + patch.object(server_args_module, "is_hip", return_value=True), + patch.object( + server_args_module, "is_gfx95_supported", return_value=False + ), + ): + explicit_args._handle_rocm_dsa_topk_compatibility() + self.assertEqual( + resolution_result(explicit_args, "dsa_topk_backend"), "torch" + ) + self.assertEqual( + resolution_result(explicit_args, "speculative_dsa_topk_backend"), + "flashinfer", + ) + self.assertTrue(envs.SGLANG_DSA_FUSE_TOPK.get()) + + class TestHiSparseDsaBackendPolicy(unittest.TestCase): # The backend selection moved to the resolution pipeline; these policy # tests drive the pass through its read-only view. From 6611363be5111b1a4bd48aa806d4c98490dca950 Mon Sep 17 00:00:00 2001 From: Ehsan Akhgari Date: Fri, 28 Aug 2026 16:34:17 -0400 Subject: [PATCH 09/44] fix(glm): mirror should_use_dp_reduce_scatterv() into the MHC communicator (#36884) Co-authored-by: Claude Fable 5 --- python/sglang/srt/layers/communicator_mhc.py | 26 +++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/python/sglang/srt/layers/communicator_mhc.py b/python/sglang/srt/layers/communicator_mhc.py index 228292dbfa6dd..4c3ea020ca1fb 100644 --- a/python/sglang/srt/layers/communicator_mhc.py +++ b/python/sglang/srt/layers/communicator_mhc.py @@ -52,10 +52,12 @@ dp_gather_replicate, dp_reduce_scatter_tensor, dp_scatter, + get_dp_global_num_tokens, get_global_dp_buffer, get_local_dp_buffer_mhc, is_allocation_symmetric, ) +from sglang.srt.layers.moe import should_use_dp_reduce_scatterv from sglang.srt.model_executor.forward_batch_info import ForwardBatch @@ -365,7 +367,19 @@ def _scatter_hidden_states( get_local_dp_buffer_mhc(get_tp_group(), 1), hidden_states, ) - if allow_reduce_scatter and forward_batch.dp_padding_mode.is_max_len(): + # Mirror CommunicateSummableTensorPairFn._scatter_hidden_states: when + # should_use_dp_reduce_scatterv() is true, the MoE skipped its + # post-experts all-reduce (should_skip_post_experts_all_reduce) on the + # promise that THIS scatter performs the combine. Without this branch, + # SUM_LEN rounds take the non-reducing dp_scatter and every DP rank's + # tokens keep only that rank's local-expert partial sums. + if should_use_dp_reduce_scatterv(): + get_tp_group().reduce_scatterv( + global_hidden_states, + output=hidden_states, + sizes=get_dp_global_num_tokens(), + ) + elif allow_reduce_scatter and forward_batch.dp_padding_mode.is_max_len(): dp_reduce_scatter_tensor(hidden_states, global_hidden_states) else: dp_scatter(hidden_states, global_hidden_states, forward_batch) @@ -581,9 +595,15 @@ def should_use_reduce_scatter(self, forward_batch: ForwardBatch): if ( self._communicate_summable_tensor_pair_fn is MHCCommunicateSummableTensorPairFn._scatter_hidden_states - and forward_batch.dp_padding_mode.is_max_len() ): - return True + # Mirror LayerCommunicator.should_use_reduce_scatter (PR #24785): + # True on should_use_dp_reduce_scatterv() regardless of padding + # mode, else RowParallelLinear keeps all-reducing the dense MLP + # while the scatter above reduce-scatters on top of it. + if should_use_dp_reduce_scatterv(): + return True + if forward_batch.dp_padding_mode.is_max_len(): + return True if dsa_use_prefill_cp(forward_batch): return True From e1887489c4427a4f30c5d5356bfcc1da5589a9b2 Mon Sep 17 00:00:00 2001 From: Ehsan Akhgari Date: Fri, 28 Aug 2026 19:15:57 -0400 Subject: [PATCH 10/44] fix(kda): stop remapping the -1 padding sentinel onto a live mamba slot (#36885) Co-authored-by: Claude Fable 5 --- .../layers/attention/linear/kernels/kda_triton.py | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/python/sglang/srt/layers/attention/linear/kernels/kda_triton.py b/python/sglang/srt/layers/attention/linear/kernels/kda_triton.py index 6c6c3788fd2a7..c010af5953638 100644 --- a/python/sglang/srt/layers/attention/linear/kernels/kda_triton.py +++ b/python/sglang/srt/layers/attention/linear/kernels/kda_triton.py @@ -231,13 +231,10 @@ def extend( return_intermediate_states: bool = False, **kwargs, ) -> torch.Tensor: - # CP/DP padding marks zero-length requests with -1. The Triton state - # kernel performs raw pointer arithmetic on these indices, so route - # padding to MambaPool's trailing sentinel slot instead of indexing - # before the state pool. - ssm_cache_indices = torch.where( - cache_indices >= 0, cache_indices, ssm_states.shape[0] - 1 - ).to(torch.int32) + # CP/DP padding marks zero-length requests with -1, which + # chunk_gated_delta_rule_fwd_h skips (`valid_state = index >= 0` gates + # both the initial-state load and the in-place final-state store), so + # the sentinel is passed through unmodified as on the non-GLM path. return chunk_kda( q=q, k=k, @@ -245,7 +242,7 @@ def extend( g=g, beta=beta, initial_state=ssm_states, - initial_state_indices=ssm_cache_indices, + initial_state_indices=cache_indices, use_qk_l2norm_in_kernel=True, cu_seqlens=query_start_loc, A_log=A_log, From 7fa1924c04487feffc3f5f111a424ec1f0b22362 Mon Sep 17 00:00:00 2001 From: Xinyuan Tong Date: Sat, 29 Aug 2026 14:29:27 +0000 Subject: [PATCH 11/44] style: prune restating comments and drop mock self-asserting tests Delete comments/docstrings that restate the code across the GLM-5.3-Flash support diff, and drop three registered unit tests that only assert their own mocks: test_mhc_deep_gemm_gate, test_glm5_next_hybrid_pool, test_glm5_next_dcp. --- .../jit/csrc/dsa/kpool_topk_transform.cuh | 85 ++------ .../ops/attention/dsa/transform_index.py | 4 +- .../kernels/ops/attention/dsa_metadata.py | 88 +------- .../sglang/kernels/ops/kvcache/mla_buffer.py | 7 - python/sglang/kernels/ops/layernorm/mhc.py | 32 +-- .../kernels/ops/moe/kpool_topk_transform.py | 9 - .../sglang/kernels/ops/speculative/eagle.py | 18 +- python/sglang/srt/configs/model_config.py | 7 +- python/sglang/srt/disaggregation/decode.py | 1 - .../disaggregation/encoder/preprocessor.py | 3 - python/sglang/srt/disaggregation/nixl/conn.py | 11 +- python/sglang/srt/disaggregation/utils.py | 21 +- .../srt/entrypoints/openai/serving_chat.py | 16 +- python/sglang/srt/environ.py | 6 +- .../srt/layers/attention/dsa/dsa_indexer.py | 4 +- .../layers/attention/dsa/dsa_indexer_kpool.py | 17 +- .../layers/attention/dsa/kpool_fp8_index.py | 44 ++-- .../srt/layers/attention/dsa/kpool_plan.py | 35 +--- .../sglang/srt/layers/attention/dsa/utils.py | 120 ++--------- .../srt/layers/attention/dsa_backend.py | 198 ++---------------- .../attention/flashattention_backend.py | 5 +- .../attention/flashinfer_mla_backend.py | 30 +-- .../attention/hybrid_linear_attn_backend.py | 10 +- .../layers/attention/linear/kda_backend.py | 15 +- .../attention/linear/kernels/kda_flashkda.py | 5 +- .../attention/linear/kernels/kda_triton.py | 6 +- python/sglang/srt/layers/communicator.py | 10 +- .../sglang/srt/layers/communicator_dsa_cp.py | 7 +- python/sglang/srt/layers/communicator_mhc.py | 43 +--- .../srt/layers/communicator_mhc_hybrid_cp.py | 31 ++- .../srt/layers/quantization/quark/utils.py | 5 +- python/sglang/srt/managers/scheduler.py | 5 +- .../sglang/srt/managers/tokenizer_manager.py | 20 +- .../hybrid_cache/hybrid_pool_assembler.py | 1 - .../srt/mem_cache/kv_cache_configurator.py | 2 - python/sglang/srt/mem_cache/memory_pool.py | 12 +- python/sglang/srt/mem_cache/radix_cache.py | 6 +- .../attention_forward_methods/forward_mha.py | 5 +- python/sglang/srt/models/glm5_next.py | 51 ++--- python/sglang/srt/models/glm5_next_nextn.py | 13 +- python/sglang/srt/multimodal/mm_utils.py | 6 +- .../multimodal/processors/base_processor.py | 4 +- .../sglang/srt/multimodal/processors/glm4v.py | 40 +--- .../sglang/srt/parser/jinja_template_utils.py | 22 +- python/sglang/srt/parser/template_manager.py | 1 - .../eagle_draft_extend_cuda_graph_runner.py | 4 +- python/sglang/srt/speculative/eagle_utils.py | 4 +- .../srt/speculative/eagle_worker_common.py | 5 +- .../sglang/srt/speculative/eagle_worker_v2.py | 27 +-- python/sglang/srt/speculative/spec_utils.py | 61 +----- python/sglang/srt/utils/video_decoder.py | 1 - .../unit/layers/test_mhc_deep_gemm_gate.py | 89 -------- .../mem_cache/test_glm5_next_hybrid_pool.py | 121 ----------- .../unit/models/test_glm5_next_dcp.py | 49 ----- 54 files changed, 203 insertions(+), 1239 deletions(-) delete mode 100644 test/registered/unit/layers/test_mhc_deep_gemm_gate.py delete mode 100644 test/registered/unit/mem_cache/test_glm5_next_hybrid_pool.py delete mode 100644 test/registered/unit/models/test_glm5_next_dcp.py diff --git a/python/sglang/kernels/jit/csrc/dsa/kpool_topk_transform.cuh b/python/sglang/kernels/jit/csrc/dsa/kpool_topk_transform.cuh index f49d4ac0d4af9..995a75dab19bb 100644 --- a/python/sglang/kernels/jit/csrc/dsa/kpool_topk_transform.cuh +++ b/python/sglang/kernels/jit/csrc/dsa/kpool_topk_transform.cuh @@ -1,17 +1,9 @@ -/** - * @NOTE: The radix top-k core (fast_topk_cuda_tl_impl) is adapted from - * https://github.com/tile-ai/tilelang/blob/main/examples/deepseek_v32/topk_selector.py - * and was previously shipped as an AOT sgl-kernel op (fast_kpool_topk_transform_fused). - * It is re-implemented here as a lightweight JIT kernel for the NSA kpool indexer: - * select pool groups at pool granularity, expand each group to `pool_size` token - * indices, and optionally transform those indices through a page table or ragged offset. - * - * The pool-level top-k value is a compile-time constant injected via -DSGL_GROUP_TOPK. - */ -#include // For TensorMatcher, SymbolicSize, SymbolicDevice, is_type -#include // For RuntimeCheck, RuntimeDeviceCheck - -#include // For LaunchKernel, type aliases +// Radix top-k core adapted from https://github.com/tile-ai/tilelang/blob/main/examples/deepseek_v32/topk_selector.py. +// This JIT variant adds pool expansion and page-table/ragged-offset transforms. +#include +#include + +#include #include #include @@ -36,13 +28,9 @@ namespace { #define SGL_GROUP_TOPK 256 #endif -// Compile-time pool-level top-k (number of groups selected per row). inline constexpr int kGroupTopK = SGL_GROUP_TOPK; inline constexpr int kThreadsPerBlock = 1024; -// Reduced from 128KB to 32KB to improve occupancy. -// Each radix pass needs at most ~K candidates in the threshold bin, -// so 4K entries per round (2 rounds = 8K entries = 32KB) is sufficient. inline constexpr std::size_t kSmem = 8 * 1024 * sizeof(uint32_t); // 32KB (bytes) struct FastTopKParams { @@ -68,7 +56,6 @@ __device__ __forceinline__ auto convert_to_uint32(float x) -> uint32_t { template __device__ void fast_topk_cuda_tl_impl(const float* __restrict__ input, int* __restrict__ index, int row_start, int length) { - // An optimized topk kernel copied from tilelang kernel // We assume length > K here, or it will crash int topk = K; constexpr auto BLOCK_SIZE = 1024; @@ -81,12 +68,10 @@ fast_topk_cuda_tl_impl(const float* __restrict__ input, int* __restrict__ index, alignas(128) __shared__ int s_num_input[2]; auto& s_histogram = s_histogram_buf[0]; - // allocate for two rounds extern __shared__ int s_input_idx[][SMEM_INPUT_SIZE]; const int tx = threadIdx.x; - // stage 1: 8bit coarse histogram if (tx < RADIX + 1) s_histogram[tx] = 0; __syncthreads(); @@ -149,7 +134,6 @@ fast_topk_cuda_tl_impl(const float* __restrict__ input, int* __restrict__ index, index[pos] = idx; } else if (bin == threshold_bin) { const auto pos = ::atomicAdd(&s_num_input[0], 1); - /// NOTE: (dark) fuse the histogram computation here if (C10_LIKELY(pos < SMEM_INPUT_SIZE)) { s_input_idx[0][pos] = idx; const auto bin = convert_to_uint32(raw_input); @@ -161,13 +145,11 @@ fast_topk_cuda_tl_impl(const float* __restrict__ input, int* __restrict__ index, __syncthreads(); } - // stage 2: refine with 8bit radix passes #pragma unroll 4 for (int round = 0; round < 4; ++round) { __shared__ int s_last_remain; const auto r_idx = round % 2; - // clip here to prevent overflow const auto _raw_num_input = s_num_input[r_idx]; const auto num_input = (_raw_num_input < int(SMEM_INPUT_SIZE)) ? _raw_num_input : int(SMEM_INPUT_SIZE); @@ -217,7 +199,6 @@ fast_topk_cuda_tl_impl(const float* __restrict__ input, int* __restrict__ index, } else { const auto pos = ::atomicAdd(&s_num_input[r_idx ^ 1], 1); if (C10_LIKELY(pos < SMEM_INPUT_SIZE)) { - /// NOTE: (dark) fuse the histogram computation here s_input_idx[r_idx ^ 1][pos] = idx; const auto bin = convert_to_uint32(raw_input); const auto sub_bin = (bin >> (offset - 8)) & 0xFF; @@ -333,15 +314,6 @@ const T* optional_data_ptr(const tvm::ffi::Optional& opt) struct KpoolTopKTransformKernel { static constexpr auto kernel = kpool_topk_transform_kernel; - // Pool-level radix top-k for the NSA kpool indexer. - // score : [B, S] strided float32 scores (one score per pool group) - // lengths : [B] int32 valid group count per row - // dst_token_indices : [B, out_cols] int32 output token indices (contiguous) - // pool_size : tokens per pool group - // page_table (opt) : [B, P] strided int32 raw-token -> real-token map - // topk_indices_offset : [B] int32 per-row offset added to raw tokens (ragged) - // row_starts (opt) : [B] int32 score row start offsets - // seq_lens (opt) : [B] int32 sequence lengths; enables tail append static void transform( const tvm::ffi::TensorView score, const tvm::ffi::TensorView lengths, @@ -360,19 +332,9 @@ struct KpoolTopKTransformKernel { auto device = SymbolicDevice{}; device.set_options(); - TensorMatcher({B, -1}) // strided scores - .with_strides({S, 1}) - .with_dtype() - .with_device(device) - .verify(score); - TensorMatcher({B}) // lengths, contiguous int32 - .with_dtype() - .with_device(device) - .verify(lengths); - TensorMatcher({B, out_cols_sym}) // output, contiguous int32 - .with_dtype() - .with_device(device) - .verify(dst_token_indices); + TensorMatcher({B, -1}).with_strides({S, 1}).with_dtype().with_device(device).verify(score); + TensorMatcher({B}).with_dtype().with_device(device).verify(lengths); + TensorMatcher({B, out_cols_sym}).with_dtype().with_device(device).verify(dst_token_indices); RuntimeCheck(pool_size > 1, "pool_size must be > 1, got ", pool_size); RuntimeCheck( @@ -402,45 +364,30 @@ struct KpoolTopKTransformKernel { auto P = SymbolicSize{"page_table_stride"}; if (page_table_row_index_opt.has_value()) { auto page_table_rows = SymbolicSize{"page_table_rows"}; - TensorMatcher({page_table_rows, -1}) // compact shared page table + TensorMatcher({page_table_rows, -1}) .with_strides({P, 1}) .with_dtype() .with_device(device) .verify(page_table_opt.value()); } else { - TensorMatcher({B, -1}) // one page-table row per score row - .with_strides({P, 1}) - .with_dtype() - .with_device(device) - .verify(page_table_opt.value()); + TensorMatcher({B, -1}).with_strides({P, 1}).with_dtype().with_device(device).verify( + page_table_opt.value()); } page_table_ptr = static_cast(page_table_opt.value().data_ptr()); page_table_stride = static_cast(P.unwrap()); } if (topk_indices_offset_opt.has_value()) { - TensorMatcher({B}) // - .with_dtype() - .with_device(device) - .verify(topk_indices_offset_opt.value()); + TensorMatcher({B}).with_dtype().with_device(device).verify(topk_indices_offset_opt.value()); } if (row_starts_opt.has_value()) { - TensorMatcher({B}) // - .with_dtype() - .with_device(device) - .verify(row_starts_opt.value()); + TensorMatcher({B}).with_dtype().with_device(device).verify(row_starts_opt.value()); } if (seq_lens_opt.has_value()) { - TensorMatcher({B}) // - .with_dtype() - .with_device(device) - .verify(seq_lens_opt.value()); + TensorMatcher({B}).with_dtype().with_device(device).verify(seq_lens_opt.value()); } if (page_table_row_index_opt.has_value()) { - TensorMatcher({B}) // - .with_dtype() - .with_device(device) - .verify(page_table_row_index_opt.value()); + TensorMatcher({B}).with_dtype().with_device(device).verify(page_table_row_index_opt.value()); } const auto params = FastTopKParams{ diff --git a/python/sglang/kernels/ops/attention/dsa/transform_index.py b/python/sglang/kernels/ops/attention/dsa/transform_index.py index f30c357c06b77..d9c1226d023f0 100644 --- a/python/sglang/kernels/ops/attention/dsa/transform_index.py +++ b/python/sglang/kernels/ops/attention/dsa/transform_index.py @@ -233,9 +233,7 @@ def transform_index_page_table_decode_fast( result = torch.empty_like(topk_indices, dtype=torch.int32) topk = topk_indices.shape[1] if topk == 2048: - # Preserve the existing single-program fast path for the standard DSA - # width. KPool can append a live partial-pool tail, which is handled by - # the generic tiled path below without changing this common path. + # Keep the 2048-wide fast path; KPool tail widths use the tiled kernel. transform_index_page_table_decode_kernel[(qo_len,)]( page_table, topk_indices, diff --git a/python/sglang/kernels/ops/attention/dsa_metadata.py b/python/sglang/kernels/ops/attention/dsa_metadata.py index cc79645d70e1d..8d029b61423b3 100644 --- a/python/sglang/kernels/ops/attention/dsa_metadata.py +++ b/python/sglang/kernels/ops/attention/dsa_metadata.py @@ -4,25 +4,12 @@ import triton import triton.language as tl -# Target page-table tile-program count per launch for the bounded column scan -# below. Enough programs to saturate a datacenter GPU for this copy kernel, -# while the dispatch cost of a full grid of idle programs stays at a few -# microseconds. +# Bound the replay grid while retaining enough copy programs to saturate the GPU. _TILE_PROGRAM_TARGET = 8192 def _bounded_scan_num_splits(rows: int, num_col_blocks: int) -> int: - """Column-split factor for the bounded page-table scan. - - Each of ``rows`` output rows gets this many tile programs; program ``s`` - of a row covers column blocks ``s, s + splits, s + 2*splits, ...`` up to - the row's own kv length, which the kernel reads at run time. The grid is - therefore data-independent (CUDA-graph-safe by construction) while the - traversal is bounded by the live data: dispatch scales with - ``rows * splits`` instead of ``rows * table_width / BLOCK_N``. The factor - never exceeds the full-width column-block count, so the grid is never - larger than the full-width scan's. - """ + """Keep the grid capture-safe while bounding traversal by replay-time data.""" assert rows > 0 return max(1, min(num_col_blocks, _TILE_PROGRAM_TARGET // rows)) @@ -74,10 +61,7 @@ def _fused_dsa_decode_metadata_kernel( if index_kpool <= 1: dsa_seq = tl.minimum(seq_i32, dsa_index_topk) else: - # Match compute_dsa_seqlens exactly (same formula as the - # target-verify kernel below): select complete history pools up - # to top-k, then retain the partial trailing pool. In - # particular, topk+pool-1 -> topk+pool-1 while topk+pool -> topk. + # Preserve the live partial pool after selecting pool-aligned history. full_pool_tokens = (seq_i32 // index_kpool) * index_kpool selected_history_tokens = tl.minimum(full_pool_tokens, dsa_index_topk) tail_tokens = seq_i32 - full_pool_tokens @@ -108,23 +92,10 @@ def _fused_dsa_decode_metadata_kernel( mask=row < bs, other=0, ).to(tl.int32) - # Same int64 row-term promotion as the target-verify and draft-extend - # kernels below: the wide table's row stride is ~max_context_len (2^20 + - # headroom on 1M-context models), so the int32 product row * stride wraps - # negative once row reaches 2^31 / stride (~2048). Decode rows equal the - # batch size, so today's graph buckets stay below the wrap, but the store - # math should not depend on that. + # Page-table row offsets can overflow int32 at 1M context. row_i64 = row.to(tl.int64) - # Bounded traversal: scan only up to this row's kv length, read here at - # run (replay) time. Column blocks past kv_len hold no consumer-visible - # data (attention and the indexer both stay within cache_seqlens), so the - # write set is identical to a full-width scan that early-exits dead - # blocks; what changes is that those blocks are never dispatched. num_live_blocks = tl.minimum(tl.cdiv(kv_len, BLOCK_N), tl.cdiv(max_len, BLOCK_N)) - # num_stages: this dot-free copy loop is not software-pipelined by - # default, which would leave one load in flight per warp and make - # multi-iteration rows (long contexts at high row counts) latency-bound; - # explicit staging turns the loads into multi-buffered async copies. + # Three stages hide latency across strided copy iterations. for col_block in tl.range(split_id, num_live_blocks, num_splits, num_stages=3): offs_n = col_block * BLOCK_N + tl.arange(0, BLOCK_N) mask = (row < bs) & (offs_n < max_len) @@ -135,9 +106,6 @@ def _fused_dsa_decode_metadata_kernel( mask=mask, other=0, ).to(tl.int32) - # Write the wide page_size=1 table only when the caller provides it; - # the fused decode CUDA graph drops it and consumes real_page_table - # alone. if HAS_PAGE_TABLE_1: tl.store( page_table_1 @@ -334,9 +302,7 @@ def _fused_dsa_target_verify_metadata_kernel( if index_kpool <= 1: dsa_seq = tl.minimum(expanded_seq, dsa_index_topk) else: - # Match compute_dsa_seqlens exactly: select complete history pools - # up to top-k, then retain the partial trailing pool. In - # particular, topk+pool-1 -> topk+pool-1 while topk+pool -> topk. + # Preserve the live partial pool after selecting pool-aligned history. full_pool_tokens = (expanded_seq // index_kpool) * index_kpool selected_history_tokens = tl.minimum(full_pool_tokens, dsa_index_topk) tail_tokens = expanded_seq - full_pool_tokens @@ -376,23 +342,11 @@ def _fused_dsa_target_verify_metadata_kernel( ).to(tl.int32) + next_n ) - # Promote the row term to int64 before the pointer add: the wide table's - # row stride is ~max_context_len (2^20 + headroom for 1M-context models), - # so the int32 product out_row * stride wraps negative from - # out_row == 2048 (expanded rows = bs * next_n > 2048), sending the - # stores below wild. The column term stays int32 (bounded by the row - # stride itself). + # Output-row offsets can overflow int32 at 1M context. out_row_i64 = out_row.to(tl.int64) - # Bounded traversal: scan only up to this row's kv length - # (seq_len + next_n), read here at run (replay) time. Column blocks past - # kv_len hold no consumer-visible data (attention and the indexer stay - # within cache_seqlens), so the write set is identical to a full-width - # scan that early-exits dead blocks; what changes is that those blocks - # are never dispatched. num_live_blocks = tl.minimum( tl.cdiv(kv_len, BLOCK_N), tl.cdiv(max_seqlen_k, BLOCK_N) ) - # num_stages: see the decode kernel above. for col_block in tl.range(split_id, num_live_blocks, num_splits, num_stages=3): offs_n = col_block * BLOCK_N + tl.arange(0, BLOCK_N) mask = (out_row < expanded_size) & (offs_n < max_seqlen_k) @@ -403,9 +357,6 @@ def _fused_dsa_target_verify_metadata_kernel( mask=mask, other=0, ).to(tl.int32) - # Write the wide page_size=1 table only when the caller provides it - # (see fused_dsa_decode_metadata for the optional-page_table_1 - # contract). if HAS_PAGE_TABLE_1: tl.store( page_table_1 @@ -446,9 +397,6 @@ def _prep_fused_dsa_target_verify_metadata_launch( paged_mqa_ctx_lens_2d: torch.Tensor = None, index_kpool: int = 1, ): - """Validate and build the (grid, args, constexpr kwargs) launch spec for - the target-verify metadata kernel (bs > 0). Shared between the per-call - wrapper below and the prebound cuda-graph replay launcher.""" assert seq_lens.is_cuda assert req_pool_indices.is_cuda assert req_to_token.is_cuda @@ -684,10 +632,7 @@ def _fused_dsa_draft_extend_metadata_kernel( if index_kpool <= 1: dsa_seq = tl.minimum(expanded_seq, dsa_index_topk) else: - # Match compute_dsa_seqlens exactly (same formula as the - # target-verify kernel above): select complete history pools up - # to top-k, then retain the partial trailing pool. In - # particular, topk+pool-1 -> topk+pool-1 while topk+pool -> topk. + # Preserve the live partial pool after selecting pool-aligned history. full_pool_tokens = (expanded_seq // index_kpool) * index_kpool selected_history_tokens = tl.minimum(full_pool_tokens, dsa_index_topk) tail_tokens = expanded_seq - full_pool_tokens @@ -714,13 +659,7 @@ def _fused_dsa_draft_extend_metadata_kernel( mask=req_row < bs, other=0, ).to(tl.int32) - # Bounded traversal: scan only up to this request's kv length, read here - # at run (replay) time. Column blocks past kv_len hold no - # consumer-visible data (attention and the indexer both stay within - # cache_seqlens), so the write set is identical to a full-width scan that - # early-exits dead blocks; what changes is that those blocks are never - # dispatched. The early return below also keeps idle programs from paying - # the dynamic-extend prefix loop. + # Bound the scan by the live replay-time kv length. num_live_blocks = tl.minimum( tl.cdiv(kv_len, BLOCK_N), tl.cdiv(max_seqlen_k, BLOCK_N) ) @@ -745,12 +684,8 @@ def _fused_dsa_draft_extend_metadata_kernel( mask=has_rows, other=0, ) - # Same int64 row-term promotion as the target-verify kernel above: - # out_rows spans bs * max_extend_len rows and the wide table's row stride - # is ~max_context_len, so the int32 product wraps negative once - # row * stride reaches 2^31. + # Output-row offsets can overflow int32 at 1M context. out_rows_i64 = out_rows.to(tl.int64) - # num_stages: see the decode kernel above. for col_block in tl.range(split_id, num_live_blocks, num_splits, num_stages=3): offs_n = col_block * BLOCK_N + tl.arange(0, BLOCK_N) col_mask = offs_n < max_seqlen_k @@ -763,9 +698,6 @@ def _fused_dsa_draft_extend_metadata_kernel( mask=col_mask & has_rows, other=0, ).to(tl.int32) - # Write the wide page_size=1 table only when the caller provides it - # (see fused_dsa_decode_metadata for the optional-page_table_1 - # contract). if HAS_PAGE_TABLE_1: tl.store( page_table_1 diff --git a/python/sglang/kernels/ops/kvcache/mla_buffer.py b/python/sglang/kernels/ops/kvcache/mla_buffer.py index 6ed36d5e8a93d..b4be4204d673c 100644 --- a/python/sglang/kernels/ops/kvcache/mla_buffer.py +++ b/python/sglang/kernels/ops/kvcache/mla_buffer.py @@ -94,7 +94,6 @@ def set_mla_kv_buffer_kernel_norope( BLOCK: tl.constexpr, USE_GDC: tl.constexpr = False, ): - """Variant of ``set_mla_kv_buffer_kernel`` for qk_rope_head_dim==0.""" pid_loc = tl.program_id(0) pid_blk = tl.program_id(1) @@ -149,11 +148,6 @@ def set_mla_kv_buffer_triton( a one-shot per CTA. This is also the path for SM<90 and for shapes that violate the TMA 16-byte alignment. - A third path is taken when ``cache_k_rope`` is None or empty - (qk_rope_head_dim==0): the dedicated ``set_mla_kv_buffer_kernel_norope`` - Triton kernel bypasses the rope branch entirely. The JIT TMA path assumes - both nope and rope are present, so it is skipped here. - Speedup vs the legacy BLOCK=128 Triton kernel on GB300 (BF16, nope=512, rope=64): ~1.05x at bs=8, ~1.5x at bs=128, 3.5x at bs=512, **11.7x at bs=16384**. @@ -461,7 +455,6 @@ def get_mla_kv_buffer_kernel_norope( nope_stride: tl.constexpr, nope_dim: tl.constexpr, ): - """Variant of ``get_mla_kv_buffer_kernel`` for qk_rope_head_dim==0.""" pid_loc = tl.program_id(0) loc = tl.load(loc_ptr + pid_loc).to(tl.int64) loc_src_ptr = kv_buffer_ptr + loc * buffer_stride diff --git a/python/sglang/kernels/ops/layernorm/mhc.py b/python/sglang/kernels/ops/layernorm/mhc.py index 870875b108c62..248d242bc7b90 100644 --- a/python/sglang/kernels/ops/layernorm/mhc.py +++ b/python/sglang/kernels/ops/layernorm/mhc.py @@ -1672,24 +1672,13 @@ def mhc_fused_post_pre( def hc_expand(x: torch.Tensor, n: int) -> torch.Tensor: - """[s, hidden_size] -> [s, n * hidden_size] by replication.""" return x.repeat(1, n) def hc_contract(x: torch.Tensor, n: int) -> torch.Tensor: - """[s, n * hidden_size] -> [s, hidden_size] by averaging.""" return x.unflatten(-1, (n, -1)).mean(dim=-2) -# --------------------------------------------------------------------------- -# Flat (2-D) MHC functional front-ends, matching the GLM reference contract so -# the communicator pipeline (MHCState / MHCLayerCommunicator) can keep hidden -# states as plain ``[tokens, n * hidden]`` 2-D tensors. The tilelang path reuses -# this module's ``mhc_pre`` / ``mhc_post`` kernels; a pure-torch reference is -# kept for fallback / numerics checks. -# --------------------------------------------------------------------------- - - def _mhc_pre_torch( residual: torch.Tensor, fn: torch.Tensor, @@ -1701,10 +1690,6 @@ def _mhc_pre_torch( hc_post_mult_value: float, sinkhorn_repeat: int, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """Pure-torch reference of mhc_pre. - - residual: (s, n, h); returns (post=(s, n, 1), comb=(s, n, n), layer_input=(s, h)). - """ import torch.nn.functional as F s, n, h = residual.shape @@ -1712,7 +1697,7 @@ def _mhc_pre_torch( x_flat = residual.view(s, n * h).float() rsqrt = torch.rsqrt(x_flat.square().mean(-1, keepdim=True) + rms_eps) - mixes = F.linear(x_flat, fn) * rsqrt # (s, mix_hc) + mixes = F.linear(x_flat, fn) * rsqrt pre_raw = mixes[:, :n] post_raw = mixes[:, n : 2 * n] @@ -1741,7 +1726,6 @@ def _mhc_post_torch( post_layer_mix: torch.Tensor, comb_res_mix: torch.Tensor, ) -> torch.Tensor: - """Pure-torch reference of mhc_post. x:(s,h) residual:(s,n,h) -> (s,n,h).""" out = post_layer_mix * x.unsqueeze(1) + ( comb_res_mix.unsqueeze(-1) * residual.unsqueeze(2) ).sum(dim=1) @@ -1762,10 +1746,6 @@ def _mhc_pre_dispatch( norm_weight: torch.Tensor | None = None, norm_eps: float | None = None, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, bool]: - """Run mhc_pre using the env-selected backend. - - Returns (post_mix=(s,n,1), comb_mix=(s,n,n), layer_input=(s,h), norm_fused). - """ assert residual.dim() == 3, f"residual must be (s, n, h); got {residual.shape}" if _use_aiter_mhc(): result = _try_aiter_mhc_pre( @@ -1853,11 +1833,6 @@ def hc_pre( out_norm_weight: torch.Tensor | None = None, out_norm_eps: float | None = None, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, bool]: - """MHC pre for one sublayer. - - x: [s, n*hidden] bf16. Returns (layer_input [s,hidden], h_res [s,n*n] fp32, - h_post [s,n] fp32, norm_fused). - """ s, total = x.shape hidden_size = total // hc_mult if x.numel() == 0: @@ -1898,11 +1873,6 @@ def hc_post( h_res: torch.Tensor, hc_mult: int, ) -> torch.Tensor: - """MHC post for one sublayer. - - x: [s, hidden], residual: [s, n*hidden], h_post: [s,n], h_res: [s,n*n]. - Returns [s, n*hidden]. - """ s, hidden_size = x.shape if s == 0: return x.new_zeros((s, hc_mult * hidden_size)) diff --git a/python/sglang/kernels/ops/moe/kpool_topk_transform.py b/python/sglang/kernels/ops/moe/kpool_topk_transform.py index a3bfd04fcc0fd..89f066f0827f0 100644 --- a/python/sglang/kernels/ops/moe/kpool_topk_transform.py +++ b/python/sglang/kernels/ops/moe/kpool_topk_transform.py @@ -9,13 +9,11 @@ if TYPE_CHECKING: from tvm_ffi.module import Module -# Pool-level top-k values that have dedicated, validated kernel instantiations. SUPPORTED_GROUP_TOPK = (128, 160, 192, 224, 256, 512) @cache_once def _jit_kpool_topk_transform_module(group_topk: int) -> Module: - """Compile and cache the kpool top-k transform module for a given group_topk.""" assert group_topk in SUPPORTED_GROUP_TOPK, ( "fast_kpool_topk_transform supports pool-level topk " f"{SUPPORTED_GROUP_TOPK}, got {group_topk}" @@ -39,13 +37,6 @@ def fast_kpool_topk_transform_fused( seq_lens: Optional[torch.Tensor] = None, page_table_row_index: Optional[torch.Tensor] = None, ) -> torch.Tensor: - """ - Pool-level radix top-k for the NSA kpool indexer. - - Selects pool groups from ``score`` at pool granularity, expands each selected - group to ``pool_size`` token indices, and optionally transforms those token - indices through a page table or a ragged offset. - """ assert topk % pool_size == 0 group_topk = topk // pool_size assert group_topk in SUPPORTED_GROUP_TOPK, ( diff --git a/python/sglang/kernels/ops/speculative/eagle.py b/python/sglang/kernels/ops/speculative/eagle.py index b8051a6f08baf..0d8af0d935a9f 100644 --- a/python/sglang/kernels/ops/speculative/eagle.py +++ b/python/sglang/kernels/ops/speculative/eagle.py @@ -100,16 +100,10 @@ def nextn_mamba_commit_prologue( mamba_track_interval, HAS_TRACK: tl.constexpr, ): - # Chain-spec (topk == 1) commit prologue. accept_index[i, j] == i*draft + j - # for accepted slots, so the last-accepted tree step is accept_lens - 1 and - # the interval-crossing candidate step equals its own in-request index — - # no accept_index gathers are needed. One launch replaces the ~21-op eager - # sequence in commit_mamba_states_after_verify. + # In topk=1 chains, accepted node indices equal per-request step indices, so the eager accept_index gathers are identities. pid = tl.program_id(axis=0) al = tl.load(accept_lens_ptr + pid).to(tl.int64) - # Outputs are int32 (matching the eager path, whose gathers preserve the - # int32 accept_index dtype); the values are tree-step indices bounded by - # draft_token_num, so the narrowing cast is always exact. + # Eager accept_index gathers yield int32; draft-step bounds make this narrowing exact. tl.store(last_correct_ptr + pid, (al - 1).to(tl.int32)) if HAS_TRACK: pre = tl.load(seq_lens_ptr + pid).to(tl.int64) @@ -128,13 +122,7 @@ def nextn_mamba_commit_prologue_func( mamba_track_interval: int, has_track: bool, ): - """Fused topk==1 replacement for the eager commit prologue. - - Returns (last_correct_step_indices, mamba_steps_to_track) with the same - dtypes/values as the eager reference path (int32, the dtype of - accept_index that the eager gathers preserve; track entries are -1 where - no interval crossing happened). - """ + """Return int32 chain-step indices equivalent to the eager accept_index gathers.""" bs = accept_lens.shape[0] last_correct = torch.empty(bs, dtype=torch.int32, device=accept_lens.device) steps_to_track = ( diff --git a/python/sglang/srt/configs/model_config.py b/python/sglang/srt/configs/model_config.py index 3db0a69b5f99f..7ba2be15673c1 100644 --- a/python/sglang/srt/configs/model_config.py +++ b/python/sglang/srt/configs/model_config.py @@ -282,12 +282,7 @@ def get_dsa_index_kpool(config: PretrainedConfig) -> int: def get_dsa_mtp_topk_width(config: PretrainedConfig) -> int: - """Return the physical index width carried by DSA MTP IndexShare. - - KPool selects ``index_topk`` history tokens and appends the unpooled tail, - whose maximum width is ``index_kpool - 1``. Seed buffers must preserve - both parts so their shape matches the indexer's output. - """ + """MTP seeds include index_topk pooled tokens plus up to index_kpool - 1 tail tokens.""" index_kpool = get_dsa_index_kpool(config) assert index_kpool >= 1, f"index_kpool must be positive, got {index_kpool}" return get_dsa_index_topk(config) + index_kpool - 1 diff --git a/python/sglang/srt/disaggregation/decode.py b/python/sglang/srt/disaggregation/decode.py index 976ebb7a371f0..a0d5d1f7ba555 100644 --- a/python/sglang/srt/disaggregation/decode.py +++ b/python/sglang/srt/disaggregation/decode.py @@ -1132,7 +1132,6 @@ def pop_preallocated( ) self.queue.sort(key=lambda r: r.req.priority * priority_sign) - # First, remove all failed or timed-out requests from the queue. for i, decode_req in enumerate(self.queue): if rids_to_check is not None and decode_req.req.rid not in rids_to_check: continue diff --git a/python/sglang/srt/disaggregation/encoder/preprocessor.py b/python/sglang/srt/disaggregation/encoder/preprocessor.py index cd1308876cd23..04e29ba2ac36c 100644 --- a/python/sglang/srt/disaggregation/encoder/preprocessor.py +++ b/python/sglang/srt/disaggregation/encoder/preprocessor.py @@ -446,7 +446,6 @@ async def _dp_sharded_decode_single_video( video_processor_kwargs: dict, precomputed_indices: Optional[List[int]] = None, ): - """Decode and preprocess only this encoder rank's temporal units.""" video_config = video_config or {} video_fps = vr.avg_fps duration = len(vr) / video_fps if video_fps else 0 @@ -592,8 +591,6 @@ async def _flatten_and_load_videos(self, mm_items): target_fps=config.get("fps"), max_frame_count=config.get("max_frames"), ) - # The static threshold intentionally keeps small videos on the - # simpler path; only large single videos need decode sharding. if ( self.server_args.mm_enable_dp_encoder and tp_size > 1 diff --git a/python/sglang/srt/disaggregation/nixl/conn.py b/python/sglang/srt/disaggregation/nixl/conn.py index 8ee7e5f63870c..69e06b506fd4f 100644 --- a/python/sglang/srt/disaggregation/nixl/conn.py +++ b/python/sglang/srt/disaggregation/nixl/conn.py @@ -1315,10 +1315,8 @@ def transfer_worker(self, queue: FastQueue, staging_buffer=None): ) handles.append(aux_xfer_handle) else: - # The payload is request-global and another source - # rank writes it. Keep this source rank's no-KV - # accounting/completion notification without - # racing that shared destination slot. + # AUX is replicated; non-writers still notify so + # per-source completion accounting advances. self.agent.send_notif( req.agent_name, aux_notif.encode("ascii") ) @@ -2508,9 +2506,8 @@ def maybe_send_extra( if h is not None: handles.append(h) if skipped_replicated_state and not handles: - # Decode waits for one state notification from every connected - # Prefill source rank. A non-owner CP rank has no bytes to write, - # but it must still satisfy that completion barrier. + # Non-owner CP ranks have no state bytes, but decode still expects + # one completion per source rank. self.agent.send_notif(peer_name, f"{notif}_marker".encode("ascii")) return handles diff --git a/python/sglang/srt/disaggregation/utils.py b/python/sglang/srt/disaggregation/utils.py index fcbdcc6405399..b076281aed98a 100644 --- a/python/sglang/srt/disaggregation/utils.py +++ b/python/sglang/srt/disaggregation/utils.py @@ -82,13 +82,7 @@ def should_send_aux_metadata( decode_attn_tp_size: int, decode_attn_tp_rank: int, ) -> bool: - """Select the sole prefill writer of request-global AUX metadata. - - KV and side-state payloads may be partitioned across CP ranks, but AUX - metadata is replicated and every sender targets the same decode-side slot. - Select CP rank zero and one prefill TP rank for each decode TP destination. - Non-writers must still send their normal completion notifications. - """ + """Choose the sole PP/CP/TP writer for replicated AUX; non-writers must still notify completion.""" primary_prefill_tp_rank = ( decode_attn_tp_rank * prefill_attn_tp_size // decode_attn_tp_size ) @@ -862,10 +856,7 @@ def resolve_linear_state_shards( decode_attn_tp_size: int, decode_tp_rank: int, ) -> Optional[Tuple[int, int, int, int]]: - """Select the linear-state source shard for one destination rank. Prefill - shards by attention CP (DSA Prefill CP) or attention TP; decode by - attention TP only. Returns ``None`` when the two ranks own disjoint head - ranges.""" + """Map a prefill TP/CP head shard to decode TP; return None for disjoint ranges.""" values = { "prefill_attn_tp_size": prefill_attn_tp_size, "prefill_attn_cp_size": prefill_attn_cp_size, @@ -1082,7 +1073,6 @@ def slice_dsa_tail_dst_ptrs_for_pp( start_layer: int, end_layer: Optional[int], ) -> List[int]: - """Align ``[key layers..., score layers...]`` tail pointers across PP.""" if len(src_ptrs) == len(dst_ptrs): return list(dst_ptrs) if len(src_ptrs) % 2 != 0 or len(dst_ptrs) % 2 != 0: @@ -1116,12 +1106,7 @@ def build_dsa_tail_transfer_blocks( dst_indices: List[int], dst_item_lens: Optional[List[int]] = None, ) -> List[Tuple[int, int, int]]: - """Build byte ranges for a request-scoped DSA tail ring transfer. - - The Prefill and Decode pools may reserve different numbers of speculative - tail slots. Preserve the logical token order while remapping between their - physical rings. - """ + """Remap live DSA tail tokens between rings with different speculative-slot counts.""" if not src_indices and not dst_indices: return [] if not src_indices or not dst_indices: diff --git a/python/sglang/srt/entrypoints/openai/serving_chat.py b/python/sglang/srt/entrypoints/openai/serving_chat.py index 628b3d48d6e4d..e0584e65f05e6 100644 --- a/python/sglang/srt/entrypoints/openai/serving_chat.py +++ b/python/sglang/srt/entrypoints/openai/serving_chat.py @@ -729,17 +729,7 @@ def _recover_media_order_from_chat_template( video_data: List[Any], audio_data: List[Any], ) -> tuple[List[Any], List[Any], List[Any]]: - """Align media data with the order emitted by the chat template. - - Media extraction walks request messages, but templates that associate - tool results by ``tool_call_id`` may emit those results in tool-call - order. Render a media-free copy containing indexed text sentinels and - use their rendered order as the permutation for each modality. - - A permutation is applied only when every collected item appears exactly - once. Templates that drop, duplicate, or transform a sentinel safely - retain the original order. - """ + """Tool-result templates can reorder positional media independently of request extraction.""" counters = {media_type: 0 for media_type in self._MM_ORDER_TAGS} sentinel_messages = [] for message in messages: @@ -1514,10 +1504,6 @@ def _apply_jinja_template( # should be treated as client errors (400 BadRequest) raise ValueError(str(template_error)) from template_error - # Templates that associate results with assistant tool calls can - # emit result messages in call order rather than request order. An - # extra render is needed only when that can change a positional - # media binding: at least two tool-result items of one modality. if getattr( self.template_manager, "jinja_template_may_reorder_tool_results", diff --git a/python/sglang/srt/environ.py b/python/sglang/srt/environ.py index 8d77fdc00654c..8e740f04b093a 100644 --- a/python/sglang/srt/environ.py +++ b/python/sglang/srt/environ.py @@ -1387,11 +1387,7 @@ class Envs: SGLANG_DSA_FUSE_TOPK = EnvBoolWithAlias( True, deprecated_name="SGLANG_NSA_FUSE_TOPK" ) - # Ported optimization gates (all default-off). - # KPOOL_METADATA_FUSION covers the fused kpool metadata refresh for all - # three replay phases (verify / decode / draft-extend), including the - # multi-step draft metadata dedup (later step backends D2D-copy the - # derived metadata from step 0 instead of recomputing it). + # Later draft steps reuse step-0 metadata instead of recomputing it. SGLANG_EXPERIMENTAL_DSA_KPOOL_METADATA_FUSION = EnvBool(False) # Capture the verify metadata refresh inside the CUDA graph; the # DG_OUT_OF_GRAPH sub-mode keeps DeepGEMM scheduling out of the graph. diff --git a/python/sglang/srt/layers/attention/dsa/dsa_indexer.py b/python/sglang/srt/layers/attention/dsa/dsa_indexer.py index 3ad46e995ac66..84fef069d60f8 100644 --- a/python/sglang/srt/layers/attention/dsa/dsa_indexer.py +++ b/python/sglang/srt/layers/attention/dsa/dsa_indexer.py @@ -895,9 +895,7 @@ def _get_topk_paged( assert len(weights.shape) == 3 weights = weights.squeeze(2) - # DeepGEMM SM100 paged MQA misaligns when batch_size exceeds num_sms: - # chunk per sm_count with per-chunk schedule metadata, else defer to the - # plain kernel. Injected into the shared helpers as the kernel fn. + # SM100 DeepGEMM paged MQA requires batch_size <= num_sms; chunk larger batches. def _chunked_fp8_paged_mqa_logits( q: torch.Tensor, kv_cache: torch.Tensor, diff --git a/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py b/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py index b466a8b5b3334..177c7e2cd2b25 100644 --- a/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py +++ b/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py @@ -136,7 +136,8 @@ def __init__( quant_config=quant_config, prefix=add_prefix("wk", prefix), ) - # NOTE: weights_proj in the checkpoint is stored in bf16, while the parameters here are stored in fp32 for convenience + # Keep weights_proj in FP32 because its accumulation/scale path requires FP32; + # checkpoint BF16 weights are cast on load. self.weights_proj = ReplicatedLinear( self.hidden_size, self.n_heads, @@ -881,10 +882,9 @@ def _get_topk_paged( pool = get_token_to_kv_pool() page_size = pool.page_size - # NOTE(dark): blocksize = 64 is hardcoded in deep_gemm + # DeepGEMM paged-MQA requires 64-token pages. assert page_size == 64, "only support page size 64" - # NOTE(dark): this support extend/decode/decode+graph block_tables = metadata.get_page_table_64() kv_cache_fp8 = self._get_index_k_read_buffer(pool, layer_id) @@ -988,19 +988,13 @@ def _get_topk_paged( def _should_chunk_mqa_logits( self, num_q: int, num_k: int, device: torch.device ) -> Tuple[bool, int]: - """ - Detect whether we need to chunk the MQA logits computation to avoid OOM - Return: (need_chunk, free_mem) - """ - # Quick static check for normal batches - if num_q * num_k < 8_000_000: # 8M elements ≈ 32MB logits + if num_q * num_k < 8_000_000: return False, 0 free_mem, total_mem = torch.cuda.mem_get_info(device) - bytes_per_elem = 4 # float32 + bytes_per_elem = 4 logits_bytes = num_q * num_k * bytes_per_elem - # Logits should not exceed 50% of free memory or 30% of total memory need_chunk = (logits_bytes * 2 > free_mem) or (logits_bytes > total_mem * 0.3) return need_chunk, free_mem @@ -1664,7 +1658,6 @@ def forward_cuda( return_indices=return_indices, ) - # CUDA graph capture keeps the full topk path; the skip branch is extend-only. skip_logits_computation = False if forward_batch.forward_mode.is_extend_without_speculative(): if forward_batch.seq_lens_cpu is not None: diff --git a/python/sglang/srt/layers/attention/dsa/kpool_fp8_index.py b/python/sglang/srt/layers/attention/dsa/kpool_fp8_index.py index 9a0b8fe3ba8bc..3c0cd65febe22 100644 --- a/python/sglang/srt/layers/attention/dsa/kpool_fp8_index.py +++ b/python/sglang/srt/layers/attention/dsa/kpool_fp8_index.py @@ -46,7 +46,6 @@ def _kpool_cache_k_offsets( def kpool_max_closed_pools(num_draft_tokens: int, pool_size: int) -> int: - """Return the most pools an N-token write can close at any start offset.""" return (num_draft_tokens + pool_size - 1) // pool_size @@ -54,14 +53,8 @@ def build_pooled_page_table_64( page_table_64: torch.Tensor, pool_size: int, ) -> torch.Tensor: - """Pack one logical pool page into the first token page of each page group. - - Uses advanced indexing (gather) rather than strided slicing so the result - is always a freshly allocated row-major tensor. Strided slicing produces - a view whose .contiguous() short-circuits for shape==(1, 1), leaving - stride(-1) == pool_size and breaking downstream kernels that require - stride(-1) == 1 (e.g. deep_gemm.fp8_paged_mqa_logits). - """ + # Advanced indexing is required: a (1, 1) strided slice can remain non-unit- + # stride even after contiguous(), which DeepGEMM rejects. assert ( BLOCK_SIZE_K % pool_size == 0 ), f"pool_size ({pool_size}) must divide page_size ({BLOCK_SIZE_K})" @@ -163,12 +156,8 @@ def kpool_build_ragged_layout( total_q: int, pool_size: int, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """Build one flat pooled-page table plus per-q row starts/ends. - - DSA stores 64 pooled entries per physical page. A pooled page therefore - corresponds to every ``pool_size``-th 64-token page in the original real - page table. - """ + # One packed-cache page represents 64 pools, so its source is every + # pool_size-th real token page. device = full_page_table.device n_rag = cu_pages_excl.shape[0] concat_page_table = torch.empty( @@ -265,10 +254,8 @@ def _prep_update_kpool_write_plan_launch( num_draft_tokens: int, slots_per_page: int, ): - """Validate and build the (bs, args, constexpr kwargs) launch spec for the - write-plan kernel. Shared between the per-call wrapper below and the - prebound cuda-graph replay launcher. Mirrors the eager path exactly, - including pool_size < num_draft_tokens support (max_closed_pools).""" + # Eager and captured replay must share one launch spec, including + # N > pool_size where one write closes multiple pools. max_closed_pools = kpool_max_closed_pools(num_draft_tokens, pool_size) bs = write_start.shape[0] @@ -385,9 +372,8 @@ def _update_kpool_write_plan_kernel( token_page_row = tl.minimum( tl.maximum(token_page_row, 0), real_page_table_cols - 1 ) - # Promote the row term to int64 before the pointer math (same as the - # fused metadata kernels): a row index times a context-scale stride - # wraps int32 well before the buffer does. + # Promote the row term before multiplication; 1M-context strides + # overflow int32 around row 2048. packed_page = tl.load( real_page_table_ptr + (b * N).to(tl.int64) * real_page_table_stride_0 @@ -405,7 +391,6 @@ def compute_pooled_write_locs( pool_ids: torch.Tensor, pool_size: int, ) -> torch.Tensor: - """Map logical pooled-K ids to packed physical index-cache locations.""" assert page_table_64.ndim == 1 pool_ids = pool_ids.to(torch.int64) pool_page_group = torch.div(pool_ids, BLOCK_SIZE_K, rounding_mode="floor") @@ -429,7 +414,6 @@ def expand_pooled_groups_to_topk( page_table: torch.Tensor | None = None, topk_offsets: torch.Tensor | None = None, ) -> torch.Tensor: - """Expand selected full-pool ids to a strict-width token topk tensor.""" assert group_ids.ndim == 2 assert group_valid.shape == group_ids.shape assert topk % pool_size == 0 @@ -471,7 +455,6 @@ def append_kpool_tail_to_topk( page_table: torch.Tensor | None = None, topk_offsets: torch.Tensor | None = None, ) -> torch.Tensor: - """Append non-pooled tail tokens after selected expanded-history tokens.""" assert topk_result.dtype == torch.int32 assert seq_lens.ndim == 1 assert pool_lens.ndim == 1 @@ -578,9 +561,8 @@ def _append_kpool_tail_to_topk_kernel( tail_value = tail_raw if HAS_PAGE_TABLE: safe_tail = tl.minimum(tl.maximum(tail_raw, 0), PAGE_TABLE_COLS - 1) - # int64 row term: the wide page table's row stride is context-scale - # (~2^20 on 1M-context models), so row * stride wraps int32 from - # row ~2048 — same promotion as the fused metadata kernels. + # Promote the row term before multiplication; 1M-context strides + # overflow int32 around row 2048. tail_value = tl.load( page_table_ptr + row.to(tl.int64) * page_table_stride_0 @@ -609,7 +591,6 @@ def topk_from_pooled_history_logits( out_rows: int | None = None, page_table_row_index: torch.Tensor | None = None, ) -> torch.Tensor: - """Select full-pool groups, expand to tokens, and optionally append tail.""" assert logits.ndim == 2 assert group_lengths.ndim == 1 assert logits.shape[0] == group_lengths.shape[0] @@ -636,9 +617,8 @@ def topk_from_pooled_history_logits( f"is disabled. Got device={logits.device}, dtype={logits.dtype}." ) - # The JIT fused path supports the dedicated 128..512 group-topk kernels on - # both CUDA and HIP. Keep the legacy HIP fallback only for the separate - # 2048-group AOT path, which is not covered by the JIT implementation. + # The JIT kernel covers group_topk <= 512 on CUDA/HIP; HIP 2048 still + # requires the legacy AOT fallback. if is_hip() and group_topk == 2048: return _topk_from_pooled_history_logits_unfused( logits=logits, diff --git a/python/sglang/srt/layers/attention/dsa/kpool_plan.py b/python/sglang/srt/layers/attention/dsa/kpool_plan.py index 8ef618b2aaf38..ea2d3a3fb63c4 100644 --- a/python/sglang/srt/layers/attention/dsa/kpool_plan.py +++ b/python/sglang/srt/layers/attention/dsa/kpool_plan.py @@ -103,12 +103,8 @@ class KPoolExtendPlan: @dataclass(frozen=True) class KPoolWritePlan: - """Layer-invariant plan for kpool tail writes and closed-pool compression. - - ``write_loc[b, p]`` is the compression destination for logical pool - ``base_pool[b] + p``. The compression kernel determines how many of these - candidate pools were actually closed by each batch. - """ + """``write_loc[b, p]`` is the compression destination for candidate closed + pool ``base_pool[b] + p``; the kernel decides which candidates closed.""" req: torch.Tensor write_start: torch.Tensor @@ -540,9 +536,8 @@ def init_kpool_extend_metadata( def _get_deep_gemm(): - """Cached deep_gemm import, hoisted out of the per-replay schedule - refresh (the old per-call try-import re-ran the import machinery on - every cuda-graph replay cycle).""" + # Cache import failure too, because this helper runs on every graph-replay + # metadata refresh. global _DEEP_GEMM_MODULE, _DEEP_GEMM_IMPORT_FAILED if _DEEP_GEMM_MODULE is None and not _DEEP_GEMM_IMPORT_FAILED: try: @@ -772,13 +767,8 @@ def update_kpool_write_plan( effective_n_per_batch.to(torch.int32) ) - # include_deep_gemm_schedule=False: the caller records the write-plan - # kernel inside a cuda graph but keeps the DeepGEMM schedule build - # out-of-graph (SGLANG_EXPERIMENTAL_DSA_INGRAPH_VERIFY_METADATA_DG_OUT_OF_ - # GRAPH); it refreshes the schedule per replay via - # refresh_kpool_pool_schedule_from with a source rebuilt from raw - # seq_lens, since plan.pool_seqlens_per_q is only written when the - # captured kernel replays. + # In-graph replay updates plan lengths too late for host schedule construction; + # the caller rebuilds the schedule from raw seq_lens out of graph. if include_deep_gemm_schedule and plan.pool_schedule_metadata is not None: new_schedule = _compute_pool_schedule_metadata( plan.pool_seqlens_per_q, @@ -794,17 +784,8 @@ def refresh_kpool_pool_schedule_from( *, slots_per_page: int, ) -> None: - """Refresh ONLY the pooled DeepGEMM schedule of the verify write plan from - an EXPLICIT per-q pooled-seqlens source. - - Out-of-graph residual of the in-graph verify metadata capture (see - update_kpool_write_plan's include_deep_gemm_schedule): the caller derives - ``pool_seqlens_per_q`` from the raw seq_lens buffer using the same closed - form the captured write-plan kernel stores - (``(write_start + k + 1) // pool_size``), because the plan's own - ``pool_seqlens_per_q`` buffer is not refreshed until the captured graph - replays. No-op when the plan or its schedule buffer is absent. - """ + """Use an explicit source because the captured plan buffer remains stale + until replay.""" plan = metadata.kpool_write_plan if plan is None or plan.pool_schedule_metadata is None: return diff --git a/python/sglang/srt/layers/attention/dsa/utils.py b/python/sglang/srt/layers/attention/dsa/utils.py index b3543d15f6cea..5f92047080eda 100644 --- a/python/sglang/srt/layers/attention/dsa/utils.py +++ b/python/sglang/srt/layers/attention/dsa/utils.py @@ -84,10 +84,8 @@ def compute_dsa_seqlens(original_seq_lens, dsa_index_topk: int, index_kpool: int if index_kpool <= 1: return original_seq_lens.clamp(max=dsa_index_topk) - # kpool: history tokens are selected at pool granularity (multiples of - # index_kpool), while the ragged tail (the partial trailing pool) is always - # kept. Round the history part down to a pool boundary, clamp it to topk, - # then add back the tail. + # Clamp only complete pools; the unfinished tail must remain selectable + # outside the pooled top-k budget. full_pool_tokens = ( torch.div(original_seq_lens, index_kpool, rounding_mode="floor") * index_kpool ) @@ -441,16 +439,8 @@ def cp_split_and_rebuild_position(forward_batch, positions: torch.Tensor): def cp_attn_tp_all_gather_reorganazied_into_tensor( input_: torch.Tensor, attn_tp_size, forward_batch ): - """ - Allgather communication for context_parallel(kv_cache, index_k, hidden_states). - This implementation mainly consists of three parts: - Step 1, padding the input shape to unify the shape for allgather communication (the shape must be the same). - Step 2, synchronized allgather communication. - Step 3, removing the padding and reassembling the data according to the actual tokens. - """ - # The metadata is the source of truth for the per-rank physical extent. - # ceil(total_len / cp_size) can be smaller for multi-request batches whose - # per-sequence remainders accumulate on the same rank. + # Use metadata extents: per-request remainders can make a rank longer than + # ceil(total_len / cp_size). max_rank_len = forward_batch.attn_cp_metadata.max_rank_len max_len = max_rank_len[0] assert len(max_rank_len) == attn_tp_size and all( @@ -491,32 +481,6 @@ def cp_attn_tp_all_gather_reorganazied_into_tensor( def cp_all_gather_rerange_output(input_tensor, cp_size, forward_batch, stream): - """ - # for in-seq-split - | +-----------before allgather------------+| - | | dp_atten_tp0: block0, block7 | - | | dp_atten_tp1: block1, block6 | - | | dp_atten_tp2: block2, block5 | - | | dp_atten_tp3: block3, block4 | - | - | +----------before rerange---------------+| - | block0 | block7 | block1 | block6 | block2 | block5 | block3 | block4 | - | - | +--------------result-------------------+ - | block0 | block1 | block2 | block3 | block4 | block5 | block6 | block7 | - | +-------------------------+ - - # for round-robin-split - | +-----------before allgather------------+| - | dp_atten_tp0: token0, token4, token8, token12, token16, ... | - | dp_atten_tp1: token1, token5, token9, token13, token17, ... | - | dp_atten_tp2: token2, token6, token10, token14, token18, ... | - | dp_atten_tp3: token3, token7, token11, token15, token19, ... | - | - | +--------------result-------------------+ - | token0, token1, token2, token3, token4, token5, token6, token7, ... - | +-------------------------+ - """ if is_dsa_prefill_cp_round_robin_split(): with use_symmetric_memory( get_parallel().attn_cp_group, disabled=not is_allocation_symmetric() @@ -555,27 +519,9 @@ def cp_all_gather_rerange_output(input_tensor, cp_size, forward_batch, stream): return output_tensor -# "Plain" CP layout: rank i holds the contiguous token slice -# [i*S/cp, (i+1)*S/cp). This is the natural layout produced by a vanilla -# all_gather on rank-major buffers, so KDA layers (which need natural-sequential -# tokens for causal_conv1d / chunk_kda) can use plain all_gather / plain -# reduce_scatter with zero rerange permute. At MLA boundaries the layout is -# converted to/from the configured scattered mode (round-robin or zigzag) that -# MLA's CP attention expects for load balance. -# -# Residual streams stay in plain throughout the layer stack and never need -# conversion -- they are re-derived from hidden_states at each layer entry by -# `mhc.attn_split`, so they inherit hidden_states' layer-input layout, which -# under the plain cross-layer contract is always plain. - - +# Plain CP keeps rank-contiguous token slices across layers; only MLA boundaries +# convert to/from the load-balanced layout. def cp_plain_split(input_tensor: torch.Tensor) -> torch.Tensor: - """Model entry scatter under the plain layout contract. - - Slice the global [S_total, ...] tensor into this rank's contiguous chunk - [cp_rank * K, (cp_rank+1) * K). Pure local op; replaces - `cp_split_and_rebuild_data` at model entry when the plain contract is on. - """ cp_size = get_parallel().attn_cp_size cp_rank = get_parallel().attn_cp_rank assert input_tensor.shape[0] % cp_size == 0, ( @@ -587,13 +533,8 @@ def cp_plain_split(input_tensor: torch.Tensor) -> torch.Tensor: def cp_plain_all_gather(input_tensor: torch.Tensor, cp_size: int) -> torch.Tensor: - """Inverse of cp_plain_split: gather plain per-rank slices into the full - [S, ...] tensor in natural sequential order. - - Under the plain contract the all_gather output [rank0_chunk | rank1_chunk | - ...] *is* the natural sequential ordering, so no rerange permute is needed. - Used at model exit and at KDA prepare_attn entry. - """ + # Rank-major all-gather is already in natural order under the plain layout, + # so no rerange is needed. out_shape = (input_tensor.shape[0] * cp_size,) + tuple(input_tensor.shape[1:]) with use_symmetric_memory( get_parallel().attn_cp_group, disabled=not is_allocation_symmetric() @@ -604,17 +545,8 @@ def cp_plain_all_gather(input_tensor: torch.Tensor, cp_size: int) -> torch.Tenso def cp_plain_reduce_scatter(input_tensor: torch.Tensor, cp_size: int) -> torch.Tensor: - """Inverse of cp_plain_all_gather for KDA o_proj output. - - Takes a CP-partial-sum [S, H] in natural sequential order and emits this - rank's contiguous slice [S/cp, H] via a single reduce_scatter. The plain - layout is rank-major contiguous, so reduce_scatter's default contiguous - split is exactly what we want -- no permute or view+transpose. - - Comm cost: (N-1)/N * D, vs all_reduce + split which is 2*(N-1)/N * D - -- ~33% cheaper in NCCL ring traffic than the all_reduce path, and saves - the full-tensor permute that a round-robin reduce_scatter would need. - """ + # Contiguous plain layout permits one reduce-scatter and avoids a full-tensor + # permutation. S = input_tensor.shape[0] assert S % cp_size == 0, ( f"cp_plain_reduce_scatter expects S divisible by cp_size, " @@ -634,20 +566,8 @@ def cp_plain_to_scattered( forward_batch, cp_size: int, ) -> torch.Tensor: - """Convert a plain per-rank slice [S/cp, H] into the configured CP scatter - layout (round-robin or zigzag), suitable for MLA's CP attention kernel. - - Used at MLA prepare_attn. Composes existing primitives: - 1. plain all_gather: rank-major output IS natural sequential under the - plain contract, so no rerange needed. - 2. cp_split_and_rebuild_data: local split per the active mode - (round-robin via stride-cp_size, or zigzag via metadata indices). - - Fast path: for round-robin mode with K = S/cp divisible by cp, replace - AG + local stride-cp split with a single all_to_all_single. Each rank - sends K/cp rows to each destination instead of broadcasting all K rows -- - cp x less NCCL traffic and no [S, H] intermediate. - """ + # When K % cp_size == 0, all-to-all is equivalent to the round-robin split + # and avoids a full all-gather. K = input_tensor.shape[0] if is_dsa_prefill_cp_round_robin_split() and K % cp_size == 0: tail = input_tensor.shape[1:] @@ -669,20 +589,8 @@ def cp_scattered_to_plain( forward_batch, cp_size: int, ) -> torch.Tensor: - """Inverse of cp_plain_to_scattered. Takes a scattered (round-robin or - zigzag) per-rank slice [S/cp, H] (MLA's natural output layout) and emits - a plain per-rank slice. - - Used at MLA prepare_mlp. Composes: - 1. cp_all_gather_rerange_output: gather + rerange to natural sequential. - 2. local contiguous slice [cp_rank * K, (cp_rank+1) * K). - - Fast path: for round-robin mode with K = S/cp divisible by cp, replace - AG + rerange + slice with a single all_to_all_single. Each rank sends - K/cp contiguous rows to each destination -- send buffer is already laid - out correctly (no pre-copy), recv needs one transpose-contiguous to - interleave by source rank. cp x less NCCL traffic and no [S, H] alloc. - """ + # When K % cp_size == 0, all-to-all avoids a full all-gather; transposing + # the received source-major rows restores plain order. K = input_tensor.shape[0] if is_dsa_prefill_cp_round_robin_split() and K % cp_size == 0: tail = input_tensor.shape[1:] diff --git a/python/sglang/srt/layers/attention/dsa_backend.py b/python/sglang/srt/layers/attention/dsa_backend.py index b6055c2d4dd4b..5938b78d1f891 100644 --- a/python/sglang/srt/layers/attention/dsa_backend.py +++ b/python/sglang/srt/layers/attention/dsa_backend.py @@ -352,34 +352,8 @@ def _cat(tensors: list[torch.Tensor], dim: int = -1) -> torch.Tensor: class _DSAInGraphVerifyMetadataState: - """Marker + replay-side residual for a TARGET_VERIFY metadata refresh that - was recorded INSIDE the captured cuda graph - (SGLANG_EXPERIMENTAL_DSA_INGRAPH_VERIFY_METADATA). - - Published on the frozen ``decode_cuda_graph_metadata[bs]`` entry by - :py:meth:`DeepseekSparseAttnBackend.init_forward_metadata_in_graph` once - the refresh nodes were recorded, as an UNDECLARED attribute - (``object.__setattr__``), so both a graph recapture (fresh DSAMetadata) - and ``dataclasses.replace()`` drop it automatically. - - Its presence tells :py:meth:`_apply_cuda_graph_metadata` that - ``graph.replay()`` re-executes the whole refresh sequence reading the - LIVE contents of the static seq_lens / req_pool_indices buffers, so the - out-of-graph replay body must skip the corresponding device work: values - it wrote would be recomputed by the captured nodes anyway and -- if - derived from any other buffers -- clobbered by them. Only host-side - state survives out-of-graph: the memoized - ``set_dsa_prefill_impl(None)`` result and the optional DG_OUT_OF_GRAPH - residual (DeepGEMM schedule builds rebuilt from raw seq_lens). - - :py:meth:`matches` revalidates on every replay that the incoming - seq_lens / req_pool_indices alias the storage the captured nodes read - (data_ptr/stride identity). A mismatch - is a HARD ERROR rather than a fallback: running the generic out-of-graph - body against foreign buffers cannot help, because the captured refresh - still re-executes at replay and overwrites the metadata from the static - buffers the caller never filled. - """ + """Captured refreshes require fixed input-buffer identities at replay. + Mismatches must fail because captured nodes would overwrite fallback metadata.""" __slots__ = ( "prefill_impl_state", @@ -466,12 +440,7 @@ def __init__( self.dsa_index_topk = get_dsa_index_topk(hf_config) self.dsa_index_kpool = get_dsa_index_kpool(hf_config) self.needs_cpu_seq_lens = self.dsa_index_kpool > 1 - # The fused metadata kernels are already the standard path for - # kpool<=1 backends; this flag extends them to page-aligned KPool - # geometries with pool-aligned topk. - # Any other geometry keeps the eager path: the env var is global and - # may be set fleet-wide across heterogeneous DSA backends, so an - # unsupported backend must degrade gracefully, not fail startup. + # The env is global, so unsupported KPool geometry or platforms must fall back. _kpool_fusion_requested = ( envs.SGLANG_EXPERIMENTAL_DSA_KPOOL_METADATA_FUSION.get() ) @@ -480,10 +449,6 @@ def __init__( self.real_page_size, self.dsa_index_topk, ) - # The fused kernels and the multi-step sibling-copy dedup are - # CUDA-only (every replay call site guards on is_cuda() and not - # _is_hip); fold the platform into the effective enable so every - # consumer of this attribute inherits it. _kpool_fusion_platform_ok = is_cuda() and not _is_hip self.experimental_kpool_metadata_fusion = ( _kpool_fusion_requested @@ -505,11 +470,8 @@ def __init__( self.real_page_size, self.dsa_index_topk, ) - # Experimental, default-off: record the whole TARGET_VERIFY metadata - # refresh inside the captured verify graph at capture time so replay - # gets it for free (see init_forward_metadata_in_graph / - # _DSAInGraphVerifyMetadataState). The DG_OUT_OF_GRAPH sub-mode keeps - # only the two DeepGEMM schedule builds out-of-graph. + # Replay may refresh target-verify metadata in-graph; DG_OUT_OF_GRAPH + # leaves only the DeepGEMM schedule builds outside. self.ingraph_verify_metadata_enabled = ( envs.SGLANG_EXPERIMENTAL_DSA_INGRAPH_VERIFY_METADATA.get() ) @@ -2097,18 +2059,8 @@ def _apply_cuda_graph_metadata( metadata: DSAMetadata = self.decode_cuda_graph_metadata[bs] - # Experimental in-graph verify metadata - # (SGLANG_EXPERIMENTAL_DSA_INGRAPH_VERIFY_METADATA): the whole - # TARGET_VERIFY refresh sequence for this entry was recorded INSIDE - # the captured graph at capture time (init_forward_metadata_in_graph), - # so graph.replay() re-executes it -- ahead of the attention kernels, - # reading the CURRENT contents of the static seq_lens / - # req_pool_indices buffers that fill_from refreshed this cycle. Skip - # the corresponding out-of-graph device work here; keep only host - # state (the memoized set_dsa_prefill_impl(None) result) and the - # optional DG_OUT_OF_GRAPH residual. Runs during recapture too - # (in_capture out_graph replays this body): the residual is harmless - # there and the in-graph hook re-publishes a fresh state afterwards. + # Captured graphs recompute device metadata, so this path retains only + # host state and any out-of-graph DeepGEMM residual. if forward_mode.is_target_verify(): ingraph_state = getattr(metadata, "_ingraph_verify_metadata", None) if ingraph_state is not None: @@ -2456,47 +2408,8 @@ def _ingraph_verify_metadata_eligible(self) -> bool: ) def init_forward_metadata_in_graph(self, forward_batch: ForwardBatch): - """Graph-recordable TARGET_VERIFY metadata refresh (experimental, - SGLANG_EXPERIMENTAL_DSA_INGRAPH_VERIFY_METADATA; default no-op). - - Runs inside ``with graph.capture():`` (the decode runner's run_once, - after init_forward_metadata_out_graph(in_capture=True) built the - metadata entry and BEFORE the model forward), so every launch below - is recorded as graph nodes that precede the attention kernels in the - SAME captured graph. At replay they re-execute reading the CURRENT - contents of the runner's static seq_lens / req_pool_indices buffers - -- buffer contents are read at replay execution time, not capture - time, and fill_from refreshes them on the fwd/plan stream before - graph.replay() in stream order. - - Capture-legality per recorded op (base-hook lint contract): - - fused_dsa_target_verify_metadata: plain triton launch; the - JITFunction host planning happens once here at capture. - - ctx-lens publication: captured copy_ between static buffers. - - deep_gemm.get_paged_mqa_logits_metadata: static-shape device - build; the fresh output tensor is allocated in the graph-private - pool (address stable across replays) and the captured copy_ into - the static schedule buffer pins the dataflow. If a deep_gemm - build is ever not stream-capture-safe, set - SGLANG_EXPERIMENTAL_DSA_INGRAPH_VERIFY_METADATA_DG_OUT_OF_GRAPH=1 - to keep both DeepGEMM builds out-of-graph (rebuilt per replay - from raw seq_lens by the residual). - - plan_topk_v2(out=...): single tvm-ffi kernel launch into the - preallocated plan buffer (LaunchKernel resolves the capture - stream; no sync, no alloc). - - KPool write plan: triton launch (+ pooled DeepGEMM schedule when - DG stays in-graph). - - No-op -- leaving the generic out-of-graph replay body in charge -- - for non-TARGET_VERIFY captures (e.g. the multi-step draft DECODE - backends reach this via DeepseekSparseAttnMultiStepBackend), - ineligible configs, and any structural surprise in - _record_ingraph_verify_metadata. The hybrid linear (KDA/mamba) - sibling stays out-of-graph: its query_start_loc clamp and - state-index poisoning depend on the host-side per-replay num_padding - and the live v2p mamba translate, so they are not trivially - graph-recordable. - """ + """Record target-verify refreshes only for capture-safe configurations. + Replay reads the same static input buffers with updated contents.""" if not forward_batch.forward_mode.is_target_verify(): return if not self._ingraph_verify_metadata_eligible(): @@ -2519,18 +2432,8 @@ def _record_ingraph_verify_metadata( seq_lens: torch.Tensor, req_pool_indices: torch.Tensor, ) -> None: - """Record the fused TARGET_VERIFY refresh into the graph being - captured and publish _DSAInGraphVerifyMetadataState on success. - - Mirrors, node for node and in the same stream order, the fused - TARGET_VERIFY body of _apply_cuda_graph_metadata (fused metadata - kernel -> DeepGEMM schedule -> ctx-lens publication -> top-k v2 plan - -> KPool write plan + pooled schedule). Bails WITHOUT publishing on - any structural surprise, leaving the graph without refresh nodes and - the generic out-of-graph replay in charge. Also runs eagerly during - the pre-capture warmup invocations of run_once, which is idempotent: - it rewrites the same buffers with the same capture-time values. - """ + """Publish replay state only after every structural check passes. + Otherwise the generic out-of-graph path remains responsible.""" if metadata.paged_mqa_schedule_metadata is None: return next_n = self.speculative_num_draft_tokens @@ -2539,7 +2442,6 @@ def _record_ingraph_verify_metadata( expanded_size = bs * next_n max_seqlen_k = self._graph_page_table_width(metadata) - # Same DG-native eligibility checks as the fused replay body. paged_mqa_ctx_lens_2d = None if ( next_n >= 2 @@ -2573,10 +2475,6 @@ def _record_ingraph_verify_metadata( return ctx_lens_copy_src = schedule_src_2d - # ---- Recorded nodes; identical device-work order to the fused - # out-of-graph replay body. ------------------------------------ - # 1. Fused verify metadata (triton): cache/dsa seqlens, cu_seqlens, - # page tables, expanded seqlens, optional DG-native ctx lens. fused_dsa_target_verify_metadata( seq_lens=seq_lens, req_pool_indices=req_pool_indices, @@ -2597,23 +2495,22 @@ def _record_ingraph_verify_metadata( index_kpool=self.dsa_index_kpool, ) - # 2. DeepGEMM paged-MQA schedule refresh + ctx-lens publication. dg_in_graph = not self.ingraph_verify_metadata_dg_out_of_graph num_sms = deep_gemm.get_num_sms() if dg_in_graph: + # Copy into the static buffer to keep the captured destination stable. metadata.paged_mqa_schedule_metadata.copy_( deep_gemm.get_paged_mqa_logits_metadata(schedule_src_2d, 64, num_sms) ) if ctx_lens_copy_src is not None: metadata.paged_mqa_ctx_lens_2d.copy_(ctx_lens_copy_src) - # 3. Top-k v2 plan refresh (tvm-ffi kernel into the captured plan). if metadata.topk_v2_plan is not None: + # A preallocated output avoids allocation during capture. _get_plan_topk_v2()( metadata.dsa_seqlens_expanded, out=metadata.topk_v2_plan ) - # 4. KPool write plan (+ pooled schedule iff DG stays in-graph). self._update_kpool_metadata_replay( metadata, seq_lens, @@ -2632,8 +2529,6 @@ def _record_ingraph_verify_metadata( ctx_lens_written, ) - # set_dsa_prefill_impl(forward_batch=None) is a pure function of - # init-time config; capture its result for the in-graph replay state. self.set_dsa_prefill_impl(forward_batch=None) state = _DSAInGraphVerifyMetadataState( prefill_impl_state=(self.use_mha, self.dsa_prefill_impl), @@ -2661,22 +2556,8 @@ def _build_ingraph_verify_dg_residual( num_sms: int, ctx_lens_written: bool, ) -> Callable[[], None]: - """Out-of-graph per-replay residual for the DG_OUT_OF_GRAPH fallback. - - Only the two DeepGEMM schedule builds stay out-of-graph. They must - NOT read the kernel-written metadata buffers here: at residual time - (the out-of-graph replay body, before graph.replay()) the captured - triton refresh has not run yet for this cycle, so those buffers - still hold LAST replay's values. Both schedule sources are instead - rebuilt from the raw seq_lens buffer using the exact closed forms - the captured kernels write: - - main schedule ctx lens: cache_seqlens = seq_lens + next_n - ((bs, next_n) DG-native expand), or the per-token expanded - lens seq_lens + [1..next_n] as (bs*next_n, 1) otherwise; - - pooled KPool per-q lens: (seq_lens + k + 1) // pool_size for - k in [0, next_n) (verify write_start == seq_lens; see - _update_kpool_write_plan_kernel). - """ + """Rebuild residual schedules from raw seq_lens before graph replay. + Captured metadata still contains the previous replay's values then.""" schedule_dst = metadata.paged_mqa_schedule_metadata dg_get = deep_gemm.get_paged_mqa_logits_metadata pool_size = self.dsa_index_kpool @@ -2742,10 +2623,8 @@ def init_forward_metadata_replay_cuda_graph_from_precomputed( self._copy_base_replay_buffers(bs, metadata, precomputed, forward_mode) - # Refresh DeepGEMM paged MQA schedule metadata for the actual seqlens of - # this replay (the captured graph holds stale data otherwise, which can - # deadlock the kernel when the runtime work decomposition diverges from - # the captured one). + # Refresh the schedule because stale shape decomposition can deadlock + # DeepGEMM paged MQA. if is_cuda(): if forward_mode.is_decode_or_idle(): seqlens_32_2d = _to_2d_context_lens(metadata.cache_seqlens_int32, bs) @@ -2901,11 +2780,7 @@ def _copy_base_replay_buffers( @staticmethod def _sibling_replay_metadata_compatible(dst: DSAMetadata, src: DSAMetadata) -> bool: - """Structural check that every derived buffer the sibling-copy path - writes exists on both sides. Step backends of a multi-step group are - constructed and captured identically, so this always holds in - practice; a mismatch routes the caller back to the full recompute - path instead of risking stale derived metadata.""" + """Check that both sides expose the same optional derived buffers.""" def _match(a, b) -> bool: return (a is None) == (b is None) @@ -2935,10 +2810,7 @@ def _match(a, b) -> bool: def _copy_kpool_metadata_from_sibling( self, metadata: DSAMetadata, src_metadata: DSAMetadata ) -> None: - """D2D mirror of `_update_kpool_metadata_from_precomputed`: copy every - buffer that function writes (pooled seqlens div, pooled page table, - DeepGEMM pool schedule, and the kpool write plan) from a sibling - backend that just ran the real update on identical inputs.""" + """Copy KPool metadata derived from identical inputs from a sibling.""" if self.dsa_index_kpool <= 1 or not is_cuda(): return @@ -2977,21 +2849,7 @@ def _copy_replay_metadata_from_sibling( precomputed: PrecomputedMetadata, forward_mode: ForwardMode, ) -> None: - """Replay fast path for step backends past the first in the multi-step - draft loop (engaged when SGLANG_EXPERIMENTAL_DSA_KPOOL_METADATA_FUSION - is on; internal behavior, no standalone flag). - - The base captured buffers are still copied from `precomputed` (one - fused kernel launch), but the DERIVED metadata that - `init_forward_metadata_replay_cuda_graph_from_precomputed` recomputes - per backend -- the deep_gemm.get_paged_mqa_logits_metadata schedule, - the top-k v2 plan, and everything - `_update_kpool_metadata_from_precomputed` derives (pooled seqlens div, - build_pooled_page_table_64, the DeepGEMM pool schedule and the kpool - write plan) -- is copied device-to-device from `src_backend`, which - just ran the full path on the SAME `precomputed`. Every derived - quantity is a pure function of `precomputed`, so the copy is bit-exact - with the recompute.""" + """Copy replay metadata from a sibling using the same precomputed input.""" metadata = self.decode_cuda_graph_metadata.get(bs) src_metadata = src_backend.decode_cuda_graph_metadata.get(bs) if ( @@ -4721,14 +4579,7 @@ def init_forward_metadata(self, forward_batch: ForwardBatch): self.attn_backends[i].init_forward_metadata(forward_batch) def _multistep_dedup_enabled(self) -> bool: - """Whether later step backends may sibling-copy derived replay - metadata from step 0 instead of recomputing it. - - Internal behavior of the fused metadata path (no standalone flag): - follows the step backends' effective fusion enable, which already - folds in the geometry and platform gates -- on unsupported backends - every step recomputes independently, the pre-fusion contract. - """ + """The effective fusion gate includes geometry and platform support.""" return getattr( self.attn_backends[0], "experimental_kpool_metadata_fusion", False ) @@ -4904,12 +4755,7 @@ def init_forward_metadata_out_graph( forward_mode=ForwardMode.DECODE, ) else: - # Less than 3 backends: copy to each backend individually. - # Backend 0 always runs the full path (base copy + derived - # recompute). When the fused metadata path is enabled, later step - # backends D2D-copy the derived metadata from backend 0 instead of - # recomputing it -- the inputs (`precomputed`) are identical across - # the step backends, so the derived quantities are too. + # Backend 0 fully refreshes; later backends may copy its derived metadata. dedup = self._multistep_dedup_enabled() self.attn_backends[ 0 diff --git a/python/sglang/srt/layers/attention/flashattention_backend.py b/python/sglang/srt/layers/attention/flashattention_backend.py index 00fc8720843bc..5c14293fd4ff6 100644 --- a/python/sglang/srt/layers/attention/flashattention_backend.py +++ b/python/sglang/srt/layers/attention/flashattention_backend.py @@ -1609,9 +1609,8 @@ def _fa_cp_attn( and self.fa_impl_ver == 4 and not any(forward_batch.extend_prefix_lens_cpu or []) ): - # FA4 has no absorbed MLA KV-cache kernel. In the MHA fallback, - # gather the rank-local projected K/V into global token order, - # then run each zigzag Q half against its causal K/V prefix. + # FA4 lacks absorbed MLA under CP, so projected K/V must be gathered + # globally before each zigzag Q half runs. k_full = cp_all_gather_rerange_kv_cache( k.contiguous(), self.attn_cp_size, diff --git a/python/sglang/srt/layers/attention/flashinfer_mla_backend.py b/python/sglang/srt/layers/attention/flashinfer_mla_backend.py index 7a2934c8974fa..95dafb5e18a1a 100644 --- a/python/sglang/srt/layers/attention/flashinfer_mla_backend.py +++ b/python/sglang/srt/layers/attention/flashinfer_mla_backend.py @@ -81,15 +81,8 @@ def _referenced_kv_to_bf16(k_fp8, kv_indices): - """Dequantize only the KV rows referenced by ``kv_indices`` (this batch's tokens) - into a persistent bf16 buffer mirroring the fp8 pool layout, so the paged wrapper - reads it with the same (unmodified) ``kv_indices``. Avoids converting the whole - pool every layer (the decode-latency bottleneck); since fa2 has no fp8 tensor - cores, feeding bf16 to the proven bf16 MLA kernel also keeps EAGLE draft acceptance - intact (the native in-kernel fp8 repack subtly degrades draft proposals). - - Keyed by shape (one buffer reused across layers, overwritten before each read) and - allocated outside inference mode so the in-place scatter is legal under cuda graph. + """Dequantize only referenced KV rows instead of the entire pool. + Allocate the persistent CUDA graph buffer outside inference mode. """ key = (k_fp8.device, tuple(k_fp8.shape)) scratch = _MLA_BF16_DEQUANT_SCRATCH.get(key) @@ -105,12 +98,7 @@ def _referenced_kv_to_bf16(k_fp8, kv_indices): def _verify_plan_indptr_cpu(bs, draft_token_num, seq_lens_cpu): - """Build target-verify plan indptr on the host so the flashinfer plan skips its - blocking ``qo_indptr/kv_indptr/kv_len_arr.to("cpu")`` device sync (the decode - per-token bottleneck). Verify's layout is structural — ``q_len == draft_token_num`` - and ``kv_len == seq_len + draft_token_num`` — so these match - ``generate_attn_arg_prefill`` exactly while the GPU ``kv_indices`` stay unchanged. - """ + """Build verify indptr on CPU to avoid FlashInfer plan's blocking GPU-to-host synchronization.""" n = draft_token_num qo_indptr = torch.arange(0, (bs + 1) * n, step=n, dtype=torch.int32) kv_len_arr = seq_lens_cpu[:bs].to(torch.int32) + n @@ -120,11 +108,7 @@ def _verify_plan_indptr_cpu(bs, draft_token_num, seq_lens_cpu): def _extend_plan_indptr_cpu(bs, seq_lens_cpu, extend_seq_lens_cpu): - """Host-side plan indptr for non-spec paged extend / draft-extend, skipping the - plan's blocking ``.to("cpu")`` sync. ``kv_len == seq_len`` and - ``q_len == extend_len`` match the GPU cumsum in ``call_begin_forward`` exactly - while the GPU ``kv_indices`` stay unchanged. - """ + """Build extend indptr on CPU to avoid FlashInfer plan's blocking GPU-to-host synchronization.""" kv_len_arr = seq_lens_cpu[:bs].to(torch.int32) kv_indptr = torch.zeros(bs + 1, dtype=torch.int32) kv_indptr[1:] = torch.cumsum(kv_len_arr, dim=0) @@ -817,11 +801,7 @@ def _dequant_referenced_kv_extend(self, k_fp8): return _referenced_kv_to_bf16(k_fp8, idx) def _scaled_fp8_kv_kwargs(self, k_fp8, kv_indices, kv_indptr=None, kv_indptr_idx=0): - """Split a scaled-fp8 KV row (``[ckv fp8 | per-128-group fp32 scales]``) into the - fp8 ckv view and the ``run()`` kwargs carrying the contiguous per-group scales. - Only the referenced rows are gathered into the persistent scale buffer, which - mirrors the pool layout so the kernel reads it with the same physical indices. - """ + """Gather referenced per-group FP8 scales into an index-compatible persistent buffer.""" assert self.use_dsa_scaled_kv assert self._dsa_ckv_scale_buf is not None scale_src = k_fp8[ diff --git a/python/sglang/srt/layers/attention/hybrid_linear_attn_backend.py b/python/sglang/srt/layers/attention/hybrid_linear_attn_backend.py index 5b7d551207de3..8530cf99cabec 100644 --- a/python/sglang/srt/layers/attention/hybrid_linear_attn_backend.py +++ b/python/sglang/srt/layers/attention/hybrid_linear_attn_backend.py @@ -194,9 +194,8 @@ def _forward_metadata(self, forward_batch: ForwardBatch): and forward_batch.extend_seq_lens is not None ) if forward_batch.forward_mode.is_draft_extend_v2() and not has_extend_meta: - # HybridLinearAttnBackend.init_forward_metadata calls all sub-backends - # unconditionally, but DRAFT_EXTEND_V2 only runs full-attn layers in - # the draft model, so mamba metadata can be skipped. + # Draft-extend-v2 may omit linear metadata when the draft runs only + # full-attention layers. query_start_loc = None elif forward_batch.forward_mode.is_target_verify(): ragged_layout = forward_batch.spec_info.ragged_verify_layout @@ -1014,9 +1013,8 @@ def use_mha(self) -> bool: @property def kv_cache_dtype(self): - # DSA/NSA fused-rope path (forward_mla._fuse_rope_for_trtllm_mla) reads - # this off get_attn_backend(), which returns this wrapper; delegate to - # the wrapped full-attn (DSA) backend that actually owns it. + # Expose the full-attention backend's cache dtype because fused DSA/NSA RoPE + # reads it from this wrapper. return getattr(self.full_attn_backend, "kv_cache_dtype", None) def _is_full_attn( diff --git a/python/sglang/srt/layers/attention/linear/kda_backend.py b/python/sglang/srt/layers/attention/linear/kda_backend.py index 528b188344a5f..ca5cf9b9cdacc 100644 --- a/python/sglang/srt/layers/attention/linear/kda_backend.py +++ b/python/sglang/srt/layers/attention/linear/kda_backend.py @@ -378,15 +378,12 @@ class KDAAttnBackend(MambaAttnBackendBase): # to its dense layout, so ragged verify graphs are supported. supports_ragged_verify_graph: bool = True - # Target graph loading snapshots request-to-state indices and fixed replay - # metadata only. Candidate conv/SSM states stay isolated until acceptance - # commits them on the main forward stream, so metadata loading is safe on - # the MTP plan stream after the draft/tree handoff event. + # Candidate states remain isolated until acceptance, so target metadata may load + # on the MTP plan stream. supports_overlap_plan_stream_graph_load: bool = True - # KDA graph replay receives padding explicitly and does not use the generic - # ReplaySSM host-seqlen force-flush path. Keep the speculative length relay - # on device instead of synchronizing a D2H mirror every MTP cycle. + # KDA gets graph padding explicitly and never uses ReplaySSM's host-seqlen + # force-flush path. needs_cpu_seq_lens: bool = False def __init__(self, model_runner: ModelRunner): @@ -552,8 +549,7 @@ def forward_decode( conv_state_indices=cache_indices, ) - # The packed kernel assumes one token per request. It does not support - # the GLM-5 lower-bound gate variant, which stays on the unfused path. + # The packed kernel assumes one token per request. if ( self.kernel_dispatcher.supports_packed_decode and getattr(layer, "lower_bound", None) is None @@ -677,7 +673,6 @@ def forward_extend( gate_was_flat = a.ndim == 3 if gate_was_flat: - # Kernel backends use the explicit [B, T, H, D] gate layout. a = a.unflatten(-1, (-1, layer.head_k_dim)) track_ssm = self.forward_metadata.has_mamba_track_mask diff --git a/python/sglang/srt/layers/attention/linear/kernels/kda_flashkda.py b/python/sglang/srt/layers/attention/linear/kernels/kda_flashkda.py index 3b90607fde457..8e8a184b89a13 100644 --- a/python/sglang/srt/layers/attention/linear/kernels/kda_flashkda.py +++ b/python/sglang/srt/layers/attention/linear/kernels/kda_flashkda.py @@ -226,9 +226,8 @@ def _flashkda_extend( v = v.contiguous() g = g.contiguous() - # GLM-5 passes raw beta logits. Kimi Linear currently passes an already - # activated beta, which must be inverted because FlashKDA applies - # sigmoid internally. + # FlashKDA applies sigmoid internally; invert only the already-activated + # Kimi beta path. if not beta_is_raw: beta = torch.logit(beta.float().clamp_(1e-7, 1.0 - 1e-7)) beta = beta.to(torch.bfloat16).contiguous() diff --git a/python/sglang/srt/layers/attention/linear/kernels/kda_triton.py b/python/sglang/srt/layers/attention/linear/kernels/kda_triton.py index c010af5953638..3e47054d76fae 100644 --- a/python/sglang/srt/layers/attention/linear/kernels/kda_triton.py +++ b/python/sglang/srt/layers/attention/linear/kernels/kda_triton.py @@ -231,10 +231,8 @@ def extend( return_intermediate_states: bool = False, **kwargs, ) -> torch.Tensor: - # CP/DP padding marks zero-length requests with -1, which - # chunk_gated_delta_rule_fwd_h skips (`valid_state = index >= 0` gates - # both the initial-state load and the in-place final-state store), so - # the sentinel is passed through unmodified as on the non-GLM path. + # Preserve -1 padding sentinels: chunk_gated_delta_rule_fwd_h masks both + # state loads and stores for them. return chunk_kda( q=q, k=k, diff --git a/python/sglang/srt/layers/communicator.py b/python/sglang/srt/layers/communicator.py index 084d76d23bff6..fd2705964799a 100644 --- a/python/sglang/srt/layers/communicator.py +++ b/python/sglang/srt/layers/communicator.py @@ -272,9 +272,8 @@ def __init__(self): self.is_dsa = False def init_context(self, q_lora_rank, is_dsa, is_mhc=False): - # DSA + input_scattered requires hidden_states to be attn_tp-gathered - # before the attention call. Currently only MHC's prepare_attn does this - # pre-gather; hence is_mhc gates DSA's eligibility for input_scattered. + # Only MHC pre-gathers hidden states before DSA attention, so non-MHC DSA + # cannot use scattered inputs. self.is_dsa = is_dsa self.allow_input_scattered = ( get_parallel().config.enable_attn_tp_input_scattered @@ -463,9 +462,8 @@ def tp_reduce_scatter( residual: Optional[torch.Tensor], context: "CommunicateContext", ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: - """Reduce-scatter ``hidden_states`` over the full TP group and slice - ``residual`` to this rank. Module-level so variant communicators (e.g. MHC) - can reuse it without holding a ``LayerCommunicator`` instance.""" + """Module-level so MHC communicators can reuse it without a + ``LayerCommunicator`` instance.""" if hidden_states.shape[0] == 0: return hidden_states, hidden_states assert ( diff --git a/python/sglang/srt/layers/communicator_dsa_cp.py b/python/sglang/srt/layers/communicator_dsa_cp.py index 2d3893178ead0..0b74d65be0112 100644 --- a/python/sglang/srt/layers/communicator_dsa_cp.py +++ b/python/sglang/srt/layers/communicator_dsa_cp.py @@ -53,12 +53,7 @@ def maybe_prefetch_next_full_attention_kv( forward_batch: ForwardBatch, next_full_attention_layer_id: Optional[int], ) -> None: - """Prefetch (owner-broadcast) the next layer's DSA KV under layer split. - - Hybrid pools expose ``prefetch_full_attention_kv_buffer`` to translate the - model layer id to the compact full-attention pool id. Non-hybrid - layer-sharded pools expose ``prefetch_kv_buffer`` directly. - """ + """Hybrid pools map model layer IDs to compact full-attention pool IDs.""" if next_full_attention_layer_id is None or not dsa_use_prefill_cp(forward_batch): return diff --git a/python/sglang/srt/layers/communicator_mhc.py b/python/sglang/srt/layers/communicator_mhc.py index 4c3ea020ca1fb..9c1618ba0ae62 100644 --- a/python/sglang/srt/layers/communicator_mhc.py +++ b/python/sglang/srt/layers/communicator_mhc.py @@ -11,14 +11,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== -"""MHC (Manifold-Constrained Hyper-Connections) communicator for attention preparation. - -Adapted from the GLM reference: NSA naming -> DSA (``dsa_use_prefill_cp``, -``ctx.is_dsa``). ``hc_expand`` / ``hc_contract`` live in ``layers/mhc.py``; -the hc_mult-width local DP buffer is exposed via -``get_local_dp_buffer_mhc(get_tp_group(), n)``. -""" - from dataclasses import dataclass from functools import partial from typing import Callable, Optional @@ -74,15 +66,8 @@ def tp_all_gather_hidden_states(hidden_states, forward_batch): @dataclass class MHCState: - """ - Per-layer mHC runtime scratch. - - The parameter-bearing pre/post stages live on the owning layer and - are injected here as callables (``hc_attn_pre`` / ``hc_ffn_pre`` / - ``hc_post``); this class only orchestrates the cross-stage scratch - (``h_res``, ``h_post``) and exposes the layer's ``hc_mult`` for the - few sites that need it as a raw scalar. - """ + """Parameters belong to the owning layer; this state only holds scratch + shared across communication stages.""" hc_mult: int hc_attn_pre: Callable @@ -367,12 +352,8 @@ def _scatter_hidden_states( get_local_dp_buffer_mhc(get_tp_group(), 1), hidden_states, ) - # Mirror CommunicateSummableTensorPairFn._scatter_hidden_states: when - # should_use_dp_reduce_scatterv() is true, the MoE skipped its - # post-experts all-reduce (should_skip_post_experts_all_reduce) on the - # promise that THIS scatter performs the combine. Without this branch, - # SUM_LEN rounds take the non-reducing dp_scatter and every DP rank's - # tokens keep only that rank's local-expert partial sums. + # MoE skips its post-expert all-reduce with reduce_scatterv, so this + # scatter must reduce while combining local-expert partial sums. if should_use_dp_reduce_scatterv(): get_tp_group().reduce_scatterv( global_hidden_states, @@ -473,9 +454,8 @@ def __init__( ) def _post_init_communicate(self): - # MOE_FULL resolves to base *_moe methods that take no `mhc`, which - # this subclass passes unconditionally -> runtime TypeError. Not wired - # for MHC yet; fail loudly at construction instead. + # Base MOE_FULL callables do not accept ``mhc``, so reject this + # combination at construction. if self.layer_scatter_modes.mlp_mode == ScatterMode.MOE_FULL: raise NotImplementedError( "MHCLayerCommunicator does not support MOE_FULL " @@ -531,9 +511,8 @@ def prepare_attn( context=self._context, ) - # Pre-gather to avoid duplicate all_gather in DSA; without a - # qkv_latent hook the attention impl reads mixed_qkv directly, so the - # full hidden_states must be materialized here. + # DSA and attention without a QKV hook consume full hidden states, so + # gather them before attention. ctx = get_attn_tp_context() dsa_pre_gather = ctx.input_scattered and ctx.is_dsa no_qkv_latent_pre_gather = ctx.input_scattered and self.qkv_latent_func is None @@ -596,10 +575,8 @@ def should_use_reduce_scatter(self, forward_batch: ForwardBatch): self._communicate_summable_tensor_pair_fn is MHCCommunicateSummableTensorPairFn._scatter_hidden_states ): - # Mirror LayerCommunicator.should_use_reduce_scatter (PR #24785): - # True on should_use_dp_reduce_scatterv() regardless of padding - # mode, else RowParallelLinear keeps all-reducing the dense MLP - # while the scatter above reduce-scatters on top of it. + # reduce_scatterv already combines expert outputs; returning False + # would make RowParallelLinear perform an extra all-reduce. if should_use_dp_reduce_scatterv(): return True if forward_batch.dp_padding_mode.is_max_len(): diff --git a/python/sglang/srt/layers/communicator_mhc_hybrid_cp.py b/python/sglang/srt/layers/communicator_mhc_hybrid_cp.py index 6a1d9717b6025..f40b58aa1b2c2 100644 --- a/python/sglang/srt/layers/communicator_mhc_hybrid_cp.py +++ b/python/sglang/srt/layers/communicator_mhc_hybrid_cp.py @@ -11,11 +11,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== -"""MHC + DSA prefill-CP hybrid communicator. - -hc_mult-width local DP buffer is routed through ``get_local_dp_buffer_mhc``. -""" - from functools import partial from typing import Optional @@ -55,18 +50,22 @@ def _post_init_communicate(self): output_mode=ScatterMode.SCATTERED, context=self._context, ) - self._communicate_with_all_reduce_and_layer_norm_fn = MHCHybridDSACPCommunicateWithAllReduceAndLayerNormFn.get_fn( - hidden_states_input_mode=ScatterMode.SCATTERED, - residual_input_mode=ScatterMode.SCATTERED, - hidden_states_output_mode=self.layer_scatter_modes.mlp_mode, # SCATTERED, FULL - residual_output_mode=ScatterMode.SCATTERED, - context=self._context, + self._communicate_with_all_reduce_and_layer_norm_fn = ( + MHCHybridDSACPCommunicateWithAllReduceAndLayerNormFn.get_fn( + hidden_states_input_mode=ScatterMode.SCATTERED, + residual_input_mode=ScatterMode.SCATTERED, + hidden_states_output_mode=self.layer_scatter_modes.mlp_mode, + residual_output_mode=ScatterMode.SCATTERED, + context=self._context, + ) ) - self._communicate_summable_tensor_pair_fn = MHCHybridDSACPCommunicateSummableTensorPairFn.get_fn( - hidden_states_input_mode=self.layer_scatter_modes.mlp_mode, # SCATTERED, FULL - residual_input_mode=ScatterMode.SCATTERED, - output_mode=ScatterMode.SCATTERED, - context=self._context, + self._communicate_summable_tensor_pair_fn = ( + MHCHybridDSACPCommunicateSummableTensorPairFn.get_fn( + hidden_states_input_mode=self.layer_scatter_modes.mlp_mode, + residual_input_mode=ScatterMode.SCATTERED, + output_mode=ScatterMode.SCATTERED, + context=self._context, + ) ) def maybe_prefetch_next_full_attention_kv( diff --git a/python/sglang/srt/layers/quantization/quark/utils.py b/python/sglang/srt/layers/quantization/quark/utils.py index 1cdf8d4e70d63..5eb35af80149b 100644 --- a/python/sglang/srt/layers/quantization/quark/utils.py +++ b/python/sglang/srt/layers/quantization/quark/utils.py @@ -55,9 +55,8 @@ def should_ignore_layer( # proj_name = qkv_proj proj_name = layer_name.split(".")[-1] - # Some checkpoints serialize an already-fused module (for example a - # vision ``qkv`` projection) and list that fused name in ``exclude``. - # Honor the direct match before expanding model-level packed mappings. + # A serialized fused module may appear directly in ``exclude``, so match it + # before expanding the packed mapping. if check_equal_or_regex_match(layer_name=layer_name, targets=ignore): return True diff --git a/python/sglang/srt/managers/scheduler.py b/python/sglang/srt/managers/scheduler.py index d39ac479f749e..fdd31ddb28e1b 100644 --- a/python/sglang/srt/managers/scheduler.py +++ b/python/sglang/srt/managers/scheduler.py @@ -1565,9 +1565,8 @@ def init_deterministic_inference_config(self): ) def init_dsa_kpool_truncation_align(self): - """The kpool compress-write path asserts each chunked extend starts on a - pool boundary; truncation_align_size enforces that per request. LCM with - any existing align size so deterministic inference and kpool coexist.""" + """Kpool compress-write asserts chunked extends start on pool boundaries. + Use the LCM to preserve any existing deterministic-inference alignment.""" from sglang.srt.configs.model_config import ( get_dsa_index_kpool, is_deepseek_dsa, diff --git a/python/sglang/srt/managers/tokenizer_manager.py b/python/sglang/srt/managers/tokenizer_manager.py index d95d8e15be3ed..fd73d4b7ffbd0 100644 --- a/python/sglang/srt/managers/tokenizer_manager.py +++ b/python/sglang/srt/managers/tokenizer_manager.py @@ -828,13 +828,8 @@ async def generate_request( ): yield response except BaseException: - # _init_req_state created a rid_to_state entry per (sub-)request up - # front. The normal remover is the scheduler-response path - # (_handle_batch_output), so a failure *before* a request reaches the - # scheduler -- e.g. input-length validation rejecting an over-context - # request -- would otherwise leak those entries forever. Drop - # undelivered states, but abort dispatched requests for scheduler-side - # cleanup. + # A batch may fail after partial dispatch; abort dispatched RIDs so + # scheduler resources are released. self._release_req_states_on_failure(request_rids) raise @@ -1581,11 +1576,6 @@ def _send_one_request( self.cuda_vmm_feature_transport.cancel_for_dispatch(prepared_mm_items) def _mark_state_dispatched(self, rid: str): - """Record that *rid* reached the scheduler. - - Only dispatched requests are aborted (not discarded) by the - handler-failure cleanup; see _release_req_states_on_failure. - """ state = self.rid_to_state.get(rid) if state is not None: state.dispatched = True @@ -3446,11 +3436,7 @@ def _init_req_state( time_stats.set_created_time(created_time) def _release_req_states_on_failure(self, rids: Iterable[str]): - """Release rid_to_state entries created for a failed handler. - - Undelivered states are removed locally. Dispatched requests are aborted - and retained until the scheduler response removes them. - """ + """Keep dispatched states until the scheduler acknowledges their abort.""" for rid in rids: state = self.rid_to_state.get(rid) if state is None: diff --git a/python/sglang/srt/mem_cache/hybrid_cache/hybrid_pool_assembler.py b/python/sglang/srt/mem_cache/hybrid_cache/hybrid_pool_assembler.py index 01672d854b9c3..35862cd4d29be 100644 --- a/python/sglang/srt/mem_cache/hybrid_cache/hybrid_pool_assembler.py +++ b/python/sglang/srt/mem_cache/hybrid_cache/hybrid_pool_assembler.py @@ -714,7 +714,6 @@ def build_hybrid_mamba_stack( mamba_allocator = params.req_to_token_pool.mamba_allocator from sglang.srt.mem_cache.memory_pool import HybridLinearKVPool - # Hybrid drafts wrap attention KV in HybridLinearKVPool; DSA drafts are bare pools. mtp_draft_device_pools = tuple( pool.full_kv_pool if isinstance(pool, HybridLinearKVPool) else pool for pool in params.mtp_draft_device_pools diff --git a/python/sglang/srt/mem_cache/kv_cache_configurator.py b/python/sglang/srt/mem_cache/kv_cache_configurator.py index 16214ffe30177..e1ecf6132e11c 100644 --- a/python/sglang/srt/mem_cache/kv_cache_configurator.py +++ b/python/sglang/srt/mem_cache/kv_cache_configurator.py @@ -1594,8 +1594,6 @@ def _build_hybrid_linear_kv_pool( "kv_lora_rank": self.model_config.kv_lora_rank, "qk_rope_head_dim": self.model_config.qk_rope_head_dim, } - # Route DSATokenToKVPool in as the hybrid pool's full_kv_pool - # instead of a dense MLA pool. if is_deepseek_dsa(self.model_config.hf_config): from sglang.srt.layers.cp.utils import get_glm_dsa_cp_layer_shard_info diff --git a/python/sglang/srt/mem_cache/memory_pool.py b/python/sglang/srt/mem_cache/memory_pool.py index 16ad8c6722fe2..ec04261a110f2 100644 --- a/python/sglang/srt/mem_cache/memory_pool.py +++ b/python/sglang/srt/mem_cache/memory_pool.py @@ -4859,7 +4859,7 @@ def _init_kpool_compress_tail_buffers( device: str, max_running_requests: Optional[int], ) -> None: - """In-flight per-request bf16 key/score tail buffers; kept on the pool, not the Indexer, because they are part of the index cache state.""" + """Keep request tails on the pool so they follow the index-cache lifecycle.""" self.kpool_use_compress = index_kpool > 1 and index_kpool_compress if not self.kpool_use_compress: @@ -4914,7 +4914,6 @@ def get_compress_tail_buffers( ) def get_compress_tail_buf_infos(self): - """Buffer infos for per-request DSA kpool compress-tail rows.""" if not self.kpool_use_compress: return [], [], [] if self.layer_shard_enabled: @@ -4982,8 +4981,7 @@ def set_compress_tail_for_request( n_remain: int, dst_logical_start: int, ) -> None: - """Overwrite per-request tail ring rows after a chunk. ``n_remain == 0`` - means the chunk landed on a pool boundary, no tail carries over.""" + """Leave the ring untouched at a pool boundary; no tail carries over.""" assert ( self.kpool_use_compress ), "set_compress_tail_for_request called when kpool compress is disabled" @@ -5090,11 +5088,7 @@ def _load_compress_tail_cpu_copy(self, tail_k_cpu, tail_score_cpu, req_pool_inde ) def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): - # DSA keeps a page-indexed index_k_with_scale_buffer alongside kv_buffer. - # Retract frees the slots/pages and they get reused by other reqs' - # set_index_k_scale_buffer, so we must offload it here too -- otherwise - # resume restores kv_buffer but leaves foreign index/scale in place and - # DSA attention reads garbage at those token positions. + # Retraction reuses index-cache pages; offload index/scale with KV so resume cannot read another request's entries. kv_cache_cpu = super().get_cpu_copy(indices, mamba_indices=mamba_indices) cpu_copy = { "kv": kv_cache_cpu, diff --git a/python/sglang/srt/mem_cache/radix_cache.py b/python/sglang/srt/mem_cache/radix_cache.py index e2e14c0b7958f..b5a9ff562245c 100644 --- a/python/sglang/srt/mem_cache/radix_cache.py +++ b/python/sglang/srt/mem_cache/radix_cache.py @@ -183,11 +183,7 @@ def match(self, other: RadixKey, page_size: int = 1) -> int: return self.match_at(other, offset=0, page_size=page_size) def match_at(self, other: RadixKey, offset: int, page_size: int = 1) -> int: - """Match this key against ``other`` starting at a logical offset. - - This is the no-copy equivalent of ``self.match(other[offset:])`` and - preserves bigram boundary-token semantics and ``limit`` handling. - """ + """Match without slicing while preserving bigram boundaries and limit semantics.""" self._check_compatible(other) if self.is_bigram != other.is_bigram: raise ValueError("RadixKey operations require matching bigram modes") diff --git a/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha.py b/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha.py index b680fbfe5e10f..2aa3f13b8f260 100644 --- a/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha.py +++ b/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha.py @@ -431,9 +431,8 @@ def _set_mla_kv_buffer( dsa_use_prefill_cp(forward_batch, self.dsa_enable_prefill_cp) or mla_use_prefill_cp(forward_batch, self.mla_enable_prefill_cp) ) and not is_cp_v2_active(forward_batch): - # CP-v1 keeps Q rank-local, but every rank owns a complete KV pool. - # Rebuild the zigzag-split latent KV in global token order before - # writing it with the (unsplit) out_cache_loc indices. + # CP-v1 keeps Q rank-local but gives every rank a complete KV pool, so + # rebuild KV in global token order against the unsplit out_cache_loc. kv_a, k_pe = self.rebuild_cp_kv_cache( latent_cache.squeeze(1), forward_batch, diff --git a/python/sglang/srt/models/glm5_next.py b/python/sglang/srt/models/glm5_next.py index c4b1566fd7e65..63a99fdb85248 100644 --- a/python/sglang/srt/models/glm5_next.py +++ b/python/sglang/srt/models/glm5_next.py @@ -378,15 +378,15 @@ def __init__( self.fused_qkvbfg_a_proj = MergedColumnParallelRepeatedLinear( self.hidden_size, - self.qkvb_sizes, # column parallel: q, k, v, beta - self.fg_sizes, # replicated: f_a, g_a + self.qkvb_sizes, + self.fg_sizes, quant_config=quant_config, prefix=f"{prefix}.fused_qkvbfg_a_proj", ) self.split_sizes = [ - 3 * projection_size // head_shard_size, # qkv - self.num_heads // head_shard_size, # beta - 2 * self.head_dim, # f_a, g_a (replicated) + 3 * projection_size // head_shard_size, + self.num_heads // head_shard_size, + 2 * self.head_dim, ] fused_dtype = ( getattr(config, "dtype", None) @@ -472,9 +472,8 @@ def __init__( tp_rank=head_shard_rank, tp_size=head_shard_size, ) - # unsqueeze to fit conv1d weights shape into the linear weights shape. - # Can't do this in `weight_loader` since it already exists in - # `ColumnParallelLinear` and `set_weight_attrs` doesn't allow override. + # ColumnParallelLinear's loader cannot reshape conv1d weights, so add the + # singleton dimension after construction. self.qkv_conv1d.weight.data = self.qkv_conv1d.weight.data.unsqueeze(1) self.A_log = nn.Parameter( @@ -588,11 +587,9 @@ def forward( b=beta, ) - norm_gate = g_proj_states.unflatten( - -1, (-1, self.head_dim) - ) # ... (h d) -> ... h d + norm_gate = g_proj_states.unflatten(-1, (-1, self.head_dim)) core_attn_out = self.o_norm(core_attn_out, norm_gate) - core_attn_out = core_attn_out.squeeze(0).flatten(-2) # 1 n h d -> n (h d) + core_attn_out = core_attn_out.squeeze(0).flatten(-2) output = self.o_proj(core_attn_out)[0] if dsa_use_prefill_cp(forward_batch, self.enable_prefill_cp): @@ -724,10 +721,8 @@ def __init__( mix_hc = (2 + hc_mult) * hc_mult hc_dim = hc_mult * config.hidden_size - # mHC params live directly on the decoder layer so their names - # (hc_{attn,ffn}_{base,scale,fn}) match the ckpt verbatim and - # default_weight_loader hits them without any rename. The - # communicator reads them at runtime via MHCState(layer=self). + # Keep mHC params directly on the decoder layer so their names match + # the checkpoint verbatim. self.hc_attn_base = nn.Parameter(torch.empty(mix_hc, dtype=torch.float32)) self.hc_attn_scale = nn.Parameter(torch.empty(3, dtype=torch.float32)) self.hc_attn_fn = nn.Parameter( @@ -796,7 +791,6 @@ def _hc_pre( ) def hc_attn_pre(self, hidden_states, out_norm_weight, out_norm_eps): - """Attention-stage mHC pre: hidden_states ``[s, hc_mult*hidden]`` -> (layer_input [s,hidden], h_res [s,n*n], h_post [s,n], norm_fused).""" return self._hc_pre( self.hc_attn_fn, self.hc_attn_scale, @@ -817,7 +811,6 @@ def hc_ffn_pre(self, hidden_states, out_norm_weight, out_norm_eps): ) def hc_post(self, hidden_states, residual, h_res, h_post): - """mHC post-stage (parameter-free, scalar hc_mult only).""" assert self.config.mhc, "hc_post is only valid when config.mhc=True" return _hc_post_fn( x=hidden_states, @@ -836,7 +829,6 @@ def hc_attn_to_mlp( out_norm_weight, out_norm_eps, ): - """Fuse attention mHC post with FFN mHC pre on AITER gfx95.""" global _GLM_AITER_FUSED_MHC_LOGGED from sglang.srt.models.deepseek_common.amd.deepseek_v4_fused_mhc import ( @@ -899,21 +891,14 @@ def forward( ): hidden_states_orig = hidden_states - # Attn-input prep, MHC attn_split, and (DSA-CP) scatter all happen inside - # the communicator; it also stores the AttentionInputs for fetch_qkv_latent. hidden_states, residual = self.layer_communicator.prepare_attn( hidden_states, residual, forward_batch, ) - # MLA's CP attention consumes the scattered (round-robin/zigzag) - # layout while the cross-layer contract is plain (block-contiguous, - # see Glm5NextModel.forward). KDA handles its own CP gather/scatter - # inside Glm5NextLinearAttention, so only MLA layers need this wrap. - # NOTE: prepare_attn already stored an AttentionInputs referencing the - # plain hidden_states for fetch_qkv_latent(); rebind that ref to the - # scattered tensor so q/kv latent and positions stay token-aligned. + # MLA consumes scattered CP layout, so rebind cached AttentionInputs to the + # scattered tensor to keep Q/KV latents and positions token-aligned. mla_cp_wrap = not self.is_linear_attn and ( dsa_use_prefill_cp(forward_batch, self.dsa_enable_prefill_cp) or mla_use_prefill_cp(forward_batch, self.mla_enable_prefill_cp) @@ -959,7 +944,6 @@ def forward( ) ) - # For DP with padding, reduce scatter can be used instead of all-reduce. use_reduce_scatter = self.layer_communicator.should_use_reduce_scatter( forward_batch ) @@ -1133,9 +1117,8 @@ def get_input_embeddings(self) -> torch.Tensor: def _prepare_aux_hidden_state( self, hidden_states: torch.Tensor, residual: Optional[torch.Tensor] ) -> torch.Tensor: - # Under mHC the residual is folded into the widened hidden state, so the - # layer communicator hands back residual=None and hc_contract below does - # the merge. Only the plain residual-stream path has a tensor to add. + # mHC folds the residual into widened hidden state, so residual remains None + # until hc_contract merges it; only plain residual streams are added here. aux_hidden_state = ( hidden_states if residual is None else hidden_states + residual ) @@ -1656,10 +1639,8 @@ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]], is_nextn=Fal raise ValueError("num_nextn_predict_layers is not in the config") stacked_params_mapping = [ - # (param_name, shard_name, shard_id) ("gate_up_proj", "gate_proj", 0), ("gate_up_proj", "up_proj", 1), - # Fused path (".fused_qkvbfg_a_proj", ".q_proj", 0), (".fused_qkvbfg_a_proj", ".k_proj", 1), (".fused_qkvbfg_a_proj", ".v_proj", 2), @@ -1668,11 +1649,9 @@ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]], is_nextn=Fal (".fused_qkvbfg_a_proj", ".g_a_proj", 5), (".fused_fg_b_proj", ".f_b_proj", 0), (".fused_fg_b_proj", ".g_b_proj", 1), - # Unfused path: separate qkv_proj (when do_fuse_qkvbfg=False) (".qkv_proj", ".q_proj", "q"), (".qkv_proj", ".k_proj", "k"), (".qkv_proj", ".v_proj", "v"), - # qkv conv fuse (".qkv_conv1d", ".q_conv1d", 0), (".qkv_conv1d", ".k_conv1d", 1), (".qkv_conv1d", ".v_conv1d", 2), diff --git a/python/sglang/srt/models/glm5_next_nextn.py b/python/sglang/srt/models/glm5_next_nextn.py index 3ae3112dcb6e4..fb7cf55549d2b 100644 --- a/python/sglang/srt/models/glm5_next_nextn.py +++ b/python/sglang/srt/models/glm5_next_nextn.py @@ -12,8 +12,6 @@ # limitations under the License. # ============================================================================== -"""Inference-only GLM5-Next Speculative Decoding.""" - import logging from sglang.srt.models.deepseek_nextn import DeepseekV3ForCausalLMNextN @@ -34,15 +32,8 @@ def get_hf_to_sglang_mapper(cls, config) -> WeightsMapper: ) def _resolve_nextn_quant_config(self, config, quant_config): - """Keep a checkpoint-declared BF16 NextN block unquantized. - - The Hybrid FP8+NVFP4 checkpoint advertises a global FP8 quantization - method, but its full ``model.layers..*`` NextN block - is listed in ``quantization_config.ignore`` and stored as BF16. Passing - the target quant config into that block allocates FP8 parameters and - loads the BF16 payload without matching scales, corrupting the first - QKV projection. - """ + """Mixed checkpoints list the BF16 NextN block in ``quantization_config.ignore``; + inheriting global FP8 quantization would corrupt its QKV weights.""" raw_quant_config = getattr(config, "quantization_config", None) or {} if hasattr(raw_quant_config, "to_dict"): raw_quant_config = raw_quant_config.to_dict() diff --git a/python/sglang/srt/multimodal/mm_utils.py b/python/sglang/srt/multimodal/mm_utils.py index 91526c425b6aa..dcdb006797ef2 100644 --- a/python/sglang/srt/multimodal/mm_utils.py +++ b/python/sglang/srt/multimodal/mm_utils.py @@ -831,11 +831,7 @@ def run_dp_presharded_mrope_vision_model( global_grid_thw_list: list, gpu_sample_counts: list, ) -> torch.Tensor: - """Run a vision tower when video decode already sharded temporal units. - - Rank-local inputs are contiguous pieces of the global video, so stripping - all-gather padding and concatenating rank order restores global order. - """ + """Rank-local shards are contiguous, so rank-order concatenation restores global video order.""" parallel = get_parallel() tp_size = parallel.attn_tp_size patches_per_unit = [math.prod(grid) for grid in global_grid_thw_list] diff --git a/python/sglang/srt/multimodal/processors/base_processor.py b/python/sglang/srt/multimodal/processors/base_processor.py index 9e31472f6dd6c..354ec56162586 100644 --- a/python/sglang/srt/multimodal/processors/base_processor.py +++ b/python/sglang/srt/multimodal/processors/base_processor.py @@ -721,9 +721,7 @@ def process_mm_data( if processor_device is not None: kwargs["device"] = processor_device - # Model families may keep video preprocessing off the GPU: the - # tokenizer process otherwise competes with the scheduler's pools for - # device memory on long videos. + # Long-video preprocessing stays on CPU to avoid competing with scheduler GPU pools. if videos: video_device = getattr(self, "video_preprocessing_device", None) if video_device is not None: diff --git a/python/sglang/srt/multimodal/processors/glm4v.py b/python/sglang/srt/multimodal/processors/glm4v.py index 7aeafc9cf5d60..2ae08f977048e 100644 --- a/python/sglang/srt/multimodal/processors/glm4v.py +++ b/python/sglang/srt/multimodal/processors/glm4v.py @@ -63,7 +63,6 @@ def _glm_item_config(item): def split_glm_video_items(mm_data): - """Extract per-video controls and return sources suitable for decoding.""" if mm_data is None: return None, [] items = mm_data if isinstance(mm_data, (list, tuple)) else [mm_data] @@ -80,7 +79,6 @@ def split_glm_video_items(mm_data): def glm_budget_kwargs(processor, user_max_image_tokens=None, count=1, split=False): - """Resolve an optional per-item visual-token budget for a HF processor.""" if processor is None: return None default_max = getattr(processor, "max_image_tokens", None) @@ -102,7 +100,6 @@ def glm_budget_kwargs(processor, user_max_image_tokens=None, count=1, split=Fals def glm_max_image_tokens_from_configs(configs): - """Return the tightest max_image_tokens override across media items.""" values = [ int(config["max_image_tokens"]) for config in configs or [] @@ -112,7 +109,6 @@ def glm_max_image_tokens_from_configs(configs): def glm_processor_video_config(processor): - """Read GLM video defaults exposed by the model's HF processor.""" if processor is None: return {} config = { @@ -127,12 +123,7 @@ def glm_processor_video_config(processor): def _glm_processor_resize_budget(processor): - """Resize geometry inputs mirroring the HF GLM video processor. - - The budget comes from the processor's token limits, not `size`: on - Glm5NextVideoProcessor `size.longest_edge` is a sentinel (1) and the real - bound is `max_image_tokens * temporal_patch_size * (patch*merge)^2`. - """ + """Use token limits because Glm5NextVideoProcessor.size.longest_edge is only a sentinel.""" max_image_tokens = getattr(processor, "max_image_tokens", None) if not max_image_tokens: return None @@ -153,7 +144,6 @@ def _glm_processor_resize_budget(processor): def _glm_effective_presize_budget(video_config, effective_max_image_tokens): - """Overlay the call-effective token budget onto a video's presize budget.""" budget = video_config.get("_presize_budget") if video_config else None if not budget or effective_max_image_tokens is None: return video_config @@ -166,7 +156,6 @@ def _glm_effective_presize_budget(video_config, effective_max_image_tokens): def _merge_glm_video_configs(default_config, item_configs): - """Merge server defaults with per-request overrides.""" defaults = dict(default_config or {}) return [{**defaults, **dict(config or {})} for config in item_configs] @@ -179,12 +168,7 @@ def glm_sample_frame_indices( target_fps=None, max_frame_count=None, ): - """Sample GLM video frames deterministically and keep temporal pairs. - - The algorithm mirrors the GLM/HF processor rather than treating target - timestamps as independent nearest-neighbour lookups. That keeps the - no-override EPD path byte-for-byte aligned with ordinary preprocessing. - """ + """Mirror HF's sequential sampler so EPD stays byte-identical, then preserve temporal pairs.""" if total_frames <= 0: return [] target_fps = GLM_VIDEO_DEFAULT_FPS if target_fps is None else float(target_fps) @@ -238,7 +222,6 @@ def glm_sample_frame_indices( def _resize_frames_to_max_tokens(frames, max_tokens_per_frame): - """Downscale NHWC frames to the GLM per-frame post-merge token budget.""" import torchvision.transforms.functional as TF if not isinstance(frames, torch.Tensor): @@ -268,7 +251,6 @@ def _resize_frames_to_max_tokens(frames, max_tokens_per_frame): def preprocess_video_frames_sync(frame_list: List[dict]): - """Convert a client-provided GLM frame list to processor input.""" total_num_frames = len(frame_list) if total_num_frames == 0: raise ValueError("GLM video frame list must not be empty") @@ -341,14 +323,7 @@ def _pre_resize_frames_for_processor( max_pixels, resize_mode, ): - """Reproduce the HF GLM video processor's resize+pad output ahead of time. - - The HF Glm5Next video processor converts the full stacked tensor to - float32 at native resolution before resizing; handing it an exact copy of - its own output makes its resize a no-op, keeping the final grid identical - while bounding the allocation. The resize runs in chunks because - torchvision materializes float32 intermediates. - """ + """Pre-resize in chunks to avoid HF's native-resolution float32 intermediate while preserving its output grid.""" import torchvision.transforms.functional as TF if not isinstance(frames, torch.Tensor): @@ -392,12 +367,10 @@ def _pre_resize_frames_for_processor( def glm_decode_frames_at(vr, indices, video_config=None): - """Decode only an explicitly assigned frame subset for one encoder rank.""" indices = list(indices) if not indices: return None video_config = video_config or {} - # VideoDecoderWrapper already uses parallel extraction where supported. if hasattr(vr, "get_frames_as_tensor"): frames = vr.get_frames_as_tensor(indices) else: @@ -503,9 +476,7 @@ async def process_mm_data_async( *args, **kwargs, ): - # Normalize inline media dictionaries before loading. In particular, a - # bare base64 video must go through SGLang's decoder rather than being - # forwarded to the HF video loader as a path-like string. + # Bare base64 video must use SGLang's decoder because HF treats it as a path-like string. video_urls, video_configs = split_glm_video_items(request_obj.video_data) video_processor = getattr(self._processor, "video_processor", None) default_video_config = glm_processor_video_config(video_processor) @@ -567,8 +538,7 @@ async def process_mm_data_async( combine_kwargs = {} if video_metadata is not None: - # Frames were already sampled by SGLang. Preserve the original - # indices for timestamps and prevent a second HF sampling pass. + # Skip HF resampling because these frames already carry their original indices. combine_kwargs["video_metadata"] = video_metadata combine_kwargs["do_sample_frames"] = False processor_video_config = { diff --git a/python/sglang/srt/parser/jinja_template_utils.py b/python/sglang/srt/parser/jinja_template_utils.py index fee4d9d823ae8..fbe7456fbc974 100644 --- a/python/sglang/srt/parser/jinja_template_utils.py +++ b/python/sglang/srt/parser/jinja_template_utils.py @@ -121,19 +121,7 @@ def detect_jinja_template_content_format(chat_template: str) -> str: def jinja_template_may_reorder_tool_results(chat_template: str) -> bool: - """Return whether a template associates tool results by call ID. - - A template that reads ``tool_call_id`` can emit tool results in an order - other than the request's message order (for example, by iterating the - assistant's ``tool_calls`` and looking up each matching result). Media is - collected from the request in message order, so those templates need a - rendered-order recovery pass to keep media and placeholders aligned. - - Inspecting the parsed template is deliberately model-agnostic: custom and - future templates get the same behavior without a model-name allowlist or a - runtime environment switch, while templates that simply stream messages in - request order pay no per-request recovery cost. - """ + """Detect call-ID use so rendered media can be realigned without model-specific allowlists.""" if not isinstance(chat_template, str): return False @@ -154,7 +142,6 @@ def is_tool_call_id(node: jinja2.nodes.Node) -> bool: ): return True - # ``message.get('tool_call_id')`` is another common spelling. for call in jinja_ast.find_all(jinja2.nodes.Call): if ( isinstance(call.node, jinja2.nodes.Getattr) @@ -164,9 +151,6 @@ def is_tool_call_id(node: jinja2.nodes.Node) -> bool: ): return True - # Templates can look up or sort result messages without a direct field - # access, e.g. ``messages | selectattr('tool_call_id', 'equalto', id)`` or - # ``messages | sort(attribute='tool_call_id')``. attribute_filters = {"groupby", "map", "rejectattr", "selectattr", "sort"} for filter_node in jinja_ast.find_all(jinja2.nodes.Filter): if filter_node.name not in attribute_filters: @@ -274,9 +258,7 @@ def process_content_for_template_format( {"type": "text", "text": chunk["text"]} ) elif chunk_type == "tool_reference": - # GLM-specific extension: pass through so the chat template - # can match tool_reference.name against tools[*].function.name - # and render the referenced tool schemas inline. + # Preserve this extension because GLM templates resolve referenced tool schemas by function name. processed_content_parts.append(chunk) new_msg = { diff --git a/python/sglang/srt/parser/template_manager.py b/python/sglang/srt/parser/template_manager.py index 84db5a8265529..d69458f870495 100644 --- a/python/sglang/srt/parser/template_manager.py +++ b/python/sglang/srt/parser/template_manager.py @@ -115,7 +115,6 @@ def suggested_tool_call_parser(self) -> Optional[str]: @property def jinja_template_may_reorder_tool_results(self) -> bool: - """Whether the active Jinja template associates results by call ID.""" return self._jinja_template_may_reorder_tool_results def _run_template_detection(self, template, tokenizer) -> None: diff --git a/python/sglang/srt/speculative/eagle_draft_extend_cuda_graph_runner.py b/python/sglang/srt/speculative/eagle_draft_extend_cuda_graph_runner.py index e85a552ecb5e6..f16024780ff69 100644 --- a/python/sglang/srt/speculative/eagle_draft_extend_cuda_graph_runner.py +++ b/python/sglang/srt/speculative/eagle_draft_extend_cuda_graph_runner.py @@ -58,9 +58,7 @@ def resolve_draft_extend_seq_len_fill_value( attn_backend, captured_req_width: int ) -> int: - """DRAFT_EXTEND_V2 subtracts the fixed draft width when building the KPool - write plan; padding rows need enough synthetic history for that subtraction - plus the KPool offset.""" + """Pad synthetic history past the fixed draft-width subtraction and KPool offset.""" fill_value = attn_backend.get_cuda_graph_seq_len_fill_value() full_attn_backend = getattr(attn_backend, "full_attn_backend", attn_backend) dsa_index_kpool = getattr(full_attn_backend, "dsa_index_kpool", 1) diff --git a/python/sglang/srt/speculative/eagle_utils.py b/python/sglang/srt/speculative/eagle_utils.py index 4d6468a039e6f..6d796fa8df686 100644 --- a/python/sglang/srt/speculative/eagle_utils.py +++ b/python/sglang/srt/speculative/eagle_utils.py @@ -591,9 +591,7 @@ def eagle_prepare_for_verify( verify_forward_batch ) ) - # Pure full-attention backends can preload graph metadata on the plan - # stream. Recurrent backends opt in only after their metadata path has - # been audited not to touch state still used by the preceding draft. + # Recurrent backends may defer graph metadata loading because it can mutate state still consumed by the draft. defer_graph_load = overlap_plan_stream and not getattr( target_worker.model_runner.attn_backend, "supports_overlap_plan_stream_graph_load", diff --git a/python/sglang/srt/speculative/eagle_worker_common.py b/python/sglang/srt/speculative/eagle_worker_common.py index acd9de705de27..a16d8a23ce27e 100644 --- a/python/sglang/srt/speculative/eagle_worker_common.py +++ b/python/sglang/srt/speculative/eagle_worker_common.py @@ -485,10 +485,7 @@ def run_eagle_verify( - ``finalize_tree_path``: single-layer compacts the accepted tree path to the front of each per-req block for topk > 1; multi-layer has never run this compaction. - - ``verify_handoff_event``: forward-stream event recorded at the - draft/tree frontier; when set, the plan stream waits on it (letting host - planning run ahead) instead of the full ``wait_stream(fwd_stream)``, - which remains the fallback when None. + - ``verify_handoff_event`` gates plan-stream GPU work at the completed draft/tree frontier. """ fwd_stream = torch.get_device_module(device).current_stream() verify_input: EagleVerifyInput = batch.spec_info diff --git a/python/sglang/srt/speculative/eagle_worker_v2.py b/python/sglang/srt/speculative/eagle_worker_v2.py index 197bf8c2c3960..da17486c5b641 100644 --- a/python/sglang/srt/speculative/eagle_worker_v2.py +++ b/python/sglang/srt/speculative/eagle_worker_v2.py @@ -195,12 +195,8 @@ def __init__( self.tree_mask_mode = default_tree_mask_mode() self.plan_stream, self.plan_stream_ctx = get_plan_stream(self.device) - # Keep phase handoffs outside replayed CUDA graphs. The ring prevents - # a later speculative iteration from re-recording an event that an - # earlier plan-stream wait may still reference. One event per kind - # (verify / draft-extend) is recorded per scheduler cycle and only a - # couple of speculative cycles can be in flight, so a small ring is - # ample. + # Keep handoff events outside captured graphs; per-kind rings avoid + # re-recording an event with a pending wait. handoff_ring_size = 8 if self.plan_stream is not None: event_cls = torch.get_device_module(self.device).Event @@ -218,13 +214,6 @@ def __init__( self._pending_verify_handoff_event = None def _record_handoff_event(self, kind: str, stream): - """Record a phase-handoff event on ``stream`` and return it. - - Returns None when no plan stream exists (single-stream mode). Events - come from a fixed per-kind ring; the ring size must exceed the maximum - number of in-flight speculative iterations so an event is never - re-recorded while a plan-stream wait on it is still pending. - """ if self.plan_stream is None: return None if kind == "verify": @@ -619,9 +608,7 @@ def draft(self, batch: ScheduleBatch): tree_mask_mode=self.tree_mask_mode, device=self.device, ) - # Publish the exact forward-stream frontier that produced the tree and - # verify inputs. Host planning can run ahead, while dependent GPU work - # on the plan stream waits for this event. + # Gate plan-stream GPU work on the forward-stream point that finalized the verify tree. self._pending_verify_handoff_event = self._record_handoff_event( "verify", torch.get_device_module(self.device).current_stream() ) @@ -949,7 +936,6 @@ def _draft_extend_for_prefill( ) def _get_dsa_extend_topk_buf(self, num_tokens: int) -> torch.Tensor: - """Lazily grow the eager draft-extend MTP seed buffer.""" buf = self.dsa_extend_topk_buf if buf is None or buf.shape[0] < num_tokens: buf = torch.full( @@ -1296,12 +1282,7 @@ def forward_batch_generation( # Drafting disabled (high batch size). _draft_extend below still # runs, keeping draft KV warm for when the batch shrinks. verify_input = self._build_trivial_verify_input(batch) - # The trivial input is produced on the current forward stream - # just like a drafted one, but this path bypasses draft() -- - # the only other site recording the verify handoff event. - # Record this cycle's frontier here so the plan-stream verify - # wait neither asserts on a first zero-step cycle nor reuses - # a stale event after an adaptive downshift. + # This zero-step path bypasses draft(), so it must publish the verify handoff itself. self.draft_worker._pending_verify_handoff_event = ( self.draft_worker._record_handoff_event( "verify", diff --git a/python/sglang/srt/speculative/spec_utils.py b/python/sglang/srt/speculative/spec_utils.py index 18d48bf3107cc..bfefff7bd0e87 100644 --- a/python/sglang/srt/speculative/spec_utils.py +++ b/python/sglang/srt/speculative/spec_utils.py @@ -213,16 +213,7 @@ def draft_kv_indices_used_len( def record_stream_each(tensors, stream): - """Call record_stream(stream) on each accelerator tensor in `tensors`, - skipping non-tensor / host entries. Tells the caching allocator that the - tensors are also used on `stream`, so memory is not recycled while - queued work is still in flight after Python refs drop. - - Guarded by device type, not ``is_cuda``: the overlap plan stream runs on - every accelerator with a stream module (NPU/MUSA/XPU included, HIP - reports as cuda), and their caching allocators need the same - cross-stream lifetime hint. - """ + """Protect accelerator tensors from allocator reuse while overlap-stream work is pending.""" for t in tensors: if isinstance(t, torch.Tensor) and t.device.type in ( "cuda", @@ -1026,22 +1017,14 @@ def commit_mamba_states_after_verify( mamba_track_interval = mamba_track_grid(batch.tree_cache.page_size) track_indices_to_pass = batch.mamba_track_indices if _is_cuda and not _is_hip and speculative_eagle_topk in (None, 1): - # Chain spec: accept_index[i, j] == i*draft + j on accepted slots, - # so both gathers below are identities (last step = accept_lens-1, - # candidate step = its own index). One fused launch replaces the - # ~21-op eager prologue. + # For topk=1, accepted node indices equal per-request step indices, so both eager gathers are identities. from sglang.kernels.ops.speculative.eagle import ( nextn_mamba_commit_prologue_func, ) has_track = track_indices_to_pass is not None if has_track: - # Host-side sufficient no-crossing test: post-verify length is - # at most pre + draft_token_num (accept_lens includes the - # bonus and is capped at draft_token_num), so identical - # interval buckets for pre and pre+draft rule out any - # interval crossing this cycle — the whole track commit - # (two scatter launches + wrappers) can be skipped. + # If pre + max accepted tokens stays in the same interval, no tracking snapshot can be needed. seq_lens_cpu = getattr(batch, "seq_lens_cpu", None) interval = mamba_track_interval if seq_lens_cpu is not None and seq_lens_cpu.numel() == bs: @@ -1054,37 +1037,7 @@ def commit_mamba_states_after_verify( has_track = False track_indices_to_pass = None elif interval > 0: - # GPU-only seq_lens (a backend that sets - # needs_cpu_seq_lens = False, e.g. KDA): no CPU - # mirror, so bound the true pre-verify length with the - # scheduler's host counter instead of reading it. - # req.kv_committed_len only advances when a verify - # result is resolved (batch_result_processor), so it is - # a LOWER bound on the device seq_lens, lagging by at - # most one in-flight verify in overlap mode — the same - # lag the doubled alloc reserve absorbs (see - # eagle_prepare_for_decode / get_alloc_reserve_per_decode). - # A verify commits at most the draft size's tokens - # (accept_lens includes the bonus), so with the matching - # 2x safety margin: - # pre_verify_len in [lb, lb + 2 * max_draft] - # and post-verify adds at most max_draft more. - # max_draft must be the CONFIGURED maximum, not this - # cycle's draft_token_num: with adaptive speculation the - # in-flight verify the counter lags behind may have used - # a larger draft than the current (downshifted) cycle, - # and the alloc reserve this lag argument leans on is - # sized by the configured value. Note the plain - # speculative_num_draft_tokens field is NOT that maximum: - # adaptive gear switches sync it to the current gear - # (server_args.override in _restore_worker_state); the - # max_ property is derived from the immutable candidate - # config. floor(x / interval) is monotone, so if lb and - # lb + 3 * max_draft share a bucket, every length - # reachable this cycle does too — no crossing is - # possible and the track commit can be skipped. Any - # uncertainty (missing counter, req/row mismatch) keeps - # the exact full path. + # The host counter may lag one overlap cycle; skip only when the conservative 3x max-draft bound stays in one interval. reqs = getattr(batch, "reqs", None) if reqs is not None and len(reqs) == bs: max_draft = ( @@ -1149,12 +1102,6 @@ def spec_prepare_for_decode(batch: ScheduleBatch) -> None: def get_plan_stream( device: str, ) -> Tuple[Any, contextlib.AbstractContextManager]: - """Return (plan_stream, ctx) when SGLANG_ENABLE_OVERLAP_PLAN_STREAM is on. - - With the flag off this returns (None, nullcontext()), so callers can - unconditionally enter the context and check ``plan_stream is None`` to - detect the single-stream fallback. - """ if envs.SGLANG_ENABLE_OVERLAP_PLAN_STREAM.get(): plan_stream = torch.get_device_module(device).Stream() plan_stream_ctx = torch.get_device_module(device).stream(plan_stream) diff --git a/python/sglang/srt/utils/video_decoder.py b/python/sglang/srt/utils/video_decoder.py index 48277187fd9e5..3b398b58e4230 100644 --- a/python/sglang/srt/utils/video_decoder.py +++ b/python/sglang/srt/utils/video_decoder.py @@ -192,7 +192,6 @@ def source_bytes(self) -> bytes | None: return None def close(self): - """Release decoder state, retained source bytes, and temporary files.""" self._decoder = None self._source = None self._source_bytes = None diff --git a/test/registered/unit/layers/test_mhc_deep_gemm_gate.py b/test/registered/unit/layers/test_mhc_deep_gemm_gate.py deleted file mode 100644 index 055e3709b1e7c..0000000000000 --- a/test/registered/unit/layers/test_mhc_deep_gemm_gate.py +++ /dev/null @@ -1,89 +0,0 @@ -import unittest -from unittest.mock import patch - -from sglang.kernels.ops.layernorm import mhc -from sglang.srt.environ import envs -from sglang.test.ci.ci_register import register_cpu_ci -from sglang.test.test_utils import CustomTestCase - -register_cpu_ci(est_time=1, suite="base-a-test-cpu") - - -class TestMhcDeepGemmGate(CustomTestCase): - def test_falls_back_when_deep_gemm_is_unavailable(self): - with ( - envs.SGLANG_OPT_DEEPGEMM_HC_PRENORM.override(True), - patch( - "sglang.srt.layers.deep_gemm_wrapper.configurer.ENABLE_JIT_DEEPGEMM", - False, - ), - ): - self.assertFalse(mhc._use_deep_gemm_hc_prenorm()) - - def test_preserves_deep_gemm_path_when_available(self): - with ( - envs.SGLANG_OPT_DEEPGEMM_HC_PRENORM.override(True), - patch( - "sglang.srt.layers.deep_gemm_wrapper.configurer.ENABLE_JIT_DEEPGEMM", - True, - ), - ): - self.assertTrue(mhc._use_deep_gemm_hc_prenorm()) - - def test_explicit_disable_takes_precedence(self): - with ( - envs.SGLANG_OPT_DEEPGEMM_HC_PRENORM.override(False), - patch( - "sglang.srt.layers.deep_gemm_wrapper.configurer.ENABLE_JIT_DEEPGEMM", - True, - ), - ): - self.assertFalse(mhc._use_deep_gemm_hc_prenorm()) - - -class TestMhcTilelangBackendGate(CustomTestCase): - def test_cuda_keeps_env_selected_tilelang_pre_path(self): - with ( - envs.SGLANG_OPT_USE_TILELANG_MHC_PRE.override(True), - patch.object(mhc, "is_hip", return_value=False), - ): - self.assertTrue(mhc._use_tilelang_mhc_pre()) - - def test_hip_always_uses_torch_pre_path(self): - with ( - envs.SGLANG_OPT_USE_TILELANG_MHC_PRE.override(True), - patch.object(mhc, "is_hip", return_value=True), - ): - self.assertFalse(mhc._use_tilelang_mhc_pre()) - - def test_explicit_tilelang_pre_disable_takes_precedence(self): - with ( - envs.SGLANG_OPT_USE_TILELANG_MHC_PRE.override(False), - patch.object(mhc, "is_hip", return_value=False), - ): - self.assertFalse(mhc._use_tilelang_mhc_pre()) - - def test_cuda_keeps_env_selected_tilelang_post_path(self): - with ( - envs.SGLANG_OPT_USE_TILELANG_MHC_POST.override(True), - patch.object(mhc, "is_hip", return_value=False), - ): - self.assertTrue(mhc._use_tilelang_mhc_post()) - - def test_hip_always_uses_torch_post_path(self): - with ( - envs.SGLANG_OPT_USE_TILELANG_MHC_POST.override(True), - patch.object(mhc, "is_hip", return_value=True), - ): - self.assertFalse(mhc._use_tilelang_mhc_post()) - - def test_explicit_tilelang_post_disable_takes_precedence(self): - with ( - envs.SGLANG_OPT_USE_TILELANG_MHC_POST.override(False), - patch.object(mhc, "is_hip", return_value=False), - ): - self.assertFalse(mhc._use_tilelang_mhc_post()) - - -if __name__ == "__main__": - unittest.main() diff --git a/test/registered/unit/mem_cache/test_glm5_next_hybrid_pool.py b/test/registered/unit/mem_cache/test_glm5_next_hybrid_pool.py deleted file mode 100644 index 6a9a7edf44a36..0000000000000 --- a/test/registered/unit/mem_cache/test_glm5_next_hybrid_pool.py +++ /dev/null @@ -1,121 +0,0 @@ -"""Regression coverage for GLM-5.3's hybrid DSA/KDA KV pool.""" - -import sys -import unittest -from types import ModuleType, SimpleNamespace -from unittest.mock import patch - -import torch - -from sglang.test.ci.ci_register import register_cpu_ci -from sglang.test.test_utils import CustomTestCase - -register_cpu_ci(est_time=1, suite="base-a-test-cpu") - - -class TestGlm5NextHybridPool(CustomTestCase): - @patch( - "sglang.srt.mem_cache.kv_cache_configurator.HybridLinearKVPool", - autospec=True, - ) - @patch( - "sglang.srt.mem_cache.kv_cache_configurator.calculate_mla_kv_cache_dim", - autospec=True, - return_value=576, - ) - @patch( - "sglang.srt.mem_cache.kv_cache_configurator.get_dsa_index_kpool_compress", - return_value=True, - ) - @patch( - "sglang.srt.mem_cache.kv_cache_configurator.get_dsa_index_kpool", - return_value=1, - ) - @patch( - "sglang.srt.mem_cache.kv_cache_configurator.get_dsa_index_head_dim", - return_value=128, - ) - @patch( - "sglang.srt.mem_cache.kv_cache_configurator.dsa_layer_skips_topk", - return_value=False, - ) - @patch( - "sglang.srt.mem_cache.kv_cache_configurator.is_deepseek_dsa", - return_value=True, - ) - def test_dsa_kv_dimension_uses_current_calculator_contract( - self, - _mock_is_deepseek_dsa, - _mock_dsa_layer_skips_topk, - _mock_index_head_dim, - _mock_index_kpool, - _mock_index_kpool_compress, - mock_calculate_mla_kv_cache_dim, - mock_hybrid_pool, - ): - from sglang.srt.mem_cache.kv_cache_configurator import KVCacheConfigurator - - configurator = object.__new__(KVCacheConfigurator) - configurator.is_draft_worker = False - configurator.mambaish_config = SimpleNamespace(full_attention_layer_ids=[3]) - configurator.layer_info = SimpleNamespace(start_layer=0, end_layer=4) - configurator.use_mla_backend = True - configurator.model_config = SimpleNamespace( - hf_config=SimpleNamespace(), - kv_lora_rank=512, - qk_rope_head_dim=64, - head_dim=128, - get_num_kv_heads=lambda _tp_size, _dcp_size: 1, - ) - configurator.kv_cache_dtype = torch.bfloat16 - configurator.kv_cache_dtype_str = "bfloat16" - configurator.device = "cuda" - configurator.post_capture_kv_active = False - - req_to_token_pool = SimpleNamespace(mamba_pool=object()) - fake_cp_utils = ModuleType("sglang.srt.layers.cp.utils") - fake_cp_utils.get_glm_dsa_cp_layer_shard_info = lambda _configurator: (0, 1) - with ( - patch.dict( - sys.modules, - {"sglang.srt.layers.cp.utils": fake_cp_utils}, - ), - patch.object( - KVCacheConfigurator, - "_build_fp4_quant_method", - return_value=None, - ), - patch( - "sglang.srt.mem_cache.kv_cache_configurator.get_parallel", - return_value=SimpleNamespace(attn_tp_size=8, attn_dcp_size=1), - ), - patch( - "sglang.srt.mem_cache.kv_cache_configurator.get_exec", - return_value=SimpleNamespace( - features=SimpleNamespace(enable_memory_saver=False) - ), - ), - patch( - "sglang.srt.mem_cache.kv_cache_configurator.get_schedule", - return_value=SimpleNamespace(page_size=64), - ), - patch( - "sglang.srt.mem_cache.kv_cache_configurator.get_spec", - return_value=SimpleNamespace(speculative_algorithm=None), - ), - ): - configurator._build_hybrid_linear_kv_pool( - max_total_num_tokens=1024, - req_to_token_pool=req_to_token_pool, - mha_pool_class=object, - ) - - mock_calculate_mla_kv_cache_dim.assert_called_once_with( - model_config=configurator.model_config, - kv_cache_dtype=torch.bfloat16, - ) - self.assertEqual(mock_hybrid_pool.call_args.kwargs["kv_cache_dim"], 576) - - -if __name__ == "__main__": - unittest.main() diff --git a/test/registered/unit/models/test_glm5_next_dcp.py b/test/registered/unit/models/test_glm5_next_dcp.py deleted file mode 100644 index 6802395e48352..0000000000000 --- a/test/registered/unit/models/test_glm5_next_dcp.py +++ /dev/null @@ -1,49 +0,0 @@ -import sys -from types import SimpleNamespace -from unittest.mock import patch, sentinel - -import pytest - -from sglang.srt.models.glm5_next import Glm5NextForConditionalGeneration -from sglang.test.ci.ci_register import register_cpu_ci - -register_cpu_ci( - est_time=5, - suite="base-a-test-cpu", - nightly=False, - disabled=None, -) - - -def test_multimodal_wrapper_builds_dcp_extend_metadata(): - """The top-level model must publish DCP metadata before prefix KV gather.""" - kwargs = { - "seq_lens": sentinel.seq_lens, - "extend_prefix_lens": sentinel.extend_prefix_lens, - "extend_prefix_lens_cpu": sentinel.extend_prefix_lens_cpu, - "extend_seq_lens": sentinel.extend_seq_lens, - "req_pool_indices": sentinel.req_pool_indices, - "req_to_token": sentinel.req_to_token, - "seq_lens_sum": 17, - "kv_buffer_shape": sentinel.kv_buffer_shape, - "kv_cache_dtype": sentinel.kv_cache_dtype, - "kv_cache_device": sentinel.kv_cache_device, - "create_chunked_prefix_cache_kv_indices_fn": sentinel.create_indices, - } - - with patch( - "sglang.srt.models.glm5_next.prepare_decode_context_parallel_metadata", - return_value=sentinel.metadata, - ) as planner: - result = ( - Glm5NextForConditionalGeneration.prepare_context_parallel_metadata_for_dcp( - SimpleNamespace(), **kwargs - ) - ) - - assert result is sentinel.metadata - planner.assert_called_once_with(**kwargs) - - -if __name__ == "__main__": - sys.exit(pytest.main([__file__])) From de4a004e73ff84450ace5e95f5d04c772b28f37c Mon Sep 17 00:00:00 2001 From: Baizhou Zhang Date: Sun, 30 Aug 2026 18:58:49 -0700 Subject: [PATCH 12/44] test: add executable entry for DCP metadata test --- .../runner/test_eager_runner_dcp_metadata.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/test/registered/unit/model_executor/runner/test_eager_runner_dcp_metadata.py b/test/registered/unit/model_executor/runner/test_eager_runner_dcp_metadata.py index 414623fc5c14e..30c7f802b3928 100644 --- a/test/registered/unit/model_executor/runner/test_eager_runner_dcp_metadata.py +++ b/test/registered/unit/model_executor/runner/test_eager_runner_dcp_metadata.py @@ -1,6 +1,9 @@ +import sys from types import SimpleNamespace from unittest.mock import Mock, patch +import pytest + from sglang.srt.model_executor.forward_batch_info import ForwardMode from sglang.srt.model_executor.runner.eager_runner import EagerRunner from sglang.test.ci.ci_register import register_cpu_ci @@ -72,3 +75,7 @@ def test_cp_v2_metadata_is_prepared_once(_is_cp_v2_active, prepare_cp_forward): prepare_cp_forward.assert_called_once_with(batch) model_runner.attn_backend.init_forward_metadata.assert_called_once_with(batch) runner._execute_extend_cp_v2.assert_called_once() + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) From 1645ac65432876270c705584859b0521e86cc872 Mon Sep 17 00:00:00 2001 From: Baizhou Zhang Date: Sun, 30 Aug 2026 19:09:22 -0700 Subject: [PATCH 13/44] test: add executable entry for GLM AITER mHC test --- test/registered/unit/models/test_glm5_next_aiter_mhc.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/test/registered/unit/models/test_glm5_next_aiter_mhc.py b/test/registered/unit/models/test_glm5_next_aiter_mhc.py index 4a1438e598c7a..7caad60cf1834 100644 --- a/test/registered/unit/models/test_glm5_next_aiter_mhc.py +++ b/test/registered/unit/models/test_glm5_next_aiter_mhc.py @@ -2,6 +2,7 @@ from types import ModuleType, SimpleNamespace from unittest.mock import MagicMock, patch +import pytest import torch from torch import nn @@ -236,3 +237,7 @@ def test_glm_aiter_mhc_boundary_preserves_communicator_shapes(): assert norm_fused assert fused.call_args.kwargs["fn_transpose"] is True assert fused.call_args.kwargs["residual"].shape == (2, 4, 8) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) From 493322b1284b89be759e2c96f3358da3cd727914 Mon Sep 17 00:00:00 2001 From: Baizhou Zhang Date: Sun, 30 Aug 2026 20:54:06 -0700 Subject: [PATCH 14/44] test: add GLM-5.3 Flash B200 E2E coverage --- .../models_e2e/test_glm53_flash_b200.py | 111 ++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 test/registered/models_e2e/test_glm53_flash_b200.py diff --git a/test/registered/models_e2e/test_glm53_flash_b200.py b/test/registered/models_e2e/test_glm53_flash_b200.py new file mode 100644 index 0000000000000..a9ea7aef3785c --- /dev/null +++ b/test/registered/models_e2e/test_glm53_flash_b200.py @@ -0,0 +1,111 @@ +"""B200 per-commit coverage for the GLM-5.3-Flash serving recipes. + +Runs the Low Latency and High Throughput TP4/EP4 recipes on four B200 GPUs. +Both recipes must retain GSM8K accuracy; the Low Latency recipe also checks +EAGLE speculative acceptance and single-request decode performance. +""" + +import unittest + +from sglang.srt.utils import kill_process_tree +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.kits.eval_accuracy_kit import GSM8KMixin +from sglang.test.kits.spec_decoding_kit import SpecDecodingMixin +from sglang.test.test_utils import ( + DEFAULT_URL_FOR_TEST, + CustomTestCase, + _wait_for_gpu_idle_in_ci, + popen_launch_server, + try_cached_model, +) + +register_cuda_ci(est_time=1800, stage="base-c", runner_config="4-gpu-b200") + +MODEL_PATH = "zai-org/GLM-5.3-Flash" +SERVER_LAUNCH_TIMEOUT = 3600 +GPU_IDLE_TIMEOUT = 120 + +COMMON_SERVER_ARGS = [ + "--tp-size", + "4", + "--ep-size", + "4", + "--dsa-prefill-backend", + "trtllm", + "--dsa-decode-backend", + "trtllm", + "--kv-cache-dtype", + "fp8_e4m3", + "--moe-runner-backend", + "deep_gemm", + "--reasoning-parser", + "glm45", + "--tool-call-parser", + "glm47", +] + + +def _stop_server(process): + if process: + kill_process_tree(process.pid) + _wait_for_gpu_idle_in_ci(timeout=GPU_IDLE_TIMEOUT) + + +class _GLM53FlashB200Base(CustomTestCase): + server_args: list[str] + gsm8k_score_threshold = 0.93 + + @classmethod + def setUpClass(cls): + cls.model = try_cached_model(MODEL_PATH) + cls.base_url = DEFAULT_URL_FOR_TEST + cls.process = None + cls.process = popen_launch_server( + cls.model, + cls.base_url, + timeout=SERVER_LAUNCH_TIMEOUT, + other_args=cls.server_args, + ) + + @classmethod + def tearDownClass(cls): + _stop_server(getattr(cls, "process", None)) + + +class TestGLM53FlashB200LowLatency( + SpecDecodingMixin, + GSM8KMixin, + _GLM53FlashB200Base, +): + accept_length_thres = 4.0 + bs_1_speed_thres = 300 + server_args = [ + *COMMON_SERVER_ARGS, + "--speculative-algorithm", + "EAGLE", + "--speculative-num-steps", + "5", + "--speculative-eagle-topk", + "1", + "--speculative-num-draft-tokens", + "6", + "--speculative-adaptive", + ] + + +class TestGLM53FlashB200HighThroughput( + GSM8KMixin, + _GLM53FlashB200Base, +): + server_args = [ + *COMMON_SERVER_ARGS, + "--enable-dp-attention", + "--dp-size", + "4", + "--moe-a2a-backend", + "deepep", + ] + + +if __name__ == "__main__": + unittest.main() From b9c0e90debd4bd47e2007136826fc741d7095fa1 Mon Sep 17 00:00:00 2001 From: Baizhou Zhang Date: Mon, 31 Aug 2026 02:12:32 -0700 Subject: [PATCH 15/44] clean tests --- .gitignore | 1 - .../{unit => cp}/test_dsa_trtllm_fp8_cp.py | 0 .../ops/attention/test_silu_and_mul_clamp.py | 90 ----------- .../ops/moe/test_minimax_quant_scatter.py | 39 ----- .../attention/test_dsa_multistep_dedup.py | 144 ------------------ .../layers/moe/test_fused_moe_swiglu_clamp.py | 38 ----- test/registered/unit/layers/test_dcp_comm.py | 42 ----- .../test_tokenizer_manager_rid_cleanup.py | 67 +------- .../runner/test_eager_runner_dcp_metadata.py | 81 ---------- .../test_glm5_next_nextn_weight_loading.py | 68 --------- .../unit/models/test_glm5_next_pp_metadata.py | 39 ----- .../models/test_glm5_next_weight_loading.py | 54 ------- .../models/test_nextn_hf_to_sglang_mapper.py | 73 --------- .../unit/server_args/test_server_args.py | 112 -------------- .../spec/test_spec_cpu_overlap_constraint.py | 50 ------ 15 files changed, 1 insertion(+), 897 deletions(-) rename test/registered/{unit => cp}/test_dsa_trtllm_fp8_cp.py (100%) delete mode 100644 test/registered/kernels/ops/attention/test_silu_and_mul_clamp.py delete mode 100644 test/registered/unit/attention/test_dsa_multistep_dedup.py delete mode 100644 test/registered/unit/layers/moe/test_fused_moe_swiglu_clamp.py delete mode 100644 test/registered/unit/layers/test_dcp_comm.py delete mode 100644 test/registered/unit/model_executor/runner/test_eager_runner_dcp_metadata.py delete mode 100644 test/registered/unit/models/test_glm5_next_nextn_weight_loading.py delete mode 100644 test/registered/unit/models/test_glm5_next_pp_metadata.py delete mode 100644 test/registered/unit/models/test_glm5_next_weight_loading.py delete mode 100644 test/registered/unit/models/test_nextn_hf_to_sglang_mapper.py diff --git a/.gitignore b/.gitignore index 777fbcff6019d..cd1c6325d3559 100644 --- a/.gitignore +++ b/.gitignore @@ -281,4 +281,3 @@ artifacts/ # Internal, non-published docs internal-docs/ -.trellis diff --git a/test/registered/unit/test_dsa_trtllm_fp8_cp.py b/test/registered/cp/test_dsa_trtllm_fp8_cp.py similarity index 100% rename from test/registered/unit/test_dsa_trtllm_fp8_cp.py rename to test/registered/cp/test_dsa_trtllm_fp8_cp.py diff --git a/test/registered/kernels/ops/attention/test_silu_and_mul_clamp.py b/test/registered/kernels/ops/attention/test_silu_and_mul_clamp.py deleted file mode 100644 index 6e81fa7173505..0000000000000 --- a/test/registered/kernels/ops/attention/test_silu_and_mul_clamp.py +++ /dev/null @@ -1,90 +0,0 @@ -import sys - -import pytest -import torch -import torch.nn.functional as F - -from sglang.kernels.ops.attention.dsv4 import silu_and_mul_clamp -from sglang.test.ci.ci_register import register_cuda_ci - -register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") - -pytestmark = pytest.mark.skipif( - not torch.cuda.is_available() or torch.version.cuda is None, - reason="silu_and_mul_clamp requires CUDA", -) - - -def _reference(input: torch.Tensor, limit: float) -> torch.Tensor: - gate, up = input.chunk(2, dim=-1) - limit_tensor = torch.tensor(limit, dtype=input.dtype, device=input.device) - gate = torch.minimum(gate, limit_tensor) - up = torch.minimum(torch.maximum(up, -limit_tensor), limit_tensor) - return (F.silu(gate.float()) * up.float()).to(input.dtype) - - -@pytest.mark.parametrize("num_tokens", [1, 4]) -@pytest.mark.parametrize("hidden_size", [4096, 8192, 16384]) -@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16]) -def test_silu_and_mul_clamp_matches_reference( - num_tokens: int, hidden_size: int, dtype: torch.dtype -) -> None: - generator = torch.Generator(device="cuda").manual_seed(hidden_size + num_tokens) - input = ( - torch.randn( - num_tokens, - hidden_size * 2, - generator=generator, - device="cuda", - dtype=torch.float32, - ) - * 8 - ).to(dtype) - output = torch.full( - (num_tokens, hidden_size), - float("nan"), - device="cuda", - dtype=dtype, - ) - - silu_and_mul_clamp(input, output, 7.0) - torch.cuda.synchronize() - - assert torch.isfinite(output).all() - torch.testing.assert_close(output, _reference(input, 7.0), rtol=2e-2, atol=5e-2) - - -def test_silu_and_mul_clamp_rejects_mismatched_width() -> None: - input = torch.randn(1, 8192, device="cuda", dtype=torch.bfloat16) - output = torch.empty(1, 4104, device="cuda", dtype=torch.bfloat16) - - with pytest.raises(RuntimeError, match="input last dim must be 2"): - silu_and_mul_clamp(input, output, 7.0) - - -def test_silu_and_mul_clamp_rejects_unaligned_width() -> None: - input = torch.randn(1, 8200, device="cuda", dtype=torch.bfloat16) - output = torch.empty(1, 4100, device="cuda", dtype=torch.bfloat16) - - with pytest.raises(RuntimeError, match="out_dim must be divisible by vector size"): - silu_and_mul_clamp(input, output, 7.0) - - -def test_silu_and_mul_clamp_rejects_empty_width() -> None: - input = torch.empty(1, 0, device="cuda", dtype=torch.bfloat16) - output = torch.empty_like(input) - - with pytest.raises(RuntimeError, match="out_dim must be positive"): - silu_and_mul_clamp(input, output, 7.0) - - -def test_silu_and_mul_clamp_rejects_output_dtype_mismatch() -> None: - input = torch.randn(1, 8192, device="cuda", dtype=torch.bfloat16) - output = torch.empty(1, 4096, device="cuda", dtype=torch.float16) - - with pytest.raises(RuntimeError, match="Dtype value.*not in the allowed options"): - silu_and_mul_clamp(input, output, 7.0) - - -if __name__ == "__main__": - sys.exit(pytest.main([__file__])) diff --git a/test/registered/kernels/ops/moe/test_minimax_quant_scatter.py b/test/registered/kernels/ops/moe/test_minimax_quant_scatter.py index f7cde67b841d8..7007fd9897fc1 100644 --- a/test/registered/kernels/ops/moe/test_minimax_quant_scatter.py +++ b/test/registered/kernels/ops/moe/test_minimax_quant_scatter.py @@ -8,7 +8,6 @@ import sglang.srt.layers.moe.moe_runner.deep_gemm as deep_gemm_runner from sglang.kernels.ops.moe.ep_moe_kernels import ( - ep_scatter, fill_gateup_input_triton_kernel, moe_ep_deepgemm_preprocess, ) @@ -141,44 +140,6 @@ def test_standard_deepgemm_preprocess_quantizes_with_ue8m0_scale(): ) -def test_ep_scatter_initializes_compact_expert_offsets(): - hidden_states = torch.arange(3 * 128, device=dev, dtype=torch.bfloat16).reshape( - 3, 128 - ) - topk_ids = torch.tensor([[0], [1], [0]], device=dev, dtype=torch.int32) - padded_tokens_per_expert = torch.tensor([128, 128], device=dev, dtype=torch.int32) - valid_tokens_per_expert = torch.tensor([2, 1], device=dev, dtype=torch.int32) - expert_start_loc = torch.zeros(2, device=dev, dtype=torch.int32) - packed_hidden_states = torch.zeros(256, 128, device=dev, dtype=torch.bfloat16) - m_indices = torch.full((256,), -2, device=dev, dtype=torch.int32) - src2dst = torch.full((3, 1), -1, device=dev, dtype=torch.int32) - - ep_scatter( - hidden_states, - None, - topk_ids, - padded_tokens_per_expert, - valid_tokens_per_expert, - expert_start_loc, - packed_hidden_states, - torch.empty(0, device=dev), - m_indices, - src2dst, - ) - torch.cuda.synchronize() - - assert torch.equal( - expert_start_loc.cpu(), torch.tensor([2, 129], dtype=torch.int32) - ) - src2dst_cpu = src2dst.cpu().flatten() - assert set(src2dst_cpu[[0, 2]].tolist()) == {0, 1} - assert src2dst_cpu[1].item() == 128 - assert torch.equal(m_indices[:2].cpu(), torch.tensor([0, 0], dtype=torch.int32)) - assert torch.equal(m_indices[128:129].cpu(), torch.tensor([1], dtype=torch.int32)) - for token_id, dst in enumerate(src2dst_cpu.tolist()): - assert torch.equal(packed_hidden_states[dst], hidden_states[token_id]) - - @pytest.mark.parametrize( "num_assignments,num_experts,expected", [ diff --git a/test/registered/unit/attention/test_dsa_multistep_dedup.py b/test/registered/unit/attention/test_dsa_multistep_dedup.py deleted file mode 100644 index 7378ed6f9f01d..0000000000000 --- a/test/registered/unit/attention/test_dsa_multistep_dedup.py +++ /dev/null @@ -1,144 +0,0 @@ -import unittest -from unittest.mock import MagicMock, patch - -from sglang.srt.layers.attention.dsa_backend import ( - DeepseekSparseAttnBackend, - DeepseekSparseAttnMultiStepBackend, - _is_kpool_metadata_fusion_supported, -) -from sglang.srt.model_executor.forward_batch_info import ForwardMode -from sglang.test.ci.ci_register import register_cpu_ci -from sglang.test.test_utils import CustomTestCase - -register_cpu_ci(est_time=10, suite="base-a-test-cpu") - - -class TestMultiStepDedupGate(CustomTestCase): - """The multi-step sibling-copy dedup is internal behavior of the fused - metadata path: it must follow the step backends' effective fusion enable - (which folds in the geometry and platform gates), with no standalone - knob.""" - - def _wrapper_with_backend_flag(self, value): - wrapper = MagicMock(spec=DeepseekSparseAttnMultiStepBackend) - backend0 = MagicMock() - backend0.experimental_kpool_metadata_fusion = value - wrapper.attn_backends = [backend0, MagicMock(), MagicMock()] - return wrapper - - def test_dedup_follows_fusion_enable(self): - wrapper = self._wrapper_with_backend_flag(True) - self.assertTrue( - DeepseekSparseAttnMultiStepBackend._multistep_dedup_enabled(wrapper) - ) - - def test_dedup_off_when_fusion_off(self): - wrapper = self._wrapper_with_backend_flag(False) - self.assertFalse( - DeepseekSparseAttnMultiStepBackend._multistep_dedup_enabled(wrapper) - ) - - def test_dedup_off_when_backend_predates_flag(self): - wrapper = MagicMock(spec=DeepseekSparseAttnMultiStepBackend) - backend0 = MagicMock(spec=[]) # no fusion attribute at all - wrapper.attn_backends = [backend0] - self.assertFalse( - DeepseekSparseAttnMultiStepBackend._multistep_dedup_enabled(wrapper) - ) - - -class TestSiblingCopyFallback(CustomTestCase): - """_copy_replay_metadata_from_sibling must take the FULL recompute path - whenever the CUDA-only derived-copy body cannot run bit-exactly: - non-CUDA platforms, missing metadata, or a stale/incompatible sibling.""" - - def _mock_backend(self, bs=4, with_metadata=True): - be = MagicMock(spec=DeepseekSparseAttnBackend) - metadata = MagicMock() - be.decode_cuda_graph_metadata = {bs: metadata} if with_metadata else {} - be.forward_metadata = metadata - return be, metadata - - def _run(self, is_cuda_val, is_hip_val=False, self_has_metadata=True): - bs = 4 - dst, dst_meta = self._mock_backend(bs, with_metadata=self_has_metadata) - src, src_meta = self._mock_backend(bs) - src.forward_metadata = src_meta # fresh sibling - dst._sibling_replay_metadata_compatible = MagicMock(return_value=True) - precomputed = MagicMock() - - with patch( - "sglang.srt.layers.attention.dsa_backend.is_cuda", - return_value=is_cuda_val, - ), patch("sglang.srt.layers.attention.dsa_backend._is_hip", is_hip_val): - DeepseekSparseAttnBackend._copy_replay_metadata_from_sibling( - dst, - src_backend=src, - bs=bs, - precomputed=precomputed, - forward_mode=ForwardMode.DECODE, - ) - return dst - - def test_non_cuda_platform_recomputes_in_full(self): - dst = self._run(is_cuda_val=False) - dst.init_forward_metadata_replay_cuda_graph_from_precomputed.assert_called_once() - dst._copy_base_replay_buffers.assert_not_called() - - def test_hip_platform_recomputes_in_full(self): - dst = self._run(is_cuda_val=True, is_hip_val=True) - dst.init_forward_metadata_replay_cuda_graph_from_precomputed.assert_called_once() - dst._copy_base_replay_buffers.assert_not_called() - - def test_missing_metadata_recomputes_in_full(self): - dst = self._run(is_cuda_val=True, self_has_metadata=False) - dst.init_forward_metadata_replay_cuda_graph_from_precomputed.assert_called_once() - dst._copy_base_replay_buffers.assert_not_called() - - def test_cuda_compatible_sibling_takes_copy_path(self): - dst = self._run(is_cuda_val=True) - dst.init_forward_metadata_replay_cuda_graph_from_precomputed.assert_not_called() - dst._copy_base_replay_buffers.assert_called_once() - dst._copy_kpool_metadata_from_sibling.assert_called_once() - - -class TestInGraphVerifyEligibility(CustomTestCase): - def _eligible(self, dcp_enabled): - backend = MagicMock(spec=DeepseekSparseAttnBackend) - backend.ingraph_verify_metadata_enabled = True - backend.dsa_index_kpool = 16 - backend.experimental_kpool_metadata_fusion = True - backend.dsa_decode_impl = "trtllm" - parallel = MagicMock(dcp_enabled=dcp_enabled) - - with patch( - "sglang.srt.layers.attention.dsa_backend.is_cuda", return_value=True - ), patch("sglang.srt.layers.attention.dsa_backend._is_hip", False), patch( - "sglang.srt.layers.attention.dsa_backend.get_parallel", - return_value=parallel, - ): - return DeepseekSparseAttnBackend._ingraph_verify_metadata_eligible(backend) - - def test_uninitialized_dcp_group_is_eligible(self): - self.assertTrue(self._eligible(dcp_enabled=False)) - - def test_dcp_is_not_eligible(self): - self.assertFalse(self._eligible(dcp_enabled=True)) - - -class TestKPoolMetadataFusionGeometry(CustomTestCase): - def test_final_checkpoint_geometry_is_supported(self): - self.assertTrue(_is_kpool_metadata_fusion_supported(4, 64, 2048)) - - def test_legacy_checkpoint_geometry_is_supported(self): - self.assertTrue(_is_kpool_metadata_fusion_supported(16, 64, 2048)) - - def test_non_page_aligned_pool_is_not_supported(self): - self.assertFalse(_is_kpool_metadata_fusion_supported(6, 64, 2048)) - - def test_non_pool_aligned_topk_is_not_supported(self): - self.assertFalse(_is_kpool_metadata_fusion_supported(4, 64, 2049)) - - -if __name__ == "__main__": - unittest.main() diff --git a/test/registered/unit/layers/moe/test_fused_moe_swiglu_clamp.py b/test/registered/unit/layers/moe/test_fused_moe_swiglu_clamp.py deleted file mode 100644 index fd37950c87daa..0000000000000 --- a/test/registered/unit/layers/moe/test_fused_moe_swiglu_clamp.py +++ /dev/null @@ -1,38 +0,0 @@ -import unittest - -import torch -import torch.nn.functional as F - -from sglang.srt.layers.moe.moe_runner.triton_utils.fused_moe import ( - _clamp_swiglu_inputs_, -) -from sglang.test.ci.ci_register import register_cpu_ci -from sglang.test.test_utils import CustomTestCase - -register_cpu_ci(est_time=1, suite="base-a-test-cpu") - - -class TestFusedMoeSwigluClamp(CustomTestCase): - def test_clamps_gate_and_up_with_the_deepseek_contract(self): - inputs = torch.tensor([[-20.0, 20.0, -20.0, 20.0], [3.0, 11.0, -4.0, 5.0]]) - - _clamp_swiglu_inputs_(inputs, limit=10.0) - - torch.testing.assert_close( - inputs, - torch.tensor([[-20.0, 10.0, -10.0, 10.0], [3.0, 10.0, -4.0, 5.0]]), - ) - - def test_clamped_inputs_match_reference_swiglu(self): - inputs = torch.tensor([[-12.0, 14.0, -13.0, 15.0]]) - - _clamp_swiglu_inputs_(inputs, limit=10.0) - output = F.silu(inputs[..., :2]) * inputs[..., 2:] - - expected_gate = torch.tensor([[-12.0, 10.0]]) - expected_up = torch.tensor([[-10.0, 10.0]]) - torch.testing.assert_close(output, F.silu(expected_gate) * expected_up) - - -if __name__ == "__main__": - unittest.main() diff --git a/test/registered/unit/layers/test_dcp_comm.py b/test/registered/unit/layers/test_dcp_comm.py deleted file mode 100644 index 87acadc3a3340..0000000000000 --- a/test/registered/unit/layers/test_dcp_comm.py +++ /dev/null @@ -1,42 +0,0 @@ -import sys -from types import SimpleNamespace -from unittest.mock import patch - -import pytest -import torch - -from sglang.srt.layers.dcp.comm import all_gather_kv_cache_for_dcp -from sglang.test.ci.ci_register import register_cpu_ci - -register_cpu_ci( - est_time=5, - suite="base-a-test-cpu", - nightly=False, - disabled=None, -) - - -def test_nope_prefix_kv_gather_accepts_missing_rope_cache(): - """NoPE DCP prefix reuse must not require a rope-cache tensor.""" - prefix_kv_a = torch.arange(12, dtype=torch.float32).reshape(3, 1, 4) - prefix_kv_lens_cpu = torch.tensor([3], dtype=torch.int32) - parallel = SimpleNamespace(dcp_enabled=True, dcp_size=1, dcp_rank=0) - - with ( - patch("sglang.srt.layers.dcp.comm.get_parallel", return_value=parallel), - patch( - "sglang.srt.layers.dcp.comm._all_gather_dcp_kv_cache", - side_effect=lambda tensor: tensor, - ), - ): - result = all_gather_kv_cache_for_dcp( - prefix_kv_a, - None, - prefix_kv_lens_cpu, - ) - - assert torch.equal(result, prefix_kv_a) - - -if __name__ == "__main__": - sys.exit(pytest.main([__file__])) diff --git a/test/registered/unit/managers/test_tokenizer_manager_rid_cleanup.py b/test/registered/unit/managers/test_tokenizer_manager_rid_cleanup.py index bf54ddd8b2867..f7acd97797a72 100644 --- a/test/registered/unit/managers/test_tokenizer_manager_rid_cleanup.py +++ b/test/registered/unit/managers/test_tokenizer_manager_rid_cleanup.py @@ -15,7 +15,7 @@ import asyncio import unittest -from unittest.mock import AsyncMock, MagicMock, Mock, patch +from unittest.mock import AsyncMock, MagicMock, Mock import msgspec @@ -643,27 +643,6 @@ async def drive(): for r in rids: self.assertNotIn(r, tm.rid_to_state) - def test_parallel_sampling_failure_cleans_generated_rid(self): - tm = _make_tm_for_generate(self) - obj = GenerateReqInput( - text=["hello"], - rid=["base"], - sampling_params={"n": 2}, - ) - tokenized = MagicMock() - tokenized.mm_inputs = None - tokenized.sampling_params = MagicMock() - tm._tokenize_one_request = AsyncMock(return_value=tokenized) - tm._send_one_request = Mock(side_effect=RuntimeError("dispatch failed")) - - async def drive(): - await tm.generate_request(obj).__anext__() - - with self.assertRaisesRegex(RuntimeError, "dispatch failed"): - asyncio.run(drive()) - - self.assertFalse(tm.rid_to_state) - def test_thinking_budget_rejects_runtime_without_strict_thinking(self): tm = _make_tm_for_generate(self) obj = GenerateReqInput( @@ -682,50 +661,6 @@ async def drive(): self.assertFalse(tm.rid_to_state) -class TestDisconnectAfterDispatchAbortsRequest(CustomTestCase): - """Cancellation after dispatch must stop the scheduler request.""" - - @patch( - "sglang.srt.managers.tokenizer_manager.wrap_shm_features", - side_effect=lambda obj: obj, - ) - def test_cancel_after_dispatch_sends_abort_and_keeps_state(self, _wrap_shm): - tm = _make_tm_for_generate(self) - tm.cuda_vmm_feature_transport = Mock() - tm._dispatch_to_scheduler = Mock() - rid = "disconnect_zombie" - obj = _make_generate_obj(rid, is_single=True) - obj.return_prompt_token_ids = False - tokenized = MagicMock() - tokenized.rid = rid - tokenized.mm_inputs = None - tm._tokenize_one_request = AsyncMock(return_value=tokenized) - - async def drive(): - task = asyncio.create_task(tm.generate_request(obj).__anext__()) - for _ in range(100): - await asyncio.sleep(0) - if tm._dispatch_to_scheduler.called: - break - self.assertTrue( - tm._dispatch_to_scheduler.called, "request never dispatched" - ) - state = tm.rid_to_state.get(rid) - self.assertIsNotNone(state) - self.assertTrue(state.dispatched) - - task.cancel() - with self.assertRaises(asyncio.CancelledError): - await task - - asyncio.run(drive()) - - sent = [c.args[0] for c in tm._dispatch_to_scheduler.call_args_list] - aborts = [m for m in sent if isinstance(m, AbortReq) and m.rid == rid] - self.assertTrue(aborts, "disconnect must send an AbortReq to the scheduler") - self.assertIn(rid, tm.rid_to_state) - - class TestWaitOneResponseAfterStateFreed(CustomTestCase): """A waiter built before its request finishes must still deliver the output. diff --git a/test/registered/unit/model_executor/runner/test_eager_runner_dcp_metadata.py b/test/registered/unit/model_executor/runner/test_eager_runner_dcp_metadata.py deleted file mode 100644 index 30c7f802b3928..0000000000000 --- a/test/registered/unit/model_executor/runner/test_eager_runner_dcp_metadata.py +++ /dev/null @@ -1,81 +0,0 @@ -import sys -from types import SimpleNamespace -from unittest.mock import Mock, patch - -import pytest - -from sglang.srt.model_executor.forward_batch_info import ForwardMode -from sglang.srt.model_executor.runner.eager_runner import EagerRunner -from sglang.test.ci.ci_register import register_cpu_ci - -register_cpu_ci(est_time=1, suite="base-a-test-cpu") - - -def test_target_verify_skips_dcp_extend_metadata(): - runner = EagerRunner.__new__(EagerRunner) - runner.enable_pdmux = False - runner.load_batch = lambda batch, _proxy: batch - - model = Mock() - model.forward.return_value = object() - model_runner = SimpleNamespace( - _extend_forward_kwargs=lambda *_args: {}, - _pp_kwargs=lambda *_args: {}, - ps=SimpleNamespace(attn_dcp_size=4), - model=model, - attn_backend=Mock(), - device_timer=None, - prefill_cuda_graph_runner=None, - ) - runner.model_runner = model_runner - batch = SimpleNamespace( - forward_mode=ForwardMode.TARGET_VERIFY, - needs_forward_metadata_init=lambda: True, - input_ids=object(), - positions=object(), - ) - - runner._execute_extend(batch) - - model.prepare_context_parallel_metadata_for_dcp.assert_not_called() - model_runner.attn_backend.init_forward_metadata.assert_called_once_with(batch) - - -@patch("sglang.srt.model_executor.runner.eager_runner.prepare_cp_forward") -@patch( - "sglang.srt.model_executor.runner.eager_runner.is_cp_v2_active", return_value=True -) -def test_cp_v2_metadata_is_prepared_once(_is_cp_v2_active, prepare_cp_forward): - runner = EagerRunner.__new__(EagerRunner) - runner.enable_pdmux = False - runner.load_batch = lambda batch, _proxy: batch - runner._execute_extend_cp_v2 = Mock(return_value=object()) - - model = Mock() - model.forward.return_value = object() - model_runner = SimpleNamespace( - _extend_forward_kwargs=lambda *_args: {}, - _pp_kwargs=lambda *_args: {}, - ps=SimpleNamespace(attn_dcp_size=1), - model=model, - attn_backend=Mock(), - device_timer=None, - prefill_cuda_graph_runner=None, - ) - runner.model_runner = model_runner - batch = SimpleNamespace( - forward_mode=ForwardMode.EXTEND, - needs_forward_metadata_init=lambda: True, - input_ids=object(), - positions=object(), - ) - - runner._execute_extend(batch) - - prepare_cp_forward.assert_called_once_with(batch) - model_runner.attn_backend.init_forward_metadata.assert_called_once_with(batch) - runner._execute_extend_cp_v2.assert_called_once() - - -if __name__ == "__main__": - sys.exit(pytest.main([__file__, "-v"])) diff --git a/test/registered/unit/models/test_glm5_next_nextn_weight_loading.py b/test/registered/unit/models/test_glm5_next_nextn_weight_loading.py deleted file mode 100644 index bc043a0ecd5a7..0000000000000 --- a/test/registered/unit/models/test_glm5_next_nextn_weight_loading.py +++ /dev/null @@ -1,68 +0,0 @@ -import unittest -from types import SimpleNamespace - -import torch - -from sglang.srt.models.glm5_next_nextn import ( - Glm5NextForConditionalGenerationNextN, -) -from sglang.test.ci.ci_register import register_cpu_ci - -register_cpu_ci(est_time=5, suite="base-a-test-cpu") - - -class _FakeParam: - def __init__(self): - self.loaded = None - - def weight_loader(self, param, loaded_weight): - self.loaded = loaded_weight - - -class TestGlm5NextNextNWeightLoading(unittest.TestCase): - def test_checkpoint_qkv_sources_load_fused_projection(self): - fused_param = _FakeParam() - model = SimpleNamespace( - config=SimpleNamespace( - num_hidden_layers=45, - num_nextn_predict_layers=1, - n_routed_experts=0, - q_lora_rank=1536, - ), - model=SimpleNamespace( - decoder=SimpleNamespace(self_attn=None), - ), - named_parameters=lambda: iter( - [ - ( - "model.decoder.self_attn.fused_qkv_a_proj_with_mqa.weight", - fused_param, - ) - ] - ), - num_fused_shared_experts=0, - quant_config=None, - ) - q_weight = torch.arange(6, dtype=torch.float32).reshape(2, 3) - kv_weight = torch.arange(3, dtype=torch.float32).reshape(1, 3) + 10 - - Glm5NextForConditionalGenerationNextN.load_weights( - model, - [ - ("model.layers.45.self_attn.q_a_proj.weight", q_weight), - ( - "model.layers.45.self_attn.kv_a_proj_with_mqa.weight", - kv_weight, - ), - ], - ) - - self.assertTrue(model.fuse_qkv_a_proj) - torch.testing.assert_close( - fused_param.loaded, - torch.cat([q_weight, kv_weight], dim=0), - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/test/registered/unit/models/test_glm5_next_pp_metadata.py b/test/registered/unit/models/test_glm5_next_pp_metadata.py deleted file mode 100644 index 257168908207f..0000000000000 --- a/test/registered/unit/models/test_glm5_next_pp_metadata.py +++ /dev/null @@ -1,39 +0,0 @@ -import sys -from types import SimpleNamespace - -import pytest -import torch - -from sglang.srt.model_executor.forward_batch_info import PPProxyTensors -from sglang.srt.models.glm5_next import Glm5NextForConditionalGeneration -from sglang.test.ci.ci_register import register_cpu_ci - -register_cpu_ci( - est_time=10, - suite="base-a-test-cpu", - nightly=False, - disabled=None, -) - - -def _make_self(): - return SimpleNamespace( - dsa_enable_prefill_cp=False, - mla_enable_prefill_cp=False, - cp_rank=1, - cp_size=2, - use_dsa=True, - ) - - -def test_pp_nonfirst_rank_both_inputs_none_does_not_crash(): - hidden = torch.zeros((8, 4096)) - proxy = PPProxyTensors({"hidden_states": hidden}) - self = _make_self() - Glm5NextForConditionalGeneration._prepare_context_parallel_metadata( - self, None, None, SimpleNamespace(), proxy - ) - - -if __name__ == "__main__": - sys.exit(pytest.main([__file__])) diff --git a/test/registered/unit/models/test_glm5_next_weight_loading.py b/test/registered/unit/models/test_glm5_next_weight_loading.py deleted file mode 100644 index b6d90b5b4ce8a..0000000000000 --- a/test/registered/unit/models/test_glm5_next_weight_loading.py +++ /dev/null @@ -1,54 +0,0 @@ -import unittest -from types import SimpleNamespace -from unittest.mock import patch - -import torch - -from sglang.srt.models.glm5_next import Glm5NextForConditionalGeneration -from sglang.test.ci.ci_register import register_cpu_ci - -register_cpu_ci(est_time=5, suite="base-a-test-cpu") - - -class _FakeParam: - def __init__(self): - self.loaded = None - - def weight_loader(self, param, loaded_weight): - self.loaded = loaded_weight - - -class TestGlm5NextWeightLoading(unittest.TestCase): - @patch("sglang.srt.models.glm5_next.DeepseekV2WeightLoaderMixin.post_load_weights") - def test_quark_block_fp8_weight_scale_loads_scale_inv(self, post_load): - scale_param = _FakeParam() - model = SimpleNamespace( - config=SimpleNamespace( - n_routed_experts=0, - num_hidden_layers=45, - num_nextn_predict_layers=1, - ), - num_fused_shared_experts=0, - quant_config=None, - named_parameters=lambda: iter( - [("model.layers.0.mlp.down_proj.weight_scale_inv", scale_param)] - ), - ) - loaded_scale = torch.arange(6, dtype=torch.float32).reshape(2, 3) - - Glm5NextForConditionalGeneration.load_weights( - model, - [ - ( - "model.language_model.layers.0.mlp.down_proj.weight_scale", - loaded_scale, - ) - ], - ) - - self.assertIs(scale_param.loaded, loaded_scale) - post_load.assert_called_once() - - -if __name__ == "__main__": - unittest.main() diff --git a/test/registered/unit/models/test_nextn_hf_to_sglang_mapper.py b/test/registered/unit/models/test_nextn_hf_to_sglang_mapper.py deleted file mode 100644 index cb0970f976963..0000000000000 --- a/test/registered/unit/models/test_nextn_hf_to_sglang_mapper.py +++ /dev/null @@ -1,73 +0,0 @@ -import sys -from types import SimpleNamespace - -import pytest - -from sglang.srt.model_loader.loader import _get_quantization_config -from sglang.srt.models.glm5_next_nextn import Glm5NextForConditionalGenerationNextN -from sglang.test.ci.ci_register import register_cpu_ci - -register_cpu_ci( - est_time=10, - suite="base-a-test-cpu", - nightly=False, - disabled=None, -) - - -class _FakeQuarkConfig: - def __init__(self): - self.exclude_layers = ["model.layers.46"] - - def get_name(self): - return "quark" - - def get_min_capability(self): - return 75 - - def get_supported_act_dtypes(self): - return ["auto"] - - def apply_weight_name_mapper(self, mapper): - self.exclude_layers = mapper.apply_list(self.exclude_layers) - - -def test_loader_mapper_hook_flows_into_quark_nextn_exclusion(monkeypatch): - monkeypatch.setattr( - Glm5NextForConditionalGenerationNextN, "packed_modules_mapping", {} - ) - monkeypatch.setattr( - "sglang.srt.model_loader.loader.get_model_architecture", - lambda mc: (Glm5NextForConditionalGenerationNextN, None), - ) - fake = _FakeQuarkConfig() - monkeypatch.setattr( - "sglang.srt.model_loader.loader.get_quant_config", - lambda *a, **k: fake, - ) - monkeypatch.setattr( - "sglang.srt.model_loader.loader.get_device_capability", - lambda: (None, None), - ) - - model_config = SimpleNamespace( - hf_config=SimpleNamespace(text_config=SimpleNamespace(num_hidden_layers=46)), - quantization="quark", - dtype="auto", - is_fp4_experts=False, - dequant_fp4_to_fp8=False, - nvfp4_moe_meta=None, - packed_modules_mapping={}, - ) - quant_config = _get_quantization_config(model_config, SimpleNamespace()) - - assert quant_config.exclude_layers == ["model.decoder"] - - resolved = Glm5NextForConditionalGenerationNextN.__new__( - Glm5NextForConditionalGenerationNextN - )._resolve_nextn_quant_config(SimpleNamespace(num_hidden_layers=46), quant_config) - assert resolved is None - - -if __name__ == "__main__": - sys.exit(pytest.main([__file__])) diff --git a/test/registered/unit/server_args/test_server_args.py b/test/registered/unit/server_args/test_server_args.py index 64688e5d39a8e..803a623436be6 100644 --- a/test/registered/unit/server_args/test_server_args.py +++ b/test/registered/unit/server_args/test_server_args.py @@ -806,74 +806,6 @@ def test_skip_tokenizer_worker_counts(self): self.assertEqual(resolution_result(server_args, "detokenizer_worker_num"), 1) -class TestRocmDsaTopKCompatibility(CustomTestCase): - def test_gfx942_defaults_to_torch_unfused_topk(self): - args = ServerArgs(model_path="dummy") - - with ( - envs.SGLANG_DSA_FUSE_TOPK.override(True), - patch.object(server_args_module, "is_hip", return_value=True), - patch.object(server_args_module, "is_gfx95_supported", return_value=False), - ): - args._handle_rocm_dsa_topk_compatibility() - - self.assertEqual(resolution_result(args, "dsa_topk_backend"), "torch") - self.assertEqual( - resolution_result(args, "speculative_dsa_topk_backend"), - "sgl-kernel", - ) - self.assertFalse(envs.SGLANG_DSA_FUSE_TOPK.get()) - - def test_gfx950_keeps_sgl_kernel_fused_topk(self): - args = ServerArgs(model_path="dummy") - - with ( - envs.SGLANG_DSA_FUSE_TOPK.override(True), - patch.object(server_args_module, "is_hip", return_value=True), - patch.object(server_args_module, "is_gfx95_supported", return_value=True), - ): - args._handle_rocm_dsa_topk_compatibility() - - self.assertEqual(resolution_result(args, "dsa_topk_backend"), "sgl-kernel") - self.assertEqual( - resolution_result(args, "speculative_dsa_topk_backend"), - "sgl-kernel", - ) - self.assertTrue(envs.SGLANG_DSA_FUSE_TOPK.get()) - - def test_cuda_and_explicit_backends_are_unchanged(self): - cuda_args = ServerArgs(model_path="dummy") - explicit_args = ServerArgs( - model_path="dummy", - dsa_topk_backend="torch", - speculative_dsa_topk_backend="flashinfer", - ) - - with envs.SGLANG_DSA_FUSE_TOPK.override(True): - with patch.object(server_args_module, "is_hip", return_value=False): - cuda_args._handle_rocm_dsa_topk_compatibility() - self.assertEqual( - resolution_result(cuda_args, "dsa_topk_backend"), "sgl-kernel" - ) - self.assertTrue(envs.SGLANG_DSA_FUSE_TOPK.get()) - - with ( - patch.object(server_args_module, "is_hip", return_value=True), - patch.object( - server_args_module, "is_gfx95_supported", return_value=False - ), - ): - explicit_args._handle_rocm_dsa_topk_compatibility() - self.assertEqual( - resolution_result(explicit_args, "dsa_topk_backend"), "torch" - ) - self.assertEqual( - resolution_result(explicit_args, "speculative_dsa_topk_backend"), - "flashinfer", - ) - self.assertTrue(envs.SGLANG_DSA_FUSE_TOPK.get()) - - class TestHiSparseDsaBackendPolicy(unittest.TestCase): # The backend selection moved to the resolution pipeline; these policy # tests drive the pass through its read-only view. @@ -2103,50 +2035,6 @@ def test_lora_still_disables_tc_piecewise_prefill_graph(self): ) -class TestBreakableCudaGraphKDACompatibility(CustomTestCase): - def _handled_args(self, **overrides): - args = ServerArgs(model_path="dummy", **overrides) - text_config = SimpleNamespace( - layer_types=["linear_attention", "deepseek_sparse_attention"], - linear_num_heads=64, - linear_head_dim=128, - ) - args.model_config = SimpleNamespace( - hf_config=SimpleNamespace( - architectures=["KimiLinearForCausalLM"], - get_text_config=lambda: text_config, - ), - is_piecewise_cuda_graph_disabled_model=False, - is_multimodal=False, - is_multimodal_piecewise_cuda_graph_supported=False, - is_multimodal_breakable_cuda_graph_supported=False, - ) - with ( - patch("sglang.srt.utils.is_cuda", return_value=True), - patch.object(ServerArgs, "use_mla_backend", return_value=False), - ): - args._handle_cuda_graph_config() - return args - - def test_default_breakable_prefill_graph_is_disabled(self): - args = self._handled_args() - - self.assertEqual(args.cuda_graph_config.prefill.backend, Backend.DISABLED) - self.assertNotEqual(args.cuda_graph_config.decode.backend, Backend.DISABLED) - - def test_explicit_breakable_prefill_graph_is_preserved(self): - args = self._handled_args(cuda_graph_backend_prefill=Backend.BREAKABLE) - - self.assertEqual(args.cuda_graph_config.prefill.backend, Backend.BREAKABLE) - - def test_legacy_kda_layer_list_is_detected(self): - from sglang.srt.configs.model_config import uses_kda_attention - - config = SimpleNamespace(linear_attn_config={"kda_layers": [0, 2]}) - - self.assertTrue(uses_kda_attention(config)) - - class TestBreakableCudaGraphMultimodalAllowlist(CustomTestCase): """The BCG "multimodal model" rule exempts archs on the BCG multimodal opt-in allowlist (multimodal_breakable_cuda_graph_supported_model_archs).""" diff --git a/test/registered/unit/spec/test_spec_cpu_overlap_constraint.py b/test/registered/unit/spec/test_spec_cpu_overlap_constraint.py index d699afd3fdbd8..dabc6e95a9615 100644 --- a/test/registered/unit/spec/test_spec_cpu_overlap_constraint.py +++ b/test/registered/unit/spec/test_spec_cpu_overlap_constraint.py @@ -1,6 +1,5 @@ import unittest from types import SimpleNamespace -from unittest.mock import Mock from sglang.srt.arg_groups.overrides import resolution_result from sglang.srt.arg_groups.speculative_hook import handle_speculative_decoding @@ -72,55 +71,6 @@ def test_cuda_eagle_keeps_overlap_schedule(self): self.assertFalse(resolution_result(args, "disable_overlap_schedule")) - def test_hybrid_kda_allows_plan_stream_graph_load(self): - from sglang.srt.layers.attention.hybrid_linear_attn_backend import ( - HybridLinearAttnBackend, - ) - from sglang.srt.layers.attention.linear.kda_backend import KDAAttnBackend - - full_backend = Mock( - token_to_kv_pool=object(), - req_to_token_pool=object(), - max_context_len=4096, - needs_cpu_seq_lens=False, - ) - linear_backend = Mock( - spec=KDAAttnBackend, - needs_cpu_seq_lens=False, - supports_overlap_plan_stream_graph_load=( - KDAAttnBackend.supports_overlap_plan_stream_graph_load - ), - ) - - backend = HybridLinearAttnBackend(full_backend, linear_backend, []) - - self.assertTrue(backend.supports_overlap_plan_stream_graph_load) - self.assertFalse(backend.needs_cpu_seq_lens) - - def test_unaudited_linear_backend_defers_plan_stream_graph_load(self): - from sglang.srt.layers.attention.hybrid_linear_attn_backend import ( - HybridLinearAttnBackend, - MambaAttnBackendBase, - ) - - full_backend = Mock( - token_to_kv_pool=object(), - req_to_token_pool=object(), - max_context_len=4096, - needs_cpu_seq_lens=False, - ) - linear_backend = Mock( - spec=MambaAttnBackendBase, - needs_cpu_seq_lens=False, - supports_overlap_plan_stream_graph_load=( - MambaAttnBackendBase.supports_overlap_plan_stream_graph_load - ), - ) - - backend = HybridLinearAttnBackend(full_backend, linear_backend, []) - - self.assertFalse(backend.supports_overlap_plan_stream_graph_load) - if __name__ == "__main__": unittest.main() From 399499ca159da099c16d20ddc2f5898491071431 Mon Sep 17 00:00:00 2001 From: Baizhou Zhang Date: Mon, 31 Aug 2026 03:36:06 -0700 Subject: [PATCH 16/44] fix: resolve GLM-5.3-flash post-rebase CI regressions (#37235) --- .../sglang/srt/arg_groups/cuda_graph_hook.py | 2 +- .../disaggregation/encoder/preprocessor.py | 12 +++----- python/sglang/srt/disaggregation/utils.py | 9 +++--- .../layers/attention/dsa/dsa_indexer_kpool.py | 4 +-- .../sglang/srt/mem_cache/kv_cache_builder.py | 2 +- python/sglang/srt/models/glm5_next.py | 30 +++++++------------ .../disaggregation/test_nixl_backend_basic.py | 3 ++ .../test_fp8_moe_runner_ownership.py | 9 ++++-- .../test_generation_auxiliary_output.py | 2 ++ .../test_scheduler_chunked_abort_race.py | 4 +-- .../model_executor/test_pool_configurator.py | 2 +- .../multimodal/test_gpu_feature_transport.py | 3 ++ .../test_eagle_worker_v2_topk1_fastpath.py | 1 + 13 files changed, 43 insertions(+), 40 deletions(-) diff --git a/python/sglang/srt/arg_groups/cuda_graph_hook.py b/python/sglang/srt/arg_groups/cuda_graph_hook.py index b15a7dbb0ed72..0aa5038167995 100644 --- a/python/sglang/srt/arg_groups/cuda_graph_hook.py +++ b/python/sglang/srt/arg_groups/cuda_graph_hook.py @@ -321,8 +321,8 @@ def disable_breakable_cudagraph_if_incompatible(server_args: Any): name, ) declare_resolution( - "_disable_breakable_cudagraph_if_incompatible", server_args, + "_disable_breakable_cudagraph_if_incompatible", cuda_graph_config=with_phase( cfg.cuda_graph_config, Phase.PREFILL, backend=Backend.DISABLED ), diff --git a/python/sglang/srt/disaggregation/encoder/preprocessor.py b/python/sglang/srt/disaggregation/encoder/preprocessor.py index d198a96a2c319..cb88889d6b78c 100644 --- a/python/sglang/srt/disaggregation/encoder/preprocessor.py +++ b/python/sglang/srt/disaggregation/encoder/preprocessor.py @@ -19,11 +19,6 @@ from transformers import AutoProcessor from sglang.srt.configs.model_config import ModelConfig -from sglang.srt.distributed.parallel_state import ( - get_attn_tensor_model_parallel_rank, - get_attn_tensor_model_parallel_world_size, - get_attn_tp_group, -) from sglang.srt.environ import envs from sglang.srt.managers.schedule_batch import Modality from sglang.srt.multimodal.cache import parse_content_hash, snapshot_media @@ -485,7 +480,7 @@ async def _dp_sharded_decode_single_video( torch.distributed.all_reduce( ok, op=torch.distributed.ReduceOp.MIN, - group=get_attn_tp_group().cpu_group, + group=get_parallel().attn_tp_group.cpu_group, ) if not int(ok.item()): if local_error is not None: @@ -579,7 +574,8 @@ async def _flatten_and_load_videos(self, mm_items): ] ) else: - tp_size = get_attn_tensor_model_parallel_world_size() + parallel = get_parallel() + tp_size = parallel.attn_tp_size sampled = None if len(video_items) == 1: vr = video_items[0] @@ -600,7 +596,7 @@ async def _flatten_and_load_videos(self, mm_items): result = await self._dp_sharded_decode_single_video( video_items[0], video_configs[0], - tp_rank=get_attn_tensor_model_parallel_rank(), + tp_rank=parallel.attn_tp_rank, tp_size=tp_size, video_processor_kwargs=video_processor_kwargs, precomputed_indices=sampled, diff --git a/python/sglang/srt/disaggregation/utils.py b/python/sglang/srt/disaggregation/utils.py index 1f713e1e3307f..3ca8d8fd289ed 100644 --- a/python/sglang/srt/disaggregation/utils.py +++ b/python/sglang/srt/disaggregation/utils.py @@ -24,6 +24,7 @@ from sglang.srt.environ import envs from sglang.srt.runtime_context import ( get_disagg, + get_parallel, ) from sglang.srt.utils import is_hip, is_npu @@ -171,13 +172,13 @@ def decode_gate() -> bool: ) -def should_bypass_dsa_cp_prefix_cache(server_args) -> bool: +def should_bypass_dsa_cp_prefix_cache() -> bool: """Bypass prefix cache under DSA Prefill CP until CP-aware radix resharding exists; without it, cache hits let attention read non-local page rows.""" return ( - server_args.disaggregation_mode == DisaggregationMode.PREFILL.value - and server_args.attn_cp_size > 1 - and server_args.enable_dsa_prefill_context_parallel + get_disagg().disaggregation_mode == DisaggregationMode.PREFILL.value + and get_parallel().attn_cp_size > 1 + and get_parallel().enable_dsa_prefill_context_parallel ) diff --git a/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py b/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py index 177c7e2cd2b25..8403bbf278ec3 100644 --- a/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py +++ b/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py @@ -47,7 +47,7 @@ get_token_to_kv_pool, ) from sglang.srt.model_executor.runner import get_is_capture_mode -from sglang.srt.runtime_context import get_parallel, get_server_args +from sglang.srt.runtime_context import get_device, get_parallel if TYPE_CHECKING: from sglang.srt.mem_cache.memory_pool import DSATokenToKVPool @@ -154,7 +154,7 @@ def __init__( base=rope_theta, # type: ignore rope_scaling=rope_scaling, is_neox_style=is_neox_style, - device=get_server_args().device, + device=get_device().device, ) self.block_size = block_size self.scale_fmt = scale_fmt diff --git a/python/sglang/srt/mem_cache/kv_cache_builder.py b/python/sglang/srt/mem_cache/kv_cache_builder.py index 93ecf7c96a0ce..afa878e86b6bd 100644 --- a/python/sglang/srt/mem_cache/kv_cache_builder.py +++ b/python/sglang/srt/mem_cache/kv_cache_builder.py @@ -239,7 +239,7 @@ def build_kv_cache( retraction_backup = resolve_decode_retraction_backup(tp_worker=tp_worker) - bypass_dsa_cp_prefix_cache = should_bypass_dsa_cp_prefix_cache(server_args) + bypass_dsa_cp_prefix_cache = should_bypass_dsa_cp_prefix_cache() disable_radix_cache = ( get_memory().disable_radix_cache or (model_config.is_multimodal and uses_transformers_backend) diff --git a/python/sglang/srt/models/glm5_next.py b/python/sglang/srt/models/glm5_next.py index 63a99fdb85248..4eba804851cdb 100644 --- a/python/sglang/srt/models/glm5_next.py +++ b/python/sglang/srt/models/glm5_next.py @@ -60,7 +60,10 @@ ) from sglang.srt.layers.logits_processor import LogitsProcessor from sglang.srt.layers.moe.fused_moe_triton.layer import FusedMoE -from sglang.srt.layers.moe.utils import get_moe_a2a_backend +from sglang.srt.layers.moe.utils import ( + get_moe_a2a_backend, + is_shared_experts_fusion_disabled, +) from sglang.srt.layers.quantization.base_config import QuantizationConfig from sglang.srt.layers.radix_linear_attention import RadixLinearAttention from sglang.srt.layers.rotary_embedding import get_rope @@ -118,7 +121,7 @@ run_dp_presharded_mrope_vision_model, run_dp_sharded_mrope_vision_model, ) -from sglang.srt.runtime_context import get_forward, get_parallel, get_server_args +from sglang.srt.runtime_context import get_forward, get_mm, get_parallel, get_spec from sglang.srt.speculative.spec_info import SpeculativeAlgorithm from sglang.srt.utils.common import ( BumpAllocator, @@ -622,7 +625,7 @@ def __init__( rope_scaling = config.rope_scaling max_position_embeddings = config.max_position_embeddings self.speculative_algorithm = SpeculativeAlgorithm.from_string( - get_server_args().speculative_algorithm + get_spec().speculative_algorithm ) self.dsa_enable_prefill_cp = dsa_enable_prefill_cp self.mla_enable_prefill_cp = mla_enable_prefill_cp @@ -1321,7 +1324,7 @@ def __init__( text_config.hidden_size, quant_config=quant_config, prefix=add_prefix("lm_head", prefix), - use_attn_tp_group=get_server_args().enable_dp_lm_head, + use_attn_tp_group=get_parallel().enable_dp_lm_head, ) else: self.lm_head = PPMissingLayer() @@ -1361,7 +1364,7 @@ def __init__( text_config.mhc, ) - self.use_data_parallel = get_server_args().mm_enable_dp_encoder + self.use_data_parallel = get_mm().mm_enable_dp_encoder self.visual = None if not self.language_only: self.visual = Glm5NextVisionModel( @@ -1420,22 +1423,11 @@ def shared_experts_fusion_disable_reason(cls, hf_config, quant_config): return None def determine_num_fused_shared_experts(self): - self.num_fused_shared_experts = 0 - if get_server_args().disable_shared_experts_fusion: - return - - disable_reason = type(self).shared_experts_fusion_disable_reason( - self.config, self.quant_config + self.num_fused_shared_experts = ( + 0 if is_shared_experts_fusion_disabled() else self.config.n_shared_experts ) - - if disable_reason is not None: - log_info_on_rank0( - logger, - f"{disable_reason} Shared experts fusion optimization is disabled.", - ) + if self.num_fused_shared_experts == 0: return - - self.num_fused_shared_experts = self.config.n_shared_experts assert ( self.num_fused_shared_experts == 1 ), f"Only 1 fused shared expert is supported for {type(self).__name__}" diff --git a/test/registered/unit/disaggregation/test_nixl_backend_basic.py b/test/registered/unit/disaggregation/test_nixl_backend_basic.py index b5f8c8e5cb2d6..54354374e366b 100644 --- a/test/registered/unit/disaggregation/test_nixl_backend_basic.py +++ b/test/registered/unit/disaggregation/test_nixl_backend_basic.py @@ -452,6 +452,7 @@ def _make_manager(self, room): mgr.decode_kv_args_table = { "agent": SimpleNamespace( decode_tp_size=1, + decode_tp_rank=0, dst_kv_ptrs=[0], dst_aux_ptrs=[0], gpu_id=0, @@ -475,6 +476,8 @@ def _make_manager(self, room): mgr.is_mla_backend = False mgr.is_hybrid_mla_backend = False mgr.attn_tp_size = 1 + mgr.attn_tp_rank = 0 + mgr.attn_cp_rank = 0 mgr.transfer_source_rank = 0 mgr.kv_args = SimpleNamespace(engine_rank=0, kv_data_ptrs=[0]) mgr.exceptions = {} diff --git a/test/registered/unit/layers/quantization/test_fp8_moe_runner_ownership.py b/test/registered/unit/layers/quantization/test_fp8_moe_runner_ownership.py index 3e5f5787c18c4..4623f75d21ce1 100644 --- a/test/registered/unit/layers/quantization/test_fp8_moe_runner_ownership.py +++ b/test/registered/unit/layers/quantization/test_fp8_moe_runner_ownership.py @@ -129,7 +129,9 @@ def test_global_aiter_does_not_shuffle_triton_runner_weights(self): patch("sglang.srt.layers.quantization.fp8._use_aiter", True), patch("sglang.srt.layers.quantization.fp8._is_fp8_fnuz", False), patch.object(method, "_convert_mxfp8_moe_to_block_fp8"), - patch("sglang.srt.layers.quantization.fp8.shuffle_weight") as shuffle, + patch( + "sglang.srt.layers.quantization.fp8.shuffle_weight", create=True + ) as shuffle, ): method.process_weights_after_loading_block_quant(layer) @@ -150,7 +152,9 @@ def test_borrowed_delegate_skips_aiter_weight_shuffle(self): patch("sglang.srt.layers.quantization.fp8._use_aiter", True), patch("sglang.srt.layers.quantization.fp8._is_fp8_fnuz", False), patch.object(method, "_convert_mxfp8_moe_to_block_fp8"), - patch("sglang.srt.layers.quantization.fp8.shuffle_weight") as shuffle, + patch( + "sglang.srt.layers.quantization.fp8.shuffle_weight", create=True + ) as shuffle, ): method.process_weights_after_loading_block_quant(layer) @@ -179,6 +183,7 @@ def add_one(weight, _tile): patch( "sglang.srt.layers.quantization.fp8.shuffle_weight", side_effect=add_one, + create=True, ) as shuffle, ): method.process_weights_after_loading_block_quant(layer) diff --git a/test/registered/unit/managers/test_generation_auxiliary_output.py b/test/registered/unit/managers/test_generation_auxiliary_output.py index ae371fd12dbe0..85c539ad7d13b 100644 --- a/test/registered/unit/managers/test_generation_auxiliary_output.py +++ b/test/registered/unit/managers/test_generation_auxiliary_output.py @@ -472,6 +472,7 @@ def test_disaggregated_prefill_consumes_auxiliary_output_after_commit(): disagg_prefill_inflight_queue=[], send_kv_chunk=Mock(), metrics_reporter=SimpleNamespace(report_prefill_stats=Mock()), + maybe_send_health_check_signal=Mock(), ) with patch("sglang.srt.disaggregation.prefill.maybe_cache_unfinished_req"): @@ -488,6 +489,7 @@ def test_disaggregated_prefill_consumes_auxiliary_output_after_commit(): host_output, [0], ) + scheduler.maybe_send_health_check_signal.assert_called_once_with() def test_logprob_only_reuses_preprocessing_without_observer_lifecycle(): diff --git a/test/registered/unit/managers/test_scheduler_chunked_abort_race.py b/test/registered/unit/managers/test_scheduler_chunked_abort_race.py index b7f0a82941512..084b6db176f75 100644 --- a/test/registered/unit/managers/test_scheduler_chunked_abort_race.py +++ b/test/registered/unit/managers/test_scheduler_chunked_abort_race.py @@ -19,8 +19,7 @@ class _FakeReq: def __init__(self, rid: str): self.rid = rid - self.req_pool_idx = 1 - self.mamba_pool_idx = None + self.kv = SimpleNamespace(req_pool_idx=1) self.to_finish = None self._finished = False @@ -33,6 +32,7 @@ def _make_scheduler(pending_req, *, chunked_req, running_reqs) -> Scheduler: sched.chunked_req = chunked_req sched._pending_chunked_abort_req = pending_req sched.waiting_queue = [] + sched.mm_receiver = None sched.dllm_config = None sched.grammar_manager = Mock() sched.disaggregation_mode = None diff --git a/test/registered/unit/model_executor/test_pool_configurator.py b/test/registered/unit/model_executor/test_pool_configurator.py index 752ece2d24c8e..b07e08c006ae9 100644 --- a/test/registered/unit/model_executor/test_pool_configurator.py +++ b/test/registered/unit/model_executor/test_pool_configurator.py @@ -746,7 +746,7 @@ def test_hybrid_swa_scales_draft_budget_with_dcp(self): expected = ( full_pt * (16 + 4 * dcp_size) - + mr.server_args.swa_full_tokens_ratio * swa_pt * 16 + + get_schedule().swa_full_tokens_ratio * swa_pt * 16 ) self.assertEqual(cfg._cell_size, expected) diff --git a/test/registered/unit/multimodal/test_gpu_feature_transport.py b/test/registered/unit/multimodal/test_gpu_feature_transport.py index 14424291afa61..86b25c7409fe5 100644 --- a/test/registered/unit/multimodal/test_gpu_feature_transport.py +++ b/test/registered/unit/multimodal/test_gpu_feature_transport.py @@ -270,6 +270,7 @@ def test_text_request_uses_base_send_path(self): from sglang.srt.managers.tokenizer_manager import TokenizerManager manager = object.__new__(TokenizerManager) + manager.rid_to_state = {} transport = MagicMock() transport.prepare_for_dispatch.return_value = [] manager.cuda_vmm_feature_transport = transport @@ -297,6 +298,7 @@ def test_failed_dispatch_cancels_published_items(self): ) manager = object.__new__(tokenizer_manager.TokenizerManager) + manager.rid_to_state = {} transport = MagicMock() manager._dispatch_to_scheduler = MagicMock( side_effect=RuntimeError("send failed") @@ -331,6 +333,7 @@ def test_post_dispatch_failure_does_not_cancel_published_items(self): ) manager = object.__new__(tokenizer_manager.TokenizerManager) + manager.rid_to_state = {} transport = MagicMock() manager._dispatch_to_scheduler = MagicMock() time_stats = MagicMock() diff --git a/test/registered/unit/spec/test_eagle_worker_v2_topk1_fastpath.py b/test/registered/unit/spec/test_eagle_worker_v2_topk1_fastpath.py index 9587dda35b9c6..db5109c6412af 100644 --- a/test/registered/unit/spec/test_eagle_worker_v2_topk1_fastpath.py +++ b/test/registered/unit/spec/test_eagle_worker_v2_topk1_fastpath.py @@ -204,6 +204,7 @@ def test_missing_seed_cuda_graph_fallback(self): worker.speculative_num_steps = 1 worker.speculative_num_draft_tokens = 2 worker.device = DEVICE + worker.plan_stream = None worker.tree_mask_mode = None worker.seed_dsa_topk_from_draft_extend = seed_enabled worker.index_share_for_mtp_iteration = True From 3992c4ce2410ec1be554aadd11836fc539ced6b9 Mon Sep 17 00:00:00 2001 From: Jinn <47354855+jhinpan@users.noreply.github.com> Date: Mon, 31 Aug 2026 11:24:14 -0700 Subject: [PATCH 17/44] fix(kda): preserve split-grid program ids (#37250) --- .../kernels/ops/attention/fla/fused_sigmoid_gating_recurrent.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/python/sglang/kernels/ops/attention/fla/fused_sigmoid_gating_recurrent.py b/python/sglang/kernels/ops/attention/fla/fused_sigmoid_gating_recurrent.py index 07cd25407a205..8f7c3420025fe 100644 --- a/python/sglang/kernels/ops/attention/fla/fused_sigmoid_gating_recurrent.py +++ b/python/sglang/kernels/ops/attention/fla/fused_sigmoid_gating_recurrent.py @@ -92,8 +92,6 @@ def fused_sigmoid_gating_delta_rule_update_kernel( tl.extra.cuda.gdc_wait() tl.extra.cuda.gdc_launch_dependents() - i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2) - i_n, i_hv = i_nh // HV, i_nh % HV i_h = i_hv // (HV // H) if IS_VARLEN: From 4464e0f540408855e55c1f51fabf4338049f9104 Mon Sep 17 00:00:00 2001 From: Baizhou Zhang Date: Mon, 31 Aug 2026 14:48:56 -0700 Subject: [PATCH 18/44] fix: resolve remaining GLM-5.3 rebase regressions (#37243) --- .../ops/attention/helion/kda_prefill.py | 3 ++ python/sglang/srt/configs/hybrid_arch.py | 4 +- .../srt/speculative/base_spec_worker.py | 37 +++++++++++++++++ .../sglang/srt/speculative/eagle_worker_v2.py | 35 +--------------- .../speculative/frozen_kv_mtp_worker_v2.py | 9 +++- test/registered/cp/test_dsa_trtllm_fp8_cp.py | 13 +++--- .../kernels/ops/attention/test_kda_helion.py | 41 ++++++++++++++++++- .../unit/spec/test_adaptive_spec_params.py | 23 ++++++----- 8 files changed, 111 insertions(+), 54 deletions(-) diff --git a/python/sglang/kernels/ops/attention/helion/kda_prefill.py b/python/sglang/kernels/ops/attention/helion/kda_prefill.py index 25e0eb3c12c98..ad67fea7297c6 100644 --- a/python/sglang/kernels/ops/attention/helion/kda_prefill.py +++ b/python/sglang/kernels/ops/attention/helion/kda_prefill.py @@ -1314,6 +1314,7 @@ def chunk_kda( dt_bias: torch.Tensor | None = None, lower_bound: float | None = None, output_intermediate_states: bool = False, + beta_is_raw: bool = False, **kwargs: object, ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: """Match the public forward contract of SGLang's Triton ``chunk_kda``.""" @@ -1327,6 +1328,8 @@ def chunk_kda( raise ValueError("g and beta must cover every q token") g = g[:, :num_tokens] beta = beta[:, :num_tokens] + if beta_is_raw: + beta = beta.float().sigmoid() if num_tokens == 1: # Tracing constant-folds size-one dimensions, but the resulting kernel # can share a cache entry with longer inputs. Keep T=1 on Triton so a diff --git a/python/sglang/srt/configs/hybrid_arch.py b/python/sglang/srt/configs/hybrid_arch.py index 8e5c6155d6658..c6d6bf5a1bdca 100644 --- a/python/sglang/srt/configs/hybrid_arch.py +++ b/python/sglang/srt/configs/hybrid_arch.py @@ -115,7 +115,9 @@ def kimi_linear_config(model_config: ModelConfig): def glm5_next_config(model_config: ModelConfig): hf_config = model_config.hf_config - if hf_config.model_type == "glm5_next" and not model_config.is_draft_model: + if getattr(hf_config, "model_type", None) == "glm5_next" and not getattr( + model_config, "is_draft_model", False + ): return hf_config.get_text_config() return None diff --git a/python/sglang/srt/speculative/base_spec_worker.py b/python/sglang/srt/speculative/base_spec_worker.py index 7f6edb3362092..d9e5b52e5fa45 100644 --- a/python/sglang/srt/speculative/base_spec_worker.py +++ b/python/sglang/srt/speculative/base_spec_worker.py @@ -12,6 +12,7 @@ merge_graph_time_usage, ) from sglang.srt.runtime_context import get_disagg, get_exec, get_memory, get_schedule +from sglang.srt.speculative.spec_utils import get_plan_stream if TYPE_CHECKING: from sglang.srt.managers.io_struct import ( @@ -63,6 +64,42 @@ def __init__(self) -> None: self._specialized_graph_memory_usage: dict[str, float] = {} self._specialized_graph_time_usage: dict[str, float] = {} + def _init_handoff_events(self) -> None: + self.plan_stream, self.plan_stream_ctx = get_plan_stream(self.device) + # Keep handoff events outside captured graphs; per-kind rings avoid + # re-recording an event with a pending wait. + handoff_ring_size = 8 + if self.plan_stream is not None: + event_cls = torch.get_device_module(self.device).Event + self._verify_handoff_events = [ + event_cls() for _ in range(handoff_ring_size) + ] + self._draft_extend_handoff_events = [ + event_cls() for _ in range(handoff_ring_size) + ] + else: + self._verify_handoff_events = [] + self._draft_extend_handoff_events = [] + self._verify_handoff_index = 0 + self._draft_extend_handoff_index = 0 + self._pending_verify_handoff_event = None + + def _record_handoff_event(self, kind: str, stream): + if self.plan_stream is None: + return None + if kind == "verify": + events = self._verify_handoff_events + index = self._verify_handoff_index + self._verify_handoff_index += 1 + else: + assert kind == "draft_extend" + events = self._draft_extend_handoff_events + index = self._draft_extend_handoff_index + self._draft_extend_handoff_index += 1 + event = events[index % len(events)] + event.record(stream) + return event + @abstractmethod def draft(): pass diff --git a/python/sglang/srt/speculative/eagle_worker_v2.py b/python/sglang/srt/speculative/eagle_worker_v2.py index cd03f759ed112..642f8f230ea91 100644 --- a/python/sglang/srt/speculative/eagle_worker_v2.py +++ b/python/sglang/srt/speculative/eagle_worker_v2.py @@ -195,40 +195,7 @@ def __init__( ) self.tree_mask_mode = default_tree_mask_mode() - self.plan_stream, self.plan_stream_ctx = get_plan_stream(self.device) - # Keep handoff events outside captured graphs; per-kind rings avoid - # re-recording an event with a pending wait. - handoff_ring_size = 8 - if self.plan_stream is not None: - event_cls = torch.get_device_module(self.device).Event - self._verify_handoff_events = [ - event_cls() for _ in range(handoff_ring_size) - ] - self._draft_extend_handoff_events = [ - event_cls() for _ in range(handoff_ring_size) - ] - else: - self._verify_handoff_events = [] - self._draft_extend_handoff_events = [] - self._verify_handoff_index = 0 - self._draft_extend_handoff_index = 0 - self._pending_verify_handoff_event = None - - def _record_handoff_event(self, kind: str, stream): - if self.plan_stream is None: - return None - if kind == "verify": - events = self._verify_handoff_events - index = self._verify_handoff_index - self._verify_handoff_index += 1 - else: - assert kind == "draft_extend" - events = self._draft_extend_handoff_events - index = self._draft_extend_handoff_index - self._draft_extend_handoff_index += 1 - event = events[index % len(events)] - event.record(stream) - return event + self._init_handoff_events() def alloc_memory_pool( self, diff --git a/python/sglang/srt/speculative/frozen_kv_mtp_worker_v2.py b/python/sglang/srt/speculative/frozen_kv_mtp_worker_v2.py index 056f73e7ea859..e67e76651d1c8 100644 --- a/python/sglang/srt/speculative/frozen_kv_mtp_worker_v2.py +++ b/python/sglang/srt/speculative/frozen_kv_mtp_worker_v2.py @@ -172,6 +172,7 @@ def __init__( # None so inherited probes (spec_v2_attn_backends, adaptive) stay typed. self.draft_extend_attn_backend = None self.cuda_graph_runner_for_draft_extend = None + self._init_handoff_events() def alloc_memory_pool( self, @@ -509,7 +510,7 @@ def draft(self, batch: ScheduleBatch): self.speculative_num_draft_tokens, ) - return FrozenKVMTPVerifyInput( + verify_input = FrozenKVMTPVerifyInput( draft_token=draft_tokens, custom_mask=tree_mask, positions=position, @@ -524,6 +525,12 @@ def draft(self, batch: ScheduleBatch): seq_lens_sum=batch.seq_lens_sum, seq_lens_cpu=batch.seq_lens_cpu, ) + # Gate plan-stream GPU work on the forward-stream point that finalized + # the verify tree, matching the regular EAGLE draft worker contract. + self._pending_verify_handoff_event = self._record_handoff_event( + "verify", torch.get_device_module(self.device).current_stream() + ) + return verify_input def draft_forward(self, forward_batch: ForwardBatch): spec_info = forward_batch.spec_info diff --git a/test/registered/cp/test_dsa_trtllm_fp8_cp.py b/test/registered/cp/test_dsa_trtllm_fp8_cp.py index 134a7a462a777..c6543d8df2b31 100644 --- a/test/registered/cp/test_dsa_trtllm_fp8_cp.py +++ b/test/registered/cp/test_dsa_trtllm_fp8_cp.py @@ -4,15 +4,16 @@ from sglang.srt.layers.attention.dsa_backend import ( _should_all_gather_dsa_trtllm_fp8_kv, - _should_return_dsa_trtllm_lse, + _should_return_dsa_dcp_lse, ) from sglang.srt.model_executor.forward_batch_info import ForwardMode from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase register_cpu_ci(est_time=1, suite="base-a-test-cpu") -class TestDSATRTLLMFP8CP(unittest.TestCase): +class TestDSATRTLLMFP8CP(CustomTestCase): def test_nope_kv_is_not_gathered_again(self): self.assertFalse( _should_all_gather_dsa_trtllm_fp8_kv( @@ -50,13 +51,13 @@ def test_non_cp_and_no_cache_paths_do_not_gather(self): def test_dcp_decode_and_verify_request_lse(self): self.assertTrue( - _should_return_dsa_trtllm_lse( + _should_return_dsa_dcp_lse( forward_mode=ForwardMode.DECODE, dcp_enabled=True, ) ) self.assertTrue( - _should_return_dsa_trtllm_lse( + _should_return_dsa_dcp_lse( forward_mode=ForwardMode.TARGET_VERIFY, dcp_enabled=True, ) @@ -64,13 +65,13 @@ def test_dcp_decode_and_verify_request_lse(self): def test_non_dcp_and_prefill_do_not_request_lse(self): self.assertFalse( - _should_return_dsa_trtllm_lse( + _should_return_dsa_dcp_lse( forward_mode=ForwardMode.DECODE, dcp_enabled=False, ) ) self.assertFalse( - _should_return_dsa_trtllm_lse( + _should_return_dsa_dcp_lse( forward_mode=ForwardMode.EXTEND, dcp_enabled=True, ) diff --git a/test/registered/kernels/ops/attention/test_kda_helion.py b/test/registered/kernels/ops/attention/test_kda_helion.py index 36a8f34b35748..f4f0c558a09b4 100644 --- a/test/registered/kernels/ops/attention/test_kda_helion.py +++ b/test/registered/kernels/ops/attention/test_kda_helion.py @@ -706,6 +706,7 @@ def _compare_prefill( A_log: torch.Tensor | None = None, dt_bias: torch.Tensor | None = None, lower_bound: float | None = None, + beta_is_raw: bool = False, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: batch, tokens, heads, key_dim = q.shape value_dim = v.size(-1) @@ -740,7 +741,8 @@ def _compare_prefill( k_rows = reference_k.view(batch * tokens, heads, key_dim) v_rows = v.view(batch * tokens, heads, value_dim).float() gate_rows = reference_gate.view(batch * tokens, heads, key_dim) - beta_rows = beta.view(batch * tokens, heads).float() + reference_beta = beta.float().sigmoid() if beta_is_raw else beta + beta_rows = reference_beta.view(batch * tokens, heads).float() out_rows = reference_out.view(batch * tokens, heads, value_dim) if cu_seqlens is None: @@ -811,6 +813,7 @@ def _compare_prefill( A_log=A_log, dt_bias=dt_bias, lower_bound=lower_bound, + beta_is_raw=beta_is_raw, ) assert helion_out.data_ptr() == helion_v.data_ptr() @@ -852,6 +855,42 @@ def test_fixed_partial_prefill_and_state_pool_contract() -> None: assert torch.equal(helion_state[untouched], state[untouched]) +def test_raw_beta_prefill_contract() -> None: + torch.manual_seed(811) + batch, tokens, heads, key_dim, value_dim = 2, 17, 2, 32, 32 + q = torch.randn(batch, tokens, heads, key_dim, device="cuda", dtype=torch.bfloat16) + # Keep the unnormalized recurrence numerically contractive while still + # exercising the no-QK-L2-normalization path. Unit-scale random keys make + # (I - beta * k k^T) expansive and obscure the raw-beta contract with + # exponentially amplified BF16 round-off. + k = torch.randn_like(q) * 0.05 + v = torch.randn( + batch, tokens, heads, value_dim, device="cuda", dtype=torch.bfloat16 + ) + # Keep the recurrent decay contractive so the raw-beta check measures the + # sigmoid conversion instead of amplifying BF16 round-off exponentially. + gate = -torch.rand_like(q) * 0.2 + raw_beta = torch.linspace( + -2, + 2, + steps=batch * tokens * heads, + device="cuda", + ).reshape(batch, tokens, heads) + indices = torch.tensor([3, 1], device="cuda", dtype=torch.int32) + state = torch.randn(5, heads, value_dim, key_dim, device="cuda") * 0.01 + + _compare_prefill( + q, + k, + v, + gate, + raw_beta, + state, + indices, + beta_is_raw=True, + ) + + @pytest.mark.parametrize("is_varlen", [False, True], ids=["fixed", "varlen"]) def test_single_token_prefill_does_not_poison_later_shapes( is_varlen: bool, diff --git a/test/registered/unit/spec/test_adaptive_spec_params.py b/test/registered/unit/spec/test_adaptive_spec_params.py index 6cb71f1fbf7ba..f9bcf80e8886b 100644 --- a/test/registered/unit/spec/test_adaptive_spec_params.py +++ b/test/registered/unit/spec/test_adaptive_spec_params.py @@ -8,12 +8,13 @@ resolve_candidate_steps_from_config, ) from sglang.test.ci.ci_register import register_cpu_ci, register_xpu_ci +from sglang.test.test_utils import CustomTestCase register_cpu_ci(est_time=6, suite="base-a-test-cpu") register_xpu_ci(est_time=10, suite="stage-a-test-1-gpu-xpu") -class TestAdaptiveStepSlot(unittest.TestCase): +class TestAdaptiveStepSlot(CustomTestCase): def _make_params_from_config(self, initial_steps: int, config: dict): return AdaptiveStepSlot(initial_steps=initial_steps, cfg=config) @@ -244,11 +245,11 @@ def test_ceiling_disabled_by_default(self): self.assertEqual(params.ceiling_coeff, 0) -class TestAdaptiveSpeculativeParams(unittest.TestCase): +class TestAdaptiveSpeculativeParams(CustomTestCase): def test_default_config_loads(self): params = AdaptiveSpeculativeParams(initial_steps=3) self.assertEqual(params._bs_list, [1, 8, 32, 64]) - self.assertEqual(params._slots[1].candidate_steps, [1, 3, 7]) + self.assertEqual(params._slots[1].candidate_steps, [1, 3, 5, 7]) self.assertEqual(params._slots[8].candidate_steps, [0, 1, 3]) self.assertEqual(params._slots[32].candidate_steps, [0, 1]) self.assertEqual(params._slots[64].candidate_steps, [0]) @@ -339,18 +340,18 @@ def test_entry_hysteresis_overrides_global(self): self.assertEqual(params._slots[1].up_hysteresis, 0.1) -class TestBatchSizeRouting(unittest.TestCase): +class TestBatchSizeRouting(CustomTestCase): """BS-aware routing: batch size selects the slot, CUDA-graph BS pads first.""" def _params(self): - # Slots: bs=1 -> [1,3,7], bs=8 -> [1,3], bs=32 -> [1]. + # Slots: bs=1 -> [1,3,5,7], bs=8 -> [0,1,3], bs=32 -> [0,1]. return AdaptiveSpeculativeParams(initial_steps=3) def test_routes_to_floor_slot_without_cuda_graph(self): params = self._params() # A batch maps to the largest slot BS <= batch (floor), capped at the top slot. - self.assertEqual(params._route(1).candidate_steps, [1, 3, 7]) - self.assertEqual(params._route(7).candidate_steps, [1, 3, 7]) + self.assertEqual(params._route(1).candidate_steps, [1, 3, 5, 7]) + self.assertEqual(params._route(7).candidate_steps, [1, 3, 5, 7]) self.assertEqual(params._route(8).candidate_steps, [0, 1, 3]) self.assertEqual(params._route(31).candidate_steps, [0, 1, 3]) self.assertEqual(params._route(32).candidate_steps, [0, 1]) @@ -373,6 +374,8 @@ def test_cuda_graph_bs_for_step_prunes_unreachable_graphs(self): self.assertEqual(params.cuda_graph_bs_for_step(1), [4, 8, 16, 32]) # step=3 lives in the bs=1 and bs=8 slots: graphs 4,8,16 floor into them. self.assertEqual(params.cuda_graph_bs_for_step(3), [4, 8, 16]) + # step=5 lives only in the bs=1 slot: only graph BS 4 floors into it. + self.assertEqual(params.cuda_graph_bs_for_step(5), [4]) # step=7 lives only in the bs=1 slot: only graph BS 4 floors into it. self.assertEqual(params.cuda_graph_bs_for_step(7), [4]) @@ -392,12 +395,10 @@ def test_observe_verify_feeds_the_routed_slot(self): self.assertEqual(params.get_steps_for_batch(32), 1) -class TestResolveCandidateSteps(unittest.TestCase): +class TestResolveCandidateSteps(CustomTestCase): def test_default_config(self): steps = resolve_candidate_steps_from_config() - self.assertIn(1, steps) - self.assertIn(3, steps) - self.assertIn(7, steps) + self.assertEqual(steps, [0, 1, 3, 5, 7]) def test_config_file(self): with tempfile.NamedTemporaryFile("w", suffix=".json") as f: From 4033e798549c64b01efff0432aac1b8b8f5115e3 Mon Sep 17 00:00:00 2001 From: Baizhou Zhang Date: Mon, 31 Aug 2026 22:34:04 -0700 Subject: [PATCH 19/44] fix: resolve CI regressions after GLM-5.3 Flash rebase (#37298) --- python/sglang/srt/configs/model_config.py | 2 +- .../srt/layers/attention/triton_backend.py | 4 ++ .../sglang/srt/speculative/eagle_worker_v2.py | 2 +- .../test_trtllm_mha_graph_metadata.py | 1 + .../test_flashinfer_mla_chunk_metadata.py | 4 +- .../registered/kernels/test_lean_attention.py | 24 ++++---- .../models_e2e/test_glm53_flash_b200.py | 10 +++- .../mlx/test_attention_patching.py | 1 + .../test_mla_decode_forced_splits.py | 14 ++--- .../unit/managers/test_hisparse_unit.py | 3 +- .../test_scheduler_chunked_abort_race.py | 3 +- .../test_eagle_worker_v2_topk1_fastpath.py | 60 +++++++++++++++++++ 12 files changed, 99 insertions(+), 29 deletions(-) diff --git a/python/sglang/srt/configs/model_config.py b/python/sglang/srt/configs/model_config.py index 7c2706cb3c54a..6532b22ec2718 100644 --- a/python/sglang/srt/configs/model_config.py +++ b/python/sglang/srt/configs/model_config.py @@ -293,7 +293,7 @@ def get_dsa_mtp_topk_width(config: PretrainedConfig) -> int: """MTP seeds include index_topk pooled tokens plus up to index_kpool - 1 tail tokens.""" index_kpool = get_dsa_index_kpool(config) assert index_kpool >= 1, f"index_kpool must be positive, got {index_kpool}" - return get_dsa_index_topk(config) + index_kpool - 1 + return config.index_topk + index_kpool - 1 def get_dsa_index_kpool_compress(config: PretrainedConfig) -> bool: diff --git a/python/sglang/srt/layers/attention/triton_backend.py b/python/sglang/srt/layers/attention/triton_backend.py index b9eb036c5126b..04694b80ce168 100644 --- a/python/sglang/srt/layers/attention/triton_backend.py +++ b/python/sglang/srt/layers/attention/triton_backend.py @@ -671,6 +671,10 @@ def init_forward_metadata_out_graph( window_num_kv_splits=None, window_kv_offsets=None, swa_attn_logits=self.cuda_graph_swa_attn_logits, + lean_Mp=self.cuda_graph_lean_Mp, + lean_Lp=self.cuda_graph_lean_Lp, + lean_Op=self.cuda_graph_lean_Op, + lean_locks=self.cuda_graph_lean_locks, ) return diff --git a/python/sglang/srt/speculative/eagle_worker_v2.py b/python/sglang/srt/speculative/eagle_worker_v2.py index 642f8f230ea91..48fae9d9e1eee 100644 --- a/python/sglang/srt/speculative/eagle_worker_v2.py +++ b/python/sglang/srt/speculative/eagle_worker_v2.py @@ -268,7 +268,7 @@ def _init_dsa_index_share_state(self) -> None: self.dsa_index_topk = getattr(hf_config, "index_topk", None) self.dsa_seed_topk_width = ( get_dsa_mtp_topk_width(hf_config) - if self.dsa_index_topk is not None + if self.index_share_for_mtp_iteration and self.dsa_index_topk is not None else None ) self.seed_dsa_topk_from_draft_extend = ( diff --git a/test/registered/attention/test_trtllm_mha_graph_metadata.py b/test/registered/attention/test_trtllm_mha_graph_metadata.py index 6d46cbe1725cf..ce9c2e3c40532 100644 --- a/test/registered/attention/test_trtllm_mha_graph_metadata.py +++ b/test/registered/attention/test_trtllm_mha_graph_metadata.py @@ -151,6 +151,7 @@ def make_fake(name, calls): token_to_kv_pool=None, req_to_token_pool=None, needs_cpu_seq_lens=False, + supports_overlap_plan_stream_graph_load=False, init_forward_metadata_in_graph=lambda fb: calls.append(name), ) diff --git a/test/registered/attention/unittests/hybrid_linear/test_flashinfer_mla_chunk_metadata.py b/test/registered/attention/unittests/hybrid_linear/test_flashinfer_mla_chunk_metadata.py index 81abb6133963f..50f6705b2fdd5 100644 --- a/test/registered/attention/unittests/hybrid_linear/test_flashinfer_mla_chunk_metadata.py +++ b/test/registered/attention/unittests/hybrid_linear/test_flashinfer_mla_chunk_metadata.py @@ -103,7 +103,9 @@ def _build_hybrid_backend(testcase, case: MLAAttentionCase): # full_attn_layers=[0] routes layer 0 through the MLA backend, as a hybrid # model's full-attention layers do. The linear backend is unused here. hybrid = HybridLinearAttnBackend( - full_backend, SimpleNamespace(), full_attn_layers=[0] + full_backend, + SimpleNamespace(supports_overlap_plan_stream_graph_load=False), + full_attn_layers=[0], ) return runner, full_backend, hybrid diff --git a/test/registered/kernels/test_lean_attention.py b/test/registered/kernels/test_lean_attention.py index 73e5124d414fc..a0c7bd679a32b 100644 --- a/test/registered/kernels/test_lean_attention.py +++ b/test/registered/kernels/test_lean_attention.py @@ -197,12 +197,12 @@ def _call(enable_lean): def _run_pair_paged( H_Q, H_KV, D, B, S, page_size, dev="cuda", dt=torch.float16, seed=0 ): - """Standard vs Lean on a **paged** 4-D KV buffer ``[num_pages, page_size, head, dim]``. + """Standard vs Lean with page-aware addressing over a dense 3-D KV buffer. - The KV cache is stored in pages and addressed through scattered slot ids in ``kv_indices`` - (a permutation), so the kernel's page-aware address math (``kv_loc // page_size`` / - ``kv_loc % page_size``) is genuinely exercised — not the contiguous fast path. Both arms read - the identical buffer + indices, so their outputs must agree. Returns (o_std, o_lean). + The dense ``[max_slots, head, dim]`` cache is addressed through scattered slot ids in + ``kv_indices`` (a permutation). With ``page_size > 1``, the kernel still exercises its + page-aware address math (``kv_loc // page_size`` / ``kv_loc % page_size``). Both arms read the + identical buffer + indices, so their outputs must agree. Returns (o_std, o_lean). """ torch.manual_seed(seed) D_V = D @@ -212,11 +212,9 @@ def _run_pair_paged( assert ( tot % page_size == 0 ), "test setup: total tokens must be a multiple of page_size" - num_pages = tot // page_size - - # 4-D paged KV buffers [num_pages, page_size, head, dim] (the shared-pool layout). - k = torch.randn(num_pages, page_size, H_KV, D, dtype=dt, device=dev) - v = torch.randn(num_pages, page_size, H_KV, D_V, dtype=dt, device=dev) + # Unified memory exposes dense 3-D KV views even when the allocator uses pages. + k = torch.randn(tot, H_KV, D, dtype=dt, device=dev) + v = torch.randn(tot, H_KV, D_V, dtype=dt, device=dev) kv_indptr = torch.arange(0, (B + 1) * S, step=S, device=dev, dtype=torch.int32) # Scatter slots across pages so page_id/tok_in_p vary within every BLOCK_N tile. @@ -312,9 +310,9 @@ def test_fp8_kv_parity(self): ) def test_paged_kv_parity(self): - # Lean must read a paged 4-D KV buffer the same way the standard kernel does. Guards - # the page-aware address math (kv_loc // page_size, kv_loc % page_size); a regression - # to the contiguous-only form would scramble reads and drop cos well below 1. + # Lean must apply page-aware address math to dense KV views the same way the standard + # kernel does. A regression in kv_loc // page_size or kv_loc % page_size would scramble + # the scattered reads and drop cos well below 1. for name, H_Q, H_KV, D in GQA_SHAPES: for page_size in (16, 64): with self.subTest(model=name, page_size=page_size): diff --git a/test/registered/models_e2e/test_glm53_flash_b200.py b/test/registered/models_e2e/test_glm53_flash_b200.py index a9ea7aef3785c..00a0813d59c64 100644 --- a/test/registered/models_e2e/test_glm53_flash_b200.py +++ b/test/registered/models_e2e/test_glm53_flash_b200.py @@ -53,7 +53,6 @@ def _stop_server(process): class _GLM53FlashB200Base(CustomTestCase): server_args: list[str] - gsm8k_score_threshold = 0.93 @classmethod def setUpClass(cls): @@ -77,6 +76,12 @@ class TestGLM53FlashB200LowLatency( GSM8KMixin, _GLM53FlashB200Base, ): + gsm8k_score_threshold = 0.93 + # Match the established DSA+MTP accuracy workload. The generic 200-question, + # 5-shot defaults leave a single question worth 0.5 percentage points and + # make this tight quality floor unnecessarily sensitive to kernel numerics. + gsm8k_num_examples = 500 + gsm8k_num_shots = 20 accept_length_thres = 4.0 bs_1_speed_thres = 300 server_args = [ @@ -97,6 +102,9 @@ class TestGLM53FlashB200HighThroughput( GSM8KMixin, _GLM53FlashB200Base, ): + gsm8k_score_threshold = 0.93 + gsm8k_num_examples = 500 + gsm8k_num_shots = 20 server_args = [ *COMMON_SERVER_ARGS, "--enable-dp-attention", diff --git a/test/registered/unit/hardware_backend/mlx/test_attention_patching.py b/test/registered/unit/hardware_backend/mlx/test_attention_patching.py index 2eb416e52d6bf..6e518b9b3ad8b 100644 --- a/test/registered/unit/hardware_backend/mlx/test_attention_patching.py +++ b/test/registered/unit/hardware_backend/mlx/test_attention_patching.py @@ -1521,6 +1521,7 @@ class FakeRequest: def __init__(self): self.kv = ReqKvInfo() self.inflight_middle_chunks = 0 + self.mamba_branching_seqlen = None class FakeTpWorker: def __init__(self, next_token_ids): diff --git a/test/registered/unit/layers/attention/test_mla_decode_forced_splits.py b/test/registered/unit/layers/attention/test_mla_decode_forced_splits.py index b7d1c7c01cd00..49825f7041f98 100644 --- a/test/registered/unit/layers/attention/test_mla_decode_forced_splits.py +++ b/test/registered/unit/layers/attention/test_mla_decode_forced_splits.py @@ -74,16 +74,10 @@ def _inputs(seq_lens, head_num, page_size, max_kv_splits, seed): total = sum(seq_lens) n_slots = total + 64 - if page_size == 1: - pool = torch.randn( - n_slots, 1, LK, dtype=torch.bfloat16, device=dev, generator=gen - ) - else: - n_pages = (n_slots + page_size - 1) // page_size - pool = torch.randn( - n_pages, page_size, 1, LK, dtype=torch.bfloat16, device=dev, generator=gen - ) - n_slots = n_pages * page_size + if page_size > 1: + n_slots = ((n_slots + page_size - 1) // page_size) * page_size + # Unified memory exposes dense 3-D KV views even when the allocator uses pages. + pool = torch.randn(n_slots, 1, LK, dtype=torch.bfloat16, device=dev, generator=gen) kv_indptr = torch.zeros(batch + 1, dtype=torch.int32, device=dev) kv_indptr[1:] = torch.cumsum( diff --git a/test/registered/unit/managers/test_hisparse_unit.py b/test/registered/unit/managers/test_hisparse_unit.py index c2b5bdf99e4d6..e716f4057127f 100644 --- a/test/registered/unit/managers/test_hisparse_unit.py +++ b/test/registered/unit/managers/test_hisparse_unit.py @@ -14,6 +14,7 @@ import torch +from sglang.srt.managers.schedule_batch import ReqKvInfo from sglang.srt.utils import is_cuda, is_hip, is_npu, is_xpu from sglang.srt.utils.common import Range from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci @@ -49,7 +50,7 @@ def _make_req(rid="test-req-0", origin_input_ids=None, output_ids=None): output_ids=output_ids, fill_ids=origin_input_ids + output_ids, seqlen=len(origin_input_ids) + len(output_ids), - kv=SimpleNamespace(req_pool_idx=None, kv_allocated_len=0, kv_committed_len=0), + kv=ReqKvInfo(), finished_reason=None, hisparse_staging=False, staging=False, diff --git a/test/registered/unit/managers/test_scheduler_chunked_abort_race.py b/test/registered/unit/managers/test_scheduler_chunked_abort_race.py index 084b6db176f75..ff243db63f767 100644 --- a/test/registered/unit/managers/test_scheduler_chunked_abort_race.py +++ b/test/registered/unit/managers/test_scheduler_chunked_abort_race.py @@ -9,6 +9,7 @@ maybe_stub_sgl_kernel() +from sglang.srt.managers.schedule_batch import ReqKvInfo # noqa: E402 from sglang.srt.managers.scheduler import Scheduler # noqa: E402 register_cpu_ci(est_time=10, suite="base-a-test-cpu") @@ -19,7 +20,7 @@ class _FakeReq: def __init__(self, rid: str): self.rid = rid - self.kv = SimpleNamespace(req_pool_idx=1) + self.kv = ReqKvInfo(req_pool_idx=1) self.to_finish = None self._finished = False diff --git a/test/registered/unit/spec/test_eagle_worker_v2_topk1_fastpath.py b/test/registered/unit/spec/test_eagle_worker_v2_topk1_fastpath.py index db5109c6412af..8a728eeceeede 100644 --- a/test/registered/unit/spec/test_eagle_worker_v2_topk1_fastpath.py +++ b/test/registered/unit/spec/test_eagle_worker_v2_topk1_fastpath.py @@ -135,6 +135,66 @@ def test_assert_on_inconsistent_steps_and_draft_tokens(self): with self.assertRaises(AssertionError): worker._rebuild_topk1_chain_buffers() + def test_non_index_share_model_does_not_initialize_dsa_seed(self): + worker = object.__new__(EagleDraftWorker) + worker.topk = 1 + worker.draft_runner = SimpleNamespace( + model_config=SimpleNamespace( + hf_config=SimpleNamespace( + architectures=["DeepseekV4ForCausalLMNextN"], + index_topk=512, + ) + ) + ) + + worker._init_dsa_index_share_state() + + self.assertFalse(worker.index_share_for_mtp_iteration) + self.assertEqual(worker.dsa_index_topk, 512) + self.assertIsNone(worker.dsa_seed_topk_width) + self.assertFalse(worker.seed_dsa_topk_from_draft_extend) + + def test_index_share_model_initializes_pooled_dsa_seed_width(self): + worker = object.__new__(EagleDraftWorker) + worker.topk = 1 + worker.draft_runner = SimpleNamespace( + model_config=SimpleNamespace( + hf_config=SimpleNamespace( + architectures=["GlmMoeDsaForCausalLMNextN"], + index_topk=2048, + index_kpool=4, + index_share_for_mtp_iteration=True, + ) + ) + ) + + worker._init_dsa_index_share_state() + + self.assertTrue(worker.index_share_for_mtp_iteration) + self.assertEqual(worker.dsa_index_topk, 2048) + self.assertEqual(worker.dsa_seed_topk_width, 2051) + self.assertTrue(worker.seed_dsa_topk_from_draft_extend) + + def test_non_dsa_index_share_model_initializes_unpooled_seed_width(self): + worker = object.__new__(EagleDraftWorker) + worker.topk = 1 + worker.draft_runner = SimpleNamespace( + model_config=SimpleNamespace( + hf_config=SimpleNamespace( + architectures=["DeepseekV4ForCausalLMNextN"], + index_topk=2048, + index_share_for_mtp_iteration=True, + ) + ) + ) + + worker._init_dsa_index_share_state() + + self.assertTrue(worker.index_share_for_mtp_iteration) + self.assertEqual(worker.dsa_index_topk, 2048) + self.assertEqual(worker.dsa_seed_topk_width, 2048) + self.assertTrue(worker.seed_dsa_topk_from_draft_extend) + def test_idle_draft_runs_each_eager_forward_without_tree_layout(self): worker = object.__new__(EagleDraftWorker) worker.speculative_num_steps = 3 From c767511ea832829129ba5255ced67b9ce1a9bc2b Mon Sep 17 00:00:00 2001 From: Baizhou Zhang Date: Tue, 1 Sep 2026 01:13:55 -0700 Subject: [PATCH 20/44] Revert "[AMD] Enable GLM-5.3-Flash on gfx942 and gfx950 (#36607)" This reverts commit aa8c950a3df62b6642c4ea60a93a5e3eb1a1450e. --- .../jit/csrc/dsa/kpool_topk_transform.cuh | 8 - .../ops/attention/dsa/tilelang_kernel.py | 70 ++--- .../ops/attention/dsa/transform_index.py | 75 +---- python/sglang/kernels/ops/layernorm/mhc.py | 145 +--------- .../layers/attention/dsa/dsa_indexer_kpool.py | 87 +----- .../layers/attention/dsa/kpool_fp8_index.py | 195 ++----------- python/sglang/srt/layers/communicator_mhc.py | 30 +- .../moe/moe_runner/triton_utils/fused_moe.py | 10 - python/sglang/srt/layers/quantization/fp8.py | 14 +- .../srt/layers/quantization/quark/quark.py | 89 +----- .../srt/layers/quantization/quark/utils.py | 5 - .../forward_mha_rocm.py | 6 +- python/sglang/srt/models/glm5_next.py | 82 +----- .../ops/attention/test_dsa_transform_index.py | 26 +- .../kernels/test_dsa_kpool_multi_pool.py | 257 +----------------- .../test_fp8_moe_runner_ownership.py | 89 +----- .../layers/quantization/test_quark_config.py | 114 -------- .../layers/quantization/test_quark_utils.py | 16 +- .../layers/test_dsa_indexer_kpool_backend.py | 196 ------------- .../unit/models/test_glm5_next_aiter_mhc.py | 243 ----------------- .../unit/models/test_nope_mha_k_cast.py | 20 +- .../test_shared_experts_fusion_gates.py | 56 ---- 22 files changed, 111 insertions(+), 1722 deletions(-) delete mode 100644 test/registered/unit/layers/test_dsa_indexer_kpool_backend.py delete mode 100644 test/registered/unit/models/test_glm5_next_aiter_mhc.py diff --git a/python/sglang/kernels/jit/csrc/dsa/kpool_topk_transform.cuh b/python/sglang/kernels/jit/csrc/dsa/kpool_topk_transform.cuh index 995a75dab19bb..e2dffd907c36b 100644 --- a/python/sglang/kernels/jit/csrc/dsa/kpool_topk_transform.cuh +++ b/python/sglang/kernels/jit/csrc/dsa/kpool_topk_transform.cuh @@ -11,11 +11,7 @@ #include #include #include -#if defined(__HIP_PLATFORM_AMD__) -#include -#else #include -#endif namespace sglang { namespace { @@ -294,11 +290,7 @@ void setup_kernel_smem_once(host::DebugInfo where = {}) { [[maybe_unused]] static const auto result = [] { const auto fptr = std::bit_cast(f); -#if defined(__HIP_PLATFORM_AMD__) - return ::hipFuncSetAttribute(fptr, ::hipFuncAttributeMaxDynamicSharedMemorySize, kMaxDynamicSMEM); -#else return ::cudaFuncSetAttribute(fptr, ::cudaFuncAttributeMaxDynamicSharedMemorySize, kMaxDynamicSMEM); -#endif }(); host::RuntimeDeviceCheck(result, where); } diff --git a/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py b/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py index a49852cb0219b..2c1eff2e2e3c9 100644 --- a/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py +++ b/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py @@ -895,16 +895,13 @@ def main( with T.Kernel(seq_len * REPLICATE_H, N_GROUPS, threads=threads) as (bx, by): if _q_in_shared: Q_buf = T.alloc_shared([H_per_block, D], dtype) - if D_tail > 0: - Q_tail_buf = T.alloc_shared([H_per_block, D_tail], dtype) + Q_tail_buf = T.alloc_shared([H_per_block, D_tail], dtype) else: Q_buf = T.alloc_fragment([H_per_block, D], dtype) - if D_tail > 0: - Q_tail_buf = T.alloc_fragment([H_per_block, D_tail], dtype) + Q_tail_buf = T.alloc_fragment([H_per_block, D_tail], dtype) KV_shared = T.alloc_shared([BI, D], dtype) - if D_tail > 0: - K_tail_shared = T.alloc_shared([BI, D_tail], dtype) + K_tail_shared = T.alloc_shared([BI, D_tail], dtype) S_shared = T.alloc_shared([H_per_block, BI], dtype) mask = T.alloc_fragment([BI], T.bool) @@ -927,8 +924,7 @@ def main( H1 = H0 + H_per_block T.copy(Q[b_i, s_i, H0:H1, :D], Q_buf) - if D_tail > 0: - T.copy(Q[b_i, s_i, H0:H1, D:], Q_tail_buf) + T.copy(Q[b_i, s_i, H0:H1, D:], Q_tail_buf) for k_i in T.Pipelined(inner_iter, num_stages=num_stages): topk_block_i = group_i * inner_iter + k_i @@ -940,12 +936,11 @@ def main( KV_shared[bi_i, d_i] = KV[ b_i, T.if_then_else(idx >= 0, idx, 0), g_i, d_i ] - if D_tail > 0: - for bi_i, d_i in T.Parallel(BI, D_tail): - idx = Indices[b_i, s_i, g_i, topk_block_i * BI + bi_i] - K_tail_shared[bi_i, d_i] = KV[ - b_i, T.if_then_else(idx >= 0, idx, 0), g_i, D + d_i - ] + for bi_i, d_i in T.Parallel(BI, D_tail): + idx = Indices[b_i, s_i, g_i, topk_block_i * BI + bi_i] + K_tail_shared[bi_i, d_i] = KV[ + b_i, T.if_then_else(idx >= 0, idx, 0), g_i, D + d_i + ] for h_i, bi_i in T.Parallel(H_per_block, BI): acc_s[h_i, bi_i] = T.if_then_else( @@ -959,14 +954,13 @@ def main( transpose_B=True, policy=T.GemmWarpPolicy.FullCol, ) - if D_tail > 0: - T.gemm( - Q_tail_buf, - K_tail_shared, - acc_s, - transpose_B=True, - policy=T.GemmWarpPolicy.FullCol, - ) + T.gemm( + Q_tail_buf, + K_tail_shared, + acc_s, + transpose_B=True, + policy=T.GemmWarpPolicy.FullCol, + ) T.copy(m_i, m_i_prev) T.reduce_max(acc_s, m_i, dim=1, clear=False) @@ -1177,9 +1171,8 @@ def main( kv_tile1 = T.alloc_shared([BI, group_size], fp8_dtype) kv_tile2 = T.alloc_shared([BI, group_size], fp8_dtype) kv_tile3 = T.alloc_shared([BI, group_size], fp8_dtype) - if d_tail > 0: - q_tail_buf = T.alloc_shared([h_per_block, d_tail], fp8_dtype) - k_tail_shared = T.alloc_shared([BI, d_tail], fp8_dtype) + q_tail_buf = T.alloc_shared([h_per_block, d_tail], fp8_dtype) + k_tail_shared = T.alloc_shared([BI, d_tail], fp8_dtype) s_fp8_shared = T.alloc_shared([h_per_block, BI], fp8_dtype) page_idx_shared = T.alloc_shared([BI], T.int32) @@ -1206,8 +1199,7 @@ def main( T.fill(sumexp, 0) T.fill(m_i, -(2**30)) - if d_tail > 0: - T.copy(q_fp8[b_i, s_i, H0:H1, d_v:], q_tail_buf) + T.copy(q_fp8[b_i, s_i, H0:H1, d_v:], q_tail_buf) T.copy(q_fp8[b_i, s_i, H0:H1, 0 * group_size : 1 * group_size], q_tile0) T.copy(q_fp8[b_i, s_i, H0:H1, 1 * group_size : 2 * group_size], q_tile1) T.copy(q_fp8[b_i, s_i, H0:H1, 2 * group_size : 3 * group_size], q_tile2) @@ -1229,12 +1221,9 @@ def main( kv_tile2[bi_i, j] = kv_fp8[b_i, page, g_i, 2 * group_size + j] kv_tile3[bi_i, j] = kv_fp8[b_i, page, g_i, 3 * group_size + j] - if d_tail > 0: - for bi_i, j in T.Parallel(BI, d_tail): - page = page_idx_shared[bi_i] - k_tail_shared[bi_i, j] = kv_fp8[ - b_i, page, g_i, rope_offset_fp8 + j - ] + for bi_i, j in T.Parallel(BI, d_tail): + page = page_idx_shared[bi_i] + k_tail_shared[bi_i, j] = kv_fp8[b_i, page, g_i, rope_offset_fp8 + j] for h_i, bi_i in T.Parallel(h_per_block, BI): acc_s[h_i, bi_i] = T.if_then_else( @@ -1251,14 +1240,13 @@ def main( T.gemm(q_tile3, kv_tile3, acc_tile, transpose_B=True, clear_accum=True) for h_i, bi_i in T.Parallel(h_per_block, BI): acc_s[h_i, bi_i] += acc_tile[h_i, bi_i] - if d_tail > 0: - T.gemm( - q_tail_buf, - k_tail_shared, - acc_s, - transpose_B=True, - policy=T.GemmWarpPolicy.FullCol, - ) + T.gemm( + q_tail_buf, + k_tail_shared, + acc_s, + transpose_B=True, + policy=T.GemmWarpPolicy.FullCol, + ) T.copy(m_i, m_i_prev) T.reduce_max(acc_s, m_i, dim=1, clear=False) diff --git a/python/sglang/kernels/ops/attention/dsa/transform_index.py b/python/sglang/kernels/ops/attention/dsa/transform_index.py index d9c1226d023f0..8fbfa190f5b97 100644 --- a/python/sglang/kernels/ops/attention/dsa/transform_index.py +++ b/python/sglang/kernels/ops/attention/dsa/transform_index.py @@ -116,43 +116,6 @@ def transform_index_page_table_decode_kernel( tl.store(result_ptr + offset, -1, mask=~mask) -@triton.jit -def transform_index_page_table_decode_tiled_kernel( - page_table_ptr: torch.Tensor, - topk_indices_ptr: torch.Tensor, - result_ptr: torch.Tensor, - page_table_row_stride: tl.constexpr, - topk_indices_stride_0: tl.constexpr, - topk_indices_stride_1: tl.constexpr, - result_stride_0: tl.constexpr, - result_stride_1: tl.constexpr, - TOPK: tl.constexpr, - BLOCK_TOPK: tl.constexpr, -): - req_id = tl.program_id(0) - topk_offsets = tl.program_id(1) * BLOCK_TOPK + tl.arange(0, BLOCK_TOPK) - mask = topk_offsets < TOPK - - loaded_topk_indices = tl.load( - topk_indices_ptr - + req_id * topk_indices_stride_0 - + topk_offsets * topk_indices_stride_1, - mask=mask, - other=-1, - ) - valid_topk_mask = mask & (loaded_topk_indices >= 0) - loaded_kv_indices = tl.load( - page_table_ptr + req_id * page_table_row_stride + loaded_topk_indices, - mask=valid_topk_mask, - other=-1, - ) - tl.store( - result_ptr + req_id * result_stride_0 + topk_offsets * result_stride_1, - loaded_kv_indices, - mask=mask, - ) - - @triton.jit def transform_index_page_table_prefill_kernel( page_table_ptr: torch.Tensor, @@ -228,36 +191,19 @@ def transform_index_page_table_decode_fast( """ assert page_size == 1 assert page_table.shape[0] == topk_indices.shape[0] + assert topk_indices.shape[1] == 2048 qo_len = topk_indices.shape[0] if result is None: result = torch.empty_like(topk_indices, dtype=torch.int32) - topk = topk_indices.shape[1] - if topk == 2048: - # Keep the 2048-wide fast path; KPool tail widths use the tiled kernel. - transform_index_page_table_decode_kernel[(qo_len,)]( - page_table, - topk_indices, - result, - page_size, - page_table_row_stride=page_table.stride(0), - ) - else: - block_topk = 256 - transform_index_page_table_decode_tiled_kernel[ - (qo_len, triton.cdiv(topk, block_topk)) - ]( - page_table, - topk_indices, - result, - page_table.stride(0), - topk_indices.stride(0), - topk_indices.stride(1), - result.stride(0), - result.stride(1), - TOPK=topk, - BLOCK_TOPK=block_topk, - num_warps=4, - ) + # Launch triton kernel + grid = (qo_len,) + transform_index_page_table_decode_kernel[grid]( + page_table, + topk_indices, + result, + page_size, + page_table_row_stride=page_table.stride(0), + ) return result @@ -271,6 +217,7 @@ def transform_index_page_table_prefill_fast( cu_seqlens_q: Optional[torch.Tensor] = None, ) -> torch.Tensor: assert page_size == 1 + assert topk_indices.shape[1] == 2048 real_num_tokens = sum(extend_lens_cpu) result = _allocate_prefill_result(topk_indices, real_num_tokens, output_num_tokens) if real_num_tokens == 0: diff --git a/python/sglang/kernels/ops/layernorm/mhc.py b/python/sglang/kernels/ops/layernorm/mhc.py index eccf38b51b318..9868a8da79293 100644 --- a/python/sglang/kernels/ops/layernorm/mhc.py +++ b/python/sglang/kernels/ops/layernorm/mhc.py @@ -18,99 +18,10 @@ from sglang.srt.layers.attention.dsa.utils import is_dsa_prefill_cp_round_robin_split from sglang.srt.layers.dp_attention import is_allocation_symmetric from sglang.srt.layers.utils.common import strict_contiguous -from sglang.srt.utils import is_gfx95_supported, is_hip -from sglang.srt.utils.common import get_bool_env_var, is_gfx1250_supported +from sglang.srt.utils.common import is_gfx1250_supported logger = logging.getLogger(__name__) -_AITER_MHC_RUNTIME_DISABLED = False -_AITER_MHC_IMPORT_WARNED = False -_AITER_MHC_ACTIVE_LOGGED = False - - -def _use_aiter_mhc() -> bool: - return ( - not _AITER_MHC_RUNTIME_DISABLED - and is_hip() - and is_gfx95_supported() - and get_bool_env_var("SGLANG_USE_AITER") - ) - - -def _try_aiter_mhc_pre( - residual: torch.Tensor, - fn: torch.Tensor, - hc_scale: torch.Tensor, - hc_base: torch.Tensor, - rms_eps: float, - hc_pre_eps: float, - hc_sinkhorn_eps: float, - hc_post_mult_value: float, - sinkhorn_repeat: int, - norm_weight: torch.Tensor | None, - norm_eps: float | None, -) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor] | None: - global _AITER_MHC_RUNTIME_DISABLED, _AITER_MHC_IMPORT_WARNED - global _AITER_MHC_ACTIVE_LOGGED - - try: - from aiter.ops.mhc import mhc_pre as aiter_mhc_pre - except Exception as err: - if not _AITER_MHC_IMPORT_WARNED: - logger.warning("AITER mHC pre is unavailable, falling back: %s", err) - _AITER_MHC_IMPORT_WARNED = True - _AITER_MHC_RUNTIME_DISABLED = True - return None - - kwargs = {} - if norm_weight is not None: - kwargs["norm_weight"] = norm_weight - kwargs["norm_eps"] = norm_eps if norm_eps is not None else rms_eps - - try: - result = aiter_mhc_pre( - residual, - fn, - hc_scale, - hc_base, - rms_eps, - hc_pre_eps, - hc_sinkhorn_eps, - hc_post_mult_value, - sinkhorn_repeat, - **kwargs, - ) - except Exception as err: - logger.warning("AITER mHC pre failed, disabling fast path: %s", err) - _AITER_MHC_RUNTIME_DISABLED = True - return None - - if not _AITER_MHC_ACTIVE_LOGGED: - logger.info("Using AITER gfx950 mHC pre/post kernels") - _AITER_MHC_ACTIVE_LOGGED = True - return result - - -def _try_aiter_mhc_post( - x: torch.Tensor, - residual: torch.Tensor, - post_layer_mix: torch.Tensor, - comb_res_mix: torch.Tensor, -) -> torch.Tensor | None: - global _AITER_MHC_RUNTIME_DISABLED - - try: - from aiter.ops.mhc import mhc_post as aiter_mhc_post - - out = torch.empty_like(residual) - aiter_mhc_post(out, x, residual, post_layer_mix, comb_res_mix) - return out - except Exception as err: - logger.warning("AITER mHC post failed, disabling fast path: %s", err) - _AITER_MHC_RUNTIME_DISABLED = True - return None - - # This module is imported during model-registry discovery. Do not import the real # TileLang package here: it loads native CUDA stubs. The proxy below lets # module-level @tilelang.jit declarations parse, then imports and applies real @@ -208,24 +119,6 @@ def __getattr__(self, name): tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True, } - -def _use_deep_gemm_hc_prenorm() -> bool: - if not envs.SGLANG_OPT_DEEPGEMM_HC_PRENORM.get(): - return False - - from sglang.srt.layers.deep_gemm_wrapper.configurer import ENABLE_JIT_DEEPGEMM - - return ENABLE_JIT_DEEPGEMM - - -def _use_tilelang_mhc_pre() -> bool: - return envs.SGLANG_OPT_USE_TILELANG_MHC_PRE.get() and not is_hip() - - -def _use_tilelang_mhc_post() -> bool: - return envs.SGLANG_OPT_USE_TILELANG_MHC_POST.get() and not is_hip() - - FP8 = "float8_e4m3" BF16 = "bfloat16" FP32 = "float32" @@ -1113,7 +1006,7 @@ def mhc_pre( num_tokens, hidden_size, dtype=torch.bfloat16, device=residual.device ) - if _use_deep_gemm_hc_prenorm(): + if envs.SGLANG_OPT_DEEPGEMM_HC_PRENORM.get(): n_splits = _compute_num_split_for_mhc_pre(num_tokens, hc_hidden_size) gemm_out_mul = torch.empty( @@ -1725,7 +1618,7 @@ def mhc_fused_post_pre( hidden_size, ) - if _use_deep_gemm_hc_prenorm(): + if envs.SGLANG_OPT_DEEPGEMM_HC_PRENORM.get(): import deep_gemm deep_gemm.tf32_hc_prenorm_gemm( @@ -1917,25 +1810,7 @@ def _mhc_pre_dispatch( norm_eps: float | None = None, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, bool]: assert residual.dim() == 3, f"residual must be (s, n, h); got {residual.shape}" - if _use_aiter_mhc(): - result = _try_aiter_mhc_pre( - residual=residual, - fn=fn, - hc_scale=hc_scale, - hc_base=hc_base, - rms_eps=rms_eps, - hc_pre_eps=hc_pre_eps, - hc_sinkhorn_eps=hc_sinkhorn_eps, - hc_post_mult_value=hc_post_mult_value, - sinkhorn_repeat=sinkhorn_repeat, - norm_weight=norm_weight, - norm_eps=norm_eps, - ) - if result is not None: - post_mix, comb_mix, layer_input = result - return post_mix, comb_mix, layer_input, norm_weight is not None - - if not _use_tilelang_mhc_pre(): + if not envs.SGLANG_OPT_USE_TILELANG_MHC_PRE.get(): post_mix, comb_mix, layer_input = _mhc_pre_torch( residual=residual, fn=fn, @@ -1974,17 +1849,7 @@ def _mhc_post_dispatch( ) -> torch.Tensor: assert x.dim() == 2 and residual.dim() == 3 assert post_layer_mix.dim() == 3 and comb_res_mix.dim() == 3 - if _use_aiter_mhc(): - result = _try_aiter_mhc_post( - x=x, - residual=residual, - post_layer_mix=post_layer_mix, - comb_res_mix=comb_res_mix, - ) - if result is not None: - return result - - if not _use_tilelang_mhc_post(): + if not envs.SGLANG_OPT_USE_TILELANG_MHC_POST.get(): return _mhc_post_torch(x, residual, post_layer_mix, comb_res_mix) return mhc_post(x, residual, post_layer_mix, comb_res_mix) diff --git a/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py b/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py index 8403bbf278ec3..2ee56808deddd 100644 --- a/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py +++ b/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py @@ -30,7 +30,6 @@ from sglang.srt.environ import envs from sglang.srt.layers import deep_gemm_wrapper from sglang.srt.layers.attention.dsa.utils import ( - aiter_can_use_preshuffle_paged_mqa, cp_zigzag_full_plan_rows, dsa_use_prefill_cp, is_dsa_enable_prefill_cp, @@ -167,39 +166,6 @@ def _get_logits_head_gate(self, x: torch.Tensor, q_scale: torch.Tensor): weights = weights.unsqueeze(-1) * q_scale * self.softmax_scale return weights - @staticmethod - def _fp8_mqa_logits( - q_fp8: torch.Tensor, - k_fp8: torch.Tensor, - k_scale: torch.Tensor, - weights: torch.Tensor, - starts: torch.Tensor, - ends: torch.Tensor, - *, - clean_logits: bool, - ) -> torch.Tensor: - if is_hip(): - from aiter.ops.triton.fp8_mqa_logits import fp8_mqa_logits - - return fp8_mqa_logits( - q_fp8, - k_fp8, - k_scale, - weights, - starts, - ends, - clean_logits=clean_logits, - ) - - return deep_gemm.fp8_mqa_logits( - q_fp8, - (k_fp8, k_scale), - weights, - starts, - ends, - clean_logits=clean_logits, - ) - @staticmethod def _cp_gather_concat( tensors: List[torch.Tensor], @@ -866,7 +832,7 @@ def _should_use_tilelang_paged_mqa_logits(q_fp8: torch.Tensor) -> bool: if not is_cuda(): return False arch_major, _ = torch.cuda.get_device_capability(q_fp8.device) - num_heads = q_fp8.shape[1] + num_heads = q_fp8.shape[2] return arch_major == 9 and num_heads not in (32, 64) def _get_topk_paged( @@ -903,6 +869,7 @@ def _get_topk_paged( if n_real < num_q_padded: q_fp8 = q_fp8[:n_real] weights = weights[:n_real] + q_fp8 = q_fp8.unsqueeze(1) # the next_n dim is 1 now assert len(kv_cache_fp8.shape) == 2 block_kv = 64 num_heads_kv = 1 @@ -912,11 +879,7 @@ def _get_topk_paged( ) assert len(weights.shape) == 3 weights = weights.squeeze(2) - use_aiter_paged_mqa = is_hip() - use_tilelang_paged_mqa = ( - not use_aiter_paged_mqa - and self._should_use_tilelang_paged_mqa_logits(q_fp8) - ) + use_tilelang_paged_mqa = self._should_use_tilelang_paged_mqa_logits(q_fp8) pool_seqlens, pool_context_lens, pool_block_tables, pool_schedule_metadata = ( self._get_kpool_decode_metadata( @@ -924,36 +887,17 @@ def _get_topk_paged( block_tables, seqlens_32, blocksize, - build_schedule_metadata=not ( - use_aiter_paged_mqa or use_tilelang_paged_mqa - ), + build_schedule_metadata=not use_tilelang_paged_mqa, ) ) pool_max_seq_len = pool_block_tables.shape[1] * blocksize - if use_aiter_paged_mqa: - if not aiter_can_use_preshuffle_paged_mqa(): - raise RuntimeError( - "ROCm kpool indexer requires the AITER preshuffle paged-MQA kernel" - ) - from sglang.kernels.ops.attention.dsa import aiter_paged_mqa_logits - - logits = aiter_paged_mqa_logits( - q_fp8, - kv_cache_fp8, - weights, - pool_seqlens, - pool_block_tables, - pool_max_seq_len, - preshuffle=True, - kv_block_size=block_kv, - ) - elif use_tilelang_paged_mqa: + if use_tilelang_paged_mqa: from sglang.kernels.ops.attention.dsa.tilelang_kernel import ( tilelang_fp8_paged_mqa_logits, ) logits = tilelang_fp8_paged_mqa_logits( - q_fp8.unsqueeze(1), + q_fp8, kv_cache_fp8, weights, pool_seqlens, @@ -964,7 +908,7 @@ def _get_topk_paged( ) else: logits = deep_gemm.fp8_paged_mqa_logits( - q_fp8.unsqueeze(1), + q_fp8, kv_cache_fp8, weights, pool_context_lens, @@ -1051,10 +995,9 @@ def _get_topk_ragged_kpool_plan( scale_out=k_scale, ) k_fp8 = k_u8.view(torch.float8_e4m3fn) - logits = self._fp8_mqa_logits( + logits = deep_gemm.fp8_mqa_logits( q_fp8[:n_real].contiguous(), - k_fp8.contiguous(), - k_scale.contiguous(), + (k_fp8.contiguous(), k_scale.contiguous()), weights[:n_real].contiguous(), ks_per_q, ke_per_q, @@ -1166,10 +1109,9 @@ def _get_topk_ragged_with_cp( ke = torch.div(tail_tokens, pool_size, rounding_mode="floor").to( torch.int32 ) - logits = self._fp8_mqa_logits( + logits = deep_gemm.fp8_mqa_logits( q_work, - k_fp8.contiguous(), - k_scale.contiguous(), + (k_fp8.contiguous(), k_scale.contiguous()), weights_work, ks, ke, @@ -1401,10 +1343,9 @@ def _get_topk_ragged_kpool( and zero_starts_by_batch[i] is not None else torch.zeros((q_len,), dtype=torch.int32, device=q_fp8.device) ) - local_logits = self._fp8_mqa_logits( + local_logits = deep_gemm.fp8_mqa_logits( q_fp8[q_slice].contiguous(), - k_fp8.contiguous(), - k_scale.contiguous(), + (k_fp8.contiguous(), k_scale.contiguous()), weights[q_slice].contiguous(), row_starts, local_pool_lens, @@ -1749,7 +1690,7 @@ def forward_cuda( if weights is None: weights = self._get_logits_head_gate(x, q_scale) - if is_cuda() or is_hip(): + if is_cuda(): if ( forward_batch.forward_mode.is_decode_or_idle() or forward_batch.forward_mode.is_target_verify() diff --git a/python/sglang/srt/layers/attention/dsa/kpool_fp8_index.py b/python/sglang/srt/layers/attention/dsa/kpool_fp8_index.py index 3c0cd65febe22..f9bf231375cc2 100644 --- a/python/sglang/srt/layers/attention/dsa/kpool_fp8_index.py +++ b/python/sglang/srt/layers/attention/dsa/kpool_fp8_index.py @@ -4,47 +4,11 @@ import triton import triton.language as tl -from sglang.srt.layers.attention.dsa.utils import ( - INDEXER_K_CACHE_PRESHUFFLE_TILE, - aiter_can_use_preshuffle_paged_mqa, -) -from sglang.srt.utils import is_hip - BLOCK_SIZE_K = 64 INDEX_HEAD_DIM = 128 KPOOL_SCORE_DTYPES = (torch.float16, torch.bfloat16, torch.float32) -def _preshuffle_tile() -> int: - return ( - INDEXER_K_CACHE_PRESHUFFLE_TILE if aiter_can_use_preshuffle_paged_mqa() else 0 - ) - - -@triton.jit -def _kpool_cache_k_offsets( - page, - slot, - cols, - PAGE_BYTES: tl.constexpr, - HEAD_DIM: tl.constexpr, - PRESHUFFLE_TILE: tl.constexpr, -): - if PRESHUFFLE_TILE: - token_tile_id = slot // PRESHUFFLE_TILE - token_in_tile = slot % PRESHUFFLE_TILE - col_tile_id = cols // PRESHUFFLE_TILE - col_in_tile = cols % PRESHUFFLE_TILE - return ( - page * PAGE_BYTES - + token_tile_id * (PRESHUFFLE_TILE * HEAD_DIM) - + col_tile_id * (PRESHUFFLE_TILE * PRESHUFFLE_TILE) - + token_in_tile * PRESHUFFLE_TILE - + col_in_tile - ) - return page * PAGE_BYTES + slot * HEAD_DIM + cols - - def kpool_max_closed_pools(num_draft_tokens: int, pool_size: int) -> int: return (num_draft_tokens + pool_size - 1) // pool_size @@ -97,7 +61,6 @@ def gather_index_k_scale_prefix_into( BUF_NUMEL_PER_PAGE=buf.shape[1], HEAD_DIM=INDEX_HEAD_DIM, S_OFFSET_NBYTES_IN_PAGE=pool.page_size * INDEX_HEAD_DIM, - PRESHUFFLE_TILE=_preshuffle_tile(), BLOCK_D=triton.next_power_of_2(INDEX_HEAD_DIM), ) @@ -113,7 +76,6 @@ def _gather_index_k_scale_prefix_into_kernel( BUF_NUMEL_PER_PAGE: tl.constexpr, HEAD_DIM: tl.constexpr, S_OFFSET_NBYTES_IN_PAGE: tl.constexpr, - PRESHUFFLE_TILE: tl.constexpr, BLOCK_D: tl.constexpr, ): token_id = tl.program_id(0) @@ -123,14 +85,7 @@ def _gather_index_k_scale_prefix_into_kernel( offs = tl.arange(0, BLOCK_D) mask = offs < HEAD_DIM - src_k_offsets = _kpool_cache_k_offsets( - page, - token_offset_in_page, - offs, - BUF_NUMEL_PER_PAGE, - HEAD_DIM, - PRESHUFFLE_TILE, - ) + src_k_offsets = page * BUF_NUMEL_PER_PAGE + token_offset_in_page * HEAD_DIM + offs dst_k_offsets = token_id * HEAD_DIM + offs k = tl.load(buf_u8_ptr + src_k_offsets, mask=mask) tl.store(k_out_ptr + dst_k_offsets, k, mask=mask) @@ -617,22 +572,6 @@ def topk_from_pooled_history_logits( f"is disabled. Got device={logits.device}, dtype={logits.dtype}." ) - # The JIT kernel covers group_topk <= 512 on CUDA/HIP; HIP 2048 still - # requires the legacy AOT fallback. - if is_hip() and group_topk == 2048: - return _topk_from_pooled_history_logits_unfused( - logits=logits, - group_lengths=group_lengths, - pool_size=pool_size, - topk=topk, - page_table=page_table, - topk_offsets=topk_offsets, - seq_lens=seq_lens, - row_starts=row_starts, - out_rows=out_rows, - page_table_row_index=page_table_row_index, - ) - if group_topk in (128, 160, 192, 224, 256, 512): from sglang.kernels.ops.moe.kpool_topk_transform import ( fast_kpool_topk_transform_fused, @@ -705,66 +644,6 @@ def topk_from_pooled_history_logits( return padded -def _topk_from_pooled_history_logits_unfused( - logits: torch.Tensor, - group_lengths: torch.Tensor, - pool_size: int, - topk: int, - page_table: torch.Tensor | None = None, - topk_offsets: torch.Tensor | None = None, - seq_lens: torch.Tensor | None = None, - row_starts: torch.Tensor | None = None, - out_rows: int | None = None, - page_table_row_index: torch.Tensor | None = None, -) -> torch.Tensor: - from sglang.srt.layers.attention.dsa.dsa_topk_backend import _topk_unfused - - group_topk = history_group_budget_for_topk(topk, pool_size) - selected_groups = _topk_unfused( - logits, - group_lengths, - group_topk, - row_starts=row_starts, - topk_op=torch.topk, - topk_op_kwargs={"dim": -1}, - ) - group_valid = selected_groups >= 0 - - page_table_for_rows = page_table - if page_table_row_index is not None: - assert page_table is not None - page_table_for_rows = page_table.index_select( - 0, page_table_row_index.to(dtype=torch.int64, device=page_table.device) - ) - - expanded = expand_pooled_groups_to_topk( - selected_groups.contiguous(), - group_valid, - topk=topk, - pool_size=pool_size, - page_table=page_table_for_rows, - topk_offsets=topk_offsets, - ) - if seq_lens is None: - result = expanded - else: - result = append_kpool_tail_to_topk( - expanded, - seq_lens=seq_lens, - pool_lens=group_lengths, - pool_size=pool_size, - page_table=page_table_for_rows, - topk_offsets=topk_offsets, - ) - if out_rows is None or out_rows == result.shape[0]: - return result - padded = torch.full( - (out_rows, result.shape[1]), -1, dtype=result.dtype, device=result.device - ) - padded[: result.shape[0]] = result - return padded - - def kpool_softmax_rotate_write_cache( pool, buf: torch.Tensor, @@ -849,7 +728,6 @@ def kpool_softmax_rotate_write_cache( POOL_SIZE=slot_k.shape[1], HEAD_DIM=slot_k.shape[2], S_OFFSET_NBYTES_IN_PAGE=pool.page_size * pool.index_head_dim, - PRESHUFFLE_TILE=_preshuffle_tile(), ROUND_SCALE=round_scale, HAS_WRITE_MASK=has_write_mask, RETURN_COMPRESSED=return_compressed, @@ -945,7 +823,6 @@ def kpool_decode_update_and_maybe_write_cache( HEAD_DIM=tail_k.shape[2], BLOCK_TABLE_COLS=block_tables.shape[1], S_OFFSET_NBYTES_IN_PAGE=pool.slots_per_page * pool.index_head_dim, - PRESHUFFLE_TILE=_preshuffle_tile(), ROUND_SCALE=round_scale, BLOCK_D=triton.next_power_of_2(tail_k.shape[2]), SLOTS_PER_PAGE=pool.slots_per_page, @@ -995,7 +872,6 @@ def _kpool_softmax_rotate_write_cache_kernel( POOL_SIZE: tl.constexpr, HEAD_DIM: tl.constexpr, S_OFFSET_NBYTES_IN_PAGE: tl.constexpr, - PRESHUFFLE_TILE: tl.constexpr, ROUND_SCALE: tl.constexpr, HAS_WRITE_MASK: tl.constexpr, RETURN_COMPRESSED: tl.constexpr, @@ -1071,13 +947,10 @@ def _kpool_softmax_rotate_write_cache_kernel( loc = tl.load(loc_ptr + row, mask=do_write, other=0) loc_page_index = loc // PAGE_SIZE loc_token_offset_in_page = loc % PAGE_SIZE - out_k_offsets = _kpool_cache_k_offsets( - loc_page_index, - loc_token_offset_in_page, - offs, - BUF_NUMEL_PER_PAGE, - HEAD_DIM, - PRESHUFFLE_TILE, + out_k_offsets = ( + loc_page_index * BUF_NUMEL_PER_PAGE + + loc_token_offset_in_page * HEAD_DIM + + offs ) out_s_offset = ( loc_page_index * BUF_NUMEL_PER_PAGE // 4 @@ -1127,7 +1000,6 @@ def _kpool_decode_update_and_maybe_write_cache_kernel( HEAD_DIM: tl.constexpr, BLOCK_TABLE_COLS: tl.constexpr, S_OFFSET_NBYTES_IN_PAGE: tl.constexpr, - PRESHUFFLE_TILE: tl.constexpr, ROUND_SCALE: tl.constexpr, BLOCK_D: tl.constexpr, SLOTS_PER_PAGE: tl.constexpr, @@ -1240,13 +1112,10 @@ def _kpool_decode_update_and_maybe_write_cache_kernel( ) loc_page_index = packed_page.to(tl.int64) loc_token_offset_in_page = pool_id % SLOTS_PER_PAGE - out_k_offsets = _kpool_cache_k_offsets( - loc_page_index, - loc_token_offset_in_page, - offs, - BUF_NUMEL_PER_PAGE, - HEAD_DIM, - PRESHUFFLE_TILE, + out_k_offsets = ( + loc_page_index * BUF_NUMEL_PER_PAGE + + loc_token_offset_in_page * HEAD_DIM + + offs ) out_s_offset = ( loc_page_index * BUF_NUMEL_PER_PAGE // 4 @@ -1306,7 +1175,6 @@ def _kpool_assemble_softmax_rotate_write_cache_kernel( TAIL_SIZE: tl.constexpr, HEAD_DIM: tl.constexpr, S_OFFSET_NBYTES_IN_PAGE: tl.constexpr, - PRESHUFFLE_TILE: tl.constexpr, ROUND_SCALE: tl.constexpr, HAS_WRITE_MASK: tl.constexpr, BLOCK_D: tl.constexpr, @@ -1354,13 +1222,8 @@ def _kpool_assemble_softmax_rotate_write_cache_kernel( loc = tl.load(loc_ptr + row) loc_page_index = loc // SLOTS_PER_PAGE loc_token_offset_in_page = loc % SLOTS_PER_PAGE - out_k_offsets = _kpool_cache_k_offsets( - loc_page_index, - loc_token_offset_in_page, - offs, - BUF_NUMEL_PER_PAGE, - HEAD_DIM, - PRESHUFFLE_TILE, + out_k_offsets = ( + loc_page_index * BUF_NUMEL_PER_PAGE + loc_token_offset_in_page * HEAD_DIM + offs ) out_s_offset = ( loc_page_index * BUF_NUMEL_PER_PAGE // 4 @@ -1431,7 +1294,6 @@ def kpool_assemble_softmax_rotate_write_cache( TAIL_SIZE=tail_k.shape[1], HEAD_DIM=INDEX_HEAD_DIM, S_OFFSET_NBYTES_IN_PAGE=slots_per_page * INDEX_HEAD_DIM, - PRESHUFFLE_TILE=_preshuffle_tile(), ROUND_SCALE=round_scale, HAS_WRITE_MASK=has_write_mask, BLOCK_D=triton.next_power_of_2(INDEX_HEAD_DIM), @@ -1529,7 +1391,6 @@ def _pack_pool_slots_to_payload_kernel( head_dim: tl.constexpr, page_bytes: tl.constexpr, scale_region_off: tl.constexpr, - PRESHUFFLE_TILE: tl.constexpr, BLOCK_D: tl.constexpr, ): row = tl.program_id(0) @@ -1540,14 +1401,7 @@ def _pack_pool_slots_to_payload_kernel( offs = tl.arange(0, BLOCK_D) mask = offs < head_dim - src = _kpool_cache_k_offsets( - page, - slot, - offs, - page_bytes, - head_dim, - PRESHUFFLE_TILE, - ) + src = page_base + slot * head_dim + offs val = tl.load(buf_ptr + src, mask=mask, other=0).to(tl.uint8) tl.store(payload_ptr + row * payload_bytes + offs, val, mask=mask) @@ -1570,7 +1424,6 @@ def _select_and_scatter_pool_slots_kernel( page_bytes: tl.constexpr, scale_region_off: tl.constexpr, n_total: tl.constexpr, - PRESHUFFLE_TILE: tl.constexpr, BLOCK_D: tl.constexpr, ): row = tl.program_id(0) @@ -1587,14 +1440,7 @@ def _select_and_scatter_pool_slots_kernel( offs = tl.arange(0, BLOCK_D) mask = offs < head_dim val = tl.load(recv_ptr + recv_row_base + offs, mask=mask, other=0).to(tl.uint8) - dst = _kpool_cache_k_offsets( - page, - slot, - offs, - page_bytes, - head_dim, - PRESHUFFLE_TILE, - ) + dst = page_base + slot * head_dim + offs tl.store(buf_ptr + dst, val, mask=mask) s_offs = tl.arange(0, 4) @@ -1636,7 +1482,6 @@ def all_gather_and_scatter_pool_slots( head_dim=head_dim, page_bytes=page_bytes, scale_region_off=scale_region_off, - PRESHUFFLE_TILE=_preshuffle_tile(), BLOCK_D=triton.next_power_of_2(head_dim), ) @@ -1659,7 +1504,6 @@ def all_gather_and_scatter_pool_slots( page_bytes=page_bytes, scale_region_off=scale_region_off, n_total=n_total, - PRESHUFFLE_TILE=_preshuffle_tile(), BLOCK_D=triton.next_power_of_2(head_dim), ) @@ -1693,7 +1537,6 @@ def _kpool_write_tail_and_maybe_compress_kernel( SLOTS_PER_PAGE: tl.constexpr, BUF_NUMEL_PER_PAGE: tl.constexpr, S_OFFSET_NBYTES_IN_PAGE: tl.constexpr, - PRESHUFFLE_TILE: tl.constexpr, ROUND_SCALE: tl.constexpr, HAS_EFFECTIVE_N: tl.constexpr, MAX_CLOSED_POOLS: tl.constexpr, @@ -1758,13 +1601,10 @@ def _kpool_write_tail_and_maybe_compress_kernel( loc = tl.load(write_loc_ptr + b * write_loc_stride_0 + p) loc_page_index = loc // SLOTS_PER_PAGE loc_token_offset_in_page = loc % SLOTS_PER_PAGE - out_k_offsets = _kpool_cache_k_offsets( - loc_page_index, - loc_token_offset_in_page, - offs, - BUF_NUMEL_PER_PAGE, - HEAD_DIM, - PRESHUFFLE_TILE, + out_k_offsets = ( + loc_page_index * BUF_NUMEL_PER_PAGE + + loc_token_offset_in_page * HEAD_DIM + + offs ) out_s_offset = ( loc_page_index * BUF_NUMEL_PER_PAGE // 4 @@ -1855,7 +1695,6 @@ def kpool_write_tail_and_maybe_compress( SLOTS_PER_PAGE=slots_per_page, BUF_NUMEL_PER_PAGE=buf.shape[1], S_OFFSET_NBYTES_IN_PAGE=slots_per_page * pool.index_head_dim, - PRESHUFFLE_TILE=_preshuffle_tile(), ROUND_SCALE=round_scale, HAS_EFFECTIVE_N=effective_n_per_batch is not None, MAX_CLOSED_POOLS=max_closed_pools, diff --git a/python/sglang/srt/layers/communicator_mhc.py b/python/sglang/srt/layers/communicator_mhc.py index 9c1618ba0ae62..a8c342afd93bc 100644 --- a/python/sglang/srt/layers/communicator_mhc.py +++ b/python/sglang/srt/layers/communicator_mhc.py @@ -73,7 +73,6 @@ class MHCState: hc_attn_pre: Callable hc_ffn_pre: Callable hc_post: Callable - hc_attn_to_mlp: Optional[Callable] = None h_res: Optional[torch.Tensor] = None h_post: Optional[torch.Tensor] = None @@ -96,34 +95,9 @@ def attn_split(self, hidden_states, out_norm: Optional[torch.nn.Module] = None): def attn_to_mlp( self, hidden_states, residual, out_norm: Optional[torch.nn.Module] = None ): - out_norm_weight, out_norm_eps = self._resolve_out_norm(out_norm) - if self.hc_attn_to_mlp is not None: - fused = self.hc_attn_to_mlp( - hidden_states, - residual, - self.h_res, - self.h_post, - out_norm_weight, - out_norm_eps, - ) - if fused is not None: - ( - hidden_states, - residual, - self.h_res, - self.h_post, - norm_fused, - ) = fused - if ( - out_norm is not None - and not norm_fused - and hidden_states.shape[0] != 0 - ): - hidden_states = out_norm(hidden_states) - return hidden_states, residual - hidden_states = self.hc_post(hidden_states, residual, self.h_res, self.h_post) residual = hidden_states + out_norm_weight, out_norm_eps = self._resolve_out_norm(out_norm) hidden_states, self.h_res, self.h_post, norm_fused = self.hc_ffn_pre( hidden_states, out_norm_weight, out_norm_eps ) @@ -433,7 +407,6 @@ def __init__( hc_attn_pre: Callable, hc_ffn_pre: Callable, hc_post: Callable, - hc_attn_to_mlp: Optional[Callable] = None, ): self.is_first_layer = is_first_layer self.mhc = MHCState( @@ -441,7 +414,6 @@ def __init__( hc_attn_pre=hc_attn_pre, hc_ffn_pre=hc_ffn_pre, hc_post=hc_post, - hc_attn_to_mlp=hc_attn_to_mlp, ) super().__init__( diff --git a/python/sglang/srt/layers/moe/moe_runner/triton_utils/fused_moe.py b/python/sglang/srt/layers/moe/moe_runner/triton_utils/fused_moe.py index 9e74a784228fb..758c2eacf6395 100644 --- a/python/sglang/srt/layers/moe/moe_runner/triton_utils/fused_moe.py +++ b/python/sglang/srt/layers/moe/moe_runner/triton_utils/fused_moe.py @@ -95,12 +95,6 @@ logger = logging.getLogger(__name__) -def _clamp_swiglu_inputs_(x: torch.Tensor, limit: float) -> None: - half = x.shape[-1] // 2 - x[..., :half].clamp_(max=limit) - x[..., half:].clamp_(min=-limit, max=limit) - - def _validate_fused_swiglu_interleaved( *, activation: str, @@ -714,10 +708,6 @@ def _fused_moe_kernel_sequence( if filter_expert: swiglu_limit_for_triton = swiglu_limit - elif _is_hip: - # The fused clamp kernel is CUDA/XPU-only; apply its gate/up - # contract before the regular HIP silu_and_mul kernel. - _clamp_swiglu_inputs_(intermediate_cache1, swiglu_limit) else: assert ( _is_cuda or _is_xpu diff --git a/python/sglang/srt/layers/quantization/fp8.py b/python/sglang/srt/layers/quantization/fp8.py index b4b0392b33c64..72935cffb0f20 100644 --- a/python/sglang/srt/layers/quantization/fp8.py +++ b/python/sglang/srt/layers/quantization/fp8.py @@ -1609,7 +1609,8 @@ def process_weights_after_loading_block_quant(self, layer: Module) -> None: layer.w13_input_scale = None layer.w2_input_scale = None runner_is_aiter = ( - self._owns_moe_runner and self.runner.runner_backend.is_aiter() + getattr(self, "runner", None) is not None + and self.runner.runner_backend.is_aiter() ) if _use_aiter and runner_is_aiter: layer.w13_weight.data = shuffle_weight( @@ -1649,21 +1650,14 @@ def process_weights_after_loading_block_quant(self, layer: Module) -> None: w2_weight_scale, requires_grad=False ) layer.w2_input_scale = None - runner_is_aiter = ( - self._owns_moe_runner and self.runner.runner_backend.is_aiter() - ) - if _use_aiter and runner_is_aiter: + if _use_aiter: layer.w13_weight.data = shuffle_weight( layer.w13_weight.contiguous(), (16, 16) ) layer.w2_weight.data = shuffle_weight( layer.w2_weight.contiguous(), (16, 16) ) - elif ( - _use_aiter - and self._owns_moe_runner - and self.runner.runner_backend.is_aiter() - ): + elif _use_aiter: # Pre-shuffle weights t = shuffle_weight(layer.w13_weight, (16, 16)) layer.w13_weight.copy_(t) diff --git a/python/sglang/srt/layers/quantization/quark/quark.py b/python/sglang/srt/layers/quantization/quark/quark.py index 41b5321765636..60db3f52b59e0 100644 --- a/python/sglang/srt/layers/quantization/quark/quark.py +++ b/python/sglang/srt/layers/quantization/quark/quark.py @@ -15,11 +15,7 @@ QuantizationConfig, QuantizeMethodBase, ) -from sglang.srt.layers.quantization.fp8 import ( - Fp8Config, - Fp8LinearMethod, - Fp8MoEMethod, -) +from sglang.srt.layers.quantization.fp8 import Fp8Config, Fp8LinearMethod from sglang.srt.layers.quantization.kv_cache import BaseKVCacheMethod from sglang.srt.layers.quantization.quark.schemes import ( QuarkLinearScheme, @@ -380,59 +376,9 @@ def apply_weight_name_mapper(self, hf_to_sglang_mapper): expanded.append(name.removeprefix("language_model.")) self.exclude_layers = list(dict.fromkeys(expanded)) - layer_quant_config = self.quant_config.get("layer_quant_config") - if layer_quant_config: - self.quant_config["layer_quant_config"] = hf_to_sglang_mapper.apply_dict( - layer_quant_config - ) - - if self.kv_cache_group: - self.kv_cache_group = hf_to_sglang_mapper.apply_list(self.kv_cache_group) - - @staticmethod - def _get_block_fp8_config( - layer_quant_config: Optional[dict[str, Any]], - packed_modules_mapping: dict[str, list[str]], - ) -> Optional[Fp8Config]: - if layer_quant_config is None: - return None - - weight_config = layer_quant_config.get("weight") or {} - input_config = layer_quant_config.get("input_tensors") or {} - block_size = weight_config.get("block_size") - if not ( - weight_config.get("dtype") in {"fp8_e4m3", "fp8_e4m3fn"} - and weight_config.get("qscheme") == "per_block" - and weight_config.get("is_dynamic") is False - and isinstance(block_size, list) - and len(block_size) == 2 - and input_config.get("dtype") in {"fp8_e4m3", "fp8_e4m3fn"} - and input_config.get("is_dynamic") is True - ): - return None - - return Fp8Config( - is_checkpoint_fp8_serialized=True, - activation_scheme="dynamic", - weight_block_size=block_size, - packed_modules_mapping=packed_modules_mapping, - ) - def get_quant_method( self, layer: torch.nn.Module, prefix: str ) -> Optional["QuantizeMethodBase"]: - from sglang.srt.layers.moe.fused_moe_triton.layer import FusedMoE - - explicit_layer_config = self._find_matched_layer_config(prefix, layer) - block_fp8_config = self._get_block_fp8_config( - explicit_layer_config, self.packed_modules_mapping - ) - if block_fp8_config is not None: - if isinstance(layer, LinearBase): - return Fp8LinearMethod(block_fp8_config) - if isinstance(layer, FusedMoE): - return Fp8MoEMethod(block_fp8_config) - # Check if the layer is skipped for quantization. if should_ignore_layer( prefix, @@ -461,6 +407,8 @@ def get_quant_method( self._online_quantized_layers.add(prefix) return QuarkKVCacheMethod(self) + from sglang.srt.layers.moe.fused_moe_triton.layer import FusedMoE + if isinstance(layer, FusedMoE): self._online_quantized_layers.add(prefix) layer.scheme = self.get_moe_scheme(layer, prefix) @@ -835,9 +783,9 @@ def _is_mx_w4a8( ) return is_mx_fp4_weight and is_static_fp8_activation - def _find_matched_layer_config( + def _find_matched_config( self, layer_name: str, module: torch.nn.Module - ) -> Optional[dict[str, Any]]: + ) -> dict[str, Any]: proj_name = layer_name.split(".")[-1] if proj_name in self.packed_modules_mapping: @@ -849,17 +797,9 @@ def _find_matched_layer_config( for shard_proj_name in shard_proj_names ] shard_configs = [ - self._find_matched_layer_config(shard_name, module) + self._find_matched_config(shard_name, module) for shard_name in shard_names ] - if all(q_config is None for q_config in shard_configs): - return None - if any(q_config is None for q_config in shard_configs): - raise ValueError( - f"Found a partially specified quantization configuration for " - f"{shard_proj_names} in {layer_name}. SGLang requires all " - "fused shards to use the same scheme." - ) if not all( deep_compare(q_config, shard_configs[0]) for q_config in shard_configs ): @@ -884,19 +824,10 @@ def _find_matched_layer_config( if layer_type in layer_type_quant_config: return layer_type_quant_config[layer_type] - return None - - def _find_matched_config( - self, layer_name: str, module: torch.nn.Module - ) -> dict[str, Any]: - layer_config = self._find_matched_layer_config(layer_name, module) - if layer_config is not None: - return layer_config - - global_quant_config = cast( - dict[str, Any], self.quant_config.get("global_quant_config") - ) - return global_quant_config + global_quant_config = cast( + dict[str, Any], self.quant_config.get("global_quant_config") + ) + return global_quant_config def _get_scheme_from_config(self, config: dict[str, Any]) -> "QuarkLinearScheme": if config.get("output_tensors") or config.get("bias"): diff --git a/python/sglang/srt/layers/quantization/quark/utils.py b/python/sglang/srt/layers/quantization/quark/utils.py index 5eb35af80149b..dcd3aeb5993dd 100644 --- a/python/sglang/srt/layers/quantization/quark/utils.py +++ b/python/sglang/srt/layers/quantization/quark/utils.py @@ -55,11 +55,6 @@ def should_ignore_layer( # proj_name = qkv_proj proj_name = layer_name.split(".")[-1] - # A serialized fused module may appear directly in ``exclude``, so match it - # before expanding the packed mapping. - if check_equal_or_regex_match(layer_name=layer_name, targets=ignore): - return True - # Fused layers like gate_up_proj or qkv_proj will not be fused # in the safetensors checkpoint. So, we convert the name # from the fused version to unfused + check to make sure that diff --git a/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha_rocm.py b/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha_rocm.py index 1dab68c7d6f58..39fc8ab092306 100644 --- a/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha_rocm.py +++ b/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha_rocm.py @@ -269,12 +269,8 @@ def forward_normal_one_shot_rocm_prepare( def _concat_and_cast_mha_k_rocm( self: DeepseekV2AttentionMLA, k_nope: torch.Tensor, - k_pe: torch.Tensor | None, + k_pe: torch.Tensor, ): - if self.qk_rope_head_dim == 0: - assert k_pe is None or k_pe.shape[-1] == 0 - return k_nope.contiguous() - k_shape = (k_nope.shape[0], self.num_local_heads, self.qk_head_dim) k = k_nope.new_empty(*k_shape) if self.current_attention_backend == "aiter": diff --git a/python/sglang/srt/models/glm5_next.py b/python/sglang/srt/models/glm5_next.py index 4eba804851cdb..0b2e8ddbe0b45 100644 --- a/python/sglang/srt/models/glm5_next.py +++ b/python/sglang/srt/models/glm5_next.py @@ -116,7 +116,6 @@ GlmOcrVisionPatchEmbed, GlmOcrVisionPatchMerger, ) -from sglang.srt.models.utils import WeightsMapper from sglang.srt.multimodal.mm_utils import ( run_dp_presharded_mrope_vision_model, run_dp_sharded_mrope_vision_model, @@ -138,7 +137,6 @@ ) logger = logging.getLogger(__name__) -_GLM_AITER_FUSED_MHC_LOGGED = False @torch.compile @@ -758,7 +756,6 @@ def __init__( hc_attn_pre=self.hc_attn_pre, hc_ffn_pre=self.hc_ffn_pre, hc_post=self.hc_post, - hc_attn_to_mlp=(self.hc_attn_to_mlp if _use_aiter_gfx95 else None), ) if self.dsa_enable_prefill_cp: self.layer_communicator = MHCHybridDSACPLayerCommunicator( @@ -823,57 +820,6 @@ def hc_post(self, hidden_states, residual, h_res, h_post): hc_mult=self.config.hc_mult, ) - def hc_attn_to_mlp( - self, - hidden_states, - residual, - h_res, - h_post, - out_norm_weight, - out_norm_eps, - ): - global _GLM_AITER_FUSED_MHC_LOGGED - - from sglang.srt.models.deepseek_common.amd.deepseek_v4_fused_mhc import ( - apply_mhc_post_pre_boundary, - ) - - num_tokens, hidden_size = hidden_states.shape - if num_tokens == 0: - return None - hc_mult = self.config.hc_mult - fused = apply_mhc_post_pre_boundary( - layer_input=hidden_states, - residual=residual.view(num_tokens, hc_mult, hidden_size), - post=h_post.view(num_tokens, hc_mult), - comb=h_res.view(num_tokens, hc_mult, hc_mult), - hc_fn=self.hc_ffn_fn, - hc_scale=self.hc_ffn_scale, - hc_base=self.hc_ffn_base, - hc_mult=hc_mult, - rms_eps=self.config.rms_norm_eps, - hc_eps=self.config.hc_eps, - hc_post_mult=2.0, - sinkhorn_iters=self.config.hc_sinkhorn_iters, - norm_weight=out_norm_weight, - norm_eps=out_norm_eps, - fn_transpose=True, - ) - if fused is None: - return None - if not _GLM_AITER_FUSED_MHC_LOGGED: - logger.info("Using fused AITER mHC attention-to-FFN boundary") - _GLM_AITER_FUSED_MHC_LOGGED = True - - next_residual, layer_input, next_h_post, next_h_res, norm_fused = fused - return ( - layer_input, - next_residual.view(num_tokens, -1), - next_h_res.reshape(num_tokens, hc_mult * hc_mult), - next_h_post.reshape(num_tokens, hc_mult), - norm_fused, - ) - def _is_layer_sparse(self, layer_id: int, is_nextn: bool) -> bool: return is_nextn or ( self.config.n_routed_experts is not None @@ -1259,13 +1205,6 @@ def forward( class Glm5NextForConditionalGeneration(nn.Module): - hf_to_sglang_mapper = WeightsMapper( - orig_to_new_prefix={ - "model.language_model.": "model.", - "model.visual.": "visual.", - }, - orig_to_new_suffix={".attn.qkv": ".attn.qkv_proj"}, - ) packed_modules_mapping = { "fused_qkv_a_proj_with_mqa": ["q_a_proj", "kv_a_proj_with_mqa"], "fused_qkvbfg_a_proj": [ @@ -1403,12 +1342,9 @@ def shared_experts_fusion_disable_reason(cls, hf_config, quant_config): text_config = getattr(hf_config, "text_config", hf_config) if not getattr(text_config, "n_shared_experts", None): return "No shared experts are defined in the config." - if not (_is_cuda or _use_aiter_gfx95): - return ( - "Shared experts fusion requires CUDA or the supported " - "AITER ROCm path." - ) - if _is_cuda and _device_sm is not None and _device_sm < 80: + if not _is_cuda: + return "Shared experts fusion currently requires CUDA devices." + if _device_sm is not None and _device_sm < 80: return "Shared experts fusion requires SM80 or newer GPUs." if get_parallel().moe_ep_size > 1: return ( @@ -1674,14 +1610,6 @@ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]], is_nextn=Fal fused_cat_dim = 0 params_dict = dict(self.named_parameters()) - - def maybe_map_fp8_block_scale_name(name: str) -> str: - if name.endswith(".weight_scale"): - candidate = name.removesuffix(".weight_scale") + ".weight_scale_inv" - if candidate in params_dict: - return candidate - return name - weight_names = [] for name, loaded_weight in weights: is_visual_weight = "visual" in name @@ -1745,7 +1673,6 @@ def maybe_map_fp8_block_scale_name(name: str) -> str: if "mlp.experts" in name: continue candidate = name.replace(weight_name, param_name) - candidate = maybe_map_fp8_block_scale_name(candidate) if ( param_name in { @@ -1774,7 +1701,6 @@ def maybe_map_fp8_block_scale_name(name: str) -> str: continue is_expert_weight = True name = name.replace(weight_name, param_name) - name = maybe_map_fp8_block_scale_name(name) if name not in params_dict: continue param = params_dict[name] @@ -1826,7 +1752,6 @@ def maybe_map_fp8_block_scale_name(name: str) -> str: "fused_qkv_a_proj_with_mqa", ) ) - target = maybe_map_fp8_block_scale_name(target) if target in params_dict: param = params_dict[target] weight_loader = getattr( @@ -1837,7 +1762,6 @@ def maybe_map_fp8_block_scale_name(name: str) -> str: cached_a_proj.pop(kv_a_proj_name, None) continue - name = maybe_map_fp8_block_scale_name(name) if name not in params_dict: continue diff --git a/test/registered/kernels/ops/attention/test_dsa_transform_index.py b/test/registered/kernels/ops/attention/test_dsa_transform_index.py index a9a7f63378ca0..e4c32e3593c39 100644 --- a/test/registered/kernels/ops/attention/test_dsa_transform_index.py +++ b/test/registered/kernels/ops/attention/test_dsa_transform_index.py @@ -33,11 +33,9 @@ def _make_page_table(self, rows: int, context_length: int) -> torch.Tensor: ) return columns.unsqueeze(0) + row_bias - def _make_topk( - self, rows: int, context_length: int, topk: int = TOPK - ) -> torch.Tensor: + def _make_topk(self, rows: int, context_length: int) -> torch.Tensor: topk = ( - torch.arange(topk, dtype=torch.int64, device=self.device) + torch.arange(TOPK, dtype=torch.int64, device=self.device) .remainder(context_length) .repeat(rows, 1) ) @@ -57,7 +55,7 @@ def _expected( ) -> torch.Tensor: real_num_tokens = sum(extend_lens_cpu) expected = torch.full( - (output_num_tokens, topk_indices.shape[1]), + (output_num_tokens, TOPK), -1, dtype=torch.int32, device=self.device, @@ -93,15 +91,14 @@ def _check_decode_case( *, zero_row_stride: bool = False, provide_result: bool = False, - topk: int = TOPK, ) -> None: if zero_row_stride: page_table = self._make_page_table(1, context_length).expand(batch_size, -1) else: page_table = self._make_page_table(batch_size, context_length) - topk_indices = self._make_topk(batch_size, context_length, topk) + topk_indices = self._make_topk(batch_size, context_length) expected = torch.empty( - (batch_size, topk), dtype=torch.int32, device=self.device + (batch_size, TOPK), dtype=torch.int32, device=self.device ) torch.gather( page_table, @@ -130,7 +127,6 @@ def _check_case( page_table_is_expanded: bool, topk_padding: int = 0, output_padding: int = 0, - topk: int = TOPK, ) -> None: real_num_tokens = sum(extend_lens_cpu) page_table_rows = ( @@ -139,7 +135,7 @@ def _check_case( topk_num_tokens = real_num_tokens + topk_padding output_num_tokens = topk_num_tokens + output_padding page_table = self._make_page_table(page_table_rows, context_length) - topk_indices = self._make_topk(topk_num_tokens, context_length, topk) + topk_indices = self._make_topk(topk_num_tokens, context_length) expected = self._expected( page_table, topk_indices, @@ -239,16 +235,6 @@ def test_decode_fast_extreme_shapes(self): self._check_decode_case(8192, 4096) self._check_decode_case(2, 1_000_000) - def test_kpool_tail_extended_width(self): - kpool_topk = TOPK + 15 - self._check_decode_case(17, 8192, topk=kpool_topk) - self._check_case( - [2, 1], - 8192, - page_table_is_expanded=False, - topk=kpool_topk, - ) - if __name__ == "__main__": unittest.main() diff --git a/test/registered/kernels/test_dsa_kpool_multi_pool.py b/test/registered/kernels/test_dsa_kpool_multi_pool.py index 18bf35845c5e2..26ce445333f00 100644 --- a/test/registered/kernels/test_dsa_kpool_multi_pool.py +++ b/test/registered/kernels/test_dsa_kpool_multi_pool.py @@ -1,46 +1,32 @@ -"""GPU regressions for DSA kpool speculative writes and cache layout.""" +"""CUDA regressions for DSA kpool speculative writes spanning multiple pools.""" import unittest from types import SimpleNamespace -from unittest.mock import patch import torch -from sglang.kernels.ops.attention.dsa import aiter_paged_mqa_logits -from sglang.kernels.ops.quantization.fp8_kernel import fp8_dtype -from sglang.srt.layers.attention.dsa import kpool_fp8_index from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( INDEX_HEAD_DIM, - _topk_from_pooled_history_logits_unfused, - gather_index_k_scale_prefix_into, kpool_assemble_softmax_rotate_write_cache, kpool_max_closed_pools, - kpool_softmax_rotate_write_cache, kpool_write_tail_and_maybe_compress, - topk_from_pooled_history_logits, update_kpool_write_plan_cuda_graph, ) from sglang.srt.layers.attention.dsa.kpool_plan import ( _alloc_kpool_write_plan_buffers, ) -from sglang.srt.layers.attention.dsa.utils import ( - aiter_can_use_preshuffle_paged_mqa, -) -from sglang.srt.utils import is_hip -from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.ci.ci_register import register_cuda_ci from sglang.test.test_utils import CustomTestCase register_cuda_ci(est_time=15, stage="base-b-kernel-unit", runner_config="1-gpu-large") -register_amd_ci(est_time=20, stage="jit-kernel-unit", runner_config="amd") -@unittest.skipUnless(torch.cuda.is_available(), "Test requires a GPU") +@unittest.skipUnless(torch.cuda.is_available(), "Test requires CUDA") class TestDsaKpoolMultiPool(CustomTestCase): POOL_SIZE = 4 PAGE_SIZE = 64 SLOTS_PER_PAGE = 64 NUM_DRAFT_TOKENS = 6 - NUM_INDEX_HEADS = 32 def _pool(self) -> SimpleNamespace: return SimpleNamespace( @@ -56,47 +42,6 @@ def _empty_cache(self) -> torch.Tensor: page_nbytes = self.SLOTS_PER_PAGE * INDEX_HEAD_DIM + self.SLOTS_PER_PAGE * 4 return torch.zeros((1, page_nbytes), dtype=torch.uint8, device="cuda") - def test_fused_topk_matches_unfused_physical_token_sets(self): - torch.manual_seed(45) - batch_size = 2 - score_cols = 4096 - pool_size = self.POOL_SIZE - topk = 2048 - logits = torch.randn(batch_size, score_cols, dtype=torch.float32, device="cuda") - group_lengths = torch.tensor([256, 511], dtype=torch.int32, device="cuda") - seq_lens = group_lengths * pool_size + torch.tensor( - [0, 3], dtype=torch.int32, device="cuda" - ) - page_table = torch.arange( - batch_size * score_cols * pool_size, - dtype=torch.int32, - device="cuda", - ).view(batch_size, score_cols * pool_size) - - actual = topk_from_pooled_history_logits( - logits=logits, - group_lengths=group_lengths, - pool_size=pool_size, - topk=topk, - page_table=page_table, - seq_lens=seq_lens, - ) - expected = _topk_from_pooled_history_logits_unfused( - logits=logits, - group_lengths=group_lengths, - pool_size=pool_size, - topk=topk, - page_table=page_table, - seq_lens=seq_lens, - ) - - torch.testing.assert_close( - torch.sort(actual, dim=1).values, - torch.sort(expected, dim=1).values, - atol=0, - rtol=0, - ) - def test_write_plan_records_every_candidate_pool(self): batch_size = 2 num_draft_tokens = self.NUM_DRAFT_TOKENS @@ -263,202 +208,6 @@ def test_compresses_two_pools_when_draft_window_closes_two(self): def test_effective_n_only_compresses_accepted_pools(self): self._run_compress_case(effective_n=2, expected_closed_pools=1) - def test_preshuffled_cache_round_trip_and_raw_layout(self): - torch.manual_seed(43) - pool = self._pool() - num_slots = self.SLOTS_PER_PAGE - tile = 16 - num_col_tiles = INDEX_HEAD_DIM // tile - - slot_k = torch.randn( - num_slots, - self.POOL_SIZE, - INDEX_HEAD_DIM, - dtype=torch.bfloat16, - device="cuda", - ) - slot_score = torch.zeros_like(slot_k) - ape = torch.zeros( - self.POOL_SIZE, - INDEX_HEAD_DIM, - dtype=torch.float32, - device="cuda", - ) - loc = torch.arange(num_slots, dtype=torch.int64, device="cuda") - cache = self._empty_cache() - - with patch.object(kpool_fp8_index, "_preshuffle_tile", return_value=tile): - compressed_k, compressed_scale = kpool_softmax_rotate_write_cache( - pool=pool, - buf=cache, - slot_k=slot_k, - slot_score=slot_score, - ape=ape, - loc=loc, - return_compressed=True, - ) - - gathered_k = torch.empty( - (num_slots, INDEX_HEAD_DIM), dtype=torch.uint8, device="cuda" - ) - gathered_scale = torch.empty( - (num_slots,), dtype=torch.float32, device="cuda" - ) - gather_index_k_scale_prefix_into( - pool=pool, - buf=cache, - page_indices=torch.zeros(1, dtype=torch.int32, device="cuda"), - seq_len=num_slots, - k_out=gathered_k, - scale_out=gathered_scale, - ) - - compressed_k_u8 = compressed_k.view(torch.uint8) - torch.testing.assert_close(gathered_k, compressed_k_u8, atol=0, rtol=0) - torch.testing.assert_close(gathered_scale, compressed_scale, atol=0, rtol=0) - - raw_k = cache[0, : num_slots * INDEX_HEAD_DIM].view( - num_slots // tile, num_col_tiles, tile, tile - ) - expected_raw_k = ( - compressed_k_u8.view(num_slots // tile, tile, num_col_tiles, tile) - .permute(0, 2, 1, 3) - .contiguous() - ) - torch.testing.assert_close(raw_k, expected_raw_k, atol=0, rtol=0) - - @unittest.skipUnless( - is_hip() and aiter_can_use_preshuffle_paged_mqa(), - "requires the ROCm AITER preshuffle paged-MQA path", - ) - def test_preshuffled_paged_mqa_matches_gathered_mqa(self): - from aiter.ops.triton.fp8_mqa_logits import fp8_mqa_logits - - torch.manual_seed(44) - pool = self._pool() - page_nbytes = self.SLOTS_PER_PAGE * (INDEX_HEAD_DIM + 4) - tile = 16 - num_token_tiles = self.SLOTS_PER_PAGE // tile - num_col_tiles = INDEX_HEAD_DIM // tile - - for batch_size in (1, 8): - with self.subTest(batch_size=batch_size): - cache = torch.zeros( - (batch_size, page_nbytes), dtype=torch.uint8, device="cuda" - ) - k = ( - torch.randn( - batch_size, - self.SLOTS_PER_PAGE, - INDEX_HEAD_DIM, - device="cuda", - ) - * 2 - ).to(fp8_dtype) - k_scale = ( - torch.rand(batch_size, self.SLOTS_PER_PAGE, device="cuda") + 0.25 - ) - - preshuffled = ( - k.view( - batch_size, - num_token_tiles, - tile, - num_col_tiles, - tile, - ) - .permute(0, 1, 3, 2, 4) - .contiguous() - .view(batch_size, -1) - .view(torch.uint8) - ) - k_region_bytes = self.SLOTS_PER_PAGE * INDEX_HEAD_DIM - cache[:, :k_region_bytes].copy_(preshuffled) - cache[:, k_region_bytes:].view(torch.float32).copy_(k_scale) - - q = ( - torch.randn( - batch_size, - self.NUM_INDEX_HEADS, - INDEX_HEAD_DIM, - device="cuda", - ) - * 2 - ).to(fp8_dtype) - weights = torch.randn( - batch_size, - self.NUM_INDEX_HEADS, - dtype=torch.float32, - device="cuda", - ) - if batch_size == 1: - seq_lens = torch.tensor([53], dtype=torch.int32, device="cuda") - else: - seq_lens = torch.tensor( - [1, 7, 16, 31, 32, 47, 63, 64], - dtype=torch.int32, - device="cuda", - ) - block_tables = torch.arange( - batch_size, dtype=torch.int32, device="cuda" - ).view(batch_size, 1) - - paged_logits = aiter_paged_mqa_logits( - q, - cache.view(batch_size, self.SLOTS_PER_PAGE, 1, INDEX_HEAD_DIM + 4), - weights, - seq_lens, - block_tables, - self.SLOTS_PER_PAGE, - preshuffle=True, - kv_block_size=self.SLOTS_PER_PAGE, - ) - - gathered_k = [] - gathered_scale = [] - for batch_idx, seq_len in enumerate(seq_lens.tolist()): - k_out = torch.empty( - (seq_len, INDEX_HEAD_DIM), dtype=torch.uint8, device="cuda" - ) - scale_out = torch.empty( - (seq_len,), dtype=torch.float32, device="cuda" - ) - gather_index_k_scale_prefix_into( - pool=pool, - buf=cache, - page_indices=torch.tensor( - [batch_idx], dtype=torch.int32, device="cuda" - ), - seq_len=seq_len, - k_out=k_out, - scale_out=scale_out, - ) - gathered_k.append(k_out.view(fp8_dtype)) - gathered_scale.append(scale_out) - - flat_k = torch.cat(gathered_k) - flat_scale = torch.cat(gathered_scale) - ends = seq_lens.cumsum(0) - starts = ends - seq_lens - gathered_logits = fp8_mqa_logits( - q, - flat_k, - flat_scale, - weights, - starts, - ends, - clean_logits=True, - ) - - for batch_idx, seq_len in enumerate(seq_lens.tolist()): - start = starts[batch_idx].item() - torch.testing.assert_close( - paged_logits[batch_idx, :seq_len], - gathered_logits[batch_idx, start : start + seq_len], - atol=2e-2, - rtol=2e-2, - ) - if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/layers/quantization/test_fp8_moe_runner_ownership.py b/test/registered/unit/layers/quantization/test_fp8_moe_runner_ownership.py index 4623f75d21ce1..08316b4f57aed 100644 --- a/test/registered/unit/layers/quantization/test_fp8_moe_runner_ownership.py +++ b/test/registered/unit/layers/quantization/test_fp8_moe_runner_ownership.py @@ -1,9 +1,10 @@ """Unit tests for srt/layers/quantization/fp8.py MoE runner ownership. -MoE backend flags are global, so `Fp8MoEMethod.process_weights_after_loading` -must require that this instance owns a MoeRunner before materializing -backend-specific parameters or layouts. MxFP4 wrappers borrow an `Fp8MoEMethod` -for weight loading without giving it a runner (issue #36264). +`--moe-runner-backend flashinfer_trtllm[_routed]` is a global setting, so +`Fp8MoEMethod.process_weights_after_loading` must also require that this +instance owns a MoeRunner before materializing the TRT-LLM SwiGLU params: +the MxFP4 wrapper methods borrow an `Fp8MoEMethod` for weight loading only +and never give it a `moe_runner_config` (issue #36264). """ import unittest @@ -112,86 +113,6 @@ def test_owning_method_skips_params_on_non_trtllm_backend(self): self._assert_activation_params_absent(layer) - def test_global_aiter_does_not_shuffle_triton_runner_weights(self): - """SGLANG_USE_AITER also enables non-MoE kernels, so the selected MoE - runner must own the preshuffled layout before weights are rewritten.""" - method = self._make_block_fp8_method() - method.convert_mxfp8_to_block = True - method.use_mxfp8 = True - method.runner = SimpleNamespace(runner_backend=MoeRunnerBackend.TRITON) - method._owns_moe_runner = True - layer = SimpleNamespace( - w13_weight=torch.nn.Parameter(torch.arange(16.0).reshape(1, 4, 4)), - w2_weight=torch.nn.Parameter(torch.arange(16.0).reshape(1, 4, 4)), - ) - - with ( - patch("sglang.srt.layers.quantization.fp8._use_aiter", True), - patch("sglang.srt.layers.quantization.fp8._is_fp8_fnuz", False), - patch.object(method, "_convert_mxfp8_moe_to_block_fp8"), - patch( - "sglang.srt.layers.quantization.fp8.shuffle_weight", create=True - ) as shuffle, - ): - method.process_weights_after_loading_block_quant(layer) - - shuffle.assert_not_called() - - def test_borrowed_delegate_skips_aiter_weight_shuffle(self): - """MxFP4 delegates do not own a runner, so global AITER enablement must - not make weight loading dereference or prepare an absent runner.""" - method = self._make_block_fp8_method() - method.convert_mxfp8_to_block = True - method.use_mxfp8 = True - layer = SimpleNamespace( - w13_weight=torch.nn.Parameter(torch.arange(16.0).reshape(1, 4, 4)), - w2_weight=torch.nn.Parameter(torch.arange(16.0).reshape(1, 4, 4)), - ) - - with ( - patch("sglang.srt.layers.quantization.fp8._use_aiter", True), - patch("sglang.srt.layers.quantization.fp8._is_fp8_fnuz", False), - patch.object(method, "_convert_mxfp8_moe_to_block_fp8"), - patch( - "sglang.srt.layers.quantization.fp8.shuffle_weight", create=True - ) as shuffle, - ): - method.process_weights_after_loading_block_quant(layer) - - shuffle.assert_not_called() - - def test_aiter_runner_keeps_preshuffled_weight_layout(self): - method = self._make_block_fp8_method() - method.convert_mxfp8_to_block = True - method.use_mxfp8 = True - method.runner = SimpleNamespace(runner_backend=MoeRunnerBackend.AITER) - method._owns_moe_runner = True - original_w13 = torch.arange(16.0).reshape(1, 4, 4) - original_w2 = torch.arange(16.0, 32.0).reshape(1, 4, 4) - layer = SimpleNamespace( - w13_weight=torch.nn.Parameter(original_w13.clone()), - w2_weight=torch.nn.Parameter(original_w2.clone()), - ) - - def add_one(weight, _tile): - return weight + 1 - - with ( - patch("sglang.srt.layers.quantization.fp8._use_aiter", True), - patch("sglang.srt.layers.quantization.fp8._is_fp8_fnuz", False), - patch.object(method, "_convert_mxfp8_moe_to_block_fp8"), - patch( - "sglang.srt.layers.quantization.fp8.shuffle_weight", - side_effect=add_one, - create=True, - ) as shuffle, - ): - method.process_weights_after_loading_block_quant(layer) - - self.assertEqual(shuffle.call_count, 2) - torch.testing.assert_close(layer.w13_weight, original_w13 + 1) - torch.testing.assert_close(layer.w2_weight, original_w2 + 1) - if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/layers/quantization/test_quark_config.py b/test/registered/unit/layers/quantization/test_quark_config.py index db59bb4e53eb3..c2990d79bf10f 100644 --- a/test/registered/unit/layers/quantization/test_quark_config.py +++ b/test/registered/unit/layers/quantization/test_quark_config.py @@ -5,13 +5,10 @@ register_cpu_ci(est_time=5, suite="base-a-test-cpu") import unittest -from copy import deepcopy from unittest.mock import patch import torch -from sglang.srt.layers.linear import LinearBase -from sglang.srt.layers.quantization.fp8 import Fp8LinearMethod from sglang.srt.layers.quantization.quark.quark import ( QuarkConfig, _build_mixed_precision_layer_quant_config, @@ -19,7 +16,6 @@ _parse_nvfp4_excludes, ) from sglang.srt.layers.quantization.quark.utils import check_equal_or_regex_match -from sglang.srt.models.glm5_next import Glm5NextForConditionalGeneration from sglang.test.test_utils import CustomTestCase _GET_CAP = "sglang.srt.layers.quantization.quark.quark.get_device_capability" @@ -211,115 +207,5 @@ def test_already_regex_entries_pass_through_and_match(self): ) -class TestQuarkPerLayerBlockFp8(CustomTestCase): - _BLOCK_FP8_CONFIG = { - "weight": { - "dtype": "fp8_e4m3", - "qscheme": "per_block", - "block_size": [128, 128], - "is_dynamic": False, - }, - "input_tensors": { - "dtype": "fp8_e4m3", - "qscheme": "per_group", - "group_size": 128, - "is_dynamic": True, - }, - "output_tensors": None, - "bias": None, - } - - def _build_bare_config(self) -> QuarkConfig: - config = _bare_config() - config.quant_config = { - "layer_quant_config": { - "model.language_model.layers.0.mlp.down_proj": self._BLOCK_FP8_CONFIG - }, - "layer_type_quant_config": {}, - "global_quant_config": { - "weight": { - "dtype": "fp4", - "qscheme": "per_group", - "group_size": 32, - "is_dynamic": False, - "scale_format": "e8m0", - }, - "input_tensors": { - "dtype": "fp4", - "qscheme": "per_group", - "group_size": 32, - "is_dynamic": True, - "scale_format": "e8m0", - }, - }, - } - config.exclude_layers = [] - config.kv_cache_group = [] - config.packed_modules_mapping = {} - config.excluded_fp8_config = None - config._online_quantized_layers = set() - return config - - def test_model_mapper_rewrites_explicit_layer_config(self): - config = self._build_bare_config() - - config.apply_weight_name_mapper( - Glm5NextForConditionalGeneration.hf_to_sglang_mapper - ) - - self.assertIn( - "model.layers.0.mlp.down_proj", - config.quant_config["layer_quant_config"], - ) - - def test_model_mapper_rewrites_fused_visual_exclusion(self): - config = self._build_bare_config() - config.exclude_layers = ["model.visual.blocks.0.attn.qkv"] - - config.apply_weight_name_mapper( - Glm5NextForConditionalGeneration.hf_to_sglang_mapper - ) - - self.assertEqual( - config.exclude_layers, - ["visual.blocks.0.attn.qkv_proj"], - ) - self.assertNotIn( - "model.language_model.layers.0.mlp.down_proj", - config.quant_config["layer_quant_config"], - ) - - def test_explicit_block_fp8_linear_uses_fp8_method(self): - config = self._build_bare_config() - config.apply_weight_name_mapper( - Glm5NextForConditionalGeneration.hf_to_sglang_mapper - ) - layer = LinearBase.__new__(LinearBase) - - method = config.get_quant_method(layer, "model.layers.0.mlp.down_proj") - - self.assertIsInstance(method, Fp8LinearMethod) - self.assertTrue(method.quant_config.is_checkpoint_fp8_serialized) - self.assertEqual(method.quant_config.weight_block_size, [128, 128]) - - def test_dynamic_block_fp8_weight_is_not_treated_as_serialized(self): - layer_config = deepcopy(self._BLOCK_FP8_CONFIG) - layer_config["weight"]["is_dynamic"] = True - - self.assertIsNone(QuarkConfig._get_block_fp8_config(layer_config, {})) - - def test_unmatched_layer_still_uses_global_quark_config(self): - config = self._build_bare_config() - config.apply_weight_name_mapper( - Glm5NextForConditionalGeneration.hf_to_sglang_mapper - ) - - matched = config._find_matched_config( - "model.layers.4.mlp.down_proj", torch.nn.Module() - ) - - self.assertEqual(matched["weight"]["dtype"], "fp4") - - if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/layers/quantization/test_quark_utils.py b/test/registered/unit/layers/quantization/test_quark_utils.py index cc027a743e163..606dd346d12db 100644 --- a/test/registered/unit/layers/quantization/test_quark_utils.py +++ b/test/registered/unit/layers/quantization/test_quark_utils.py @@ -8,10 +8,7 @@ import torch -from sglang.srt.layers.quantization.quark.utils import ( - e8m0_to_f32, - should_ignore_layer, -) +from sglang.srt.layers.quantization.quark.utils import e8m0_to_f32 from sglang.test.test_utils import CustomTestCase @@ -69,16 +66,5 @@ def test_cuda_parity(self): self.assertTrue(torch.isnan(out[2]).item()) -class TestShouldIgnoreLayer(CustomTestCase): - def test_direct_fused_module_exclusion_takes_precedence(self): - self.assertTrue( - should_ignore_layer( - "visual.blocks.0.attn.qkv_proj", - ["visual.blocks.0.attn.qkv_proj"], - {"qkv_proj": ["q_proj", "k_proj", "v_proj"]}, - ) - ) - - if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/layers/test_dsa_indexer_kpool_backend.py b/test/registered/unit/layers/test_dsa_indexer_kpool_backend.py deleted file mode 100644 index 8f75c9b8ba934..0000000000000 --- a/test/registered/unit/layers/test_dsa_indexer_kpool_backend.py +++ /dev/null @@ -1,196 +0,0 @@ -import sys -import unittest -from types import ModuleType -from unittest.mock import MagicMock, patch - -import torch - -from sglang.srt.layers.attention.dsa import dsa_indexer_kpool -from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( - _topk_from_pooled_history_logits_unfused, - topk_from_pooled_history_logits, -) -from sglang.test.ci.ci_register import register_cpu_ci -from sglang.test.test_utils import CustomTestCase - -register_cpu_ci(est_time=1, suite="base-a-test-cpu") - - -class TestKPoolMqaBackend(CustomTestCase): - def test_cuda_tilelang_selector_reads_heads_from_unexpanded_query(self): - with ( - patch.object(dsa_indexer_kpool, "is_cuda", return_value=True), - patch("torch.cuda.get_device_capability", return_value=(9, 0)), - ): - self.assertFalse( - dsa_indexer_kpool.IndexerKPool._should_use_tilelang_paged_mqa_logits( - torch.empty(1, 32, 128) - ) - ) - self.assertTrue( - dsa_indexer_kpool.IndexerKPool._should_use_tilelang_paged_mqa_logits( - torch.empty(1, 16, 128) - ) - ) - - def test_rocm_uses_aiter_mqa_logits(self): - marker = object() - aiter_impl = MagicMock(return_value=marker) - module = ModuleType("aiter.ops.triton.fp8_mqa_logits") - module.fp8_mqa_logits = aiter_impl - - args = tuple(object() for _ in range(6)) - with ( - patch.object(dsa_indexer_kpool, "is_hip", return_value=True), - patch.dict( - sys.modules, - {"aiter.ops.triton.fp8_mqa_logits": module}, - ), - ): - result = dsa_indexer_kpool.IndexerKPool._fp8_mqa_logits( - *args, clean_logits=False - ) - - self.assertIs(result, marker) - aiter_impl.assert_called_once_with(*args, clean_logits=False) - - def test_cuda_keeps_deep_gemm_mqa_logits(self): - marker = object() - deep_gemm = MagicMock() - deep_gemm.fp8_mqa_logits.return_value = marker - q_fp8, k_fp8, k_scale, weights, starts, ends = (object() for _ in range(6)) - - with ( - patch.object(dsa_indexer_kpool, "is_hip", return_value=False), - patch.object(dsa_indexer_kpool, "deep_gemm", deep_gemm, create=True), - ): - result = dsa_indexer_kpool.IndexerKPool._fp8_mqa_logits( - q_fp8, - k_fp8, - k_scale, - weights, - starts, - ends, - clean_logits=True, - ) - - self.assertIs(result, marker) - deep_gemm.fp8_mqa_logits.assert_called_once_with( - q_fp8, - (k_fp8, k_scale), - weights, - starts, - ends, - clean_logits=True, - ) - - def test_portable_topk_masks_invalid_groups_and_expands(self): - logits = torch.tensor([[0.1, 0.9, 0.8, 50.0]], dtype=torch.float32) - result = _topk_from_pooled_history_logits_unfused( - logits=logits, - group_lengths=torch.tensor([3], dtype=torch.int32), - pool_size=2, - topk=4, - ) - - torch.testing.assert_close( - result, - torch.tensor([[2, 3, 4, 5]], dtype=torch.int32), - ) - - def test_rocm_uses_fused_kpool_topk_for_supported_group_count(self): - logits = MagicMock() - logits.ndim = 2 - logits.shape = (1, 512) - logits.is_cuda = True - logits.dtype = torch.float32 - group_lengths = torch.tensor([256], dtype=torch.int32) - marker = MagicMock() - marker.shape = (1, 2048) - - with ( - patch( - "sglang.srt.layers.attention.dsa.kpool_fp8_index.is_hip", - return_value=True, - ), - patch( - "sglang.kernels.ops.moe.kpool_topk_transform.fast_kpool_topk_transform_fused", - return_value=marker, - ) as fused, - patch( - "sglang.srt.layers.attention.dsa.kpool_fp8_index._topk_from_pooled_history_logits_unfused" - ) as unfused, - ): - result = topk_from_pooled_history_logits( - logits=logits, - group_lengths=group_lengths, - pool_size=4, - topk=2048, - ) - - self.assertIs(result, marker) - fused.assert_called_once() - unfused.assert_not_called() - - def test_rocm_keeps_2048_group_topk_on_unfused_path(self): - logits = MagicMock() - logits.ndim = 2 - logits.shape = (1, 2048) - logits.is_cuda = True - logits.dtype = torch.float32 - group_lengths = torch.tensor([2048], dtype=torch.int32) - marker = object() - - with ( - patch( - "sglang.srt.layers.attention.dsa.kpool_fp8_index.is_hip", - return_value=True, - ), - patch( - "sglang.srt.layers.attention.dsa.kpool_fp8_index._topk_from_pooled_history_logits_unfused", - return_value=marker, - ) as unfused, - ): - result = topk_from_pooled_history_logits( - logits=logits, - group_lengths=group_lengths, - pool_size=4, - topk=8192, - ) - - self.assertIs(result, marker) - unfused.assert_called_once() - - def test_cuda_keeps_supported_group_count_on_fused_path(self): - logits = MagicMock() - logits.ndim = 2 - logits.shape = (1, 512) - logits.is_cuda = True - logits.dtype = torch.float32 - group_lengths = torch.tensor([256], dtype=torch.int32) - marker = MagicMock() - marker.shape = (1, 2048) - - with ( - patch( - "sglang.srt.layers.attention.dsa.kpool_fp8_index.is_hip", - return_value=False, - ), - patch( - "sglang.kernels.ops.moe.kpool_topk_transform.fast_kpool_topk_transform_fused", - return_value=marker, - ) as fused, - ): - result = topk_from_pooled_history_logits( - logits=logits, - group_lengths=group_lengths, - pool_size=4, - topk=2048, - ) - - self.assertIs(result, marker) - fused.assert_called_once() - - -if __name__ == "__main__": - unittest.main() diff --git a/test/registered/unit/models/test_glm5_next_aiter_mhc.py b/test/registered/unit/models/test_glm5_next_aiter_mhc.py deleted file mode 100644 index 7caad60cf1834..0000000000000 --- a/test/registered/unit/models/test_glm5_next_aiter_mhc.py +++ /dev/null @@ -1,243 +0,0 @@ -import sys -from types import ModuleType, SimpleNamespace -from unittest.mock import MagicMock, patch - -import pytest -import torch -from torch import nn - -from sglang.kernels.ops.layernorm import mhc -from sglang.srt.layers.communicator_mhc import MHCState -from sglang.srt.models import glm5_next -from sglang.srt.models.glm5_next import Glm5NextDecoderLayer -from sglang.test.ci.ci_register import register_cpu_ci - -register_cpu_ci(est_time=6, suite="base-a-test-cpu") - - -def _fake_aiter_mhc_module(*, mhc_pre=None, mhc_post=None): - aiter_module = ModuleType("aiter") - ops_module = ModuleType("aiter.ops") - mhc_module = ModuleType("aiter.ops.mhc") - if mhc_pre is not None: - mhc_module.mhc_pre = mhc_pre - if mhc_post is not None: - mhc_module.mhc_post = mhc_post - aiter_module.ops = ops_module - ops_module.mhc = mhc_module - return { - "aiter": aiter_module, - "aiter.ops": ops_module, - "aiter.ops.mhc": mhc_module, - } - - -def test_aiter_mhc_gate_is_rocm_gfx95_only(): - with ( - patch.object(mhc, "is_hip", return_value=True), - patch.object(mhc, "is_gfx95_supported", return_value=True), - patch.object(mhc, "get_bool_env_var", return_value=True), - patch.object(mhc, "_AITER_MHC_RUNTIME_DISABLED", False), - ): - assert mhc._use_aiter_mhc() - - for is_hip, is_gfx95, use_aiter in ( - (False, True, True), - (True, False, True), - (True, True, False), - ): - with ( - patch.object(mhc, "is_hip", return_value=is_hip), - patch.object(mhc, "is_gfx95_supported", return_value=is_gfx95), - patch.object(mhc, "get_bool_env_var", return_value=use_aiter), - patch.object(mhc, "_AITER_MHC_RUNTIME_DISABLED", False), - ): - assert not mhc._use_aiter_mhc() - - -def test_aiter_mhc_pre_dispatch_forwards_norm_contract(): - residual = torch.randn(2, 4, 8) - fn = torch.randn(24, 32) - hc_scale = torch.randn(3) - hc_base = torch.randn(24) - norm_weight = torch.randn(8) - expected = ( - torch.randn(2, 4, 1), - torch.randn(2, 4, 4), - torch.randn(2, 8), - ) - fake_pre = MagicMock(return_value=expected) - - with ( - patch.dict(sys.modules, _fake_aiter_mhc_module(mhc_pre=fake_pre)), - patch.object(mhc, "_use_aiter_mhc", return_value=True), - patch.object(mhc, "_AITER_MHC_ACTIVE_LOGGED", False), - ): - actual = mhc._mhc_pre_dispatch( - residual=residual, - fn=fn, - hc_scale=hc_scale, - hc_base=hc_base, - rms_eps=1e-6, - hc_pre_eps=1e-5, - hc_sinkhorn_eps=1e-5, - hc_post_mult_value=2.0, - sinkhorn_repeat=20, - norm_weight=norm_weight, - norm_eps=1e-4, - ) - - assert actual[0] is expected[0] - assert actual[1] is expected[1] - assert actual[2] is expected[2] - assert actual[3] is True - fake_pre.assert_called_once_with( - residual, - fn, - hc_scale, - hc_base, - 1e-6, - 1e-5, - 1e-5, - 2.0, - 20, - norm_weight=norm_weight, - norm_eps=1e-4, - ) - - -def test_aiter_mhc_post_dispatch_uses_preallocated_output(): - x = torch.randn(2, 8) - residual = torch.randn(2, 4, 8) - post = torch.randn(2, 4, 1) - comb = torch.randn(2, 4, 4) - - def fake_post(out, x_arg, residual_arg, post_arg, comb_arg): - assert x_arg is x - assert residual_arg is residual - assert post_arg is post - assert comb_arg is comb - out.copy_(residual + 1) - - with ( - patch.dict(sys.modules, _fake_aiter_mhc_module(mhc_post=fake_post)), - patch.object(mhc, "_use_aiter_mhc", return_value=True), - ): - actual = mhc._mhc_post_dispatch(x, residual, post, comb) - - torch.testing.assert_close(actual, residual + 1) - - -class _AddOneNorm(nn.Module): - def __init__(self, hidden_size): - super().__init__() - self.weight = nn.Parameter(torch.ones(hidden_size)) - self.variance_epsilon = 1e-6 - - def forward(self, x): - return x + 1 - - -def test_mhc_state_uses_optional_fused_attention_to_mlp_boundary(): - hidden_states = torch.randn(2, 8) - residual = torch.randn(2, 32) - next_hidden_states = torch.randn(2, 8) - next_residual = torch.randn(2, 32) - next_h_res = torch.randn(2, 16) - next_h_post = torch.randn(2, 4) - fused = MagicMock( - return_value=( - next_hidden_states, - next_residual, - next_h_res, - next_h_post, - False, - ) - ) - initial_h_res = torch.randn(2, 16) - initial_h_post = torch.randn(2, 4) - state = MHCState( - hc_mult=4, - hc_attn_pre=MagicMock(), - hc_ffn_pre=MagicMock(side_effect=AssertionError("unfused pre called")), - hc_post=MagicMock(side_effect=AssertionError("unfused post called")), - hc_attn_to_mlp=fused, - h_res=initial_h_res, - h_post=initial_h_post, - ) - norm = _AddOneNorm(8) - - actual_hidden_states, actual_residual = state.attn_to_mlp( - hidden_states, residual, norm - ) - - torch.testing.assert_close(actual_hidden_states, next_hidden_states + 1) - assert actual_residual is next_residual - assert state.h_res is next_h_res - assert state.h_post is next_h_post - fused.assert_called_once() - call_args = fused.call_args.args - assert call_args[0] is hidden_states - assert call_args[1] is residual - assert call_args[2] is initial_h_res - assert call_args[3] is initial_h_post - torch.testing.assert_close(call_args[4], norm.weight) - assert call_args[5] == norm.variance_epsilon - - -def test_glm_aiter_mhc_boundary_preserves_communicator_shapes(): - layer = Glm5NextDecoderLayer.__new__(Glm5NextDecoderLayer) - nn.Module.__init__(layer) - layer.config = SimpleNamespace( - hc_mult=4, - rms_norm_eps=1e-6, - hc_eps=1e-5, - hc_sinkhorn_iters=20, - ) - layer.hc_ffn_fn = nn.Parameter(torch.randn(24, 32)) - layer.hc_ffn_scale = nn.Parameter(torch.randn(3)) - layer.hc_ffn_base = nn.Parameter(torch.randn(24)) - - hidden_states = torch.randn(2, 8) - residual = torch.randn(2, 32) - h_res = torch.randn(2, 16) - h_post = torch.randn(2, 4) - next_residual = torch.randn(2, 4, 8) - next_hidden_states = torch.randn(2, 8) - next_h_post = torch.randn(2, 4) - next_h_res = torch.randn(2, 4, 4) - - with ( - patch( - "sglang.srt.models.deepseek_common.amd.deepseek_v4_fused_mhc.apply_mhc_post_pre_boundary", - return_value=( - next_residual, - next_hidden_states, - next_h_post, - next_h_res, - True, - ), - ) as fused, - patch.object(glm5_next, "_GLM_AITER_FUSED_MHC_LOGGED", False), - ): - actual = layer.hc_attn_to_mlp( - hidden_states, - residual, - h_res, - h_post, - torch.ones(8), - 1e-6, - ) - - actual_hidden, actual_residual, actual_h_res, actual_h_post, norm_fused = actual - assert actual_hidden is next_hidden_states - torch.testing.assert_close(actual_residual, next_residual.reshape(2, 32)) - torch.testing.assert_close(actual_h_res, next_h_res.reshape(2, 16)) - torch.testing.assert_close(actual_h_post, next_h_post) - assert norm_fused - assert fused.call_args.kwargs["fn_transpose"] is True - assert fused.call_args.kwargs["residual"].shape == (2, 4, 8) - - -if __name__ == "__main__": - sys.exit(pytest.main([__file__, "-v"])) diff --git a/test/registered/unit/models/test_nope_mha_k_cast.py b/test/registered/unit/models/test_nope_mha_k_cast.py index 7b5c6748327c0..5e9cfef4f908f 100644 --- a/test/registered/unit/models/test_nope_mha_k_cast.py +++ b/test/registered/unit/models/test_nope_mha_k_cast.py @@ -5,10 +5,7 @@ import pytest import torch -from sglang.srt.models.deepseek_common.attention_forward_methods import ( - forward_mha, - forward_mha_rocm, -) +from sglang.srt.models.deepseek_common.attention_forward_methods import forward_mha from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci( @@ -51,20 +48,5 @@ def test_nope_mha_k_cast(backend, kv_cache_dtype, pool_dtype, expected_dtype): assert out.dtype == expected_dtype -@pytest.mark.parametrize("k_pe", [None, torch.empty(4, 1, 0)]) -def test_nope_mha_k_rocm_skips_empty_rope_tail(k_pe): - fake_self = SimpleNamespace(qk_rope_head_dim=0) - k_nope = torch.randn(4, 2, 128, dtype=torch.bfloat16) - - out = forward_mha_rocm.DeepseekMHARocmForwardMixin._concat_and_cast_mha_k_rocm( - fake_self, - k_nope, - k_pe, - ) - - torch.testing.assert_close(out, k_nope) - assert out.is_contiguous() - - if __name__ == "__main__": sys.exit(pytest.main([__file__])) diff --git a/test/registered/unit/models/test_shared_experts_fusion_gates.py b/test/registered/unit/models/test_shared_experts_fusion_gates.py index 5ddaf2d696280..e9a7ff710ee7a 100644 --- a/test/registered/unit/models/test_shared_experts_fusion_gates.py +++ b/test/registered/unit/models/test_shared_experts_fusion_gates.py @@ -215,62 +215,6 @@ def test_the_dsa_variant_declares_its_own_architecture(self): ) -class TestGlm5NextGate(_FusionGateCase): - def _config(self): - return SimpleNamespace(n_shared_experts=1) - - def _reason_for_backend( - self, - *, - is_cuda=False, - use_aiter_gfx95=False, - device_sm=None, - moe_ep_size=1, - deepep=False, - ): - import sglang.srt.models.glm5_next as glm5_next - - backend = SimpleNamespace(is_deepep=lambda: deepep) - with ( - unittest.mock.patch.object(glm5_next, "_is_cuda", is_cuda), - unittest.mock.patch.object(glm5_next, "_use_aiter_gfx95", use_aiter_gfx95), - unittest.mock.patch.object(glm5_next, "_device_sm", device_sm), - unittest.mock.patch.object( - glm5_next, "get_moe_a2a_backend", return_value=backend - ), - ): - return self._reason( - glm5_next.Glm5NextForConditionalGeneration, - self._config(), - moe_ep_size=moe_ep_size, - ) - - def test_aiter_gfx95_enables_shared_expert_fusion(self): - self.assertIsNone(self._reason_for_backend(use_aiter_gfx95=True)) - - def test_unsupported_non_cuda_backend_disables_shared_expert_fusion(self): - self.assertIn("requires CUDA", self._reason_for_backend()) - - def test_cuda_sm80_path_is_unchanged(self): - self.assertIsNone(self._reason_for_backend(is_cuda=True, device_sm=80)) - self.assertIn( - "SM80 or newer", - self._reason_for_backend(is_cuda=True, device_sm=75), - ) - - def test_expert_parallelism_still_disables_shared_expert_fusion(self): - self.assertIn( - "expert parallelism", - self._reason_for_backend(use_aiter_gfx95=True, moe_ep_size=2), - ) - - def test_deepep_still_disables_shared_expert_fusion(self): - self.assertIn( - "Deepep", - self._reason_for_backend(use_aiter_gfx95=True, deepep=True), - ) - - class TestMiniMaxGates(_FusionGateCase): def test_a_config_without_shared_experts_cannot_fuse(self): from sglang.srt.models.minimax_m3 import MiniMaxM3SparseForCausalLM From 58a2a90862e5d1fc2f54b5d4ffa8371ef3469ad3 Mon Sep 17 00:00:00 2001 From: Baizhou Zhang Date: Tue, 1 Sep 2026 01:25:02 -0700 Subject: [PATCH 21/44] Fix GLM-5.3 Flash CI regressions after latest main merge (#37366) --- .../srt/layers/attention/hybrid_linear_attn_backend.py | 6 +++++- python/sglang/srt/mem_cache/hisparse_memory_pool.py | 10 ++++++++++ python/sglang/srt/mem_cache/memory_pool.py | 6 ++++-- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/python/sglang/srt/layers/attention/hybrid_linear_attn_backend.py b/python/sglang/srt/layers/attention/hybrid_linear_attn_backend.py index 8419ffad389bd..a5f02f714e04d 100644 --- a/python/sglang/srt/layers/attention/hybrid_linear_attn_backend.py +++ b/python/sglang/srt/layers/attention/hybrid_linear_attn_backend.py @@ -1022,7 +1022,11 @@ def __init__( full_attn_backend, "extend_dummy_seqs_capped_by_req_pool", False ) or getattr(linear_attn_backend, "extend_dummy_seqs_capped_by_req_pool", False) self.supports_overlap_plan_stream_graph_load = bool( - linear_attn_backend.supports_overlap_plan_stream_graph_load + getattr( + linear_attn_backend, + "supports_overlap_plan_stream_graph_load", + False, + ) ) @property diff --git a/python/sglang/srt/mem_cache/hisparse_memory_pool.py b/python/sglang/srt/mem_cache/hisparse_memory_pool.py index ad45ce76a1781..4808dadd34645 100644 --- a/python/sglang/srt/mem_cache/hisparse_memory_pool.py +++ b/python/sglang/srt/mem_cache/hisparse_memory_pool.py @@ -40,6 +40,11 @@ def __init__( kv_cache_dim: int, start_layer: Optional[int] = None, end_layer: Optional[int] = None, + index_kpool: int = 1, + index_kpool_compress: bool = False, + tail_extra_slots: int = 0, + max_running_requests: Optional[int] = None, + skip_topk_layers: Optional[list[bool]] = None, host_to_device_ratio: int = 2, ): super().__init__( @@ -56,6 +61,11 @@ def __init__( start_layer=start_layer, end_layer=end_layer, index_buf_size=size * host_to_device_ratio, + index_kpool=index_kpool, + index_kpool_compress=index_kpool_compress, + tail_extra_slots=tail_extra_slots, + max_running_requests=max_running_requests, + skip_topk_layers=skip_topk_layers, ) self.bytes_per_token = self.kv_cache_dim * self.dtype.itemsize diff --git a/python/sglang/srt/mem_cache/memory_pool.py b/python/sglang/srt/mem_cache/memory_pool.py index 3e4235e4acb60..24bb9cd533697 100644 --- a/python/sglang/srt/mem_cache/memory_pool.py +++ b/python/sglang/srt/mem_cache/memory_pool.py @@ -3546,7 +3546,7 @@ def _read_scales(self, idx, loc): ) return self.k_scale_buffer[idx][loc], self.v_scale_buffer[idx][loc] - def get_cpu_copy(self, indices, mamba_indices=None): + def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): # The scales travel with their fp8 payload; a restored slot dequantizes # against mismatched exponents without them. assert not self.use_hnd, ( @@ -3576,7 +3576,9 @@ def get_cpu_copy(self, indices, mamba_indices=None): current_platform.synchronize() return kv_cache_cpu - def load_cpu_copy(self, kv_cache_cpu, indices, mamba_indices=None): + def load_cpu_copy( + self, kv_cache_cpu, indices, mamba_indices=None, req_pool_index=None + ): assert not self.use_hnd, ( "CPU KV offload indexes by slot (NHD); HND KV cache " "(SGLANG_USE_HND_KVCACHE) is not supported with CPU offload yet." From fe236ea6c3338c76670c6b27893bb498f667ddf5 Mon Sep 17 00:00:00 2001 From: Xinyuan Tong Date: Tue, 1 Sep 2026 07:15:29 +0000 Subject: [PATCH 22/44] fix(modelopt_fp4): skip NVFP4 swiglu-fusion interleave for shared experts with swiglu_limit DeepseekV2MoE gates the shared-expert NVFP4 swiglu-fusion weight interleave on SM100 + fc1_n % 128, but DeepseekV2MLP.forward only takes the fused path when swiglu_limit is None. For clamped-swiglu models (e.g. GLM-5 family, swiglu_limit=10.0) with separate shared experts (modelopt_fp4, shared-experts fusion disabled under moe_ep_size > 1), process_weights_after_loading interleaves and frees layer.weight (torch.empty(0), 1-D) while forward falls back to the unfused apply: modelopt_quant.py apply: w_n, _ = layer.weight.shape ValueError: not enough values to unpack (expected 2, got 1) on the first real forward. TP-only is unaffected only because shared experts are fused into the FusedMoE there. Add the missing swiglu_limit check so the interleave gate matches the forward condition. --- python/sglang/srt/models/deepseek_v2.py | 1 + 1 file changed, 1 insertion(+) diff --git a/python/sglang/srt/models/deepseek_v2.py b/python/sglang/srt/models/deepseek_v2.py index ea4871cecfa50..b203d05d3bb41 100644 --- a/python/sglang/srt/models/deepseek_v2.py +++ b/python/sglang/srt/models/deepseek_v2.py @@ -781,6 +781,7 @@ def __init__( ModelOptFp4LinearMethod, ) and fc1_n % 128 == 0 + and self.shared_experts.swiglu_limit is None and not check_cuda_graph_backend(Phase.PREFILL, Backend.TC_PIECEWISE) ): self.shared_experts.gate_up_proj._interleave_for_swiglu_fusion = True From 0a6b5d8c7b92825eb2687946aba2c5f728d7382e Mon Sep 17 00:00:00 2001 From: Baizhou Zhang Date: Tue, 1 Sep 2026 16:52:12 -0700 Subject: [PATCH 23/44] test: add GLM-5.3 Flash DFlash2 B200 coverage (#37486) --- .../models_e2e/test_glm53_flash_b200.py | 27 ++++++++++++++++--- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/test/registered/models_e2e/test_glm53_flash_b200.py b/test/registered/models_e2e/test_glm53_flash_b200.py index 00a0813d59c64..e8b16685da116 100644 --- a/test/registered/models_e2e/test_glm53_flash_b200.py +++ b/test/registered/models_e2e/test_glm53_flash_b200.py @@ -1,8 +1,8 @@ """B200 per-commit coverage for the GLM-5.3-Flash serving recipes. -Runs the Low Latency and High Throughput TP4/EP4 recipes on four B200 GPUs. -Both recipes must retain GSM8K accuracy; the Low Latency recipe also checks -EAGLE speculative acceptance and single-request decode performance. +Runs the Low Latency, DFlash2, and High Throughput TP4/EP4 recipes on four +B200 GPUs. All recipes must retain GSM8K accuracy; the Low Latency recipe also +checks EAGLE speculative acceptance and single-request decode performance. """ import unittest @@ -19,9 +19,10 @@ try_cached_model, ) -register_cuda_ci(est_time=1800, stage="base-c", runner_config="4-gpu-b200") +register_cuda_ci(est_time=2400, stage="base-c", runner_config="4-gpu-b200") MODEL_PATH = "zai-org/GLM-5.3-Flash" +DFLASH2_DRAFT_MODEL_PATH = "incoai/GLM-5.3-Flash-DFlash2" SERVER_LAUNCH_TIMEOUT = 3600 GPU_IDLE_TIMEOUT = 120 @@ -115,5 +116,23 @@ class TestGLM53FlashB200HighThroughput( ] +class TestGLM53FlashB200DFlash2( + GSM8KMixin, + _GLM53FlashB200Base, +): + gsm8k_score_threshold = 0.93 + gsm8k_num_examples = 500 + gsm8k_num_shots = 20 + server_args = [ + *COMMON_SERVER_ARGS, + "--speculative-algorithm", + "DFLASH", + "--speculative-draft-model-path", + DFLASH2_DRAFT_MODEL_PATH, + "--speculative-draft-attention-backend", + "fa4", + ] + + if __name__ == "__main__": unittest.main() From 515e865189dd2491fcdae8d70c06e52ecfcb96ba Mon Sep 17 00:00:00 2001 From: Baizhou Zhang Date: Tue, 1 Sep 2026 18:43:52 -0700 Subject: [PATCH 24/44] Temporarily Remove GLM-5.3 Flash prefill CP support (#37484) --- python/sglang/srt/configs/glm5_next.py | 10 +- python/sglang/srt/disaggregation/nixl/conn.py | 46 ++-- .../layers/attention/dsa/dsa_indexer_kpool.py | 252 +----------------- .../sglang/srt/layers/attention/dsa/utils.py | 93 ------- .../sglang/srt/layers/communicator_dsa_cp.py | 27 +- python/sglang/srt/layers/communicator_mhc.py | 7 +- .../srt/layers/communicator_mhc_hybrid_cp.py | 221 --------------- python/sglang/srt/layers/cp/utils.py | 1 + .../srt/mem_cache/dsa_cache_layer_split.py | 18 +- .../srt/mem_cache/kv_cache_configurator.py | 8 - python/sglang/srt/mem_cache/memory_pool.py | 54 +--- .../srt/model_executor/pool_configurator.py | 77 +++--- python/sglang/srt/models/glm5_next.py | 196 +------------- 13 files changed, 83 insertions(+), 927 deletions(-) delete mode 100644 python/sglang/srt/layers/communicator_mhc_hybrid_cp.py diff --git a/python/sglang/srt/configs/glm5_next.py b/python/sglang/srt/configs/glm5_next.py index ddeaf0efdac01..17c149ff02ebb 100644 --- a/python/sglang/srt/configs/glm5_next.py +++ b/python/sglang/srt/configs/glm5_next.py @@ -262,16 +262,8 @@ def full_attention_layer_ids(self): @property def mamba2_cache_params(self) -> KimiLinearCacheParams: - from sglang.srt.layers.attention.dsa.utils import is_dsa_enable_prefill_cp - - head_shard_size = ( - get_parallel().attn_cp_size - if is_dsa_enable_prefill_cp() - else get_parallel().attn_tp_size - ) - shape = KimiLinearStateShape.create( - tp_world_size=head_shard_size, + tp_world_size=get_parallel().attn_tp_size, num_heads=self.linear_attn_config["num_heads"], head_dim=self.linear_attn_config["head_dim"], conv_kernel_size=self.linear_attn_config["short_conv_kernel_size"], diff --git a/python/sglang/srt/disaggregation/nixl/conn.py b/python/sglang/srt/disaggregation/nixl/conn.py index 3814a946d6036..1411a21af640a 100644 --- a/python/sglang/srt/disaggregation/nixl/conn.py +++ b/python/sglang/srt/disaggregation/nixl/conn.py @@ -2458,11 +2458,7 @@ def maybe_send_extra( dst_layer_ids=dst_lids, ) elif st == StateType.DSA_TAIL: - if ( - self.attn_cp_size > 1 - and self.attn_cp_rank != 0 - and not self.server_args.enable_dsa_cache_layer_split - ): + if self.attn_cp_size > 1 and self.attn_cp_rank != 0: skipped_replicated_state = True h = None else: @@ -2478,31 +2474,23 @@ def maybe_send_extra( comp_notif, ) elif st == StateType.DSA: - if ( - self.attn_cp_size > 1 - and self.attn_cp_rank != 0 - and not self.server_args.enable_dsa_cache_layer_split - ): - skipped_replicated_state = True - h = None - else: - if len(src_indices) != len(dst_indices): - raise RuntimeError( - f"State index length mismatch at component {i}: " - f"prefill={len(src_indices)}, dst={len(dst_indices)}" - ) - h = self._send_kvcache_generic( - peer_name=peer_name, - src_data_ptrs=src_ptrs, - dst_data_ptrs=dst_ptrs, - item_lens=src_lens, - prefill_data_indices=np.array(src_indices, dtype=np.int32), - dst_data_indices=np.array(dst_indices, dtype=np.int32), - dst_gpu_id=dst_gpu_id, - notif=comp_notif, - state_type=st, - force_flat=True, + if len(src_indices) != len(dst_indices): + raise RuntimeError( + f"State index length mismatch at component {i}: " + f"prefill={len(src_indices)}, dst={len(dst_indices)}" ) + h = self._send_kvcache_generic( + peer_name=peer_name, + src_data_ptrs=src_ptrs, + dst_data_ptrs=dst_ptrs, + item_lens=src_lens, + prefill_data_indices=np.array(src_indices, dtype=np.int32), + dst_data_indices=np.array(dst_indices, dtype=np.int32), + dst_gpu_id=dst_gpu_id, + notif=comp_notif, + state_type=st, + force_flat=True, + ) elif st in (StateType.SWA, StateType.SWA_RING, StateType.C128_STATE): if not self.is_mla_backend and self.attn_tp_size != decode_tp_size: raise RuntimeError( diff --git a/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py b/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py index 2ee56808deddd..266c3c6d9f9e7 100644 --- a/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py +++ b/python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py @@ -29,16 +29,9 @@ from sglang.srt.environ import envs from sglang.srt.layers import deep_gemm_wrapper -from sglang.srt.layers.attention.dsa.utils import ( - cp_zigzag_full_plan_rows, - dsa_use_prefill_cp, - is_dsa_enable_prefill_cp, - is_dsa_prefill_cp_in_seq_split, -) from sglang.srt.layers.linear import ReplicatedLinear from sglang.srt.layers.quantization.base_config import QuantizationConfig from sglang.srt.layers.rotary_embedding import get_rope_wrapper -from sglang.srt.layers.utils.cp_utils import cp_all_gather_rerange_output from sglang.srt.model_executor.forward_batch_info import ForwardBatch from sglang.srt.model_executor.forward_context import ( get_attn_backend, @@ -46,7 +39,7 @@ get_token_to_kv_pool, ) from sglang.srt.model_executor.runner import get_is_capture_mode -from sglang.srt.runtime_context import get_device, get_parallel +from sglang.srt.runtime_context import get_device if TYPE_CHECKING: from sglang.srt.mem_cache.memory_pool import DSATokenToKVPool @@ -84,8 +77,6 @@ def __init__( self.layer_id = layer_id self.alt_stream = alt_stream self.compress_gate_stream = None - self.dsa_enable_prefill_cp = is_dsa_enable_prefill_cp() - self.cp_size = get_parallel().attn_cp_size if self.dsa_enable_prefill_cp else 1 self.skip_rope = skip_rope self.index_kpool = config.index_kpool @@ -166,35 +157,6 @@ def _get_logits_head_gate(self, x: torch.Tensor, q_scale: torch.Tensor): weights = weights.unsqueeze(-1) * q_scale * self.softmax_scale return weights - @staticmethod - def _cp_gather_concat( - tensors: List[torch.Tensor], - cp_size: int, - forward_batch: ForwardBatch, - ) -> List[torch.Tensor]: - if not tensors: - return [] - n_local = tensors[0].shape[0] - flats = [] - feature_sizes = [] - tails = [] - for tensor in tensors: - assert tensor.shape[0] == n_local - assert tensor.dtype == tensors[0].dtype - tails.append(tensor.shape[1:]) - flat = tensor.reshape(n_local, -1).contiguous() - feature_sizes.append(flat.shape[1]) - flats.append(flat) - combined = flats[0] if len(flats) == 1 else torch.cat(flats, dim=1) - gathered = cp_all_gather_rerange_output( - combined, - cp_size, - forward_batch, - torch.cuda.current_stream(), - ) - parts = torch.split(gathered, feature_sizes, dim=1) - return [part.reshape(part.shape[0], *tail) for part, tail in zip(parts, tails)] - @staticmethod def _get_index_k_read_buffer(pool, layer_id: int) -> torch.Tensor: if hasattr(pool, "get_broadcastable_index_k_with_scale_buffer"): @@ -232,10 +194,6 @@ def _write_compressed_pooled_index_cache( pool = get_token_to_kv_pool() if hasattr(pool, "invalidate_index_buffer_for_layer"): pool.invalidate_index_buffer_for_layer(layer_id) - if hasattr(pool, "_is_layer_owned") and not pool._is_layer_owned(layer_id): - if not return_compressed: - return None - write_cache = False buf = pool.get_index_k_with_scale_buffer(layer_id=layer_id) return kpool_softmax_rotate_write_cache( @@ -280,8 +238,6 @@ def _compress_write_decode( pool = get_token_to_kv_pool() if hasattr(pool, "invalidate_index_buffer_for_layer"): pool.invalidate_index_buffer_for_layer(layer_id) - if hasattr(pool, "_is_layer_owned") and not pool._is_layer_owned(layer_id): - return pool.kpool_decode_update_index_cache( layer_id=layer_id, @@ -317,7 +273,6 @@ def _compress_write_extend( import os from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( - all_gather_and_scatter_pool_slots, kpool_assemble_softmax_rotate_write_cache, scatter_kpool_tail_updates, ) @@ -325,26 +280,15 @@ def _compress_write_extend( pool = get_token_to_kv_pool() if hasattr(pool, "invalidate_index_buffer_for_layer"): pool.invalidate_index_buffer_for_layer(layer_id) - layer_owned = not ( - hasattr(pool, "_is_layer_owned") and not pool._is_layer_owned(layer_id) - ) - if not layer_owned: - return None - writes, tails, cp = plan.writes, plan.tails, plan.cp + writes, tails = plan.writes, plan.tails if writes.is_empty and tails.is_empty: return None tail_k_buf, tail_score_buf = pool.get_compress_tail_buffers(layer_id) - layer_sharded = bool(getattr(pool, "layer_shard_enabled", False)) - cache_cp = None if layer_sharded else cp if os.environ.get("SGLANG_DSA_KPOOL_DEBUG_BOUNDS") == "1": if not writes.is_empty: - active = ( - cache_cp.local_write_mask - if cache_cp is not None - else torch.ones_like(writes.req, dtype=torch.bool) - ) + active = torch.ones_like(writes.req, dtype=torch.bool) if bool(active.any().item()): active_req = writes.req[active] active_write_loc = writes.write_loc[active] @@ -380,9 +324,7 @@ def _compress_write_extend( f"{key.shape=}, {gate_score.shape=}, {tail_k_buf.shape=}, " f"{pool.get_index_k_with_scale_buffer(layer_id=layer_id).shape=}, " f"{min_chunk=}, {max_chunk=}, {min_req=}, {max_req=}, " - f"{min_loc=}, {max_loc=}, {pool.slots_per_page=}, " - f"cp_rank={cache_cp.rank if cache_cp is not None else None}, " - f"cp_size={cache_cp.size if cache_cp is not None else None}" + f"{min_loc=}, {max_loc=}, {pool.slots_per_page=}" ) if not tails.is_empty: tail_chunk_max = tails.chunk_src.to(torch.long) + torch.clamp( @@ -419,20 +361,8 @@ def _compress_write_extend( tail_logical_base=writes.tail_logical_base, ape=self.index_kpool_compress_ape, loc=writes.write_loc, - write_mask=( - cache_cp.local_write_mask if cache_cp is not None else None - ), round_scale=self.scale_fmt is not None, ) - if cache_cp is not None and write_cache: - all_gather_and_scatter_pool_slots( - buf=buf, - local_locs=writes.write_loc, - owner_rank=cache_cp.owner_rank, - cp_size=cache_cp.size, - cp_rank=cache_cp.rank, - slots_per_page=pool.slots_per_page, - ) if not tails.is_empty: scatter_kpool_tail_updates( @@ -968,15 +898,6 @@ def _get_topk_ragged_kpool_plan( total_k_rows = plan.ragged_total_k_rows n_real = seq_lens_expanded.shape[0] - row_select = None - if n_real > total_q: - row_select = cp_zigzag_full_plan_rows(forward_batch, device) - if row_select is not None: - seq_lens_expanded = seq_lens_expanded.index_select(0, row_select) - pool_lens = pool_lens.index_select(0, row_select) - ks_per_q = ks_per_q.index_select(0, row_select) - ke_per_q = ke_per_q.index_select(0, row_select) - n_real = seq_lens_expanded.shape[0] assert ( n_real <= total_q ), f"plan has more real rows ({n_real}) than q_fp8 ({total_q})" @@ -1015,16 +936,8 @@ def _get_topk_ragged_kpool_plan( if topk_method == TopkTransformMethod.PAGED: page_table_all = plan.ragged_paged_page_table page_table_row_index_all = plan.ragged_paged_page_table_row_index - if page_table_row_index_all is not None and row_select is not None: - page_table_row_index_all = page_table_row_index_all.index_select( - 0, row_select - ) - elif page_table_all is not None and row_select is not None: - page_table_all = page_table_all.index_select(0, row_select) elif topk_method == TopkTransformMethod.RAGGED: topk_offsets_all = attn_metadata.topk_indices_offset - if topk_offsets_all is not None and row_select is not None: - topk_offsets_all = topk_offsets_all.index_select(0, row_select) return self._topk_from_kpool_logits( logits, @@ -1037,114 +950,6 @@ def _get_topk_ragged_kpool_plan( page_table_row_index=page_table_row_index_all, ) - def _get_topk_ragged_with_cp( - self, - forward_batch: ForwardBatch, - layer_id: int, - q_fp8: torch.Tensor, - weights: torch.Tensor, - metadata: BaseIndexerMetadata, - kv_len: int, - actual_seq_q: int, - cp_index: Optional[List[Tuple[int, int, int]]] = None, - ) -> torch.Tensor: - from sglang.srt.layers.attention.dsa.kpool_fp8_index import ( - build_pooled_page_table_64, - gather_index_k_scale_prefix_into, - ) - - assert cp_index is None, "DSA kpool CP topk currently supports batch size 1" - assert forward_batch.batch_size == 1 - assert len(weights.shape) == 3 - weights = weights.squeeze(-1) - - pool = get_token_to_kv_pool() - pool_size = self.index_kpool - slots_per_page = pool.slots_per_page - device = q_fp8.device - out_rows = q_fp8.shape[0] - actual_seq_q = int(actual_seq_q) - - assert forward_batch.seq_lens_cpu is not None - assert forward_batch.extend_seq_lens_cpu is not None - kv_len_token = int( - forward_batch.seq_lens_cpu[0].item() - - forward_batch.extend_seq_lens_cpu[0] - + kv_len - ) - pool_kv_len = kv_len_token // pool_size - - q_work = q_fp8[:actual_seq_q].contiguous() - weights_work = weights[:actual_seq_q].contiguous() - tail_tokens = torch.arange( - kv_len_token - actual_seq_q + 1, - kv_len_token + 1, - dtype=torch.int32, - device=device, - ) - - if pool_kv_len > 0 and actual_seq_q > 0: - block_tables = metadata.get_page_table_64() - bt_row = block_tables[0] - n_pages = (pool_kv_len + slots_per_page - 1) // slots_per_page - packed_page_indices = ( - build_pooled_page_table_64(bt_row, pool_size)[:n_pages] - .to(torch.int32) - .contiguous() - ) - k_u8 = torch.empty( - (pool_kv_len, self.head_dim), dtype=torch.uint8, device=device - ) - k_scale = torch.empty((pool_kv_len,), dtype=torch.float32, device=device) - gather_index_k_scale_prefix_into( - pool=pool, - buf=self._get_index_k_read_buffer(pool, layer_id), - page_indices=packed_page_indices, - seq_len=pool_kv_len, - k_out=k_u8, - scale_out=k_scale, - ) - k_fp8 = k_u8.view(torch.float8_e4m3fn) - ks = torch.zeros((actual_seq_q,), dtype=torch.int32, device=device) - ke = torch.div(tail_tokens, pool_size, rounding_mode="floor").to( - torch.int32 - ) - logits = deep_gemm.fp8_mqa_logits( - q_work, - (k_fp8.contiguous(), k_scale.contiguous()), - weights_work, - ks, - ke, - clean_logits=True, - ) - pool_lens = ke - else: - logits = torch.empty((actual_seq_q, 0), dtype=torch.float32, device=device) - pool_lens = torch.zeros((actual_seq_q,), dtype=torch.int32, device=device) - ks = torch.zeros((actual_seq_q,), dtype=torch.int32, device=device) - - page_table_local = None - topk_method = metadata.topk_transform_method - if envs.SGLANG_DSA_FUSE_TOPK.get() and topk_method == TopkTransformMethod.PAGED: - req_pool_idx = int(forward_batch.req_pool_indices[0].item()) - page_table_local = ( - get_req_to_token_pool() - .req_to_token[req_pool_idx, :kv_len_token] - .to(torch.int32) - .unsqueeze(0) - .expand(actual_seq_q, -1) - ) - - return self._topk_from_kpool_logits( - logits, - pool_lens, - seq_lens=tail_tokens, - page_table=page_table_local, - topk_offsets=None, - row_starts=ks, - out_rows=out_rows, - ) - def _get_topk_ragged_kpool( self, forward_batch: ForwardBatch, @@ -1605,7 +1410,7 @@ def forward_cuda( max_kv_len = forward_batch.seq_lens_cpu.max().item() skip_logits_computation = max_kv_len <= self.index_topk - if skip_logits_computation and (not self.dsa_enable_prefill_cp): + if skip_logits_computation: return self._forward_cuda_skip_logits( x, positions, @@ -1631,13 +1436,6 @@ def forward_cuda( forward_batch=forward_batch, precompute_compress_gate=precompute_compress_gate, ) - use_cp = dsa_use_prefill_cp(forward_batch, self.dsa_enable_prefill_cp) - if use_cp: - if gate_score is None: - gate_score = self._compute_gate_score_if_missing(x, gate_score) - key, gate_score = self._cp_gather_concat( - [key, gate_score], self.cp_size, forward_batch - ) weights = None kpool_extend_cache = None @@ -1700,45 +1498,7 @@ def forward_cuda( forward_batch, layer_id, q_fp8, weights, metadata ) else: - if ( - forward_batch.attn_cp_metadata is not None - and self.dsa_enable_prefill_cp - and is_dsa_prefill_cp_in_seq_split() - ): - kv_len_prev = forward_batch.attn_cp_metadata.kv_len_prev_list[0] - kv_len_next = forward_batch.attn_cp_metadata.kv_len_next_list[0] - actual_seq_q_prev = ( - forward_batch.attn_cp_metadata.actual_seq_q_prev_list[0] - ) - actual_seq_q_next = ( - forward_batch.attn_cp_metadata.actual_seq_q_next_list[0] - ) - q_fp8_prev, q_fp8_next = torch.split( - q_fp8, (q_fp8.shape[0] + 1) // 2, dim=0 - ) - weights_prev, weights_next = torch.split( - weights, (weights.shape[0] + 1) // 2, dim=0 - ) - topk_result_prev = self._get_topk_ragged_with_cp( - forward_batch, - layer_id, - q_fp8_prev, - weights_prev, - metadata, - kv_len_prev, - actual_seq_q_prev, - ) - topk_result_next = self._get_topk_ragged_with_cp( - forward_batch, - layer_id, - q_fp8_next, - weights_next, - metadata, - kv_len_next, - actual_seq_q_next, - ) - topk_result = torch.cat([topk_result_prev, topk_result_next], dim=0) - elif has_kpool_extend_plan: + if has_kpool_extend_plan: topk_result = self._get_topk_ragged_kpool_plan( forward_batch, layer_id, diff --git a/python/sglang/srt/layers/attention/dsa/utils.py b/python/sglang/srt/layers/attention/dsa/utils.py index 6661641e0dbdf..def27c6059a0a 100644 --- a/python/sglang/srt/layers/attention/dsa/utils.py +++ b/python/sglang/srt/layers/attention/dsa/utils.py @@ -12,7 +12,6 @@ from sglang.srt.layers.dp_attention import ( DpPaddingMode, attn_cp_all_gather_into_tensor, - attn_cp_reduce_scatter_tensor, is_allocation_symmetric, ) from sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph import ( @@ -519,98 +518,6 @@ def cp_all_gather_rerange_output(input_tensor, cp_size, forward_batch, stream): return output_tensor -# Plain CP keeps rank-contiguous token slices across layers; only MLA boundaries -# convert to/from the load-balanced layout. -def cp_plain_split(input_tensor: torch.Tensor) -> torch.Tensor: - cp_size = get_parallel().attn_cp_size - cp_rank = get_parallel().attn_cp_rank - assert input_tensor.shape[0] % cp_size == 0, ( - f"cp_plain_split expects total tokens divisible by cp_size, " - f"got {input_tensor.shape[0]} % {cp_size} != 0" - ) - chunk = input_tensor.shape[0] // cp_size - return input_tensor[cp_rank * chunk : (cp_rank + 1) * chunk].contiguous() - - -def cp_plain_all_gather(input_tensor: torch.Tensor, cp_size: int) -> torch.Tensor: - # Rank-major all-gather is already in natural order under the plain layout, - # so no rerange is needed. - out_shape = (input_tensor.shape[0] * cp_size,) + tuple(input_tensor.shape[1:]) - with use_symmetric_memory( - get_parallel().attn_cp_group, disabled=not is_allocation_symmetric() - ): - output_tensor = input_tensor.new_empty(out_shape) - attn_cp_all_gather_into_tensor(output_tensor, input_tensor) - return output_tensor - - -def cp_plain_reduce_scatter(input_tensor: torch.Tensor, cp_size: int) -> torch.Tensor: - # Contiguous plain layout permits one reduce-scatter and avoids a full-tensor - # permutation. - S = input_tensor.shape[0] - assert S % cp_size == 0, ( - f"cp_plain_reduce_scatter expects S divisible by cp_size, " - f"got S={S}, cp_size={cp_size}" - ) - out_shape = (S // cp_size,) + tuple(input_tensor.shape[1:]) - with use_symmetric_memory( - get_parallel().attn_cp_group, disabled=not is_allocation_symmetric() - ): - output_tensor = input_tensor.new_empty(out_shape) - attn_cp_reduce_scatter_tensor(output_tensor, input_tensor.contiguous()) - return output_tensor - - -def cp_plain_to_scattered( - input_tensor: torch.Tensor, - forward_batch, - cp_size: int, -) -> torch.Tensor: - # When K % cp_size == 0, all-to-all is equivalent to the round-robin split - # and avoids a full all-gather. - K = input_tensor.shape[0] - if is_dsa_prefill_cp_round_robin_split() and K % cp_size == 0: - tail = input_tensor.shape[1:] - send = ( - input_tensor.view(K // cp_size, cp_size, *tail).transpose(0, 1).contiguous() - ) - recv = torch.empty_like(send) - torch.distributed.all_to_all_single( - recv, send, group=get_parallel().attn_cp_group.device_group - ) - return recv.flatten(0, 1) - - full = cp_plain_all_gather(input_tensor, cp_size) - return cp_split_and_rebuild_data(forward_batch, full) - - -def cp_scattered_to_plain( - input_tensor: torch.Tensor, - forward_batch, - cp_size: int, -) -> torch.Tensor: - # When K % cp_size == 0, all-to-all avoids a full all-gather; transposing - # the received source-major rows restores plain order. - K = input_tensor.shape[0] - if is_dsa_prefill_cp_round_robin_split() and K % cp_size == 0: - tail = input_tensor.shape[1:] - send = input_tensor.view(cp_size, K // cp_size, *tail) - recv = torch.empty_like(send) - torch.distributed.all_to_all_single( - recv, send, group=get_parallel().attn_cp_group.device_group - ) - # recv[s, n] = global token at position r*K + n*cp + s on this rank r; - # plain out[n*cp + s] = recv[s, n], i.e. transpose dims 0 and 1. - return recv.transpose(0, 1).contiguous().view(K, *tail) - - full = cp_all_gather_rerange_output( - input_tensor, cp_size, forward_batch, torch.cuda.current_stream() - ) - cp_rank = get_parallel().attn_cp_rank - chunk = full.shape[0] // cp_size - return full[cp_rank * chunk : (cp_rank + 1) * chunk].contiguous() - - def fp8_mqa_logits_ceil_to_ue8m0(x: torch.Tensor) -> torch.Tensor: return torch.pow(2.0, torch.ceil(torch.log2(x.abs()))) diff --git a/python/sglang/srt/layers/communicator_dsa_cp.py b/python/sglang/srt/layers/communicator_dsa_cp.py index 0b74d65be0112..c55d64b3bdd00 100644 --- a/python/sglang/srt/layers/communicator_dsa_cp.py +++ b/python/sglang/srt/layers/communicator_dsa_cp.py @@ -53,19 +53,17 @@ def maybe_prefetch_next_full_attention_kv( forward_batch: ForwardBatch, next_full_attention_layer_id: Optional[int], ) -> None: - """Hybrid pools map model layer IDs to compact full-attention pool IDs.""" - if next_full_attention_layer_id is None or not dsa_use_prefill_cp(forward_batch): - return + """Prefetch (owner-broadcast) the next layer's DSA KV under layer split. - token_to_kv_pool = get_token_to_kv_pool() - prefetch_full_attention_kv = getattr( - token_to_kv_pool, "prefetch_full_attention_kv_buffer", None - ) - if prefetch_full_attention_kv is not None: - prefetch_full_attention_kv(next_full_attention_layer_id) + No-op unless the current batch runs DSA prefill-CP and the active KV pool is + a layer-sharded pool exposing ``prefetch_kv_buffer`` (i.e. + ``LayerSplitDSATokenToKVPool``). Kicking the broadcast off one layer ahead + overlaps it with the current layer's attention compute. + """ + if next_full_attention_layer_id is None or not dsa_use_prefill_cp(forward_batch): return - prefetch_kv_buffer = getattr(token_to_kv_pool, "prefetch_kv_buffer", None) + prefetch_kv_buffer = getattr(get_token_to_kv_pool(), "prefetch_kv_buffer", None) if prefetch_kv_buffer is not None: prefetch_kv_buffer(next_full_attention_layer_id) @@ -139,15 +137,6 @@ def _post_init_communicate(self): context=self._context, ) - def maybe_prefetch_next_full_attention_kv( - self, - forward_batch: ForwardBatch, - next_full_attention_layer_id: Optional[int], - ) -> None: - maybe_prefetch_next_full_attention_kv( - forward_batch, next_full_attention_layer_id - ) - class DSACPCommunicateSimpleFn(CommunicateSimpleFn): @staticmethod diff --git a/python/sglang/srt/layers/communicator_mhc.py b/python/sglang/srt/layers/communicator_mhc.py index a8c342afd93bc..ba8a8638cb351 100644 --- a/python/sglang/srt/layers/communicator_mhc.py +++ b/python/sglang/srt/layers/communicator_mhc.py @@ -25,7 +25,6 @@ from sglang.srt.distributed.device_communicators.pynccl_allocator import ( use_symmetric_memory, ) -from sglang.srt.layers.attention.dsa.utils import dsa_use_prefill_cp from sglang.srt.layers.communicator import ( AttentionInputs, CommunicateContext, @@ -431,8 +430,7 @@ def _post_init_communicate(self): if self.layer_scatter_modes.mlp_mode == ScatterMode.MOE_FULL: raise NotImplementedError( "MHCLayerCommunicator does not support MOE_FULL " - "(moe_dp_size < attention_context_parallel_size without " - "--enable-prefill-cp). Set --enable-prefill-cp or raise " + "(moe_dp_size < attention_context_parallel_size). Increase " "moe_dp_size to match attention_context_parallel_size." ) self._communicate_simple_fn = CommunicateSimpleFn.get_fn( @@ -554,9 +552,6 @@ def should_use_reduce_scatter(self, forward_batch: ForwardBatch): if forward_batch.dp_padding_mode.is_max_len(): return True - if dsa_use_prefill_cp(forward_batch): - return True - if get_attn_tp_context().input_scattered: return True return False diff --git a/python/sglang/srt/layers/communicator_mhc_hybrid_cp.py b/python/sglang/srt/layers/communicator_mhc_hybrid_cp.py deleted file mode 100644 index f40b58aa1b2c2..0000000000000 --- a/python/sglang/srt/layers/communicator_mhc_hybrid_cp.py +++ /dev/null @@ -1,221 +0,0 @@ -# Copyright 2023-2024 SGLang Team -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== -from functools import partial -from typing import Optional - -import torch - -from sglang.kernels.ops.layernorm.mhc import hc_contract -from sglang.srt.distributed import get_tp_group -from sglang.srt.layers.attention.dsa.utils import dsa_use_prefill_cp -from sglang.srt.layers.communicator import ( - CommunicateContext, - ScatterMode, -) -from sglang.srt.layers.communicator_dsa_cp import ( - DSACPCommunicateSimpleFn, - DSACPCommunicateSummableTensorPairFn, - DSACPCommunicateWithAllReduceAndLayerNormFn, - maybe_prefetch_next_full_attention_kv, -) -from sglang.srt.layers.communicator_mhc import MHCLayerCommunicator, MHCState -from sglang.srt.layers.dp_attention import ( - attn_cp_all_gather_into_tensor, - attn_cp_reduce_scatter_tensor, - get_local_dp_buffer_mhc, -) -from sglang.srt.model_executor.forward_batch_info import ForwardBatch - - -class MHCHybridDSACPLayerCommunicator(MHCLayerCommunicator): - def _post_init_communicate(self): - # SCATTERED in attn tp is different from SCATTERED in global tp when dp_size > 1 - if self.layer_scatter_modes.mlp_mode != ScatterMode.SCATTERED: - assert ( - self._context.attn_dp_size == 1 - ), "dp_size should be 1 when moe_runner_backend is none" - self._communicate_simple_fn = DSACPCommunicateSimpleFn.get_fn( - input_mode=ScatterMode.SCATTERED, - output_mode=ScatterMode.SCATTERED, - context=self._context, - ) - self._communicate_with_all_reduce_and_layer_norm_fn = ( - MHCHybridDSACPCommunicateWithAllReduceAndLayerNormFn.get_fn( - hidden_states_input_mode=ScatterMode.SCATTERED, - residual_input_mode=ScatterMode.SCATTERED, - hidden_states_output_mode=self.layer_scatter_modes.mlp_mode, - residual_output_mode=ScatterMode.SCATTERED, - context=self._context, - ) - ) - self._communicate_summable_tensor_pair_fn = ( - MHCHybridDSACPCommunicateSummableTensorPairFn.get_fn( - hidden_states_input_mode=self.layer_scatter_modes.mlp_mode, - residual_input_mode=ScatterMode.SCATTERED, - output_mode=ScatterMode.SCATTERED, - context=self._context, - ) - ) - - def maybe_prefetch_next_full_attention_kv( - self, - forward_batch: ForwardBatch, - next_full_attention_layer_id: Optional[int], - ) -> None: - maybe_prefetch_next_full_attention_kv( - forward_batch, next_full_attention_layer_id - ) - - -class MHCHybridDSACPCommunicateWithAllReduceAndLayerNormFn( - DSACPCommunicateWithAllReduceAndLayerNormFn -): - @staticmethod - def get_fn( - hidden_states_input_mode: ScatterMode, - residual_input_mode: ScatterMode, - hidden_states_output_mode: ScatterMode, - residual_output_mode: ScatterMode, - context: CommunicateContext, - ): - assert hidden_states_input_mode == ScatterMode.SCATTERED - assert residual_input_mode == ScatterMode.SCATTERED - assert residual_output_mode == ScatterMode.SCATTERED - if hidden_states_output_mode == ScatterMode.SCATTERED: - return MHCHybridDSACPCommunicateWithAllReduceAndLayerNormFn._simple - - if hidden_states_output_mode == ScatterMode.FULL: - return partial( - MHCHybridDSACPCommunicateWithAllReduceAndLayerNormFn._gather_hidden_states_and_residual, - residual_input_mode=residual_input_mode, - ) - - raise NotImplementedError( - f"{hidden_states_input_mode=} {residual_input_mode=} " - f"{hidden_states_output_mode=} {residual_output_mode=}" - ) - - @staticmethod - def _simple( - hidden_states: torch.Tensor, - residual: torch.Tensor, - forward_batch: ForwardBatch, - layernorm: torch.nn.Module, - context: CommunicateContext, - *, - mhc: MHCState, - ): - hidden_states, residual = mhc.attn_to_mlp( - hidden_states, residual, out_norm=layernorm - ) - return hidden_states, residual - - @staticmethod - def _gather_hidden_states_and_residual( - hidden_states: torch.Tensor, - residual: torch.Tensor, - forward_batch: ForwardBatch, - layernorm: torch.nn.Module, - context: CommunicateContext, - *, - residual_input_mode, - mhc: MHCState, - ): - hidden_states, residual = mhc.attn_to_mlp( - hidden_states, residual, out_norm=layernorm - ) - - if dsa_use_prefill_cp(forward_batch): - assert context.attn_dp_size == 1 - hidden_states, local_hidden_states = ( - get_local_dp_buffer_mhc(get_tp_group(), 1), - hidden_states, - ) - attn_cp_all_gather_into_tensor( - hidden_states, - local_hidden_states, - ) - return hidden_states, residual - - -class MHCHybridDSACPCommunicateSummableTensorPairFn( - DSACPCommunicateSummableTensorPairFn -): - @staticmethod - def get_fn( - hidden_states_input_mode: ScatterMode, - residual_input_mode: ScatterMode, - output_mode: ScatterMode, - context: CommunicateContext, - ): - if ( - (hidden_states_input_mode == ScatterMode.FULL) - and (residual_input_mode == ScatterMode.SCATTERED) - and (output_mode == ScatterMode.SCATTERED) - ): - return MHCHybridDSACPCommunicateSummableTensorPairFn._scatter_hidden_states - - if context.is_same_group_size( - hidden_states_input_mode, output_mode - ) and context.is_same_group_size(residual_input_mode, output_mode): - return MHCHybridDSACPCommunicateSummableTensorPairFn._trivial - - raise NotImplementedError( - f"{hidden_states_input_mode=} {residual_input_mode=} {output_mode=}" - ) - - @staticmethod - def _trivial( - hidden_states: torch.Tensor, - residual: torch.Tensor, - forward_batch: ForwardBatch, - context: CommunicateContext, - *, - mhc: MHCState, - is_last_layer: bool, - **kwargs, - ): - hidden_states = mhc.mlp_combine(hidden_states, residual) - if not is_last_layer: - return hidden_states, None - - hidden_states = hc_contract(hidden_states, mhc.hc_mult) - return hidden_states, None - - @staticmethod - def _scatter_hidden_states( - hidden_states: torch.Tensor, - residual: torch.Tensor, - forward_batch: ForwardBatch, - context: CommunicateContext, - allow_reduce_scatter: bool = False, - *, - mhc: MHCState, - is_last_layer: bool, - **kwargs, - ): - if dsa_use_prefill_cp(forward_batch): - assert context.attn_dp_size == 1 - input_hidden_states = hidden_states - hidden_states = hidden_states.tensor_split(context.attn_cp_size)[ - context.attn_cp_rank - ] - attn_cp_reduce_scatter_tensor(hidden_states, input_hidden_states) - - hidden_states = mhc.mlp_combine(hidden_states, residual) - if not is_last_layer: - return hidden_states, None - - hidden_states = hc_contract(hidden_states, mhc.hc_mult) - return hidden_states, None diff --git a/python/sglang/srt/layers/cp/utils.py b/python/sglang/srt/layers/cp/utils.py index 54157743f711f..5ec30fd7d8be6 100644 --- a/python/sglang/srt/layers/cp/utils.py +++ b/python/sglang/srt/layers/cp/utils.py @@ -65,6 +65,7 @@ def is_glm_dsa_cache_layer_split_enabled(model_runner: "ModelRunner") -> bool: not model_runner.is_draft_worker and get_parallel().enable_dsa_cache_layer_split and model_runner.use_mla_backend + and not getattr(model_runner, "mambaish_config", None) and is_deepseek_dsa(model_runner.model_config.hf_config) ) diff --git a/python/sglang/srt/mem_cache/dsa_cache_layer_split.py b/python/sglang/srt/mem_cache/dsa_cache_layer_split.py index de83e56413909..6bf449068b9ad 100644 --- a/python/sglang/srt/mem_cache/dsa_cache_layer_split.py +++ b/python/sglang/srt/mem_cache/dsa_cache_layer_split.py @@ -234,11 +234,6 @@ def _get_layer_owner_rank(self, layer_id: int) -> int: self._local_layer_idx(layer_id), self.layer_shard_size, self.layer_num ) - def _should_allocate_index_layer(self, local_layer_idx: int) -> bool: - return self._is_layer_owned( - self.start_layer + local_layer_idx - ) and super()._should_allocate_index_layer(local_layer_idx) - def _log_layer_shard_plan(self) -> None: partitions = [] for rank in range(self.layer_shard_size): @@ -574,15 +569,10 @@ def get_cpu_copy(self, indices, mamba_indices=None, req_pool_index=None): kv_cache_cpu[-1].append(kv_cpu) current_platform.synchronize() - cpu_copy = { + return { "kv": kv_cache_cpu, "index_k": self.index_key_cache.cpu_copy(indices), } - compress_tail = self._get_compress_tail_cpu_copy(req_pool_index) - if compress_tail is not None: - cpu_copy["tail_k"], cpu_copy["tail_score"] = compress_tail - torch.cuda.synchronize() - return cpu_copy def load_cpu_copy( self, @@ -608,9 +598,3 @@ def load_cpu_copy( current_platform.synchronize() self.index_key_cache.load_cpu_copy(kv_cache_cpu_dict["index_k"], indices) - self._load_compress_tail_cpu_copy( - kv_cache_cpu_dict.get("tail_k"), - kv_cache_cpu_dict.get("tail_score"), - req_pool_index, - ) - torch.cuda.synchronize() diff --git a/python/sglang/srt/mem_cache/kv_cache_configurator.py b/python/sglang/srt/mem_cache/kv_cache_configurator.py index 20d4e1e5205fa..7cd9bb01b3c49 100644 --- a/python/sglang/srt/mem_cache/kv_cache_configurator.py +++ b/python/sglang/srt/mem_cache/kv_cache_configurator.py @@ -1761,12 +1761,6 @@ def _build_hybrid_linear_kv_pool( "qk_rope_head_dim": self.model_config.qk_rope_head_dim, } if is_deepseek_dsa(self.model_config.hf_config): - from sglang.srt.layers.cp.utils import get_glm_dsa_cp_layer_shard_info - - ( - dsa_cp_layer_shard_rank, - dsa_cp_layer_shard_size, - ) = get_glm_dsa_cp_layer_shard_info(self) dsa_index_kpool = get_dsa_index_kpool(self.model_config.hf_config) extra_args.update( use_dsa=True, @@ -1779,8 +1773,6 @@ def _build_hybrid_linear_kv_pool( index_kpool_compress=get_dsa_index_kpool_compress( self.model_config.hf_config ), - layer_shard_rank=dsa_cp_layer_shard_rank, - layer_shard_size=dsa_cp_layer_shard_size, skip_topk_layers=( None if self.is_draft_worker diff --git a/python/sglang/srt/mem_cache/memory_pool.py b/python/sglang/srt/mem_cache/memory_pool.py index 91ee90d00b529..54aa6a2e56eff 100644 --- a/python/sglang/srt/mem_cache/memory_pool.py +++ b/python/sglang/srt/mem_cache/memory_pool.py @@ -3674,8 +3674,6 @@ def __init__( max_running_requests: Optional[int] = None, skip_topk_layers: Optional[List[bool]] = None, start_layer: Optional[int] = None, - layer_shard_rank: Optional[int] = None, - layer_shard_size: int = 1, full_kv_pool_class: Optional[type] = None, quant_method=None, # When provided (shared-KV-pool path), use this pool for the @@ -3751,17 +3749,7 @@ def __init__( assert ( index_head_dim is not None and kv_cache_dim is not None ), "HybridLinearKVPool with use_dsa requires index_head_dim and kv_cache_dim" - pool_kwargs = {} - DSAPoolCls = DSATokenToKVPool - if layer_shard_rank is not None and layer_shard_size > 1: - from sglang.srt.mem_cache.dsa_cache_layer_split import ( - LayerSplitDSATokenToKVPool, - ) - - DSAPoolCls = LayerSplitDSATokenToKVPool - pool_kwargs["layer_shard_rank"] = layer_shard_rank - pool_kwargs["layer_shard_size"] = layer_shard_size - self.full_kv_pool = DSAPoolCls( + self.full_kv_pool = DSATokenToKVPool( size=size, page_size=self.page_size, kv_lora_rank=kv_lora_rank, @@ -3777,7 +3765,6 @@ def __init__( tail_extra_slots=tail_extra_slots, max_running_requests=max_running_requests, skip_topk_layers=skip_topk_layers, - **pool_kwargs, ) else: TokenToKVPoolClass = MLATokenToKVPool @@ -3855,28 +3842,6 @@ def tail_extra_slots(self) -> int: def slots_per_page(self) -> int: return getattr(self.full_kv_pool, "slots_per_page", self.page_size) - @property - def layer_shard_enabled(self) -> bool: - return bool(getattr(self.full_kv_pool, "layer_shard_enabled", False)) - - @property - def layer_shard_rank(self) -> Optional[int]: - return getattr(self.full_kv_pool, "layer_shard_rank", None) - - @property - def layer_shard_size(self) -> int: - return getattr(self.full_kv_pool, "layer_shard_size", 1) - - @property - def layer_shard_start(self) -> int: - return getattr(self.full_kv_pool, "layer_shard_start", self.start_layer) - - def _is_layer_owned(self, layer_id: int) -> bool: - if not self.layer_shard_enabled: - return True - full_layer_id = self._transfer_full_attention_id(layer_id) - return self.full_kv_pool._is_layer_owned(full_layer_id) - def get_kv_size_bytes(self): return self.full_kv_pool.get_kv_size_bytes() @@ -4079,14 +4044,6 @@ def set_mla_kv_buffer( with self._transfer_id_context(layer): self.full_kv_pool.set_mla_kv_buffer(layer, loc, cache_k_nope, cache_k_rope) - def prefetch_full_attention_kv_buffer(self, layer_id: int) -> None: - if not self.use_mla or not hasattr(self.full_kv_pool, "prefetch_kv_buffer"): - return - if layer_id not in self.full_attention_layer_id_mapping: - return - full_layer_id = self._transfer_full_attention_id(layer_id) - self.full_kv_pool.prefetch_kv_buffer(full_layer_id) - def get_mla_kv_buffer( self, layer: RadixAttention, @@ -4873,14 +4830,7 @@ def get_compress_tail_buffers( def get_compress_tail_buf_infos(self): if not self.kpool_use_compress: return [], [], [] - if self.layer_shard_enabled: - transfer_layer_ids = [ - i - for i in range(self.layer_num) - if self._is_layer_owned(self.start_layer + i) - ] - else: - transfer_layer_ids = list(range(self.layer_num)) + transfer_layer_ids = list(range(self.layer_num)) # Keep zero-row indexShare entries in the pointer list so layer offsets # stay aligned across PD peers; item_len=0 makes transfer backends skip them. tail_buffers = [self._compress_tail_k[i] for i in transfer_layer_ids] + [ diff --git a/python/sglang/srt/model_executor/pool_configurator.py b/python/sglang/srt/model_executor/pool_configurator.py index cb115f7752057..6bdc8c79756c2 100644 --- a/python/sglang/srt/model_executor/pool_configurator.py +++ b/python/sglang/srt/model_executor/pool_configurator.py @@ -126,38 +126,6 @@ def _get_dsa_cache_layer_ids(kvc: KVCacheConfigurator, num_layers: int) -> list[ return layer_ids -def _get_dsa_indexer_effective_num_layers( - kvc: KVCacheConfigurator, cache_layer_ids: list[int] -) -> int: - """Indexer buffers materialized per rank, including split remote scratch.""" - enable_hisparse = kvc.server_args.enable_hisparse - if enable_hisparse or kvc.is_draft_worker: - included_layers = [True] * len(cache_layer_ids) - else: - included_layers = [ - not dsa_layer_skips_topk(kvc.model_config.hf_config, layer_id) - for layer_id in cache_layer_ids - ] - - from sglang.srt.layers.cp.utils import ( - get_glm_dsa_cp_layer_shard_info, - get_layer_shard_range, - ) - - layer_shard_rank, shard_size = get_glm_dsa_cp_layer_shard_info(kvc) - if enable_hisparse or layer_shard_rank is None: - return sum(included_layers) - - # All ranks must derive the same token capacity. Use the maximum number of - # non-skipped owned layers across shards, then account for the one full-size - # remote indexer scratch buffer allocated by LayerSplitDSATokenToKVPool. - max_owned_layers = 0 - for rank in range(shard_size): - start, end = get_layer_shard_range(rank, shard_size, len(cache_layer_ids)) - max_owned_layers = max(max_owned_layers, sum(included_layers[start:end])) - return max(1, max_owned_layers + 1) - - def _get_dsv4_compress_state_dtype_sizes() -> tuple[int, int]: dtype_name = envs.SGLANG_DSV4_COMPRESS_STATE_DTYPE.get().strip().lower() if dtype_name in ("float32", "fp32"): @@ -316,10 +284,6 @@ def _compute_cell_size(self, kvc: KVCacheConfigurator, num_layers: int) -> int: else get_glm_dsa_layer_split_effective_num_layers(kvc, num_layers) ) - from sglang.srt.mem_cache.kv_cache_configurator import ( - calculate_mla_kv_cache_dim, - ) - kv_size = torch._utils._element_size(kv_cache_dtype) tp_size = get_parallel().attn_tp_size dcp_size = get_parallel().attn_dcp_size @@ -448,15 +412,48 @@ def _compute_dsa_indexer_cell_size( _should_elide_dsa_index_k, ) - if allocate_all_layers or not _should_elide_dsa_index_k( - is_draft_worker=kvc.is_draft_worker + if ( + allocate_all_layers + or kvc.server_args.enable_hisparse + or not _should_elide_dsa_index_k(is_draft_worker=kvc.is_draft_worker) ): num_indexer_layers = num_layers else: - num_indexer_layers = _get_dsa_indexer_effective_num_layers( - kvc, _get_dsa_cache_layer_ids(kvc, num_layers) + from sglang.srt.layers.cp.utils import ( + get_glm_dsa_cp_layer_shard_info, + get_layer_shard_range, ) + _, shard_size = get_glm_dsa_cp_layer_shard_info(kvc) + if shard_size > 1: + # Preserve the existing LayerSplit sizing semantics. GLM-5.3 + # hybrid-layer support is intentionally limited to the normal + # (non-LayerSplit) pool below. + active_indexer_layers = [ + layer_id + for layer_id in range( + kvc.layer_info.start_layer, kvc.layer_info.end_layer + ) + if not dsa_layer_skips_topk(kvc.model_config.hf_config, layer_id) + ] + active_set = set(active_indexer_layers) + max_owned = 0 + for rank in range(shard_size): + start, end = get_layer_shard_range(rank, shard_size, num_layers) + max_owned = max( + max_owned, + sum( + kvc.layer_info.start_layer + i in active_set + for i in range(start, end) + ), + ) + num_indexer_layers = max_owned + 1 + else: + num_indexer_layers = sum( + not dsa_layer_skips_topk(kvc.model_config.hf_config, layer_id) + for layer_id in _get_dsa_cache_layer_ids(kvc, num_layers) + ) + return int( indexer_size_per_token * num_indexer_layers * element_size * indexer_ratio ) diff --git a/python/sglang/srt/models/glm5_next.py b/python/sglang/srt/models/glm5_next.py index 0b2e8ddbe0b45..7772f3a62f4a0 100644 --- a/python/sglang/srt/models/glm5_next.py +++ b/python/sglang/srt/models/glm5_next.py @@ -24,17 +24,6 @@ ) from sglang.srt.eplb.expert_location import ModelConfigForExpertLocation from sglang.srt.layers.attention import vision_utils -from sglang.srt.layers.attention.dsa.utils import ( - can_dsa_cp_split, - cp_plain_all_gather, - cp_plain_reduce_scatter, - cp_plain_split, - cp_plain_to_scattered, - cp_scattered_to_plain, - cp_split_and_rebuild_position, - dsa_use_prefill_cp, - is_dsa_enable_prefill_cp, -) from sglang.srt.layers.attention.vision import VisionAttention from sglang.srt.layers.communicator import ( LayerCommunicator, @@ -42,11 +31,7 @@ enable_moe_dense_fully_dp, get_attn_tp_context, ) -from sglang.srt.layers.communicator_dsa_cp import DSACPLayerCommunicator from sglang.srt.layers.communicator_mhc import MHCLayerCommunicator -from sglang.srt.layers.communicator_mhc_hybrid_cp import ( - MHCHybridDSACPLayerCommunicator, -) from sglang.srt.layers.dcp.planner import prepare_decode_context_parallel_metadata from sglang.srt.layers.layernorm import RMSNorm from sglang.srt.layers.linear import ( @@ -68,12 +53,6 @@ from sglang.srt.layers.radix_linear_attention import RadixLinearAttention from sglang.srt.layers.rotary_embedding import get_rope from sglang.srt.layers.utils.common import PPMissingLayer -from sglang.srt.layers.utils.cp_utils import ( - can_cp_split, - is_prefill_context_parallel_enabled, - mla_use_prefill_cp, - prepare_context_parallel_metadata, -) from sglang.srt.layers.vocab_parallel_embedding import ( ParallelLMHead, VocabParallelEmbedding, @@ -334,22 +313,13 @@ def __init__( rms_norm_eps: float = 1e-5, prefix: str = "", reduce_results: bool = False, - enable_prefill_cp: bool = False, **kwargs, ) -> None: super().__init__() - self.dsa_enable_prefill_cp = is_dsa_enable_prefill_cp() - self.enable_prefill_cp = enable_prefill_cp self.tp_size = get_parallel().tp_size - - if self.dsa_enable_prefill_cp: - head_shard_size = get_parallel().attn_cp_size - head_shard_rank = get_parallel().attn_cp_rank - _head_shard_rank_getter = partial(getattr, get_parallel(), "attn_cp_rank") - else: - head_shard_size = get_parallel().attn_tp_size - head_shard_rank = get_parallel().attn_tp_rank - _head_shard_rank_getter = partial(getattr, get_parallel(), "attn_tp_rank") + head_shard_size = get_parallel().attn_tp_size + head_shard_rank = get_parallel().attn_tp_rank + _head_shard_rank_getter = partial(getattr, get_parallel(), "attn_tp_rank") self.hidden_size = hidden_size self.config = config @@ -519,11 +489,6 @@ def __init__( self.attn.lower_bound = config.linear_attn_config.get("gate_lower_bound", None) def forward_qkvbfg(self, hidden_states: torch.Tensor, forward_batch: ForwardBatch): - if dsa_use_prefill_cp(forward_batch, self.enable_prefill_cp): - hidden_states = cp_plain_all_gather( - hidden_states, get_parallel().attn_cp_size - ) - qkv, _ = self.qkv_proj(hidden_states) beta = self.b_proj(hidden_states)[0] @@ -540,10 +505,6 @@ def forward_qkvbfg(self, hidden_states: torch.Tensor, forward_batch: ForwardBatc def forward_qkvbfg_fused( self, hidden_states: torch.Tensor, forward_batch: ForwardBatch ): - if dsa_use_prefill_cp(forward_batch, self.enable_prefill_cp): - hidden_states = cp_plain_all_gather( - hidden_states, get_parallel().attn_cp_size - ) fused_states = self.fused_qkvbfg_a_proj(hidden_states) qkv, beta, fg_a_states = torch.split(fused_states, self.split_sizes, dim=-1) @@ -592,15 +553,7 @@ def forward( core_attn_out = self.o_norm(core_attn_out, norm_gate) core_attn_out = core_attn_out.squeeze(0).flatten(-2) - output = self.o_proj(core_attn_out)[0] - if dsa_use_prefill_cp(forward_batch, self.enable_prefill_cp): - if self.dsa_enable_prefill_cp: - output = cp_plain_reduce_scatter(output, get_parallel().attn_cp_size) - else: - output = cp_plain_split(output) - elif self.dsa_enable_prefill_cp: - output = get_parallel().attn_cp_group.all_reduce(output) - return output + return self.o_proj(core_attn_out)[0] class Glm5NextDecoderLayer(nn.Module): @@ -613,8 +566,6 @@ def __init__( is_nextn: bool = False, prefix: str = "", alt_stream: Optional[torch.cuda.Stream] = None, - dsa_enable_prefill_cp: bool = False, - mla_enable_prefill_cp: bool = False, ) -> None: super().__init__() self.hidden_size = config.hidden_size @@ -625,8 +576,6 @@ def __init__( self.speculative_algorithm = SpeculativeAlgorithm.from_string( get_spec().speculative_algorithm ) - self.dsa_enable_prefill_cp = dsa_enable_prefill_cp - self.mla_enable_prefill_cp = mla_enable_prefill_cp self.layer_id = layer_id self.is_nextn = is_nextn self.is_linear_attn = config.is_kda_layer(layer_id) @@ -640,9 +589,6 @@ def __init__( prefix=f"{prefix}.self_attn", rms_norm_eps=config.rms_norm_eps, reduce_results=False, - enable_prefill_cp=( - self.dsa_enable_prefill_cp or self.mla_enable_prefill_cp - ), ) else: self.self_attn = DeepseekV2AttentionMLA( @@ -664,8 +610,6 @@ def __init__( alt_stream=alt_stream, is_nextn=is_nextn, skip_rope=True, - dsa_enable_prefill_cp=dsa_enable_prefill_cp, - mla_enable_prefill_cp=mla_enable_prefill_cp, ) if config.q_lora_rank is None and envs.SGLANG_USE_AG_AFTER_QLORA.get(): @@ -693,8 +637,6 @@ def __init__( layer_id=self.layer_id, alt_stream=alt_stream, is_nextn=is_nextn, - dsa_enable_prefill_cp=dsa_enable_prefill_cp, - mla_enable_prefill_cp=mla_enable_prefill_cp, ) else: if enable_moe_dense_fully_dp(): @@ -757,18 +699,10 @@ def __init__( hc_ffn_pre=self.hc_ffn_pre, hc_post=self.hc_post, ) - if self.dsa_enable_prefill_cp: - self.layer_communicator = MHCHybridDSACPLayerCommunicator( - **shared_kwargs, - **mhc_kwargs, - ) - else: - self.layer_communicator = MHCLayerCommunicator( - **shared_kwargs, - **mhc_kwargs, - ) - elif self.dsa_enable_prefill_cp or self.mla_enable_prefill_cp: - self.layer_communicator = DSACPLayerCommunicator(**shared_kwargs) + self.layer_communicator = MHCLayerCommunicator( + **shared_kwargs, + **mhc_kwargs, + ) else: self.layer_communicator = LayerCommunicator(**shared_kwargs) @@ -836,7 +770,6 @@ def forward( zero_allocator: Optional[BumpAllocator] = None, gemm_output_zero_allocator: BumpAllocator = None, prev_topk_indices: Optional[torch.Tensor] = None, - next_full_attention_layer_id: Optional[int] = None, ): hidden_states_orig = hidden_states @@ -846,18 +779,6 @@ def forward( forward_batch, ) - # MLA consumes scattered CP layout, so rebind cached AttentionInputs to the - # scattered tensor to keep Q/KV latents and positions token-aligned. - mla_cp_wrap = not self.is_linear_attn and ( - dsa_use_prefill_cp(forward_batch, self.dsa_enable_prefill_cp) - or mla_use_prefill_cp(forward_batch, self.mla_enable_prefill_cp) - ) - if mla_cp_wrap: - hidden_states = cp_plain_to_scattered( - hidden_states, forward_batch, get_parallel().attn_cp_size - ) - get_attn_tp_context().set_hidden_states_local(hidden_states) - hidden_states = self.self_attn( positions=positions, hidden_states=hidden_states, @@ -872,15 +793,6 @@ def forward( topk_indices = None get_attn_tp_context().clear_attn_inputs() - if mla_cp_wrap: - hidden_states = cp_scattered_to_plain( - hidden_states, forward_batch, get_parallel().attn_cp_size - ) - - self.layer_communicator.maybe_prefetch_next_full_attention_kv( - forward_batch, next_full_attention_layer_id - ) - hidden_states, residual = self.layer_communicator.prepare_mlp( hidden_states, residual, @@ -922,10 +834,7 @@ def forward( gemm_output_zero_allocator, ) - if ( - not (self.dsa_enable_prefill_cp or self.mla_enable_prefill_cp) - and should_allreduce_fusion - ): + if should_allreduce_fusion: hidden_states._sglang_needs_allreduce_fusion = True if not should_allreduce_fusion: @@ -953,14 +862,6 @@ def __init__( self.vocab_size = config.vocab_size self.first_k_dense_replace = config.first_k_dense_replace self.pp_group = get_pp_group() - self.dsa_enable_prefill_cp = is_dsa_enable_prefill_cp() - self.mla_enable_prefill_cp = ( - is_prefill_context_parallel_enabled() and not is_deepseek_dsa(config) - ) - if self.dsa_enable_prefill_cp or self.mla_enable_prefill_cp: - self.cp_size = get_parallel().attn_cp_size - else: - self.cp_size = None if self.pp_group.is_first_rank: self.embed_tokens = VocabParallelEmbedding( @@ -989,24 +890,11 @@ def __init__( quant_config=quant_config, prefix=prefix, alt_stream=self.alt_stream, - dsa_enable_prefill_cp=self.dsa_enable_prefill_cp, - mla_enable_prefill_cp=self.mla_enable_prefill_cp, ), pp_rank=self.pp_group.rank_in_group, pp_size=self.pp_group.world_size, prefix=add_prefix("layers", prefix), ) - local_full_attention_layer_ids = [ - layer_id - for layer_id in config.full_attention_layer_ids - if self.start_layer <= layer_id < self.end_layer - ] - self.next_full_attention_layer_id = dict( - zip( - local_full_attention_layer_ids, - local_full_attention_layer_ids[1:], - ) - ) if self.pp_group.is_last_rank: self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) else: @@ -1116,13 +1004,6 @@ def forward( else None ) - if dsa_use_prefill_cp( - forward_batch, self.dsa_enable_prefill_cp - ) or mla_use_prefill_cp(forward_batch, self.mla_enable_prefill_cp): - if self.pp_group.is_first_rank: - hidden_states = cp_plain_split(hidden_states) - positions = cp_split_and_rebuild_position(forward_batch, positions) - normal_start_layer = self.start_layer normal_end_layer = self.end_layer if forward_batch.can_run_tbo and not self.dflash_capture: @@ -1161,9 +1042,6 @@ def forward( zero_allocator, gemm_output_zero_allocator, prev_topk_indices=topk_indices, - next_full_attention_layer_id=( - self.next_full_attention_layer_id.get(i) - ), ) if normal_end_layer != self.end_layer: @@ -1194,11 +1072,6 @@ def forward( else: hidden_states, _ = self.norm(hidden_states, residual) - if self.pp_group.is_last_rank and ( - dsa_use_prefill_cp(forward_batch, self.dsa_enable_prefill_cp) - or mla_use_prefill_cp(forward_batch, self.mla_enable_prefill_cp) - ): - hidden_states = cp_plain_all_gather(hidden_states, self.cp_size) if len(aux_hidden_states) == 0: return hidden_states return hidden_states, aux_hidden_states @@ -1282,20 +1155,6 @@ def __init__( ) self.capture_aux_hidden_states = False - self.dsa_enable_prefill_cp = ( - not self.encoder_only and is_dsa_enable_prefill_cp() - ) - self.mla_enable_prefill_cp = ( - not self.encoder_only - and is_prefill_context_parallel_enabled() - and not is_deepseek_dsa(text_config) - ) - if self.dsa_enable_prefill_cp or self.mla_enable_prefill_cp: - self.cp_rank = get_parallel().attn_cp_rank - self.cp_size = get_parallel().attn_cp_size - else: - self.cp_rank = self.cp_size = None - if not self.encoder_only: get_attn_tp_context().init_context( getattr(text_config, "q_lora_rank", None), @@ -1483,40 +1342,6 @@ def get_video_feature(self, items: List[MultimodalDataItem]) -> torch.Tensor: video_embeds = self.visual(pixel_values, grid_thw=flattened_video_grid_thw) return video_embeds - def _prepare_context_parallel_metadata( - self, - input_ids: torch.Tensor, - input_embeds: Optional[torch.Tensor], - forward_batch: ForwardBatch, - pp_proxy_tensors: Optional[PPProxyTensors] = None, - ) -> None: - if input_ids is not None: - len_input_ids = input_ids.shape[0] - elif input_embeds is not None: - len_input_ids = input_embeds.shape[0] - else: - len_input_ids = pp_proxy_tensors["hidden_states"].shape[0] - if self.dsa_enable_prefill_cp: - if can_dsa_cp_split( - len_input_ids, self.cp_size, self.use_dsa, forward_batch - ): - forward_batch.attn_cp_metadata = prepare_context_parallel_metadata( - len_input_ids, - self.cp_rank, - self.cp_size, - forward_batch.seq_lens_cpu.tolist(), - extend_seqs_len=forward_batch.extend_seq_lens_cpu, - ) - elif self.mla_enable_prefill_cp: - if can_cp_split(len_input_ids, self.cp_size, forward_batch): - forward_batch.attn_cp_metadata = prepare_context_parallel_metadata( - len_input_ids, - self.cp_rank, - self.cp_size, - forward_batch.seq_lens_cpu.tolist(), - extend_seqs_len=forward_batch.extend_seq_lens_cpu, - ) - @torch.no_grad() def forward( self, @@ -1529,9 +1354,6 @@ def forward( if self.is_mrope_enabled: positions = forward_batch.mrope_positions - self._prepare_context_parallel_metadata( - input_ids, input_embeds, forward_batch, pp_proxy_tensors - ) with get_attn_tp_context().maybe_input_scattered(forward_batch): hidden_states = general_mm_embed_routine( input_ids=input_ids, From 491cb225faf0626d014ec5a78b8ef472738490f2 Mon Sep 17 00:00:00 2001 From: Khoa Pham Date: Wed, 2 Sep 2026 17:22:17 -0700 Subject: [PATCH 25/44] Temporarily Remove GLM-5.3 Flash decode CP support (#37487) Co-authored-by: Claude Opus 5 (1M context) --- .../ops/attention/dsa/tilelang_kernel.py | 25 +-------- .../srt/layers/attention/dsa_backend.py | 28 ---------- python/sglang/srt/layers/dcp/comm.py | 5 +- .../srt/mem_cache/kv_cache_configurator.py | 11 +--- .../srt/model_executor/pool_configurator.py | 23 +++------ .../srt/model_executor/runner/eager_runner.py | 8 +-- python/sglang/srt/models/glm5_next.py | 29 ----------- test/registered/cp/test_dsa_trtllm_fp8_cp.py | 30 ----------- test/registered/dcp/test_dcp_layout_unit.py | 24 --------- .../model_executor/test_pool_configurator.py | 51 ++++--------------- 10 files changed, 21 insertions(+), 213 deletions(-) diff --git a/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py b/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py index 2c1eff2e2e3c9..4bd96eecccac7 100644 --- a/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py +++ b/python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py @@ -271,7 +271,6 @@ def sparse_attention_fwd_kernel_v1( block_I=64, num_stages=2, threads=256, - return_lse=False, ): assert ( dim == tilelang.math.next_power_of_2(dim) or dim % 64 == 0 @@ -297,7 +296,6 @@ def sparse_attention_fwd_kernel_v1( q_shape = [batch, seq_len, num_heads, dim + tail_dim] kv_shape = [batch, seq_len_kv, kv_group, dim + tail_dim] o_shape = [batch, seq_len, num_heads, dim] - lse_shape = [batch, seq_len, num_heads] indices_shape = [batch, seq_len, kv_group, topk] indices_dtype = "int32" dtype = "bfloat16" @@ -325,7 +323,6 @@ def main( Q: T.Tensor(q_shape, dtype), # type: ignore KV: T.Tensor(kv_shape, dtype), # type: ignore Indices: T.Tensor(indices_shape, indices_dtype), # type: ignore - LSE: T.Tensor(lse_shape, accum_dtype), # type: ignore Output: T.Tensor(o_shape, dtype), # type: ignore ): with T.Kernel(seq_len * REPLICATE_H, batch, kv_group, threads=threads) as ( @@ -426,8 +423,6 @@ def main( acc_o[h_i, d_i] /= sumexp[h_i] for h_i in T.Parallel(H_per_block): sumexp[h_i] = T.log2(sumexp[h_i]) + m_i[h_i] * sm_scale - if return_lse: - T.copy(sumexp, LSE[b_i, s_i, H0:H1]) T.copy(acc_o, O_shared) T.copy(acc_o, Output[b_i, s_i, H0:H1, :]) @@ -459,7 +454,6 @@ def sparse_attention_fwd_kernel_v2( kv_group: int = 1, sm_scale: Optional[float] = None, block_I: int = 64, - return_lse: bool = False, ): assert dim == tilelang.math.next_power_of_2( dim @@ -483,7 +477,6 @@ def sparse_attention_fwd_kernel_v2( q_shape = [batch, qo_len, num_heads, dim + tail_dim] kv_shape = [batch, num_pages, kv_group, dim + tail_dim] o_shape = [batch, qo_len, num_heads, dim] - lse_shape = [batch, qo_len, num_heads] indices_shape = [batch, qo_len, kv_group, topk] indices_dtype = "int32" @@ -512,7 +505,6 @@ def main( Q: T.Tensor(q_shape, dtype), # type: ignore KV: T.Tensor(kv_shape, dtype), # type: ignore Indices: T.Tensor(indices_shape, indices_dtype), # type: ignore - LSE: T.Tensor(lse_shape, accum_dtype), # type: ignore Output: T.Tensor(o_shape, dtype), # type: ignore ): """ @@ -680,8 +672,6 @@ def main( acc_o_l[h_i, d_i] /= sumexp[h_i] for h_i in T.Parallel(H_per_block): sumexp[h_i] = T.log2(sumexp[h_i]) + m_i[h_i] * sm_scale - if return_lse: - T.copy(sumexp, LSE[b_i, s_i, H0:H1]) T.copy(acc_o_l, O_shared_l) T.copy(O_shared_l, Output[b_i, s_i, H0:H1, 0 : D // 2]) elif tx >= 128 and tx < 256: @@ -1339,7 +1329,6 @@ def tilelang_sparse_fwd( indices: torch.Tensor, sm_scale: float, d_v: int = 512, - return_lse: bool = False, ) -> torch.Tensor: assert q.dim() == 3 and kv.dim() == 3 and indices.dim() == 3 num_heads = q.shape[1] @@ -1349,7 +1338,6 @@ def tilelang_sparse_fwd( assert topk % 64 == 0, "topk must be padded to a multiple of 64" if _is_hip: - assert not return_lse, "tilelang HIP sparse fwd does not return LSE" is_fp8_kv = kv.dtype in (torch.float8_e4m3fn, torch.float8_e4m3fnuz) if is_fp8_kv: if q.dtype != kv.dtype: @@ -1406,17 +1394,8 @@ def tilelang_sparse_fwd( if tail_dim == 0 else sparse_attention_fwd_kernel_v2 ) - kernel = kernel_factory( - num_heads, d_v, tail_dim, topk, sm_scale=sm_scale, return_lse=return_lse - ) - # Caller-allocated LSE (in-place kernel arg): written only by kernels - # traced with return_lse=True, but the prim_func signature always has it. - lse = torch.empty( - (1, q.shape[0], num_heads), dtype=torch.float32, device=q.device - ) - out = kernel(q.unsqueeze(0), kv.unsqueeze(0), indices.unsqueeze(0), lse) # type: ignore - if return_lse: - return out, lse + kernel = kernel_factory(num_heads, d_v, tail_dim, topk, sm_scale=sm_scale) + out = kernel(q.unsqueeze(0), kv.unsqueeze(0), indices.unsqueeze(0)) # type: ignore return out diff --git a/python/sglang/srt/layers/attention/dsa_backend.py b/python/sglang/srt/layers/attention/dsa_backend.py index f4f7b05bbed73..0553ac0366051 100644 --- a/python/sglang/srt/layers/attention/dsa_backend.py +++ b/python/sglang/srt/layers/attention/dsa_backend.py @@ -154,10 +154,6 @@ def _should_all_gather_dsa_trtllm_fp8_kv( return save_kv_cache and cos_sin_cache is not None and dsa_prefill_cp -def _should_return_dsa_dcp_lse(*, forward_mode: ForwardMode, dcp_enabled: bool) -> bool: - return dcp_enabled and (forward_mode.is_decode() or forward_mode.is_target_verify()) - - def materialize_full_kv_cp( attn_mla, forward_batch: ForwardBatch, @@ -3094,10 +3090,6 @@ def forward_extend( page_table_1=page_table_1, sm_scale=layer.scaling, v_head_dim=layer.v_head_dim, - return_lse=_should_return_dsa_dcp_lse( - forward_mode=forward_batch.forward_mode, - dcp_enabled=get_parallel().dcp_enabled, - ), ) elif dsa_impl in ("flashmla_sparse", "flashmla_sparse_q8"): if topk_transform_method == TopkTransformMethod.RAGGED: @@ -3396,10 +3388,6 @@ def forward_decode( page_table_1=page_table_1, sm_scale=layer.scaling, v_head_dim=layer.v_head_dim, - return_lse=_should_return_dsa_dcp_lse( - forward_mode=forward_batch.forward_mode, - dcp_enabled=get_parallel().dcp_enabled, - ), ) elif dsa_impl == "fa3": return self._forward_fa3( @@ -4015,7 +4003,6 @@ def _forward_tilelang( v_head_dim: int, page_table_1: torch.Tensor, sm_scale: float, - return_lse: bool = False, ) -> torch.Tensor: from sglang.kernels.ops.attention.dsa.tilelang_kernel import tilelang_sparse_fwd @@ -4032,17 +4019,6 @@ def _forward_tilelang( dim=-1, ) - if return_lse: - out, lse = tilelang_sparse_fwd( - q=q_all, - kv=kv_cache, - indices=page_table_1.unsqueeze(1), - sm_scale=sm_scale, - d_v=v_head_dim, - return_lse=True, - ) - # [1, tokens, H] -> [tokens, H], the [B, H] dcp_pack_a2a_send expects. - return out, lse.squeeze(0) return tilelang_sparse_fwd( q=q_all, kv=kv_cache, @@ -4400,10 +4376,6 @@ def _forward_trtllm( skip_softmax_threshold_scale_factor=envs.SGLANG_SKIP_SOFTMAX_DECODE_THRESHOLD_SCALE_FACTOR.get(), sparse_mla_top_k_lens=sparse_mla_top_k_lens, multi_ctas_kv_counter_buffer=self._multi_ctas_kv_counter_buffer, - return_lse=_should_return_dsa_dcp_lse( - forward_mode=forward_batch.forward_mode, - dcp_enabled=get_parallel().dcp_enabled, - ), ) return out diff --git a/python/sglang/srt/layers/dcp/comm.py b/python/sglang/srt/layers/dcp/comm.py index a89bb2a3f2e6a..915a29b7ac3f2 100644 --- a/python/sglang/srt/layers/dcp/comm.py +++ b/python/sglang/srt/layers/dcp/comm.py @@ -305,16 +305,13 @@ def all_gather_kv_cache_for_mla_extend( # all gather kv cache and re-org to query orders def all_gather_kv_cache_for_dcp( prefix_kv_a: torch.Tensor, - prefix_k_pe: Optional[torch.Tensor], + prefix_k_pe: torch.Tensor, prefix_kv_lens_cpu: torch.Tensor, prefix_starts_cpu: torch.Tensor = None, ): """ prefix_kv_a and prefix_k_pe should have same shape, expect for last dim """ - if prefix_k_pe is None: - prefix_k_pe = prefix_kv_a.new_empty((*prefix_kv_a.shape[:-1], 0)) - parallel = get_parallel() if not parallel.dcp_enabled: return torch.cat([prefix_kv_a, prefix_k_pe], dim=-1) diff --git a/python/sglang/srt/mem_cache/kv_cache_configurator.py b/python/sglang/srt/mem_cache/kv_cache_configurator.py index 9f895d96db0e2..94738a859b871 100644 --- a/python/sglang/srt/mem_cache/kv_cache_configurator.py +++ b/python/sglang/srt/mem_cache/kv_cache_configurator.py @@ -361,12 +361,6 @@ def loc_space_scale(self) -> int: def pool_page_size(self) -> int: return get_schedule().page_size * self.loc_space_scale - def _dsa_pool_geometry(self, max_total_num_tokens: int) -> tuple[int, int]: - physical_page_size = get_schedule().page_size - # Physical page stays 64 for CUDA DSA kernels; only the token pool is grown. - pool_size = max_total_num_tokens + self.pool_page_size - physical_page_size - return pool_size, physical_page_size - def _derive_pool_sizes(self, *, config: MemoryPoolConfig) -> _PoolSizes: max_total_num_tokens = config.max_total_num_tokens max_running_requests = config.max_running_requests @@ -1519,9 +1513,6 @@ def _build_dsa_kv_pool( ) -> KVCache: from sglang.srt.layers.cp.utils import get_glm_dsa_cp_layer_shard_info - max_total_num_tokens, pool_page_size = self._dsa_pool_geometry( - max_total_num_tokens - ) ( dsa_cp_layer_shard_rank, dsa_cp_layer_shard_size, @@ -1554,7 +1545,7 @@ def _build_dsa_kv_pool( ] token_to_kv_pool = PoolCls( max_total_num_tokens, - page_size=pool_page_size, + page_size=self.pool_page_size, dtype=self.kv_cache_dtype, kv_lora_rank=self.model_config.kv_lora_rank, qk_rope_head_dim=self.model_config.qk_rope_head_dim, diff --git a/python/sglang/srt/model_executor/pool_configurator.py b/python/sglang/srt/model_executor/pool_configurator.py index 5eb75701445bf..e252ca91458d6 100644 --- a/python/sglang/srt/model_executor/pool_configurator.py +++ b/python/sglang/srt/model_executor/pool_configurator.py @@ -228,23 +228,16 @@ def __init__(self, kvc: KVCacheConfigurator): target_kv_num_layers = get_glm_dsa_layer_split_effective_num_layers( kvc, num_layers ) - # Draft pools are DCP-replicated, not sharded: budget all copies. - dcp_size = kvc.ps.attn_dcp_size - draft_kv_size = ( - int(target_kv_size * draft_num_layers / target_kv_num_layers) - * dcp_size + draft_kv_size = int( + target_kv_size * draft_num_layers / target_kv_num_layers ) - draft_indexer_size = ( - self._compute_dsa_indexer_cell_size( - kvc=kvc, - num_layers=draft_num_layers, - allocate_all_layers=True, - ) - * dcp_size + draft_indexer_size = self._compute_dsa_indexer_cell_size( + kvc=kvc, + num_layers=draft_num_layers, + allocate_all_layers=True, ) self._cell_size += draft_kv_size + draft_indexer_size else: - draft_num_layers *= kvc.ps.attn_dcp_size self._cell_size = int( self._cell_size * (1 + draft_num_layers / int(num_layers)) ) @@ -586,10 +579,6 @@ def __init__(self, kvc: KVCacheConfigurator): - self._draft_swa_layers_num - self._draft_swa_full_layers_num ) - dcp_size = kvc.ps.attn_dcp_size - self._draft_swa_layers_num *= dcp_size - self._draft_swa_full_layers_num *= dcp_size - self._draft_full_layers_num *= dcp_size self._draft_cell_size = _dflash_draft_cell_size(kvc) diff --git a/python/sglang/srt/model_executor/runner/eager_runner.py b/python/sglang/srt/model_executor/runner/eager_runner.py index ecc3c92692d5f..1e6a37c07f643 100644 --- a/python/sglang/srt/model_executor/runner/eager_runner.py +++ b/python/sglang/srt/model_executor/runner/eager_runner.py @@ -295,12 +295,8 @@ def _execute_extend( or cp_v2_active or forward_batch.forward_mode.is_target_verify() ): - if ( - model_runner.ps.attn_dcp_size > 1 - and not forward_batch.forward_mode.is_target_verify() - and hasattr( - model_runner.model, "prepare_context_parallel_metadata_for_dcp" - ) + if model_runner.ps.attn_dcp_size > 1 and hasattr( + model_runner.model, "prepare_context_parallel_metadata_for_dcp" ): # prepare kv cache buffer for dcp to gather kv cache forward_batch.attn_dcp_metadata = ( diff --git a/python/sglang/srt/models/glm5_next.py b/python/sglang/srt/models/glm5_next.py index 7772f3a62f4a0..6150696f3084f 100644 --- a/python/sglang/srt/models/glm5_next.py +++ b/python/sglang/srt/models/glm5_next.py @@ -32,7 +32,6 @@ get_attn_tp_context, ) from sglang.srt.layers.communicator_mhc import MHCLayerCommunicator -from sglang.srt.layers.dcp.planner import prepare_decode_context_parallel_metadata from sglang.srt.layers.layernorm import RMSNorm from sglang.srt.layers.linear import ( ColumnParallelBatchedLinear, @@ -1254,34 +1253,6 @@ def set_dflash_layers_to_capture(self, layer_ids: List[int]): # Capturing before layer k + 1 gives the completed output of layer k. self.model.layers_to_capture = [val + 1 for val in layer_ids] - def prepare_context_parallel_metadata_for_dcp( - self, - seq_lens: torch.Tensor, - extend_prefix_lens: torch.Tensor, - extend_prefix_lens_cpu: torch.Tensor, - extend_seq_lens: torch.Tensor, - req_pool_indices: torch.Tensor, - req_to_token: torch.Tensor, - seq_lens_sum: int, - kv_buffer_shape: torch.Size, - kv_cache_dtype, - kv_cache_device, - create_chunked_prefix_cache_kv_indices_fn, - ): - return prepare_decode_context_parallel_metadata( - seq_lens=seq_lens, - extend_prefix_lens=extend_prefix_lens, - extend_prefix_lens_cpu=extend_prefix_lens_cpu, - extend_seq_lens=extend_seq_lens, - req_pool_indices=req_pool_indices, - req_to_token=req_to_token, - seq_lens_sum=seq_lens_sum, - kv_buffer_shape=kv_buffer_shape, - kv_cache_dtype=kv_cache_dtype, - kv_cache_device=kv_cache_device, - create_chunked_prefix_cache_kv_indices_fn=create_chunked_prefix_cache_kv_indices_fn, - ) - def pad_input_ids(self, input_ids: List[int], mm_inputs: MultimodalInputs): pattern = MultiModalityDataPaddingPatternMultimodalTokens() return pattern.pad_input_tokens(input_ids, mm_inputs) diff --git a/test/registered/cp/test_dsa_trtllm_fp8_cp.py b/test/registered/cp/test_dsa_trtllm_fp8_cp.py index c6543d8df2b31..3b63267479b57 100644 --- a/test/registered/cp/test_dsa_trtllm_fp8_cp.py +++ b/test/registered/cp/test_dsa_trtllm_fp8_cp.py @@ -4,9 +4,7 @@ from sglang.srt.layers.attention.dsa_backend import ( _should_all_gather_dsa_trtllm_fp8_kv, - _should_return_dsa_dcp_lse, ) -from sglang.srt.model_executor.forward_batch_info import ForwardMode from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import CustomTestCase @@ -49,34 +47,6 @@ def test_non_cp_and_no_cache_paths_do_not_gather(self): ) ) - def test_dcp_decode_and_verify_request_lse(self): - self.assertTrue( - _should_return_dsa_dcp_lse( - forward_mode=ForwardMode.DECODE, - dcp_enabled=True, - ) - ) - self.assertTrue( - _should_return_dsa_dcp_lse( - forward_mode=ForwardMode.TARGET_VERIFY, - dcp_enabled=True, - ) - ) - - def test_non_dcp_and_prefill_do_not_request_lse(self): - self.assertFalse( - _should_return_dsa_dcp_lse( - forward_mode=ForwardMode.DECODE, - dcp_enabled=False, - ) - ) - self.assertFalse( - _should_return_dsa_dcp_lse( - forward_mode=ForwardMode.EXTEND, - dcp_enabled=True, - ) - ) - if __name__ == "__main__": unittest.main() diff --git a/test/registered/dcp/test_dcp_layout_unit.py b/test/registered/dcp/test_dcp_layout_unit.py index 6d8ca055d7952..ee20e0faec5d9 100644 --- a/test/registered/dcp/test_dcp_layout_unit.py +++ b/test/registered/dcp/test_dcp_layout_unit.py @@ -437,30 +437,6 @@ def test_configurator_scales_only_the_virtual_dcp_allocator(self): self.assertEqual(dcp4_allocator.page_size, 256) self.assertEqual(dcp4_allocator.num_pages, 16) - def test_dsa_draft_pool_preserves_physical_page_and_backs_virtual_tail(self): - physical_page_size = 64 - max_total_num_tokens = 4096 - self._sa_override = rc.get_context().override_server_args( - page_size=physical_page_size - ) - self._sa_override.install() - self.addCleanup(self._sa_override.restore) - - dcp1 = SimpleNamespace(pool_page_size=physical_page_size) - dcp4_draft = SimpleNamespace(pool_page_size=physical_page_size * 4) - - self.assertEqual( - KVCacheConfigurator._dsa_pool_geometry(dcp1, max_total_num_tokens), - (max_total_num_tokens, physical_page_size), - ) - self.assertEqual( - KVCacheConfigurator._dsa_pool_geometry(dcp4_draft, max_total_num_tokens), - ( - max_total_num_tokens + physical_page_size * 3, - physical_page_size, - ), - ) - def test_live_cell_and_page_ownership_formulas(self): dcp_size = 4 physical_page_size = 64 diff --git a/test/registered/unit/model_executor/test_pool_configurator.py b/test/registered/unit/model_executor/test_pool_configurator.py index b07e08c006ae9..88f8f282bdce1 100644 --- a/test/registered/unit/model_executor/test_pool_configurator.py +++ b/test/registered/unit/model_executor/test_pool_configurator.py @@ -704,51 +704,18 @@ def test_eagle_does_not_exceed_budget(self): mr.spec_algorithm.is_none.return_value = False mr.spec_aux_config.eagle_draft_num_layers = eagle_draft_num_layers - full_pt = _full_per_token(mr) - for dcp_size in (1, 4): - with self.subTest(dcp_size=dcp_size): - mr.ps = ParallelState.trivial(attn_dcp_size=dcp_size) - with mock_cpu_env(): - from sglang.srt.model_executor.pool_configurator import ( - create_memory_pool_configurator, - ) - - cfg = create_memory_pool_configurator(mr) - config = cfg.calculate_pool_sizes(available, 1) - - total_layers = num_layers + eagle_draft_num_layers * dcp_size - used = config.max_total_num_tokens * full_pt * total_layers - self.assertLessEqual(used, available) + with mock_cpu_env(): + from sglang.srt.model_executor.pool_configurator import ( + create_memory_pool_configurator, + ) - def test_hybrid_swa_scales_draft_budget_with_dcp(self): - mr = _make_model_runner( - self, - is_hybrid_swa=True, - full_attention_layer_ids=list(range(16)), - swa_attention_layer_ids=list(range(16, 32)), - swa_num_kv_heads=4, - ) - mr.spec_algorithm.is_eagle.return_value = True - mr.spec_algorithm.is_none.return_value = False - mr.spec_aux_config.eagle_draft_num_layers = 4 + cfg = create_memory_pool_configurator(mr) + config = cfg.calculate_pool_sizes(available, 1) full_pt = _full_per_token(mr) - swa_pt = _swa_per_token(mr) - for dcp_size in (1, 4): - with self.subTest(dcp_size=dcp_size): - mr.ps = ParallelState.trivial(attn_dcp_size=dcp_size) - with mock_cpu_env(): - from sglang.srt.model_executor.pool_configurator import ( - create_memory_pool_configurator, - ) - - cfg = create_memory_pool_configurator(mr) - - expected = ( - full_pt * (16 + 4 * dcp_size) - + get_schedule().swa_full_tokens_ratio * swa_pt * 16 - ) - self.assertEqual(cfg._cell_size, expected) + total_layers = num_layers + eagle_draft_num_layers + used = config.max_total_num_tokens * full_pt * total_layers + self.assertLessEqual(used, available) @patch( "sglang.srt.mem_cache.kv_cache_configurator.calculate_mla_kv_cache_dim", From cdfc224b0e5bd0fb5d10334d787c9bd3865ba1d9 Mon Sep 17 00:00:00 2001 From: BBuf <1182563586@qq.com> Date: Thu, 3 Sep 2026 20:04:10 +0800 Subject: [PATCH 26/44] [GLM-5.3] Fix NEXTN first-request embedding OOB on multimodal requests (#37548) DeepseekModelNextN.forward called embed_tokens directly on input_ids. For VLM requests, image-token positions in input_ids hold MM_PAD_SHIFT_VALUE+hash sentinels (far above vocab_size), so the draft embedding gather went out of bounds on the first prefill and crashed with `vectorized_gather_kernel index out of bounds`. Target models avoid this via mm_input_embeds, but the NextN draft never consulted forward_batch.mm_input_embeds. This mirrors the handling that kimi_k25_eagle3 / qwen3_5_mtp already use: - DeepseekModelNextN.forward: when input_embeds is None, use forward_batch.mm_input_embeds for multimodal extends and only call embed_tokens on the appended next-token position. - _draft_extend_for_prefill: rotate mm_input_embeds alongside input_ids (left shift per request) so embeddings stay aligned with rotated ids. Verified on 1xB300 with RadixArk/GLM-5.3-Flash-NVFP4 (TP1, NEXTN 3/1/4): first VLM request + 16/32-token text generation pass with sane spec accept rates, both with and without CUDA graphs. Adds a CPU regression test that fails before the fix (sentinel id 1000006 >= vocab_size 154880 reaches embed_tokens) and passes after. --- python/sglang/srt/models/deepseek_nextn.py | 25 ++- .../sglang/srt/speculative/eagle_worker_v2.py | 13 ++ .../models/test_deepseek_nextn_mm_embed.py | 209 ++++++++++++++++++ 3 files changed, 244 insertions(+), 3 deletions(-) create mode 100644 test/registered/unit/models/test_deepseek_nextn_mm_embed.py diff --git a/python/sglang/srt/models/deepseek_nextn.py b/python/sglang/srt/models/deepseek_nextn.py index 2186ed4a92e02..a9dff094bf702 100644 --- a/python/sglang/srt/models/deepseek_nextn.py +++ b/python/sglang/srt/models/deepseek_nextn.py @@ -221,9 +221,28 @@ def forward( ) if input_embeds is None: - hidden_states = self.embed_tokens(input_ids) - else: - hidden_states = input_embeds + # MM positions in input_ids hold MM_PAD_SHIFT_VALUE+hash sentinels + # (far above vocab_size). Use target-produced mm_input_embeds for + # these positions and only call embed_tokens on the appended + # next-token to avoid embed OOB. + input_embeds = forward_batch.mm_input_embeds + if ( + forward_batch.forward_mode.is_extend() + and forward_batch.contains_mm_inputs() + and not forward_batch.forward_mode.is_draft_extend_v2() + ): + assert input_embeds is not None + last_indices = ( + forward_batch.extend_start_loc + + forward_batch.extend_seq_lens + - 1 + ).long() + input_embeds[last_indices] = self.embed_tokens( + input_ids[last_indices] + ) + if input_embeds is None: + input_embeds = self.embed_tokens(input_ids) + hidden_states = input_embeds if hidden_states.shape[0] > 0: previous_hidden_states = forward_batch.spec_info.hidden_states diff --git a/python/sglang/srt/speculative/eagle_worker_v2.py b/python/sglang/srt/speculative/eagle_worker_v2.py index 10d6311f4e679..10febfa6b30bd 100644 --- a/python/sglang/srt/speculative/eagle_worker_v2.py +++ b/python/sglang/srt/speculative/eagle_worker_v2.py @@ -813,16 +813,29 @@ def _draft_extend_for_prefill( if not batch.forward_mode.is_idle(): # Chunked-prefill-aware tail tokens (see PR #26329). tail_tokens = _eagle_prefill_tail_tokens(batch, next_token_ids) + new_input_ids = torch.empty_like(batch.input_ids) + if mm_input_embeds is not None: + # Rotate mm embeddings the same way as input_ids: shift left by + # one per request so they stay aligned with the rotated ids. The + # last position per request is filled by the draft model's own + # embed_tokens lookup on next_token_ids (see DeepseekModelNextN). + rotated_mm = torch.empty_like(mm_input_embeds) pt = 0 for i, extend_len in enumerate(batch.extend_lens): input_ids = batch.input_ids[pt : pt + extend_len] new_input_ids[pt : pt + extend_len].copy_( torch.cat((input_ids[1:], tail_tokens[i].reshape(1))) ) + if mm_input_embeds is not None: + rotated_mm[pt : pt + extend_len - 1].copy_( + mm_input_embeds[pt + 1 : pt + extend_len] + ) pt += extend_len assert pt == batch.input_ids.numel() batch.input_ids = new_input_ids + if mm_input_embeds is not None: + mm_input_embeds = rotated_mm # Draft-extend spec_info for the extend forward; carries only # hidden_states + shape info. diff --git a/test/registered/unit/models/test_deepseek_nextn_mm_embed.py b/test/registered/unit/models/test_deepseek_nextn_mm_embed.py new file mode 100644 index 0000000000000..ada7e6715e700 --- /dev/null +++ b/test/registered/unit/models/test_deepseek_nextn_mm_embed.py @@ -0,0 +1,209 @@ +"""Regression test for sgl-project/sglang#37548. + +DeepseekModelNextN.forward must use forward_batch.mm_input_embeds for multimodal +positions (where input_ids hold MM_PAD_SHIFT_VALUE+hash sentinels far above +vocab_size) instead of calling embed_tokens on those sentinel values, which +causes a CUDA index-out-of-bounds gather. +""" + +import unittest +from unittest.mock import MagicMock, patch + +import torch +from sglang.srt.managers.schedule_batch import MM_PAD_SHIFT_VALUE +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=30, suite="base-a-test-cpu") + +VOCAB_SIZE = 154880 +HIDDEN_SIZE = 64 # tiny for CPU test + + +def _make_forward_batch( + input_ids: torch.Tensor, + mm_input_embeds: torch.Tensor = None, + extend_seq_lens: torch.Tensor = None, + extend_start_loc: torch.Tensor = None, + has_mm: bool = True, +): + """Build a minimal mock ForwardBatch for DeepseekModelNextN.forward.""" + fb = MagicMock() + fb.mm_input_embeds = mm_input_embeds + fb.contains_mm_inputs.return_value = has_mm + fb.forward_mode.is_extend.return_value = True + fb.forward_mode.is_draft_extend_v2.return_value = False + fb.forward_mode.is_idle.return_value = False + fb.extend_seq_lens = extend_seq_lens + fb.extend_start_loc = extend_start_loc + fb.spec_info.hidden_states = torch.randn(input_ids.shape[0], HIDDEN_SIZE) + return fb + + +def _make_model_nextn(vocab_size: int, hidden_size: int): + """Build a mock DeepseekModelNextN with a real embed_tokens layer.""" + from sglang.srt.models.deepseek_nextn import DeepseekModelNextN + + model = DeepseekModelNextN.__new__(DeepseekModelNextN) + torch.nn.Module.__init__(model) + # Minimal attributes needed by forward + model.vocab_size = vocab_size + model.embed_tokens = torch.nn.Embedding(vocab_size, hidden_size) + model.enorm = torch.nn.RMSNorm(hidden_size) + model.hnorm = torch.nn.RMSNorm(hidden_size) + model.eh_proj = torch.nn.Linear(2 * hidden_size, hidden_size, bias=False) + model.rot_weight = None + model.alt_stream = None + model.quant_config = None + model.cp_rank = None + model.cp_size = None + model.dsa_enable_prefill_cp = False + model.mla_enable_prefill_cp = False + model.mtp_block = MagicMock(side_effect=lambda **kw: (kw["hidden_states"], None)) + return model + + +class TestDeepseekNextNMmEmbed(CustomTestCase): + """DeepseekModelNextN must not call embed_tokens on MM sentinel token ids.""" + + def test_mm_sentinel_ids_do_not_cause_oob(self): + """input_ids containing MM_PAD_SHIFT_VALUE+hash must not reach embed_tokens.""" + num_tokens = 10 + mm_start, mm_end = 3, 7 # MM sentinel positions + + input_ids = torch.arange(num_tokens, dtype=torch.long) + # Insert MM sentinel values + for i in range(mm_start, mm_end): + input_ids[i] = MM_PAD_SHIFT_VALUE + i + + # Build mm_input_embeds matching the target-produced embeddings + mm_embeds = torch.randn(num_tokens, HIDDEN_SIZE) + extend_seq_lens = torch.tensor([num_tokens]) + extend_start_loc = torch.tensor([0]) + + fb = _make_forward_batch( + input_ids, + mm_input_embeds=mm_embeds.clone(), + extend_seq_lens=extend_seq_lens, + extend_start_loc=extend_start_loc, + ) + + model = _make_model_nextn(VOCAB_SIZE, HIDDEN_SIZE) + + # Use MagicMock to track embed_tokens calls + mock_embed = MagicMock(side_effect=model.embed_tokens) + object.__setattr__(model, "embed_tokens", mock_embed) + + with ( + patch( + "sglang.srt.models.deepseek_nextn.is_cp_v2_active", return_value=False + ), + patch( + "sglang.srt.models.deepseek_nextn.dsa_use_prefill_cp", + return_value=False, + ), + patch( + "sglang.srt.models.deepseek_nextn.mla_use_prefill_cp", + return_value=False, + ), + patch( + "sglang.srt.models.deepseek_nextn.fused_eh_norm", + side_effect=lambda h, p, ew, hw, eps: torch.cat( + [model.enorm(h), model.hnorm(p)], dim=-1 + ), + ), + patch( + "sglang.srt.models.deepseek_nextn.get_global_expert_distribution_recorder" + ), + patch("sglang.srt.models.deepseek_nextn.is_cuda", False), + patch("sglang.srt.models.deepseek_nextn.is_npu", False), + patch("sglang.srt.models.deepseek_nextn.envs") as mock_envs, + patch("sglang.srt.models.deepseek_nextn.get_model") as mock_get_model, + patch("sglang.srt.models.deepseek_nextn.get_parallel") as mock_get_parallel, + patch("sglang.srt.models.deepseek_nextn.get_spec") as mock_get_spec, + ): + mock_envs.SGLANG_NPU_USE_MULTI_STREAM.get.return_value = False + mock_get_model.return_value.quantization = None + + positions = torch.arange(num_tokens, dtype=torch.long) + try: + model.forward(input_ids, positions, fb) + except Exception: + pass # We only care about embed_tokens call args + + # embed_tokens should only be called for last_indices (the appended + # next-token), not with the full input_ids containing MM sentinels. + for call in mock_embed.call_args_list: + call_ids = call[0][0] + max_id = call_ids.max().item() + self.assertLess( + max_id, + VOCAB_SIZE, + f"embed_tokens was called with id {max_id} >= vocab_size " + f"{VOCAB_SIZE}. MM sentinel values (MM_PAD_SHIFT_VALUE+hash) " + f"must not reach embed_tokens.", + ) + + def test_no_mm_falls_back_to_embed_tokens(self): + """Without mm_input_embeds, embed_tokens is called normally.""" + num_tokens = 5 + input_ids = torch.arange(num_tokens, dtype=torch.long) + + fb = _make_forward_batch( + input_ids, + mm_input_embeds=None, + extend_seq_lens=torch.tensor([num_tokens]), + extend_start_loc=torch.tensor([0]), + has_mm=False, + ) + + model = _make_model_nextn(VOCAB_SIZE, HIDDEN_SIZE) + mock_embed = MagicMock(side_effect=model.embed_tokens) + object.__setattr__(model, "embed_tokens", mock_embed) + embed_calls = mock_embed.call_args_list + + with ( + patch( + "sglang.srt.models.deepseek_nextn.is_cp_v2_active", return_value=False + ), + patch( + "sglang.srt.models.deepseek_nextn.dsa_use_prefill_cp", + return_value=False, + ), + patch( + "sglang.srt.models.deepseek_nextn.mla_use_prefill_cp", + return_value=False, + ), + patch( + "sglang.srt.models.deepseek_nextn.fused_eh_norm", + side_effect=lambda h, p, ew, hw, eps: torch.cat( + [model.enorm(h), model.hnorm(p)], dim=-1 + ), + ), + patch( + "sglang.srt.models.deepseek_nextn.get_global_expert_distribution_recorder" + ), + patch("sglang.srt.models.deepseek_nextn.is_cuda", False), + patch("sglang.srt.models.deepseek_nextn.is_npu", False), + patch("sglang.srt.models.deepseek_nextn.envs") as mock_envs, + patch("sglang.srt.models.deepseek_nextn.get_model") as mock_get_model, + patch("sglang.srt.models.deepseek_nextn.get_parallel") as mock_get_parallel, + patch("sglang.srt.models.deepseek_nextn.get_spec") as mock_get_spec, + ): + mock_envs.SGLANG_NPU_USE_MULTI_STREAM.get.return_value = False + mock_get_model.return_value.quantization = None + + positions = torch.arange(num_tokens, dtype=torch.long) + try: + model.forward(input_ids, positions, fb) + except Exception: + pass + + # embed_tokens should be called with the full input_ids + self.assertTrue(mock_embed.call_count > 0, "embed_tokens should be called") + full_ids_call = mock_embed.call_args_list[0][0][0] + self.assertEqual(full_ids_call.numel(), num_tokens) + + +if __name__ == "__main__": + unittest.main() From 2d7606bfcd4a2253796ef5ffd64b38980dd5f255 Mon Sep 17 00:00:00 2001 From: Raiden Makoto <81530826+Raiden-Makoto@users.noreply.github.com> Date: Thu, 3 Sep 2026 15:31:05 -0700 Subject: [PATCH 27/44] [AMD] [GLM-5.3-Flash Day 0] Enable FP8 and Quark MXFP4 MoE on gfx950 (#37629) Co-authored-by: Raiden-Makoto --- .../sglang/srt/layers/moe/moe_runner/aiter.py | 11 +- python/sglang/srt/layers/quantization/fp8.py | 22 + .../quark/schemes/quark_w4a4_mxfp4_moe.py | 28 +- .../manual/test_glm53_flash_moe_checkpoint.py | 625 ++++++++++++++++++ .../moe/test_glm53_flash_quark_moe_mi35x.py | 397 +++++++++++ .../test_glm53_flash_quark_moe.py | 281 ++++++++ 6 files changed, 1356 insertions(+), 8 deletions(-) create mode 100644 test/manual/test_glm53_flash_moe_checkpoint.py create mode 100644 test/registered/kernels/ops/moe/test_glm53_flash_quark_moe_mi35x.py create mode 100644 test/registered/unit/layers/quantization/test_glm53_flash_quark_moe.py diff --git a/python/sglang/srt/layers/moe/moe_runner/aiter.py b/python/sglang/srt/layers/moe/moe_runner/aiter.py index 6159fbca65bae..c87e000794249 100644 --- a/python/sglang/srt/layers/moe/moe_runner/aiter.py +++ b/python/sglang/srt/layers/moe/moe_runner/aiter.py @@ -282,10 +282,13 @@ def run( # `SGLANG_USE_AITER_MOE_GU_ITLV=0` to switch to SEPARATED, which # matches the layout produced by `Mxfp4MoEMethod` (gpt-oss # MXFP4) and the gptoss_fp4 tuned FlyDSL kernels. - extra["gate_mode"] = ( - GateMode.INTERLEAVE.value - if envs.SGLANG_USE_AITER_MOE_GU_ITLV.get() - else GateMode.SEPARATED.value + extra.setdefault( + "gate_mode", + ( + GateMode.INTERLEAVE.value + if envs.SGLANG_USE_AITER_MOE_GU_ITLV.get() + else GateMode.SEPARATED.value + ), ) extra["swiglu_limit"] = quant_info.swiglu_limit if self.config.no_combine: diff --git a/python/sglang/srt/layers/quantization/fp8.py b/python/sglang/srt/layers/quantization/fp8.py index 1ed1d21c8a302..cab479c17c566 100644 --- a/python/sglang/srt/layers/quantization/fp8.py +++ b/python/sglang/srt/layers/quantization/fp8.py @@ -1619,6 +1619,7 @@ def process_weights_after_loading_block_quant(self, layer: Module) -> None: layer.w2_weight.data = shuffle_weight( layer.w2_weight.contiguous(), (16, 16) ) + layer._aiter_gate_up_interleaved = False return elif self.use_mxfp8: self._process_mxfp8_moe_weights( @@ -1657,6 +1658,7 @@ def process_weights_after_loading_block_quant(self, layer: Module) -> None: layer.w2_weight.data = shuffle_weight( layer.w2_weight.contiguous(), (16, 16) ) + layer._aiter_gate_up_interleaved = False elif _use_aiter: # Pre-shuffle weights t = shuffle_weight(layer.w13_weight, (16, 16)) @@ -1665,6 +1667,7 @@ def process_weights_after_loading_block_quant(self, layer: Module) -> None: t = shuffle_weight(layer.w2_weight, (16, 16)) layer.w2_weight.copy_(t) del t + layer._aiter_gate_up_interleaved = False elif _is_cpu: assert _is_cpu_amx_available, ( "Fp8MoEMethod on CPU requires that CPU has AMX support" @@ -2345,6 +2348,7 @@ def process_weights_hip_scale_padding(self, layer: Module): requires_grad=False, ) torch.cuda.empty_cache() + layer._aiter_gate_up_interleaved = False # ROCm (_use_aiter): using column-wise scaling layer.w13_weight_scale1 *= layer.w13_weight_scale.unsqueeze(-1) @@ -2743,6 +2747,23 @@ def maybe_get_hip_aiter_quant_info( quant_type = AiterQuantType.PER_TOKEN w13_scale = layer.w13_weight_scale1 w2_scale = layer.w2_weight_scale1 + + fused_moe_kwargs = None + gate_up_interleaved = getattr(layer, "_aiter_gate_up_interleaved", None) + if ( + gate_up_interleaved is not None + and (self.moe_runner_config.swiglu_limit or 0.0) > 0 + ): + from aiter.ops.flydsl.moe_common import GateMode + + fused_moe_kwargs = { + "gate_mode": ( + GateMode.INTERLEAVE.value + if gate_up_interleaved + else GateMode.SEPARATED.value + ) + } + return AiterMoeQuantInfo( w13_weight=w13_weight, w2_weight=w2_weight, @@ -2753,6 +2774,7 @@ def maybe_get_hip_aiter_quant_info( swiglu_limit=self.moe_runner_config.swiglu_limit or 0.0, hidden_pad=getattr(layer, "hidden_pad", 0), intermediate_pad=getattr(layer, "intermediate_pad", 0), + fused_moe_kwargs=fused_moe_kwargs, ) diff --git a/python/sglang/srt/layers/quantization/quark/schemes/quark_w4a4_mxfp4_moe.py b/python/sglang/srt/layers/quantization/quark/schemes/quark_w4a4_mxfp4_moe.py index 12243eb5c2e0e..5ce7cb57e91a0 100644 --- a/python/sglang/srt/layers/quantization/quark/schemes/quark_w4a4_mxfp4_moe.py +++ b/python/sglang/srt/layers/quantization/quark/schemes/quark_w4a4_mxfp4_moe.py @@ -38,12 +38,12 @@ logger = logging.getLogger(__name__) -_is_shuffle_moe_mxfp4 = is_gfx95_supported() - __all__ = ["QuarkW4A4MXFp4MoE"] _is_hip = is_hip() _use_aiter = get_bool_env_var("SGLANG_USE_AITER") and _is_hip +_is_gfx95 = is_gfx95_supported() +_is_shuffle_moe_mxfp4 = _use_aiter and _is_gfx95 if _use_aiter: from aiter.ops.shuffle import moe_shuffle_scale, moe_shuffle_weight, shuffle_weight from aiter.utility.fp4_utils import e8m0_shuffle @@ -202,6 +202,8 @@ def create_weights( is_concat=True, is_packed=True, ) + layer.hidden_pad = 0 + layer.intermediate_pad = w13_up_dim // 2 - intermediate_size_per_partition # Add the quantization method used (per tensor/grouped/channel) # to ensure the weight scales are loaded in properly @@ -819,6 +821,11 @@ def _quantize_w2_online(self, layer, dynamic_mxfp4_quant): layer.w2_weight = torch.nn.Parameter(qw2_weight, requires_grad=False) def process_weights_after_loading(self, layer: torch.nn.Module) -> None: + if not getattr(self, "_owns_moe_runner", False): + raise RuntimeError( + "Quark MXFP4 weight preshuffling requires an owned AITER runner." + ) + if ( not self.is_checkpoint_mxfp4_serialized or self.dequantization_config is not None @@ -889,15 +896,19 @@ def create_moe_runner( ) self.moe_runner_config = moe_runner_config + self._owns_moe_runner = False moe_runner_backend = get_moe_runner_backend() if moe_runner_backend.is_auto() and get_moe_a2a_backend().supports_aiter(): moe_runner_backend = MoeRunnerBackend.AITER if moe_runner_backend.is_aiter(): self.runner = MoeRunner(moe_runner_backend, moe_runner_config) + self._owns_moe_runner = True else: - # TODO(cwan): refactor other backends - pass + raise NotImplementedError( + "Quark MXFP4 MoE currently requires the AITER runner; " + f"got {moe_runner_backend.value!r}." + ) def apply_weights( self, @@ -924,6 +935,12 @@ def apply_weights( from aiter.ops.flydsl.moe_common import GateMode _fused_moe_kwargs = {"gate_mode": GateMode.INTERLEAVE.value} + elif _is_gfx95: + from aiter.ops.flydsl.moe_common import GateMode + + # Quark checkpoints store gate and up projections as separate + # contiguous row ranges. Keep that ordering for correctness. + _fused_moe_kwargs = {"gate_mode": GateMode.SEPARATED.value} else: _fused_moe_kwargs = None @@ -934,6 +951,9 @@ def apply_weights( w13_scale=layer.w13_weight_scale, w2_scale=layer.w2_weight_scale, expert_mask=layer.dispatcher.expert_mask_gpu, + hidden_pad=getattr(layer, "hidden_pad", 0), + intermediate_pad=getattr(layer, "intermediate_pad", 0), + swiglu_limit=self.moe_runner_config.swiglu_limit or 0.0, fused_moe_kwargs=_fused_moe_kwargs, ) return self.runner.run(dispatch_output, quant_info) diff --git a/test/manual/test_glm53_flash_moe_checkpoint.py b/test/manual/test_glm53_flash_moe_checkpoint.py new file mode 100644 index 0000000000000..a1751831974b9 --- /dev/null +++ b/test/manual/test_glm53_flash_moe_checkpoint.py @@ -0,0 +1,625 @@ +"""Checkpoint-driven MoE validation for GLM-5.3-Flash. + +This test loads selected expert tensors, never the model. Set: + + GLM53_FLASH_FP8_PATH=/path/to/zai-org/GLM-5.3-Flash + GLM53_FLASH_MXFP4_PATH=/path/to/GLM-5.3-Flash-Quark-MXFP4-AttnFP8 +""" + +import json +import os +import re +import struct +import unittest +from pathlib import Path +from types import SimpleNamespace + +import torch +import torch.nn.functional as F +from aiter.ops.flydsl.moe_common import GateMode +from aiter.ops.shuffle import shuffle_weight +from aiter.ops.triton.quant import dynamic_mxfp4_quant +from aiter.utility.fp4_utils import e8m0_shuffle +from safetensors import safe_open + +from sglang.kernels.ops.layernorm import mhc +from sglang.srt.layers.moe.moe_runner.aiter import ( + AiterMoeQuantInfo, + AiterQuantType, + AiterRunnerCore, + AiterRunnerInput, +) +from sglang.srt.layers.quantization.fp8_utils import dequant_mxfp4 +from sglang.srt.utils import is_gfx95_supported, is_hip +from sglang.test.test_utils import CustomTestCase + + +class TestGLM53FlashMoECheckpoint(CustomTestCase): + hidden_size = 4096 + intermediate_size = 2048 + num_experts = 288 + swiglu_limit = 10.0 + target = re.compile( + r"^model\.language_model\.layers\.(?:[3-9]|[1-3][0-9]|4[0-4])" + r"\.mlp\.experts\.\d+\.(?:gate_proj|up_proj|down_proj)\.weight$" + ) + + @classmethod + def setUpClass(cls): + super().setUpClass() + source = os.environ.get("GLM53_FLASH_FP8_PATH") + quantized = os.environ.get("GLM53_FLASH_MXFP4_PATH") + if not source or not quantized: + raise unittest.SkipTest( + "set GLM53_FLASH_FP8_PATH and GLM53_FLASH_MXFP4_PATH" + ) + cls.source = Path(source) + cls.quantized = Path(quantized) + cls.source_map, cls.source_headers = cls._read_headers(cls.source) + cls.quantized_map, cls.quantized_headers = cls._read_headers(cls.quantized) + config = json.loads((cls.quantized / "config.json").read_text()) + text_config = config.get("text_config", config) + cls.rms_eps = text_config["rms_norm_eps"] + cls.hc_eps = text_config["hc_eps"] + cls.sinkhorn_iters = text_config["hc_sinkhorn_iters"] + cls.runner = AiterRunnerCore( + SimpleNamespace( + no_combine=False, + activation="silu", + gemm1_alpha=None, + gemm1_clamp_limit=None, + ) + ) + + @classmethod + def tearDownClass(cls): + if hasattr(cls, "runner"): + del cls.runner + torch.cuda.empty_cache() + super().tearDownClass() + + @staticmethod + def _read_headers(root): + weight_map = json.loads((root / "model.safetensors.index.json").read_text())[ + "weight_map" + ] + headers = {} + for filename in sorted(set(weight_map.values())): + with (root / filename).open("rb") as stream: + size = struct.unpack("