AlexNijjar commited on
Commit
90e1a0e
1 Parent(s): 54c591b

Use gradio's built-in refresh

Browse files
Files changed (1) hide show
  1. app.py +99 -71
app.py CHANGED
@@ -1,8 +1,7 @@
1
  import json
2
  import os
3
- import time
4
  from dataclasses import dataclass
5
- from datetime import datetime
6
  from zoneinfo import ZoneInfo
7
 
8
  import bittensor as bt
@@ -31,6 +30,7 @@ bt.logging.disable_logging()
31
 
32
  runs: dict[int, list[Run]] = {}
33
  validator_identities: dict[int, str] = {}
 
34
 
35
 
36
  @dataclass
@@ -82,11 +82,15 @@ def calculate_score(baseline_generation_time: float, generation_time: float, sim
82
  return (baseline_generation_time - generation_time) * similarity_score
83
 
84
 
 
 
 
 
85
  def get_graph_entries(runs: list[Run]) -> dict[int, GraphEntry]:
86
  entries: dict[int, GraphEntry] = {}
87
 
88
  for run in reversed(runs[:GRAPH_HISTORY_DAYS]):
89
- date = datetime.strptime(run.created_at, "%Y-%m-%dT%H:%M:%SZ")
90
 
91
  for summary_key, summary_value in run.summary.items():
92
  if not summary_key.startswith("benchmarks"):
@@ -165,53 +169,6 @@ def create_graph(runs: list[Run]) -> go.Figure:
165
  return fig
166
 
167
 
168
- def create_leaderboard(runs: list[Run]) -> list[tuple]:
169
- entries: dict[int, LeaderboardEntry] = {}
170
-
171
- for run in runs:
172
- has_data = False
173
- for summary_key, summary_value in run.summary.items():
174
- if not summary_key == "benchmarks":
175
- continue
176
- for key, value in summary_value.items():
177
- has_data = True
178
-
179
- uid = int(key)
180
- generation_time = value["generation_time"]
181
- baseline_generation_time = value["baseline_generation_time"]
182
- similarity = min(1, value["similarity"])
183
-
184
- entries[uid] = LeaderboardEntry(
185
- uid=uid,
186
- winner="winner" in value,
187
- repository=run.summary["submissions"][str(uid)]["repository"],
188
- score=calculate_score(baseline_generation_time, generation_time, similarity),
189
- similarity=similarity,
190
- baseline_generation_time=baseline_generation_time,
191
- generation_time=generation_time,
192
- size=value["size"],
193
- vram_used=value["vram_used"],
194
- watts_used=value["watts_used"],
195
- hotkey=value["hotkey"],
196
- )
197
-
198
- if has_data:
199
- break
200
-
201
- return [(
202
- entry.uid,
203
- f"<span style='color: {'springgreen' if entry.winner else 'red'}'>{entry.winner}</span>",
204
- entry.repository,
205
- round(entry.score, 3),
206
- f"{entry.generation_time:.3f}s",
207
- f"{entry.similarity:.3f}",
208
- f"{entry.size / 1_000_000_000:.3f}GB",
209
- f"{entry.vram_used / 1_000_000_000:.3f}GB",
210
- f"{entry.watts_used:.3f}W",
211
- entry.hotkey,
212
- ) for entry in sorted(entries.values(), key=lambda entry: (entry.winner, entry.score), reverse=True)]
213
-
214
-
215
  def get_run_validator_uid(run: Run) -> int:
216
  json_config = json.loads(run.json_config)
217
  uid = int(json_config["uid"]["value"])
@@ -260,8 +217,17 @@ def get_validator_name(validator_uid: int) -> str:
260
 
261
 
262
  def get_choices() -> list[tuple[str, int]]:
 
 
 
 
 
263
  choices: list[tuple[str, int]] = []
264
  for uid, run in runs.items():
 
 
 
 
265
  benchmarks = dict(run[0].summary.get("benchmarks", {}))
266
  finished = any("winner" in value for value in benchmarks.values())
267
  progress_text = "Finished" if finished else "In Progress"
@@ -273,9 +239,81 @@ def refresh():
273
  metagraph.sync(subtensor=subtensor)
274
  fetch_wandb_data()
275
  fetch_identities()
276
- demo.clear()
 
 
 
277
  now = datetime.now(tz=ZoneInfo("America/New_York"))
278
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
  with demo:
280
  gr.Image(
281
  "cover.png",
@@ -291,12 +329,12 @@ def refresh():
291
  """
292
  <center>
293
  <h1 style="font-size: 50px"> SN39 EdgeMaxxing Leaderboard </h1>
294
-
295
  This leaderboard for SN39 tracks the results and top model submissions from current and previous contests.
296
  </center>
297
  """)
298
 
299
- with gr.Accordion(f"Contest #1 Submission Leader: New Dream SDXL on NVIDIA RTX 4090s (Last updated: {now.strftime('%Y-%m-%d %I:%M:%S %p')} EST)"):
300
  dropdown = gr.Dropdown(
301
  get_choices(),
302
  value=SOURCE_VALIDATOR_UID,
@@ -304,28 +342,18 @@ def refresh():
304
  label="Source Validator"
305
  )
306
 
307
- leaderboard = gr.components.Dataframe(
308
- create_leaderboard(runs[dropdown.value]),
309
- headers=["Uid", "Winner", "Model", "Score", "Gen Time", "Similarity", "Size", "VRAM Usage", "Power Usage", "Hotkey"],
310
- datatype=["number", "markdown", "markdown", "number", "markdown", "number", "markdown", "markdown", "markdown", "markdown"],
311
- elem_id="leaderboard-table",
312
- )
313
 
314
  graph = gr.Plot()
315
- demo.load(lambda uid: create_graph(runs[uid]), [dropdown], [graph])
316
-
317
  dropdown.change(lambda uid: create_graph(runs[uid]), [dropdown], [graph])
318
- dropdown.change(lambda uid: create_leaderboard(runs[uid]), [dropdown], [leaderboard])
319
 
 
320
 
321
- if __name__ == "__main__":
322
- refresh()
323
- demo.launch(prevent_thread_lock=True)
324
 
325
- while True:
326
- time.sleep(REFRESH_RATE)
327
 
328
- now = datetime.now(tz=ZoneInfo("America/New_York"))
329
- print(f"Refreshing Leaderboard at {now.strftime('%Y-%m-%d %H:%M:%S')}")
330
-
331
- refresh()
 
1
  import json
2
  import os
 
3
  from dataclasses import dataclass
4
+ from datetime import datetime, timedelta
5
  from zoneinfo import ZoneInfo
6
 
7
  import bittensor as bt
 
30
 
31
  runs: dict[int, list[Run]] = {}
32
  validator_identities: dict[int, str] = {}
33
+ last_refresh: datetime = datetime.now(tz=ZoneInfo("America/New_York"))
34
 
35
 
36
  @dataclass
 
82
  return (baseline_generation_time - generation_time) * similarity_score
83
 
84
 
85
+ def date_from_run(run: Run) -> datetime:
86
+ return datetime.strptime(run.created_at, "%Y-%m-%dT%H:%M:%SZ").astimezone(ZoneInfo("America/New_York"))
87
+
88
+
89
  def get_graph_entries(runs: list[Run]) -> dict[int, GraphEntry]:
90
  entries: dict[int, GraphEntry] = {}
91
 
92
  for run in reversed(runs[:GRAPH_HISTORY_DAYS]):
93
+ date = date_from_run(run)
94
 
95
  for summary_key, summary_value in run.summary.items():
96
  if not summary_key.startswith("benchmarks"):
 
169
  return fig
170
 
171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  def get_run_validator_uid(run: Run) -> int:
173
  json_config = json.loads(run.json_config)
174
  uid = int(json_config["uid"]["value"])
 
217
 
218
 
219
  def get_choices() -> list[tuple[str, int]]:
220
+ now = datetime.now(tz=ZoneInfo("America/New_York"))
221
+ noon = now.replace(hour=12, minute=0, second=0, microsecond=0)
222
+ if now.hour < 12:
223
+ noon -= timedelta(days=1)
224
+
225
  choices: list[tuple[str, int]] = []
226
  for uid, run in runs.items():
227
+ date = date_from_run(run[0])
228
+ if date < noon:
229
+ continue
230
+
231
  benchmarks = dict(run[0].summary.get("benchmarks", {}))
232
  finished = any("winner" in value for value in benchmarks.values())
233
  progress_text = "Finished" if finished else "In Progress"
 
239
  metagraph.sync(subtensor=subtensor)
240
  fetch_wandb_data()
241
  fetch_identities()
242
+
243
+
244
+ def get_data(validator_uid: int) -> gr.Dataframe:
245
+ global last_refresh
246
  now = datetime.now(tz=ZoneInfo("America/New_York"))
247
 
248
+ if (now - last_refresh).total_seconds() > REFRESH_RATE:
249
+ refresh()
250
+ last_refresh = now
251
+ print(f"Refreshing Leaderboard at {now.strftime('%Y-%m-%d %H:%M:%S')}")
252
+
253
+ entries: dict[int, LeaderboardEntry] = {}
254
+
255
+ for run in runs[validator_uid]:
256
+ has_data = False
257
+ for summary_key, summary_value in run.summary.items():
258
+ if not summary_key == "benchmarks":
259
+ continue
260
+ for key, value in summary_value.items():
261
+ has_data = True
262
+
263
+ uid = int(key)
264
+ generation_time = value["generation_time"]
265
+ baseline_generation_time = value["baseline_generation_time"]
266
+ similarity = min(1, value["similarity"])
267
+
268
+ entries[uid] = LeaderboardEntry(
269
+ uid=uid,
270
+ winner="winner" in value,
271
+ repository=run.summary["submissions"][str(uid)]["repository"],
272
+ score=calculate_score(baseline_generation_time, generation_time, similarity),
273
+ similarity=similarity,
274
+ baseline_generation_time=baseline_generation_time,
275
+ generation_time=generation_time,
276
+ size=value["size"],
277
+ vram_used=value["vram_used"],
278
+ watts_used=value["watts_used"],
279
+ hotkey=value["hotkey"],
280
+ )
281
+
282
+ if has_data:
283
+ break
284
+
285
+ sorted_entries = [(
286
+ entry.uid,
287
+ f"<span style='color: {'springgreen' if entry.winner else 'red'}'>{entry.winner}</span>",
288
+ entry.repository,
289
+ round(entry.score, 3),
290
+ f"{entry.generation_time:.3f}s",
291
+ f"{entry.similarity:.3f}",
292
+ f"{entry.size / 1_000_000_000:.3f}GB",
293
+ f"{entry.vram_used / 1_000_000_000:.3f}GB",
294
+ f"{entry.watts_used:.3f}W",
295
+ entry.hotkey,
296
+ ) for entry in sorted(entries.values(), key=lambda entry: (entry.winner, entry.score), reverse=True)]
297
+
298
+ return gr.Dataframe(
299
+ sorted_entries,
300
+ headers=["Uid", "Winner", "Model", "Score", "Gen Time", "Similarity", "Size", "VRAM Usage", "Power Usage", "Hotkey"],
301
+ datatype=["number", "markdown", "markdown", "number", "markdown", "number", "markdown", "markdown", "markdown", "markdown"],
302
+ label=f"Last updated: {last_refresh.strftime('%Y-%m-%d %I:%M:%S %p')} EST",
303
+ interactive=False,
304
+ )
305
+
306
+
307
+ dropdown_value = SOURCE_VALIDATOR_UID
308
+
309
+
310
+ def set_checkbox_value(value: int):
311
+ global dropdown_value
312
+ dropdown_value = value
313
+
314
+
315
+ def main():
316
+ refresh()
317
  with demo:
318
  gr.Image(
319
  "cover.png",
 
329
  """
330
  <center>
331
  <h1 style="font-size: 50px"> SN39 EdgeMaxxing Leaderboard </h1>
332
+
333
  This leaderboard for SN39 tracks the results and top model submissions from current and previous contests.
334
  </center>
335
  """)
336
 
337
+ with gr.Accordion(f"Contest #1 Submission Leader: New Dream SDXL on NVIDIA RTX 4090s"):
338
  dropdown = gr.Dropdown(
339
  get_choices(),
340
  value=SOURCE_VALIDATOR_UID,
 
342
  label="Source Validator"
343
  )
344
 
345
+ table = get_data(dropdown.value)
346
+ table.attach_load_event(lambda _: get_data(dropdown_value), REFRESH_RATE, [table])
347
+ dropdown.change(lambda uid: get_data(uid), [dropdown], [table])
 
 
 
348
 
349
  graph = gr.Plot()
350
+ graph.attach_load_event(lambda _: create_graph(runs[dropdown_value]), REFRESH_RATE, [graph])
 
351
  dropdown.change(lambda uid: create_graph(runs[uid]), [dropdown], [graph])
 
352
 
353
+ dropdown.change(set_checkbox_value, [dropdown]) # TODO hacky
354
 
355
+ demo.queue().launch()
 
 
356
 
 
 
357
 
358
+ if __name__ == "__main__":
359
+ main()