Skip to content

vllm.models.deepseek_v4.compressor

Classes:

Functions:

DeepseekCompressor

Bases: Module

DeepSeek V4 KV/score compressor.

Owns the linear / norm / state-cache / ape state and the shared forward prologue (kv/score split, save_partial_states launch). The compress → norm → RoPE → store step is dispatched to a triton kernel (compress_norm_rope_store_triton) by default, except for the NVIDIA head_dim=512 path which uses the CuTeDSL compressor kernels for better performance.

Source code in vllm/models/deepseek_v4/compressor.py
class DeepseekCompressor(nn.Module):
    """DeepSeek V4 KV/score compressor.

    Owns the linear / norm / state-cache / ape state and the shared forward
    prologue (kv/score split, save_partial_states launch). The
    compress → norm → RoPE → store step is dispatched to a triton kernel
    (`compress_norm_rope_store_triton`) by default, except for the NVIDIA
    head_dim=512 path which uses the CuTeDSL compressor kernels for better
    performance.
    """

    def __init__(
        self,
        vllm_config: VllmConfig,
        compress_ratio: int,
        hidden_size: int,
        head_dim: int,
        rotate: bool = False,
        prefix: str = "",
        k_cache_prefix="",
        use_fp4_cache: bool = False,
    ):
        super().__init__()
        self.compress_ratio = compress_ratio
        self.hidden_size = hidden_size
        self.head_dim = head_dim
        self.rotate = rotate
        self.prefix = prefix
        self.k_cache_prefix = k_cache_prefix
        self.use_fp4_cache = use_fp4_cache

        config = vllm_config.model_config.hf_config
        self.rope_head_dim = config.qk_rope_head_dim
        self.nope_head_dim = self.head_dim - self.rope_head_dim
        self.rms_norm_eps = config.rms_norm_eps
        self.device = current_platform.device_type
        self.max_num_reqs = vllm_config.scheduler_config.max_num_seqs
        self.max_model_len = vllm_config.model_config.max_model_len

        self.overlap = compress_ratio == 4
        self.coff = 1 + self.overlap

        # The head=512 cr>=128 no-overlap deep gather uses the two-stage
        # compressor, which needs an fp32 scratch [max_batched, 512] for
        # the intermediate compressed_kv.
        # Currently only tested on ROCm
        self._use_two_stage_fused_compressor = (
            _prefer_two_stage_compressor() and head_dim == 512 and not self.overlap
        )
        self.max_num_batched_tokens = (
            vllm_config.scheduler_config.max_num_batched_tokens
        )
        self._compress_scratch: torch.Tensor | None = None
        if self._use_two_stage_fused_compressor:
            self._compress_scratch = torch.empty(
                self.max_num_batched_tokens,
                self.head_dim,
                dtype=torch.float32,
                device=self.device,
            )

        state_dtype = torch.float32
        self.ape = nn.Parameter(
            torch.empty(
                (compress_ratio, self.coff * self.head_dim),
                dtype=state_dtype,
                device=self.device,
            ),
            requires_grad=False,
        )

        # CPU packs the weight for its GEMM and frees the raw copy, so it keeps
        # the quant-method forward and upcasts the BF16 output itself.
        kv_score_linear = (
            MergedColumnParallelLinear
            if current_platform.is_cpu()
            else DeepseekV4CompressorKVScoreLinear
        )
        self.fused_wkv_wgate = kv_score_linear(
            self.hidden_size,
            [self.coff * self.head_dim, self.coff * self.head_dim],
            bias=False,
            return_bias=False,
            quant_config=None,
            disable_tp=True,
            prefix=f"{prefix}.fused_wkv_wgate",
        )
        self.norm = RMSNorm(self.head_dim, self.rms_norm_eps)

        self.state_cache = CompressorStateCache(
            state_dim=2 * self.coff * self.head_dim,  # kv_state + score_state
            dtype=state_dtype,
            compress_ratio=compress_ratio,
            prefix=f"{prefix}.state_cache",
        )

        # Save reference to static_forward_context for forward-time KV cache lookup.
        # get_current_vllm_config() is only available during __init__, not forward.
        self._static_forward_context = (
            vllm_config.compilation_config.static_forward_context
        )

        if self.head_dim == 512:
            assert not use_fp4_cache, (
                "MXFP4 cache is only supported for indexer (head=128)"
            )
            self._quant_block = 64
            self._token_stride = self.nope_head_dim + self.rope_head_dim * 2
            self._scale_dim = self.nope_head_dim // 64 + 1  # 7 real + 1 pad
        elif self.head_dim == 128:
            if use_fp4_cache:
                self._quant_block = MXFP4_BLOCK_SIZE
                self._token_stride = self.head_dim // 2
                self._scale_dim = self.head_dim // MXFP4_BLOCK_SIZE
            else:
                self._quant_block = 128
                self._token_stride = self.head_dim
                self._scale_dim = 4  # single float32 scale
        else:
            raise ValueError(
                f"Unsupported head_dim for fused quant+cache: {self.head_dim}"
            )

        if vllm_config.kernel_config.enable_jit_warmup:
            _SAVE_PARTIAL_STATES_KERNEL.register_warmup(
                head_dim=self.head_dim,
                compress_ratio=self.compress_ratio,
            )
            if current_platform.is_cuda() and self.head_dim == 512:
                from vllm.models.deepseek_v4.nvidia.ops.sparse_attn_compress_cutedsl import (  # noqa: E501
                    _SPARSE_ATTN_COMPRESS_C128_BLOCK8_KERNEL,
                    _SPARSE_ATTN_COMPRESS_NORM_ROPE_STORE_C4_KERNEL,
                    _SPARSE_ATTN_COMPRESS_NORM_ROPE_STORE_FULL_C4_KERNEL,
                    _SPARSE_ATTN_NORM_ROPE_STORE_FULL_KERNEL,
                    _SPARSE_ATTN_NORM_ROPE_STORE_KERNEL,
                )

                store_full_kv = vllm_config.cache_config.cache_dtype != "fp8_ds_mla"
                if self.compress_ratio == 4:
                    (
                        _SPARSE_ATTN_COMPRESS_NORM_ROPE_STORE_FULL_C4_KERNEL
                        if store_full_kv
                        else _SPARSE_ATTN_COMPRESS_NORM_ROPE_STORE_C4_KERNEL
                    ).register_warmup()
                else:
                    _SPARSE_ATTN_COMPRESS_C128_BLOCK8_KERNEL.register_warmup()
                    if store_full_kv:
                        _SPARSE_ATTN_NORM_ROPE_STORE_FULL_KERNEL.register_warmup()
                    else:
                        _SPARSE_ATTN_NORM_ROPE_STORE_KERNEL.register_warmup(
                            vllm_config,
                            k_cache_prefix=self.k_cache_prefix,
                            compress_ratio=self.compress_ratio,
                        )
            else:
                from vllm.models.deepseek_v4.common.ops.fused_compress_quant_cache import (  # noqa: E501
                    _FUSED_KV_COMPRESS_NORM_ROPE_INSERT_INDEXER_TRITON_KERNEL,
                )

                _FUSED_KV_COMPRESS_NORM_ROPE_INSERT_INDEXER_TRITON_KERNEL.register_warmup()

    def forward(
        self,
        # [num_tokens, 2 * self.coff * self.head_dim]
        kv_score: torch.Tensor,
        # [num_tokens]
        positions: torch.Tensor,
        rotary_emb,
    ) -> None:
        # Each of shape [num_tokens, coff * self.head_dim]
        # input bf16, output are fp32
        kv, score = kv_score.split(
            [self.coff * self.head_dim, self.coff * self.head_dim], dim=-1
        )

        # Get the metadata and handle dummy profiling run.
        forward_context = get_forward_context()
        attn_metadata = forward_context.attn_metadata
        if not isinstance(attn_metadata, dict):
            return

        state_metadata = cast(
            CompressorMetadata, attn_metadata[self.state_cache.prefix]
        )
        slot_mapping = state_metadata.slot_mapping
        block_size = state_metadata.block_size

        # [num_blocks, block_size, kv_dim+score_dim], where kv_dim == score_dim
        state_cache = self.state_cache.kv_cache
        # kv_state stored in first half, score_state stored in second half
        state_width = state_cache.shape[-1] // 2
        pdl_kwargs = (
            {}
            if current_platform.is_rocm() or current_platform.is_xpu()
            else {"launch_pdl": False}
        )

        # Store the KV and score (with fused APE addition) in the state.
        # NOTE: PDL is disabled — both this kernel and the compress kernels
        # below depend on preceding kernel outputs (kv/score from the cublas
        # GEMM; state_cache from this kernel) but neither emits/waits on PDL
        # grid dependency primitives, so launch_pdl=True caused a
        # read-after-write race and non-deterministic output.
        _SAVE_PARTIAL_STATES_KERNEL(
            kv=kv,
            score=score,
            ape=self.ape,
            positions=positions,
            state_cache=state_cache,
            slot_mapping=slot_mapping,
            block_size=block_size,
            state_width=state_width,
            compress_ratio=self.compress_ratio,
            pdl_kwargs=pdl_kwargs,
        )

        # A captured graph would replay the capture batch's skip decision.
        if (
            current_platform.is_cuda()
            and self.head_dim == 512
            and self.compress_ratio == 128
            and not torch.cuda.is_current_stream_capturing()
            and state_metadata.c128_boundary is False
        ):
            return

        self._compress_norm_rope_store(
            state_metadata,
            state_cache,
            state_width,
            positions,
            rotary_emb,
            attn_metadata,
            pdl_kwargs,
        )

    def _compress_norm_rope_store(
        self,
        state_metadata: CompressorMetadata,
        state_cache: torch.Tensor,
        state_width: int,
        positions: torch.Tensor,
        rotary_emb,
        attn_metadata: dict[str, Any],
        pdl_kwargs: dict,
    ) -> None:
        """Compress the saved states and write K to the cache; a platform
        subclass overrides it to write its own cache layout."""
        token_to_req_indices = state_metadata.token_to_req_indices
        slot_mapping = state_metadata.slot_mapping
        num_actual = slot_mapping.shape[0]
        block_table = state_metadata.block_table
        block_size = state_metadata.block_size

        # Fused: compress → RMSNorm → RoPE → FP8 quant → KV cache write.
        # RoPE requirements (kernel applies forward GPT-J style rotation):
        # - is_neox_style=False (interleaved pairs, NOT split-half)
        # - cos_sin_cache layout: [max_pos, rope_head_dim] with first half cos,
        #   second half sin (per-pair, length rope_head_dim // 2 each)
        # - applied to LAST rope_head_dim elements of head_dim
        # - position used: (positions // compress_ratio) * compress_ratio
        cos_sin_cache = rotary_emb.cos_sin_cache
        k_cache_metadata = cast(Any, attn_metadata[self.k_cache_prefix])
        k_cache_layer = self._static_forward_context[self.k_cache_prefix]
        kv_cache = k_cache_layer.kv_cache

        # Plain-row V4 reads a contiguous bf16 / per-tensor fp8 cache row; the
        # fp8_ds_mla path uses the UE8M0 paged uint8 layout.
        store_full_kv = self.head_dim == 512 and kv_cache.dtype != torch.uint8
        store_full_fp8 = kv_cache.dtype == torch.float8_e4m3fn
        fp8_scale = (
            getattr(k_cache_layer, "_flashinfer_fp8_kv_scale", None)
            if store_full_fp8
            else None
        )

        # cutedsl (head=512) accepts the full-cache flags; triton (indexer/AMD)
        # does not, so the two callables have different signatures.
        compress_norm_rope_store_fn: Any
        if current_platform.is_cuda() and self.head_dim == 512:
            from .nvidia.ops.sparse_attn_compress_cutedsl import (
                _SPARSE_ATTN_COMPRESSOR_CUTEDSL_KERNEL,
            )

            # head=512 on CUDA always uses cutedsl, for both the fp8_ds_mla
            # layout and the plain full-cache layout. The full-cache flags
            # are consumed only here.
            compress_norm_rope_store_fn = _SPARSE_ATTN_COMPRESSOR_CUTEDSL_KERNEL
            extra_kwargs: dict[str, Any] = dict(
                store_full_kv=store_full_kv,
                store_full_fp8=store_full_fp8,
                fp8_scale=fp8_scale,
            )
        elif self._use_two_stage_fused_compressor:
            # head=512 cr>=128 (no overlap): two-pass split compressor on the
            # prefill suffix, single-pass on the decode prefix.
            assert state_metadata.num_decode_tokens is not None
            compress_norm_rope_store_fn = compress_norm_rope_store_two_stage_triton
            extra_kwargs = {
                "num_decode_tokens": state_metadata.num_decode_tokens,
                "compress_scratch": self._compress_scratch,
                "fp8_scale": fp8_scale,
            }
        else:
            # Indexer path (head_dim == 128) or non-CUDA GPUs (AMD, XPU, etc.).
            compress_norm_rope_store_fn = compress_norm_rope_store_triton
            extra_kwargs = {"fp8_scale": fp8_scale}

        compress_norm_rope_store_fn(
            state_cache=state_cache,
            num_actual=num_actual,
            token_to_req_indices=token_to_req_indices,
            positions=positions,
            slot_mapping=slot_mapping,
            block_table=block_table,
            block_size=block_size,
            state_width=state_width,
            cos_sin_cache=cos_sin_cache,
            kv_cache=kv_cache,
            k_cache_metadata=k_cache_metadata,
            pdl_kwargs=pdl_kwargs,
            head_dim=self.head_dim,
            rope_head_dim=self.rope_head_dim,
            compress_ratio=self.compress_ratio,
            overlap=self.overlap,
            use_fp4_cache=self.use_fp4_cache,
            rms_norm_weight=self.norm.weight,
            rms_norm_eps=self.rms_norm_eps,
            quant_block=self._quant_block,
            token_stride=self._token_stride,
            scale_dim=self._scale_dim,
            **extra_kwargs,
        )

_compress_norm_rope_store(state_metadata, state_cache, state_width, positions, rotary_emb, attn_metadata, pdl_kwargs)

Compress the saved states and write K to the cache; a platform subclass overrides it to write its own cache layout.

Source code in vllm/models/deepseek_v4/compressor.py
def _compress_norm_rope_store(
    self,
    state_metadata: CompressorMetadata,
    state_cache: torch.Tensor,
    state_width: int,
    positions: torch.Tensor,
    rotary_emb,
    attn_metadata: dict[str, Any],
    pdl_kwargs: dict,
) -> None:
    """Compress the saved states and write K to the cache; a platform
    subclass overrides it to write its own cache layout."""
    token_to_req_indices = state_metadata.token_to_req_indices
    slot_mapping = state_metadata.slot_mapping
    num_actual = slot_mapping.shape[0]
    block_table = state_metadata.block_table
    block_size = state_metadata.block_size

    # Fused: compress → RMSNorm → RoPE → FP8 quant → KV cache write.
    # RoPE requirements (kernel applies forward GPT-J style rotation):
    # - is_neox_style=False (interleaved pairs, NOT split-half)
    # - cos_sin_cache layout: [max_pos, rope_head_dim] with first half cos,
    #   second half sin (per-pair, length rope_head_dim // 2 each)
    # - applied to LAST rope_head_dim elements of head_dim
    # - position used: (positions // compress_ratio) * compress_ratio
    cos_sin_cache = rotary_emb.cos_sin_cache
    k_cache_metadata = cast(Any, attn_metadata[self.k_cache_prefix])
    k_cache_layer = self._static_forward_context[self.k_cache_prefix]
    kv_cache = k_cache_layer.kv_cache

    # Plain-row V4 reads a contiguous bf16 / per-tensor fp8 cache row; the
    # fp8_ds_mla path uses the UE8M0 paged uint8 layout.
    store_full_kv = self.head_dim == 512 and kv_cache.dtype != torch.uint8
    store_full_fp8 = kv_cache.dtype == torch.float8_e4m3fn
    fp8_scale = (
        getattr(k_cache_layer, "_flashinfer_fp8_kv_scale", None)
        if store_full_fp8
        else None
    )

    # cutedsl (head=512) accepts the full-cache flags; triton (indexer/AMD)
    # does not, so the two callables have different signatures.
    compress_norm_rope_store_fn: Any
    if current_platform.is_cuda() and self.head_dim == 512:
        from .nvidia.ops.sparse_attn_compress_cutedsl import (
            _SPARSE_ATTN_COMPRESSOR_CUTEDSL_KERNEL,
        )

        # head=512 on CUDA always uses cutedsl, for both the fp8_ds_mla
        # layout and the plain full-cache layout. The full-cache flags
        # are consumed only here.
        compress_norm_rope_store_fn = _SPARSE_ATTN_COMPRESSOR_CUTEDSL_KERNEL
        extra_kwargs: dict[str, Any] = dict(
            store_full_kv=store_full_kv,
            store_full_fp8=store_full_fp8,
            fp8_scale=fp8_scale,
        )
    elif self._use_two_stage_fused_compressor:
        # head=512 cr>=128 (no overlap): two-pass split compressor on the
        # prefill suffix, single-pass on the decode prefix.
        assert state_metadata.num_decode_tokens is not None
        compress_norm_rope_store_fn = compress_norm_rope_store_two_stage_triton
        extra_kwargs = {
            "num_decode_tokens": state_metadata.num_decode_tokens,
            "compress_scratch": self._compress_scratch,
            "fp8_scale": fp8_scale,
        }
    else:
        # Indexer path (head_dim == 128) or non-CUDA GPUs (AMD, XPU, etc.).
        compress_norm_rope_store_fn = compress_norm_rope_store_triton
        extra_kwargs = {"fp8_scale": fp8_scale}

    compress_norm_rope_store_fn(
        state_cache=state_cache,
        num_actual=num_actual,
        token_to_req_indices=token_to_req_indices,
        positions=positions,
        slot_mapping=slot_mapping,
        block_table=block_table,
        block_size=block_size,
        state_width=state_width,
        cos_sin_cache=cos_sin_cache,
        kv_cache=kv_cache,
        k_cache_metadata=k_cache_metadata,
        pdl_kwargs=pdl_kwargs,
        head_dim=self.head_dim,
        rope_head_dim=self.rope_head_dim,
        compress_ratio=self.compress_ratio,
        overlap=self.overlap,
        use_fp4_cache=self.use_fp4_cache,
        rms_norm_weight=self.norm.weight,
        rms_norm_eps=self.rms_norm_eps,
        quant_block=self._quant_block,
        token_stride=self._token_stride,
        scale_dim=self._scale_dim,
        **extra_kwargs,
    )

DeepseekV4CompressorKVScoreLinear

Bases: MergedColumnParallelLinear

Fused wkv/wgate projection with the FP32 output the compressor state accumulates in.

Source code in vllm/models/deepseek_v4/compressor.py
class DeepseekV4CompressorKVScoreLinear(MergedColumnParallelLinear):
    """Fused `wkv`/`wgate` projection with the FP32 output the compressor
    state accumulates in."""

    def forward(self, input_: torch.Tensor) -> torch.Tensor:
        return torch.mm(input_, self.weight.T, out_dtype=torch.float32)

dsv4_swa_replay_enabled(vllm_config)

Whether DeepSeek-V4 rebuilds its sliding-window state by replay.

ROCm only, and only when the KV connector asks for it (UMBP with rebuild_sliding_window: true): the SWA cache and compressor states then stay out of prefix caching, so the connector stores just the compressed KV and the scheduler recomputes the last window of every hit. The ROCm sparse SWA metadata clamps the window at replay_start. Unlike DeepSeek-V4.1, V4 needs about sliding_window * num_layers replayed tokens for an exact window state, so the one-window replay is an approximation.

Source code in vllm/models/deepseek_v4/compressor.py
def dsv4_swa_replay_enabled(vllm_config: VllmConfig) -> bool:
    """Whether DeepSeek-V4 rebuilds its sliding-window state by replay.

    ROCm only, and only when the KV connector asks for it (UMBP with
    `rebuild_sliding_window: true`): the SWA cache and compressor states then
    stay out of prefix caching, so the connector stores just the compressed KV
    and the scheduler recomputes the last window of every hit. The ROCm sparse
    SWA metadata clamps the window at `replay_start`. Unlike DeepSeek-V4.1,
    V4 needs about `sliding_window * num_layers` replayed tokens for an exact
    window state, so the one-window replay is an approximation.
    """
    if not current_platform.is_rocm():
        return False
    kv_transfer_config = vllm_config.kv_transfer_config
    if kv_transfer_config is None:
        return False
    from vllm.distributed.kv_transfer.kv_connector.factory import (
        KVConnectorFactory,
    )

    connector_cls = KVConnectorFactory.get_connector_class(kv_transfer_config)
    if not connector_cls.requests_sliding_window_replay(kv_transfer_config):
        return False
    blockers = []
    if not vllm_config.cache_config.swa_bounded_replay:
        blockers.append("--no-swa-bounded-replay")
    if vllm_config.parallel_config.prefill_context_parallel_size > 1:
        blockers.append("prefill context parallelism")
    if blockers:
        logger.warning_once(
            "DeepSeek-V4 SWA bounded replay: disabled (%s); %s stores every "
            "KV cache group, including the sliding-window cache and "
            "compressor states.",
            ", ".join(blockers),
            kv_transfer_config.kv_connector,
        )
        return False
    logger.info_once(
        "DeepSeek-V4 SWA bounded replay: enabled; %s stores the compressed KV "
        "only, and the sliding-window cache and compressor states stay out of "
        "prefix caching and are rebuilt by recomputing each hit's last window.",
        kv_transfer_config.kv_connector,
    )
    return True