metrics.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. from loguru import logger
  2. from prometheus_client import (
  3. Counter,
  4. Gauge,
  5. Histogram,
  6. Info,
  7. REGISTRY,
  8. disable_created_metrics,
  9. )
  10. import time
  11. import numpy as np
  12. from typing import Dict, List
  13. from dataclasses import dataclass
  14. disable_created_metrics()
  15. # The begin-* and end* here are used by the documentation generator
  16. # to extract the metrics definitions.
  17. # begin-metrics-definitions
  18. class Metrics:
  19. def __init__(self, labelnames: List[str]):
  20. # Unregister any existing Aphrodite collectors
  21. for collector in list(REGISTRY._collector_to_names):
  22. if hasattr(collector, "_name") and "aphrodite" in collector._name:
  23. REGISTRY.unregister(collector)
  24. # Config Information
  25. self.info_cache_config = Info(
  26. name="aphrodite:cache_config",
  27. documentation="information of cache_config",
  28. )
  29. # System stats
  30. self.gauge_scheduler_running = Gauge(
  31. name="aphrodite:num_requests_running",
  32. documentation="Number of requests currently running on GPU.",
  33. labelnames=labelnames,
  34. )
  35. self.gauge_scheduler_swapped = Gauge(
  36. name="aphrodite:num_requests_swapped",
  37. documentation="Number of requests swapped to CPU.",
  38. labelnames=labelnames,
  39. )
  40. self.gauge_scheduler_waiting = Gauge(
  41. name="aphrodite:num_requests_waiting",
  42. documentation="Number of requests waiting to be processed.",
  43. labelnames=labelnames,
  44. )
  45. self.gauge_gpu_cache_usage = Gauge(
  46. name="aphrodite:gpu_cache_usage_perc",
  47. documentation="GPU KV-cache usage. 1 means 100 percent usage.",
  48. labelnames=labelnames,
  49. )
  50. self.gauge_cpu_cache_usage = Gauge(
  51. name="aphrodite:cpu_cache_usage_perc",
  52. documentation="CPU KV-cache usage. 1 means 100 percent usage.",
  53. labelnames=labelnames,
  54. )
  55. # Raw stats from last model iteration
  56. self.counter_prompt_tokens = Counter(
  57. name="aphrodite:prompt_tokens_total",
  58. documentation="Number of prefill tokens processed.",
  59. labelnames=labelnames,
  60. )
  61. self.counter_generation_tokens = Counter(
  62. name="aphrodite:generation_tokens_total",
  63. documentation="Number of generation tokens processed.",
  64. labelnames=labelnames,
  65. )
  66. self.histogram_time_to_first_token = Histogram(
  67. name="aphrodite:time_to_first_token_seconds",
  68. documentation="Histogram of time to first token in seconds.",
  69. labelnames=labelnames,
  70. buckets=[
  71. 0.001,
  72. 0.005,
  73. 0.01,
  74. 0.02,
  75. 0.04,
  76. 0.06,
  77. 0.08,
  78. 0.1,
  79. 0.25,
  80. 0.5,
  81. 0.75,
  82. 1.0,
  83. 2.5,
  84. 5.0,
  85. 7.5,
  86. 10.0,
  87. ],
  88. )
  89. self.histogram_time_per_output_token = Histogram(
  90. name="aphrodite:time_per_output_token_seconds",
  91. documentation="Histogram of time per output token in seconds.",
  92. labelnames=labelnames,
  93. buckets=[
  94. 0.01,
  95. 0.025,
  96. 0.05,
  97. 0.075,
  98. 0.1,
  99. 0.15,
  100. 0.2,
  101. 0.3,
  102. 0.4,
  103. 0.5,
  104. 0.75,
  105. 1.0,
  106. 2.5,
  107. ],
  108. )
  109. self.histogram_e2e_request_latency = Histogram(
  110. name="aphrodite:e2e_request_latency_seconds",
  111. documentation="Histogram of end to end request latency in seconds.",
  112. labelnames=labelnames,
  113. buckets=[1.0, 2.5, 5.0, 10.0, 15.0, 20.0, 30.0, 40.0, 50.0, 60.0],
  114. )
  115. # Legacy metrics
  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. self.gauge_avg_generation_throughput = Gauge(
  122. name="aphrodite:avg_generation_throughput_toks_per_s",
  123. documentation="Average generation throughput in tokens/s.",
  124. labelnames=labelnames,
  125. )
  126. # end-metrics-definitions
  127. @dataclass
  128. class Stats:
  129. """Created by AphroditeEngine for use by StatLogger."""
  130. now: float
  131. # System stats.
  132. num_running: int
  133. num_waiting: int
  134. num_swapped: int
  135. gpu_cache_usage: float
  136. cpu_cache_usage: float
  137. # Raw stats from last model iteration.
  138. num_prompt_tokens: int
  139. num_generation_tokens: int
  140. time_to_first_tokens: List[float]
  141. time_per_output_tokens: List[float]
  142. time_e2e_requests: List[float]
  143. class StatLogger:
  144. """StatLogger is used AphroditeEngine to log to Promethus and Stdout."""
  145. def __init__(self, local_interval: float, labels: Dict[str, str]) -> None:
  146. # Metadata for logging locally.
  147. self.last_local_log = time.monotonic()
  148. self.local_interval = local_interval
  149. # Tracked stats over current local logging interval.
  150. self.num_prompt_tokens: List[int] = []
  151. self.num_generation_tokens: List[int] = []
  152. # Prometheus metrics
  153. self.labels = labels
  154. self.metrics = Metrics(labelnames=list(labels.keys()))
  155. def info(self, type: str, obj: object) -> None:
  156. if type == "cache_config":
  157. self.metrics.info_cache_config.info(obj.metrics_info())
  158. def _get_throughput(self, tracked_stats: List[int], now: float) -> float:
  159. return float(np.sum(tracked_stats) / (now - self.last_local_log))
  160. def _local_interval_elapsed(self, now: float) -> bool:
  161. elapsed_time = now - self.last_local_log
  162. return elapsed_time > self.local_interval
  163. def _log_prometheus(self, stats: Stats) -> None:
  164. # Set system stat gauges.
  165. self.metrics.gauge_scheduler_running.labels(**self.labels).set(
  166. stats.num_running)
  167. self.metrics.gauge_scheduler_swapped.labels(**self.labels).set(
  168. stats.num_swapped)
  169. self.metrics.gauge_scheduler_waiting.labels(**self.labels).set(
  170. stats.num_waiting)
  171. self.metrics.gauge_gpu_cache_usage.labels(**self.labels).set(
  172. stats.gpu_cache_usage)
  173. self.metrics.gauge_cpu_cache_usage.labels(**self.labels).set(
  174. stats.cpu_cache_usage)
  175. # Add to token counters.
  176. self.metrics.counter_prompt_tokens.labels(**self.labels).inc(
  177. stats.num_prompt_tokens)
  178. self.metrics.counter_generation_tokens.labels(**self.labels).inc(
  179. stats.num_generation_tokens)
  180. # Observe request level latencies in histograms.
  181. for ttft in stats.time_to_first_tokens:
  182. self.metrics.histogram_time_to_first_token.labels(
  183. **self.labels).observe(ttft)
  184. for tpot in stats.time_per_output_tokens:
  185. self.metrics.histogram_time_per_output_token.labels(
  186. **self.labels).observe(tpot)
  187. for e2e in stats.time_e2e_requests:
  188. self.metrics.histogram_e2e_request_latency.labels(
  189. **self.labels).observe(e2e)
  190. def _log_prometheus_interval(self, prompt_throughput: float,
  191. generation_throughput: float) -> None:
  192. # Logs metrics to prometheus that are computed every logging_interval.
  193. # Support legacy gauge metrics that make throughput calculations on
  194. # the Aphrodite side.
  195. # Moving forward, we should use counters like counter_prompt_tokens,
  196. # counter_generation_tokens
  197. # Which log raw data and calculate summaries using rate() on the
  198. # grafana/prometheus side.
  199. self.metrics.gauge_avg_prompt_throughput.labels(
  200. **self.labels).set(prompt_throughput)
  201. self.metrics.gauge_avg_generation_throughput.labels(
  202. **self.labels).set(generation_throughput)
  203. def log(self, stats: Stats) -> None:
  204. """Called by AphroditeEngine.
  205. Logs to prometheus and tracked stats every iteration.
  206. Logs to Stdout every self.local_interval seconds."""
  207. # Log to prometheus.
  208. self._log_prometheus(stats)
  209. # Save tracked stats for token counters.
  210. self.num_prompt_tokens.append(stats.num_prompt_tokens)
  211. self.num_generation_tokens.append(stats.num_generation_tokens)
  212. # Log locally every local_interval seconds.
  213. if self._local_interval_elapsed(stats.now):
  214. # Compute summary metrics for tracked stats (and log them to
  215. # prometheus if applicable).
  216. prompt_throughput = self._get_throughput(self.num_prompt_tokens,
  217. now=stats.now)
  218. generation_throughput = self._get_throughput(
  219. self.num_generation_tokens, now=stats.now)
  220. self._log_prometheus_interval(
  221. prompt_throughput=prompt_throughput,
  222. generation_throughput=generation_throughput,
  223. )
  224. # Log to stdout.
  225. logger.info(
  226. f"Avg prompt throughput: {prompt_throughput:.1f} tokens/s, "
  227. f"Avg generation throughput: {generation_throughput:.1f} "
  228. "tokens/s, "
  229. f"Running: {stats.num_running} reqs, "
  230. f"Swapped: {stats.num_swapped} reqs, "
  231. f"Pending: {stats.num_waiting} reqs, "
  232. f"GPU KV cache usage: {stats.gpu_cache_usage * 100:.1f}%, "
  233. f"CPU KV cache usage: {stats.cpu_cache_usage * 100:.1f}%")
  234. # Reset tracked stats for next interval.
  235. self.num_prompt_tokens = []
  236. self.num_generation_tokens = []
  237. self.last_local_log = stats.now