metrics.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. import time
  2. from abc import ABC, abstractmethod
  3. from dataclasses import dataclass
  4. from typing import TYPE_CHECKING
  5. from typing import Counter as CollectionsCounter
  6. from typing import Dict, List, Optional, Protocol, Union
  7. import numpy as np
  8. import prometheus_client
  9. from loguru import logger
  10. from aphrodite.executor.ray_utils import ray
  11. if ray is not None:
  12. from ray.util import metrics as ray_metrics
  13. else:
  14. ray_metrics = None
  15. if TYPE_CHECKING:
  16. from aphrodite.spec_decode.metrics import SpecDecodeWorkerMetrics
  17. prometheus_client.disable_created_metrics()
  18. # begin-metrics-definitions
  19. class Metrics:
  20. labelname_finish_reason = "finished_reason"
  21. _base_library = prometheus_client
  22. def __init__(self, labelnames: List[str], max_model_len: int):
  23. # Unregister any existing Aphrodite collectors
  24. self._unregister_aphrodite_metrics()
  25. # Config Information
  26. self.info_cache_config = prometheus_client.Info(
  27. name='aphrodite:cache_config',
  28. documentation='information of cache_config')
  29. # System stats
  30. # Scheduler State
  31. self.gauge_scheduler_running = self._base_library.Gauge(
  32. name="aphrodite:num_requests_running",
  33. documentation="Number of requests currently running on GPU.",
  34. labelnames=labelnames)
  35. self.gauge_scheduler_waiting = self._base_library.Gauge(
  36. name="aphrodite:num_requests_waiting",
  37. documentation="Number of requests waiting to be processed.",
  38. labelnames=labelnames)
  39. self.gauge_scheduler_swapped = self._base_library.Gauge(
  40. name="aphrodite:num_requests_swapped",
  41. documentation="Number of requests swapped to CPU.",
  42. labelnames=labelnames)
  43. # KV Cache Usage in %
  44. self.gauge_gpu_cache_usage = self._base_library.Gauge(
  45. name="aphrodite:gpu_cache_usage_perc",
  46. documentation="GPU KV-cache usage. 1 means 100 percent usage.",
  47. labelnames=labelnames)
  48. self.gauge_cpu_cache_usage = self._base_library.Gauge(
  49. name="aphrodite:cpu_cache_usage_perc",
  50. documentation="CPU KV-cache usage. 1 means 100 percent usage.",
  51. labelnames=labelnames)
  52. # Iteration stats
  53. self.counter_num_preemption = self._base_library.Counter(
  54. name="aphrodite:num_preemptions_total",
  55. documentation="Cumulative number of preemption from the engine.",
  56. labelnames=labelnames)
  57. self.counter_prompt_tokens = self._base_library.Counter(
  58. name="aphrodite:prompt_tokens_total",
  59. documentation="Number of prefill tokens processed.",
  60. labelnames=labelnames)
  61. self.counter_generation_tokens = self._base_library.Counter(
  62. name="aphrodite:generation_tokens_total",
  63. documentation="Number of generation tokens processed.",
  64. labelnames=labelnames)
  65. self.histogram_time_to_first_token = self._base_library.Histogram(
  66. name="aphrodite:time_to_first_token_seconds",
  67. documentation="Histogram of time to first token in seconds.",
  68. labelnames=labelnames,
  69. buckets=[
  70. 0.001, 0.005, 0.01, 0.02, 0.04, 0.06, 0.08, 0.1, 0.25, 0.5,
  71. 0.75, 1.0, 2.5, 5.0, 7.5, 10.0
  72. ])
  73. self.histogram_time_per_output_token = self._base_library.Histogram(
  74. name="aphrodite:time_per_output_token_seconds",
  75. documentation="Histogram of time per output token in seconds.",
  76. labelnames=labelnames,
  77. buckets=[
  78. 0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.75,
  79. 1.0, 2.5
  80. ])
  81. # Request stats
  82. # Latency
  83. self.histogram_e2e_time_request = self._base_library.Histogram(
  84. name="aphrodite:e2e_request_latency_seconds",
  85. documentation="Histogram of end to end request latency in seconds.",
  86. labelnames=labelnames,
  87. buckets=[1.0, 2.5, 5.0, 10.0, 15.0, 20.0, 30.0, 40.0, 50.0, 60.0])
  88. # Metadata
  89. self.histogram_num_prompt_tokens_request = self._base_library.Histogram(
  90. name="aphrodite:request_prompt_tokens",
  91. documentation="Number of prefill tokens processed.",
  92. labelnames=labelnames,
  93. buckets=build_1_2_5_buckets(max_model_len),
  94. )
  95. self.histogram_num_generation_tokens_request = \
  96. self._base_library.Histogram(
  97. name="aphrodite:request_generation_tokens",
  98. documentation="Number of generation tokens processed.",
  99. labelnames=labelnames,
  100. buckets=build_1_2_5_buckets(max_model_len),
  101. )
  102. self.histogram_best_of_request = self._base_library.Histogram(
  103. name="aphrodite:request_params_best_of",
  104. documentation="Histogram of the best_of request parameter.",
  105. labelnames=labelnames,
  106. buckets=[1, 2, 5, 10, 20],
  107. )
  108. self.histogram_n_request = self._base_library.Histogram(
  109. name="aphrodite:request_params_n",
  110. documentation="Histogram of the n request parameter.",
  111. labelnames=labelnames,
  112. buckets=[1, 2, 5, 10, 20],
  113. )
  114. self.counter_request_success = self._base_library.Counter(
  115. name="aphrodite:request_success_total",
  116. documentation="Count of successfully processed requests.",
  117. labelnames=labelnames + [Metrics.labelname_finish_reason])
  118. # Deprecated in favor of aphrodite:prompt_tokens_total
  119. self.gauge_avg_prompt_throughput = self._base_library.Gauge(
  120. name="aphrodite:avg_prompt_throughput_toks_per_s",
  121. documentation="Average prefill throughput in tokens/s.",
  122. labelnames=labelnames,
  123. )
  124. # Deprecated in favor of aphrodite:generation_tokens_total
  125. self.gauge_avg_generation_throughput = self._base_library.Gauge(
  126. name="aphrodite:avg_generation_throughput_toks_per_s",
  127. documentation="Average generation throughput in tokens/s.",
  128. labelnames=labelnames,
  129. )
  130. def _unregister_aphrodite_metrics(self) -> None:
  131. for collector in list(self._base_library.REGISTRY._collector_to_names):
  132. if hasattr(collector, "_name") and "aphrodite" in collector._name:
  133. self._base_library.REGISTRY.unregister(collector)
  134. class RayMetrics(Metrics):
  135. """
  136. RayMetrics is used by RayPrometheusStatLogger to log to Ray metrics.
  137. Provides the same metrics as Metrics but uses Ray's util.metrics library.
  138. """
  139. _base_library = ray_metrics
  140. def __init__(self, labelnames: List[str], max_model_len: int):
  141. if ray_metrics is None:
  142. raise ImportError("RayMetrics requires Ray to be installed.")
  143. super().__init__(labelnames, max_model_len)
  144. def _unregister_aphrodite_metrics(self) -> None:
  145. # No-op on purpose
  146. pass
  147. # end-metrics-definitions
  148. def build_1_2_5_buckets(max_value: int) -> List[int]:
  149. """
  150. Builds a list of buckets with increasing powers of 10 multiplied by
  151. mantissa values (1, 2, 5) until the value exceeds the specified maximum.
  152. Example:
  153. >>> build_1_2_5_buckets(100)
  154. [1, 2, 5, 10, 20, 50, 100]
  155. """
  156. mantissa_lst = [1, 2, 5]
  157. exponent = 0
  158. buckets: List[int] = []
  159. while True:
  160. for m in mantissa_lst:
  161. value = m * 10**exponent
  162. if value <= max_value:
  163. buckets.append(value)
  164. else:
  165. return buckets
  166. exponent += 1
  167. @dataclass
  168. class Stats:
  169. """Created by LLMEngine for use by StatLogger."""
  170. now: float
  171. # System stats (should have _sys suffix)
  172. # Scheduler State
  173. num_running_sys: int
  174. num_waiting_sys: int
  175. num_swapped_sys: int
  176. # KV Cache Usage in %
  177. gpu_cache_usage_sys: float
  178. cpu_cache_usage_sys: float
  179. # Iteration stats (should have _iter suffix)
  180. num_prompt_tokens_iter: int
  181. num_generation_tokens_iter: int
  182. time_to_first_tokens_iter: List[float]
  183. time_per_output_tokens_iter: List[float]
  184. num_preemption_iter: int
  185. # Request stats (should have _requests suffix)
  186. # Latency
  187. time_e2e_requests: List[float]
  188. # Metadata
  189. num_prompt_tokens_requests: List[int]
  190. num_generation_tokens_requests: List[int]
  191. best_of_requests: List[int]
  192. n_requests: List[int]
  193. finished_reason_requests: List[str]
  194. spec_decode_metrics: Optional["SpecDecodeWorkerMetrics"] = None
  195. class SupportsMetricsInfo(Protocol):
  196. def metrics_info(self) -> Dict[str, str]:
  197. ...
  198. def local_interval_elapsed(now: float, last_log: float,
  199. local_interval: float) -> bool:
  200. elapsed_time = now - last_log
  201. return elapsed_time > local_interval
  202. def get_throughput(tracked_stats: List[int], now: float,
  203. last_log: float) -> float:
  204. return float(np.sum(tracked_stats) / (now - last_log))
  205. class StatLoggerBase(ABC):
  206. """Base class for StatLogger."""
  207. def __init__(self, local_interval: float) -> None:
  208. # Tracked stats over current local logging interval.
  209. self.num_prompt_tokens: List[int] = []
  210. self.num_generation_tokens: List[int] = []
  211. self.last_local_log = time.time()
  212. self.local_interval = local_interval
  213. @abstractmethod
  214. def info(self, type: str, obj: SupportsMetricsInfo) -> None:
  215. raise NotImplementedError
  216. @abstractmethod
  217. def log(self, stats: Stats) -> None:
  218. raise NotImplementedError
  219. class LoggingStatLogger(StatLoggerBase):
  220. """LoggingStatLogger is used in LLMEngine to log to Stdout."""
  221. def info(self, type: str, obj: SupportsMetricsInfo) -> None:
  222. raise NotImplementedError
  223. def log(self, stats: Stats) -> None:
  224. """Called by LLMEngine.
  225. Logs to Stdout every self.local_interval seconds."""
  226. # Save tracked stats for token counters.
  227. self.num_prompt_tokens.append(stats.num_prompt_tokens_iter)
  228. self.num_generation_tokens.append(stats.num_generation_tokens_iter)
  229. # Log locally every local_interval seconds.
  230. if local_interval_elapsed(stats.now, self.last_local_log,
  231. self.local_interval):
  232. # Compute summary metrics for tracked stats (and log them
  233. # to promethus if applicable).
  234. prompt_throughput = get_throughput(self.num_prompt_tokens,
  235. now=stats.now,
  236. last_log=self.last_local_log)
  237. generation_throughput = get_throughput(
  238. self.num_generation_tokens,
  239. now=stats.now,
  240. last_log=self.last_local_log)
  241. # Log to stdout.
  242. logger.info(
  243. "Avg prompt throughput: "
  244. f"{prompt_throughput:.1f} tokens/s, "
  245. "Avg generation throughput: "
  246. f"{generation_throughput:.1f} tokens/s, "
  247. f"Running: {stats.num_running_sys} reqs, "
  248. f"Swapped: {stats.num_swapped_sys} reqs, "
  249. f"Pending: {stats.num_waiting_sys} reqs, "
  250. f"GPU KV cache usage: {stats.gpu_cache_usage_sys * 100:.1f}%, "
  251. f"CPU KV cache usage: {stats.cpu_cache_usage_sys * 100:.1f}%.")
  252. # Reset tracked stats for next interval.
  253. self.num_prompt_tokens = []
  254. self.num_generation_tokens = []
  255. self.last_local_log = stats.now
  256. if stats.spec_decode_metrics is not None:
  257. logger.info(
  258. self._format_spec_decode_metrics_str(
  259. stats.spec_decode_metrics))
  260. def _format_spec_decode_metrics_str(
  261. self, metrics: "SpecDecodeWorkerMetrics") -> str:
  262. return ("Speculative metrics: "
  263. f"Draft acceptance rate: {metrics.draft_acceptance_rate:.3f}, "
  264. f"System efficiency: {metrics.system_efficiency:.3f}, "
  265. f"Number of speculative tokens: {metrics.num_spec_tokens}, "
  266. f"Number of accepted tokens: {metrics.accepted_tokens}, "
  267. f"Number of draft tokens tokens: {metrics.draft_tokens}, "
  268. f"Number of emitted tokens tokens: {metrics.emitted_tokens}.")
  269. class PrometheusStatLogger(StatLoggerBase):
  270. """PrometheusStatLogger is used LLMEngine to log to Promethus."""
  271. _metrics_cls = Metrics
  272. def __init__(self, local_interval: float, labels: Dict[str, str],
  273. max_model_len: int) -> None:
  274. super().__init__(local_interval)
  275. # Prometheus metrics
  276. self.labels = labels
  277. self.metrics = self._metrics_cls(labelnames=list(labels.keys()),
  278. max_model_len=max_model_len)
  279. def info(self, type: str, obj: SupportsMetricsInfo) -> None:
  280. if type == "cache_config":
  281. self.metrics.info_cache_config.info(obj.metrics_info())
  282. def _log_gauge(self, gauge, data: Union[int, float]) -> None:
  283. # Convenience function for logging to gauge.
  284. gauge.labels(**self.labels).set(data)
  285. def _log_counter(self, counter, data: Union[int, float]) -> None:
  286. # Convenience function for logging to counter.
  287. counter.labels(**self.labels).inc(data)
  288. def _log_counter_labels(self, counter, data: CollectionsCounter,
  289. label_key: str) -> None:
  290. # Convenience function for collection counter of labels.
  291. for label, count in data.items():
  292. counter.labels(**{**self.labels, label_key: label}).inc(count)
  293. def _log_histogram(self, histogram, data: Union[List[int],
  294. List[float]]) -> None:
  295. # Convenience function for logging list to histogram.
  296. for datum in data:
  297. histogram.labels(**self.labels).observe(datum)
  298. def _log_prometheus(self, stats: Stats) -> None:
  299. # System state data
  300. self._log_gauge(self.metrics.gauge_scheduler_running,
  301. stats.num_running_sys)
  302. self._log_gauge(self.metrics.gauge_scheduler_swapped,
  303. stats.num_swapped_sys)
  304. self._log_gauge(self.metrics.gauge_scheduler_waiting,
  305. stats.num_waiting_sys)
  306. self._log_gauge(self.metrics.gauge_gpu_cache_usage,
  307. stats.gpu_cache_usage_sys)
  308. self._log_gauge(self.metrics.gauge_cpu_cache_usage,
  309. stats.cpu_cache_usage_sys)
  310. # Iteration level data
  311. self._log_counter(self.metrics.counter_num_preemption,
  312. stats.num_preemption_iter)
  313. self._log_counter(self.metrics.counter_prompt_tokens,
  314. stats.num_prompt_tokens_iter)
  315. self._log_counter(self.metrics.counter_generation_tokens,
  316. stats.num_generation_tokens_iter)
  317. self._log_histogram(self.metrics.histogram_time_to_first_token,
  318. stats.time_to_first_tokens_iter)
  319. self._log_histogram(self.metrics.histogram_time_per_output_token,
  320. stats.time_per_output_tokens_iter)
  321. # Request level data
  322. # Latency
  323. self._log_histogram(self.metrics.histogram_e2e_time_request,
  324. stats.time_e2e_requests)
  325. # Metadata
  326. finished_reason_counter = CollectionsCounter(
  327. stats.finished_reason_requests)
  328. self._log_counter_labels(self.metrics.counter_request_success,
  329. finished_reason_counter,
  330. Metrics.labelname_finish_reason)
  331. self._log_histogram(self.metrics.histogram_num_prompt_tokens_request,
  332. stats.num_prompt_tokens_requests)
  333. self._log_histogram(
  334. self.metrics.histogram_num_generation_tokens_request,
  335. stats.num_generation_tokens_requests)
  336. self._log_histogram(self.metrics.histogram_n_request, stats.n_requests)
  337. self._log_histogram(self.metrics.histogram_best_of_request,
  338. stats.best_of_requests)
  339. def _log_prometheus_interval(self, prompt_throughput: float,
  340. generation_throughput: float) -> None:
  341. # Logs metrics to prometheus that are computed every logging_interval.
  342. # Support legacy gauge metrics that make throughput calculations on
  343. # the Aphrodite side. Moving forward, we should use counters like
  344. # counter_prompt_tokens, counter_generation_tokens
  345. # Which log raw data and calculate summaries using rate() on the
  346. # grafana/prometheus side.
  347. self.metrics.gauge_avg_prompt_throughput.labels(
  348. **self.labels).set(prompt_throughput)
  349. self.metrics.gauge_avg_generation_throughput.labels(
  350. **self.labels).set(generation_throughput)
  351. def log(self, stats: Stats):
  352. """Logs to prometheus and tracked stats every iteration."""
  353. # Log to prometheus.
  354. self._log_prometheus(stats)
  355. # Save tracked stats for token counters.
  356. self.num_prompt_tokens.append(stats.num_prompt_tokens_iter)
  357. self.num_generation_tokens.append(stats.num_generation_tokens_iter)
  358. # Log locally every local_interval seconds.
  359. if local_interval_elapsed(stats.now, self.last_local_log,
  360. self.local_interval):
  361. # Compute summary metrics for tracked stats (and log them
  362. # to promethus if applicable).
  363. prompt_throughput = get_throughput(self.num_prompt_tokens,
  364. now=stats.now,
  365. last_log=self.last_local_log)
  366. generation_throughput = get_throughput(
  367. self.num_generation_tokens,
  368. now=stats.now,
  369. last_log=self.last_local_log)
  370. self._log_prometheus_interval(
  371. prompt_throughput=prompt_throughput,
  372. generation_throughput=generation_throughput)
  373. # Reset tracked stats for next interval.
  374. self.num_prompt_tokens = []
  375. self.num_generation_tokens = []
  376. self.last_local_log = stats.now
  377. class RayPrometheusStatLogger(PrometheusStatLogger):
  378. """RayPrometheusStatLogger uses Ray metrics instead."""
  379. _metrics_cls = RayMetrics