metrics.py 15 KB

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