[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
@@ -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