metrics.py 22 KB

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