Skip to content

vllm.v1.core.kv_cache_coordinator

Classes:

Functions:

HybridKVCacheCoordinator

Bases: KVCacheCoordinator

KV cache coordinator for hybrid models with multiple KV cache types, and thus multiple kv cache groups.

Methods:

Source code in vllm/v1/core/kv_cache_coordinator.py
class HybridKVCacheCoordinator(KVCacheCoordinator):
    """KV cache coordinator for hybrid models with multiple KV cache types, and
    thus multiple kv cache groups.
    """

    def __init__(
        self,
        kv_cache_config: KVCacheConfig,
        max_model_len: int,
        max_in_flight_tokens: int,
        use_eagle: bool,
        enable_caching: bool,
        enable_kv_cache_events: bool,
        dcp_world_size: int,
        pcp_world_size: int,
        scheduler_block_size: int,
        hash_block_size: int,
        metrics_collector: KVCacheMetricsCollector | None = None,
        num_hash_lookahead_tokens: int = 0,
        num_prefill_lookahead: int = 0,
        allow_partial_hash_hits: bool = True,
    ):
        super().__init__(
            kv_cache_config,
            max_model_len,
            max_in_flight_tokens,
            use_eagle,
            enable_caching,
            enable_kv_cache_events,
            dcp_world_size=dcp_world_size,
            pcp_world_size=pcp_world_size,
            scheduler_block_size=scheduler_block_size,
            hash_block_size=hash_block_size,
            metrics_collector=metrics_collector,
            num_hash_lookahead_tokens=num_hash_lookahead_tokens,
            num_prefill_lookahead=num_prefill_lookahead,
        )
        # hash_block_size: the block size used to compute block hashes.
        # The actual block size usually equals hash_block_size, but in cases where
        # different KV cache groups have different block sizes, the actual block size
        # can be a multiple of hash_block_size.
        self.hash_block_size = hash_block_size
        self.dcp_world_size = dcp_world_size
        # Only groups that participate in prefix caching must satisfy the
        # divisibility constraint; groups that opt out (e.g. circular buffers
        # such as the GLM-5.3-Flash indexer tail) are scratch and excluded.
        cacheable_block_sizes = [
            manager.block_size
            for manager, group in zip(
                self.single_type_managers, kv_cache_config.kv_cache_groups
            )
            if group.prefix_cacheable
        ]
        assert all(
            block_size % hash_block_size == 0 for block_size in cacheable_block_sizes
        ), (
            "Each KV cache group's real block_size must be divisible by "
            f"hash_block_size. block_sizes={cacheable_block_sizes}, "
            f"hash_block_size={hash_block_size}"
        )
        for g in kv_cache_config.kv_cache_groups:
            replicated = not g.dcp_sharded
            if pcp_world_size > 1:
                assert issubclass(g.manager_cls, FullAttentionManager) or (
                    replicated
                    and all(
                        isinstance(spec, AttentionSpec)
                        for spec in g.kv_cache_specs.values()
                    )
                ), "PCP only supports full attention and replicated draft groups."
            if dcp_world_size > 1:
                assert issubclass(g.manager_cls, FullAttentionManager) or replicated, (
                    "DCP with hybrid KV cache layouts only supports "
                    "full-attention, Mamba, and replicated draft groups, got: "
                    f"{g.manager_cls.__name__}."
                )
        # Fine-grained hash hits require Mamba "align" and compatible cache
        # managers in every group. TP needs hashing finer than the Mamba block;
        # DCP accepts equality because it scales the effective full-attention
        # block instead.
        self.enable_partial_hash_hits = (
            allow_partial_hash_hits
            and partial_hash_hits_enabled(
                kv_cache_config.kv_cache_groups,
                hash_block_size,
                dcp_world_size,
                [type(manager) for manager in self.single_type_managers],
            )
        )
        cache_hit_alignment_tokens = self._cache_hit_alignment_tokens
        for manager in self.single_type_managers:
            manager.cache_hit_alignment_tokens = cache_hit_alignment_tokens
        self.verify_and_split_kv_cache_groups()

    @property
    def _cache_hit_alignment_tokens(self) -> int:
        # Fine-grained partial hits may return hash-block-aligned lengths;
        # otherwise it must stay scheduler-block-aligned.
        return (
            self.hash_block_size
            if self.enable_partial_hash_hits
            else self.scheduler_block_size
        )

    def verify_and_split_kv_cache_groups(self) -> None:
        """Groups KV cache groups by their manager policy for efficient batch processing
        during cache hit lookup.
        """
        # Groups that opt out of prefix caching (e.g. circular buffers) hold
        # per-request scratch and never take part in hit lookup; their slot in
        # the per-group hit tuple stays empty.
        groups = self.kv_cache_config.kv_cache_groups
        self.attention_groups = [
            g._replace(
                use_eagle=any(i in self.drop_eagle_group_ids for i in g.group_ids)
            )
            for g in prefix_lookup_groups(groups)
        ]

        assert self.attention_groups, (
            "HybridKVCacheCoordinator requires at least one cacheable group."
        )

        # Put full attention first: its efficient left-to-right scan provides
        # a tighter initial bound, reducing work for subsequent groups.
        self.attention_groups.sort(
            key=lambda g: not issubclass(g.manager_cls, FullAttentionManager)
        )

        # Dense reference group for per-group lookups (None when the model
        # has no full-attention layers): full attention is downward-closed,
        # so any group reporting a longer per-group hit implies the union of
        # per-group hits is not consistent at a single boundary (#46453).
        first = self.attention_groups[0]
        self.full_attention_group_id: int | None = (
            first.group_ids[0]
            if issubclass(first.manager_cls, FullAttentionManager)
            else None
        )

        # Propagate the eagle bit to each manager (default to ``use_eagle=False``).
        for group in self.attention_groups:
            if group.use_eagle:
                for gid in group.group_ids:
                    self.single_type_managers[gid].use_eagle = True

    def _align_cacheable(self, num_tokens: int) -> int:
        """Largest prefix of `num_tokens` a future cache hit could match.

        Hits are `scheduler_block_size`-aligned (see
        `find_longest_cache_hit`) unless fine-grained partial hash hits are
        enabled, in which case no rounding applies -- rounding even to
        `hash_block_size` would re-register a privatized Mamba tail.
        """
        if self.enable_partial_hash_hits:
            return num_tokens
        return round_down(num_tokens, self.scheduler_block_size)

    def get_num_cacheable_tokens(
        self, num_computed_tokens: int, kv_cache_group_id: int
    ) -> int:
        cached_num_computed_tokens = self._align_cacheable(num_computed_tokens)
        manager = self.single_type_managers[kv_cache_group_id]
        # EAGLE matches one block past the aligned boundary, then drops it.
        if manager.use_eagle and cached_num_computed_tokens > 0:
            num_finalized_computed_tokens = max(
                0, num_computed_tokens - self.num_reprefillable_tokens
            )
            return min(
                num_finalized_computed_tokens,
                self._align_cacheable(num_finalized_computed_tokens)
                + manager.block_size,
            )
        return cached_num_computed_tokens

    def find_longest_cache_hit(
        self,
        block_hashes: list[BlockHash],
        max_cache_hit_length: int,
    ) -> tuple[tuple[list[KVCacheBlock], ...], int, int]:
        """Find the longest cache hit using an iterative fixed-point algorithm.

        Each attention type either accepts the current candidate length or
        reduces it. If any type reduces the length, restart checks over all
        types. This converges because length monotonically decreases and is
        bounded below by 0.

        Args:
            block_hashes: The block hashes of the request.
            max_cache_hit_length: The maximum length of the cache hit.

        Returns:
            A tuple containing:
                - A tuple of the cache hit blocks for each single type manager.
                - The number of tokens of the reconciled (combined) cache hit.
                - `num_uncached_common_prefix_tokens`: a shared prefix that a
                  sparse-retention group has not cached yet (0 unless hybrid).

        """
        num_groups = len(self.kv_cache_config.kv_cache_groups)
        hit_length = max_cache_hit_length
        longest_hit_length = 0
        hit_blocks_by_group: list[list[KVCacheBlock] | None] = [None] * num_groups
        hit_length_by_group: list[int] = [0] * num_groups

        # Simple hybrid (1 full attn + 1 other): one iteration suffices.
        # Full attn is always first if it exists.
        is_simple_hybrid = len(self.attention_groups) == 2 and issubclass(
            self.attention_groups[0].manager_cls, FullAttentionManager
        )

        # Attention-group indices whose EAGLE drop is verified at the current
        # ``curr_hit_length``. Each eagle group applies the drop at most once
        # per candidate length (see issue #32802).
        eagle_verified: set[int] = set()

        while True:
            curr_hit_length = hit_length

            for idx, (manager_config, block_size, group_ids, use_eagle) in enumerate(
                self.attention_groups
            ):
                manager_cls = manager_config.manager_cls
                first_group_id = group_ids[0]
                # DCP/PCP shard each block's KV across ranks, so the manager's
                # effective block size may exceed the spec's.
                group_block_size = self.single_type_managers[first_group_id].block_size
                cached_blocks = hit_blocks_by_group[first_group_id]
                if (
                    issubclass(manager_cls, FullAttentionManager)
                    and cached_blocks is not None
                ):
                    # Full attention is downward-closed: we only need to look
                    # up cached blocks once; on subsequent iterations just trim
                    # to the (reduced) current hit length.
                    curr_hit_length = min(
                        curr_hit_length, hit_length_by_group[first_group_id]
                    )
                    continue

                drop_eagle_block = use_eagle and idx not in eagle_verified

                _max_length = curr_hit_length
                # Eagle matches one extra drop unit (one hash unit for
                # fine-grained managers, else one cache block) and then drops
                # it, landing back at the candidate length. No margin for
                # mamba: its finder never drops (draft models have no mamba
                # layers), so the hit would grow past the candidate.
                if drop_eagle_block and not issubclass(manager_cls, MambaManager):
                    eagle_margin = eagle_proof_margin(
                        group_block_size,
                        self.hash_block_size,
                        self.enable_partial_hash_hits
                        and manager_cls.supports_fine_grained_hash_lookup,
                    )
                    _max_length = min(
                        curr_hit_length + eagle_margin,
                        len(block_hashes) * self.hash_block_size,
                    )
                hit_blocks, _new_hit_length = manager_cls.find_longest_cache_hit(
                    block_hashes=block_hashes,
                    max_length=_max_length,
                    kv_cache_group_ids=group_ids,
                    block_pool=self.single_type_managers[first_group_id].block_pool,
                    block_size=block_size,
                    manager_config=manager_config,
                    drop_eagle_block=drop_eagle_block,
                    alignment_tokens=self._cache_hit_alignment_tokens,
                    dcp_world_size=self.single_type_managers[
                        first_group_id
                    ].dcp_world_size,
                    pcp_world_size=self.single_type_managers[
                        first_group_id
                    ].pcp_world_size,
                )
                if drop_eagle_block:
                    eagle_verified.add(idx)
                elif _new_hit_length < curr_hit_length:
                    # length shrunk; invalidate previous eagle verifications
                    eagle_verified.clear()
                curr_hit_length = _new_hit_length
                for group_id, blocks in zip(group_ids, hit_blocks):
                    hit_blocks_by_group[group_id] = blocks
                    hit_length_by_group[group_id] = _new_hit_length

                longest_hit_length = max(longest_hit_length, curr_hit_length)

            if curr_hit_length >= hit_length:
                break
            hit_length = curr_hit_length
            if is_simple_hybrid:
                break

        # Truncate every full-attention group (target and draft) blocks
        # to final hit_length.
        for group in self.attention_groups:
            if not issubclass(group.manager_cls, FullAttentionManager):
                continue
            manager = self.single_type_managers[group.group_ids[0]]
            if manager.retains_longer_hit:
                continue
            group_block_size = manager.block_size
            num_blocks = cdiv(hit_length, group_block_size)
            for group_id in group.group_ids:
                if (blks := hit_blocks_by_group[group_id]) is not None:
                    del blks[num_blocks:]
                    hit_length_by_group[group_id] = hit_length

        # Uncached shared prefix detection: if any attn. group cached a longer
        # prefix than the reconciled hit, it is an uncached common prefix across
        # requests that a sparse-retention group hasn't cached yet.
        num_uncached_common_prefix_tokens = longest_hit_length - hit_length
        cache_hit_blocks = tuple(
            blocks if blocks is not None else [] for blocks in hit_blocks_by_group
        )
        return cache_hit_blocks, hit_length, num_uncached_common_prefix_tokens

    def find_longest_cache_hit_per_group(
        self,
        block_hashes: list[BlockHash],
        max_cache_hit_length: int,
    ) -> tuple[tuple[list[KVCacheBlock], ...], tuple[int, ...]]:
        """Like find_longest_cache_hit but evaluates each group independently.

        Returns:
            (blocks_per_group, hit_lengths_per_group)

        """
        num_groups = len(self.kv_cache_config.kv_cache_groups)
        hit_blocks: list[list[KVCacheBlock]] = [[] for _ in range(num_groups)]
        hit_lengths: list[int] = [0] * num_groups

        for manager_config, block_size, group_ids, use_eagle in self.attention_groups:
            manager_cls = manager_config.manager_cls
            manager = self.single_type_managers[group_ids[0]]
            lookup_length = max_cache_hit_length
            if use_eagle and not issubclass(manager_cls, MambaManager):
                eagle_margin = eagle_proof_margin(
                    manager.block_size,
                    self.hash_block_size,
                    self.enable_partial_hash_hits
                    and manager_cls.supports_fine_grained_hash_lookup,
                )
                lookup_length = min(
                    max_cache_hit_length + eagle_margin,
                    len(block_hashes) * self.hash_block_size,
                )
            blocks, group_hit = manager_cls.find_longest_cache_hit(
                block_hashes=block_hashes,
                max_length=lookup_length,
                kv_cache_group_ids=group_ids,
                block_pool=manager.block_pool,
                block_size=block_size,
                manager_config=manager_config,
                drop_eagle_block=use_eagle,
                alignment_tokens=self._cache_hit_alignment_tokens,
                dcp_world_size=manager.dcp_world_size,
                pcp_world_size=manager.pcp_world_size,
            )
            for gid, blks in zip(group_ids, blocks):
                hit_blocks[gid] = blks
                hit_lengths[gid] = group_hit

        return tuple(hit_blocks), tuple(hit_lengths)

_align_cacheable(num_tokens)

Largest prefix of num_tokens a future cache hit could match.

Hits are scheduler_block_size-aligned (see find_longest_cache_hit) unless fine-grained partial hash hits are enabled, in which case no rounding applies -- rounding even to hash_block_size would re-register a privatized Mamba tail.

Source code in vllm/v1/core/kv_cache_coordinator.py
def _align_cacheable(self, num_tokens: int) -> int:
    """Largest prefix of `num_tokens` a future cache hit could match.

    Hits are `scheduler_block_size`-aligned (see
    `find_longest_cache_hit`) unless fine-grained partial hash hits are
    enabled, in which case no rounding applies -- rounding even to
    `hash_block_size` would re-register a privatized Mamba tail.
    """
    if self.enable_partial_hash_hits:
        return num_tokens
    return round_down(num_tokens, self.scheduler_block_size)

find_longest_cache_hit(block_hashes, max_cache_hit_length)

Find the longest cache hit using an iterative fixed-point algorithm.

Each attention type either accepts the current candidate length or reduces it. If any type reduces the length, restart checks over all types. This converges because length monotonically decreases and is bounded below by 0.

Parameters:

  • block_hashes

    (list[BlockHash]) –

    The block hashes of the request.

  • max_cache_hit_length

    (int) –

    The maximum length of the cache hit.

Returns:

  • tuple[tuple[list[KVCacheBlock], ...], int, int] –

    A tuple containing: - A tuple of the cache hit blocks for each single type manager. - The number of tokens of the reconciled (combined) cache hit. - num_uncached_common_prefix_tokens: a shared prefix that a sparse-retention group has not cached yet (0 unless hybrid).

Source code in vllm/v1/core/kv_cache_coordinator.py
def find_longest_cache_hit(
    self,
    block_hashes: list[BlockHash],
    max_cache_hit_length: int,
) -> tuple[tuple[list[KVCacheBlock], ...], int, int]:
    """Find the longest cache hit using an iterative fixed-point algorithm.

    Each attention type either accepts the current candidate length or
    reduces it. If any type reduces the length, restart checks over all
    types. This converges because length monotonically decreases and is
    bounded below by 0.

    Args:
        block_hashes: The block hashes of the request.
        max_cache_hit_length: The maximum length of the cache hit.

    Returns:
        A tuple containing:
            - A tuple of the cache hit blocks for each single type manager.
            - The number of tokens of the reconciled (combined) cache hit.
            - `num_uncached_common_prefix_tokens`: a shared prefix that a
              sparse-retention group has not cached yet (0 unless hybrid).

    """
    num_groups = len(self.kv_cache_config.kv_cache_groups)
    hit_length = max_cache_hit_length
    longest_hit_length = 0
    hit_blocks_by_group: list[list[KVCacheBlock] | None] = [None] * num_groups
    hit_length_by_group: list[int] = [0] * num_groups

    # Simple hybrid (1 full attn + 1 other): one iteration suffices.
    # Full attn is always first if it exists.
    is_simple_hybrid = len(self.attention_groups) == 2 and issubclass(
        self.attention_groups[0].manager_cls, FullAttentionManager
    )

    # Attention-group indices whose EAGLE drop is verified at the current
    # ``curr_hit_length``. Each eagle group applies the drop at most once
    # per candidate length (see issue #32802).
    eagle_verified: set[int] = set()

    while True:
        curr_hit_length = hit_length

        for idx, (manager_config, block_size, group_ids, use_eagle) in enumerate(
            self.attention_groups
        ):
            manager_cls = manager_config.manager_cls
            first_group_id = group_ids[0]
            # DCP/PCP shard each block's KV across ranks, so the manager's
            # effective block size may exceed the spec's.
            group_block_size = self.single_type_managers[first_group_id].block_size
            cached_blocks = hit_blocks_by_group[first_group_id]
            if (
                issubclass(manager_cls, FullAttentionManager)
                and cached_blocks is not None
            ):
                # Full attention is downward-closed: we only need to look
                # up cached blocks once; on subsequent iterations just trim
                # to the (reduced) current hit length.
                curr_hit_length = min(
                    curr_hit_length, hit_length_by_group[first_group_id]
                )
                continue

            drop_eagle_block = use_eagle and idx not in eagle_verified

            _max_length = curr_hit_length
            # Eagle matches one extra drop unit (one hash unit for
            # fine-grained managers, else one cache block) and then drops
            # it, landing back at the candidate length. No margin for
            # mamba: its finder never drops (draft models have no mamba
            # layers), so the hit would grow past the candidate.
            if drop_eagle_block and not issubclass(manager_cls, MambaManager):
                eagle_margin = eagle_proof_margin(
                    group_block_size,
                    self.hash_block_size,
                    self.enable_partial_hash_hits
                    and manager_cls.supports_fine_grained_hash_lookup,
                )
                _max_length = min(
                    curr_hit_length + eagle_margin,
                    len(block_hashes) * self.hash_block_size,
                )
            hit_blocks, _new_hit_length = manager_cls.find_longest_cache_hit(
                block_hashes=block_hashes,
                max_length=_max_length,
                kv_cache_group_ids=group_ids,
                block_pool=self.single_type_managers[first_group_id].block_pool,
                block_size=block_size,
                manager_config=manager_config,
                drop_eagle_block=drop_eagle_block,
                alignment_tokens=self._cache_hit_alignment_tokens,
                dcp_world_size=self.single_type_managers[
                    first_group_id
                ].dcp_world_size,
                pcp_world_size=self.single_type_managers[
                    first_group_id
                ].pcp_world_size,
            )
            if drop_eagle_block:
                eagle_verified.add(idx)
            elif _new_hit_length < curr_hit_length:
                # length shrunk; invalidate previous eagle verifications
                eagle_verified.clear()
            curr_hit_length = _new_hit_length
            for group_id, blocks in zip(group_ids, hit_blocks):
                hit_blocks_by_group[group_id] = blocks
                hit_length_by_group[group_id] = _new_hit_length

            longest_hit_length = max(longest_hit_length, curr_hit_length)

        if curr_hit_length >= hit_length:
            break
        hit_length = curr_hit_length
        if is_simple_hybrid:
            break

    # Truncate every full-attention group (target and draft) blocks
    # to final hit_length.
    for group in self.attention_groups:
        if not issubclass(group.manager_cls, FullAttentionManager):
            continue
        manager = self.single_type_managers[group.group_ids[0]]
        if manager.retains_longer_hit:
            continue
        group_block_size = manager.block_size
        num_blocks = cdiv(hit_length, group_block_size)
        for group_id in group.group_ids:
            if (blks := hit_blocks_by_group[group_id]) is not None:
                del blks[num_blocks:]
                hit_length_by_group[group_id] = hit_length

    # Uncached shared prefix detection: if any attn. group cached a longer
    # prefix than the reconciled hit, it is an uncached common prefix across
    # requests that a sparse-retention group hasn't cached yet.
    num_uncached_common_prefix_tokens = longest_hit_length - hit_length
    cache_hit_blocks = tuple(
        blocks if blocks is not None else [] for blocks in hit_blocks_by_group
    )
    return cache_hit_blocks, hit_length, num_uncached_common_prefix_tokens

find_longest_cache_hit_per_group(block_hashes, max_cache_hit_length)

Like find_longest_cache_hit but evaluates each group independently.

Returns:

Source code in vllm/v1/core/kv_cache_coordinator.py
def find_longest_cache_hit_per_group(
    self,
    block_hashes: list[BlockHash],
    max_cache_hit_length: int,
) -> tuple[tuple[list[KVCacheBlock], ...], tuple[int, ...]]:
    """Like find_longest_cache_hit but evaluates each group independently.

    Returns:
        (blocks_per_group, hit_lengths_per_group)

    """
    num_groups = len(self.kv_cache_config.kv_cache_groups)
    hit_blocks: list[list[KVCacheBlock]] = [[] for _ in range(num_groups)]
    hit_lengths: list[int] = [0] * num_groups

    for manager_config, block_size, group_ids, use_eagle in self.attention_groups:
        manager_cls = manager_config.manager_cls
        manager = self.single_type_managers[group_ids[0]]
        lookup_length = max_cache_hit_length
        if use_eagle and not issubclass(manager_cls, MambaManager):
            eagle_margin = eagle_proof_margin(
                manager.block_size,
                self.hash_block_size,
                self.enable_partial_hash_hits
                and manager_cls.supports_fine_grained_hash_lookup,
            )
            lookup_length = min(
                max_cache_hit_length + eagle_margin,
                len(block_hashes) * self.hash_block_size,
            )
        blocks, group_hit = manager_cls.find_longest_cache_hit(
            block_hashes=block_hashes,
            max_length=lookup_length,
            kv_cache_group_ids=group_ids,
            block_pool=manager.block_pool,
            block_size=block_size,
            manager_config=manager_config,
            drop_eagle_block=use_eagle,
            alignment_tokens=self._cache_hit_alignment_tokens,
            dcp_world_size=manager.dcp_world_size,
            pcp_world_size=manager.pcp_world_size,
        )
        for gid, blks in zip(group_ids, blocks):
            hit_blocks[gid] = blks
            hit_lengths[gid] = group_hit

    return tuple(hit_blocks), tuple(hit_lengths)

verify_and_split_kv_cache_groups()

Groups KV cache groups by their manager policy for efficient batch processing during cache hit lookup.

Source code in vllm/v1/core/kv_cache_coordinator.py
def verify_and_split_kv_cache_groups(self) -> None:
    """Groups KV cache groups by their manager policy for efficient batch processing
    during cache hit lookup.
    """
    # Groups that opt out of prefix caching (e.g. circular buffers) hold
    # per-request scratch and never take part in hit lookup; their slot in
    # the per-group hit tuple stays empty.
    groups = self.kv_cache_config.kv_cache_groups
    self.attention_groups = [
        g._replace(
            use_eagle=any(i in self.drop_eagle_group_ids for i in g.group_ids)
        )
        for g in prefix_lookup_groups(groups)
    ]

    assert self.attention_groups, (
        "HybridKVCacheCoordinator requires at least one cacheable group."
    )

    # Put full attention first: its efficient left-to-right scan provides
    # a tighter initial bound, reducing work for subsequent groups.
    self.attention_groups.sort(
        key=lambda g: not issubclass(g.manager_cls, FullAttentionManager)
    )

    # Dense reference group for per-group lookups (None when the model
    # has no full-attention layers): full attention is downward-closed,
    # so any group reporting a longer per-group hit implies the union of
    # per-group hits is not consistent at a single boundary (#46453).
    first = self.attention_groups[0]
    self.full_attention_group_id: int | None = (
        first.group_ids[0]
        if issubclass(first.manager_cls, FullAttentionManager)
        else None
    )

    # Propagate the eagle bit to each manager (default to ``use_eagle=False``).
    for group in self.attention_groups:
        if group.use_eagle:
            for gid in group.group_ids:
                self.single_type_managers[gid].use_eagle = True

KVCacheCoordinator

Bases: ABC

Coordinate the KV cache of different KV cache groups.

Methods:

Source code in vllm/v1/core/kv_cache_coordinator.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
class KVCacheCoordinator(ABC):
    """Coordinate the KV cache of different KV cache groups."""

    enable_partial_hash_hits = False

    def __init__(
        self,
        kv_cache_config: KVCacheConfig,
        max_model_len: int,
        max_in_flight_tokens: int,
        use_eagle: bool,
        enable_caching: bool,
        enable_kv_cache_events: bool,
        dcp_world_size: int,
        pcp_world_size: int,
        scheduler_block_size: int,
        hash_block_size: int,
        metrics_collector: KVCacheMetricsCollector | None = None,
        num_prefill_lookahead: int = 0,
        num_hash_lookahead_tokens: int = 0,
    ):
        self.kv_cache_config = kv_cache_config
        # The scheduling granularity (LCM of all group block sizes), must be a multiple
        # of the hash_block_size and the block size of each group.
        assert scheduler_block_size % hash_block_size == 0 and all(
            scheduler_block_size % g.block_size == 0
            for g in kv_cache_config.kv_cache_groups
        )
        self.scheduler_block_size = scheduler_block_size
        self.num_reprefillable_tokens = max(0, num_prefill_lookahead - 1)

        self.block_pool = BlockPool(
            num_gpu_blocks=kv_cache_config.num_blocks,
            enable_caching=enable_caching,
            hash_block_size=hash_block_size,
            enable_kv_cache_events=enable_kv_cache_events,
            metrics_collector=metrics_collector,
            num_hash_lookahead_tokens=num_hash_lookahead_tokens,
        )

        # KV cache group indices that get the EAGLE last-block drop.
        self.eagle_group_ids: set[int] = {
            i for i, g in enumerate(kv_cache_config.kv_cache_groups) if g.is_eagle_group
        }
        # Conservatively fall back to flag all groups when no group is flagged.
        if use_eagle and not self.eagle_group_ids:
            self.eagle_group_ids = set(range(len(kv_cache_config.kv_cache_groups)))
        # Lookahead hashes clear ``use_eagle``: groups stay flagged, none drops.
        self.drop_eagle_group_ids = self.eagle_group_ids if use_eagle else set()

        # During chunked prefill with EAGLE, the single next prefill lookahead
        # token past the chunk boundary is combined with the final hidden state
        # and written to the KV cache. Therefore, the final chunk token must be
        # excluded from prefix cache hits to prevent requests from acquiring the
        # KV cache slot polluted with the next prefill token, which may or may not
        # be present after the matching prefix. The last-block drop handles this
        # edge case. During multi-module MTP, the issue generalizes to a prefill
        # lookahead of num_speculative_tokens, so the dropped tail must be large
        # enough to contain them. Hits land on scheduler-block boundaries (see
        # `_cache_hit_alignment_tokens`), so the excluded tail is
        # scheduler_block_size, not the group's own block size.
        if (
            enable_caching
            and self.eagle_group_ids
            and scheduler_block_size < num_prefill_lookahead
        ):
            raise ValueError(
                f"Multi-module MTP with prefix caching requires scheduler_block_size"
                f" (={scheduler_block_size}) >= num_speculative_tokens"
                f" (={num_prefill_lookahead})."
            )

        self.single_type_managers = tuple(
            create_single_type_manager(
                kv_cache_group,
                max_in_flight_tokens=max_in_flight_tokens,
                max_model_len=max_model_len,
                block_pool=self.block_pool,
                enable_caching=enable_caching,
                kv_cache_group_id=i,
                dcp_world_size=dcp_world_size,
                pcp_world_size=pcp_world_size,
                scheduler_block_size=self.scheduler_block_size,
                needs_kv_cache_zeroing=self.kv_cache_config.needs_kv_cache_zeroing,
            )
            for i, kv_cache_group in enumerate(self.kv_cache_config.kv_cache_groups)
        )
        # Match Mamba checkpoints to Eagle's attention replay boundary.
        if use_eagle:
            for manager in self.single_type_managers:
                if isinstance(manager, MambaManager):
                    manager.drop_eagle_checkpoint_block = True
        self.group_block_sizes = tuple(
            manager.block_size for manager in self.single_type_managers
        )

        # A positive retention interval must be a multiple of the base hit granularity
        # (``scheduler_block_size``) to land on real cache-hit boundaries.
        # 0 = keep only the latest replay boundary; None = dense;
        self.retention_interval = kv_cache_config.prefix_cache_retention_interval
        _validate_prefix_cache_retention_interval(
            self.retention_interval, self.scheduler_block_size, kv_cache_config
        )

    def get_num_blocks_to_allocate(
        self,
        request_id: str,
        num_tokens: int,
        new_computed_blocks: tuple[Sequence[KVCacheBlock], ...],
        num_encoder_tokens: int,
        total_computed_tokens: int,
        num_local_computed_tokens: int,
        num_tokens_main_model: int,
        apply_admission_cap: bool = False,
        prefill_end: int = 0,
    ) -> int:
        """Get the number of device blocks needed to be allocated for the request.

        Args:
            request_id: The request ID.
            num_tokens: The total number of tokens that need a slot (including
                tokens that are already allocated).
            new_computed_blocks: The new computed blocks just hitting the
                prefix caching.
            num_encoder_tokens: The number of encoder tokens for allocating
                blocks for cross-attention.
            total_computed_tokens: Include both local and external tokens.
            num_local_computed_tokens: The number of local prefix-cache computed
                tokens.
            num_tokens_main_model: The number of tokens for the main model (aka target
                model in spec decode). w/o spec decode, it is num_tokens;
                with spec decode, it is num_tokens - num_lookahead_tokens.
            apply_admission_cap: If True, apply the recycling-aware
                per-request admission cap (SWA / chunked-local). Set only by
                the full-sequence admission gate; per-step allocation must
                leave it False so the predictor matches `allocate_new_blocks`.
            prefill_end: The token index the request's prefill ends at, the
                same value the scheduler splits chunks against. Under sparse
                retention Mamba reserves a prefill checkpoint only on the chunk
                reaching it; under dense retention every chunk publishes a
                state, so it is ignored (0).

        Returns:
            The number of blocks to allocate.

        """
        num_blocks_to_allocate = 0
        if self.retention_interval != 0:
            prefill_end = 0
        for i, manager in enumerate(self.single_type_managers):
            if isinstance(manager, CrossAttentionManager):
                # For cross-attention, we issue a single static allocation
                # of blocks based on the number of encoder input tokens.
                num_blocks_to_allocate += manager.get_num_blocks_to_allocate(
                    request_id,
                    num_encoder_tokens,
                    [],
                    0,
                    0,
                    num_encoder_tokens,
                    apply_admission_cap=apply_admission_cap,
                )
            else:
                num_blocks_to_allocate += manager.get_num_blocks_to_allocate(
                    request_id,
                    num_tokens,
                    new_computed_blocks[i],
                    total_computed_tokens,
                    num_local_computed_tokens,
                    num_tokens_main_model,
                    apply_admission_cap=apply_admission_cap,
                    prefill_end=prefill_end,
                )
        return num_blocks_to_allocate

    def allocate_new_computed_blocks(
        self,
        request_id: str,
        new_computed_blocks: tuple[Sequence[KVCacheBlock], ...],
        num_local_computed_tokens: int,
        num_external_computed_tokens: int,
        skip_zeroing_group_ids: tuple[int, ...] = (),
    ) -> None:
        """Add the new computed blocks to the request. Optionally allocate new
            blocks for external computed tokens (if any).

        Args:
            request_id: The request ID.
            new_computed_blocks: The new computed blocks just hitting the
                prefix cache.
            num_local_computed_tokens: The number of local computed tokens.
            num_external_computed_tokens: The number of external computed tokens.
            skip_zeroing_group_ids: Groups whose external-token blocks are
                written by an async load and must not be zeroed.

        """
        # A running request is already tracked in num_cached_block and won't
        # have new prefix-cache hits, so this is a no-op for it.
        if any(
            request_id in manager.num_cached_block
            for manager in self.single_type_managers
        ):
            assert all(len(blocks) == 0 for blocks in new_computed_blocks)
            return

        # Two-phase allocation (issue #33775): first touch every group's local
        # cache-hit blocks, then allocate external blocks for every group. This
        # ensures an earlier group's external `get_new_blocks` cannot evict a
        # later group's not-yet-touched cache-hit blocks.
        for i, manager in enumerate(self.single_type_managers):
            manager.add_local_computed_blocks(
                request_id,
                new_computed_blocks[i],
                num_local_computed_tokens,
                num_external_computed_tokens,
            )
        if num_external_computed_tokens > 0:
            for i, manager in enumerate(self.single_type_managers):
                manager.allocate_external_computed_blocks(
                    request_id,
                    num_local_computed_tokens,
                    num_external_computed_tokens,
                    record_for_zeroing=i not in skip_zeroing_group_ids,
                )

    def allocate_new_blocks(
        self,
        request_id: str,
        num_tokens: int,
        num_tokens_main_model: int,
        num_encoder_tokens: int = 0,
    ) -> tuple[list[KVCacheBlock], ...]:
        """Allocate new blocks for the request to give it at least `num_tokens`
        token slots.

        Args:
            request_id: The request ID.
            num_tokens: The total number of tokens that need a slot (including
                tokens that are already allocated).
            num_tokens_main_model: The number of tokens for the main model (aka target
                model in spec decode). w/o spec decode, it is num_tokens;
                with spec decode, it is num_tokens - num_lookahead_tokens.
            num_encoder_tokens: The number of encoder tokens for allocating
                blocks for cross-attention.

        Returns:
            The new allocated blocks.

        """
        return tuple(
            manager.allocate_new_blocks(
                request_id,
                num_encoder_tokens
                if isinstance(manager, CrossAttentionManager)
                else num_tokens,
                num_tokens_main_model,
            )
            for manager in self.single_type_managers
        )

    def get_num_cacheable_tokens(
        self, num_computed_tokens: int, kv_cache_group_id: int
    ) -> int:
        """Return the prefix eligible for hashing in this group."""
        # Only cache tokens with finalized KV. The last num_reprefillable_tokens
        # tokens can be re-prefilled during multi-module MTP.
        return max(0, num_computed_tokens - self.num_reprefillable_tokens)

    def cache_blocks(self, request: Request, num_computed_tokens: int) -> None:
        """Cache the blocks for the request.

        Args:
            request: The request.
            num_computed_tokens: The total number of tokens
                that need to be cached
                (including tokens that are already cached).

        """
        boundaries = replay_boundaries(
            request.num_prompt_tokens,
            self.scheduler_block_size,
            use_eagle=bool(self.drop_eagle_group_ids),
            num_hash_lookahead_tokens=self.block_pool.num_hash_lookahead_tokens,
        )
        for group_id, manager in enumerate(self.single_type_managers):
            if not manager.enable_caching:
                continue
            manager.cache_blocks(
                request,
                self.get_num_cacheable_tokens(num_computed_tokens, group_id),
                retention_interval=self.retention_interval,
                replay_boundaries=boundaries,
            )

    def emit_cached_block_events(
        self, request: Request, computed_blocks: tuple[list[KVCacheBlock], ...]
    ) -> None:
        for group_idx, group_blocks in enumerate(computed_blocks):
            if group_blocks:
                manager = self.single_type_managers[group_idx]
                group = self.kv_cache_config.kv_cache_groups[group_idx]
                manager.block_pool.emit_cached_block_events(
                    request,
                    len(group_blocks),
                    group.block_size,
                    group_idx,
                )

    def reset_prefix_cache(self) -> bool:
        """Reset each manager's pool once."""
        pools = dict.fromkeys(
            manager.block_pool for manager in self.single_type_managers
        )
        return all([pool.reset_prefix_cache() for pool in pools])

    def free(self, request_id: str) -> None:
        """Free the blocks for the request.

        Args:
            request_id: The request ID.

        """
        for manager in self.single_type_managers:
            manager.free(request_id)

    def pop_blocks_for_free(self, request_id: str) -> list[KVCacheBlock]:
        """Pop the request's bookkeeping from all single-type managers and
        return its blocks without returning them to the block pool. The
        caller must eventually pass the returned blocks to
        `block_pool.free_blocks`, freeing them in reverse order (so that
        tail blocks are evicted first).

        Args:
            request_id: The request ID.

        Returns:
            The request's blocks in allocation order.

        """
        blocks: list[KVCacheBlock] = []
        for manager in self.single_type_managers:
            blocks.extend(manager.pop_blocks_for_free(request_id))
        return blocks

    def remove_skipped_blocks(
        self,
        request_id: str,
        processed_computed_tokens: int,
        num_prompt_tokens: int | None = None,
    ) -> None:
        """Remove the blocks that are no longer needed from `blocks` and replace
        the removed blocks with null_block.

        Args:
            request_id: The request ID.
            processed_computed_tokens: Computed-token prefix length covering
                fully processed and committed tokens only (safe to free).
            num_prompt_tokens: Optional prompt length. R-SWA managers use this to
                free gap blocks between the prefill tail and decode window; other
                manager types ignore it.

        """
        for manager in self.single_type_managers:
            manager.remove_skipped_blocks(
                request_id, processed_computed_tokens, num_prompt_tokens
            )

    def get_blocks(self, request_id: str) -> tuple[list[KVCacheBlock], ...]:
        """Get the blocks for the request."""
        return tuple(
            manager.req_to_blocks.get(request_id) or []
            for manager in self.single_type_managers
        )

    @abstractmethod
    def find_longest_cache_hit(
        self,
        block_hashes: list[BlockHash],
        max_cache_hit_length: int,
    ) -> tuple[tuple[list[KVCacheBlock], ...], int, int]:
        """Returns the per-group hit blocks, the hit length, and the number of
        `num_uncached_common_prefix_tokens` (a shared prefix that a
        sparse-retention group has not cached yet; 0 unless hybrid)."""
        pass

    def new_step_starts(self) -> None:
        """Notify each manager that a new step is starting."""
        for manager in self.single_type_managers:
            manager.new_step_starts()

allocate_new_blocks(request_id, num_tokens, num_tokens_main_model, num_encoder_tokens=0)

Allocate new blocks for the request to give it at least num_tokens token slots.

Parameters:

  • request_id

    (str) –

    The request ID.

  • num_tokens

    (int) –

    The total number of tokens that need a slot (including tokens that are already allocated).

  • num_tokens_main_model

    (int) –

    The number of tokens for the main model (aka target model in spec decode). w/o spec decode, it is num_tokens; with spec decode, it is num_tokens - num_lookahead_tokens.

  • num_encoder_tokens

    (int, default: 0 ) –

    The number of encoder tokens for allocating blocks for cross-attention.

Returns:

Source code in vllm/v1/core/kv_cache_coordinator.py
def allocate_new_blocks(
    self,
    request_id: str,
    num_tokens: int,
    num_tokens_main_model: int,
    num_encoder_tokens: int = 0,
) -> tuple[list[KVCacheBlock], ...]:
    """Allocate new blocks for the request to give it at least `num_tokens`
    token slots.

    Args:
        request_id: The request ID.
        num_tokens: The total number of tokens that need a slot (including
            tokens that are already allocated).
        num_tokens_main_model: The number of tokens for the main model (aka target
            model in spec decode). w/o spec decode, it is num_tokens;
            with spec decode, it is num_tokens - num_lookahead_tokens.
        num_encoder_tokens: The number of encoder tokens for allocating
            blocks for cross-attention.

    Returns:
        The new allocated blocks.

    """
    return tuple(
        manager.allocate_new_blocks(
            request_id,
            num_encoder_tokens
            if isinstance(manager, CrossAttentionManager)
            else num_tokens,
            num_tokens_main_model,
        )
        for manager in self.single_type_managers
    )

allocate_new_computed_blocks(request_id, new_computed_blocks, num_local_computed_tokens, num_external_computed_tokens, skip_zeroing_group_ids=())

Add the new computed blocks to the request. Optionally allocate new blocks for external computed tokens (if any).

Parameters:

  • request_id

    (str) –

    The request ID.

  • new_computed_blocks

    (tuple[Sequence[KVCacheBlock], ...]) –

    The new computed blocks just hitting the prefix cache.

  • num_local_computed_tokens

    (int) –

    The number of local computed tokens.

  • num_external_computed_tokens

    (int) –

    The number of external computed tokens.

  • skip_zeroing_group_ids

    (tuple[int, ...], default: () ) –

    Groups whose external-token blocks are written by an async load and must not be zeroed.

Source code in vllm/v1/core/kv_cache_coordinator.py
def allocate_new_computed_blocks(
    self,
    request_id: str,
    new_computed_blocks: tuple[Sequence[KVCacheBlock], ...],
    num_local_computed_tokens: int,
    num_external_computed_tokens: int,
    skip_zeroing_group_ids: tuple[int, ...] = (),
) -> None:
    """Add the new computed blocks to the request. Optionally allocate new
        blocks for external computed tokens (if any).

    Args:
        request_id: The request ID.
        new_computed_blocks: The new computed blocks just hitting the
            prefix cache.
        num_local_computed_tokens: The number of local computed tokens.
        num_external_computed_tokens: The number of external computed tokens.
        skip_zeroing_group_ids: Groups whose external-token blocks are
            written by an async load and must not be zeroed.

    """
    # A running request is already tracked in num_cached_block and won't
    # have new prefix-cache hits, so this is a no-op for it.
    if any(
        request_id in manager.num_cached_block
        for manager in self.single_type_managers
    ):
        assert all(len(blocks) == 0 for blocks in new_computed_blocks)
        return

    # Two-phase allocation (issue #33775): first touch every group's local
    # cache-hit blocks, then allocate external blocks for every group. This
    # ensures an earlier group's external `get_new_blocks` cannot evict a
    # later group's not-yet-touched cache-hit blocks.
    for i, manager in enumerate(self.single_type_managers):
        manager.add_local_computed_blocks(
            request_id,
            new_computed_blocks[i],
            num_local_computed_tokens,
            num_external_computed_tokens,
        )
    if num_external_computed_tokens > 0:
        for i, manager in enumerate(self.single_type_managers):
            manager.allocate_external_computed_blocks(
                request_id,
                num_local_computed_tokens,
                num_external_computed_tokens,
                record_for_zeroing=i not in skip_zeroing_group_ids,
            )

cache_blocks(request, num_computed_tokens)

Cache the blocks for the request.

Parameters:

  • request

    (Request) –

    The request.

  • num_computed_tokens

    (int) –

    The total number of tokens that need to be cached (including tokens that are already cached).

Source code in vllm/v1/core/kv_cache_coordinator.py
def cache_blocks(self, request: Request, num_computed_tokens: int) -> None:
    """Cache the blocks for the request.

    Args:
        request: The request.
        num_computed_tokens: The total number of tokens
            that need to be cached
            (including tokens that are already cached).

    """
    boundaries = replay_boundaries(
        request.num_prompt_tokens,
        self.scheduler_block_size,
        use_eagle=bool(self.drop_eagle_group_ids),
        num_hash_lookahead_tokens=self.block_pool.num_hash_lookahead_tokens,
    )
    for group_id, manager in enumerate(self.single_type_managers):
        if not manager.enable_caching:
            continue
        manager.cache_blocks(
            request,
            self.get_num_cacheable_tokens(num_computed_tokens, group_id),
            retention_interval=self.retention_interval,
            replay_boundaries=boundaries,
        )

find_longest_cache_hit(block_hashes, max_cache_hit_length) abstractmethod

Returns the per-group hit blocks, the hit length, and the number of num_uncached_common_prefix_tokens (a shared prefix that a sparse-retention group has not cached yet; 0 unless hybrid).

Source code in vllm/v1/core/kv_cache_coordinator.py
@abstractmethod
def find_longest_cache_hit(
    self,
    block_hashes: list[BlockHash],
    max_cache_hit_length: int,
) -> tuple[tuple[list[KVCacheBlock], ...], int, int]:
    """Returns the per-group hit blocks, the hit length, and the number of
    `num_uncached_common_prefix_tokens` (a shared prefix that a
    sparse-retention group has not cached yet; 0 unless hybrid)."""
    pass

free(request_id)

Free the blocks for the request.

Parameters:

  • request_id

    (str) –

    The request ID.

Source code in vllm/v1/core/kv_cache_coordinator.py
def free(self, request_id: str) -> None:
    """Free the blocks for the request.

    Args:
        request_id: The request ID.

    """
    for manager in self.single_type_managers:
        manager.free(request_id)

get_blocks(request_id)

Get the blocks for the request.

Source code in vllm/v1/core/kv_cache_coordinator.py
def get_blocks(self, request_id: str) -> tuple[list[KVCacheBlock], ...]:
    """Get the blocks for the request."""
    return tuple(
        manager.req_to_blocks.get(request_id) or []
        for manager in self.single_type_managers
    )

get_num_blocks_to_allocate(request_id, num_tokens, new_computed_blocks, num_encoder_tokens, total_computed_tokens, num_local_computed_tokens, num_tokens_main_model, apply_admission_cap=False, prefill_end=0)

Get the number of device blocks needed to be allocated for the request.

Parameters:

  • request_id

    (str) –

    The request ID.

  • num_tokens

    (int) –

    The total number of tokens that need a slot (including tokens that are already allocated).

  • new_computed_blocks

    (tuple[Sequence[KVCacheBlock], ...]) –

    The new computed blocks just hitting the prefix caching.

  • num_encoder_tokens

    (int) –

    The number of encoder tokens for allocating blocks for cross-attention.

  • total_computed_tokens

    (int) –

    Include both local and external tokens.

  • num_local_computed_tokens

    (int) –

    The number of local prefix-cache computed tokens.

  • num_tokens_main_model

    (int) –

    The number of tokens for the main model (aka target model in spec decode). w/o spec decode, it is num_tokens; with spec decode, it is num_tokens - num_lookahead_tokens.

  • apply_admission_cap

    (bool, default: False ) –

    If True, apply the recycling-aware per-request admission cap (SWA / chunked-local). Set only by the full-sequence admission gate; per-step allocation must leave it False so the predictor matches allocate_new_blocks.

  • prefill_end

    (int, default: 0 ) –

    The token index the request's prefill ends at, the same value the scheduler splits chunks against. Under sparse retention Mamba reserves a prefill checkpoint only on the chunk reaching it; under dense retention every chunk publishes a state, so it is ignored (0).

Returns:

  • int –

    The number of blocks to allocate.

Source code in vllm/v1/core/kv_cache_coordinator.py
def get_num_blocks_to_allocate(
    self,
    request_id: str,
    num_tokens: int,
    new_computed_blocks: tuple[Sequence[KVCacheBlock], ...],
    num_encoder_tokens: int,
    total_computed_tokens: int,
    num_local_computed_tokens: int,
    num_tokens_main_model: int,
    apply_admission_cap: bool = False,
    prefill_end: int = 0,
) -> int:
    """Get the number of device blocks needed to be allocated for the request.

    Args:
        request_id: The request ID.
        num_tokens: The total number of tokens that need a slot (including
            tokens that are already allocated).
        new_computed_blocks: The new computed blocks just hitting the
            prefix caching.
        num_encoder_tokens: The number of encoder tokens for allocating
            blocks for cross-attention.
        total_computed_tokens: Include both local and external tokens.
        num_local_computed_tokens: The number of local prefix-cache computed
            tokens.
        num_tokens_main_model: The number of tokens for the main model (aka target
            model in spec decode). w/o spec decode, it is num_tokens;
            with spec decode, it is num_tokens - num_lookahead_tokens.
        apply_admission_cap: If True, apply the recycling-aware
            per-request admission cap (SWA / chunked-local). Set only by
            the full-sequence admission gate; per-step allocation must
            leave it False so the predictor matches `allocate_new_blocks`.
        prefill_end: The token index the request's prefill ends at, the
            same value the scheduler splits chunks against. Under sparse
            retention Mamba reserves a prefill checkpoint only on the chunk
            reaching it; under dense retention every chunk publishes a
            state, so it is ignored (0).

    Returns:
        The number of blocks to allocate.

    """
    num_blocks_to_allocate = 0
    if self.retention_interval != 0:
        prefill_end = 0
    for i, manager in enumerate(self.single_type_managers):
        if isinstance(manager, CrossAttentionManager):
            # For cross-attention, we issue a single static allocation
            # of blocks based on the number of encoder input tokens.
            num_blocks_to_allocate += manager.get_num_blocks_to_allocate(
                request_id,
                num_encoder_tokens,
                [],
                0,
                0,
                num_encoder_tokens,
                apply_admission_cap=apply_admission_cap,
            )
        else:
            num_blocks_to_allocate += manager.get_num_blocks_to_allocate(
                request_id,
                num_tokens,
                new_computed_blocks[i],
                total_computed_tokens,
                num_local_computed_tokens,
                num_tokens_main_model,
                apply_admission_cap=apply_admission_cap,
                prefill_end=prefill_end,
            )
    return num_blocks_to_allocate

get_num_cacheable_tokens(num_computed_tokens, kv_cache_group_id)

Return the prefix eligible for hashing in this group.

Source code in vllm/v1/core/kv_cache_coordinator.py
def get_num_cacheable_tokens(
    self, num_computed_tokens: int, kv_cache_group_id: int
) -> int:
    """Return the prefix eligible for hashing in this group."""
    # Only cache tokens with finalized KV. The last num_reprefillable_tokens
    # tokens can be re-prefilled during multi-module MTP.
    return max(0, num_computed_tokens - self.num_reprefillable_tokens)

new_step_starts()

Notify each manager that a new step is starting.

Source code in vllm/v1/core/kv_cache_coordinator.py
def new_step_starts(self) -> None:
    """Notify each manager that a new step is starting."""
    for manager in self.single_type_managers:
        manager.new_step_starts()

pop_blocks_for_free(request_id)

Pop the request's bookkeeping from all single-type managers and return its blocks without returning them to the block pool. The caller must eventually pass the returned blocks to block_pool.free_blocks, freeing them in reverse order (so that tail blocks are evicted first).

Parameters:

  • request_id

    (str) –

    The request ID.

Returns:

Source code in vllm/v1/core/kv_cache_coordinator.py
def pop_blocks_for_free(self, request_id: str) -> list[KVCacheBlock]:
    """Pop the request's bookkeeping from all single-type managers and
    return its blocks without returning them to the block pool. The
    caller must eventually pass the returned blocks to
    `block_pool.free_blocks`, freeing them in reverse order (so that
    tail blocks are evicted first).

    Args:
        request_id: The request ID.

    Returns:
        The request's blocks in allocation order.

    """
    blocks: list[KVCacheBlock] = []
    for manager in self.single_type_managers:
        blocks.extend(manager.pop_blocks_for_free(request_id))
    return blocks

remove_skipped_blocks(request_id, processed_computed_tokens, num_prompt_tokens=None)

Remove the blocks that are no longer needed from blocks and replace the removed blocks with null_block.

Parameters:

  • request_id

    (str) –

    The request ID.

  • processed_computed_tokens

    (int) –

    Computed-token prefix length covering fully processed and committed tokens only (safe to free).

  • num_prompt_tokens

    (int | None, default: None ) –

    Optional prompt length. R-SWA managers use this to free gap blocks between the prefill tail and decode window; other manager types ignore it.

Source code in vllm/v1/core/kv_cache_coordinator.py
def remove_skipped_blocks(
    self,
    request_id: str,
    processed_computed_tokens: int,
    num_prompt_tokens: int | None = None,
) -> None:
    """Remove the blocks that are no longer needed from `blocks` and replace
    the removed blocks with null_block.

    Args:
        request_id: The request ID.
        processed_computed_tokens: Computed-token prefix length covering
            fully processed and committed tokens only (safe to free).
        num_prompt_tokens: Optional prompt length. R-SWA managers use this to
            free gap blocks between the prefill tail and decode window; other
            manager types ignore it.

    """
    for manager in self.single_type_managers:
        manager.remove_skipped_blocks(
            request_id, processed_computed_tokens, num_prompt_tokens
        )

reset_prefix_cache()

Reset each manager's pool once.

Source code in vllm/v1/core/kv_cache_coordinator.py
def reset_prefix_cache(self) -> bool:
    """Reset each manager's pool once."""
    pools = dict.fromkeys(
        manager.block_pool for manager in self.single_type_managers
    )
    return all([pool.reset_prefix_cache() for pool in pools])

KVCacheCoordinatorNoPrefixCache

Bases: KVCacheCoordinator

KV cache coordinator to use if prefix caching is disabled or unsupported. In contrast to UnitaryKVCacheCoordinator and HybridKVCacheCoordinator, supports arbitrary numbers of KV cache groups (including 0 groups). Does not implement any features related to prefix caching.

Source code in vllm/v1/core/kv_cache_coordinator.py
class KVCacheCoordinatorNoPrefixCache(KVCacheCoordinator):
    """KV cache coordinator to use if prefix caching is disabled or unsupported.
    In contrast to UnitaryKVCacheCoordinator and HybridKVCacheCoordinator,
    supports arbitrary numbers of KV cache groups (including 0 groups).
    Does not implement any features related to prefix caching.
    """

    def __init__(
        self,
        kv_cache_config: KVCacheConfig,
        max_model_len: int,
        max_in_flight_tokens: int,
        use_eagle: bool,
        enable_kv_cache_events: bool,
        dcp_world_size: int,
        pcp_world_size: int,
        scheduler_block_size: int,
        hash_block_size: int,
        metrics_collector: KVCacheMetricsCollector | None = None,
        num_hash_lookahead_tokens: int = 0,
        num_prefill_lookahead: int = 0,
    ):
        super().__init__(
            kv_cache_config,
            max_model_len,
            max_in_flight_tokens,
            use_eagle,
            False,
            enable_kv_cache_events,
            dcp_world_size=dcp_world_size,
            pcp_world_size=pcp_world_size,
            scheduler_block_size=scheduler_block_size,
            hash_block_size=hash_block_size,
            metrics_collector=metrics_collector,
            num_hash_lookahead_tokens=num_hash_lookahead_tokens,
            num_prefill_lookahead=num_prefill_lookahead,
        )
        self.num_single_type_manager = len(self.single_type_managers)

    def find_longest_cache_hit(
        self,
        block_hashes: list[BlockHash],
        max_cache_hit_length: int,
    ) -> tuple[tuple[list[KVCacheBlock], ...], int, int]:
        blocks: tuple[list[KVCacheBlock], ...] = tuple(
            [] for _ in range(self.num_single_type_manager)
        )
        return blocks, 0, 0

UnitaryKVCacheCoordinator

Bases: KVCacheCoordinator

KV cache coordinator for models with only one KV cache group. This is the case for models with only one KV cache type, e.g., all attention layers use full attention or all attention layers use sliding window attention.

Source code in vllm/v1/core/kv_cache_coordinator.py
class UnitaryKVCacheCoordinator(KVCacheCoordinator):
    """KV cache coordinator for models with only one KV cache group. This is the
    case for models with only one KV cache type, e.g., all attention layers use
    full attention or all attention layers use sliding window attention.
    """

    def __init__(
        self,
        kv_cache_config: KVCacheConfig,
        max_model_len: int,
        max_in_flight_tokens: int,
        use_eagle: bool,
        enable_caching: bool,
        enable_kv_cache_events: bool,
        dcp_world_size: int,
        pcp_world_size: int,
        scheduler_block_size: int,
        hash_block_size: int,
        metrics_collector: KVCacheMetricsCollector | None = None,
        num_hash_lookahead_tokens: int = 0,
        num_prefill_lookahead: int = 0,
    ):
        super().__init__(
            kv_cache_config,
            max_model_len,
            max_in_flight_tokens,
            use_eagle,
            enable_caching,
            enable_kv_cache_events,
            dcp_world_size=dcp_world_size,
            pcp_world_size=pcp_world_size,
            scheduler_block_size=scheduler_block_size,
            hash_block_size=hash_block_size,
            metrics_collector=metrics_collector,
            num_hash_lookahead_tokens=num_hash_lookahead_tokens,
            num_prefill_lookahead=num_prefill_lookahead,
        )
        self.group_block_size = self.kv_cache_config.kv_cache_groups[0].block_size
        self.manager_config = self.kv_cache_config.kv_cache_groups[0].manager_config
        self.dcp_world_size = self.single_type_managers[0].dcp_world_size
        self.pcp_world_size = pcp_world_size
        self.block_size = self.single_type_managers[0].block_size
        # For models using only Mamba, block_size is set to max_model_len when
        # prefix caching is disabled, and hash_block_size validation is skipped.
        assert not enable_caching or (hash_block_size == self.block_size), (
            "UnitaryKVCacheCoordinator assumes hash_block_size == block_size"
        )
        assert len(self.kv_cache_config.kv_cache_groups) == 1, (
            "UnitaryKVCacheCoordinator assumes only one kv cache group"
        )
        # Single group; useless but just set ``use_eagle`` for consistency regardless.
        self.single_type_managers[0].use_eagle = 0 in self.drop_eagle_group_ids

    def find_longest_cache_hit(
        self,
        block_hashes: list[BlockHash],
        max_cache_hit_length: int,
    ) -> tuple[tuple[list[KVCacheBlock], ...], int, int]:
        hit_blocks, hit_length = self.single_type_managers[0].find_longest_cache_hit(
            block_hashes=block_hashes,
            max_length=max_cache_hit_length,
            kv_cache_group_ids=[0],
            block_pool=self.block_pool,
            block_size=self.group_block_size,
            manager_config=self.manager_config,
            drop_eagle_block=0 in self.drop_eagle_group_ids,
            alignment_tokens=self.block_size,
            dcp_world_size=self.dcp_world_size,
            pcp_world_size=self.pcp_world_size,
        )
        # Single group: nothing "uncached common" -- no other group to lag it.
        return hit_blocks, hit_length, 0

replay_boundaries(num_prompt_tokens, scheduler_block_size, use_eagle, num_hash_lookahead_tokens)

Positions a later request replaying a prompt can resume at.

A hit is the shortest across all groups, so every group retains state at each position; EAGLE groups also keep the block above, which they match and drop back from (see reachable_block_mask).

Two positions are reachable: a resend of the identical prompt is capped at num_tokens - 1 (its last token is recomputed for logits), a longer sibling matches the final aligned block. They differ only on a block-aligned prompt, where retaining just the higher one collapses the resend's hit to 0. The alignment is the scheduler block size, not the finer hash granularity, which would over-estimate the reach.

A lookahead hash exists only once the tokens after its block are known, so a resend reaches at most num_tokens - num_hash_lookahead_tokens.

Source code in vllm/v1/core/kv_cache_coordinator.py
def replay_boundaries(
    num_prompt_tokens: int,
    scheduler_block_size: int,
    use_eagle: bool,
    num_hash_lookahead_tokens: int,
) -> tuple[int, ...]:
    """Positions a later request replaying a prompt can resume at.

    A hit is the shortest across all groups, so every group retains state
    at each position; EAGLE groups also keep the block above, which they
    match and drop back from (see `reachable_block_mask`).

    Two positions are reachable: a resend of the identical prompt is capped
    at `num_tokens - 1` (its last token is recomputed for logits), a
    longer sibling matches the final aligned block. They differ only on a
    block-aligned prompt, where retaining just the higher one collapses the
    resend's hit to 0. The alignment is the scheduler block size, not the
    finer hash granularity, which would over-estimate the reach.

    A lookahead hash exists only once the tokens after its block are known, so
    a resend reaches at most `num_tokens - num_hash_lookahead_tokens`.
    """
    if not use_eagle:
        return (num_prompt_tokens - max(1, num_hash_lookahead_tokens),)
    block = scheduler_block_size
    resend = (num_prompt_tokens - 1) // block * block
    extension = num_prompt_tokens // block * block
    return tuple(sorted({max(resend - block, 0), max(extension - block, 0)}))