-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathaudit.py
1377 lines (1287 loc) · 54.3 KB
/
audit.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
import io
import os
import re
import csv
import ast
import uuid
import shutil
import random
import aiohttp
import yaml
import tqdm
import orjson as json
import asyncio
import tempfile
import hashlib
import backoff
import traceback
from pathlib import Path
import numpy as np
import pybase64 as base64
import sounddevice as sd
import soundfile as sf
from typing import Optional
from fiber import Keypair
from fiber.chain import weights
from fiber.chain import fetch_nodes
from fiber.networking.models import NodeWithFernet as Node
from fiber.chain.chain_utils import query_substrate
from functools import lru_cache
from datetime import datetime, timedelta
from langdetect import detect as detect_language
from term_image.image import from_file as image_from_file
from loguru import logger
from typing import AsyncGenerator
from pydantic import BaseModel
from substrateinterface import SubstrateInterface
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker, declarative_base
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy import (
Column,
String,
DateTime,
Double,
Integer,
Boolean,
BigInteger,
func,
select,
ForeignKey,
text,
)
from munch import munchify
from datasets import load_dataset
from contextlib import asynccontextmanager, contextmanager
# Database configuration.
engine = create_async_engine(
os.getenv("POSTGRESQL", "postgresql+asyncpg://user:[email protected]:5432/chutes_audit"),
echo=False,
pool_pre_ping=True,
pool_reset_on_return="rollback",
)
SessionLocal = sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
)
Base = declarative_base()
# Query and score weighting values to use for calculating incentive/setting weights.
VERSION_KEY = 69420
FEATURE_WEIGHTS = {
"compute_units": 0.45, # Total amount of compute time (compute muliplier * total time).
"invocation_count": 0.25, # Total number of invocations.
"unique_chute_count": 0.20, # Number of unique chutes over the scoring period.
"bounty_count": 0.1, # Number of bounties received (not bounty values, just counts).
}
MINER_METRICS_QUERY = """
WITH computation_rates AS (
SELECT
chute_id,
percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch from completed_at - started_at) / (metrics->>'steps')::float) as median_step_time,
percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch from completed_at - started_at) / (metrics->>'tokens')::float) as median_token_time
FROM invocations
WHERE ((metrics->>'steps' IS NOT NULL and (metrics->>'steps')::float > 0) OR (metrics->>'tokens' IS NOT NULL and (metrics->>'tokens')::float > 0)) AND started_at >= (now() AT TIME ZONE 'UTC') - interval '2 days'
GROUP BY chute_id
)
SELECT
i.miner_hotkey,
COUNT(*) as invocation_count,
COUNT(DISTINCT(i.chute_id)) AS unique_chute_count,
COUNT(CASE WHEN i.bounty > 0 THEN 1 END) AS bounty_count,
sum(
i.bounty +
i.compute_multiplier *
CASE
WHEN i.metrics->>'steps' IS NOT NULL
AND r.median_step_time IS NOT NULL
AND EXTRACT(EPOCH FROM (i.completed_at - i.started_at)) > ((i.metrics->>'steps')::float * r.median_step_time)
THEN (i.metrics->>'steps')::float * r.median_step_time
WHEN i.metrics->>'tokens' IS NOT NULL
AND r.median_token_time IS NOT NULL
AND EXTRACT(EPOCH FROM (i.completed_at - i.started_at)) > ((i.metrics->>'tokens')::float * r.median_token_time)
THEN (i.metrics->>'tokens')::float * r.median_token_time
ELSE EXTRACT(EPOCH FROM (i.completed_at - i.started_at))
END
) AS compute_units
FROM invocations i
LEFT JOIN computation_rates r ON i.chute_id = r.chute_id
WHERE i.started_at > (now() AT TIME ZONE 'UTC') - INTERVAL '7 days'
AND (i.error_message IS NULL or i.error_message = '')
AND i.miner_uid > 0
AND i.completed_at IS NOT NULL
GROUP BY i.miner_hotkey
ORDER BY compute_units DESC;
"""
MISSING_INVOCATIONS_QUERY = """
SELECT s.*
FROM synthetics s
LEFT JOIN invocations i ON s.invocation_id = i.invocation_id
WHERE (i.invocation_id IS NULL OR s.miner_hotkey != i.miner_hotkey)
AND created_at < (SELECT MAX(start_time) FROM audit_entries WHERE hotkey = '{hotkey}')
"""
MINER_SUMMARY_METRICS_QUERY = """
SELECT
COALESCE(i.miner_hotkey, m.hotkey) as hotkey,
i.invocation_count,
m.metrics_count
FROM
(SELECT miner_hotkey, COUNT(*) AS invocation_count
FROM invocations
WHERE error_message is null
GROUP BY miner_hotkey) i
FULL OUTER JOIN
(SELECT hotkey, SUM(total_count) as metrics_count
FROM miner_metrics
GROUP BY hotkey) m
ON i.miner_hotkey = m.hotkey
ORDER BY COALESCE(i.invocation_count, 0) DESC
"""
MINER_COVERAGE_QUERY = "SELECT SUM(EXTRACT(EPOCH FROM end_time - start_time)::integer) AS coverage_seconds FROM audit_entries WHERE hotkey = '{hotkey}' AND start_time >= (now() AT TIME ZONE 'UTC') - interval '169 hours'"
EXPECTED_COVERAGE = 7 * 24 * 60 * 60 - (60 * 60)
class IntegrityViolation(RuntimeError): ...
@asynccontextmanager
async def get_session() -> AsyncGenerator[AsyncSession, None]:
async with SessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
class Invocation(Base):
__tablename__ = "invocations"
parent_invocation_id = Column(String)
invocation_id = Column(String, primary_key=True)
chute_id = Column(String)
chute_user_id = Column(String)
function_name = Column(String)
user_id = Column(String)
image_id = Column(String)
image_user_id = Column(String)
instance_id = Column(String)
miner_uid = Column(Integer)
miner_hotkey = Column(String)
error_message = Column(String)
compute_multiplier = Column(Double)
bounty = Column(Integer)
metrics = Column(JSONB, nullable=True)
started_at = Column(DateTime(timezone=False))
completed_at = Column(DateTime(timezone=False), nullable=True)
class InstanceAudit(Base):
__tablename__ = "instance_audits"
audit_id = Column(String, primary_key=True)
entry_id = Column(String, ForeignKey("audit_entries.entry_id", ondelete="CASCADE"))
instance_id = Column(String)
source = Column(String)
deployment_id = Column(String)
validator = Column(String)
chute_id = Column(String)
version = Column(String)
deletion_reason = Column(String)
miner_uid = Column(Integer)
miner_hotkey = Column(String)
region = Column(String)
created_at = Column(DateTime(timezone=False))
verified_at = Column(DateTime(timezone=False))
deleted_at = Column(DateTime(timezone=False))
class MinerMetric(Base):
__tablename__ = "miner_metrics"
entry_id = Column(
String, ForeignKey("audit_entries.entry_id", ondelete="CASCADE"), primary_key=True
)
deployment_id = Column(String, primary_key=True)
function = Column(String, primary_key=True)
hotkey = Column(String)
chute_id = Column(String)
total_seconds = Column(Double)
total_count = Column(Integer)
class AuditEntry(Base):
__tablename__ = "audit_entries"
entry_id = Column(String, primary_key=True)
hotkey = Column(String)
block = Column(BigInteger)
path = Column(String)
created_at = Column(DateTime(timezone=False))
start_time = Column(DateTime(timezone=False))
end_time = Column(DateTime(timezone=False))
class Synthetic(Base):
__tablename__ = "synthetics"
parent_invocation_id = Column(String, primary_key=True)
invocation_id = Column(String)
instance_id = Column(String)
chute_id = Column(String)
miner_uid = Column(String)
miner_hotkey = Column(String)
created_at = Column(DateTime(timezone=False))
has_error = Column(Boolean, default=False)
class Target(BaseModel):
instance_id: str
invocation_id: str
child_id: str
uid: str
hotkey: str
error: str = None
class Auditor:
def __init__(self, config_path: str = None):
"""
Load config.
"""
if not config_path:
config_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "config", "config.yml"
)
logger.debug(f"Loading {config_path=}")
with open(config_path, "r") as infile:
self.config = munchify(yaml.safe_load(infile))
if self.config.synthetics.enabled:
text_config = self.config.synthetics.text
if text_config.enabled:
logger.debug(f"Loading text prompt dataset: {text_config.dataset.name}")
self.text_prompts = load_dataset(
text_config.dataset.name, **dict(text_config.dataset.options)
)
image_config = self.config.synthetics.image
if image_config.enabled:
logger.debug(f"Loading image prompt dataset: {image_config.dataset.name}")
self.image_prompts = load_dataset(
image_config.dataset.name, **dict(image_config.dataset.options)
)
self.validators = {v.hotkey: v for v in self.config.validators}
self._slock = asyncio.Lock()
self._asession = None
self._running = True
self.chutes = {}
self._substrate = SubstrateInterface(url=self.config.subtensor, ss58_format=42)
# Keypair -- only set if you are a registered validator.
self.ss58_address = None
self.keypair = None
if self.config.set_weights.enabled:
self.ss58_address = self.config.set_weights.ss58_address
self.keypair = Keypair.create_from_seed(self.config.set_weights.secret_seed)
@contextmanager
def substrate(self):
"""
Yield the substrate interface, reconnecting on error.
"""
try:
yield self._substrate
except Exception:
self._substrate = SubstrateInterface(url=self.config.subtensor, ss58_format=42)
raise
@asynccontextmanager
async def aiosession(self) -> aiohttp.ClientSession:
"""
Get or create an aiohttp session.
"""
async with self._slock:
if self._asession is None or self._asession.closed:
self._asession = aiohttp.ClientSession(
connector=aiohttp.TCPConnector(limit=100, ttl_dns_cache=120, force_close=False),
read_bufsize=64 * 1024 * 1024,
raise_for_status=False,
trust_env=True,
)
yield self._asession
def get_random_image_payload(self, model: str):
"""
Get a random request payload for diffusion chutes.
"""
prompt = self.image_prompts[random.randint(0, len(self.image_prompts))][
self.config.synthetics.image.dataset.field_name
]
prompt = prompt.lstrip('"').rstrip('"').replace('\\"', '"')
return {
"prompt": prompt,
"seed": random.randint(0, 1000000000),
"num_inference_steps": random.randint(5, 30),
}
def get_random_text_payload(self, model: str, endpoint: str = "chat"):
"""
Get a random prompt for vllm chutes.
"""
messages = self.text_prompts[random.randint(0, len(self.text_prompts))][
self.config.synthetics.text.dataset.field_name
]
messages = [
{
"role": message["role"],
"content": message["content"],
}
for message in messages
]
payload = {
"model": model,
"messages": messages,
"temperature": random.random() + 0.1,
"seed": random.randint(0, 1000000000),
"max_tokens": random.randint(10, 200),
"stream": True,
"logprobs": True,
}
if endpoint != "chat":
payload["prompt"] = payload.pop("messages")[0]["content"]
return payload
async def load_chutes(self):
"""
Load chutes from the API.
"""
logger.debug("Loading chutes from API...")
async with self.aiosession() as session:
async with session.get(
"https://api.chutes.ai/chutes/?include_public=true&limit=1000"
) as resp:
data = await resp.json()
chutes = {}
for item in data["items"]:
item["cords"] = data.get("cord_refs", {}).get(item["cord_ref_id"], [])
chutes[item["chute_id"]] = munchify(item)
self.chutes = chutes
def _get_vllm_chute(self):
"""
Randomly select a hot vllm chute.
"""
vllm_chutes = [
chute
for chute in self.chutes.values()
if chute.standard_template == "vllm"
and any([instance.active and instance.verified for instance in chute.instances])
]
if not vllm_chutes:
logger.warning("No vllm chutes hot - this is very bad and should not really happen...")
return None
return random.choice(vllm_chutes)
def _get_diffusion_chute(self):
"""
Randomly select a hot diffusion chute.
"""
diffusion_chutes = [
chute
for chute in self.chutes.values()
if chute.standard_template == "diffusion"
and any([instance.active and instance.verified for instance in chute.instances])
]
if not diffusion_chutes:
logger.warning(
"No diffusion chutes hot - this is very bad and should not really happen..."
)
return None
return random.choice(diffusion_chutes)
def _get_tts_chute(self):
"""
Randomly select a hot TTS chute.
"""
tts_chutes = [
chute
for chute in self.chutes.values()
if any([cord.path == "/speak" and not cord.stream for cord in chute.cords])
and chute.user.username == "chutes"
]
if not tts_chutes:
logger.warning("No TTS chutes hot.")
return None
return random.choice(tts_chutes)
def _get_tei_chute(self, endpoint: str = "/embed"):
"""
Get text-embeding-inference chutes.
"""
tei_chutes = [
chute
for chute in self.chutes.values()
if chute.standard_template == "tei"
and any([cord.path == endpoint for cord in chute.cords])
and chute.user.username == "chutes"
]
if not tei_chutes:
logger.warning("No TEI chutes hot.")
return None
return random.choice(tei_chutes)
def _render(self, chute, data):
if chute.standard_template == "diffusion" and self.config.synthetics.image.render:
try:
if (
chute.standard_template == "diffusion"
and isinstance(data["result"], dict)
and data["result"].get("bytes")
):
with tempfile.NamedTemporaryFile(mode="wb") as outfile:
outfile.write(base64.b64decode(data["result"]["bytes"].encode()))
outfile.flush()
image = image_from_file(outfile.name)
image.draw()
except Exception as exc:
logger.warning(f"Could not render image: {exc}")
elif chute.standard_template == "vllm" and self.config.synthetics.text.render:
try:
chunk_data = json.loads(data["result"][6:])
if chunk_data["choices"][0].get("delta"):
print(chunk_data["choices"][0]["delta"]["content"], end="", flush=True)
else:
print(chunk_data["choices"][0]["text"], end="", flush=True)
except Exception:
...
elif chute.standard_template == "tts" and self.config.synthetics.tts.render:
try:
if isinstance(data["result"], dict) and data["result"].get("bytes"):
chunk_data = base64.b64decode(data["result"]["bytes"].encode())
audio_io = io.BytesIO(chunk_data)
audio_chunk, sr = sf.read(audio_io)
if len(audio_chunk.shape) > 1:
audio_chunk = np.mean(audio_chunk, axis=1)
audio_chunk = audio_chunk.astype(np.float32)
logger.info("Playing audio, turn up your volume...")
sd.play(audio_chunk, 24000)
sd.wait()
except Exception as exc:
logger.warning(f"Error playing audio: {exc}")
elif chute.standard_template == "tei" and self.config.synthetics.embed.render:
try:
if data["result"].get("json"):
logger.info(
f"Generated a matrix with shape: {np.array(data['result']['json']).shape}"
)
except Exception as exc:
logger.warning(f"Failed to render embeddings: {exc}")
async def _perform_request(self, chute, payload, url) -> list[Synthetic]:
"""
Perform invocation request.
"""
try:
synthetics = []
async with self.aiosession() as session:
logger.info(f"Invoking {chute.name=} at {url}")
async with session.post(
url,
headers={
"Authorization": f"Bearer {self.config.synthetics.api_key}",
"X-Chutes-Trace": "true",
},
json=payload,
) as resp:
if resp.status != 200:
logger.warning(
f"Error sending synthetic to {chute.chute_id} [{chute.name}]: {resp.status=} {await resp.text()}"
)
return []
parent_id = resp.headers["X-Chutes-InvocationID"]
async for chunk_bytes in resp.content:
if not chunk_bytes or not chunk_bytes.startswith(b"data: "):
continue
data = json.loads(chunk_bytes[6:])
target = self._extract_target(data)
if (target := self._extract_target(data)) is not None:
self._debug_target(data)
synthetics.append(
Synthetic(
instance_id=target.instance_id,
parent_invocation_id=parent_id,
invocation_id=target.child_id,
chute_id=chute.chute_id,
miner_uid=target.uid,
miner_hotkey=target.hotkey,
created_at=func.timezone("UTC", func.now()),
has_error=False,
)
)
elif (target := self._extract_target_error(data)) is not None:
logger.warning(target.error)
# Can't really not be the case that we're not talking about the existing attempt.
assert target.instance_id == synthetics[-1].instance_id
assert target.invocation_id == synthetics[-1].invocation_id
synthetics[-1].has_error = True
elif data.get("error"):
logger.error(data["error"])
elif data.get("result"):
self._render(chute, data)
return synthetics
except Exception as exc:
logger.warning(f"Error performing synthetic request: {exc}")
return []
@staticmethod
def _debug_target(chunk) -> None:
"""
Show debug logging for a chute invocation target.
"""
message = "".join(
[
chunk["trace"]["timestamp"],
" ["
+ " ".join(
[
f"{key}={value}"
for key, value in chunk["trace"].items()
if key not in ("timestamp", "message")
]
),
f"]: {chunk['trace']['message']}",
]
)
logger.info(message)
@staticmethod
def _extract_target(chunk) -> Target:
"""
Extract miner info from trace messages.
"""
if not chunk.get("trace"):
return None
message = chunk["trace"].get("message")
re_match = re.search(r"query target=([^ ]+) uid=([0-9+]+) hotkey=([^ ]+)", message)
if re_match:
return Target(
invocation_id=chunk["trace"].get("invocation_id"),
child_id=chunk["trace"].get("child_id"),
instance_id=re_match.group(1),
uid=re_match.group(2),
hotkey=re_match.group(3),
)
return None
@staticmethod
def _extract_target_error(chunk) -> Target:
"""
Extract target errors from trace messages.
"""
if not chunk.get("trace"):
return None
message = chunk["trace"].get("message")
re_match = re.search(
r"error encountered while querying target=([^ ]+) uid=([0-9]+) hotkey=([^ ]+) coldkey=[^ ]+: (.*)",
message,
)
if re_match:
return Target(
invocation_id=chunk["trace"].get("invocation_id"),
child_id=chunk["trace"].get("child_id"),
instance_id=re_match.group(1),
uid=re_match.group(2),
hotkey=re_match.group(3),
error=re_match.group(4),
)
async def _perform_chat(self) -> list[Synthetic]:
"""
Perform a single chat request, with trace SSEs to see raw events.
"""
if (chute := self._get_vllm_chute()) is None:
return None
payload = self.get_random_text_payload(model=chute.name, endpoint="chat")
synthetics = await self._perform_request(
chute, payload, "https://llm.chutes.ai/v1/chat/completions"
)
print("", flush=True)
logger.info(f"Chat invocation generated {len(synthetics)} invocation objects.")
return synthetics
async def _perform_completion(self) -> list[Synthetic]:
"""
Perform a single LLM completion request, with trace SSEs to see raw events.
"""
if (chute := self._get_vllm_chute()) is None:
return []
payload = self.get_random_text_payload(model=chute.name, endpoint="completion")
synthetics = await self._perform_request(
chute, payload, "https://llm.chutes.ai/v1/completions"
)
print("", flush=True)
logger.info(f"Chat invocation generated {len(synthetics)} invocation objects.")
return synthetics
async def _perform_image(self) -> list[Synthetic]:
"""
Perform a single image generation request.
"""
if (chute := self._get_diffusion_chute()) is None:
return []
payload = self.get_random_image_payload(model=chute.name)
synthetics = await self._perform_request(
chute, payload, f"https://{chute.slug}.chutes.ai/generate"
)
logger.info(f"Image generation request generated {len(synthetics)} invocation objects.")
return synthetics
async def _perform_tts(self) -> list[Synthetic]:
"""
Perform a single text-to-speech request.
"""
if (chute := self._get_tts_chute()) is None:
return []
while text := self.get_random_image_payload(model=chute.name)["prompt"][:1000]:
try:
language = detect_language(text)
if language == "en":
break
except Exception:
...
chute.standard_template = "tts"
payload = {"text": text}
if chute.name == "Kokoro-82M":
payload["voice"] = random.choice(
[
"af",
"af_bella",
"af_sarah",
"am_adam",
"am_michael",
"bf_emma",
"bf_isabella",
"bm_george",
"bm_lewis",
"af_nicole",
"af_sky",
]
)
synthetics = await self._perform_request(
chute, payload, f"https://{chute.slug}.chutes.ai/speak"
)
logger.info(f"TTS generation request generated {len(synthetics)} invocation objects.")
return synthetics
async def _perform_embedding(self) -> list[Synthetic]:
"""
Perform a single text embedding request.
"""
if (chute := self._get_tei_chute("/embed")) is None:
return []
text = self.get_random_image_payload(model=chute.name)["prompt"][:500]
payload = {"inputs": [text]}
synthetics = await self._perform_request(
chute, payload, f"https://{chute.slug}.chutes.ai/embed"
)
logger.info(f"Text embedding request generated {len(synthetics)} invocation objects.")
return synthetics
async def perform_synthetic(self):
"""
Send a single, random synthetic request.
"""
await self.load_chutes()
# Randomly select a task to perform.
task_type = random.choice(
[
"chat",
"completion",
"image",
"tts",
"embedding",
]
)
logger.info(f"Attempting to perform synthetic task: {task_type=}")
synthetics = await getattr(self, f"_perform_{task_type}")()
if not synthetics:
return
async with get_session() as session:
for synthetic in synthetics:
session.add(synthetic)
await session.commit()
logger.success(f"Tracked {len(synthetics)} new synthetic records from {task_type} request")
@lru_cache(maxsize=1024)
def get_block_hash(self, block):
"""
Get a block (number) hash.
"""
with self.substrate() as substrate:
return substrate.get_block_hash(block)
def get_block_commit(self, block, who):
"""
Given a block number, fetch all set_commitment events.
"""
logger.info(f"Attempting to process {block=}")
with self.substrate() as substrate:
block_hash = self.get_block_hash(block)
commitment = substrate.query(
module="Commitments",
storage_function="CommitmentOf",
params=[64, who],
block_hash=block_hash,
)
if commitment:
for c in commitment.value.get("info", {}).get("fields"):
if "Sha256" in c:
return c["Sha256"][2:]
logger.warning(f"Failed to get commit sha256 for {block=} from {who}")
return None
def check_audit_report_integrity(self, record, path, content):
"""
Check a single audit report's sha256 compared to the set_commitment call's checksum.
"""
calculated = hashlib.sha256(content).hexdigest()
try:
committed = self.get_block_commit(record.block, record.hotkey)
except Exception as exc:
if "unknown Block: State already discarded" in str(exc):
logger.warning(
f"State already discarded for block {record.block}, unable to verify!"
)
return True
if not committed:
logger.warning(
f"Could not find commitment for hotkey {record.hotkey} on netuid 64 in block {record.block}"
)
if record.hotkey in self.validators:
return False
return True
if committed != calculated:
if record.hotkey in self.validators:
logger.error(
f"Validator committed checksum does not match calculated checksum: {calculated} vs {committed} -> {record}"
)
return False
else:
logger.warning(
f"Miner committed checksum does not match calculated checksum: {calculated} vs {committed} -> {record}"
)
# Miners could try to be malicous here so we'll treat this as a warning (perhaps we can set lower weights too?)
logger.success(
f"Verified commitment from {record.hotkey} in block {record.block} matches sha256: {calculated}"
)
return True
@backoff.on_exception(
backoff.constant,
Exception,
jitter=None,
interval=10,
max_tries=7,
)
async def download_and_check_one(self, db_record) -> str:
"""
Download and verify a single audit report (and the associated CSV exports if from validator).
"""
# Download the report locally.
path = Path(os.path.join("reports", db_record.entry_id, db_record.path)).resolve()
try:
path.relative_to(os.path.dirname(os.path.abspath(__file__)))
except ValueError:
raise ValueError(f"Path {db_record.path} attempts to escape base directory!")
path.parent.mkdir(parents=True, exist_ok=True)
audit_content = None
csv_path = None
data = None
async with self.aiosession() as session:
async with session.get(
"https://api.chutes.ai/audit/download", params={"path": db_record.path}
) as resp:
with open(path, "wb") as outfile:
audit_content = await resp.read()
outfile.write(audit_content)
data = json.loads(audit_content)
# Also need to download the CSV reports if it's from a validator.
if db_record.hotkey in self.validators:
vali_url = self.validators[db_record.hotkey]["url"]
inv = data.get("csv_exports", {}).get("invocations")
if inv:
logger.info(
f"Downloading and verifying CSV export of invocations: {inv['path']}"
)
remote_path = inv["path"].replace("invocations/", "/invocations/exports/")
csv_path = Path(
os.path.join("reports", db_record.entry_id, inv["path"])
).resolve()
try:
path.relative_to(os.path.dirname(os.path.abspath(__file__)))
except ValueError:
raise ValueError(
f"Path {db_record.path} attempts to escape base directory!"
)
csv_path.parent.mkdir(parents=True, exist_ok=True)
async with session.get(f"{vali_url}/{remote_path}") as csv_resp:
csv_content = await csv_resp.read()
calculated = hashlib.sha256(csv_content).hexdigest()
if calculated != inv["sha256"]:
raise IntegrityViolation(
f"CSV export {remote_path} of validator: {vali_url} does not match!"
)
with open(csv_path, "wb") as outfile:
outfile.write(csv_content)
logger.success(
f"Successfully downloaded CSV report data from {remote_path}"
)
# Now we can compare the sha256 of the report to the commitment on chain.
logger.success(
f"Successfully download audit data between {db_record.start_time} and {db_record.end_time} "
f"for hotkey {db_record.hotkey} committed in block {db_record.block}, now verifying..."
)
if not self.check_audit_report_integrity(db_record, path, audit_content):
raise IntegrityViolation(
f"Commitment on chain does not match downloaded report! {db_record.record_id}"
)
return data, csv_path
async def load_invocations(self, session, csv_path):
"""
Populate our local database with invocations from the CSV exports.
"""
logger.info(f"Inserting invocation records from {csv_path}")
total = 0
with open(csv_path, "r") as infile:
reader = csv.DictReader(infile)
batch = []
for row in reader:
row_data = dict(row)
row_data.update(
{
"miner_uid": int(row["miner_uid"]),
"compute_multiplier": float(row["compute_multiplier"]),
"bounty": int(row["bounty"]),
"started_at": datetime.fromisoformat(row["started_at"].rstrip("Z")).replace(
tzinfo=None
),
}
)
if row["completed_at"]:
row_data.update(
{
"completed_at": datetime.fromisoformat(
row["completed_at"].rstrip("Z")
).replace(tzinfo=None)
}
)
else:
row_data["completed_at"] = None
for key in row_data:
if isinstance(row_data[key], str) and not row_data[key].strip():
row_data[key] = None
if row.get("metrics"):
try:
row_data["metrics"] = ast.literal_eval(row["metrics"])
except ValueError as exc:
logger.warning(f"Error parsing metrics: {exc}: {row['metrics']}")
else:
row_data["metrics"] = None
batch.append(row_data)
total += 1
if len(batch) == 100:
bulk_insert = pg_insert(Invocation).values(batch).on_conflict_do_nothing()
await session.execute(bulk_insert)
batch = []
if batch:
bulk_insert = pg_insert(Invocation).values(batch).on_conflict_do_nothing()
await session.execute(bulk_insert)
await session.commit()
if total:
logger.success(f"Successfully loaded {total} invocations from {csv_path}")
async def load_audit_entries(self, record, audit_data):
"""
Load the deployment audit history from the report.
"""
key = "instance_audit" if record.hotkey in self.validators else "deployment_audit"
total = 0
for item in audit_data.get(key, []):
try:
item["audit_id"] = str(
uuid.uuid5(
uuid.NAMESPACE_OID,
":".join(
[
json.dumps(item).decode(),
record.entry_id,
record.hotkey,
]
),
)
)
item["entry_id"] = record.entry_id
audit = InstanceAudit(**item)
audit.source = "validator" if record.hotkey in self.validators else "miner"
audit.created_at = datetime.fromisoformat(audit.created_at.rstrip("Z")).replace(
tzinfo=None
)
if audit.verified_at:
audit.verified_at = datetime.fromisoformat(
audit.verified_at.rstrip("Z")
).replace(tzinfo=None)
if audit.deleted_at:
audit.deleted_at = datetime.fromisoformat(audit.deleted_at.rstrip("Z")).replace(
tzinfo=None
)
if audit.miner_uid is not None:
audit.miner_uid = int(audit.miner_uid)
async with get_session() as session:
session.add(audit)
await session.commit()
total += 1
except Exception as exc:
logger.error(
f"Error populating instance audit data from {record.hotkey} {record.entry_id=}: {exc}"
)
logger.error(item)
if total:
logger.success(
f"Populated {total} instance audit records for {record.hotkey} in {record.entry_id=}"
)
else:
logger.info(
f"No new instance audit records to process for {record.hotkey} in {record.entry_id=}"
)
async def load_miner_metrics(self, record, audit_data):
"""
Load the miner-reported metrics for a given report.
"""
total = 0
for item in audit_data.get("prometheus_metrics", []):
try:
async with get_session() as session:
item["entry_id"] = record.entry_id
item["hotkey"] = record.hotkey
session.add(MinerMetric(**item))
await session.commit()
total += 1
except Exception as exc:
logger.error(
f"Error populating miner-reported metrics from {record.hotkey} {record.entry_id=}: {exc}"
)
if total:
logger.success(
f"Populated {total} self-reported chute metric records for {record.hotkey} in {record.entry_id=}"
)
else:
logger.info(
f"No self-reported chute metric records for {record.hotkey} in {record.entry_id=}"
)
async def get_weights_to_set(
self,
hotkeys_to_node_ids: Optional[dict[str, int]] = None,
) -> tuple[list[int], list[float]] | None:
"""
Get weights to set from the invocation data.
"""
if not hotkeys_to_node_ids:
with self.substrate() as substrate:
all_nodes = fetch_nodes.get_nodes_for_netuid(substrate, 64)
hotkeys_to_node_ids = {node.hotkey: node.node_id for node in all_nodes}