metrics.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. # Speculative decoding stats
  119. self.gauge_spec_decode_draft_acceptance_rate = self._base_library.Gauge(
  120. name="aphrodite:spec_decode_draft_acceptance_rate",
  121. documentation="Speulative token acceptance rate.",
  122. labelnames=labelnames)
  123. self.gauge_spec_decode_efficiency = self._base_library.Gauge(
  124. name="aphrodite:spec_decode_efficiency",
  125. documentation="Speculative decoding system efficiency.",
  126. labelnames=labelnames)
  127. self.counter_spec_decode_num_accepted_tokens = (
  128. self._base_library.Counter(
  129. name="aphrodite:spec_decode_num_accepted_tokens_total",
  130. documentation="Number of accepted tokens.",
  131. labelnames=labelnames))
  132. self.counter_spec_decode_num_draft_tokens = self._base_library.Counter(
  133. name="aphrodite:spec_decode_num_draft_tokens_total",
  134. documentation="Number of draft tokens.",
  135. labelnames=labelnames)
  136. self.counter_spec_decode_num_emitted_tokens = (
  137. self._base_library.Counter(
  138. name="aphrodite:spec_decode_num_emitted_tokens_total",
  139. documentation="Number of emitted tokens.",
  140. labelnames=labelnames))
  141. # Deprecated in favor of aphrodite:prompt_tokens_total
  142. self.gauge_avg_prompt_throughput = self._base_library.Gauge(
  143. name="aphrodite:avg_prompt_throughput_toks_per_s",
  144. documentation="Average prefill throughput in tokens/s.",
  145. labelnames=labelnames,
  146. )
  147. # Deprecated in favor of aphrodite:generation_tokens_total
  148. self.gauge_avg_generation_throughput = self._base_library.Gauge(
  149. name="aphrodite:avg_generation_throughput_toks_per_s",
  150. documentation="Average generation throughput in tokens/s.",
  151. labelnames=labelnames,
  152. )
  153. def _unregister_aphrodite_metrics(self) -> None:
  154. for collector in list(self._base_library.REGISTRY._collector_to_names):
  155. if hasattr(collector, "_name") and "aphrodite" in collector._name:
  156. self._base_library.REGISTRY.unregister(collector)
  157. class RayMetrics(Metrics):
  158. """
  159. RayMetrics is used by RayPrometheusStatLogger to log to Ray metrics.
  160. Provides the same metrics as Metrics but uses Ray's util.metrics library.
  161. """
  162. _base_library = ray_metrics
  163. def __init__(self, labelnames: List[str], max_model_len: int):
  164. if ray_metrics is None:
  165. raise ImportError("RayMetrics requires Ray to be installed.")
  166. super().__init__(labelnames, max_model_len)
  167. def _unregister_aphrodite_metrics(self) -> None:
  168. # No-op on purpose
  169. pass
  170. # end-metrics-definitions
  171. def build_1_2_5_buckets(max_value: int) -> List[int]:
  172. """
  173. Builds a list of buckets with increasing powers of 10 multiplied by
  174. mantissa values (1, 2, 5) until the value exceeds the specified maximum.
  175. Example:
  176. >>> build_1_2_5_buckets(100)
  177. [1, 2, 5, 10, 20, 50, 100]
  178. """
  179. mantissa_lst = [1, 2, 5]
  180. exponent = 0
  181. buckets: List[int] = []
  182. while True:
  183. for m in mantissa_lst:
  184. value = m * 10**exponent
  185. if value <= max_value:
  186. buckets.append(value)
  187. else:
  188. return buckets
  189. exponent += 1
  190. @dataclass
  191. class Stats:
  192. """Created by LLMEngine for use by StatLogger."""
  193. now: float
  194. # System stats (should have _sys suffix)
  195. # Scheduler State
  196. num_running_sys: int
  197. num_waiting_sys: int
  198. num_swapped_sys: int
  199. # KV Cache Usage in %
  200. gpu_cache_usage_sys: float
  201. cpu_cache_usage_sys: float
  202. # Iteration stats (should have _iter suffix)
  203. num_prompt_tokens_iter: int
  204. num_generation_tokens_iter: int
  205. time_to_first_tokens_iter: List[float]
  206. time_per_output_tokens_iter: List[float]
  207. num_preemption_iter: int
  208. # Request stats (should have _requests suffix)
  209. # Latency
  210. time_e2e_requests: List[float]
  211. # Metadata
  212. num_prompt_tokens_requests: List[int]
  213. num_generation_tokens_requests: List[int]
  214. best_of_requests: List[int]
  215. n_requests: List[int]
  216. finished_reason_requests: List[str]
  217. spec_decode_metrics: Optional["SpecDecodeWorkerMetrics"] = None
  218. class SupportsMetricsInfo(Protocol):
  219. def metrics_info(self) -> Dict[str, str]:
  220. ...
  221. def local_interval_elapsed(now: float, last_log: float,
  222. local_interval: float) -> bool:
  223. elapsed_time = now - last_log
  224. return elapsed_time > local_interval
  225. def get_throughput(tracked_stats: List[int], now: float,
  226. last_log: float) -> float:
  227. return float(np.sum(tracked_stats) / (now - last_log))
  228. class StatLoggerBase(ABC):
  229. """Base class for StatLogger."""
  230. def __init__(self, local_interval: float) -> None:
  231. # Tracked stats over current local logging interval.
  232. self.num_prompt_tokens: List[int] = []
  233. self.num_generation_tokens: List[int] = []
  234. self.last_local_log = time.time()
  235. self.local_interval = local_interval
  236. @abstractmethod
  237. def info(self, type: str, obj: SupportsMetricsInfo) -> None:
  238. raise NotImplementedError
  239. @abstractmethod
  240. def log(self, stats: Stats) -> None:
  241. raise NotImplementedError
  242. class LoggingStatLogger(StatLoggerBase):
  243. """LoggingStatLogger is used in LLMEngine to log to Stdout."""
  244. def info(self, type: str, obj: SupportsMetricsInfo) -> None:
  245. raise NotImplementedError
  246. def log(self, stats: Stats) -> None:
  247. """Called by LLMEngine.
  248. Logs to Stdout every self.local_interval seconds."""
  249. # Save tracked stats for token counters.
  250. self.num_prompt_tokens.append(stats.num_prompt_tokens_iter)
  251. self.num_generation_tokens.append(stats.num_generation_tokens_iter)
  252. # Log locally every local_interval seconds.
  253. if local_interval_elapsed(stats.now, self.last_local_log,
  254. self.local_interval):
  255. # Compute summary metrics for tracked stats (and log them
  256. # to promethus if applicable).
  257. prompt_throughput = get_throughput(self.num_prompt_tokens,
  258. now=stats.now,
  259. last_log=self.last_local_log)
  260. generation_throughput = get_throughput(
  261. self.num_generation_tokens,
  262. now=stats.now,
  263. last_log=self.last_local_log)
  264. # Log to stdout.
  265. logger.info(
  266. "Avg prompt throughput: "
  267. f"{prompt_throughput:.1f} tokens/s, "
  268. "Avg generation throughput: "
  269. f"{generation_throughput:.1f} tokens/s, "
  270. f"Running: {stats.num_running_sys} reqs, "
  271. f"Swapped: {stats.num_swapped_sys} reqs, "
  272. f"Pending: {stats.num_waiting_sys} reqs, "
  273. f"GPU KV cache usage: {stats.gpu_cache_usage_sys * 100:.1f}%, "
  274. f"CPU KV cache usage: {stats.cpu_cache_usage_sys * 100:.1f}%.")
  275. # Reset tracked stats for next interval.
  276. self.num_prompt_tokens = []
  277. self.num_generation_tokens = []
  278. self.last_local_log = stats.now
  279. if stats.spec_decode_metrics is not None:
  280. logger.info(
  281. self._format_spec_decode_metrics_str(
  282. stats.spec_decode_metrics))
  283. def _format_spec_decode_metrics_str(
  284. self, metrics: "SpecDecodeWorkerMetrics") -> str:
  285. return ("Speculative metrics: "
  286. f"Draft acceptance rate: {metrics.draft_acceptance_rate:.3f}, "
  287. f"System efficiency: {metrics.system_efficiency:.3f}, "
  288. f"Number of speculative tokens: {metrics.num_spec_tokens}, "
  289. f"Number of accepted tokens: {metrics.accepted_tokens}, "
  290. f"Number of draft tokens: {metrics.draft_tokens}, "
  291. f"Number of emitted tokens: {metrics.emitted_tokens}.")
  292. class PrometheusStatLogger(StatLoggerBase):
  293. """PrometheusStatLogger is used LLMEngine to log to Promethus."""
  294. _metrics_cls = Metrics
  295. def __init__(self, local_interval: float, labels: Dict[str, str],
  296. max_model_len: int) -> None:
  297. super().__init__(local_interval)
  298. # Prometheus metrics
  299. self.labels = labels
  300. self.metrics = self._metrics_cls(labelnames=list(labels.keys()),
  301. max_model_len=max_model_len)
  302. def info(self, type: str, obj: SupportsMetricsInfo) -> None:
  303. if type == "cache_config":
  304. self.metrics.info_cache_config.info(obj.metrics_info())
  305. def _log_gauge(self, gauge, data: Union[int, float]) -> None:
  306. # Convenience function for logging to gauge.
  307. gauge.labels(**self.labels).set(data)
  308. def _log_counter(self, counter, data: Union[int, float]) -> None:
  309. # Convenience function for logging to counter.
  310. counter.labels(**self.labels).inc(data)
  311. def _log_counter_labels(self, counter, data: CollectionsCounter,
  312. label_key: str) -> None:
  313. # Convenience function for collection counter of labels.
  314. for label, count in data.items():
  315. counter.labels(**{**self.labels, label_key: label}).inc(count)
  316. def _log_histogram(self, histogram, data: Union[List[int],
  317. List[float]]) -> None:
  318. # Convenience function for logging list to histogram.
  319. for datum in data:
  320. histogram.labels(**self.labels).observe(datum)
  321. def _log_prometheus(self, stats: Stats) -> None:
  322. # System state data
  323. self._log_gauge(self.metrics.gauge_scheduler_running,
  324. stats.num_running_sys)
  325. self._log_gauge(self.metrics.gauge_scheduler_swapped,
  326. stats.num_swapped_sys)
  327. self._log_gauge(self.metrics.gauge_scheduler_waiting,
  328. stats.num_waiting_sys)
  329. self._log_gauge(self.metrics.gauge_gpu_cache_usage,
  330. stats.gpu_cache_usage_sys)
  331. self._log_gauge(self.metrics.gauge_cpu_cache_usage,
  332. stats.cpu_cache_usage_sys)
  333. # Iteration level data
  334. self._log_counter(self.metrics.counter_num_preemption,
  335. stats.num_preemption_iter)
  336. self._log_counter(self.metrics.counter_prompt_tokens,
  337. stats.num_prompt_tokens_iter)
  338. self._log_counter(self.metrics.counter_generation_tokens,
  339. stats.num_generation_tokens_iter)
  340. self._log_histogram(self.metrics.histogram_time_to_first_token,
  341. stats.time_to_first_tokens_iter)
  342. self._log_histogram(self.metrics.histogram_time_per_output_token,
  343. stats.time_per_output_tokens_iter)
  344. # Request level data
  345. # Latency
  346. self._log_histogram(self.metrics.histogram_e2e_time_request,
  347. stats.time_e2e_requests)
  348. # Metadata
  349. finished_reason_counter = CollectionsCounter(
  350. stats.finished_reason_requests)
  351. self._log_counter_labels(self.metrics.counter_request_success,
  352. finished_reason_counter,
  353. Metrics.labelname_finish_reason)
  354. self._log_histogram(self.metrics.histogram_num_prompt_tokens_request,
  355. stats.num_prompt_tokens_requests)
  356. self._log_histogram(
  357. self.metrics.histogram_num_generation_tokens_request,
  358. stats.num_generation_tokens_requests)
  359. self._log_histogram(self.metrics.histogram_n_request, stats.n_requests)
  360. self._log_histogram(self.metrics.histogram_best_of_request,
  361. stats.best_of_requests)
  362. def _log_prometheus_interval(self, prompt_throughput: float,
  363. generation_throughput: float) -> None:
  364. # Logs metrics to prometheus that are computed every logging_interval.
  365. # Support legacy gauge metrics that make throughput calculations on
  366. # the Aphrodite side. Moving forward, we should use counters like
  367. # counter_prompt_tokens, counter_generation_tokens
  368. # Which log raw data and calculate summaries using rate() on the
  369. # grafana/prometheus side.
  370. self.metrics.gauge_avg_prompt_throughput.labels(
  371. **self.labels).set(prompt_throughput)
  372. self.metrics.gauge_avg_generation_throughput.labels(
  373. **self.labels).set(generation_throughput)
  374. def log(self, stats: Stats):
  375. """Logs to prometheus and tracked stats every iteration."""
  376. # Log to prometheus.
  377. self._log_prometheus(stats)
  378. # Save tracked stats for token counters.
  379. self.num_prompt_tokens.append(stats.num_prompt_tokens_iter)
  380. self.num_generation_tokens.append(stats.num_generation_tokens_iter)
  381. # Log locally every local_interval seconds.
  382. if local_interval_elapsed(stats.now, self.last_local_log,
  383. self.local_interval):
  384. # Compute summary metrics for tracked stats (and log them
  385. # to promethus if applicable).
  386. prompt_throughput = get_throughput(self.num_prompt_tokens,
  387. now=stats.now,
  388. last_log=self.last_local_log)
  389. generation_throughput = get_throughput(
  390. self.num_generation_tokens,
  391. now=stats.now,
  392. last_log=self.last_local_log)
  393. self._log_prometheus_interval(
  394. prompt_throughput=prompt_throughput,
  395. generation_throughput=generation_throughput)
  396. # Reset tracked stats for next interval.
  397. self.num_prompt_tokens = []
  398. self.num_generation_tokens = []
  399. self.last_local_log = stats.now
  400. if stats.spec_decode_metrics is not None:
  401. self._log_gauge(
  402. self.metrics.gauge_spec_decode_draft_acceptance_rate,
  403. stats.spec_decode_metrics.draft_acceptance_rate)
  404. self._log_gauge(self.metrics.gauge_spec_decode_efficiency,
  405. stats.spec_decode_metrics.system_efficiency)
  406. self._log_counter(
  407. self.metrics.counter_spec_decode_num_accepted_tokens,
  408. stats.spec_decode_metrics.accepted_tokens)
  409. self._log_counter(
  410. self.metrics.counter_spec_decode_num_draft_tokens,
  411. stats.spec_decode_metrics.draft_tokens)
  412. self._log_counter(
  413. self.metrics.counter_spec_decode_num_emitted_tokens,
  414. stats.spec_decode_metrics.emitted_tokens)
  415. class RayPrometheusStatLogger(PrometheusStatLogger):
  416. """RayPrometheusStatLogger uses Ray metrics instead."""
  417. _metrics_cls = RayMetrics