metrics.py 11 KB

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