metrics.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. import functools
  2. import logging
  3. import time
  4. from collections.abc import Callable
  5. from enum import Enum
  6. from typing import Any
  7. from .import_utils import is_opentelemetry_available
  8. class RequestStatus(Enum):
  9. """Status of a generation request through its lifecycle."""
  10. PENDING = "pending"
  11. PREFILLING = "prefilling"
  12. PREFILLING_SPLIT = "prefilling_split"
  13. SPLIT_PENDING_REMAINDER = "split_pending_remainder"
  14. DECODING = "decoding"
  15. FINISHED = "finished"
  16. FAILED = "failed"
  17. if is_opentelemetry_available():
  18. from opentelemetry import metrics
  19. from opentelemetry.trace import Status, StatusCode, get_tracer
  20. _has_opentelemetry = True
  21. else:
  22. _has_opentelemetry = False
  23. def attach_tracer(tracer_name_template=None):
  24. """
  25. Decorator that attaches a tracer to a class.
  26. This decorator should be applied to classes that need OpenTelemetry tracing.
  27. It adds a tracer attribute to the class instance that can be used by the traced decorator.
  28. Args:
  29. tracer_name_template: Optional template string for the tracer name.
  30. If provided, it should contain {module} which will be replaced with the class's full module path
  31. and {class_name} for the class name.
  32. If None, a default naming scheme will be used where:
  33. - If the module already starts with "transformers.", it will use that directly
  34. - Otherwise, it will prepend "transformers." to the module name
  35. Returns:
  36. Class decorator function
  37. """
  38. if not _has_opentelemetry:
  39. return lambda cls: cls
  40. def decorator(cls):
  41. original_init = cls.__init__
  42. @functools.wraps(original_init)
  43. def init_with_tracer(self, *args, **kwargs):
  44. original_init(self, *args, **kwargs)
  45. module_name = cls.__module__
  46. class_name = cls.__qualname__
  47. if tracer_name_template is None:
  48. if module_name.startswith("transformers."):
  49. tracer_name = f"{module_name}.{class_name}"
  50. else:
  51. tracer_name = f"transformers.{module_name}.{class_name}"
  52. else:
  53. tracer_name = tracer_name_template.format(module=module_name, class_name=class_name)
  54. self.tracer = get_tracer(tracer_name)
  55. cls.__init__ = init_with_tracer
  56. return cls
  57. return decorator
  58. def traced(
  59. func=None,
  60. *,
  61. span_name=None,
  62. standalone=False,
  63. additional_attributes: list[tuple[str, str, Any | Callable[[Any], Any]]] | None = None,
  64. ):
  65. """
  66. Decorator to trace function calls with OpenTelemetry.
  67. Can be used as @traced or @traced(span_name="custom_name")
  68. Args:
  69. func: The function to trace
  70. span_name: Optional custom name for the span (defaults to function name)
  71. standalone: If True, creates a parentless span
  72. additional_attributes: Optional list of additional attributes to set on the span.
  73. Each item is a tuple of (instance_attribute_name, span_attribute_key, value_or_transform_function)
  74. where:
  75. - instance_attribute_name: Name of the attribute to get from the class instance
  76. - span_attribute_key: Key to use when setting the attribute on the span
  77. - value_or_transform_function: Either a raw value to use directly, or a function to transform
  78. the attribute value before setting it on the span
  79. Returns:
  80. Decorated function with tracing
  81. """
  82. def decorator(func):
  83. if not _has_opentelemetry:
  84. return func
  85. @functools.wraps(func)
  86. def wrapper(*args, **kwargs):
  87. instance = args[0] if args and (hasattr(func, "__self__") and func.__self__ is not None) else None
  88. is_method = instance is not None
  89. if is_method and hasattr(instance, "tracer"):
  90. tracer = instance.tracer
  91. else:
  92. tracer = get_tracer(f"transformers.{func.__module__}.{func.__name__}")
  93. name = span_name or func.__name__
  94. span_fn = tracer.start_span if standalone else tracer.start_as_current_span
  95. with span_fn(name) as span:
  96. span.set_attribute("function.name", func.__name__)
  97. span.set_attribute("function.module", func.__module__)
  98. span.set_attribute("function.is_method", is_method)
  99. if args:
  100. for i, arg in enumerate(args):
  101. if isinstance(arg, (str, int, float, bool)) or arg is None:
  102. span.set_attribute(f"args.{i}", str(arg))
  103. else:
  104. span.set_attribute(f"args.{i}", str(type(arg)))
  105. if kwargs:
  106. for key, value in kwargs.items():
  107. if isinstance(value, (str, int, float, bool)) or value is None:
  108. span.set_attribute(f"kwargs.{key}", str(value))
  109. else:
  110. span.set_attribute(f"kwargs.{key}", str(type(value)))
  111. if additional_attributes and is_method:
  112. for attr_config in additional_attributes:
  113. instance_attribute_name, span_attribute_key, value_or_transform_function = attr_config
  114. if hasattr(instance, instance_attribute_name):
  115. attribute_value = getattr(instance, instance_attribute_name)
  116. if callable(value_or_transform_function):
  117. transformed_value = value_or_transform_function(attribute_value)
  118. else:
  119. transformed_value = value_or_transform_function
  120. span.set_attribute(span_attribute_key, transformed_value)
  121. try:
  122. result = func(*args, **kwargs)
  123. return result
  124. except Exception as e:
  125. span.set_status(Status(StatusCode.ERROR))
  126. span.record_exception(e)
  127. raise
  128. return wrapper
  129. if func is None:
  130. return decorator
  131. return decorator(func)
  132. logger = logging.getLogger(__name__)
  133. @attach_tracer()
  134. class ContinuousBatchProcessorMetrics:
  135. """Metrics collection for ContinuousBatchProcessor."""
  136. def __init__(self, max_batch_tokens: int):
  137. """Initialize metrics for continuous batch processor.
  138. Args:
  139. max_batch_tokens: Maximum number of tokens in a batch
  140. """
  141. self.max_batch_tokens = max_batch_tokens
  142. self._setup_metrics()
  143. def _setup_metrics(self):
  144. """Initialize OpenTelemetry metrics and tracing if the library is available."""
  145. if not _has_opentelemetry:
  146. logger.info(
  147. "OpenTelemetry is not installed. Metrics and tracing will not be recorded."
  148. "You can install it with `pip install opentelemetry-api>=1.30.0`"
  149. )
  150. return
  151. self.meter = metrics.get_meter("transformers.generation.continuous_batch_processor")
  152. # Define appropriate buckets for TTFT (typically ranges from ~50ms to several seconds)
  153. ttft_buckets = [10, 25, 50, 75, 100, 150, 200, 300, 500, 750, 1000, 2000, 5000, 10000]
  154. self.ttft_histogram = self.meter.create_histogram(
  155. name="ttft_milliseconds",
  156. description="Time to first token in milliseconds",
  157. unit="ms",
  158. explicit_bucket_boundaries_advisory=ttft_buckets,
  159. )
  160. self.active_requests_gauge = self.meter.create_gauge(
  161. name="active_requests_count",
  162. description="Number of active requests currently being processed",
  163. unit="requests",
  164. )
  165. self.waiting_requests_gauge = self.meter.create_gauge(
  166. name="waiting_requests_count",
  167. description="Number of requests waiting to be processed",
  168. unit="requests",
  169. )
  170. # Define appropriate buckets for request latency (similar to TTFT but with higher upper bounds)
  171. latency_buckets = [50, 100, 250, 500, 1000, 2000, 5000, 10000, 20000, 30000, 60000]
  172. self.request_latency_histogram = self.meter.create_histogram(
  173. name="request_latency_milliseconds",
  174. description="End-to-end latency for completed requests in milliseconds",
  175. unit="ms",
  176. explicit_bucket_boundaries_advisory=latency_buckets,
  177. )
  178. self.decode_prefill_ratio_gauge = self.meter.create_gauge(
  179. name="decode_prefill_ratio",
  180. description="Ratio of decode tokens to prefill tokens in a batch",
  181. unit="ratio",
  182. )
  183. self.prefill_tokens_counter = self.meter.create_counter(
  184. name="prefill_tokens_processed",
  185. description="Number of prefill tokens processed",
  186. unit="tokens",
  187. )
  188. self.decode_tokens_counter = self.meter.create_counter(
  189. name="decode_tokens_processed",
  190. description="Number of decode tokens processed",
  191. unit="tokens",
  192. )
  193. # Define appropriate buckets for batch fill percentage (0-100%)
  194. batch_fill_buckets = [5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 98, 100]
  195. self.batch_fill_percentage_histogram = self.meter.create_histogram(
  196. name="batch_fill_percentage",
  197. description="Percentage of max_batch_tokens utilized in each batch",
  198. unit="percent",
  199. explicit_bucket_boundaries_advisory=batch_fill_buckets,
  200. )
  201. self.kv_cache_free_memory_gauge = self.meter.create_gauge(
  202. name="kv_cache_free_memory_bytes",
  203. description="Free memory of the PagedAttentionCache in bytes",
  204. unit="bytes",
  205. )
  206. self.kv_cache_memory_gauge = self.meter.create_gauge(
  207. name="kv_cache_memory_bytes",
  208. description="Memory usage of the PagedAttentionCache in bytes",
  209. unit="bytes",
  210. )
  211. @traced
  212. def record_ttft_metric(self, created_time: float, request_id: str) -> None:
  213. """Record Time to First Token (TTFT).
  214. Args:
  215. created_time: The time the request was created
  216. request_id: The ID of the request
  217. """
  218. if not _has_opentelemetry:
  219. return
  220. ttft_ms = (time.time() - created_time) * 1000.0
  221. try:
  222. self.ttft_histogram.record(ttft_ms)
  223. logger.debug(f"Recorded TTFT for request {request_id}: {ttft_ms:.2f}ms")
  224. except Exception as e:
  225. logger.warning(f"Failed to record TTFT metric: {e}")
  226. @traced
  227. def record_batch_metrics(self, requests_in_batch: list) -> None:
  228. """Record metrics about the batch composition including decode/prefill ratio and batch fill percentage.
  229. Args:
  230. requests_in_batch: List of request states in the current batch
  231. """
  232. if not _has_opentelemetry or not requests_in_batch:
  233. return
  234. decode_tokens = 0
  235. prefill_tokens = 0
  236. for request in requests_in_batch:
  237. state = request.state
  238. if state.status == RequestStatus.DECODING:
  239. decode_tokens += 1
  240. elif state.status in [RequestStatus.PREFILLING, RequestStatus.PREFILLING_SPLIT]:
  241. prefill_tokens += len(state.prompt_ids)
  242. total_batch_tokens = decode_tokens + prefill_tokens
  243. try:
  244. if prefill_tokens > 0:
  245. self.prefill_tokens_counter.add(prefill_tokens)
  246. if decode_tokens > 0:
  247. self.decode_tokens_counter.add(decode_tokens)
  248. if prefill_tokens > 0:
  249. ratio = decode_tokens / prefill_tokens
  250. self.decode_prefill_ratio_gauge.set(ratio)
  251. fill_percentage = (total_batch_tokens / self.max_batch_tokens) * 100.0
  252. self.batch_fill_percentage_histogram.record(fill_percentage)
  253. logger.debug(
  254. f"Batch metrics: {decode_tokens} decode tokens, {prefill_tokens} prefill tokens, "
  255. f"batch fill: {fill_percentage:.2f}% ({total_batch_tokens}/{self.max_batch_tokens})"
  256. )
  257. except Exception as e:
  258. logger.warning(f"Failed to record batch metrics: {e}")
  259. @traced
  260. def record_kv_cache_memory_metrics(self, cache) -> None:
  261. """Record memory usage of the PagedAttentionCache without GPU synchronization.
  262. This calculates the theoretical memory usage based on cache configuration
  263. and the number of blocks currently in use.
  264. Args:
  265. cache: The PagedAttentionCache object to measure
  266. """
  267. if not _has_opentelemetry:
  268. return
  269. try:
  270. # Retrieve the memory footprint of the cache
  271. page_size = cache.head_dim * cache.num_key_value_heads
  272. page_mem_in_bytes = page_size * cache.dtype.itemsize
  273. # When a block is allocated, it is for both K and V, so we multiply by 2
  274. # It's also allocated across all cache tensors, so we multiply by the nb of tensors: len(cache.key_cache)
  275. block_mem_in_bytes = 2 * len(cache.key_cache) * cache.block_size * page_mem_in_bytes
  276. # Retrieve the number of used and free blocks
  277. free_blocks = cache.get_num_free_blocks()
  278. used_blocks = cache.num_blocks - free_blocks
  279. # Convert that into used and free memory in bytes
  280. used_memory_bytes = used_blocks * block_mem_in_bytes
  281. free_memory_bytes = free_blocks * block_mem_in_bytes
  282. # Update the telemetry gauges and add a message in the logs
  283. self.kv_cache_memory_gauge.set(used_memory_bytes)
  284. self.kv_cache_free_memory_gauge.set(free_memory_bytes)
  285. logger.debug(
  286. f"KV Cache memory: {used_memory_bytes / (1024 * 1024):.2f}MB, "
  287. f"Used blocks: {used_blocks}/{cache.num_blocks} "
  288. f"({used_blocks / cache.num_blocks * 100:.1f}%)"
  289. )
  290. except Exception as e:
  291. logger.warning(f"Failed to record KV cache memory metrics: {e}")
  292. @traced
  293. def record_queue_metrics(self, active_requests: int, waiting_requests: int) -> None:
  294. """Record metrics about active and waiting requests.
  295. Args:
  296. active_requests: Number of active requests
  297. waiting_requests: Number of waiting requests
  298. """
  299. if not _has_opentelemetry:
  300. return
  301. try:
  302. self.active_requests_gauge.set(active_requests)
  303. self.waiting_requests_gauge.set(waiting_requests)
  304. logger.debug(f"Queue metrics: {active_requests} active requests, {waiting_requests} waiting requests")
  305. except Exception as e:
  306. logger.warning(f"Failed to record queue metrics: {e}")
  307. @traced
  308. def record_request_completion(self, created_time: float, request_id: str) -> None:
  309. """Record metrics about a completed request.
  310. Args:
  311. created_time: The time the request was created
  312. request_id: The ID of the request
  313. """
  314. if not _has_opentelemetry:
  315. return
  316. latency_ms = (time.time() - created_time) * 1000.0
  317. try:
  318. self.request_latency_histogram.record(latency_ms)
  319. logger.debug(f"Recorded request completion for {request_id}: {latency_ms:.2f}ms")
  320. except Exception as e:
  321. logger.warning(f"Failed to record request completion metric: {e}")