chat_vllm_benchmark.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. # Default Llama tokenizer, replace with your own tokenizer
  35. TOKENIZER_PATH = params["TOKENIZER_PATH"]
  36. TEMPERATURE = params["TEMPERATURE"]
  37. TOP_P = params["TOP_P"]
  38. # Add your model endpoints here, specify the port number. You can acquire the endpoint when creating a on-prem server like vLLM.
  39. # Group of model endpoints - Send balanced requests to each endpoint for batch maximization.
  40. MODEL_ENDPOINTS = params["MODEL_ENDPOINTS"]
  41. # Get number of GPUs on this instance
  42. if torch.cuda.is_available():
  43. NUM_GPU = torch.cuda.device_count()
  44. else:
  45. print("No available GPUs")
  46. # This tokenizer is downloaded from Azure model catalog for each specific models. The main purpose is to decode the reponses for token calculation
  47. tokenizer = transformers.AutoTokenizer.from_pretrained(TOKENIZER_PATH)
  48. num_token_input_prompt = len(tokenizer.encode(PROMPT))
  49. print(f"Number of token for input prompt: {num_token_input_prompt}")
  50. # Azure content safety analysis
  51. def analyze_prompt(input):
  52. start_time = time.time()
  53. # Obtain credentials
  54. key = "" #Add your AZURE_CONTENT_SAFETY_KEY
  55. endpoint = "" #Add your AZURE_CONTENT_SAFETY_ENDPOINT
  56. # Create a content safety client
  57. client = ContentSafetyClient(endpoint, AzureKeyCredential(key))
  58. # Create request
  59. request = AnalyzeTextOptions(text=input)
  60. # Analyze prompt
  61. try:
  62. response = client.analyze_text(request)
  63. except HttpResponseError as e:
  64. print("prompt failed due to content safety filtering.")
  65. if e.error:
  66. print(f"Error code: {e.error.code}")
  67. print(f"Error message: {e.error.message}")
  68. raise
  69. print(e)
  70. raise
  71. analyze_end_time = time.time()
  72. # The round trip latency for using Azure content safety check
  73. analyze_latency = (analyze_end_time - start_time) * 1000
  74. # Simple round-robin to dispatch requests into different containers
  75. executor_id = 0
  76. lock = threading.Lock()
  77. def generate_text() -> Tuple[int, int]:
  78. headers = MODEL_HEADERS
  79. payload = {
  80. "model" : MODEL_PATH,
  81. "messages" : [
  82. {
  83. "role": "user",
  84. "content": PROMPT
  85. }
  86. ],
  87. "stream" : False,
  88. "temperature" : TEMPERATURE,
  89. "top_p" : TOP_P,
  90. "max_tokens" : MAX_NEW_TOKENS
  91. }
  92. start_time = time.time()
  93. if(SAFE_CHECK):
  94. # Function to send prompts for safety check. Add delays for request round-trip that count towards overall throughput measurement.
  95. # Expect NO returns from calling this function. If you want to check the safety check results, print it out within the function itself.
  96. analyze_prompt(PROMPT)
  97. # Or add delay simulation as below for real world situation
  98. # time.sleep(random.uniform(0.3, 0.4))
  99. # Acquire lock to dispatch the request
  100. lock.acquire()
  101. global executor_id
  102. if executor_id != len(MODEL_ENDPOINTS)-1:
  103. executor_id += 1
  104. endpoint_id = executor_id
  105. else:
  106. executor_id = 0
  107. endpoint_id = executor_id
  108. lock.release()
  109. # Send request
  110. response = requests.post(MODEL_ENDPOINTS[endpoint_id], headers=headers, json=payload)
  111. if(SAFE_CHECK):
  112. # Function to send prompts for safety check. Add delays for request round-trip that count towards overall throughput measurement.
  113. # Expect NO returns from calling this function. If you want to check the safety check results, print it out within the function itself.
  114. analyze_prompt(PROMPT)
  115. # Or add delay simulation as below for real world situation
  116. # time.sleep(random.uniform(0.3, 0.4))
  117. end_time = time.time()
  118. # Convert to ms
  119. latency = (end_time - start_time) * 1000
  120. if response.status_code != 200:
  121. raise ValueError(f"Error: {response.content}")
  122. output = json.loads(response.content)["choices"][0]["message"]["content"]
  123. token_count = len(tokenizer.encode(output))
  124. return latency, token_count
  125. def evaluate_performance(concurrent_requests: int) -> Tuple[float, float, float, float, float, float, float, List[float]]:
  126. latencies = []
  127. total_output_tokens = 0
  128. output_tokens_per_second_each_request = []
  129. start_time = time.time()
  130. # Init multi-thread execution
  131. with ThreadPoolExecutor(max_workers=concurrent_requests) as executor:
  132. future_to_req = {executor.submit(generate_text): i for i in range(concurrent_requests)}
  133. for future in as_completed(future_to_req):
  134. latency, token_count = future.result()
  135. latencies.append(latency)
  136. total_output_tokens += token_count
  137. # Calculate tokens per second for this request
  138. tokens_per_sec = token_count / (latency / 1000)
  139. output_tokens_per_second_each_request.append(tokens_per_sec)
  140. end_time = time.time()
  141. total_time = end_time - start_time
  142. # RPS (requests per second)
  143. rps = concurrent_requests / total_time
  144. # Overall tokens per second
  145. output_tokens_per_second_overall = total_output_tokens / total_time
  146. input_tokens_per_second_overall = (num_token_input_prompt * concurrent_requests) / total_time
  147. output_tokens_per_second_per_gpu = output_tokens_per_second_overall / NUM_GPU
  148. input_tokens_per_second_per_gpu = input_tokens_per_second_overall / NUM_GPU
  149. p50_latency = np.percentile(latencies, 50)
  150. p99_latency = np.percentile(latencies, 99)
  151. # Count the number of requests below the token-per-second threshold
  152. below_threshold_count = sum(1 for tps in output_tokens_per_second_each_request if tps < THRESHOLD_TPS)
  153. output_tokens_per_second_per_request = sum(output_tokens_per_second_each_request)/len(output_tokens_per_second_each_request)
  154. 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
  155. # Print markdown
  156. 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 |")
  157. print("|-------------------------------|------------------|------------------|------------------|-------------------|---------------------------|---------------------|------------------------|-------------------------------------- | ---------------------------------- |")
  158. # Save to file
  159. csv_file = "performance_metrics.csv"
  160. with open(csv_file, "w", newline='') as f:
  161. writer = csv.writer(f)
  162. 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"])
  163. for level in CONCURRENT_LEVELS:
  164. 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)
  165. 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} |")
  166. 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)])