-
Notifications
You must be signed in to change notification settings - Fork 4
/
app.py
1491 lines (1238 loc) · 65 KB
/
app.py
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
"""Gradio app for the ML.ENERGY leaderboard.
Everything is in a single file. Search for `gr.Blocks` to find the place
where UI elements are actually defined.
"""
from __future__ import annotations
import copy
import json
import random
import yaml
import requests
import itertools
import contextlib
import argparse
import os
from pathlib import Path
from abc import abstractmethod
from typing import Literal, Any
from dateutil import parser, tz
import numpy as np
import gradio as gr
import pandas as pd
from spitfight.colosseum.client import ControllerClient
COLOSSEUM_UP = False
COLOSSEUM_DOWN_MESSAGE = f"<br/><h2 style='text-align: center'>The Colosseum is currently down for maintenance.</h2>"
COLOSSUMM_YOUTUBE_DEMO_EMBED_HTML = '<div style="width: 100%; min-width: 400px;"><div style="position: relative; width: 100%; overflow: hidden; padding-top: 56.25%"><p><iframe width="560" height="315" style="margin: auto; position: absolute; top: 0; left: 0; right: 0; width: 100%; height: 100%; border: none;" src="https://www.youtube.com/embed/tvNM_gLffFs?si=rW1-10pt5BffJEGH" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe><p></div></div>'
class TableManager:
"""Manages the data for the leaderboard tables for tasks."""
def __init__(self, data_dir: str) -> None:
"""Load leaderboard data from files in `data_dir`.
Expected directory structure: `data_dir/gpu_model`.
Inside the innermost (GPU) directory, there should be:
- `models.json`: JSON file that maps huggingface model IDs to model info.
Some models listed in this file may not have benchmark results.
- `model_org/model_name/*.json`: JSON files containing the benchmark results.
"""
self.data_dir = Path(data_dir)
def __str__(self) -> str:
return f"{self.__class__}(data_dir={self.data_dir})"
def _wrap_model_name(self, url: str, model_name: str) -> str:
"""Wrap the model name in an HTML anchor."""
return f'<a style="text-decoration: underline; text-decoration-style: dotted" target="_blank" href="{url}">{model_name}</a>'
def _unwrap_model_name(self, model_name: str) -> str:
"""Unwrap the model name from an HTML anchor."""
return model_name.split(">")[1].split("<")[0]
@abstractmethod
def get_tab_name(self) -> str:
"""Return the name of the leaderboard."""
@abstractmethod
def get_intro_text(self) -> str:
"""Return the introduction text to be inserted above the table."""
@abstractmethod
def get_detail_text(self, detail_mode: bool) -> str:
"""Return the detail text chunk to be inserted below the table."""
def get_benchmark_checkboxes(self) -> dict[str, list[str]]:
"""Return data for the benchmark selection checkboxes."""
return {}
def get_benchmark_sliders(self) -> dict[str, tuple[float, float, float, float]]:
"""Return data for the benchmark selection sliders.
Dictionary values are tuples of the form (min, max, step, default).
"""
return {}
@abstractmethod
def get_all_models(self) -> list[str]:
"""Return all available models."""
@abstractmethod
def set_filter_get_df(self, detail_mode: bool, *filters) -> pd.DataFrame:
"""Set the current set of filters and return the filtered DataFrame."""
class LLMTableManager(TableManager):
def __init__(self, data_dir: str, task_name: str) -> None:
"""Load leaderboard data from files in `data_dir`.
Under `data_dir`, there should be:
- `models.json`: JSON file that maps huggingface model IDs to model info.
Some models listed in this file may not have benchmark results.
- `schema.yaml`: YAML file containing the schema of the benchmark.
Then, benchmark data files are nested under `data_dir` according to the schema.
One directory hierarchy for each choice in the schema and then two more -- the
model's HuggingFace hub organization and the model name.
"""
super().__init__(data_dir)
self.task_name = task_name
# Read in the data into a Pandas DataFrame.
# Important: The ordering `self.schema` determines the directory structure.
self.schema = yaml.safe_load(open(self.data_dir / "schema.yaml"))
models: dict[str, dict[str, Any]] = json.load(
open(self.data_dir / "models.json")
)
res_df = pd.DataFrame()
for choice in itertools.product(*self.schema.values()):
result_dir = self.data_dir / "/".join(choice)
with contextlib.suppress(FileNotFoundError):
for model_id, model_info in models.items():
for file in (result_dir / model_id).glob("*.json"):
model_df = pd.DataFrame([json.load(open(file))])
# Sanity checks and standardization of schema values.
assert model_df["Model"].iloc[0] == model_id
for key, val in zip(self.schema.keys(), choice):
assert (
str(val).lower() in str(model_df[key].iloc[0]).lower()
)
model_df[key] = val
# Format the model name as an HTML anchor.
model_df["Model"] = self._wrap_model_name(model_info["url"], model_info["nickname"])
model_df["Params (B)"] = model_info["params"]
res_df = pd.concat([res_df, model_df])
if res_df.empty:
raise ValueError(
f"No benchmark JSON files were read from {self.data_dir=}."
)
# Order columns
columns = res_df.columns.to_list()
cols_to_order = ["Model", "Params (B)"]
cols_to_order.extend(self.schema.keys())
columns = cols_to_order + [col for col in columns if col not in cols_to_order]
res_df = res_df[columns]
# Order rows
res_df = res_df.sort_values(by=["Model", *self.schema.keys(), "Energy/req (J)"])
self.full_df = res_df.round(2)
# We need to set the default view separately when `gr.State` is forked.
self.set_filter_get_df(detail_mode=False)
def get_benchmark_checkboxes(self) -> dict[str, list[str]]:
return self.schema
def get_benchmark_sliders(self) -> dict[str, tuple[float, float, float, float]]:
return {"Target Average TPOT (Time Per Output Token) (s)": (0.0, 0.5, 0.01, 0.2)}
def get_all_models(self) -> list[str]:
return self.full_df["Model"].apply(self._unwrap_model_name).unique().tolist()
def set_filter_get_df(self, detail_mode: bool, *filters) -> pd.DataFrame:
"""Set the current set of filters and return the filtered DataFrame.
Filters can either be completely empty, or be a concatenated list of
choices from all checkboxes and all sliders.
"""
# If the filter is empty, we default to the first choice for each checkbox.
if not filters:
checkboxes = [choices[:1] for choices in self.schema.values()]
sliders = [slider[3] for slider in self.get_benchmark_sliders().values()]
filters = checkboxes + sliders
index = np.full(len(self.full_df), True)
# Checkboxes
for setup, choice in zip(self.schema, filters):
index = index & self.full_df[setup].isin(choice)
cur_df = self.full_df.loc[index]
# Sliders (We just have TPOT for now.)
# For each `Model`, we want to first filter out rows whose `Avg TPOT (s)` is greater than the slider value.
# Finally, only just leave the row whose `Energy/req (J)` is the smallest.
tpot_slo = filters[-1]
cur_df = (
cur_df
.groupby("Model")[cur_df.columns]
.apply(lambda x: x[x["Avg TPOT (s)"] <= tpot_slo], include_groups=True)
.sort_values(by="Energy/req (J)")
.reset_index(drop=True)
.groupby("Model")
.head(1)
)
if not detail_mode:
core_columns = ["Model", "Params (B)", "GPU", "Energy/req (J)"]
readable_name_mapping = {
"Params (B)": "Parameters (Billions)",
"GPU": "GPU model",
"Energy/req (J)": "Energy per response (Joules)",
}
cur_df = cur_df[core_columns].rename(columns=readable_name_mapping)
return cur_df
class LLMChatTableManager(LLMTableManager):
"""LLM table manager for chat tasks."""
def get_tab_name(self) -> str:
return "LLM Chat"
def get_intro_text(self) -> str:
text = """
<h2>How much energy do GenAI models consume?</h2>
<h3>LLM chatbot response generation</h3>
<p style="font-size: 16px">
Large language models (LLMs), especially the instruction-tuned ones, can generate human-like responses to chat prompts.
Using <a href="https://ml.energy/zeus">Zeus</a> for energy measurement, we created a leaderboard for LLM chat energy consumption.
</p>
<p style="font-size: 16px">
More models will be added over time. Stay tuned!
</p>
"""
return text
def get_detail_text(self, detail_mode: bool) -> str:
if detail_mode:
text = """
**TPOT (Time Per Output Token)** is the time between each token generated by LLMs as part of their response.
An average TPOT of 0.20 seconds roughly corresponds to a person reading at 240 words per minute and assuming one word is 1.3 tokens on average.
You can tweak the TPOT slider to adjust the target average TPOT for the models.
Each row corresponds to one model, given a constraint on the maximum average TPOT.
If more than one GPU types were chosen, the row shows results from the GPU with the lowest energy consumption per request.
Columns
- **Model**: The name of the model.
- **Params (B)**: Number of parameters in the model.
- **GPU**: Name of the GPU model used for benchmarking.
- **TP**: Tensor parallelism degree.
- **PP**: Pipeline parallelism degree. (TP * PP is the total number of GPUs used.)
- **Energy/req (J)**: Energy consumed per request in Joules.
- **Avg TPOT (s)**: Average time per output token in seconds.
- **Token tput (toks/s)**: Average number of tokens generated by the engine per second.
- **Avg Output Tokens**: Average number of output tokens in the LLM's response.
- **Avg BS**: Average batch size of the serving engine over time.
- **Max BS**: Maximum batch size configuration of the serving engine.
For more detailed information, please take a look at the **About** tab.
"""
else:
text = """
Columns
- **Model**: The name of the model.
- **Parameters (Billions)**: Number of parameters in the model. This is the size of the model.
- **GPU model**: Name of the GPU model used for benchmarking.
- **Energy per response (Joules)**: Energy consumed for each LLM response in Joules.
Checking "Show more technical details" above the table will reveal more detailed columns.
Also, for more detailed information, please take a look at the **About** tab.
"""
return text
class LLMCodeTableManager(LLMTableManager):
"""LLM table manager for coding tasks."""
def get_tab_name(self) -> str:
return "LLM Code"
def get_intro_text(self) -> str:
text = """
<h2>How much energy do GenAI models consume?</h2>
<h3>LLM code generation</h3>
<p style="font-size: 16px">
Large language models (LLMs) are also capable of generating code.
Using <a href="https://ml.energy/zeus">Zeus</a> for energy measurement, we created a leaderboard for the energy consumption of LLMs specifically trained for code generation.
</p>
<p style="font-size: 16px">
More models will be added over time. Stay tuned!
</p>
"""
return text
def get_detail_text(self, detail_mode: bool) -> str:
if detail_mode:
text = """
**TPOT (Time Per Output Token)** is the time between each token generated by LLMs as part of their response.
An average TPOT of 0.20 seconds roughly corresponds to a person reading at 240 words per minute and assuming one word is 1.3 tokens on average.
You can tweak the TPOT slider to adjust the target average TPOT for the models.
Each row corresponds to one model, given a constraint on the maximum average TPOT.
If more than one GPU types were chosen, the row shows results from the GPU with the lowest energy consumption per request.
Columns
- **Model**: The name of the model.
- **Params (B)**: Number of parameters in the model.
- **GPU**: Name of the GPU model used for benchmarking.
- **TP**: Tensor parallelism degree.
- **PP**: Pipeline parallelism degree. (TP * PP is the total number of GPUs used.)
- **Energy/req (J)**: Energy consumed per request in Joules.
- **Avg TPOT (s)**: Average time per output token in seconds.
- **Token tput (toks/s)**: Average number of tokens generated by the engine per second.
- **Avg Output Tokens**: Average number of output tokens in the LLM's response.
- **Avg BS**: Average batch size of the serving engine over time.
- **Max BS**: Maximum batch size configuration of the serving engine.
For more detailed information, please take a look at the **About** tab.
"""
else:
text = """
Columns
- **Model**: The name of the model.
- **Parameters (Billions)**: Number of parameters in the model. This is the size of the model.
- **GPU model**: Name of the GPU model used for benchmarking.
- **Energy per response (Joules)**: Energy consumed for each LLM response in Joules.
Checking "Show more technical details" above the table will reveal more detailed columns.
Also, for more detailed information, please take a look at the **About** tab.
"""
return text
class VLMChatTableManager(LLMTableManager):
"""VLM table manager for chat tasks."""
def get_tab_name(self) -> str:
return "VLM Visual Chat"
def get_intro_text(self) -> str:
text = """
<h2>How much energy do GenAI models consume?</h2>
<h3>VLM visual chatbot response generation</h3>
<p style="font-size: 16px">
Vision language models (VLMs) are large language models that can understand images along with text and generate human-like responses to chat prompts with images.
Using <a href="https://ml.energy/zeus">Zeus</a> for energy measurement, we created a leaderboard for VLM chat energy consumption.
</p>
<p style="font-size: 16px">
More models will be added over time. Stay tuned!
</p>
"""
return text
def get_detail_text(self, detail_mode: bool) -> str:
if detail_mode:
text = """
**TPOT (Time Per Output Token)** is the time between each token generated by LLMs as part of their response.
An average TPOT of 0.20 seconds roughly corresponds to a person reading at 240 words per minute and assuming one word is 1.3 tokens on average.
You can tweak the TPOT slider to adjust the target average TPOT for the models.
Each row corresponds to one model, given a constraint on the maximum average TPOT.
If more than one GPU types were chosen, the row shows results from the GPU with the lowest energy consumption per request.
Columns
- **Model**: The name of the model.
- **Params (B)**: Number of parameters in the model.
- **GPU**: Name of the GPU model used for benchmarking.
- **TP**: Tensor parallelism degree.
- **PP**: Pipeline parallelism degree. (TP * PP is the total number of GPUs used.)
- **Energy/req (J)**: Energy consumed per request in Joules.
- **Avg TPOT (s)**: Average time per output token in seconds.
- **Token tput (toks/s)**: Average number of tokens generated by the engine per second.
- **Avg Output Tokens**: Average number of output tokens in the LLM's response.
- **Avg BS**: Average batch size of the serving engine over time.
- **Max BS**: Maximum batch size configuration of the serving engine.
For more detailed information, please take a look at the **About** tab.
"""
else:
text = """
Columns
- **Model**: The name of the model.
- **Parameters (Billions)**: Number of parameters in the model. This is the size of the model.
- **GPU model**: Name of the GPU model used for benchmarking.
- **Energy per response (Joules)**: Energy consumed for each LLM response in Joules.
Checking "Show more technical details" above the table will reveal more detailed columns.
Also, for more detailed information, please take a look at the **About** tab.
"""
return text
class DiffusionTableManager(TableManager):
def __init__(self, data_dir: str, task_name: str) -> None:
"""Load leaderboard data from files in `data_dir`.
Under `data_dir`, there should be:
- `models.json`: JSON file that maps huggingface model IDs to model info.
Some models listed in this file may not have benchmark results.
- `schema.yaml`: YAML file containing the schema of the benchmark.
Then, benchmark data files are nested under `data_dir` according to the schema.
One directory hierarchy for each choice in the schema and then two more -- the
model's HuggingFace hub organization and the model name.
"""
super().__init__(data_dir)
self.task_name = task_name
if "to video" in task_name.lower():
self.energy_col = "Energy/video (J)"
self.energy_col_readable = "Energy per video (Joules)"
elif "to image" in task_name.lower():
self.energy_col = "Energy/image (J)"
self.energy_col_readable = "Energy per image (Joules)"
else:
raise ValueError(f"Unknown task name: {task_name=}")
# Read in the data into a Pandas DataFrame.
# Important: The ordering `self.schema` determines the directory structure.
self.schema = yaml.safe_load(open(self.data_dir / "schema.yaml"))
models: dict[str, dict[str, Any]] = json.load(
open(self.data_dir / "models.json")
)
res_df = pd.DataFrame()
for choice in itertools.product(*self.schema.values()):
result_dir = self.data_dir / "/".join(choice)
with contextlib.suppress(FileNotFoundError):
for model_id, model_info in models.items():
for file in (result_dir / model_id).glob("*.json"):
model_df = pd.DataFrame([json.load(open(file))])
# Sanity checks and standardization of schema values.
assert model_df["Model"].iloc[0] == model_id
for key, val in zip(self.schema.keys(), choice):
assert (
str(val).lower() in str(model_df[key].iloc[0]).lower()
)
model_df[key] = val
# Format the model name as an HTML anchor.
model_df["Model"] = self._wrap_model_name(model_info["url"], model_info["nickname"])
model_df["Total params"] = model_info["total_params"]
model_df["Denoising params"] = model_info["denoising_params"]
model_df["Resolution"] = model_info["resolution"]
res_df = pd.concat([res_df, model_df])
if res_df.empty:
raise ValueError(
f"No benchmark JSON files were read from {self.data_dir=}."
)
# Order columns
columns = res_df.columns.to_list()
cols_to_order = ["Model", "Denoising params", "Total params"]
cols_to_order.extend(self.schema.keys())
columns = cols_to_order + [col for col in columns if col not in cols_to_order]
res_df = res_df[columns]
# Order rows
res_df = res_df.sort_values(by=["Model", *self.schema.keys(), self.energy_col])
self.full_df = res_df.round(2)
# We need to set the default view separately when `gr.State` is forked.
self.set_filter_get_df(detail_mode=False)
def get_benchmark_checkboxes(self) -> dict[str, list[str]]:
return self.schema
def get_all_models(self) -> list[str]:
return self.full_df["Model"].apply(self._unwrap_model_name).unique().tolist()
def set_filter_get_df(self, detail_mode: bool, *filters) -> pd.DataFrame:
"""Set the current set of filters and return the filtered DataFrame.
Filters can either be completely empty, or be a concatenated list of
choices from all checkboxes and all sliders.
"""
# If the filter is empty, we default to the first choice for each key.
if not filters:
checkboxes = [choices[:1] for choices in self.schema.values()]
sliders = [slider[3] for slider in self.get_benchmark_sliders().values()]
filters = checkboxes + sliders
index = np.full(len(self.full_df), True)
# Checkboxes
for setup, choice in zip(self.schema, filters):
index = index & self.full_df[setup].isin(choice)
cur_df = self.full_df.loc[index]
# Sliders (We just have Batch latency for now.)
# For each `Model`, we want to first filter out rows whose `Batch latency (s)` is greater than the slider value.
# Finally, only just leave the row whose `Energy/image (J)` or `Energy/video (J)` is the smallest.
batch_latency = filters[-1]
cur_df = (
cur_df
.groupby("Model")[cur_df.columns]
.apply(
lambda x: x[x["Batch latency (s)"] <= batch_latency],
include_groups=True,
)
.sort_values(by=self.energy_col)
.reset_index(drop=True)
.groupby("Model")
.head(1)
)
if not detail_mode:
core_columns = ["Model", "Denoising params", "GPU", "Resolution", "Frames", self.energy_col]
readable_name_mapping = {
"Denoising params": "Denoising parameters (Billions)",
"GPU": "GPU model",
self.energy_col: self.energy_col_readable,
}
for column in cur_df.columns:
if column not in core_columns:
cur_df = cur_df.drop(column, axis=1)
cur_df = cur_df.rename(columns=readable_name_mapping)
return cur_df
class DiffusionT2ITableManager(DiffusionTableManager):
"""Diffusion table manager for text-to-image tasks."""
def get_tab_name(self) -> str:
return "Diffusion Text to image"
def get_intro_text(self) -> str:
text = """
<h2>How much energy do GenAI models consume?</h2>
<h3>Diffusion text-to-image generation</h3>
<p style="font-size: 16px">
Diffusion models generate images that align with input text prompts.
Using <a href="https://ml.energy/zeus">Zeus</a> for energy measurement, we created a leaderboard for the energy consumption of Diffusion text-to-image.
</p>
<p style="font-size: 16px">
More models will be added over time. Stay tuned!
</p>
"""
return text
def get_detail_text(self, detail_mode: bool) -> str:
if detail_mode:
text = """
Each row corresponds to one model, given a constraint on the maximum computation time for the whole batch.
If more than one GPU types were chosen, the row shows results from the GPU with the lowest energy consumption per image.
Columns
- **Model**: The name of the model.
- **Denoising params**: Number of parameters in the denosing module (e.g., UNet, Transformer).
- **Total params**: Total number of parameters in the model, including encoders and decoders.
- **GPU**: Name of the GPU model used for benchmarking.
- **Energy/image (J)**: Energy consumed per generated image in Joules.
- **Batch latency (s)**: Time taken to generate a batch of images in seconds.
- **Batch size**: Number of prompts/images in a batch.
- **Denoising steps**: Number of denoising steps used for the diffusion model.
- **Resolution**: Resolution of the generated image.
For more detailed information, please take a look at the **About** tab.
"""
else:
text = """
Columns
- **Model**: The name of the model.
- **Denoising parameters (Billions)**: Number of parameters in the diffusion model's (core) denoising module. This part of the model is run repetitively to generate gradually refine the image.
- **GPU model**: Name of the GPU model used for benchmarking.
- **Energy per image (Joules)**: Energy consumed for each generated image in Joules.
- **Resolution**: Resolution of the generated image.
Checking "Show more technical details" above the table will reveal more detailed columns.
Also, for more detailed information, please take a look at the **About** tab.
"""
return text
def get_benchmark_sliders(self) -> dict[str, tuple[float, float, float, float]]:
return {"Batch latency (s)": (0.0, 60.0, 1.0, 10.0)}
class DiffusionT2VTableManager(DiffusionTableManager):
"""Diffusion table manager for text-to-video tasks."""
def get_tab_name(self) -> str:
return "Diffusion Text to video"
def get_intro_text(self) -> str:
text = """
<h2>How much energy do GenAI models consume?</h2>
<h3>Diffusion text-to-video generation</h3>
<p style="font-size: 16px">
Diffusion models generate videos that align with input text prompts.
Using <a href="https://ml.energy/zeus">Zeus</a> for energy measurement, we created a leaderboard for the energy consumption of Diffusion text-to-video.
</p>
<p style="font-size: 16px">
More models will be added over time. Stay tuned!
</p>
"""
return text
def get_detail_text(self, detail_mode: bool) -> str:
if detail_mode:
text = """
Each row corresponds to one model, given a constraint on the maximum computation time for the whole batch.
If more than one GPU types were chosen, the row shows results from the GPU with the lowest energy consumption per video.
Columns
- **Model**: The name of the model.
- **Denoising params**: Number of parameters in the denosing module (e.g., UNet, Transformer).
- **Total params**: Total number of parameters in the model, including encoders and decoders.
- **GPU**: Name of the GPU model used for benchmarking.
- **Energy/video (J)**: Energy consumed per generated video in Joules.
- **Batch latency (s)**: Time taken to generate a batch of videos in seconds.
- **Batch size**: Number of prompts/videos in a batch.
- **Denoising steps**: Number of denoising steps used for the diffusion model.
- **Frames**: Number of frames in the generated video.
- **Resolution**: Resolution of the generated video.
For more detailed information, please take a look at the **About** tab.
"""
else:
text = """
Columns
- **Model**: The name of the model.
- **Denoising parameters (Billions)**: Number of parameters in the diffusion model's (core) denoising module. This part of the model is run repetitively to generate gradually refine the video.
- **GPU model**: Name of the GPU model used for benchmarking.
- **Energy per video (Joules)**: Energy consumed for each generated image in Joules.
- **Frames**: Number of frames in the generated video.
- **Resolution**: Resolution of the generated video.
Checking "Show more technical details" above the table will reveal more detailed columns.
Also, for more detailed information, please take a look at the **About** tab.
"""
return text
def get_benchmark_sliders(self) -> dict[str, tuple[float, float, float, float]]:
return {"Batch latency (s)": (0.0, 60.0, 1.0, 10.0)}
class DiffusionI2VTableManager(DiffusionTableManager):
"""Diffusion table manager for image-to-video tasks."""
def get_tab_name(self) -> str:
return "Diffusion Image to video"
def get_intro_text(self) -> str:
text = """
<h2>How much energy do GenAI models consume?</h2>
<h3>Diffusion image-to-video generation</h3>
<p style="font-size: 16px">
Diffusion models generate videos given an input image (and sometimes alongside with text).
Using <a href="https://ml.energy/zeus">Zeus</a> for energy measurement, we created a leaderboard for the energy consumption of Diffusion image-to-video.
</p>
<p style="font-size: 16px">
More models will be added over time. Stay tuned!
</p>
"""
return text
def get_detail_text(self, detail_mode: bool) -> str:
if detail_mode:
text = """
Each row corresponds to one model, given a constraint on the maximum computation time for the whole batch.
If more than one GPU types were chosen, the row shows results from the GPU with the lowest energy consumption per video.
Columns
- **Model**: The name of the model.
- **Denoising params**: Number of parameters in the denosing module (e.g., UNet, Transformer).
- **Total params**: Total number of parameters in the model, including encoders and decoders.
- **GPU**: Name of the GPU model used for benchmarking.
- **Energy/video (J)**: Energy consumed per generated video in Joules.
- **Batch latency (s)**: Time taken to generate a batch of videos in seconds.
- **Batch size**: Number of prompts/videos in a batch.
- **Denoising steps**: Number of denoising steps used for the diffusion model.
- **Frames**: Number of frames in the generated video.
- **Resolution**: Resolution of the generated video.
For more detailed information, please take a look at the **About** tab.
"""
else:
text = """
Columns
- **Model**: The name of the model.
- **Denoising parameters (Billions)**: Number of parameters in the diffusion model's (core) denoising module. This part of the model is run repetitively to generate gradually refine the video.
- **GPU model**: Name of the GPU model used for benchmarking.
- **Energy per video (Joules)**: Energy consumed for each generated image in Joules.
- **Frames**: Number of frames in the generated video.
- **Resolution**: Resolution of the generated video.
Checking "Show more technical details" above the table will reveal more detailed columns.
Also, for more detailed information, please take a look at the **About** tab.
"""
return text
def get_benchmark_sliders(self) -> dict[str, tuple[float, float, float, float]]:
return {"Batch latency (s)": (0.0, 120.0, 1.0, 60.0)}
class LegacyTableManager:
def __init__(self, data_dir: str) -> None:
"""Load the legacy LLM leaderboard data from CSV files in data_dir.
Inside `data_dir`, there should be:
- `models.json`: a JSON file containing information about each model.
- `schema.yaml`: a YAML file containing the schema of the benchmark.
- `score.csv`: a CSV file containing the NLP evaluation metrics of each model.
- `*_benchmark.csv`: CSV files containing the system benchmark results.
Especially, the `*_benchmark.csv` files should be named after the
parameters used in the benchmark. For example, for the CSV file that
contains benchmarking results for A100 and the chat-concise task
(see `schema.yaml`) for possible choices, the file should be named
`A100_chat-concise_benchmark.csv`.
"""
# Load and merge CSV files.
df = self._read_tables(data_dir)
# Add the #params column.
models = json.load(open(f"{data_dir}/models.json"))
df["parameters"] = df["model"].apply(lambda x: models[x]["params"])
# Make the first column (model) an HTML anchor to the model's website.
def format_model_link(model_name: str) -> str:
url = models[model_name]["url"]
nickname = models[model_name]["nickname"]
return (
f'<a style="text-decoration: underline; text-decoration-style: dotted" '
f'target="_blank" href="{url}">{nickname}</a>'
)
df["model"] = df["model"].apply(format_model_link)
# Sort by our 'energy efficiency' score.
df = df.sort_values(by="energy", ascending=True)
# The full table where all the data are.
self.full_df = df
# Default view of the table is to only show the first options.
self.set_filter_get_df()
def _read_tables(self, data_dir: str) -> pd.DataFrame:
"""Read tables."""
df_score = pd.read_csv(f"{data_dir}/score.csv")
with open(f"{data_dir}/schema.yaml") as file:
self.schema: dict[str, list] = yaml.safe_load(file)
res_df = pd.DataFrame()
# Do a cartesian product of all the choices in the schema
# and try to read the corresponding CSV files.
for choice in itertools.product(*self.schema.values()):
filepath = f"{data_dir}/{'_'.join(choice)}_benchmark.csv"
with contextlib.suppress(FileNotFoundError):
df = pd.read_csv(filepath)
for key, val in zip(self.schema.keys(), choice):
df.insert(1, key, val)
res_df = pd.concat([res_df, df])
if res_df.empty:
raise ValueError(f"No benchmark CSV files were read from {data_dir=}.")
df = pd.merge(res_df, df_score, on=["model"]).round(2)
# Order columns.
columns = df.columns.to_list()
cols_to_order = ["model"]
cols_to_order.extend(self.schema.keys())
cols_to_order.append("energy")
columns = cols_to_order + [col for col in columns if col not in cols_to_order]
df = df[columns]
# Delete rows with *any* NaN values.
df = df.dropna()
return df
def _format_msg(self, text: str) -> str:
"""Formats into HTML that prints in Monospace font."""
return f"<pre style='font-family: monospace'>{text}</pre>"
def get_dropdown(self):
columns = self.full_df.columns.tolist()[1:]
return [
gr.Dropdown(choices=columns, value="parameters", label="X"),
gr.Dropdown(choices=columns, value="energy", label="Y"),
gr.Dropdown(choices=["None", *columns], label="Z (optional)"),
]
def update_dropdown(self):
columns = self.full_df.columns.tolist()[1:]
return [
gr.Dropdown.update(choices=columns),
gr.Dropdown.update(choices=columns),
gr.Dropdown.update(choices=["None", *columns]),
]
def set_filter_get_df(self, *filters) -> pd.DataFrame:
"""Set the current set of filters and return the filtered DataFrame."""
# If the filter is empty, we default to the first choice for each key.
if not filters:
filters = [choices[:1] for choices in self.schema.values()]
index = np.full(len(self.full_df), True)
for setup, choice in zip(self.schema, filters):
index = index & self.full_df[setup].isin(choice)
self.cur_df = self.full_df.loc[index]
self.cur_index = index
return self.cur_df
def get_intro_text(self) -> str:
"""Return the leaderboard's introduction text in HTML."""
return """
<div align="center">
<h2 style="color: #23d175">This is the legacy ML.ENERGY LLM leaderboard. This will be removed at the end of this year.</h2>
</div>
<h3>How much energy do modern Large Language Models (LLMs) consume for inference?</h3>
<p style="font-size: 16px">
We used <a href="https://ml.energy/zeus">Zeus</a> to benchmark various open source LLMs in terms of how much time and energy they consume for inference.
</p>
<p style="font-size: 16px">
For more detailed information, please take a look at the <b>About</b> tab.
Every benchmark is limited in some sense -- Before you interpret the results, please take a look at the <b>Limitations</b> section there, too.
</p>
"""
# The global instance of the TableManager should only be used when
# initializing components in the Gradio interface. If the global instance
# is mutated while handling user sessions, the change will be reflected
# in every user session. Instead, the instance provided by gr.State should
# be used.
global_ltbm = LegacyTableManager("data/legacy")
global_tbms = [
LLMChatTableManager("data/llm_text_generation/chat", "Chat"),
LLMCodeTableManager("data/llm_text_generation/code", "Code"),
VLMChatTableManager("data/mllm_text_generation/chat", "Visual chat"),
DiffusionT2ITableManager("data/diffusion/text-to-image", "Text to image"),
DiffusionT2VTableManager("data/diffusion/text-to-video", "Text to video"),
DiffusionI2VTableManager("data/diffusion/image-to-video", "Image to video"),
]
# Custom JS.
# XXX: This is a hack to make the model names clickable.
# Ideally, we should set `datatype` in the constructor of `gr.DataFrame` to
# `["markdown"] + ["number"] * (len(df.columns) - 1)` and format models names
# as an HTML <a> tag. However, because we also want to dynamically add new
# columns to the table and Gradio < 4.0 does not support updating `datatype` with
# `gr.DataFrame.update` yet, we need to manually walk into the DOM and replace
# the innerHTML of the model name cells with dynamically interpreted HTML.
# Desired feature tracked at https://github.com/gradio-app/gradio/issues/3732
dataframe_update_js = f"""
function format_model_link() {{
// Iterate over the cells of the first column of the leaderboard table.
var table_element = document.querySelectorAll(".tab-leaderboard");
for (var table of table_element) {{
for (let index = 1; index <= {len(global_ltbm.full_df) + sum(len(tbm.full_df) for tbm in global_tbms)}; index++) {{
// Get the cell from `table`.
var cell = table.querySelector(`div > div > div > table > tbody > tr:nth-child(${{index}}) > td:nth-child(1) > div > span`);
// var cell = document.querySelector(
// `.tab-leaderboard > div > div > div > table > tbody > tr:nth-child(${{index}}) > td:nth-child(1) > div > span`
// );
// If nothing was found, it likely means that now the visible table has less rows
// than the full table. This happens when the user filters the table. In this case,
// we should just return.
if (cell == null) break;
// This check exists to make this function idempotent.
// Multiple changes to the Dataframe component may invoke this function,
// multiple times to the same HTML table (e.g., adding and sorting cols).
// Thus, we check whether we already formatted the model names by seeing
// whether the child of the cell is a text node. If it is not,
// it means we already parsed it into HTML, so we should just return.
if (cell.firstChild.nodeType != 3) break;
// Decode and interpret the innerHTML of the cell as HTML.
var decoded_string = new DOMParser().parseFromString(cell.innerHTML, "text/html").documentElement.textContent;
var temp = document.createElement("template");
temp.innerHTML = decoded_string;
var model_anchor = temp.content.firstChild;
// Replace the innerHTML of the cell with the interpreted HTML.
cell.replaceChildren(model_anchor);
}}
}}
// Return all arguments as is.
return arguments
}}
"""
# Custom CSS.
custom_css = """
/* Make ML.ENERGY look like a clickable logo. */
.text-logo {
color: #23d175 !important;
text-decoration: none !important;
}
/* Make the submit button the same color as the logo. */
.btn-submit {
background: #23d175 !important;
color: white !important;
border: 0 !important;
}
/* Center the plotly plot inside its container. */
.plotly > div {
margin: auto !important;
}
/* Limit the width of the first column to 300 px. */
table td:first-child,
table th:first-child {
max-width: 300px;
overflow: auto;
white-space: nowrap;
}
/* Make tab buttons larger */
.tab-nav > button {
font-size: 18px !important;
}
/* Color texts. */
.green-text {
color: #23d175 !important;
}
.red-text {
color: #ff3860 !important;
}
/* Flashing model name borders. */
@keyframes blink {
0%, 33%, 67%, 100% {
border-color: transparent;
}
17%, 50%, 83% {
border-color: #23d175;
}
}
/* Older browser compatibility */
@-webkit-keyframes blink {
0%, 33%, 67%, 100% {
border-color: transparent;
}
17%, 50%, 83% {
border-color: #23d175;
}
}
.model-name-text {
border: 2px solid transparent; /* Transparent border initially */
animation: blink 3s ease-in-out 1; /* One complete cycle of animation, lasting 3 seconds */
-webkit-animation: blink 3s ease-in-out 1; /* Older browser compatibility */
}
/* Grey out components when the Colosseum is down. */
.greyed-out {
pointer-events: none;
opacity: 0.4;
}
/* Make the Citation header larger */
#citation-header > div > span {
font-size: 16px !important;
}
/* Align everything in tables to the right. */
/* Not the best solution, but at least makes the numbers align. */
.tab-leaderboard span {
text-align: right;
}
"""
# The app will not start without a controller address set.
controller_addr = os.environ.get("COLOSSEUM_CONTROLLER_ADDR")
if controller_addr is None:
COLOSSEUM_UP = False
COLOSSEUM_DOWN_MESSAGE = "<br/><h2 style='text-align: center'>Local testing mode. Colosseum disabled.</h2>"
controller_addr = "localhost"
global_controller_client = ControllerClient(controller_addr=controller_addr, timeout=15)
# Fetch the latest update date of the leaderboard repository.
resp = requests.get("https://api.github.com/repos/ml-energy/leaderboard/commits/master")
if resp.status_code != 200: