|
| 1 | +import concurrent.futures |
| 2 | +import os |
| 3 | +import random |
| 4 | +import time |
| 5 | +from concurrent.futures import ProcessPoolExecutor |
| 6 | +from statistics import mean |
| 7 | + |
| 8 | +import requests |
| 9 | +from tqdm import tqdm |
| 10 | +from transformers import AutoTokenizer |
| 11 | + |
| 12 | +from sglang.lang.backend.runtime_endpoint import RuntimeEndpoint |
| 13 | + |
| 14 | +############################################################################### |
| 15 | +# CONFIG |
| 16 | +############################################################################### |
| 17 | +ENDPOINT_URL = "http://127.0.0.1:30000" |
| 18 | +TOKENIZER_DIR = "/models/meta-llama/Llama-3.2-3B" |
| 19 | + |
| 20 | +# Benchmark configurations |
| 21 | +NUM_REQUESTS = 10 # Total number of requests (each with BATCH_SIZE prompts) |
| 22 | +NUM_TOKENS = 32000 # Tokens per prompt |
| 23 | +BATCH_SIZE = 8 # Number of prompts per request |
| 24 | +GEN_TOKENS = 0 # Tokens to generate per prompt |
| 25 | + |
| 26 | + |
| 27 | +############################################################################### |
| 28 | +# REQUEST GENERATION (in parallel) |
| 29 | +############################################################################### |
| 30 | +def generate_random_prompt(index, tokenizer_dir, num_tokens): |
| 31 | + """Generate a single random prompt with specified token count.""" |
| 32 | + tokenizer = AutoTokenizer.from_pretrained(tokenizer_dir) |
| 33 | + vocab_size = tokenizer.vocab_size |
| 34 | + |
| 35 | + def generate_random_text(num_toks): |
| 36 | + random_token_ids = [random.randint(0, vocab_size - 1) for _ in range(num_toks)] |
| 37 | + return tokenizer.decode(random_token_ids, clean_up_tokenization_spaces=True) |
| 38 | + |
| 39 | + random_text = generate_random_text(num_tokens) |
| 40 | + return f"Prompt {index}: {random_text}" |
| 41 | + |
| 42 | + |
| 43 | +def prepare_all_prompts(num_requests, batch_size, num_tokens, tokenizer_dir): |
| 44 | + """Generate prompts for all requests in parallel.""" |
| 45 | + total_prompts = num_requests * batch_size |
| 46 | + all_prompts = [None] * total_prompts |
| 47 | + max_workers = min(os.cpu_count() or 1, total_prompts) |
| 48 | + |
| 49 | + with ProcessPoolExecutor(max_workers=max_workers) as executor: |
| 50 | + futures = [ |
| 51 | + executor.submit(generate_random_prompt, i, tokenizer_dir, num_tokens) |
| 52 | + for i in range(total_prompts) |
| 53 | + ] |
| 54 | + for future in tqdm( |
| 55 | + concurrent.futures.as_completed(futures), |
| 56 | + total=total_prompts, |
| 57 | + desc="Generating prompts", |
| 58 | + ): |
| 59 | + index = futures.index(future) |
| 60 | + all_prompts[index] = future.result() |
| 61 | + |
| 62 | + batched_prompts = [ |
| 63 | + all_prompts[i * batch_size : (i + 1) * batch_size] for i in range(num_requests) |
| 64 | + ] |
| 65 | + |
| 66 | + print( |
| 67 | + f"Generated {total_prompts} prompts with {num_tokens} tokens each, grouped into {num_requests} requests of {batch_size} prompts.\n" |
| 68 | + ) |
| 69 | + return batched_prompts |
| 70 | + |
| 71 | + |
| 72 | +############################################################################### |
| 73 | +# HTTP CALLS |
| 74 | +############################################################################### |
| 75 | +def send_batch_request(endpoint, prompts, gen_tokens, request_id): |
| 76 | + """Send a batch of prompts to the /generate endpoint synchronously.""" |
| 77 | + sampling_params = { |
| 78 | + "max_new_tokens": gen_tokens, |
| 79 | + "temperature": 0.7, |
| 80 | + "stop": "\n", |
| 81 | + } |
| 82 | + data = {"text": prompts, "sampling_params": sampling_params} |
| 83 | + |
| 84 | + start_time = time.time() |
| 85 | + try: |
| 86 | + response = requests.post( |
| 87 | + endpoint.base_url + "/generate", json=data, timeout=3600 |
| 88 | + ) |
| 89 | + if response.status_code != 200: |
| 90 | + error = response.json() |
| 91 | + raise RuntimeError(f"Request {request_id} failed: {error}") |
| 92 | + result = response.json() |
| 93 | + elapsed_time = (time.time() - start_time) * 1000 # Convert to ms |
| 94 | + avg_per_prompt = elapsed_time / len(prompts) if prompts else 0 |
| 95 | + return request_id, elapsed_time, avg_per_prompt, True, len(prompts) |
| 96 | + except Exception as e: |
| 97 | + print(f"[Request] Error for request {request_id}: {e}") |
| 98 | + return request_id, 0, 0, False, len(prompts) |
| 99 | + |
| 100 | + |
| 101 | +def run_benchmark(endpoint, batched_prompts, batch_size, gen_tokens): |
| 102 | + """Run the benchmark sequentially.""" |
| 103 | + results = [] |
| 104 | + num_requests = len(batched_prompts) |
| 105 | + |
| 106 | + # Record start time for total latency |
| 107 | + benchmark_start_time = time.time() |
| 108 | + |
| 109 | + for i, batch_prompts in enumerate(batched_prompts): |
| 110 | + request_id = i + 1 |
| 111 | + assert ( |
| 112 | + len(batch_prompts) == batch_size |
| 113 | + ), f"Request {request_id} should have {batch_size} prompts, got {len(batch_prompts)}" |
| 114 | + |
| 115 | + print( |
| 116 | + f"[Request] Sending request {request_id}/{num_requests} with {len(batch_prompts)} prompts at {int(time.time()*1000)}" |
| 117 | + ) |
| 118 | + result = send_batch_request(endpoint, batch_prompts, gen_tokens, request_id) |
| 119 | + results.append(result) |
| 120 | + |
| 121 | + # Calculate total latency |
| 122 | + total_latency = (time.time() - benchmark_start_time) * 1000 # Convert to ms |
| 123 | + |
| 124 | + return results, total_latency |
| 125 | + |
| 126 | + |
| 127 | +############################################################################### |
| 128 | +# RESULTS |
| 129 | +############################################################################### |
| 130 | +def process_results(results, total_latency, num_requests): |
| 131 | + """Process and display benchmark results.""" |
| 132 | + total_time = 0 |
| 133 | + successful_requests = 0 |
| 134 | + failed_requests = 0 |
| 135 | + request_latencies = [] |
| 136 | + per_prompt_latencies = [] |
| 137 | + total_prompts = 0 |
| 138 | + |
| 139 | + for request_id, elapsed_time, avg_per_prompt, success, batch_size in results: |
| 140 | + if success: |
| 141 | + successful_requests += 1 |
| 142 | + total_prompts += batch_size |
| 143 | + request_latencies.append(elapsed_time) |
| 144 | + per_prompt_latencies.append(avg_per_prompt) |
| 145 | + total_time += elapsed_time / 1000 # Convert to seconds |
| 146 | + else: |
| 147 | + failed_requests += 1 |
| 148 | + |
| 149 | + avg_request_latency = mean(request_latencies) if request_latencies else 0 |
| 150 | + avg_per_prompt_latency = mean(per_prompt_latencies) if per_prompt_latencies else 0 |
| 151 | + throughput = total_prompts / total_time if total_time > 0 else 0 |
| 152 | + |
| 153 | + print("\nBenchmark Summary:") |
| 154 | + print(f" Total requests sent: {len(results)}") |
| 155 | + print(f" Total prompts sent: {total_prompts}") |
| 156 | + print(f" Successful requests: {successful_requests}") |
| 157 | + print(f" Failed requests: {failed_requests}") |
| 158 | + print(f" Total latency (all requests): {total_latency:.2f} ms") |
| 159 | + print(f" Avg per request latency: {avg_request_latency:.2f} ms") |
| 160 | + print(f" Avg per prompt latency: {avg_per_prompt_latency:.2f} ms") |
| 161 | + print(f" Throughput: {throughput:.2f} prompts/second\n") |
| 162 | + |
| 163 | + |
| 164 | +############################################################################### |
| 165 | +# MAIN |
| 166 | +############################################################################### |
| 167 | +def main(): |
| 168 | + # Initialize endpoint |
| 169 | + endpoint = RuntimeEndpoint(ENDPOINT_URL) |
| 170 | + |
| 171 | + # Generate prompts |
| 172 | + batched_prompts = prepare_all_prompts( |
| 173 | + NUM_REQUESTS, BATCH_SIZE, NUM_TOKENS, TOKENIZER_DIR |
| 174 | + ) |
| 175 | + |
| 176 | + # Flush cache before benchmark |
| 177 | + # endpoint.flush_cache() |
| 178 | + |
| 179 | + # Run benchmark |
| 180 | + print( |
| 181 | + f"Starting benchmark: NUM_TOKENS={NUM_TOKENS}, BATCH_SIZE={BATCH_SIZE}, NUM_REQUESTS={NUM_REQUESTS}\n" |
| 182 | + ) |
| 183 | + results, total_latency = run_benchmark( |
| 184 | + endpoint, batched_prompts, BATCH_SIZE, GEN_TOKENS |
| 185 | + ) |
| 186 | + |
| 187 | + # Process and display results |
| 188 | + process_results(results, total_latency, NUM_REQUESTS) |
| 189 | + |
| 190 | + |
| 191 | +if __name__ == "__main__": |
| 192 | + random.seed(0) |
| 193 | + main() |
0 commit comments