compare-llama-bench.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. #!/usr/bin/env python3
  2. import logging
  3. import argparse
  4. import heapq
  5. import sys
  6. import os
  7. from glob import glob
  8. import sqlite3
  9. import json
  10. import csv
  11. from typing import Optional, Union
  12. from collections.abc import Iterator, Sequence
  13. try:
  14. import git
  15. from tabulate import tabulate
  16. except ImportError as e:
  17. print("the following Python libraries are required: GitPython, tabulate.") # noqa: NP100
  18. raise e
  19. logger = logging.getLogger("compare-llama-bench")
  20. # All llama-bench SQL fields
  21. DB_FIELDS = [
  22. "build_commit", "build_number", "cpu_info", "gpu_info", "backends", "model_filename",
  23. "model_type", "model_size", "model_n_params", "n_batch", "n_ubatch", "n_threads",
  24. "cpu_mask", "cpu_strict", "poll", "type_k", "type_v", "n_gpu_layers",
  25. "split_mode", "main_gpu", "no_kv_offload", "flash_attn", "tensor_split", "tensor_buft_overrides",
  26. "defrag_thold",
  27. "use_mmap", "embeddings", "no_op_offload", "n_prompt", "n_gen", "n_depth",
  28. "test_time", "avg_ns", "stddev_ns", "avg_ts", "stddev_ts",
  29. ]
  30. DB_TYPES = [
  31. "TEXT", "INTEGER", "TEXT", "TEXT", "TEXT", "TEXT",
  32. "TEXT", "INTEGER", "INTEGER", "INTEGER", "INTEGER", "INTEGER",
  33. "TEXT", "INTEGER", "INTEGER", "TEXT", "TEXT", "INTEGER",
  34. "TEXT", "INTEGER", "INTEGER", "INTEGER", "TEXT", "TEXT",
  35. "REAL",
  36. "INTEGER", "INTEGER", "INTEGER", "INTEGER", "INTEGER", "INTEGER",
  37. "TEXT", "INTEGER", "INTEGER", "REAL", "REAL",
  38. ]
  39. assert len(DB_FIELDS) == len(DB_TYPES)
  40. # Properties by which to differentiate results per commit:
  41. KEY_PROPERTIES = [
  42. "cpu_info", "gpu_info", "backends", "n_gpu_layers", "tensor_buft_overrides", "model_filename", "model_type",
  43. "n_batch", "n_ubatch", "embeddings", "cpu_mask", "cpu_strict", "poll", "n_threads", "type_k", "type_v",
  44. "use_mmap", "no_kv_offload", "split_mode", "main_gpu", "tensor_split", "flash_attn", "n_prompt", "n_gen", "n_depth"
  45. ]
  46. # Properties that are boolean and are converted to Yes/No for the table:
  47. BOOL_PROPERTIES = ["embeddings", "cpu_strict", "use_mmap", "no_kv_offload", "flash_attn"]
  48. # Header names for the table:
  49. PRETTY_NAMES = {
  50. "cpu_info": "CPU", "gpu_info": "GPU", "backends": "Backends", "n_gpu_layers": "GPU layers",
  51. "tensor_buft_overrides": "Tensor overrides", "model_filename": "File", "model_type": "Model", "model_size": "Model size [GiB]",
  52. "model_n_params": "Num. of par.", "n_batch": "Batch size", "n_ubatch": "Microbatch size", "embeddings": "Embeddings",
  53. "cpu_mask": "CPU mask", "cpu_strict": "CPU strict", "poll": "Poll", "n_threads": "Threads", "type_k": "K type", "type_v": "V type",
  54. "use_mmap": "Use mmap", "no_kv_offload": "NKVO", "split_mode": "Split mode", "main_gpu": "Main GPU", "tensor_split": "Tensor split",
  55. "flash_attn": "FlashAttention",
  56. }
  57. DEFAULT_SHOW = ["model_type"] # Always show these properties by default.
  58. DEFAULT_HIDE = ["model_filename"] # Always hide these properties by default.
  59. GPU_NAME_STRIP = ["NVIDIA GeForce ", "Tesla ", "AMD Radeon "] # Strip prefixes for smaller tables.
  60. MODEL_SUFFIX_REPLACE = {" - Small": "_S", " - Medium": "_M", " - Large": "_L"}
  61. DESCRIPTION = """Creates tables from llama-bench data written to multiple JSON/CSV files, a single JSONL file or SQLite database. Example usage (Linux):
  62. $ git checkout master
  63. $ make clean && make llama-bench
  64. $ ./llama-bench -o sql | sqlite3 llama-bench.sqlite
  65. $ git checkout some_branch
  66. $ make clean && make llama-bench
  67. $ ./llama-bench -o sql | sqlite3 llama-bench.sqlite
  68. $ ./scripts/compare-llama-bench.py
  69. Performance numbers from multiple runs per commit are averaged WITHOUT being weighted by the --repetitions parameter of llama-bench.
  70. """
  71. parser = argparse.ArgumentParser(
  72. description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter)
  73. help_b = (
  74. "The baseline commit to compare performance to. "
  75. "Accepts either a branch name, tag name, or commit hash. "
  76. "Defaults to latest master commit with data."
  77. )
  78. parser.add_argument("-b", "--baseline", help=help_b)
  79. help_c = (
  80. "The commit whose performance is to be compared to the baseline. "
  81. "Accepts either a branch name, tag name, or commit hash. "
  82. "Defaults to the non-master commit for which llama-bench was run most recently."
  83. )
  84. parser.add_argument("-c", "--compare", help=help_c)
  85. help_i = (
  86. "JSON/JSONL/SQLite/CSV files for comparing commits. "
  87. "Specify multiple times to use multiple input files (JSON/CSV only). "
  88. "Defaults to 'llama-bench.sqlite' in the current working directory. "
  89. "If no such file is found and there is exactly one .sqlite file in the current directory, "
  90. "that file is instead used as input."
  91. )
  92. parser.add_argument("-i", "--input", action="append", help=help_i)
  93. help_o = (
  94. "Output format for the table. "
  95. "Defaults to 'pipe' (GitHub compatible). "
  96. "Also supports e.g. 'latex' or 'mediawiki'. "
  97. "See tabulate documentation for full list."
  98. )
  99. parser.add_argument("-o", "--output", help=help_o, default="pipe")
  100. help_s = (
  101. "Columns to add to the table. "
  102. "Accepts a comma-separated list of values. "
  103. f"Legal values: {', '.join(KEY_PROPERTIES[:-3])}. "
  104. "Defaults to model name (model_type) and CPU and/or GPU name (cpu_info, gpu_info) "
  105. "plus any column where not all data points are the same. "
  106. "If the columns are manually specified, then the results for each unique combination of the "
  107. "specified values are averaged WITHOUT weighing by the --repetitions parameter of llama-bench."
  108. )
  109. parser.add_argument("--check", action="store_true", help="check if all required Python libraries are installed")
  110. parser.add_argument("-s", "--show", help=help_s)
  111. parser.add_argument("--verbose", action="store_true", help="increase output verbosity")
  112. known_args, unknown_args = parser.parse_known_args()
  113. logging.basicConfig(level=logging.DEBUG if known_args.verbose else logging.INFO)
  114. if known_args.check:
  115. # Check if all required Python libraries are installed. Would have failed earlier if not.
  116. sys.exit(0)
  117. if unknown_args:
  118. logger.error(f"Received unknown args: {unknown_args}.\n")
  119. parser.print_help()
  120. sys.exit(1)
  121. input_file = known_args.input
  122. if not input_file and os.path.exists("./llama-bench.sqlite"):
  123. input_file = ["llama-bench.sqlite"]
  124. if not input_file:
  125. sqlite_files = glob("*.sqlite")
  126. if len(sqlite_files) == 1:
  127. input_file = sqlite_files
  128. if not input_file:
  129. logger.error("Cannot find a suitable input file, please provide one.\n")
  130. parser.print_help()
  131. sys.exit(1)
  132. class LlamaBenchData:
  133. repo: Optional[git.Repo]
  134. build_len_min: int
  135. build_len_max: int
  136. build_len: int = 8
  137. builds: list[str] = []
  138. check_keys = set(KEY_PROPERTIES + ["build_commit", "test_time", "avg_ts"])
  139. def __init__(self):
  140. try:
  141. self.repo = git.Repo(".", search_parent_directories=True)
  142. except git.InvalidGitRepositoryError:
  143. self.repo = None
  144. def _builds_init(self):
  145. self.build_len = self.build_len_min
  146. def _check_keys(self, keys: set) -> Optional[set]:
  147. """Private helper method that checks against required data keys and returns missing ones."""
  148. if not keys >= self.check_keys:
  149. return self.check_keys - keys
  150. return None
  151. def find_parent_in_data(self, commit: git.Commit) -> Optional[str]:
  152. """Helper method to find the most recent parent measured in number of commits for which there is data."""
  153. heap: list[tuple[int, git.Commit]] = [(0, commit)]
  154. seen_hexsha8 = set()
  155. while heap:
  156. depth, current_commit = heapq.heappop(heap)
  157. current_hexsha8 = commit.hexsha[:self.build_len]
  158. if current_hexsha8 in self.builds:
  159. return current_hexsha8
  160. for parent in commit.parents:
  161. parent_hexsha8 = parent.hexsha[:self.build_len]
  162. if parent_hexsha8 not in seen_hexsha8:
  163. seen_hexsha8.add(parent_hexsha8)
  164. heapq.heappush(heap, (depth + 1, parent))
  165. return None
  166. def get_all_parent_hexsha8s(self, commit: git.Commit) -> Sequence[str]:
  167. """Helper method to recursively get hexsha8 values for all parents of a commit."""
  168. unvisited = [commit]
  169. visited = []
  170. while unvisited:
  171. current_commit = unvisited.pop(0)
  172. visited.append(current_commit.hexsha[:self.build_len])
  173. for parent in current_commit.parents:
  174. if parent.hexsha[:self.build_len] not in visited:
  175. unvisited.append(parent)
  176. return visited
  177. def get_commit_name(self, hexsha8: str) -> str:
  178. """Helper method to find a human-readable name for a commit if possible."""
  179. if self.repo is None:
  180. return hexsha8
  181. for h in self.repo.heads:
  182. if h.commit.hexsha[:self.build_len] == hexsha8:
  183. return h.name
  184. for t in self.repo.tags:
  185. if t.commit.hexsha[:self.build_len] == hexsha8:
  186. return t.name
  187. return hexsha8
  188. def get_commit_hexsha8(self, name: str) -> Optional[str]:
  189. """Helper method to search for a commit given a human-readable name."""
  190. if self.repo is None:
  191. return None
  192. for h in self.repo.heads:
  193. if h.name == name:
  194. return h.commit.hexsha[:self.build_len]
  195. for t in self.repo.tags:
  196. if t.name == name:
  197. return t.commit.hexsha[:self.build_len]
  198. for c in self.repo.iter_commits("--all"):
  199. if c.hexsha[:self.build_len] == name[:self.build_len]:
  200. return c.hexsha[:self.build_len]
  201. return None
  202. def builds_timestamp(self, reverse: bool = False) -> Union[Iterator[tuple], Sequence[tuple]]:
  203. """Helper method that gets rows of (build_commit, test_time) sorted by the latter."""
  204. return []
  205. def get_rows(self, properties: list[str], hexsha8_baseline: str, hexsha8_compare: str) -> Sequence[tuple]:
  206. """
  207. Helper method that gets table rows for some list of properties.
  208. Rows are created by combining those where all provided properties are equal.
  209. The resulting rows are then grouped by the provided properties and the t/s values are averaged.
  210. The returned rows are unique in terms of property combinations.
  211. """
  212. return []
  213. class LlamaBenchDataSQLite3(LlamaBenchData):
  214. connection: sqlite3.Connection
  215. cursor: sqlite3.Cursor
  216. def __init__(self):
  217. super().__init__()
  218. self.connection = sqlite3.connect(":memory:")
  219. self.cursor = self.connection.cursor()
  220. self.cursor.execute(f"CREATE TABLE test({', '.join(' '.join(x) for x in zip(DB_FIELDS, DB_TYPES))});")
  221. def _builds_init(self):
  222. if self.connection:
  223. self.build_len_min = self.cursor.execute("SELECT MIN(LENGTH(build_commit)) from test;").fetchone()[0]
  224. self.build_len_max = self.cursor.execute("SELECT MAX(LENGTH(build_commit)) from test;").fetchone()[0]
  225. if self.build_len_min != self.build_len_max:
  226. logger.warning("Data contains commit hashes of differing lengths. It's possible that the wrong commits will be compared. "
  227. "Try purging the the database of old commits.")
  228. self.cursor.execute(f"UPDATE test SET build_commit = SUBSTRING(build_commit, 1, {self.build_len_min});")
  229. builds = self.cursor.execute("SELECT DISTINCT build_commit FROM test;").fetchall()
  230. self.builds = list(map(lambda b: b[0], builds)) # list[tuple[str]] -> list[str]
  231. super()._builds_init()
  232. def builds_timestamp(self, reverse: bool = False) -> Union[Iterator[tuple], Sequence[tuple]]:
  233. data = self.cursor.execute(
  234. "SELECT build_commit, test_time FROM test ORDER BY test_time;").fetchall()
  235. return reversed(data) if reverse else data
  236. def get_rows(self, properties: list[str], hexsha8_baseline: str, hexsha8_compare: str) -> Sequence[tuple]:
  237. select_string = ", ".join(
  238. [f"tb.{p}" for p in properties] + ["tb.n_prompt", "tb.n_gen", "tb.n_depth", "AVG(tb.avg_ts)", "AVG(tc.avg_ts)"])
  239. equal_string = " AND ".join(
  240. [f"tb.{p} = tc.{p}" for p in KEY_PROPERTIES] + [
  241. f"tb.build_commit = '{hexsha8_baseline}'", f"tc.build_commit = '{hexsha8_compare}'"]
  242. )
  243. group_order_string = ", ".join([f"tb.{p}" for p in properties] + ["tb.n_gen", "tb.n_prompt", "tb.n_depth"])
  244. query = (f"SELECT {select_string} FROM test tb JOIN test tc ON {equal_string} "
  245. f"GROUP BY {group_order_string} ORDER BY {group_order_string};")
  246. return self.cursor.execute(query).fetchall()
  247. class LlamaBenchDataSQLite3File(LlamaBenchDataSQLite3):
  248. def __init__(self, data_file: str):
  249. super().__init__()
  250. self.connection.close()
  251. self.connection = sqlite3.connect(data_file)
  252. self.cursor = self.connection.cursor()
  253. self._builds_init()
  254. @staticmethod
  255. def valid_format(data_file: str) -> bool:
  256. connection = sqlite3.connect(data_file)
  257. cursor = connection.cursor()
  258. try:
  259. if cursor.execute("PRAGMA schema_version;").fetchone()[0] == 0:
  260. raise sqlite3.DatabaseError("The provided input file does not exist or is empty.")
  261. except sqlite3.DatabaseError as e:
  262. logger.debug(f'"{data_file}" is not a valid SQLite3 file.', exc_info=e)
  263. cursor = None
  264. connection.close()
  265. return True if cursor else False
  266. class LlamaBenchDataJSONL(LlamaBenchDataSQLite3):
  267. def __init__(self, data_file: str):
  268. super().__init__()
  269. with open(data_file, "r", encoding="utf-8") as fp:
  270. for i, line in enumerate(fp):
  271. parsed = json.loads(line)
  272. for k in parsed.keys() - set(DB_FIELDS):
  273. del parsed[k]
  274. if (missing_keys := self._check_keys(parsed.keys())):
  275. raise RuntimeError(f"Missing required data key(s) at line {i + 1}: {', '.join(missing_keys)}")
  276. self.cursor.execute(f"INSERT INTO test({', '.join(parsed.keys())}) VALUES({', '.join('?' * len(parsed))});", tuple(parsed.values()))
  277. self._builds_init()
  278. @staticmethod
  279. def valid_format(data_file: str) -> bool:
  280. try:
  281. with open(data_file, "r", encoding="utf-8") as fp:
  282. for line in fp:
  283. json.loads(line)
  284. break
  285. except Exception as e:
  286. logger.debug(f'"{data_file}" is not a valid JSONL file.', exc_info=e)
  287. return False
  288. return True
  289. class LlamaBenchDataJSON(LlamaBenchDataSQLite3):
  290. def __init__(self, data_files: list[str]):
  291. super().__init__()
  292. for data_file in data_files:
  293. with open(data_file, "r", encoding="utf-8") as fp:
  294. parsed = json.load(fp)
  295. for i, entry in enumerate(parsed):
  296. for k in entry.keys() - set(DB_FIELDS):
  297. del entry[k]
  298. if (missing_keys := self._check_keys(entry.keys())):
  299. raise RuntimeError(f"Missing required data key(s) at entry {i + 1}: {', '.join(missing_keys)}")
  300. self.cursor.execute(f"INSERT INTO test({', '.join(entry.keys())}) VALUES({', '.join('?' * len(entry))});", tuple(entry.values()))
  301. self._builds_init()
  302. @staticmethod
  303. def valid_format(data_files: list[str]) -> bool:
  304. if not data_files:
  305. return False
  306. for data_file in data_files:
  307. try:
  308. with open(data_file, "r", encoding="utf-8") as fp:
  309. json.load(fp)
  310. except Exception as e:
  311. logger.debug(f'"{data_file}" is not a valid JSON file.', exc_info=e)
  312. return False
  313. return True
  314. class LlamaBenchDataCSV(LlamaBenchDataSQLite3):
  315. def __init__(self, data_files: list[str]):
  316. super().__init__()
  317. for data_file in data_files:
  318. with open(data_file, "r", encoding="utf-8") as fp:
  319. for i, parsed in enumerate(csv.DictReader(fp)):
  320. keys = set(parsed.keys())
  321. for k in keys - set(DB_FIELDS):
  322. del parsed[k]
  323. if (missing_keys := self._check_keys(keys)):
  324. raise RuntimeError(f"Missing required data key(s) at line {i + 1}: {', '.join(missing_keys)}")
  325. self.cursor.execute(f"INSERT INTO test({', '.join(parsed.keys())}) VALUES({', '.join('?' * len(parsed))});", tuple(parsed.values()))
  326. self._builds_init()
  327. @staticmethod
  328. def valid_format(data_files: list[str]) -> bool:
  329. if not data_files:
  330. return False
  331. for data_file in data_files:
  332. try:
  333. with open(data_file, "r", encoding="utf-8") as fp:
  334. for parsed in csv.DictReader(fp):
  335. break
  336. except Exception as e:
  337. logger.debug(f'"{data_file}" is not a valid CSV file.', exc_info=e)
  338. return False
  339. return True
  340. bench_data = None
  341. if len(input_file) == 1:
  342. if LlamaBenchDataSQLite3File.valid_format(input_file[0]):
  343. bench_data = LlamaBenchDataSQLite3File(input_file[0])
  344. elif LlamaBenchDataJSON.valid_format(input_file):
  345. bench_data = LlamaBenchDataJSON(input_file)
  346. elif LlamaBenchDataJSONL.valid_format(input_file[0]):
  347. bench_data = LlamaBenchDataJSONL(input_file[0])
  348. elif LlamaBenchDataCSV.valid_format(input_file):
  349. bench_data = LlamaBenchDataCSV(input_file)
  350. else:
  351. if LlamaBenchDataJSON.valid_format(input_file):
  352. bench_data = LlamaBenchDataJSON(input_file)
  353. elif LlamaBenchDataCSV.valid_format(input_file):
  354. bench_data = LlamaBenchDataCSV(input_file)
  355. if not bench_data:
  356. raise RuntimeError("No valid (or some invalid) input files found.")
  357. if not bench_data.builds:
  358. raise RuntimeError(f"{input_file} does not contain any builds.")
  359. hexsha8_baseline = name_baseline = None
  360. # If the user specified a baseline, try to find a commit for it:
  361. if known_args.baseline is not None:
  362. if known_args.baseline in bench_data.builds:
  363. hexsha8_baseline = known_args.baseline
  364. if hexsha8_baseline is None:
  365. hexsha8_baseline = bench_data.get_commit_hexsha8(known_args.baseline)
  366. name_baseline = known_args.baseline
  367. if hexsha8_baseline is None:
  368. logger.error(f"cannot find data for baseline={known_args.baseline}.")
  369. sys.exit(1)
  370. # Otherwise, search for the most recent parent of master for which there is data:
  371. elif bench_data.repo is not None:
  372. hexsha8_baseline = bench_data.find_parent_in_data(bench_data.repo.heads.master.commit)
  373. if hexsha8_baseline is None:
  374. logger.error("No baseline was provided and did not find data for any master branch commits.\n")
  375. parser.print_help()
  376. sys.exit(1)
  377. else:
  378. logger.error("No baseline was provided and the current working directory "
  379. "is not part of a git repository from which a baseline could be inferred.\n")
  380. parser.print_help()
  381. sys.exit(1)
  382. name_baseline = bench_data.get_commit_name(hexsha8_baseline)
  383. hexsha8_compare = name_compare = None
  384. # If the user has specified a compare value, try to find a corresponding commit:
  385. if known_args.compare is not None:
  386. if known_args.compare in bench_data.builds:
  387. hexsha8_compare = known_args.compare
  388. if hexsha8_compare is None:
  389. hexsha8_compare = bench_data.get_commit_hexsha8(known_args.compare)
  390. name_compare = known_args.compare
  391. if hexsha8_compare is None:
  392. logger.error(f"cannot find data for compare={known_args.compare}.")
  393. sys.exit(1)
  394. # Otherwise, search for the commit for llama-bench was most recently run
  395. # and that is not a parent of master:
  396. elif bench_data.repo is not None:
  397. hexsha8s_master = bench_data.get_all_parent_hexsha8s(bench_data.repo.heads.master.commit)
  398. for (hexsha8, _) in bench_data.builds_timestamp(reverse=True):
  399. if hexsha8 not in hexsha8s_master:
  400. hexsha8_compare = hexsha8
  401. break
  402. if hexsha8_compare is None:
  403. logger.error("No compare target was provided and did not find data for any non-master commits.\n")
  404. parser.print_help()
  405. sys.exit(1)
  406. else:
  407. logger.error("No compare target was provided and the current working directory "
  408. "is not part of a git repository from which a compare target could be inferred.\n")
  409. parser.print_help()
  410. sys.exit(1)
  411. name_compare = bench_data.get_commit_name(hexsha8_compare)
  412. # If the user provided columns to group the results by, use them:
  413. if known_args.show is not None:
  414. show = known_args.show.split(",")
  415. unknown_cols = []
  416. for prop in show:
  417. if prop not in KEY_PROPERTIES[:-3]: # Last three values are n_prompt, n_gen, n_depth.
  418. unknown_cols.append(prop)
  419. if unknown_cols:
  420. logger.error(f"Unknown values for --show: {', '.join(unknown_cols)}")
  421. parser.print_usage()
  422. sys.exit(1)
  423. rows_show = bench_data.get_rows(show, hexsha8_baseline, hexsha8_compare)
  424. # Otherwise, select those columns where the values are not all the same:
  425. else:
  426. rows_full = bench_data.get_rows(KEY_PROPERTIES, hexsha8_baseline, hexsha8_compare)
  427. properties_different = []
  428. for i, kp_i in enumerate(KEY_PROPERTIES):
  429. if kp_i in DEFAULT_SHOW or kp_i in ["n_prompt", "n_gen", "n_depth"]:
  430. continue
  431. for row_full in rows_full:
  432. if row_full[i] != rows_full[0][i]:
  433. properties_different.append(kp_i)
  434. break
  435. show = []
  436. # Show CPU and/or GPU by default even if the hardware for all results is the same:
  437. if rows_full and "n_gpu_layers" not in properties_different:
  438. ngl = int(rows_full[0][KEY_PROPERTIES.index("n_gpu_layers")])
  439. if ngl != 99 and "cpu_info" not in properties_different:
  440. show.append("cpu_info")
  441. show += properties_different
  442. index_default = 0
  443. for prop in ["cpu_info", "gpu_info", "n_gpu_layers", "main_gpu"]:
  444. if prop in show:
  445. index_default += 1
  446. show = show[:index_default] + DEFAULT_SHOW + show[index_default:]
  447. for prop in DEFAULT_HIDE:
  448. try:
  449. show.remove(prop)
  450. except ValueError:
  451. pass
  452. rows_show = bench_data.get_rows(show, hexsha8_baseline, hexsha8_compare)
  453. if not rows_show:
  454. logger.error(f"No comparable data was found between {name_baseline} and {name_compare}.\n")
  455. sys.exit(1)
  456. table = []
  457. for row in rows_show:
  458. n_prompt = int(row[-5])
  459. n_gen = int(row[-4])
  460. n_depth = int(row[-3])
  461. if n_prompt != 0 and n_gen == 0:
  462. test_name = f"pp{n_prompt}"
  463. elif n_prompt == 0 and n_gen != 0:
  464. test_name = f"tg{n_gen}"
  465. else:
  466. test_name = f"pp{n_prompt}+tg{n_gen}"
  467. if n_depth != 0:
  468. test_name = f"{test_name}@d{n_depth}"
  469. # Regular columns test name avg t/s values Speedup
  470. # VVVVVVVVVVVVV VVVVVVVVV VVVVVVVVVVVVVV VVVVVVV
  471. table.append(list(row[:-5]) + [test_name] + list(row[-2:]) + [float(row[-1]) / float(row[-2])])
  472. # Some a-posteriori fixes to make the table contents prettier:
  473. for bool_property in BOOL_PROPERTIES:
  474. if bool_property in show:
  475. ip = show.index(bool_property)
  476. for row_table in table:
  477. row_table[ip] = "Yes" if int(row_table[ip]) == 1 else "No"
  478. if "model_type" in show:
  479. ip = show.index("model_type")
  480. for (old, new) in MODEL_SUFFIX_REPLACE.items():
  481. for row_table in table:
  482. row_table[ip] = row_table[ip].replace(old, new)
  483. if "model_size" in show:
  484. ip = show.index("model_size")
  485. for row_table in table:
  486. row_table[ip] = float(row_table[ip]) / 1024 ** 3
  487. if "gpu_info" in show:
  488. ip = show.index("gpu_info")
  489. for row_table in table:
  490. for gns in GPU_NAME_STRIP:
  491. row_table[ip] = row_table[ip].replace(gns, "")
  492. gpu_names = row_table[ip].split(", ")
  493. num_gpus = len(gpu_names)
  494. all_names_the_same = len(set(gpu_names)) == 1
  495. if len(gpu_names) >= 2 and all_names_the_same:
  496. row_table[ip] = f"{num_gpus}x {gpu_names[0]}"
  497. headers = [PRETTY_NAMES[p] for p in show]
  498. headers += ["Test", f"t/s {name_baseline}", f"t/s {name_compare}", "Speedup"]
  499. print(tabulate( # noqa: NP100
  500. table,
  501. headers=headers,
  502. floatfmt=".2f",
  503. tablefmt=known_args.output
  504. ))