interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

branch main Branches Tags History

MojoLlama / src / mojollama / tests / test_batching.py

87 lines · 3468 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Continuous batching load test for server_batch_moe.py"""
3import urllib.request, json, time, threading, sys
4
5SERVER = "http://localhost:8081"
6results = []
7errors = []
8
9def send_request(prompt, idx):
10 t0 = time.time()
11 data = json.dumps({"prompt": prompt, "max_tokens": 20, "temperature": 0.0}).encode()
12 req = urllib.request.Request(f"{SERVER}/v1/completions",
13 data=data,
14 headers={"Content-Type": "application/json"})
15 try:
16 resp = urllib.request.urlopen(req, timeout=60)
17 body = json.loads(resp.read())
18 elapsed = time.time() - t0
19 gen_text = body.get("choices", [{}])[0].get("text", "")
20 finish = body.get("choices", [{}])[0].get("finish_reason", "?")
21 results.append({"idx": idx, "elapsed": elapsed, "text": gen_text[:40], "finish": finish, "tokens": body.get("usage", {}).get("completion_tokens", 0)})
22 print(f" [{idx}] {elapsed:.1f}s finish={finish} tokens={body.get('usage',{}).get('completion_tokens',0)} '{gen_text[:40]}'")
23 except Exception as e:
24 errors.append({"idx": idx, "error": str(e)})
25 print(f" [{idx}] ERROR: {e}")
26
27print("=" * 60)
28print("ITEM 6: Continuous batching load test")
29print("=" * 60)
30
31# Test 1: 5 concurrent requests
32print("\n--- Test 1: 5 concurrent requests ---")
33threads = []
34prompts = [
35 "The capital of France is",
36 "The theory of relativity states that",
37 "Machine learning is a field of",
38 "Python is a programming language that",
39 "The mitochondria is the powerhouse of",
40]
41t0 = time.time()
42for i, prompt in enumerate(prompts):
43 t = threading.Thread(target=send_request, args=(prompt, i))
44 t.start()
45 threads.append(t)
46for t in threads:
47 t.join()
48t_total = time.time() - t0
49
50print(f"\nResults: {len(results)}/{len(prompts)} OK, {len(errors)} errors")
51if results:
52 avg_lat = sum(r["elapsed"] for r in results) / len(results)
53 max_lat = max(r["elapsed"] for r in results)
54 min_lat = min(r["elapsed"] for r in results)
55 total_tokens = sum(r["tokens"] for r in results)
56 print(f" Avg latency: {avg_lat*1000:.0f} ms")
57 print(f" Min latency: {min_lat*1000:.0f} ms")
58 print(f" Max latency: {max_lat*1000:.0f} ms")
59 print(f" Total generation tokens: {total_tokens}")
60 print(f" Total wall time: {t_total:.1f}s")
61if errors:
62 for e in errors:
63 print(f" Error in request {e['idx']}: {e['error']}")
64
65# Test 2: Streaming test
66print("\n--- Test 2: Streaming test ---")
67try:
68 data = json.dumps({"prompt": "Once upon a time,", "max_tokens": 10, "temperature": 0.0, "stream": True}).encode()
69 req = urllib.request.Request(f"{SERVER}/v1/completions",
70 data=data,
71 headers={"Content-Type": "application/json"})
72 resp = urllib.request.urlopen(req, timeout=30)
73 chunks = []
74 for line in resp:
75 line = line.decode().strip()
76 if line.startswith("data:"):
77 chunks.append(line)
78 print(f" Received {len(chunks)} SSE chunks")
79 for c in chunks[:5]:
80 print(f" {c[:80]}")
81 if len(chunks) > 5:
82 print(f" ... ({len(chunks)-5} more)")
83 print(f" Streaming: OK ({len(chunks)} chunks)")
84except Exception as e:
85 print(f" Streaming ERROR: {e}")
86
87print(f"\nContinuous batching: {len(results)}/{len(prompts)} requests OK, avg latency {avg_lat*1000:.0f} ms, max concurrent {len(prompts)}")