gpu-head-to-head
aien-dev/gpu-head-to-head
Brought by drakestapleton
gpu-head-to-head / bench / test-ttft.py
| 1 | #!/usr/bin/env python3 |
| 2 | """PROTOCOL.md A10 TTFT rows: identical requests across arms, per-rep nonce, turn-2 prefix identity. |
| 3 | |
| 4 | Local synthetic HTTP only; no model, no GPU.""" |
| 5 | import hashlib |
| 6 | import importlib.util |
| 7 | import json |
| 8 | import os |
| 9 | from pathlib import Path |
| 10 | import subprocess |
| 11 | import sys |
| 12 | import tempfile |
| 13 | import threading |
| 14 | from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 15 | import unittest |
| 16 | |
| 17 | sys.dont_write_bytecode = True |
| 18 | HERE = Path(__file__).resolve().parent |
| 19 | PROMPTS = HERE.parent / 'prompts' / 'ttft.jsonl' |
| 20 | spec = importlib.util.spec_from_file_location('bench_client', HERE / 'bench.py') |
| 21 | bench = importlib.util.module_from_spec(spec) |
| 22 | spec.loader.exec_module(bench) |
| 23 | gspec = importlib.util.spec_from_file_location('make_ttft', HERE / 'make_ttft_prompts.py') |
| 24 | make_ttft = importlib.util.module_from_spec(gspec) |
| 25 | gspec.loader.exec_module(make_ttft) |
| 26 | |
| 27 | |
| 28 | def event(value): |
| 29 | return 'data: ' + json.dumps(value) + '\n\n' |
| 30 | |
| 31 | |
| 32 | STREAM = (event({'choices': [{'delta': {'content': 'x'}}]}) |
| 33 | + event({'choices': [{'finish_reason': 'length'}], 'usage': {'prompt_tokens': 7, 'completion_tokens': 1}}) |
| 34 | + 'data: [DONE]\n\n') |
| 35 | METRICS = ('# HELP vllm:prefix_cache_hits_total hits\n' |
| 36 | 'vllm:prefix_cache_queries_total{model_name="q36"} 10.0\n' |
| 37 | 'vllm:prefix_cache_hits_total{model_name="q36"} 4.0\nvllm:other_total 1.0\n') |
| 38 | |
| 39 | |
| 40 | class FakeServer: |
| 41 | """Records every request body in arrival order; answers /metrics and the chat stream.""" |
| 42 | def __enter__(self): |
| 43 | bodies, gets = self.bodies, self.gets = [], [] |
| 44 | |
| 45 | class Handler(BaseHTTPRequestHandler): |
| 46 | def log_message(self, *_): |
| 47 | pass |
| 48 | |
| 49 | def do_GET(self): |
| 50 | gets.append(self.path) |
| 51 | self.send_response(200) |
| 52 | self.end_headers() |
| 53 | self.wfile.write(METRICS.encode()) |
| 54 | |
| 55 | def do_POST(self): |
| 56 | bodies.append(self.rfile.read(int(self.headers['Content-Length']))) |
| 57 | self.send_response(200) |
| 58 | self.send_header('Content-Type', 'text/event-stream') |
| 59 | self.end_headers() |
| 60 | self.wfile.write(STREAM.encode()) |
| 61 | self.server = ThreadingHTTPServer(('127.0.0.1', 0), Handler) |
| 62 | self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) |
| 63 | self.thread.start() |
| 64 | return self |
| 65 | |
| 66 | def __exit__(self, *_): |
| 67 | self.server.shutdown() |
| 68 | self.thread.join() |
| 69 | self.server.server_close() |
| 70 | |
| 71 | |
| 72 | def run_bench(arm, *extra, prompts=PROMPTS): |
| 73 | """Run bench.py against a fresh fake server; returns (rc, raw request bodies, rows, GET paths, stderr).""" |
| 74 | with FakeServer() as srv, tempfile.TemporaryDirectory() as tmp: |
| 75 | out = Path(tmp, 'rows.jsonl') |
| 76 | r = subprocess.run([sys.executable, str(HERE / 'bench.py'), '--port', str(srv.server.server_port), |
| 77 | '--model', 'q36', '--arm', arm, '--round', 'T1', '--metric', 'ttft-x', |
| 78 | '--prompts', str(prompts), '--max-tokens', '1', '--out', str(out)] + list(extra), |
| 79 | capture_output=True, text=True, timeout=60, env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1')) |
| 80 | rows = [json.loads(l) for l in out.read_text().splitlines()] if out.exists() else [] |
| 81 | return r.returncode, list(srv.bodies), rows, list(srv.gets), r.stderr |
| 82 | |
| 83 | |
| 84 | def first_user(body): |
| 85 | return json.loads(body)['messages'][0] |
| 86 | |
| 87 | |
| 88 | class NonceTests(unittest.TestCase): |
| 89 | def test_nonce_is_deterministic_and_arm_free(self): |
| 90 | self.assertEqual(bench.ttft_nonce('t2k', 0, False), bench.ttft_nonce('t2k', 0, False)) |
| 91 | self.assertEqual(bench.ttft_nonce('t2k', 0, False), |
| 92 | hashlib.sha256(b'h2h-ttft|t2k|r0').hexdigest()[:16]) |
| 93 | |
| 94 | def test_nonce_changes_per_rep_warmup_and_prompt(self): |
| 95 | seen = {bench.ttft_nonce(p, rep, w) for p in ('t2k', 't8k', 't32k') for rep in range(4) for w in (False, True)} |
| 96 | self.assertEqual(len(seen), 3 * 4 * 2) |
| 97 | |
| 98 | |
| 99 | class FreshRowTests(unittest.TestCase): |
| 100 | ARGS = ('--ttft', 'fresh', '--select', 't8k', '--warmup', '1', '--warm-select', 't2k', '--reps', '3') |
| 101 | |
| 102 | def test_requests_are_byte_identical_across_arms(self): |
| 103 | rc_a, bodies_a, rows_a, _, err = run_bench('OURS', *self.ARGS) |
| 104 | self.assertEqual(rc_a, 0, err) |
| 105 | rc_b, bodies_b, rows_b, _, err = run_bench('VLLM_FP8', *self.ARGS) |
| 106 | self.assertEqual(rc_b, 0, err) |
| 107 | self.assertEqual(len(bodies_a), 4) |
| 108 | self.assertEqual(bodies_a, bodies_b) |
| 109 | self.assertEqual([r['messages_sha256'] for r in rows_a], [r['messages_sha256'] for r in rows_b]) |
| 110 | |
| 111 | def test_nonce_changes_per_rep_and_text_is_the_pinned_prompt(self): |
| 112 | rc, bodies, rows, gets, err = run_bench('OURS', *self.ARGS) |
| 113 | self.assertEqual(rc, 0, err) |
| 114 | byid = {p['id']: p for p in map(json.loads, PROMPTS.read_text().splitlines())} |
| 115 | users = [first_user(b)['content'] for b in bodies] |
| 116 | self.assertEqual(len(set(u.split('\n', 1)[0] for u in users)), 4) # 1 warmup + 3 reps |
| 117 | self.assertTrue(users[0].endswith(byid['t2k']['text'])) # cheap warmup prompt |
| 118 | for u, row in zip(users[1:], rows[1:]): |
| 119 | self.assertEqual(u, bench.NONCE_LINE % row['nonce'] + byid['t8k']['text']) |
| 120 | self.assertEqual(row['nonce'], bench.ttft_nonce('t8k', row['rep'], False)) |
| 121 | self.assertEqual([(r['warmup'], r['rep'], r['prompt_id']) for r in rows], |
| 122 | [(True, 0, 't2k'), (False, 0, 't8k'), (False, 1, 't8k'), (False, 2, 't8k')]) |
| 123 | self.assertEqual(gets, [], 'fresh rows never read /metrics') |
| 124 | |
| 125 | def test_rep_base_continues_the_nonce_sequence(self): |
| 126 | _, one, _, _, _ = run_bench('OURS', '--ttft', 'fresh', '--select', 't2k', '--warmup', '0', '--reps', '3') |
| 127 | _, split, _, _, _ = run_bench('OURS', '--ttft', 'fresh', '--select', 't2k', '--warmup', '0', '--reps', '2', |
| 128 | '--rep-base', '1') |
| 129 | self.assertEqual(one[1:], split) |
| 130 | |
| 131 | def test_negative_control_random_nonce_differs_across_arms(self): |
| 132 | # the legacy prefill path (uuid nonce) must fail the same identity comparison |
| 133 | a = run_bench('OURS', '--select', 't2k', '--warmup', '0', '--reps', '1', '--nonce')[1] |
| 134 | b = run_bench('VLLM_FP8', '--select', 't2k', '--warmup', '0', '--reps', '1', '--nonce')[1] |
| 135 | self.assertEqual((len(a), len(b)), (1, 1)) |
| 136 | self.assertNotEqual(a, b) |
| 137 | |
| 138 | |
| 139 | class TurnTwoTests(unittest.TestCase): |
| 140 | ARGS = ('--ttft', 'turn2', '--select', 't32k', '--warmup', '1', '--warm-select', 't2k', '--reps', '2') |
| 141 | |
| 142 | def test_turn2_prefix_is_byte_identical_to_the_primed_prompt(self): |
| 143 | rc, bodies, rows, gets, err = run_bench('VLLM_FP8', *self.ARGS) |
| 144 | self.assertEqual(rc, 0, err) |
| 145 | self.assertEqual([r['ttft_phase'] for r in rows], ['fresh', 'prime', 'turn2', 'prime', 'turn2']) |
| 146 | self.assertEqual([r['metric'] for r in rows[1:3]], ['ttft-x-prime', 'ttft-x']) |
| 147 | byid = {p['id']: p for p in map(json.loads, PROMPTS.read_text().splitlines())} |
| 148 | for prime, full in ((bodies[1], bodies[2]), (bodies[3], bodies[4])): |
| 149 | pm, fm = json.loads(prime)['messages'], json.loads(full)['messages'] |
| 150 | self.assertEqual(len(pm), 1) |
| 151 | self.assertEqual(json.dumps(pm[0]).encode(), json.dumps(fm[0]).encode()) |
| 152 | self.assertEqual([m['role'] for m in fm], ['user', 'assistant', 'user']) |
| 153 | self.assertEqual(fm[1]['content'], byid['turn2-assistant']['text']) |
| 154 | self.assertEqual(fm[2]['content'], byid['turn2-new']['text']) |
| 155 | self.assertTrue(pm[0]['content'].endswith(byid['t32k']['text'])) |
| 156 | self.assertNotEqual(first_user(bodies[1]), first_user(bodies[3]), 'nonce must change per rep') |
| 157 | self.assertEqual(rows[1]['prefix_sha256'], rows[2]['prefix_sha256']) |
| 158 | self.assertNotEqual(rows[1]['prefix_sha256'], rows[3]['prefix_sha256']) |
| 159 | |
| 160 | def test_turn2_requests_identical_across_arms(self): |
| 161 | a = run_bench('OURS', *self.ARGS) |
| 162 | b = run_bench('VLLM_NVFP4', *self.ARGS) |
| 163 | self.assertEqual((a[0], b[0]), (0, 0)) |
| 164 | self.assertEqual(a[1], b[1]) |
| 165 | |
| 166 | def test_prefix_cache_counters_are_recorded_around_each_request(self): |
| 167 | rc, _, rows, gets, err = run_bench('VLLM_FP8', *self.ARGS) |
| 168 | self.assertEqual(rc, 0, err) |
| 169 | self.assertEqual(gets, ['/metrics'] * 10) |
| 170 | want = ['vllm:prefix_cache_queries_total{model_name="q36"} 10.0', 'vllm:prefix_cache_hits_total{model_name="q36"} 4.0'] |
| 171 | self.assertEqual(rows[2]['prefix_cache_before'], {'lines': want}) |
| 172 | self.assertEqual(rows[2]['prefix_cache_after'], {'lines': want}) |
| 173 | |
| 174 | def test_negative_control_tampered_prefix_is_detected(self): |
| 175 | byid = {p['id']: p for p in map(json.loads, PROMPTS.read_text().splitlines())} |
| 176 | prime = bench.ttft_requests('turn2', byid, 't32k', bench.ttft_nonce('t32k', 0, False))[0][1] |
| 177 | other = bench.ttft_requests('turn2', byid, 't32k', bench.ttft_nonce('t32k', 1, False))[1][1] |
| 178 | self.assertNotEqual(bench.messages_sha256(prime[:1]), bench.messages_sha256(other[:1])) |
| 179 | |
| 180 | |
| 181 | class ArgumentTests(unittest.TestCase): |
| 182 | def test_refusals(self): |
| 183 | for extra in (('--ttft', 'fresh', '--select', 't2k', '--nonce'), |
| 184 | ('--ttft', 'fresh', '--select', 't2k,t8k'), |
| 185 | ('--ttft', 'fresh', '--select', 'p2k'), |
| 186 | ('--ttft', 'fresh', '--select', 't2k', '--concurrency', '2'), |
| 187 | ('--ttft', 'fresh', '--select', 't2k', '--warm-select', 'nope'), |
| 188 | ('--select', 't2k', '--rep-base', '1'), |
| 189 | ('--select', 't2k', '--warm-select', 't2k')): |
| 190 | with self.subTest(extra=extra): |
| 191 | rc, bodies, _, _, _ = run_bench('OURS', *extra) |
| 192 | self.assertEqual((rc, bodies), (2, [])) |
| 193 | |
| 194 | def test_turn2_needs_its_conversation_texts(self): |
| 195 | with tempfile.TemporaryDirectory() as tmp: |
| 196 | p = Path(tmp, 'p.jsonl') |
| 197 | p.write_text(json.dumps({'id': 't32k', 'text': 'x'}) + '\n') |
| 198 | rc, bodies, _, _, _ = run_bench('OURS', '--ttft', 'turn2', '--select', 't32k', prompts=p) |
| 199 | self.assertEqual((rc, bodies), (2, [])) |
| 200 | |
| 201 | |
| 202 | class PromptFileTests(unittest.TestCase): |
| 203 | def test_committed_prompts_carry_the_pinned_source_shas(self): |
| 204 | rows = {r['id']: r for r in map(json.loads, PROMPTS.read_text().splitlines())} |
| 205 | self.assertEqual(sorted(rows), ['t2k', 't32k', 't8k', 'turn2-assistant', 'turn2-new']) |
| 206 | for pid, (_, sha) in make_ttft.SOURCES.items(): |
| 207 | self.assertEqual(rows[pid]['source_sha256'], sha) |
| 208 | if pid != 'turn2-new': |
| 209 | self.assertEqual(hashlib.sha256(rows[pid]['text'].encode()).hexdigest(), sha) |
| 210 | self.assertEqual(rows['turn2-assistant']['text'], make_ttft.TURN2_ASSISTANT) |
| 211 | |
| 212 | def test_generator_refuses_a_wrong_source(self): |
| 213 | with tempfile.TemporaryDirectory() as tmp: |
| 214 | src = [Path(tmp, n) for n in ('a', 'b', 'c', 'd')] |
| 215 | for s in src: |
| 216 | s.write_text('wrong\n') |
| 217 | out = Path(tmp, 'out.jsonl') |
| 218 | self.assertEqual(make_ttft.main(['x'] + [str(s) for s in src] + [str(out)]), 2) |
| 219 | self.assertFalse(out.exists()) |
| 220 | |
| 221 | |
| 222 | if __name__ == '__main__': |
| 223 | unittest.main() |