chat_vllm_benchmark.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
  3. import csv
  4. import json
  5. import time
  6. import random
  7. import threading
  8. import numpy as np
  9. import requests
  10. import transformers
  11. import torch
  12. # Imports for Azure content safety
  13. from azure.ai.contentsafety import ContentSafetyClient
  14. from azure.core.credentials import AzureKeyCredential
  15. from azure.core.exceptions import HttpResponseError
  16. from azure.ai.contentsafety.models import AnalyzeTextOptions
  17. from concurrent.futures import ThreadPoolExecutor, as_completed
  18. from typing import Dict, Tuple, List
  19. with open('input.jsonl') as input:
  20. prompt_data = json.load(input)
  21. # Prompt data stored in json file. Choose from number of tokens - 5, 25, 50, 100, 500, 1k, 2k.
  22. # You can also configure and add your own prompt in input.jsonl
  23. PROMPT = prompt_data["1k"]
  24. with open('parameters.json') as parameters:
  25. params = json.load(parameters)
  26. MAX_NEW_TOKENS = params["MAX_NEW_TOKENS"]
  27. CONCURRENT_LEVELS = params["CONCURRENT_LEVELS"]
  28. # Replace with your own deployment
  29. MODEL_PATH = params["MODEL_PATH"]
  30. MODEL_HEADERS = params["MODEL_HEADERS"]
  31. SAFE_CHECK = params["SAFE_CHECK"]
  32. # Threshold for tokens per second below which we deem the query to be slow
  33. THRESHOLD_TPS = params["THRESHOLD_TPS"]
  34. TEMPERATURE = params["TEMPERATURE"]
  35. TOP_P = params["TOP_P"]
  36. # Add your model endpoints here, specify the port number. You can acquire the endpoint when creating a on-prem server like vLLM.
  37. # Group of model endpoints - Send balanced requests to each endpoint for batch maximization.
  38. MODEL_ENDPOINTS = params["MODEL_ENDPOINTS"]
  39. # Get number of GPUs on this instance
  40. if torch.cuda.is_available():
  41. NUM_GPU = torch.cuda.device_count()
  42. else:
  43. print("No available GPUs")
  44. # This tokenizer is downloaded from HuggingFace based on the model path you set. Note Llama 3 use a different tokenizer compare to Llama 2
  45. tokenizer = transformers.AutoTokenizer.from_pretrained(MODEL_PATH)
  46. num_token_input_prompt = len(tokenizer.encode(PROMPT))
  47. print(f"Number of token for input prompt: {num_token_input_prompt}")
  48. # Azure content safety analysis
  49. def analyze_prompt(input):
  50. start_time = time.time()
  51. # Obtain credentials
  52. key = "" #Add your AZURE_CONTENT_SAFETY_KEY
  53. endpoint = "" #Add your AZURE_CONTENT_SAFETY_ENDPOINT
  54. # Create a content safety client
  55. client = ContentSafetyClient(endpoint, AzureKeyCredential(key))
  56. # Create request
  57. request = AnalyzeTextOptions(text=input)
  58. # Analyze prompt
  59. try:
  60. response = client.analyze_text(request)
  61. except HttpResponseError as e:
  62. print("prompt failed due to content safety filtering.")
  63. if e.error:
  64. print(f"Error code: {e.error.code}")
  65. print(f"Error message: {e.error.message}")
  66. raise
  67. print(e)
  68. raise
  69. analyze_end_time = time.time()
  70. # The round trip latency for using Azure content safety check
  71. analyze_latency = (analyze_end_time - start_time) * 1000
  72. # Simple round-robin to dispatch requests into different containers
  73. executor_id = 0
  74. lock = threading.Lock()
  75. def generate_text() -> Tuple[int, int]:
  76. headers = MODEL_HEADERS
  77. payload = {
  78. "model" : MODEL_PATH,
  79. "messages" : [
  80. {
  81. "role": "user",
  82. "content": PROMPT
  83. }
  84. ],
  85. "stream" : False,
  86. "temperature" : TEMPERATURE,
  87. "top_p" : TOP_P,
  88. "max_tokens" : MAX_NEW_TOKENS
  89. }
  90. start_time = time.time()
  91. if(SAFE_CHECK):
  92. # Function to send prompts for safety check. Add delays for request round-trip that count towards overall throughput measurement.
  93. # Expect NO returns from calling this function. If you want to check the safety check results, print it out within the function itself.
  94. analyze_prompt(PROMPT)
  95. # Or add delay simulation if you don't want to use Azure Content Safety check. The API round-trip for this check is around 0.3-0.4 seconds depends on where you located. You can use something like this: time.sleep(random.uniform(0.3, 0.4))
  96. # Acquire lock to dispatch the request
  97. lock.acquire()
  98. global executor_id
  99. if executor_id != len(MODEL_ENDPOINTS)-1:
  100. executor_id += 1
  101. endpoint_id = executor_id
  102. else:
  103. executor_id = 0
  104. endpoint_id = executor_id
  105. lock.release()
  106. # Send request
  107. response = requests.post(MODEL_ENDPOINTS[endpoint_id], headers=headers, json=payload)
  108. if(SAFE_CHECK):
  109. # Function to send prompts for safety check. Add delays for request round-trip that count towards overall throughput measurement.
  110. # Expect NO returns from calling this function. If you want to check the safety check results, print it out within the function itself.
  111. analyze_prompt(PROMPT)
  112. # Or add delay simulation if you don't want to use Azure Content Safety check. The API round-trip for this check is around 0.3-0.4 seconds depends on where you located. You can use something like this: time.sleep(random.uniform(0.3, 0.4))
  113. end_time = time.time()
  114. # Convert to ms
  115. latency = (end_time - start_time) * 1000
  116. if response.status_code != 200:
  117. raise ValueError(f"Error: {response.content}")
  118. output = json.loads(response.content)["choices"][0]["message"]["content"]
  119. token_count = len(tokenizer.encode(output))
  120. return latency, token_count
  121. def evaluate_performance(concurrent_requests: int) -> Tuple[float, float, float, float, float, float, float, List[float]]:
  122. latencies = []
  123. total_output_tokens = 0
  124. output_tokens_per_second_each_request = []
  125. start_time = time.time()
  126. # Init multi-thread execution
  127. with ThreadPoolExecutor(max_workers=concurrent_requests) as executor:
  128. future_to_req = {executor.submit(generate_text): i for i in range(concurrent_requests)}
  129. for future in as_completed(future_to_req):
  130. latency, token_count = future.result()
  131. latencies.append(latency)
  132. total_output_tokens += token_count
  133. # Calculate tokens per second for this request
  134. tokens_per_sec = token_count / (latency / 1000)
  135. output_tokens_per_second_each_request.append(tokens_per_sec)
  136. end_time = time.time()
  137. total_time = end_time - start_time
  138. # RPS (requests per second)
  139. rps = concurrent_requests / total_time
  140. # Overall tokens per second
  141. output_tokens_per_second_overall = total_output_tokens / total_time
  142. input_tokens_per_second_overall = (num_token_input_prompt * concurrent_requests) / total_time
  143. output_tokens_per_second_per_gpu = output_tokens_per_second_overall / NUM_GPU
  144. input_tokens_per_second_per_gpu = input_tokens_per_second_overall / NUM_GPU
  145. p50_latency = np.percentile(latencies, 50)
  146. p99_latency = np.percentile(latencies, 99)
  147. # Count the number of requests below the token-per-second threshold
  148. below_threshold_count = sum(1 for tps in output_tokens_per_second_each_request if tps < THRESHOLD_TPS)
  149. output_tokens_per_second_per_request = sum(output_tokens_per_second_each_request)/len(output_tokens_per_second_each_request)
  150. return p50_latency, p99_latency, rps, output_tokens_per_second_overall, output_tokens_per_second_per_gpu, input_tokens_per_second_overall, input_tokens_per_second_per_gpu, output_tokens_per_second_per_request, below_threshold_count
  151. # Print markdown
  152. print("| Number of Concurrent Requests | P50 Latency (ms) | P99 Latency (ms) | RPS | Output Tokens per Second | Output Tokens per Second per GPU | Input Tokens per Second | Input Tokens per Second per GPU |Average Output Tokens per Second per Request | Number of Requests Below Threshold |")
  153. print("|-------------------------------|------------------|------------------|------------------|-------------------|---------------------------|---------------------|------------------------|-------------------------------------- | ---------------------------------- |")
  154. # Save to file
  155. csv_file = "performance_metrics.csv"
  156. with open(csv_file, "w", newline='') as f:
  157. writer = csv.writer(f)
  158. writer.writerow(["Number of Concurrent Requests", "P50 Latency (ms)", "P99 Latency (ms)", "RPS", "Output Tokens per Second", "Output Tokens per Second per GPU", "Input Tokens per Second", "Input Tokens per Second per GPU", "Average Output Tokens per Second per Request"])
  159. for level in CONCURRENT_LEVELS:
  160. p50_latency, p99_latency, rps, output_tokens_per_second_overall, output_tokens_per_second_per_gpu, input_tokens_per_second_overall, input_tokens_per_second_per_gpu, output_tokens_per_second_per_request, below_threshold_count = evaluate_performance(level)
  161. print(f"| {level} | {p50_latency:.2f} | {p99_latency:.2f} | {rps:.2f} | {output_tokens_per_second_overall:.2f} | {output_tokens_per_second_per_gpu:.2f} | {input_tokens_per_second_overall:.2f} | {input_tokens_per_second_per_gpu:.2f} | {output_tokens_per_second_per_request:.2f} | {below_threshold_count:.2f} |")
  162. writer.writerow([level, round(p50_latency, 2), round(p99_latency, 2), round(rps, 2), round(output_tokens_per_second_overall, 2), round(output_tokens_per_second_per_gpu, 2), round(input_tokens_per_second_overall, 2), round(input_tokens_per_second_per_gpu, 2), round(output_tokens_per_second_per_request, 2)])