[Metrics] Expose cached prompt tokens by cache tier (#56318)
Signed-off-by: Cam Quilici <cjquilici@gmail.com> Signed-off-by: Cam Quilici <cameron@semianalysis.com> Co-authored-by: Cam Quilici <cameron@semianalysis.com> Co-authored-by: Nick Hill <nickhill123@gmail.com> Co-authored-by: Yifan Qiao <yifanqiao@inferact.ai>
This commit is contained in:
co-authored by
Cam Quilici
Nick Hill
Yifan Qiao
parent
ad0f67a7ec
commit
e37e51dd24
@@ -51,6 +51,7 @@ import torch
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.attention.backend import AttentionMetadata
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -179,6 +180,10 @@ class KVConnectorWorkerMetadata(ABC):
|
||||
class KVConnectorBase_V1(ABC):
|
||||
"""Base class for KV connectors."""
|
||||
|
||||
# Source label for this connector's external hits. Subclasses must set
|
||||
# HOST/DISK/P2P or override get_external_cache_hit_sources().
|
||||
_cache_hit_source = CacheHitSource.EXTERNAL_UNSPECIFIED
|
||||
|
||||
@property
|
||||
def supports_divergent_local_hybrid_hits(self) -> bool:
|
||||
"""Whether external hits can complete divergent local hybrid hits.
|
||||
@@ -527,6 +532,24 @@ class KVConnectorBase_V1(ABC):
|
||||
"""
|
||||
pass
|
||||
|
||||
def get_external_cache_hit_sources(
|
||||
self,
|
||||
request: "Request",
|
||||
num_external_tokens: int,
|
||||
) -> dict[CacheHitSource, int]:
|
||||
"""Split ``num_external_tokens`` by the cache tier that supplied them.
|
||||
|
||||
Called after :meth:`update_state_after_alloc`, so the load plan is
|
||||
known. Counts must sum to ``num_external_tokens``; a mismatch is
|
||||
reported as ``external_unspecified``. Only non-zero counts are
|
||||
included.
|
||||
|
||||
Default: all tokens under ``_cache_hit_source``.
|
||||
"""
|
||||
if num_external_tokens == 0:
|
||||
return {}
|
||||
return {self._cache_hit_source: num_external_tokens}
|
||||
|
||||
@abstractmethod
|
||||
def update_state_after_alloc(
|
||||
self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int
|
||||
|
||||
@@ -67,6 +67,7 @@ from vllm.v1.kv_cache_interface import (
|
||||
SlidingWindowMLASpec,
|
||||
SlidingWindowSpec,
|
||||
)
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.request import RequestStatus
|
||||
from vllm.v1.worker.block_table import BlockTable
|
||||
from vllm.v1.worker.utils import select_common_block_size
|
||||
@@ -700,6 +701,8 @@ class MooncakeConnectorMetadata(KVConnectorMetadata):
|
||||
|
||||
|
||||
class MooncakeConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
_cache_hit_source = CacheHitSource.P2P
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
|
||||
@@ -99,6 +99,7 @@ from vllm.v1.kv_cache_interface import (
|
||||
SlidingWindowSpec,
|
||||
is_full_attention_spec,
|
||||
)
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
from vllm.v1.request import RequestStatus
|
||||
|
||||
@@ -222,6 +223,8 @@ def resolve_moriio_transfer_ack(
|
||||
|
||||
|
||||
class MoRIIOConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
_cache_hit_source = CacheHitSource.P2P
|
||||
|
||||
@property
|
||||
def supports_divergent_local_hybrid_hits(self) -> bool:
|
||||
# The READ path always transfers the recurrent-state slot, including
|
||||
|
||||
@@ -31,6 +31,7 @@ from vllm.distributed.kv_transfer.kv_connector.v1.metrics import (
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.attention.backend import AttentionMetadata
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -451,6 +452,18 @@ class MultiConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
to_return = (toks, load_async)
|
||||
return to_return
|
||||
|
||||
def get_external_cache_hit_sources(
|
||||
self,
|
||||
request: "Request",
|
||||
num_external_tokens: int,
|
||||
) -> dict[CacheHitSource, int]:
|
||||
chosen_connector = self._requests_to_connector.get(request.request_id)
|
||||
if chosen_connector is None:
|
||||
return super().get_external_cache_hit_sources(request, num_external_tokens)
|
||||
return self._connectors[chosen_connector].get_external_cache_hit_sources(
|
||||
request, num_external_tokens
|
||||
)
|
||||
|
||||
def update_state_after_alloc(
|
||||
self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int
|
||||
):
|
||||
|
||||
@@ -58,6 +58,7 @@ from vllm.forward_context import ForwardContext
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.attention.backend import AttentionMetadata
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -77,6 +78,8 @@ logger = init_logger(__name__)
|
||||
class NixlBaseConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
"""Base connector with common logic shared by pull and push modes."""
|
||||
|
||||
_cache_hit_source = CacheHitSource.P2P
|
||||
|
||||
@property
|
||||
def supports_divergent_local_hybrid_hits(self) -> bool:
|
||||
return True
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import time
|
||||
from collections import Counter
|
||||
from collections.abc import Iterable, Sequence
|
||||
from dataclasses import dataclass, field, replace
|
||||
from itertools import chain, islice
|
||||
@@ -56,6 +57,7 @@ from vllm.v1.kv_offload.base import (
|
||||
TierMatcher,
|
||||
make_offload_key,
|
||||
)
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
from vllm.v1.request import Request, RequestStatus
|
||||
|
||||
@@ -375,6 +377,9 @@ class RequestOffloadState:
|
||||
# Fine-grained token boundary selected beyond the last complete offload
|
||||
# chunk. It is consumed when the corresponding load is scheduled.
|
||||
partial_tail_boundary: int | None = None
|
||||
# Loaded attention keys cover their token positions. Recurrent state
|
||||
# supports the whole reused external prefix.
|
||||
load_key_ranges: list[tuple[int, int, OffloadKey]] = field(default_factory=list)
|
||||
# True once on_request_finished has been signaled to the manager.
|
||||
finished_signaled: bool = False
|
||||
|
||||
@@ -587,8 +592,9 @@ class OffloadingConnectorScheduler:
|
||||
sliding_window_groups.sort(key=_sliding_window_sort_key, reverse=True)
|
||||
|
||||
# used by _lookup
|
||||
self._full_attention_groups: tuple[int, ...] = tuple(full_attention_groups)
|
||||
self._sliding_window_groups: tuple[int, ...] = tuple(sliding_window_groups)
|
||||
self._lookup_groups = tuple(full_attention_groups) + self._sliding_window_groups
|
||||
self._lookup_groups = self._full_attention_groups + self._sliding_window_groups
|
||||
self._mamba_align_size: int | None = resolve_mamba_align_size(
|
||||
spec, kv_cache_config
|
||||
)
|
||||
@@ -1090,6 +1096,53 @@ class OffloadingConnectorScheduler:
|
||||
|
||||
return num_hit_tokens, bool(num_hit_tokens)
|
||||
|
||||
def get_external_cache_hit_sources(
|
||||
self,
|
||||
request: Request,
|
||||
num_external_tokens: int,
|
||||
) -> dict[CacheHitSource, int]:
|
||||
"""Split the accepted external hit by the tier each loaded key came from.
|
||||
|
||||
Attention keys cover only their loaded token ranges; recurrent state
|
||||
covers the whole reused prefix. Overlaps report the outermost tier.
|
||||
Uncovered tokens, including omitted sliding-window history, are
|
||||
``external_unspecified``.
|
||||
"""
|
||||
sources: dict[CacheHitSource, int] = {}
|
||||
if num_external_tokens == 0:
|
||||
return sources
|
||||
req_status = self._req_status[request.request_id]
|
||||
start = req_status.num_locally_computed_tokens
|
||||
end = start + num_external_tokens
|
||||
|
||||
events: list[tuple[int, int, CacheHitSource]] = [
|
||||
(end, 0, CacheHitSource.EXTERNAL_UNSPECIFIED)
|
||||
]
|
||||
for lo, hi, key in req_status.load_key_ranges:
|
||||
lo, hi = max(start, lo), min(end, hi)
|
||||
if lo >= hi:
|
||||
continue
|
||||
source = CacheHitSource(
|
||||
self.manager.get_load_source(key, req_status.req_context)
|
||||
)
|
||||
events.extend(((lo, 1, source), (hi, -1, source)))
|
||||
|
||||
# Sweep endpoints instead of rescanning every range for each interval.
|
||||
active: Counter[CacheHitSource] = Counter()
|
||||
position = start
|
||||
for boundary, delta, source in sorted(events):
|
||||
if boundary > position:
|
||||
tiers = [tier for tier, count in active.items() if count > 0]
|
||||
tier = (
|
||||
CacheHitSource.outermost(tiers)
|
||||
if tiers
|
||||
else CacheHitSource.EXTERNAL_UNSPECIFIED
|
||||
)
|
||||
sources[tier] = sources.get(tier, 0) + boundary - position
|
||||
active[source] += delta
|
||||
position = boundary
|
||||
return sources
|
||||
|
||||
def update_state_after_alloc(
|
||||
self, request: Request, blocks: KVCacheBlocks, num_external_tokens: int
|
||||
):
|
||||
@@ -1105,6 +1158,7 @@ class OffloadingConnectorScheduler:
|
||||
assert partial_tail_boundary == num_cached_tokens
|
||||
|
||||
keys_to_load: list[OffloadKey] = []
|
||||
req_status.load_key_ranges.clear()
|
||||
dst_block_ids: list[int] = []
|
||||
# per group
|
||||
group_sizes: list[int] = []
|
||||
@@ -1157,9 +1211,9 @@ class OffloadingConnectorScheduler:
|
||||
)
|
||||
end_chunk_idx = num_chunks - (partial_tail_boundary is not None)
|
||||
assert len(offload_keys) >= end_chunk_idx
|
||||
keys_to_load.extend(offload_keys[start_chunk_idx:end_chunk_idx])
|
||||
group_keys_to_load = offload_keys[start_chunk_idx:end_chunk_idx]
|
||||
if partial_tail_boundary is not None:
|
||||
keys_to_load.append(
|
||||
group_keys_to_load.append(
|
||||
self._make_boundary_key(
|
||||
request,
|
||||
group_config.group_idx,
|
||||
@@ -1167,6 +1221,24 @@ class OffloadingConnectorScheduler:
|
||||
req_status.req_context,
|
||||
)
|
||||
)
|
||||
keys_to_load.extend(group_keys_to_load)
|
||||
if isinstance(group_config.kv_cache_spec, MambaSpec):
|
||||
req_status.load_key_ranges.extend(
|
||||
(num_locally_computed_tokens, num_cached_tokens, key)
|
||||
for key in group_keys_to_load
|
||||
)
|
||||
else:
|
||||
for chunk_idx, key in enumerate(
|
||||
group_keys_to_load, start_chunk_idx
|
||||
):
|
||||
range_start = max(
|
||||
load_start_gpu_block_idx * tokens_per_block,
|
||||
chunk_idx * tokens_per_chunk,
|
||||
)
|
||||
range_end = min(
|
||||
num_cached_tokens, (chunk_idx + 1) * tokens_per_chunk
|
||||
)
|
||||
req_status.load_key_ranges.append((range_start, range_end, key))
|
||||
|
||||
dst_block_ids.extend(
|
||||
block.block_id
|
||||
|
||||
@@ -45,6 +45,7 @@ from vllm.v1.core.kv_cache_manager import KVCacheBlocks
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.kv_offload.factory import OffloadingSpecFactory
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
from vllm.v1.request import Request
|
||||
|
||||
@@ -179,6 +180,16 @@ class OffloadingConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
bound = min(per_group_hits[group_id] for group_id in self._bounding_group_ids)
|
||||
return max(0, bound - num_computed_tokens)
|
||||
|
||||
def get_external_cache_hit_sources(
|
||||
self,
|
||||
request: "Request",
|
||||
num_external_tokens: int,
|
||||
) -> dict[CacheHitSource, int]:
|
||||
assert self.connector_scheduler is not None
|
||||
return self.connector_scheduler.get_external_cache_hit_sources(
|
||||
request, num_external_tokens
|
||||
)
|
||||
|
||||
def update_state_after_alloc(
|
||||
self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int
|
||||
):
|
||||
|
||||
@@ -23,6 +23,7 @@ from vllm.distributed.kv_transfer.kv_connector.v1.metrics import (
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
from vllm.v1.simple_kv_offload.manager import (
|
||||
BoundaryStoreStats,
|
||||
@@ -109,6 +110,9 @@ class SimpleCPUOffloadConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
f"expected one of {VALID_KV_OFFLOAD_BACKENDS}"
|
||||
)
|
||||
disk_mode = kv_offload_backend == "disk"
|
||||
self._cache_hit_source = (
|
||||
CacheHitSource.DISK if disk_mode else CacheHitSource.HOST
|
||||
)
|
||||
|
||||
disk_path = extra_config.get("disk_path", None) or None
|
||||
disk_capacity_bytes = int(
|
||||
|
||||
@@ -1261,10 +1261,20 @@ class Scheduler(SchedulerInterface):
|
||||
self.connector_prefix_cache_stats is not None
|
||||
and connector_prefix_cache_queries != 0
|
||||
):
|
||||
preempted = request.num_preemptions > 0
|
||||
self.connector_prefix_cache_stats.record(
|
||||
num_tokens=connector_prefix_cache_queries,
|
||||
num_hits=connector_prefix_cache_hits,
|
||||
preempted=request.num_preemptions > 0,
|
||||
preempted=preempted,
|
||||
# The connector knows the tier only after the load
|
||||
# plan above exists.
|
||||
hits_by_source=(
|
||||
self.connector.get_external_cache_hit_sources(
|
||||
request, connector_prefix_cache_hits
|
||||
)
|
||||
if connector_prefix_cache_hits and not preempted
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
# Record at admission so unscheduled lookups are not counted.
|
||||
|
||||
@@ -18,6 +18,7 @@ if TYPE_CHECKING:
|
||||
|
||||
from vllm.v1.kv_hints import KvHintsEnvelope
|
||||
from vllm.v1.kv_offload.config import OffloadingConfig
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
|
||||
# `OffloadKey` identifies an offloaded block. It combines a block hash with
|
||||
# its KV cache group index, encoded as raw bytes to avoid tuple GC overhead.
|
||||
@@ -248,6 +249,18 @@ class OffloadingManager(ABC):
|
||||
"""
|
||||
pass
|
||||
|
||||
def get_load_source(
|
||||
self, key: OffloadKey, req_context: ReqContext
|
||||
) -> CacheHitSource:
|
||||
"""Return the cache tier that supplied a successful lookup.
|
||||
|
||||
This is queried only after ``lookup`` resolves to ``HIT``. Composing
|
||||
managers can override it to retain the origin across asynchronous
|
||||
promotion into a primary tier. The default keeps out-of-tree managers
|
||||
compatible while making unknown provenance explicit.
|
||||
"""
|
||||
return CacheHitSource.EXTERNAL_UNSPECIFIED
|
||||
|
||||
@abstractmethod
|
||||
def prepare_load(
|
||||
self,
|
||||
|
||||
@@ -27,6 +27,7 @@ from vllm.v1.kv_offload.cpu.common import (
|
||||
)
|
||||
from vllm.v1.kv_offload.cpu.policies.base import CachePolicy, ChunkStatus
|
||||
from vllm.v1.kv_offload.cpu.policies.factory import CachePolicyFactory
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -193,6 +194,12 @@ class CPUOffloadingManager(OffloadingManager):
|
||||
return LookupResult.HIT_PENDING
|
||||
return LookupResult.HIT
|
||||
|
||||
@override
|
||||
def get_load_source(
|
||||
self, key: OffloadKey, req_context: ReqContext
|
||||
) -> CacheHitSource:
|
||||
return CacheHitSource.HOST
|
||||
|
||||
@override
|
||||
def prepare_load(
|
||||
self,
|
||||
|
||||
@@ -24,6 +24,7 @@ from vllm.v1.kv_offload.base import (
|
||||
from vllm.v1.kv_offload.tiering.backpressure import (
|
||||
BackpressureDetector,
|
||||
)
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.offloading.metrics import (
|
||||
@@ -141,6 +142,17 @@ class SecondaryTierManager(ABC):
|
||||
"""
|
||||
|
||||
medium: ClassVar[Medium | None] = None
|
||||
# Cache tier reported for hits served from this tier. Derived from
|
||||
# ``medium`` unless a subclass sets it; ``None`` medium means unknown.
|
||||
cache_hit_source: ClassVar[CacheHitSource] = CacheHitSource.EXTERNAL_UNSPECIFIED
|
||||
|
||||
def __init_subclass__(cls, **kwargs: Any) -> None:
|
||||
super().__init_subclass__(**kwargs)
|
||||
if "cache_hit_source" not in cls.__dict__ and cls.medium is not None:
|
||||
cls.cache_hit_source = {
|
||||
Medium.CPU: CacheHitSource.HOST,
|
||||
Medium.STORAGE: CacheHitSource.DISK,
|
||||
}[cls.medium]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
||||
@@ -54,6 +54,7 @@ from vllm.v1.kv_offload.tiering.base import (
|
||||
TransferJob,
|
||||
)
|
||||
from vllm.v1.kv_offload.tiering.metrics import TieringMetricsTracker
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -232,6 +233,11 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
# complete_store(), since complete_store() can still submit cascades.
|
||||
self._req_state: dict[str, RequestState] = {}
|
||||
|
||||
# Preserve the original tier for this request's cache-hit metrics,
|
||||
# even after its KV blocks are promoted into host memory
|
||||
# (otherwise a disk or P2P hit would be mislabeled as a host hit).
|
||||
self._request_load_sources: dict[str, dict[OffloadKey, CacheHitSource]] = {}
|
||||
|
||||
# Cached ParentManager wrappers for each secondary tier.
|
||||
self._tier_parents: dict[SecondaryTierManager, _SecondaryTierFacingParent] = {
|
||||
tier: _SecondaryTierFacingParent(self, tier_idx)
|
||||
@@ -293,6 +299,13 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
successful_keys = ()
|
||||
failed_keys = transfer_job.keys
|
||||
|
||||
load_sources = self._request_load_sources.get(transfer_job.req_context.req_id)
|
||||
if load_sources is not None:
|
||||
source = self.secondary_tiers[job_metadata.tier_idx].cache_hit_source
|
||||
for key in failed_keys:
|
||||
if load_sources.get(key) == source:
|
||||
del load_sources[key]
|
||||
|
||||
if successful_keys:
|
||||
self.primary_tier.complete_write(
|
||||
successful_keys,
|
||||
@@ -464,6 +477,15 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
return LookupResult.RETRY
|
||||
return LookupResult.MISS
|
||||
|
||||
@override
|
||||
def get_load_source(
|
||||
self, key: OffloadKey, req_context: ReqContext
|
||||
) -> CacheHitSource:
|
||||
load_sources = self._request_load_sources.get(req_context.req_id)
|
||||
if load_sources is not None and key in load_sources:
|
||||
return load_sources[key]
|
||||
return self.primary_tier.get_load_source(key, req_context)
|
||||
|
||||
def _initiate_promotion(
|
||||
self,
|
||||
tier_idx: int,
|
||||
@@ -501,6 +523,10 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
|
||||
store_spec = primary_write_result.store_spec
|
||||
assert isinstance(store_spec, CPULoadStoreSpec)
|
||||
load_sources = self._request_load_sources.setdefault(req_context.req_id, {})
|
||||
source = self.secondary_tiers[tier_idx].cache_hit_source
|
||||
for promoted_key in primary_write_result.keys_to_store:
|
||||
load_sources[promoted_key] = source
|
||||
# Defer submit_load to on_schedule_end(). Group by (tier, request) so
|
||||
# each request's chunks are submitted as one batched job per tier.
|
||||
tier_pending = self._pending_load_submissions.setdefault(tier_idx, {})
|
||||
@@ -848,6 +874,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
continue
|
||||
tier.on_request_finished(state.req_context)
|
||||
self._metrics.on_request_finished(state.req_context)
|
||||
self._request_load_sources.pop(req_id, None)
|
||||
del self._req_state[req_id]
|
||||
|
||||
@override
|
||||
@@ -930,6 +957,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
# reset below invalidates; their submit_load() has not yet been
|
||||
# called so no tier I/O is touching that memory.
|
||||
self._pending_load_submissions.clear()
|
||||
self._request_load_sources.clear()
|
||||
self._metrics.assert_idle()
|
||||
|
||||
finished_req_ids = []
|
||||
|
||||
@@ -11,7 +11,7 @@ import time
|
||||
import uuid
|
||||
from collections.abc import Iterable, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from typing import TYPE_CHECKING, Any, ClassVar
|
||||
|
||||
from typing_extensions import override
|
||||
|
||||
@@ -35,6 +35,7 @@ from vllm.v1.kv_offload.tiering.base import (
|
||||
from vllm.v1.kv_offload.tiering.p2p.control import ControlTransport, ZmqTransport
|
||||
from vllm.v1.kv_offload.tiering.p2p.data import DataTransport, NixlTransport
|
||||
from vllm.v1.kv_offload.tiering.p2p.session import P2PSession
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.kv_offload.base import OffloadingSpec
|
||||
@@ -206,6 +207,8 @@ class P2PSecondaryTierManager(SecondaryTierManager):
|
||||
and existing sessions are polled even when no requests are scheduled.
|
||||
"""
|
||||
|
||||
cache_hit_source: ClassVar[CacheHitSource] = CacheHitSource.P2P
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
offloading_spec: OffloadingSpec,
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class CacheHitSource(str, Enum):
|
||||
"""Where cached prompt tokens' KV came from.
|
||||
|
||||
Members are listed in the order blocks are offloaded: accelerator, then
|
||||
host memory, then secondary tiers. Per-source token counts are plain
|
||||
``dict[CacheHitSource, int]`` mappings holding only non-zero entries.
|
||||
"""
|
||||
|
||||
DEVICE = "device"
|
||||
HOST = "host"
|
||||
P2P = "p2p"
|
||||
DISK = "disk"
|
||||
# Fallback: uninstrumented connector or remote store. Last, so mixing
|
||||
# with a known tier never reports the known one.
|
||||
EXTERNAL_UNSPECIFIED = "external_unspecified"
|
||||
|
||||
@classmethod
|
||||
def outermost(cls, sources: Iterable[CacheHitSource]) -> CacheHitSource:
|
||||
"""The tier in ``sources`` farthest from the accelerator."""
|
||||
return max(sources, key=_SOURCE_ORDER.__getitem__)
|
||||
|
||||
|
||||
_SOURCE_ORDER = {source: rank for rank, source in enumerate(CacheHitSource)}
|
||||
@@ -23,6 +23,7 @@ from vllm.logger import init_logger
|
||||
from vllm.plugins import STAT_LOGGER_PLUGINS_GROUP, load_plugins_by_group
|
||||
from vllm.v1.engine import FinishReason
|
||||
from vllm.v1.metrics.buckets import histogram_buckets
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.metrics.perf import PerfMetricsLogging, PerfMetricsProm
|
||||
from vllm.v1.metrics.prometheus import unregister_vllm_metrics
|
||||
from vllm.v1.metrics.stats import (
|
||||
@@ -752,6 +753,23 @@ class PrometheusStatLogger(AggregateStatLoggerBase):
|
||||
counter_prompt_tokens_cached, per_engine_labelvalues
|
||||
)
|
||||
|
||||
self.counter_prompt_tokens_cached_by_source = self._counter_cls(
|
||||
name="vllm:prompt_tokens_cached_by_source",
|
||||
documentation=(
|
||||
"Prefix-cache hit tokens by the cache tier that supplied them: "
|
||||
"device (local HBM), host (offloaded to DRAM), disk, p2p "
|
||||
"(transferred from another vLLM instance) or "
|
||||
"external_unspecified. Counted at admission; sums to "
|
||||
"vllm:prefix_cache_hits + vllm:external_prefix_cache_hits."
|
||||
),
|
||||
labelnames=labelnames + ["source"],
|
||||
)
|
||||
for source in CacheHitSource:
|
||||
for labelvalues in per_engine_labelvalues.values():
|
||||
self.counter_prompt_tokens_cached_by_source.labels(
|
||||
*labelvalues, source.value
|
||||
)
|
||||
|
||||
counter_generation_tokens = self._counter_cls(
|
||||
name="vllm:generation_tokens",
|
||||
documentation="Number of generation tokens processed.",
|
||||
@@ -1111,13 +1129,23 @@ class PrometheusStatLogger(AggregateStatLoggerBase):
|
||||
scheduler_stats.prefix_cache_stats.hits
|
||||
)
|
||||
|
||||
if scheduler_stats.connector_prefix_cache_stats is not None:
|
||||
labelvalues = self.per_engine_labelvalues[engine_idx]
|
||||
self.counter_prompt_tokens_cached_by_source.labels(
|
||||
*labelvalues, CacheHitSource.DEVICE.value
|
||||
).inc(scheduler_stats.prefix_cache_stats.hits)
|
||||
|
||||
connector_stats = scheduler_stats.connector_prefix_cache_stats
|
||||
if connector_stats is not None:
|
||||
self.counter_connector_prefix_cache_queries[engine_idx].inc(
|
||||
scheduler_stats.connector_prefix_cache_stats.queries
|
||||
connector_stats.queries
|
||||
)
|
||||
self.counter_connector_prefix_cache_hits[engine_idx].inc(
|
||||
scheduler_stats.connector_prefix_cache_stats.hits
|
||||
connector_stats.hits
|
||||
)
|
||||
for tier, num_tokens in connector_stats.hits_by_source.items():
|
||||
self.counter_prompt_tokens_cached_by_source.labels(
|
||||
*labelvalues, tier.value
|
||||
).inc(num_tokens)
|
||||
|
||||
if scheduler_stats.spec_decoding_stats is not None:
|
||||
self.spec_decoding_prom.observe(
|
||||
|
||||
@@ -8,9 +8,13 @@ from typing import TYPE_CHECKING, Any
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.compilation.cuda_graph import CUDAGraphStat
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.metrics.perf import PerfStats
|
||||
from vllm.v1.spec_decode.metrics import SpecDecodingStats
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.engine import EngineCoreEvent, EngineCoreOutput, FinishReason
|
||||
|
||||
@@ -128,19 +132,42 @@ class PrefixCacheStats(BaseCacheStats):
|
||||
|
||||
preempted_hits: int = 0
|
||||
"""The `hits` number for preempted requests."""
|
||||
hits_by_source: dict[CacheHitSource, int] = field(default_factory=dict)
|
||||
"""`hits` split by the cache tier that supplied them (connector stats only)."""
|
||||
|
||||
def record(self, num_tokens: int, num_hits: int, preempted: bool) -> None:
|
||||
def record(
|
||||
self,
|
||||
num_tokens: int,
|
||||
num_hits: int,
|
||||
preempted: bool,
|
||||
hits_by_source: dict[CacheHitSource, int] | None = None,
|
||||
) -> None:
|
||||
"""Aggregate request information into the stats."""
|
||||
if preempted:
|
||||
# Previously preempted request
|
||||
self.preempted_requests += 1
|
||||
self.preempted_queries += num_tokens
|
||||
self.preempted_hits += num_hits
|
||||
else:
|
||||
# New request
|
||||
self.requests += 1
|
||||
self.queries += num_tokens
|
||||
self.hits += num_hits
|
||||
return
|
||||
# New request
|
||||
self.requests += 1
|
||||
self.queries += num_tokens
|
||||
self.hits += num_hits
|
||||
if hits_by_source is None:
|
||||
return
|
||||
if sum(hits_by_source.values()) != num_hits:
|
||||
logger.warning_once(
|
||||
"Connector attributed %s for %d cached tokens; reporting them as %s.",
|
||||
str(hits_by_source),
|
||||
num_hits,
|
||||
CacheHitSource.EXTERNAL_UNSPECIFIED.value,
|
||||
)
|
||||
hits_by_source = {CacheHitSource.EXTERNAL_UNSPECIFIED: num_hits}
|
||||
for source, num_source_hits in hits_by_source.items():
|
||||
if num_source_hits:
|
||||
self.hits_by_source[source] = (
|
||||
self.hits_by_source.get(source, 0) + num_source_hits
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
Reference in New Issue
Block a user