-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathbenchmark_common.py
More file actions
2106 lines (1844 loc) · 83 KB
/
Copy pathbenchmark_common.py
File metadata and controls
2106 lines (1844 loc) · 83 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
"""Common utilities for LLM benchmarking scripts."""
import argparse
import json
import platform
import re
import subprocess
import time
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional
import matplotlib.pyplot as plt
import numpy as np
import psutil
def get_hardware_info():
"""Get hardware information for the system."""
info = {}
# Get platform info
info["platform"] = platform.platform()
info["processor"] = platform.processor()
info["machine"] = platform.machine()
# Get CPU info
info["cpu_count"] = psutil.cpu_count(logical=False)
info["cpu_count_logical"] = psutil.cpu_count(logical=True)
# Get memory info. Some macOS/Python/psutil combinations can fail inside
# host_statistics64(); keep benchmarking usable and fall back to sysctl.
try:
mem = psutil.virtual_memory()
info["memory_gb"] = round(mem.total / (1024**3), 1)
except Exception:
if platform.system() == "Darwin":
try:
result = subprocess.run(["sysctl", "-n", "hw.memsize"], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
info["memory_gb"] = round(int(result.stdout.strip()) / (1024**3), 1)
except Exception:
pass
# Try to get Mac-specific info if on macOS
if platform.system() == "Darwin":
try:
# Get Mac model info
result = subprocess.run(
["system_profiler", "SPHardwareDataType"], capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
output = result.stdout
# Extract chip info (M1, M2, M3, etc.)
chip_match = re.search(r"Chip:\s+(.+)", output)
if chip_match:
info["chip"] = chip_match.group(1).strip()
# Extract model name
model_match = re.search(r"Model Name:\s+(.+)", output)
if model_match:
info["model"] = model_match.group(1).strip()
# Extract total number of cores and breakdown
cores_match = re.search(
r"Total Number of Cores:\s+(\d+)(?:\s*\((\d+)\s+performance\s+and\s+(\d+)\s+efficiency\))?",
output,
)
if cores_match:
info["total_cores"] = int(cores_match.group(1))
# Check if we have performance and efficiency breakdown
if cores_match.group(2) and cores_match.group(3):
info["performance_cores"] = int(cores_match.group(2))
info["efficiency_cores"] = int(cores_match.group(3))
# Get GPU cores from SPDisplaysDataType
gpu_result = subprocess.run(
["system_profiler", "SPDisplaysDataType"], capture_output=True, text=True, timeout=5
)
if gpu_result.returncode == 0:
gpu_output = gpu_result.stdout
# Look for GPU cores in display data
gpu_cores_match = re.search(r"Total Number of Cores:\s+(\d+)", gpu_output)
if gpu_cores_match:
info["gpu_cores"] = int(gpu_cores_match.group(1))
except:
pass
return info
def format_hardware_string(hw_info):
"""Format hardware info into a readable string."""
parts = []
# For Mac with Apple Silicon
if "chip" in hw_info:
parts.append(hw_info["chip"])
elif "processor" in hw_info and hw_info["processor"]:
parts.append(hw_info["processor"][:50]) # Truncate long processor names
# Add memory
if "memory_gb" in hw_info:
parts.append(f"{hw_info['memory_gb']}GB RAM")
# Add CPU cores with performance/efficiency breakdown if available
if "performance_cores" in hw_info and "efficiency_cores" in hw_info:
parts.append(
f"{hw_info['total_cores']} CPU cores ({hw_info['performance_cores']}P+{hw_info['efficiency_cores']}E)"
)
elif "total_cores" in hw_info:
parts.append(f"{hw_info['total_cores']} CPU cores")
elif "cpu_count" in hw_info:
parts.append(f"{hw_info['cpu_count']} CPU cores")
# Add GPU cores for Apple Silicon
if "gpu_cores" in hw_info:
parts.append(f"{hw_info['gpu_cores']} GPU cores")
formatted = ", ".join(parts) if parts else "Unknown hardware"
# Remote endpoint: these are the benchmark client's specs, not the
# server's — label them so results don't misattribute the hardware.
if hw_info.get("role") == "client":
return f"client: {formatted}"
return formatted
def is_local_base_url(base_url: str) -> bool:
"""True when the endpoint URL points at this machine."""
import socket
from urllib.parse import urlparse
host = (urlparse(base_url).hostname or "").lower()
if host in ("127.0.0.1", "localhost", "::1", "0.0.0.0"):
return True
try:
return host in (socket.gethostname().lower(), socket.getfqdn().lower())
except OSError:
return False
def mark_client_hardware(hw_info: Dict, base_url: str) -> Dict:
"""Tag hardware info as describing the benchmark client, not the server.
For a remote endpoint the machine running this script has nothing to do
with the measured numbers — format_hardware_string() then labels it so
result folders and charts don't claim client specs as server hardware.
"""
if base_url and not is_local_base_url(base_url):
hw_info["role"] = "client"
return hw_info
def _reasoning_delta_text(reasoning_delta) -> str:
"""Normalize a reasoning delta (str, or list of str/dict parts) to text."""
if isinstance(reasoning_delta, str):
return reasoning_delta
if isinstance(reasoning_delta, list):
parts = []
for item in reasoning_delta:
if isinstance(item, dict):
text = item.get("text") or item.get("content")
if text:
parts.append(str(text))
elif isinstance(item, str):
parts.append(item)
return "".join(parts)
return ""
def warn_if_empty_stream(usage: Dict, generated_text: str, reasoning_text: str = "") -> bool:
"""Warn loudly when a stream reported tokens but carried no readable text.
This is the signature of a server streaming tokens in a delta field this
client doesn't know: every client-side timing (TTFT, prompt TPS, decode
window) silently degrades to 0/total_time. Returns True when it fired.
"""
reported = 0
if isinstance(usage, dict):
reported = usage.get("completion_tokens") or usage.get("output_tokens") or 0
if reported and not (generated_text or reasoning_text):
print(
f" WARNING: server reported {reported} completion tokens but no token text "
"was captured from the stream — the server is probably using a delta field "
"this client doesn't read. TTFT, prompt TPS and decode metrics for this row "
"are NOT trustworthy."
)
return True
return False
def stream_chat(
client,
model: str,
prompt: str,
max_tokens: int,
temperature: float = 0.0,
top_p: Optional[float] = None,
timeout: int = 3600,
chunk_hook=None,
) -> Dict[str, object]:
"""Stream one chat completion via an OpenAI-SDK client and measure it.
The one shared streaming loop for every OpenAI-compatible engine: collects
answer text, reasoning/thinking text (servers stream it as
``reasoning_content`` — DeepSeek, most local servers — or ``reasoning`` —
vLLM >= 0.23; either can be a string or a list of parts), the final
``usage`` block, and the client-side timing anchors.
``chunk_hook``, when given, is called with every raw chunk so engines can
pull server-specific extras (e.g. a top-level ``timings`` block).
Returns a dict with: ``generated_text``, ``reasoning_text``, ``usage``,
``total_time``, ``time_to_first_token`` (0.0 when no token text arrived),
``prompt_eval_duration`` (alias of TTFT — the client-side prefill proxy),
``decode_window`` (first→last token span, falling back to total-TTFT,
then total_time) and ``content_chunks`` (chunks that carried token text).
"""
request_args = {
"model": model,
"messages": [{"role": "user", "content": prompt}],
"max_tokens": max_tokens,
"temperature": temperature,
"timeout": timeout,
"stream": True,
"stream_options": {"include_usage": True},
}
if top_p is not None:
request_args["top_p"] = top_p
message_parts: List[str] = []
reasoning_parts: List[str] = []
usage: Dict = {}
content_chunks = 0
first_token_time: Optional[float] = None
last_token_time: Optional[float] = None
start_time = time.time()
stream = client.chat.completions.create(**request_args)
for chunk in stream:
if chunk_hook is not None:
chunk_hook(chunk)
choices = getattr(chunk, "choices", None)
if choices:
delta = choices[0].delta
content = getattr(delta, "content", None) or ""
reasoning = _reasoning_delta_text(
getattr(delta, "reasoning_content", None) or getattr(delta, "reasoning", None)
)
if content or reasoning:
now = time.time()
if first_token_time is None:
first_token_time = now
last_token_time = now
content_chunks += 1
if content:
message_parts.append(str(content))
if reasoning:
reasoning_parts.append(reasoning)
chunk_usage = getattr(chunk, "usage", None)
if chunk_usage:
if hasattr(chunk_usage, "model_dump"):
usage = chunk_usage.model_dump()
else:
usage = {
"prompt_tokens": getattr(chunk_usage, "prompt_tokens", 0) or 0,
"completion_tokens": getattr(chunk_usage, "completion_tokens", 0) or 0,
"total_tokens": getattr(chunk_usage, "total_tokens", 0) or 0,
}
end_time = time.time()
total_time = end_time - start_time
ttft = (first_token_time - start_time) if first_token_time else 0.0
if first_token_time and last_token_time and last_token_time > first_token_time:
decode_window = last_token_time - first_token_time
elif first_token_time:
decode_window = max(end_time - first_token_time, 0.0)
else:
decode_window = total_time
generated_text = "".join(message_parts)
reasoning_text = "".join(reasoning_parts)
warn_if_empty_stream(usage, generated_text, reasoning_text)
return {
"generated_text": generated_text,
"reasoning_text": reasoning_text,
"usage": usage,
"total_time": total_time,
"time_to_first_token": ttft,
"prompt_eval_duration": ttft,
"decode_window": decode_window,
"content_chunks": content_chunks,
}
def find_warmup_file() -> Optional[Path]:
"""Return the 0.5k.txt warmup file if it exists in the current directory."""
warmup = Path("0.5k.txt")
return warmup if warmup.exists() else None
def find_context_files(contexts_arg=None):
"""Find context files based on user input or auto-discover.
Args:
contexts_arg: Comma-separated string of context sizes or None for auto-discovery
Returns:
List of Path objects for context files, sorted by size
"""
if contexts_arg:
# User specified which contexts to run
context_sizes = [size.strip() for size in contexts_arg.split(",")]
context_files = []
for size in context_sizes:
file_path = Path(f"{size}k.txt")
if file_path.exists():
context_files.append(file_path)
else:
print(f"Warning: {file_path} not found, skipping...")
if not context_files:
print("No valid context files found from specified sizes")
return []
# Sort by size
context_files = sorted(context_files, key=lambda x: float(x.stem[:-1]))
else:
# Find all .txt files in current directory
try:
# Filter files that have a numeric prefix followed by 'k' (e.g., 0.5k.txt, 2k.txt)
def is_valid_context_file(f):
stem = f.stem
if len(stem) > 1 and stem.endswith("k"):
try:
float(stem[:-1])
return True
except ValueError:
return False
return False
context_files = sorted(
[f for f in Path(".").glob("*.txt") if is_valid_context_file(f)],
key=lambda x: float(x.stem[:-1]),
)
except:
context_files = []
if not context_files:
print("No valid context files (e.g., 2k.txt, 4k.txt) found in current directory")
return []
print(f"Will benchmark context files: {[f.name for f in context_files]}")
return context_files
def save_hardware_info(hardware_info, output_path):
"""Save hardware info to JSON file."""
with open(output_path, "w") as f:
json.dump(hardware_info, f, indent=2)
print(f"Hardware info saved to {output_path}")
def save_generated_text(result, model_name, output_path, framework=""):
"""Save generated text to a file.
Args:
result: Benchmark result dictionary
model_name: Name of the model
output_path: Path to save the file
framework: Framework name for display (e.g., "MLX", "Ollama CLI")
"""
with open(output_path, "w") as f:
f.write(f"Model: {model_name}\n")
if framework:
f.write(f"Framework: {framework}\n")
f.write(f"Context size: {result['context_size']}\n")
f.write(f"Tokens generated: {result.get('generation_tokens', 0)}\n")
# Handle different metric names
if "eval_duration" in result:
f.write(f"Generation time: {result['eval_duration']:.2f}s\n")
elif "total_time" in result:
f.write(f"Total time: {result['total_time']:.2f}s\n")
f.write(f"Generation TPS: {result.get('generation_tps', 0):.1f} t/s\n")
# Add MLX-specific metrics if present
if "peak_memory_gb" in result:
f.write(f"Peak memory: {result['peak_memory_gb']:.1f} GB\n")
reasoning_text = result.get("reasoning_text", "")
if reasoning_text:
f.write("-" * 80 + "\n")
f.write("Reasoning / thinking:\n\n")
f.write(reasoning_text + "\n\n")
f.write("-" * 80 + "\n\n")
f.write(result.get("generated_text", ""))
print(f"Generated text saved to {output_path}")
def kv_cache_bytes(cache_list) -> int:
"""Sum the byte size of an mlx-lm / mlx-vlm prompt cache list.
Each cache layer in mlx-lm exposes an ``nbytes`` property. mlx-vlm reuses
those classes but adds a few of its own (``SimpleKVCache``,
``SlidingWindowCache``, ``StaticKVCache``) that don't define ``nbytes`` —
for those we fall back to summing ``keys.nbytes + values.nbytes``.
"""
total = 0
for c in cache_list or []:
try:
total += int(c.nbytes)
continue
except (AttributeError, NotImplementedError):
pass
k = getattr(c, "keys", None)
v = getattr(c, "values", None)
if k is not None and hasattr(k, "nbytes"):
total += int(k.nbytes)
if v is not None and hasattr(v, "nbytes"):
total += int(v.nbytes)
return total
def add_throughput_metrics(result: Dict, prompt_text: str = "") -> Dict:
"""Add tokenizer-independent throughput metrics in place.
Adds five keys to ``result``:
- ``generation_utf8_bytes_per_sec`` — UTF-8 bytes of generated_text / eval_duration
- ``generation_chars_per_sec`` — Unicode code points / eval_duration
- ``prompt_utf8_bytes_per_sec`` — UTF-8 bytes of prompt_text / prompt_eval_duration
- ``prompt_chars_per_sec`` — Unicode code points / prompt_eval_duration
- ``time_per_output_token`` — eval_duration / (generation_tokens - 1), i.e. TPOT
These metrics complement the tokenizer-dependent ``*_tps`` fields and let
different tokenizers be compared on the same textual workload.
"""
# Reasoning/thinking text is generated in the same decode window but some
# engines store it separately from generated_text — count both.
gen_text = (result.get("generated_text", "") or "") + (result.get("reasoning_text", "") or "")
prompt_text = prompt_text or ""
eval_dur = result.get("eval_duration", 0) or 0
p_eval_dur = result.get("prompt_eval_duration", 0) or 0
# Fall back to deriving duration from tokens / tps when the explicit
# duration field is missing (some engines report rate but not duration).
if eval_dur <= 0:
gen_tokens = result.get("generation_tokens", 0) or 0
gen_tps = result.get("generation_tps", 0) or 0
if gen_tokens > 0 and gen_tps > 0:
eval_dur = gen_tokens / gen_tps
if p_eval_dur <= 0:
p_tokens = result.get("prompt_tokens", 0) or 0
p_tps = result.get("prompt_tps", 0) or 0
if p_tokens > 0 and p_tps > 0:
p_eval_dur = p_tokens / p_tps
gen_bytes = len(gen_text.encode("utf-8"))
gen_chars = len(gen_text)
p_bytes = len(prompt_text.encode("utf-8"))
p_chars = len(prompt_text)
result["generation_utf8_bytes_per_sec"] = gen_bytes / eval_dur if eval_dur > 0 else 0.0
result["generation_chars_per_sec"] = gen_chars / eval_dur if eval_dur > 0 else 0.0
result["prompt_utf8_bytes_per_sec"] = p_bytes / p_eval_dur if p_eval_dur > 0 else 0.0
result["prompt_chars_per_sec"] = p_chars / p_eval_dur if p_eval_dur > 0 else 0.0
# TPOT: average time per output token during decode (excluding first token).
gen_tokens = result.get("generation_tokens", 0) or 0
if eval_dur > 0 and gen_tokens > 1:
result["time_per_output_token"] = eval_dur / (gen_tokens - 1)
else:
result["time_per_output_token"] = 0.0
return result
def save_results_csv(results, csv_path, exclude_fields=None):
"""Save benchmark results to CSV, excluding specified fields.
Args:
results: List of result dictionaries
csv_path: Path to save CSV file
exclude_fields: List of field names to exclude from CSV
(default: ['generated_text', 'reasoning_text'] — multi-line text
blobs belong in the response files, not in the metrics CSV)
"""
import csv
if exclude_fields is None:
exclude_fields = ["generated_text", "reasoning_text"]
if not results:
print("Warning: No results to save to CSV")
return
with open(csv_path, "w", newline="") as f:
# Create a list of fieldnames excluding specified fields
fieldnames = [k for k in results[0].keys() if k not in exclude_fields]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
# Write rows without the excluded fields
for row in results:
csv_row = {k: v for k, v in row.items() if k not in exclude_fields}
writer.writerow(csv_row)
print(f"Results saved to {csv_path}")
def generate_xpost_text(
results, model_name, framework, hardware_info=None, perplexity=None, batch_results=None, cached_results=None
):
"""Generate X post text with results.
Args:
results: List of benchmark results
model_name: Name of the model
framework: Framework name (e.g., "Ollama API", "Ollama CLI", "MLX")
hardware_info: Hardware information dictionary
"""
xpost = f"{model_name} {framework} Benchmark Results\n"
# Add hardware info if available
if hardware_info:
hardware_str = format_hardware_string(hardware_info)
xpost += f"Hardware: {hardware_str}\n"
xpost += "\n"
total_tokens = 0
for r in sorted(results, key=lambda x: float(x["context_size"][:-1])):
# Handle N/A prompt TPS for LM Studio
if r.get("prompt_tps", 0) == 0 and "EXPERIMENTAL" in framework:
prompt_part = f"pp {r.get('prompt_tokens', 0)} tok"
else:
prompt_part = f"pp {r['prompt_tps']:.0f}"
line = f"{r['context_size']} {prompt_part} tg {r['generation_tps']:.0f} t/s"
# Add memory information if available. When both peak memory and KV
# cache are present, label both explicitly so the line stays readable.
has_kv = "kv_cache_gb" in r
if "peak_memory_gb" in r:
if has_kv:
line += f" mem {r['peak_memory_gb']:.1f}GB"
else:
line += f" {r['peak_memory_gb']:.1f}GB"
if has_kv:
line += f" kv {r['kv_cache_gb']:.2f}GB"
if "kv_cache_usage_perc" in r:
line += f" kv{r['kv_cache_usage_perc'] * 100:.0f}%"
xpost += line + "\n"
total_tokens += r.get("generation_tokens", 0)
xpost += f"\nTotal generated tokens: {total_tokens}"
if perplexity is not None:
xpost += f"\nPerplexity: {perplexity:.2f}"
if batch_results:
parts = [f"b{r['batch_size']} {r['generation_tps']:.0f}" for r in batch_results]
xpost += f"\nBatch TPS: {' '.join(parts)}"
if any("kv_cache_gb" in r for r in batch_results):
kv_parts = [f"b{r['batch_size']} {r.get('kv_cache_gb', 0):.2f}GB" for r in batch_results]
xpost += f"\nBatch KV : {' '.join(kv_parts)}"
if any("kv_cache_usage_perc" in r for r in batch_results):
kv_parts = [f"b{r['batch_size']} {r.get('kv_cache_usage_perc', 0) * 100:.0f}%" for r in batch_results]
xpost += f"\nBatch KV : {' '.join(kv_parts)}"
if cached_results:
xpost += "\n\nCached KV Cache (incremental prefill)\n"
for r in sorted(cached_results, key=lambda x: float(x["context_size"][:-1])):
if r.get("cached_tokens", 0) == 0:
continue
line = (
f"{r['context_size']} cached {r.get('cached_tokens', 0)} "
f"inc_pp {r.get('incremental_prompt_tps', 0):.0f} "
f"tg {r['generation_tps']:.0f} t/s"
)
has_kv = "kv_cache_gb" in r
if "peak_memory_gb" in r:
if has_kv:
line += f" mem {r['peak_memory_gb']:.1f}GB"
else:
line += f" {r['peak_memory_gb']:.1f}GB"
if has_kv:
line += f" kv {r['kv_cache_gb']:.2f}GB"
xpost += line + "\n"
return xpost.strip()
# Add a backward compatibility alias
generate_tweet_text = generate_xpost_text
def generate_table(
results,
model_name,
framework,
hardware_info=None,
include_memory=False,
perplexity=None,
batch_results=None,
cached_results=None,
):
"""Generate a formatted table for posting to X/Twitter.
Args:
results: List of benchmark results
model_name: Name of the model
framework: Framework name (e.g., "Ollama API", "Ollama CLI", "MLX")
hardware_info: Hardware information dictionary
include_memory: Whether to include memory column (for MLX)
"""
# Create header
table = f"{model_name} {framework} Benchmark Results\n"
# Add hardware info if available
if hardware_info:
hardware_str = format_hardware_string(hardware_info)
table += f"Hardware: {hardware_str}\n"
total_tokens = 0
if include_memory:
# Trailing memory columns render only when at least one result reports a
# non-zero value, so engines that don't expose a metric (e.g. vLLM has no
# peak VRAM) don't show an all-zero column.
trail = []
if any(r.get("peak_memory_gb", 0) > 0 for r in results):
trail.append(("Memory", 8, lambda r: f"{r.get('peak_memory_gb', 0):>6.1f} GB"))
if any("kv_cache_gb" in r for r in results):
trail.append(("KV Cache", 8, lambda r: f"{r.get('kv_cache_gb', 0):>6.2f} GB"))
if any("kv_cache_usage_perc" in r for r in results):
trail.append(("KV Cache %", 9, lambda r: f"{r.get('kv_cache_usage_perc', 0) * 100:>7.1f}%"))
base_cols = ["Context", "Prompt TPS", "Gen TPS", "Gen B/s", "Gen Ch/s", "Gen Tokens", "TPOT (ms)"]
base_widths = [7, 10, 7, 7, 8, 10, 9]
cols = base_cols + [t[0] for t in trail]
widths = base_widths + [t[1] for t in trail]
table += "\n" + " | ".join(c.rjust(w) for c, w in zip(cols, widths)) + "\n"
table += "-|-".join("-" * w for w in widths) + "\n"
for r in sorted(results, key=lambda x: float(x["context_size"][:-1])):
gen_tokens = r.get("generation_tokens", 0)
tpot_ms = r.get("time_per_output_token", 0) * 1000 # Convert to ms
# Handle N/A prompt TPS for LM Studio
if r.get("prompt_tps", 0) == 0 and "EXPERIMENTAL" in framework:
prompt_str = f"{r.get('prompt_tokens', 0)} tok"
else:
prompt_str = f"{r['prompt_tps']:>10.1f}"
parts = [
f"{r['context_size']:>7}",
prompt_str,
f"{r['generation_tps']:>7.1f}",
f"{r.get('generation_utf8_bytes_per_sec', 0):>7.1f}",
f"{r.get('generation_chars_per_sec', 0):>8.1f}",
f"{gen_tokens:>10}",
f"{tpot_ms:>8.2f}",
] + [fmt(r) for _, _, fmt in trail]
table += " | ".join(parts) + "\n"
total_tokens += gen_tokens
else:
# Check if we need special handling for LM Studio
if "EXPERIMENTAL" in framework:
table += "\nContext | Prompt Tokens | Gen TPS | Gen B/s | Gen Ch/s | Gen Tokens | TPOT (ms) | Total Time\n"
table += "--------|---------------|---------|---------|----------|------------|-----------|------------\n"
else:
table += "\nContext | Prompt TPS | Gen TPS | Gen B/s | Gen Ch/s | Gen Tokens | TPOT (ms) | Total Time\n"
table += "--------|------------|---------|---------|----------|------------|-----------|------------\n"
# Add data rows with total time
for r in sorted(results, key=lambda x: float(x["context_size"][:-1])):
total_time = r.get("total_time", r.get("wall_time", 0))
gen_tokens = r.get("generation_tokens", 0)
gen_bps = r.get("generation_utf8_bytes_per_sec", 0)
gen_chps = r.get("generation_chars_per_sec", 0)
tpot_ms = r.get("time_per_output_token", 0) * 1000 # Convert to ms
# Handle N/A prompt TPS for LM Studio
if r.get("prompt_tps", 0) == 0 and "EXPERIMENTAL" in framework:
prompt_str = f"{r.get('prompt_tokens', 0)} tok"
table += (
f"{r['context_size']:>7} | {prompt_str:>13} | {r['generation_tps']:>7.1f} | "
f"{gen_bps:>7.1f} | {gen_chps:>8.1f} | {gen_tokens:>10} | {tpot_ms:>8.2f} | {total_time:>9.1f}s\n"
)
else:
table += (
f"{r['context_size']:>7} | {r['prompt_tps']:>10.1f} | {r['generation_tps']:>7.1f} | "
f"{gen_bps:>7.1f} | {gen_chps:>8.1f} | {gen_tokens:>10} | {tpot_ms:>8.2f} | {total_time:>9.1f}s\n"
)
total_tokens += gen_tokens
table += f"\nTotal generated tokens: {total_tokens}"
if perplexity is not None:
table += f"\nPerplexity: {perplexity:.2f}"
if batch_results:
batch_has_bps = any(r.get("generation_utf8_bytes_per_sec", 0) > 0 for r in batch_results)
batch_has_ttft = any(r.get("time_to_first_token", 0) > 0 for r in batch_results)
batch_has_tpot = any(r.get("time_per_output_token", 0) > 0 for r in batch_results)
# Same all-zero suppression as the main table for batch trailing columns.
batch_trail = []
if any(r.get("peak_memory_gb", 0) > 0 for r in batch_results):
batch_trail.append(("Memory", 9, lambda r: f"{r.get('peak_memory_gb', 0):>6.1f} GB"))
if any("kv_cache_gb" in r for r in batch_results):
batch_trail.append(("KV Cache", 9, lambda r: f"{r.get('kv_cache_gb', 0):>6.2f} GB"))
if any("kv_cache_usage_perc" in r for r in batch_results):
batch_trail.append(("KV Cache %", 10, lambda r: f"{r.get('kv_cache_usage_perc', 0) * 100:>8.1f}%"))
table += "\n\nBatch Benchmark\n"
# Build header with optional Gen B/s column (only when populated by the engine)
cols = ["Batch", "Prompt TPS", "Gen TPS"]
widths = [5, 10, 7]
if batch_has_bps:
cols.append("Gen B/s")
widths.append(7)
if batch_has_ttft:
cols.append("TTFT")
widths.append(8)
if batch_has_tpot:
cols.append("TPOT")
widths.append(8)
cols += [t[0] for t in batch_trail]
widths += [t[1] for t in batch_trail]
header = " | ".join(c.rjust(w) for c, w in zip(cols, widths))
sep = "-|-".join("-" * w for w in widths)
table += header + "\n" + sep + "\n"
for r in batch_results:
parts = [
f"{r['batch_size']:>5}",
f"{r['prompt_tps']:>10.1f}",
f"{r['generation_tps']:>7.1f}",
]
if batch_has_bps:
parts.append(f"{r.get('generation_utf8_bytes_per_sec', 0):>7.1f}")
if batch_has_ttft:
ttft_ms = r.get("time_to_first_token", 0) * 1000
parts.append(f"{ttft_ms:>6.0f}ms" if ttft_ms > 0 else f"{'':>8}")
if batch_has_tpot:
tpot_ms = r.get("time_per_output_token", 0) * 1000
parts.append(f"{tpot_ms:>6.1f}ms" if tpot_ms > 0 else f"{'':>8}")
parts += [fmt(r) for _, _, fmt in batch_trail]
table += " | ".join(parts) + "\n"
if cached_results:
cached_has_kv = any("kv_cache_gb" in r for r in cached_results)
table += "\n\nCached KV Cache (incremental prefill)\n"
if cached_has_kv:
table += "Context | Total Tok | Delta Tok | Cached Tok | Inc Prefill TPS | Gen TPS | Gen B/s | KV Cache\n"
table += "--------|-----------|-----------|------------|-----------------|---------|---------|----------\n"
else:
table += "Context | Total Tok | Delta Tok | Cached Tok | Inc Prefill TPS | Gen TPS | Gen B/s\n"
table += "--------|-----------|-----------|------------|-----------------|---------|--------\n"
for r in sorted(cached_results, key=lambda x: float(x["context_size"][:-1])):
if r.get("cached_tokens", 0) == 0:
continue
row = (
f"{r['context_size']:>7} | {r['prompt_tokens']:>9} | "
f"{r.get('delta_tokens', 0):>9} | {r.get('cached_tokens', 0):>10} | "
f"{r.get('incremental_prompt_tps', 0):>15.1f} | {r['generation_tps']:>7.1f} | "
f"{r.get('generation_utf8_bytes_per_sec', 0):>7.1f}"
)
if cached_has_kv:
row += f" | {r.get('kv_cache_gb', 0):>6.2f} GB"
table += row + "\n"
return table
def _plot_throughput_panel(ax, x, context_sizes, bytes_per_sec, chars_per_sec, title):
"""Draw a throughput panel: UTF-8 bytes/sec (bars) + chars/sec (twin axis line).
Used by both create_chart_ollama and create_chart_mlx to render the
tokenizer-independent throughput metrics consistently.
"""
ax.set_title(title, fontsize=14, pad=10)
color_bytes = "#3949AB"
color_chars = "#43A047"
bars = ax.bar(x, bytes_per_sec, color=color_bytes, width=0.6, alpha=0.7, label="UTF-8 bytes/s")
if bytes_per_sec:
max_b = max(bytes_per_sec) if bytes_per_sec else 1
for bar, val in zip(bars, bytes_per_sec):
ax.text(
bar.get_x() + bar.get_width() / 2.0,
bar.get_height() + max_b * 0.02,
f"{val:.0f}",
ha="center",
va="bottom",
fontsize=9,
color=color_bytes,
)
ax.set_xticks(x)
ax.set_xticklabels(context_sizes)
ax.set_ylabel("Bytes/sec", color=color_bytes)
ax.tick_params(axis="y", labelcolor=color_bytes)
ax.set_ylim(0, max(bytes_per_sec) * 1.2 if bytes_per_sec and max(bytes_per_sec) > 0 else 1)
ax.grid(True, axis="y", alpha=0.3)
ax_right = ax.twinx()
ax_right.plot(x, chars_per_sec, "o-", color=color_chars, linewidth=2, markersize=8, label="Chars/s")
ax_right.set_ylabel("Chars/sec", color=color_chars)
ax_right.tick_params(axis="y", labelcolor=color_chars)
if chars_per_sec:
max_c = max(chars_per_sec) if chars_per_sec else 1
for i, c in enumerate(chars_per_sec):
ax_right.text(i, c + max_c * 0.02, f"{c:.0f}", ha="center", va="bottom", fontsize=8, color=color_chars)
ax_right.set_ylim(0, max(chars_per_sec) * 1.5 if max(chars_per_sec) > 0 else 1)
ax.legend(loc="upper left", fontsize=9)
ax_right.legend(loc="upper right", fontsize=9)
def create_chart_ollama(results, model_name, hardware_info, output_path="benchmark_chart.png", framework="Ollama"):
"""Create a chart for Ollama benchmarks with timing information."""
# Sort results by context size
context_sizes = []
prompt_tps = []
gen_tps = []
total_times = []
generation_tokens = []
ttft_times = []
gen_bytes_ps = []
gen_chars_ps = []
prompt_bytes_ps = []
prompt_chars_ps = []
for r in sorted(results, key=lambda x: float(x["context_size"][:-1])):
context_sizes.append(r["context_size"])
prompt_tps.append(r["prompt_tps"])
gen_tps.append(r["generation_tps"])
total_times.append(r.get("total_time", r.get("wall_time", 0)))
generation_tokens.append(r["generation_tokens"])
ttft_times.append(r.get("time_to_first_token", r.get("prompt_eval_duration", 0)))
gen_bytes_ps.append(r.get("generation_utf8_bytes_per_sec", 0))
gen_chars_ps.append(r.get("generation_chars_per_sec", 0))
prompt_bytes_ps.append(r.get("prompt_utf8_bytes_per_sec", 0))
prompt_chars_ps.append(r.get("prompt_chars_per_sec", 0))
# Create figure with six subplots (3x2 grid): existing 4 + 2 throughput panels
fig, axes = plt.subplots(3, 2, figsize=(15, 18), gridspec_kw={"hspace": 0.4, "wspace": 0.3})
ax1, ax2 = axes[0]
ax3, ax4 = axes[1]
# Throughput row: prompt on the left, generation (decode) on the right
ax_thru_prompt, ax_thru_gen = axes[2]
# Model name and hardware in title
hardware_str = format_hardware_string(hardware_info)
fig.suptitle(f"{model_name} {framework} Testing\n{hardware_str}", fontsize=16, fontweight="bold")
x = np.arange(len(context_sizes))
# First subplot - Prompt TPS
ax1.set_title("Prompt Tokens per Second", fontsize=14, pad=10)
color1 = "#2196F3" # Blue for Ollama
ax1.plot(x, prompt_tps, "o-", color=color1, linewidth=2, markersize=8)
ax1.set_ylabel("Tokens/sec", color=color1)
ax1.tick_params(axis="y", labelcolor=color1)
# Add value labels for prompt
if prompt_tps:
max_prompt = max(prompt_tps) if prompt_tps else 1
for i, p in enumerate(prompt_tps):
ax1.text(
i,
p + max_prompt * 0.03,
f"{p:.1f}",
ha="center",
va="bottom",
fontsize=9,
color=color1,
)
ax1.set_xticks(x)
ax1.set_xticklabels(context_sizes)
ax1.grid(True, alpha=0.3)
ax1.set_ylim(0, max(prompt_tps) * 1.15 if prompt_tps and max(prompt_tps) > 0 else 1)
# Second subplot - Generation TPS
ax2.set_title("Generation Tokens per Second", fontsize=14, pad=10)
color2 = "#00BCD4" # Cyan for Ollama
ax2.plot(x, gen_tps, "o-", color=color2, linewidth=2, markersize=8)
ax2.set_ylabel("Tokens/sec", color=color2)
ax2.tick_params(axis="y", labelcolor=color2)
# Add value labels for generation
if gen_tps:
max_gen = max(gen_tps) if gen_tps else 1
for i, g in enumerate(gen_tps):
ax2.text(
i,
g + max_gen * 0.03,
f"{g:.1f}",
ha="center",
va="bottom",
fontsize=9,
color=color2,
)
ax2.set_xticks(x)
ax2.set_xticklabels(context_sizes)
ax2.grid(True, alpha=0.3)
ax2.set_ylim(0, max(gen_tps) * 1.15 if gen_tps and max(gen_tps) > 0 else 1)
# Third subplot - Total Time with Tokens Generated
ax3.set_title("Total Processing Time & Tokens Generated", fontsize=14, pad=10)
# Bar chart for total time (left y-axis)
color_time = "#2196F3"
bars = ax3.bar(x, total_times, color=color_time, width=0.6, alpha=0.7, label="Total Time")
# Add value labels on bars
if total_times:
max_time = max(total_times) if total_times else 1
for i, (bar, time_val) in enumerate(zip(bars, total_times)):
height = bar.get_height()
ax3.text(
bar.get_x() + bar.get_width() / 2.0,
height + max_time * 0.02,
f"{time_val:.1f}s",
ha="center",
va="bottom",
fontsize=9,
color=color_time,
)
ax3.set_xticks(x)
ax3.set_xticklabels(context_sizes)
ax3.set_ylabel("Time (seconds)", color=color_time)
ax3.tick_params(axis="y", labelcolor=color_time)
ax3.set_ylim(0, max(total_times) * 1.2 if total_times and max(total_times) > 0 else 1)
# Create second y-axis for tokens generated
ax3_right = ax3.twinx()
color_tokens = "#FF6B35"
ax3_right.plot(
x,
generation_tokens,
"o-",
color=color_tokens,
linewidth=2,
markersize=8,
label="Tokens Generated",
)
ax3_right.set_ylabel("Tokens Generated", color=color_tokens)
ax3_right.tick_params(axis="y", labelcolor=color_tokens)
# Add value labels for tokens positioned lower than bar labels
if generation_tokens:
for i, tokens in enumerate(generation_tokens):
ax3_right.text(
i,
tokens + max(generation_tokens) * 0.02 if generation_tokens else 0,
f"{tokens}",
ha="center",
va="bottom",
fontsize=9,
color=color_tokens,
)
# Set right y-axis scale so the highest token point is positioned lower than the highest bar
max_tokens = max(generation_tokens) if generation_tokens else 1
if max_tokens > 0:
# Scale to 1.5 times the max value so the highest point appears lower
ax3_right.set_ylim(0, max_tokens * 1.5)
else:
ax3_right.set_ylim(0, 1)
# Add grid
ax3.grid(True, axis="y", alpha=0.3)
# Add legends
ax3.legend(loc="upper left")
ax3_right.legend(loc="upper right")
# Fourth subplot - Time to First Token (TTFT) and Time Per Output Token (TPOT)
ax4.set_title("Latency: TTFT (left) and TPOT (right)", fontsize=14, pad=10)
color_ttft = "#E91E63" # Pink
ax4.plot(x, ttft_times, "o-", color=color_ttft, linewidth=2, markersize=8, label="TTFT")
ax4.set_ylabel("TTFT (seconds)", color=color_ttft)
ax4.tick_params(axis="y", labelcolor=color_ttft)
# Add value labels for TTFT
if ttft_times:
max_ttft = max(ttft_times) if ttft_times else 1
for i, t in enumerate(ttft_times):
ax4.text(i, t + max_ttft * 0.03, f"{t:.2f}s", ha="center", va="bottom", fontsize=9, color=color_ttft)
ax4.set_xticks(x)
ax4.set_xticklabels(context_sizes)