serving.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. import argparse
  2. import asyncio
  3. import json
  4. import random
  5. import time
  6. from typing import AsyncGenerator, List, Tuple
  7. import aiohttp
  8. import numpy as np
  9. from transformers import PreTrainedTokenizerBase
  10. from aphrodite.transformers_utils.tokenizer import get_tokenizer
  11. # (prompt len, output len, latency)
  12. REQUEST_LATENCY: List[Tuple[int, int, float]] = []
  13. def sample_requests(
  14. dataset_path: str,
  15. num_requests: int,
  16. tokenizer: PreTrainedTokenizerBase,
  17. ) -> List[Tuple[str, int, int]]:
  18. # Load the dataset.
  19. with open(dataset_path) as f:
  20. dataset = json.load(f)
  21. # Filter out the conversations with less than 2 turns.
  22. dataset = [data for data in dataset if len(data["conversations"]) >= 2]
  23. # Only keep the first two turns of each conversation.
  24. dataset = [(data["conversations"][0]["value"],
  25. data["conversations"][1]["value"]) for data in dataset]
  26. # Tokenize the prompts and completions.
  27. prompts = [prompt for prompt, _ in dataset]
  28. prompt_token_ids = tokenizer(prompts).input_ids
  29. completions = [completion for _, completion in dataset]
  30. completion_token_ids = tokenizer(completions).input_ids
  31. tokenized_dataset = []
  32. for i in range(len(dataset)):
  33. output_len = len(completion_token_ids[i])
  34. tokenized_dataset.append((prompts[i], prompt_token_ids[i], output_len))
  35. # Filter out too long sequences.
  36. filtered_dataset: List[Tuple[str, int, int]] = []
  37. for prompt, prompt_token_ids, output_len in tokenized_dataset:
  38. prompt_len = len(prompt_token_ids)
  39. if prompt_len < 4 or output_len < 4:
  40. # Prune too short sequences.
  41. # This is because TGI causes errors when the input or output length
  42. # is too short.
  43. continue
  44. if prompt_len > 1024 or prompt_len + output_len > 2048:
  45. # Prune too long sequences.
  46. continue
  47. filtered_dataset.append((prompt, prompt_len, output_len))
  48. # Sample the requests.
  49. sampled_requests = random.sample(filtered_dataset, num_requests)
  50. return sampled_requests
  51. async def get_request(
  52. input_requests: List[Tuple[str, int, int]],
  53. request_rate: float,
  54. ) -> AsyncGenerator[Tuple[str, int, int], None]:
  55. input_requests = iter(input_requests)
  56. for request in input_requests:
  57. yield request
  58. if request_rate == float("inf"):
  59. # If the request rate is infinity, then we don't need to wait.
  60. continue
  61. # Sample the request interval from the exponential distribution.
  62. interval = np.random.exponential(1.0 / request_rate)
  63. # The next request will be sent after the interval.
  64. await asyncio.sleep(interval)
  65. async def send_request(
  66. backend: str,
  67. api_url: str,
  68. prompt: str,
  69. prompt_len: int,
  70. output_len: int,
  71. best_of: int,
  72. use_beam_search: bool,
  73. ) -> None:
  74. request_start_time = time.perf_counter()
  75. headers = {"User-Agent": "Benchmark Client"}
  76. if backend == "aphrodite":
  77. pload = {
  78. "prompt": prompt,
  79. "n": 1,
  80. "best_of": best_of,
  81. "use_beam_search": use_beam_search,
  82. "temperature": 0.0 if use_beam_search else 1.0,
  83. "top_p": 1.0,
  84. "max_tokens": output_len,
  85. "ignore_eos": True,
  86. "stream": False,
  87. }
  88. elif backend == "tgi":
  89. assert not use_beam_search
  90. params = {
  91. "best_of": best_of,
  92. "max_new_tokens": output_len,
  93. "do_sample": True,
  94. }
  95. pload = {
  96. "inputs": prompt,
  97. "parameters": params,
  98. }
  99. else:
  100. raise ValueError(f"Unknown backend: {backend}")
  101. timeout = aiohttp.ClientTimeout(total=3 * 3600)
  102. async with aiohttp.ClientSession(timeout=timeout) as session:
  103. while True:
  104. async with session.post(api_url, headers=headers,
  105. json=pload) as response:
  106. chunks = []
  107. async for chunk, _ in response.content.iter_chunks():
  108. chunks.append(chunk)
  109. output = b"".join(chunks).decode("utf-8")
  110. output = json.loads(output)
  111. # Re-send the request if it failed.
  112. if "error" not in output:
  113. break
  114. request_end_time = time.perf_counter()
  115. request_latency = request_end_time - request_start_time
  116. REQUEST_LATENCY.append((prompt_len, output_len, request_latency))
  117. async def benchmark(
  118. backend: str,
  119. api_url: str,
  120. input_requests: List[Tuple[str, int, int]],
  121. best_of: int,
  122. use_beam_search: bool,
  123. request_rate: float,
  124. ) -> None:
  125. tasks: List[asyncio.Task] = []
  126. async for request in get_request(input_requests, request_rate):
  127. prompt, prompt_len, output_len = request
  128. task = asyncio.create_task(
  129. send_request(backend, api_url, prompt, prompt_len, output_len,
  130. best_of, use_beam_search))
  131. tasks.append(task)
  132. await asyncio.gather(*tasks)
  133. def main(args: argparse.Namespace): # pylint: disable=redefined-outer-name
  134. print(args)
  135. random.seed(args.seed)
  136. np.random.seed(args.seed)
  137. api_url = f"http://{args.host}:{args.port}/api/v1/generate"
  138. tokenizer = get_tokenizer(args.tokenizer,
  139. trust_remote_code=args.trust_remote_code)
  140. input_requests = sample_requests(args.dataset, args.num_prompts, tokenizer)
  141. benchmark_start_time = time.perf_counter()
  142. asyncio.run(
  143. benchmark(args.backend, api_url, input_requests, args.best_of,
  144. args.use_beam_search, args.request_rate))
  145. benchmark_end_time = time.perf_counter()
  146. benchmark_time = benchmark_end_time - benchmark_start_time
  147. print(f"Total time: {benchmark_time:.2f} s")
  148. print(f"Throughput: {args.num_prompts / benchmark_time:.2f} requests/s")
  149. # Compute the latency statistics.
  150. avg_latency = np.mean([latency for _, _, latency in REQUEST_LATENCY])
  151. print(f"Average latency: {avg_latency:.2f} s")
  152. avg_per_token_latency = np.mean([
  153. latency / (prompt_len + output_len)
  154. for prompt_len, output_len, latency in REQUEST_LATENCY
  155. ])
  156. print(f"Average latency per token: {avg_per_token_latency:.2f} s")
  157. avg_per_output_token_latency = np.mean(
  158. [latency / output_len for _, output_len, latency in REQUEST_LATENCY])
  159. print("Average latency per output token: "
  160. f"{avg_per_output_token_latency:.2f} s")
  161. if __name__ == "__main__":
  162. parser = argparse.ArgumentParser(
  163. description="Benchmark the online serving throughput.")
  164. parser.add_argument("--backend",
  165. type=str,
  166. default="aphrodite",
  167. choices=["aphrodite", "tgi"])
  168. parser.add_argument("--host", type=str, default="localhost")
  169. parser.add_argument("--port", type=int, default=2242)
  170. parser.add_argument("--dataset",
  171. type=str,
  172. required=True,
  173. help="Path to the dataset.")
  174. parser.add_argument("--tokenizer",
  175. type=str,
  176. required=True,
  177. help="Name or path of the tokenizer.")
  178. parser.add_argument("--best-of",
  179. type=int,
  180. default=1,
  181. help="Generates `best_of` sequences per prompt and "
  182. "returns the best one.")
  183. parser.add_argument("--use-beam-search", action="store_true")
  184. parser.add_argument("--num-prompts",
  185. type=int,
  186. default=1000,
  187. help="Number of prompts to process.")
  188. parser.add_argument("--request-rate",
  189. type=float,
  190. default=float("inf"),
  191. help="Number of requests per second. If this is inf, "
  192. "then all the requests are sent at time 0. "
  193. "Otherwise, we use Poisson process to synthesize "
  194. "the request arrival times.")
  195. parser.add_argument("--seed", type=int, default=0)
  196. parser.add_argument("--trust-remote-code",
  197. action="store_true",
  198. help="trust remote code from huggingface")
  199. args = parser.parse_args()
  200. main(args)