metrics.py 8.6 KB

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