-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbenchmark_httpclient.py
More file actions
1479 lines (1274 loc) · 51.8 KB
/
benchmark_httpclient.py
File metadata and controls
1479 lines (1274 loc) · 51.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""
HTTP client performance testing utility.
Benchmarks send/recv rate of the HTTPEndpointClient using uvloop.
Can auto-launch a MaxThroughputServer or connect to an external endpoint.
Usage (see all available args in --help):
python -m inference_endpoint.utils.benchmark_httpclient -w 8 -c 512 -d 20
python -m inference_endpoint.utils.benchmark_httpclient --endpoint http://host:8080/v1/chat/completions
python -m inference_endpoint.utils.benchmark_httpclient --no-pin --track-memory
Sweep modes (-w, -c, -l accept ranges; endpoints always included):
-w 4:12 every int in [4, 12]
-c 100:500:100 start:stop:step -> [100, 200, 300, 400, 500]
-w 1:32::12 start:stop::N -> 12 evenly-spaced points in [1, 32]
-l 32,128,512 explicit values
-w 1:32::12 -c 100:500::4 cartesian product sweep
--full preset sweep of common worker counts x prompt lengths (non-streaming)
--full --stream preset sweep of common worker counts x prompt lengths (streaming)
"""
from __future__ import annotations
import argparse
import asyncio
import gc
import itertools
import os
import re
import signal
import socket
import sys
import threading
import time
from dataclasses import dataclass
from inference_endpoint.async_utils.transport.zmq.context import ManagedZMQContext
from inference_endpoint.core.types import Query, QueryResult
from inference_endpoint.endpoint_client.config import HTTPClientConfig
from inference_endpoint.endpoint_client.cpu_affinity import compute_affinity_plan
from inference_endpoint.endpoint_client.http_client import HTTPEndpointClient
from inference_endpoint.testing.max_throughput_server import (
MaxThroughputServer,
build_response,
)
@dataclass(slots=True)
class BenchmarkStats:
"""Snapshot of benchmark statistics."""
sent: int = 0
received: int = 0
errors: int = 0
send_elapsed_ns: int = 0 # Send phase duration
total_elapsed_ns: int = 0 # Total duration including drain
peak_inflight: int = 0 # Max observed in-flight count
stall_ns: int = 0 # Client overhead: time blocked waiting for responses to drain
sse_events_per_response: int = 1 # SSE events per response (set for streaming)
# Per-interval samples (populated by LiveDisplay)
send_rate_samples: list[float] | None = None
recv_rate_samples: list[float] | None = None
@dataclass(slots=True)
class MemoryStats:
"""Memory statistics for a process."""
pid: int
rss_mb: float
shm_mb: float
@dataclass(slots=True)
class SweepResult:
"""Result of a single benchmark run within a parameter sweep."""
param_values: dict[str, int] # swept param name -> value for this run
stats: BenchmarkStats
send_rate: float # req/s (mean)
recv_rate: float # resp/s (mean)
sse_rate: float # SSE pkts/s (mean, streaming only)
outstanding: int # sent - received - errors
error_rate: float # errors/sent (%)
stall_pct: float # client overhead: % of send time blocked on drain (%)
# Variation bounds from per-second samples
send_rate_min: float = 0.0
send_rate_max: float = 0.0
recv_rate_min: float = 0.0
recv_rate_max: float = 0.0
sse_rate_min: float = 0.0
sse_rate_max: float = 0.0
# ---------------------------------------------------------------------------
# Parsing helpers
# ---------------------------------------------------------------------------
def _linspace_int(start: int, stop: int, n: int) -> list[int]:
"""Generate *n* evenly-spaced integers from *start* to *stop* (inclusive).
Intermediate values are rounded to the nearest integer, but *start* and
*stop* are always included exactly.
"""
if n <= 0:
raise argparse.ArgumentTypeError(f"Number of points must be positive, got {n}")
if n == 1:
return [start]
points: list[int] = []
for i in range(n):
points.append(round(start + (stop - start) * i / (n - 1)))
# Deduplicate while preserving order (can happen with small ranges)
return list(dict.fromkeys(points))
def int_or_range(value: str) -> list[int]:
"""Parse an integer, range, or list specification. Endpoints always included.
Formats:
8 single value
4:12 every integer from 4 to 12
100:500:100 start:stop:step -> [100, 200, 300, 400, 500]
1:32::12 start:stop::N -> 12 evenly-spaced points in [1, 32]
1,4,8,16 explicit values
"""
# Detect comma-separated values: "1,4,8,16"
if "," in value:
try:
return [int(v.strip()) for v in value.split(",") if v.strip()]
except ValueError as e:
raise argparse.ArgumentTypeError(
f"Invalid integer in comma-separated list {value!r}: {e}"
) from e
# Detect linspace syntax: "start:end::N"
if "::" in value:
halves = value.split("::")
if len(halves) != 2 or ":" not in halves[0]:
raise argparse.ArgumentTypeError(
f"Linspace syntax must be start:end::N, got {value!r}"
)
try:
left = halves[0].split(":")
start, stop = int(left[0]), int(left[1])
num_points = int(halves[1])
except (ValueError, IndexError) as e:
raise argparse.ArgumentTypeError(
f"Invalid integer in linspace spec {value!r}: {e}"
) from e
if start > stop:
raise argparse.ArgumentTypeError(
f"Range start ({start}) must be <= stop ({stop})"
)
return _linspace_int(start, stop, num_points)
parts = value.split(":")
try:
if len(parts) == 1:
return [int(parts[0])]
elif len(parts) == 2:
start, stop = int(parts[0]), int(parts[1])
if start > stop:
raise argparse.ArgumentTypeError(
f"Range start ({start}) must be <= stop ({stop})"
)
return list(range(start, stop + 1))
elif len(parts) == 3:
start, stop, step = int(parts[0]), int(parts[1]), int(parts[2])
if step <= 0:
raise argparse.ArgumentTypeError(f"Step must be positive, got {step}")
if start > stop:
raise argparse.ArgumentTypeError(
f"Range start ({start}) must be <= stop ({stop})"
)
result = list(range(start, stop + 1, step))
if result[-1] != stop:
result.append(stop)
return result
else:
raise argparse.ArgumentTypeError(f"Too many ':' in range spec: {value!r}")
except ValueError as e:
raise argparse.ArgumentTypeError(
f"Invalid integer in range spec {value!r}: {e}"
) from e
def collect_sweep_params(
workers: list[int],
connections: list[int],
prompt_lengths: list[int],
stream_intervals: list[int] | None = None,
) -> list[tuple[str, list[int]]]:
"""Collect parameters that have ranges (more than one value)."""
candidates = [
("num_workers", workers),
("max_connections", connections),
("prompt_length", prompt_lengths),
]
if stream_intervals is not None:
candidates.append(("stream_interval", stream_intervals))
return [(name, vals) for name, vals in candidates if len(vals) > 1]
# ---------------------------------------------------------------------------
# Arithmetic helpers
# ---------------------------------------------------------------------------
def _safe_div(numerator: float, denominator: float) -> float:
"""Division with zero-denominator guard."""
return numerator / denominator if denominator > 0 else 0.0
def _stall_pct(stats: BenchmarkStats) -> float:
"""Client-side stall time (blocked on drain) as a percentage of send phase."""
if stats.send_elapsed_ns <= 0:
return 0.0
return _safe_div(stats.stall_ns, stats.send_elapsed_ns) * 100
def _compute_derived_stats(
stats: BenchmarkStats,
) -> tuple[float, float, float, float, float, int]:
"""Compute derived metrics from raw benchmark stats.
Returns (send_elapsed_sec, total_elapsed_sec, send_rate, recv_rate,
sse_rate, outstanding).
"""
send_elapsed_sec = stats.send_elapsed_ns / 1e9
total_elapsed_sec = stats.total_elapsed_ns / 1e9
return (
send_elapsed_sec,
total_elapsed_sec,
_safe_div(stats.sent, send_elapsed_sec),
_safe_div(stats.received, total_elapsed_sec),
_safe_div(stats.received * stats.sse_events_per_response, total_elapsed_sec),
stats.sent - stats.received - stats.errors,
)
# ---------------------------------------------------------------------------
# /proc memory helpers
# ---------------------------------------------------------------------------
def get_process_memory(pid: int) -> MemoryStats | None:
"""Get RSS and shared memory for a process from /proc."""
try:
with open(f"/proc/{pid}/statm") as f:
parts = f.read().split()
# statm fields: size resident shared text lib data dt (in pages)
page_size = os.sysconf("SC_PAGE_SIZE")
rss_pages = int(parts[1])
shared_pages = int(parts[2])
return MemoryStats(
pid=pid,
rss_mb=(rss_pages * page_size) / (1024 * 1024),
shm_mb=(shared_pages * page_size) / (1024 * 1024),
)
except (OSError, IndexError, ValueError):
return None
# ---------------------------------------------------------------------------
# Live display
# ---------------------------------------------------------------------------
class LiveDisplay:
"""Live statistics display with optional memory tracking."""
def __init__(
self,
stats_ref: BenchmarkStats,
track_memory: bool = False,
streaming: bool = False,
interval: float = 1.0,
):
self.stats = stats_ref
self.track_memory = track_memory
self.streaming = streaming
self.interval = interval
self._shutdown = threading.Event()
self._thread: threading.Thread | None = None
self._last_sent = 0
self._last_received = 0
self._last_time = time.monotonic()
self._main_pid = os.getpid()
self._worker_pids: list[int] = []
def set_worker_pids(self, pids: list[int]) -> None:
"""Set worker PIDs for memory tracking."""
self._worker_pids = pids
def start(self) -> None:
"""Start the display thread."""
self._thread = threading.Thread(target=self._run, daemon=True)
self._thread.start()
def stop(self) -> None:
"""Stop the display thread."""
self._shutdown.set()
if self._thread:
self._thread.join(timeout=2.0)
def _run(self) -> None:
"""Display loop."""
while not self._shutdown.wait(self.interval):
self._print_stats()
# Final stats (partial interval — print but don't record sample)
self._print_stats(record_sample=False)
def _print_stats(self, record_sample: bool = True) -> None:
"""Print current statistics and optionally record samples."""
now = time.monotonic()
elapsed = now - self._last_time
sent = self.stats.sent
received = self.stats.received
errors = self.stats.errors
in_flight = sent - received - errors
send_rate = (sent - self._last_sent) / elapsed if elapsed > 0 else 0
recv_rate = (received - self._last_received) / elapsed if elapsed > 0 else 0
self._last_sent = sent
self._last_received = received
self._last_time = now
# Record per-interval samples for variation analysis
# (skip partial intervals, e.g. the final stop() call)
if record_sample:
if self.stats.send_rate_samples is None:
self.stats.send_rate_samples = []
if self.stats.recv_rate_samples is None:
self.stats.recv_rate_samples = []
self.stats.send_rate_samples.append(send_rate)
self.stats.recv_rate_samples.append(recv_rate)
# Build output line
line = f"[Stats] Send/s: {send_rate:>9,.0f} | " f"Recv/s: {recv_rate:>9,.0f} | "
if self.streaming:
sse_rate = recv_rate * self.stats.sse_events_per_response
line += f"SSE-pkts/s: {sse_rate:>9,.0f} | "
line += (
f"InFlight: {in_flight:>8,} | "
f"Recv: {received:>10,} | "
f"Err: {errors:>5,}"
)
if self.track_memory:
mem_info = self._get_memory_info()
line += f" | {mem_info}"
print(line, flush=True)
def _get_memory_info(self) -> str:
"""Get memory info string."""
main_mem = get_process_memory(self._main_pid)
if main_mem is None:
return "Mem: N/A"
total_rss = main_mem.rss_mb
total_shm = main_mem.shm_mb
# Get worker memory if available
for pid in self._worker_pids:
worker_mem = get_process_memory(pid)
if worker_mem:
total_rss += worker_mem.rss_mb
total_shm += worker_mem.shm_mb
return f"RSS: {total_rss:>7.1f}MB | SHM: {total_shm:>7.1f}MB"
# ---------------------------------------------------------------------------
# Benchmark core
# ---------------------------------------------------------------------------
_SEND_BATCH = 32 # Max requests issued per event-loop yield
def build_prompt(length: int) -> str:
"""Build a prompt of specified length using repeated 'hello world '."""
base = "hello world "
repeats = (length // len(base)) + 1
return (base * repeats)[:length]
def _create_client(
endpoint_url: str,
num_workers: int,
max_connections: int,
streaming: bool,
prompt: str,
enable_affinity: bool,
verbose: bool = True,
zmq_context: ManagedZMQContext | None = None,
) -> tuple:
"""Create an endpoint client and query data dict.
Returns (client, query_data). Caller must shut down the client.
"""
cpu_affinity_plan = None
if enable_affinity:
effective = num_workers if num_workers > 0 else -1
tmp = HTTPClientConfig(endpoint_urls=[endpoint_url], num_workers=effective)
cpu_affinity_plan = compute_affinity_plan(tmp.num_workers)
if cpu_affinity_plan.loadgen_cpus:
os.sched_setaffinity(os.getpid(), set(cpu_affinity_plan.loadgen_cpus))
if verbose:
print(f"CPU Affinity Plan ({tmp.num_workers} workers):")
for line in cpu_affinity_plan.summary().split("\n"):
print(f" {line}")
elif verbose:
print("CPU Affinity: disabled")
config = HTTPClientConfig(
endpoint_urls=[endpoint_url],
num_workers=num_workers if num_workers > 0 else -1,
max_connections=max_connections if max_connections > 0 else -1,
warmup_connections=0,
worker_gc_mode="relaxed",
log_level="CRITICAL",
cpu_affinity=cpu_affinity_plan,
)
if verbose:
print(
f"Config: workers={config.num_workers}, "
f"max_connections={config.max_connections}, stream={streaming}"
)
client = HTTPEndpointClient(config, zmq_context=zmq_context)
query_data = {
"prompt": prompt,
"model": "benchmark-model",
"max_completion_tokens": 100,
"stream": streaming,
}
return client, query_data
def run_benchmark(
endpoint_url: str,
duration: float,
num_workers: int,
max_connections: int,
prompt: str,
track_memory: bool,
streaming: bool = False,
max_concurrency: int = 100_000,
send_batch: int = _SEND_BATCH,
enable_affinity: bool = False,
sse_events_per_response: int = 1,
max_total_time: float = 15.0,
) -> BenchmarkStats:
"""
Run the HTTP client benchmark.
Args:
endpoint_url: Target endpoint URL
duration: Benchmark duration in seconds
num_workers: Number of worker processes (-1 for auto)
max_connections: Max TCP connections (-1 for auto)
prompt: Prompt string to send
track_memory: Whether to track memory usage
streaming: Whether to use streaming mode
max_concurrency: Maximum in-flight requests for back-pressure
send_batch: Max requests issued per event-loop yield; auto-tuned at startup
sse_events_per_response: Number of SSE events per streaming response (for rate derivation)
max_total_time: Hard cap on total run time (send + drain) in seconds
Returns:
Final benchmark statistics
"""
# Save original affinity before _create_client pins us to loadgen CPUs.
# Without this, subsequent sweep iterations see only the restricted set
# and compute_affinity_plan detects fewer physical cores than exist.
saved_affinity: set[int] | None = None
if enable_affinity:
try:
saved_affinity = os.sched_getaffinity(os.getpid())
except OSError:
pass
zmq_ctx_manager = ManagedZMQContext.scoped()
zmq_ctx = zmq_ctx_manager.__enter__()
client, query_data = _create_client(
endpoint_url,
num_workers,
max_connections,
streaming,
prompt,
enable_affinity,
zmq_context=zmq_ctx,
)
loop = client.loop
stats = BenchmarkStats(sse_events_per_response=sse_events_per_response)
display = LiveDisplay(stats, track_memory=track_memory, streaming=streaming)
if track_memory:
worker_pids = list(client.worker_manager.worker_pids.values())
display.set_worker_pids(worker_pids)
display.start()
# Suppress GC during measurement to avoid collection pauses
gc_was_enabled = gc.isenabled()
gc.collect()
gc.disable()
async def benchmark_main():
"""Main benchmark coroutine running on event loop."""
nonlocal stats
send_done = False
start_ns = time.monotonic_ns()
send_deadline = time.monotonic() + duration
overall_deadline = time.monotonic() + max_total_time
stall_timeout = 5.0
last_recv_time = time.monotonic()
qid = 0
async def sender():
nonlocal qid, send_done
while time.monotonic() < send_deadline:
# Back-pressure: wait if too many in-flight
in_flight = stats.sent - stats.received - stats.errors
if in_flight > stats.peak_inflight:
stats.peak_inflight = in_flight
if in_flight >= max_concurrency:
stall_start = time.monotonic_ns()
await asyncio.sleep(0.0001)
stats.stall_ns += time.monotonic_ns() - stall_start
continue
# Burst up to send_batch requests before yielding
for _ in range(min(send_batch, max_concurrency - in_flight)):
query = Query(id=str(qid), data=query_data)
client.issue(query)
stats.sent += 1
qid += 1
# Yield to let receiver process
await asyncio.sleep(0)
stats.send_elapsed_ns = time.monotonic_ns() - start_ns
send_done = True
async def receiver():
nonlocal last_recv_time
while True:
result = client.poll()
if result is not None:
last_recv_time = time.monotonic()
if isinstance(result, QueryResult):
if result.error:
stats.errors += 1
else:
stats.received += 1
# Periodic deadline check on receive path
if (
stats.received % 128 == 0
and last_recv_time > overall_deadline
):
outstanding = stats.sent - stats.received - stats.errors
print(
f"\nTime limit ({max_total_time:.0f}s) reached, "
f"stopping ({outstanding:,} in-flight)"
)
return
else:
# Check completion
if send_done and (stats.received + stats.errors) >= stats.sent:
break
# Check stall
if (
send_done
and (time.monotonic() - last_recv_time) > stall_timeout
):
print(f"\nStalled for {stall_timeout}s, stopping")
break
# Check overall time limit
if time.monotonic() > overall_deadline:
outstanding = stats.sent - stats.received - stats.errors
print(
f"\nTime limit ({max_total_time:.0f}s) reached, "
f"stopping ({outstanding:,} in-flight)"
)
break
# Yield to sender
await asyncio.sleep(0)
# Run sender and receiver concurrently
await asyncio.gather(sender(), receiver())
stats.total_elapsed_ns = time.monotonic_ns() - start_ns
try:
future = asyncio.run_coroutine_threadsafe(benchmark_main(), loop)
future.result() # Block until complete
except KeyboardInterrupt:
print("\nInterrupted...")
display.stop()
# Restore GC state after measurement
if gc_was_enabled:
gc.enable()
gc.collect()
client.shutdown()
zmq_ctx_manager.__exit__(None, None, None)
# Restore original affinity so the next sweep iteration sees all CPUs
if saved_affinity is not None:
try:
os.sched_setaffinity(os.getpid(), saved_affinity)
except OSError:
pass
return stats
# ---------------------------------------------------------------------------
# Server lifecycle
# ---------------------------------------------------------------------------
_FULL_WORKERS = [1, 2, 4, 6, 8, 10, 12, 14, 16]
_FULL_PROMPT_LENGTHS = [
1,
32,
128,
512,
1024,
8192,
16384,
32768,
65536,
131072,
]
_FULL_STREAM_INTERVAL_PCTS = [0.0, 0.5, 1.0]
def _resolve_stream_intervals(output_length: int, fractions: list[float]) -> list[int]:
"""Map fractions to absolute stream_interval (chars-per-event) values, deduped and sorted.
0.0 -> 1 (1 char/event, finest); 0.5 -> output_length//2; 1.0 -> output_length (1 event total).
"""
vals: list[int] = []
for f in fractions:
if f <= 0.0:
vals.append(1)
else:
vals.append(max(1, round(output_length * f)))
return sorted(set(vals))
def _sse_events_per_response(output_length: int, stream_interval: int = 1) -> int:
"""Compute the number of SSE events the server sends per streaming response.
``ceil(output_length / stream_interval)`` content events, plus 1 finish
event and 1 [DONE] sentinel.
"""
return -(-output_length // stream_interval) + 2 # ceil division + 2
def _wait_for_port_free(host: str, port: int, timeout: float = 5.0) -> None:
"""Wait until *port* is bindable on *host* (old workers may linger in kernel)."""
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
except (AttributeError, OSError):
pass # SO_REUSEPORT unavailable — _start_workers will report
try:
s.bind((host, port))
return # port is free
except OSError:
time.sleep(0.1)
# Don't raise — proceed anyway and let _start_workers report the real error
def _restart_server(
server: MaxThroughputServer,
output_length: int,
stream: bool,
stream_interval: int = 1,
) -> None:
"""Stop, reconfigure response payload, and restart workers."""
server.stop()
# Wait for port to become available (old workers may linger in kernel)
if server._port is not None:
_wait_for_port_free(server.host, server._port)
server.stream = stream
server._response = build_response(output_length, stream, stream_interval)
# Reset shutdown flags and worker lists so _start_workers can re-use them
server._shutdown.clear()
server._workers.clear()
server._ready_events.clear()
server._start_workers()
# ---------------------------------------------------------------------------
# Single-run mode
# ---------------------------------------------------------------------------
def run_single(
args: argparse.Namespace,
endpoint_url: str,
server: MaxThroughputServer | None = None,
) -> None:
"""Run a single benchmark (original behavior)."""
mode = "streaming" if args.streaming else "non-streaming"
prompt_length = args.prompt_length[0]
prompt = build_prompt(prompt_length)
stream_interval = args.stream_interval[0]
mode_info = f"Mode: {mode} | Prompt length: {len(prompt)} chars"
if args.streaming and stream_interval > 1:
mode_info += f" | Stream interval: {stream_interval}"
print(mode_info)
if server:
_restart_server(server, prompt_length, args.streaming, stream_interval)
epr = (
_sse_events_per_response(prompt_length, stream_interval)
if args.streaming
else 1
)
print(f"\nStarting benchmark for {args.duration}s...")
print("=" * 70)
stats = run_benchmark(
endpoint_url=endpoint_url,
duration=args.duration,
num_workers=args.num_workers[0],
max_connections=args.max_connections[0],
prompt=prompt,
track_memory=args.track_memory,
streaming=args.streaming,
max_concurrency=args.max_concurrency,
send_batch=args.send_batch,
enable_affinity=args.pin,
sse_events_per_response=epr,
max_total_time=args.duration + 10,
)
send_elapsed, total_elapsed, send_rate, recv_rate, sse_rate, outstanding = (
_compute_derived_stats(stats)
)
print("=" * 70)
print("\nFinal Results:")
print(f" Send Duration: {send_elapsed:.2f}s")
print(f" Total Duration: {total_elapsed:.2f}s")
print(f" Total Sent: {stats.sent:,}")
print(f" Total Recv: {stats.received:,}")
print(f" Errors: {stats.errors:,}")
print(f" Outstanding: {outstanding:,}")
print(f" Send Rate: {send_rate:,.0f} req/s")
print(f" Recv Rate: {recv_rate:,.0f} resp/s")
if args.streaming:
print(f" SSE-pkts/s: {sse_rate:,.0f}")
print(f" Peak InFlight: {stats.peak_inflight:,} / {args.max_concurrency:,}")
print(f" Stall%: {_stall_pct(stats):.1f}%")
if outstanding > 0:
print(f" WARNING: {outstanding:,} queries did not complete")
# ---------------------------------------------------------------------------
# Sweep mode
# ---------------------------------------------------------------------------
def _make_sweep_result(pv: dict[str, int], stats: BenchmarkStats) -> SweepResult:
"""Build a SweepResult from param values and raw benchmark stats."""
_, _, send_rate, recv_rate, sse_rate, outstanding = _compute_derived_stats(stats)
sr = stats.send_rate_samples or []
rr = stats.recv_rate_samples or []
epr = stats.sse_events_per_response
return SweepResult(
param_values=pv,
stats=stats,
send_rate=send_rate,
recv_rate=recv_rate,
sse_rate=sse_rate,
outstanding=outstanding,
error_rate=_safe_div(stats.errors, stats.sent) * 100,
stall_pct=_stall_pct(stats),
send_rate_min=min(sr) if sr else send_rate,
send_rate_max=max(sr) if sr else send_rate,
recv_rate_min=min(rr) if rr else recv_rate,
recv_rate_max=max(rr) if rr else recv_rate,
sse_rate_min=min(rr) * epr if rr else sse_rate,
sse_rate_max=max(rr) * epr if rr else sse_rate,
)
def run_sweep(
args: argparse.Namespace,
sweeps: list[tuple[str, list[int]]],
endpoint_url: str,
server: MaxThroughputServer | None = None,
) -> None:
"""Run a parameter sweep (cartesian product), print summary, and plot.
When ``args._stream_interval_pcts`` is set, stream_interval is resolved
as a *dependent* inner loop per prompt_length rather than a static
cartesian dimension. This avoids redundant runs for small prompt_lengths
where the fractional intervals collapse (e.g. prompt_length=1 → [1]).
"""
si_pcts: list[float] | None = getattr(args, "_stream_interval_pcts", None)
sweep_names = [s[0] for s in sweeps]
sweep_values = [s[1] for s in sweeps]
combinations = list(itertools.product(*sweep_values))
default_workers = args.num_workers[0]
default_connections = args.max_connections[0]
default_prompt_length = args.prompt_length[0]
default_stream_interval = args.stream_interval[0]
# Build effective sweep info (includes stream_interval when pct-based)
if si_pcts is not None:
effective_sweep_names = [*sweep_names, "stream_interval"]
all_si: set[int] = set()
for combo in combinations:
pv = dict(zip(sweep_names, combo, strict=False))
pl: int = pv.get("prompt_length", default_prompt_length) # type: ignore[assignment]
all_si.update(_resolve_stream_intervals(pl, si_pcts))
effective_sweeps: list[tuple[str, list[int]]] = [
*sweeps,
("stream_interval", sorted(all_si)),
]
total_iterations = sum(
len(
_resolve_stream_intervals(
dict(zip(sweep_names, c, strict=False)).get(
"prompt_length",
default_prompt_length, # type: ignore[arg-type]
),
si_pcts,
)
)
for c in combinations
)
else:
effective_sweep_names = sweep_names
effective_sweeps = list(sweeps)
total_iterations = len(combinations)
mode = "streaming" if args.streaming else "non-streaming"
print(f"Mode: {mode}")
for name, vals in effective_sweeps:
suffix = ""
if name == "stream_interval" and si_pcts is not None:
pct_strs = ", ".join(f"{p:.0%}" for p in si_pcts)
suffix = f" (auto: {pct_strs} of prompt_length)"
print(f" {name} = {vals}{suffix}")
print(f"Total: {total_iterations} iterations of {args.duration}s each\n")
results: list[SweepResult] = []
last_prompt_length: int | None = None
last_stream_interval: int | None = None
iteration = 0
for combo in combinations:
pv_base = dict(zip(sweep_names, combo, strict=False))
workers: int = pv_base.get("num_workers", default_workers) # type: ignore[assignment]
connections: int = pv_base.get("max_connections", default_connections) # type: ignore[assignment]
prompt_length: int = pv_base.get("prompt_length", default_prompt_length) # type: ignore[assignment]
# Resolve stream_interval values for this prompt_length
if si_pcts is not None:
si_values = _resolve_stream_intervals(prompt_length, si_pcts)
else:
si_val: int = pv_base.get("stream_interval", default_stream_interval) # type: ignore[assignment]
si_values = [si_val]
for stream_interval in si_values:
iteration += 1
pv = {**pv_base}
if si_pcts is not None:
pv["stream_interval"] = stream_interval
label = ", ".join(f"{k}={v}" for k, v in pv.items())
print(f"\n{'='*70}")
print(f" Sweep {iteration}/{total_iterations}: {label}")
print(f"{'='*70}")
# Restart server when prompt_length or stream_interval changes
if server and (
prompt_length != last_prompt_length
or stream_interval != last_stream_interval
):
_restart_server(server, prompt_length, args.streaming, stream_interval)
last_prompt_length = prompt_length
last_stream_interval = stream_interval
prompt = build_prompt(prompt_length)
epr = (
_sse_events_per_response(prompt_length, stream_interval)
if args.streaming
else 1
)
stats = run_benchmark(
endpoint_url=endpoint_url,
duration=args.duration,
num_workers=workers,
max_connections=connections,
prompt=prompt,
track_memory=args.track_memory,
streaming=args.streaming,
max_concurrency=args.max_concurrency,
send_batch=args.send_batch,
enable_affinity=args.pin,
sse_events_per_response=epr,
max_total_time=args.duration + 10,
)
results.append(_make_sweep_result(pv, stats))
print_sweep_summary(effective_sweep_names, results, streaming=args.streaming)
generate_sweep_plot(effective_sweeps, results, args)
def print_sweep_summary(
sweep_names: list[str],
results: list[SweepResult],
streaming: bool = False,
) -> None:
"""Print a formatted summary table of sweep results."""
# Build dynamic param columns
param_headers = [f"{n:>14}" for n in sweep_names]
param_sep = " | ".join(param_headers)
sse_hdr = f" | {'SSE-pkts/s':>12}" if streaming else ""
header = (
f"{param_sep} | {'Send Rate':>12} | {'Recv Rate':>12}{sse_hdr} | "
f"{'Outstanding':>11} | {'Stall%':>7} | {'Errors':>8}"
)
width = len(header)
print(f"\n{'='*width}")
print(f"Sweep Summary: {', '.join(sweep_names)}")
print(f"{'='*width}")
print(header)
print(f"{'-'*width}")
for r in results:
param_cols = " | ".join(f"{r.param_values[n]:>14,}" for n in sweep_names)
sse_col = f" | {r.sse_rate:>12,.0f}" if streaming else ""
print(
f"{param_cols} | {r.send_rate:>12,.0f} | "
f"{r.recv_rate:>12,.0f}{sse_col} | "
f"{r.outstanding:>11,} | {r.stall_pct:>6.1f}% | {r.error_rate:>7.1f}%"
)
print(f"{'='*width}")
# ---------------------------------------------------------------------------
# Plot generation
# ---------------------------------------------------------------------------
def _plot_config(args: argparse.Namespace) -> list[str]:
"""Return list of 'key=val' strings for non-swept run parameters."""
si_pcts = getattr(args, "_stream_interval_pcts", None)
return [
f"duration={args.duration}",
f"max_concurrency={args.max_concurrency}",
*(["streaming=True"] if args.streaming else []),
*(
[f"stream_interval={args.stream_interval[0]}"]
if args.streaming and si_pcts is None and args.stream_interval[0] > 1
else []
),
*(["pin=False"] if not args.pin else []),
]
def _fmt_si(v: float) -> str:
"""Format a value with SI suffixes for annotations."""
abs_v = abs(v)
if abs_v >= 1e9:
return f"{v / 1e9:.2f}B" if v % 1e8 else f"{v / 1e9:.1f}B"