forked from Datura-ai/cortex.t
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiff.diff
1774 lines (1674 loc) · 71.4 KB
/
diff.diff
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
diff --git a/cortext/__init__.py b/cortext/__init__.py
index d52e2d5..348a394 100644
--- a/cortext/__init__.py
+++ b/cortext/__init__.py
@@ -19,7 +19,7 @@
# version must stay on line 22
-__version__ = "4.0.6"
+__version__ = "4.0.4"
version_split = __version__.split(".")
__spec_version__ = (
(1000 * int(version_split[0]))
@@ -27,7 +27,7 @@ __spec_version__ = (
+ (1 * int(version_split[2]))
)
-u64_max = 2 ** 64 - 9
+u64_max = 2 ** 64 - 10
__weights_version__ = u64_max
import os
@@ -36,7 +36,7 @@ from typing import Union
from openai import AsyncOpenAI
-from cortext.protocol import StreamPrompting, Embeddings, ImageResponse, IsAlive
+from cortext.protocol import StreamPrompting, TextPrompting, Embeddings, ImageResponse, IsAlive
load_dotenv()
try:
@@ -3768,4 +3768,4 @@ IMAGE_THEMES = [
]
-ALL_SYNAPSE_TYPE = Union[StreamPrompting, Embeddings, ImageResponse, IsAlive]
+ALL_SYNAPSE_TYPE = Union[StreamPrompting, TextPrompting, Embeddings, ImageResponse, IsAlive]
diff --git a/cortext/protocol.py b/cortext/protocol.py
index 4fec337..bea6ba7 100644
--- a/cortext/protocol.py
+++ b/cortext/protocol.py
@@ -1,3 +1,4 @@
+from enum import Enum
from typing import AsyncIterator, Dict, List, Optional, Union
import bittensor as bt
import pydantic
@@ -14,9 +15,6 @@ class IsAlive(bt.Synapse):
)
-class Bandwidth(bt.Synapse):
- bandwidth_rpm: Optional[Dict[str, int]] = None
-
class ImageResponse(bt.Synapse):
""" A class to represent the response for an image-related request. """
# https://platform.stability.ai/docs/api-reference#tag/v1generation/operation/textToImage
@@ -322,14 +320,95 @@ class StreamPrompting(bt.StreamingSynapse):
"axon": extract_info("bt_header_axon"),
"messages": self.messages,
"completion": self.completion,
- "provider": self.provider,
- "model": self.model,
- "seed": self.seed,
- "max_tokens": self.max_tokens,
- "temperature": self.temperature,
- "top_p": self.top_p,
- "top_k": self.top_k,
- "timeout": self.timeout,
- "streaming": self.streaming,
- "uid": self.uid,
- }
\ No newline at end of file
+ }
+
+
+class TextPrompting(bt.Synapse):
+ messages: List[Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, str]]]]]]] = pydantic.Field(
+ ...,
+ title="Messages",
+ description="A list of messages in the StreamPrompting scenario, "
+ "each containing a role and content. Immutable.",
+ allow_mutation=False,
+ )
+
+ required_hash_fields: List[str] = pydantic.Field(
+ ["messages"],
+ title="Required Hash Fields",
+ description="A list of required fields for the hash.",
+ allow_mutation=False,
+ )
+
+ seed: int = pydantic.Field(
+ default="1234",
+ title="Seed",
+ description="Seed for text generation. This attribute is immutable and cannot be updated.",
+ )
+
+ temperature: float = pydantic.Field(
+ default=0.0001,
+ title="Temperature",
+ description="Temperature for text generation. "
+ "This attribute is immutable and cannot be updated.",
+ )
+
+ max_tokens: int = pydantic.Field(
+ default=2048,
+ title="Max Tokens",
+ description="Max tokens for text generation. "
+ "This attribute is immutable and cannot be updated.",
+ )
+
+ top_p: float = pydantic.Field(
+ default=0.001,
+ title="Top_p",
+ description="Top_p for text generation. The sampler will pick one of "
+ "the top p percent tokens in the logit distirbution. "
+ "This attribute is immutable and cannot be updated.",
+ )
+
+ top_k: int = pydantic.Field(
+ default=1,
+ title="Top_k",
+ description="Top_k for text generation. Sampler will pick one of "
+ "the k most probablistic tokens in the logit distribtion. "
+ "This attribute is immutable and cannot be updated.",
+ )
+
+ completion: str = pydantic.Field(
+ None,
+ title="Completion",
+ description="Completion status of the current StreamPrompting object. "
+ "This attribute is mutable and can be updated.",
+ )
+
+ provider: str = pydantic.Field(
+ default="OpenAI",
+ title="Provider",
+ description="The provider to use when calling for your response. "
+ "Options: OpenAI, Anthropic, Gemini, Groq, Bedrock",
+ )
+
+ model: str = pydantic.Field(
+ default="gpt-3.5-turbo",
+ title="model",
+ description="The model to use when calling provider for your response.",
+ )
+
+ uid: int = pydantic.Field(
+ default=3,
+ title="uid",
+ description="The UID to send the streaming synapse to",
+ )
+
+ timeout: int = pydantic.Field(
+ default=60,
+ title="timeout",
+ description="The timeout for the dendrite of the streaming synapse",
+ )
+
+ streaming: bool = pydantic.Field(
+ default=True,
+ title="streaming",
+ description="whether to stream the output",
+ )
diff --git a/cortext/reward.py b/cortext/reward.py
index 24bd52b..f5c4a78 100644
--- a/cortext/reward.py
+++ b/cortext/reward.py
@@ -24,8 +24,13 @@ hf_logging.set_verbosity_error()
import re
import io
import torch
+import openai
+import typing
+import difflib
import asyncio
+import logging
import aiohttp
+import requests
import traceback
import numpy as np
from numpy.linalg import norm
@@ -66,8 +71,8 @@ async def api_score(api_answer: str, response: str, weight: float, temperature:
words_in_response = len(response.split())
words_in_api = len(api_answer.split())
- word_count_over_threshold = words_in_api * 1.4
- word_count_under_threshold = words_in_api * 0.50
+ word_count_over_threshold = words_in_api * 1.20
+ word_count_under_threshold = words_in_api * 0.60
# Check if the word count of the response is within the thresholds
if words_in_response <= word_count_over_threshold and words_in_response >= word_count_under_threshold:
@@ -153,7 +158,7 @@ def calculate_image_similarity(image, description, max_length: int = 77):
# Calculate cosine similarity
return torch.cosine_similarity(image_embedding, text_embedding, dim=1).item()
-async def dalle_score(uid, url, desired_size, description, weight, similarity_threshold=0.21) -> float:
+async def dalle_score(uid, url, desired_size, description, weight, similarity_threshold=0.23) -> float:
"""Calculate the image score based on similarity and size asynchronously."""
if not re.match(url_regex, url):
diff --git a/cortext/utils.py b/cortext/utils.py
index 0ded531..5f745f9 100644
--- a/cortext/utils.py
+++ b/cortext/utils.py
@@ -163,7 +163,7 @@ def fetch_random_image_urls(num_images):
images = response.json().get('hits', [])
return [image['webformatURL'] for image in images]
except Exception as e:
- bt.logging.error(f"Error fetching random images: {e}")
+ print(f"Error fetching random images: {e}")
return []
@@ -315,9 +315,9 @@ async def update_counters_and_get_new_list(category, item_type, num_questions_ne
item = await get_item_from_list(items, vision)
if not item:
- bt.logging.trace(f"Item not founded in items: {items}. Calling get_items!")
+ bt.logging.info(f"Item not founded in items: {items}. Calling get_items!")
items = await get_items(category, item_type, theme)
- bt.logging.trace(f"Items generated: {items}")
+ bt.logging.info(f"Items generated: {items}")
state[category][item_type] = items
bt.logging.debug(f"Fetched new list for {list_type}, containing {len(items)} items")
@@ -503,7 +503,7 @@ async def call_openai(messages, temperature, model, seed=1234, max_tokens=2048,
async def call_gemini(messages, temperature, model, max_tokens, top_p, top_k):
- bt.logging.debug(f"Calling Gemini. Temperature = {temperature}, Model = {model}, Messages = {messages}")
+ print(f"Calling Gemini. Temperature = {temperature}, Model = {model}, Messages = {messages}")
try:
model = genai.GenerativeModel(model)
response = model.generate_content(
@@ -520,10 +520,10 @@ async def call_gemini(messages, temperature, model, max_tokens, top_p, top_k):
),
)
- bt.logging.trace(f"validator response is {response.text}")
+ print(f"validator response is {response.text}")
return response.text
except:
- bt.logging.error(f"error in call_gemini {traceback.format_exc()}")
+ print(f"error in call_gemini {traceback.format_exc()}")
# anthropic = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
@@ -625,7 +625,7 @@ async def call_anthropic(messages, temperature, model, max_tokens, top_p, top_k)
kwargs["system"] = system_prompt
message = await anthropic_client.messages.create(**kwargs)
- bt.logging.trace(f"validator response is {message.content[0].text}")
+ bt.logging.debug(f"validator response is {message.content[0].text}")
return message.content[0].text
except:
bt.logging.error(f"error in call_anthropic {traceback.format_exc()}")
@@ -647,7 +647,7 @@ async def call_groq(messages, temperature, model, max_tokens, top_p, seed):
}
message = await groq_client.chat.completions.create(**kwargs)
- bt.logging.trace(f"validator response is {message.choices[0].message.content}")
+ bt.logging.debug(f"validator response is {message.choices[0].message.content}")
return message.choices[0].message.content
except:
bt.logging.error(f"error in call_groq {traceback.format_exc()}")
@@ -738,7 +738,7 @@ async def call_bedrock(messages, temperature, model, max_tokens, top_p, seed):
message = await response['body'].read()
message = await extract_message(message)
- bt.logging.trace(f"validator response is {message}")
+ bt.logging.debug(f"validator response is {message}")
return message
except:
bt.logging.error(f"error in call_bedrock {traceback.format_exc()}")
diff --git a/env.example b/env.example
index c9d20f6..67c5b46 100644
--- a/env.example
+++ b/env.example
@@ -1,12 +1,12 @@
-# for validators
+ENV=test
WANDB_API_KEY=
-OPENAI_API_KEY=
-PIXABAY_API_KEY=
-# For validators and miners
+# used both by validator and miner:
+OPENAI_API_KEY=
GOOGLE_API_KEY=
ANTHROPIC_API_KEY=
GROQ_API_KEY=test
AWS_ACCESS_KEY=
AWS_SECRET_KEY=
+PIXABAY_API_KEY=
diff --git a/miner/config.py b/miner/config.py
index 7cdcb40..3ad29e9 100644
--- a/miner/config.py
+++ b/miner/config.py
@@ -43,7 +43,6 @@ class Config:
self.NO_SET_WEIGHTS = os.getenv('NO_SET_WEIGHTS', False)
self.NO_SERVE = os.getenv('NO_SERVE', False)
-
def __repr__(self):
return (
f"Config(BT_SUBTENSOR_NETWORK={self.BT_SUBTENSOR_NETWORK}, WALLET_NAME={self.WALLET_NAME}, HOT_KEY={self.HOT_KEY}"
diff --git a/miner/constants.py b/miner/constants.py
deleted file mode 100644
index ef7371a..0000000
--- a/miner/constants.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from cortext import ImageResponse, StreamPrompting
-from miner.providers import OpenAI, Anthropic, AnthropicBedrock, Groq, Gemini, Bedrock
-
-task_image = ImageResponse.__name__
-task_stream = StreamPrompting.__name__
-
-openai_provider = OpenAI.__name__
-anthropic_provider = Anthropic.__name__
-anthropic_bedrock_provider = AnthropicBedrock.__name__
-groq_provider = Groq.__name__
-gemini_provider = Gemini.__name__
-bedrock_provider = Bedrock.__name__
-
-capacity_to_task_and_provider = {
- f"{task_image}_{openai_provider}": 1,
- f"{task_image}_{anthropic_provider}": 1,
- f"{task_image}_{anthropic_bedrock_provider}": 1,
- f"{task_image}_{groq_provider}": 1,
- f"{task_image}_{gemini_provider}": 1,
- f"{task_image}_{bedrock_provider}": 1,
-
- f"{task_stream}_{openai_provider}": 1,
- f"{task_stream}_{anthropic_provider}": 1,
- f"{task_stream}_{anthropic_bedrock_provider}": 1,
- f"{task_stream}_{groq_provider}": 1,
- f"{task_stream}_{gemini_provider}": 1,
- f"{task_stream}_{bedrock_provider}": 1,
-}
diff --git a/miner/providers/base.py b/miner/providers/base.py
index 9123f09..18a0734 100644
--- a/miner/providers/base.py
+++ b/miner/providers/base.py
@@ -5,7 +5,7 @@ import httpx
from starlette.types import Send
from abc import abstractmethod
-from cortext.protocol import StreamPrompting, Embeddings, ImageResponse, IsAlive
+from cortext.protocol import StreamPrompting, TextPrompting, Embeddings, ImageResponse, IsAlive
from cortext import ALL_SYNAPSE_TYPE
from cortext.metaclasses import ProviderRegistryMeta
from miner.error_handler import error_handler
@@ -15,7 +15,7 @@ class Provider(metaclass=ProviderRegistryMeta):
self.model = synapse.model
self.uid = synapse.uid
self.timeout = synapse.timeout
- if type(synapse) in [StreamPrompting]:
+ if type(synapse) in [StreamPrompting, TextPrompting]:
self.messages = synapse.messages
self.required_hash_fields = synapse.required_hash_fields
self.seed = synapse.seed
diff --git a/miner/services/__init__.py b/miner/services/__init__.py
index 0823ea8..8309158 100644
--- a/miner/services/__init__.py
+++ b/miner/services/__init__.py
@@ -4,7 +4,6 @@ from .image import ImageService
from .embedding import EmbeddingService
from .text import TextService
from .check_status import IsAliveService
-from .capacity import CapacityService
-ALL_SERVICE_TYPE = Union[PromptService, ImageService, EmbeddingService, TextService, IsAliveService, CapacityService]
-__all__ = [PromptService, ImageService, EmbeddingService, CapacityService, ALL_SERVICE_TYPE]
+ALL_SERVICE_TYPE = Union[PromptService, ImageService, EmbeddingService, TextService, IsAliveService]
+__all__ = [PromptService, ImageService, EmbeddingService, ALL_SERVICE_TYPE]
diff --git a/miner/services/capacity.py b/miner/services/capacity.py
deleted file mode 100644
index eab539b..0000000
--- a/miner/services/capacity.py
+++ /dev/null
@@ -1,24 +0,0 @@
-import bittensor as bt
-
-from cortext.protocol import Bandwidth
-from typing import Tuple
-
-from .base import BaseService
-from cortext import ISALIVE_BLACKLIST_STAKE
-from miner.constants import capacity_to_task_and_provider
-
-
-class CapacityService(BaseService):
- def __init__(self, metagraph, blacklist_amt=ISALIVE_BLACKLIST_STAKE):
- super().__init__(metagraph, blacklist_amt)
-
- async def forward_fn(self, synapse: Bandwidth):
- bt.logging.debug("capacity request is being processed")
- synapse.bandwidth_rpm = capacity_to_task_and_provider
- bt.logging.info("check status is executed.")
- return synapse
-
- def blacklist_fn(self, synapse: Bandwidth) -> Tuple[bool, str]:
- blacklist = self.base_blacklist(synapse)
- bt.logging.info(blacklist[1])
- return blacklist
diff --git a/miner/services/text.py b/miner/services/text.py
new file mode 100644
index 0000000..3f0c853
--- /dev/null
+++ b/miner/services/text.py
@@ -0,0 +1,19 @@
+import bittensor as bt
+from cortext.protocol import TextPrompting
+from typing import Tuple
+
+from .base import BaseService
+from miner.config import config
+
+
+class TextService(BaseService):
+ def __init__(self, metagraph, blacklist_amt=config.BLACKLIST_AMT):
+ super().__init__(metagraph, blacklist_amt)
+
+ async def forward_fn(self, synapse: TextPrompting):
+ synapse.completion = "completed by miner"
+ bt.logging.info("text service is executed.")
+ return synapse
+
+ def blacklist_fn(self, synapse: TextPrompting) -> Tuple[bool, str]:
+ return False, ""
diff --git a/start_validator.py b/start_validator.py
index ad013e1..4b54570 100644
--- a/start_validator.py
+++ b/start_validator.py
@@ -4,18 +4,19 @@ import subprocess
import cortext
from cortext.utils import get_version, send_discord_alert
+default_address = "wss://bittensor-finney.api.onfinality.io/public-ws"
webhook_url = ""
current_version = cortext.__version__
def update_and_restart(pm2_name, netuid, wallet_name, wallet_hotkey, address, autoupdate, logging, wandb_on):
global current_version
- wandb = "--wandb_on" if wandb_on else ""
+ wandb = "" if wandb_on else "--wandb_off"
subprocess.run(["pm2", "start", "--name", pm2_name, f"python3 -m validators.validator --wallet.name {wallet_name}"
f" --wallet.hotkey {wallet_hotkey} "
f" --netuid {netuid} "
f"--subtensor.chain_endpoint {address} "
- f"--logging.level {logging} {wandb}"])
+ f"--logging.{logging} {wandb}"])
while True:
latest_version = get_version()
print(f"Current version: {current_version}")
@@ -24,7 +25,7 @@ def update_and_restart(pm2_name, netuid, wallet_name, wallet_hotkey, address, au
if current_version != latest_version and latest_version != None:
if not autoupdate:
send_discord_alert(
- f"Your validator not running the latest code ({current_version}). You will quickly lose vtrust if you don't update to version {latest_version}",
+ f"Your validator not running the latest code ({current_version}). You will quickly lose vturst if you don't update to version {latest_version}",
webhook_url)
print("Updating to the latest version...")
subprocess.run(["pm2", "delete", pm2_name])
@@ -36,7 +37,7 @@ def update_and_restart(pm2_name, netuid, wallet_name, wallet_hotkey, address, au
f" --wallet.hotkey {wallet_hotkey} "
f" --netuid {netuid} "
f"--subtensor.chain_endpoint {address} "
- f"--logging.level {logging} {wandb}"])
+ f"--logging.{logging} {wandb}"])
current_version = latest_version
print("All up to date!")
@@ -48,15 +49,16 @@ if __name__ == "__main__":
description="Automatically update and restart the validator process when a new version is released."
)
- parser.add_argument("--pm2_name", required=False, default="autoupdater", help="Name of the PM2 process.")
- parser.add_argument("--wallet_name", required=False, default="default", help="Name of the wallet.")
- parser.add_argument("--wallet_hotkey", required=False, default="default", help="Hotkey for the wallet.")
- parser.add_argument("--netuid", required=False, default=18, help="netuid for validator")
- parser.add_argument("--subtensor.chain_endpoint", required=False, default="wss://entrypoint-finney.opentensor.ai:443", dest="address")
- parser.add_argument("--autoupdate", action='store_true', dest="autoupdate")
- parser.add_argument("--logging", required=False, default="info")
- parser.add_argument("--wandb_on", action='store_true', required=False, dest="wandb_on")
- parser.add_argument("--max_miners_cnt", type=int, default=30)
+ parser.add_argument("--pm2_name", required=True, help="Name of the PM2 process.")
+ parser.add_argument("--wallet_name", required=True, help="Name of the wallet.")
+ parser.add_argument("--wallet_hotkey", required=True, help="Hotkey for the wallet.")
+ parser.add_argument("--netuid", required=True, help="netuid for validator")
+ parser.add_argument("--subtensor.chain_endpoint", default=default_address, dest='address',
+ help="Subtensor chain_endpoint, defaults to 'wss://bittensor-finney.api.onfinality.io/public-ws' if not provided.")
+ parser.add_argument("--autoupdate", action='store_true', dest='autoupdate',
+ help="Disable automatic update. Only send a Discord alert. Add your webhook at the top of the script.")
+ parser.add_argument("--logging", required=False, default="debug")
+ parser.add_argument("--wandb_on", action='store_true', required=False, dest='wandb_on')
args = parser.parse_args()
@@ -64,4 +66,4 @@ if __name__ == "__main__":
update_and_restart(args.pm2_name, args.netuid, args.wallet_name, args.wallet_hotkey, args.address,
args.autoupdate, args.logging, args.wandb_on)
except Exception as e:
- parser.error(f"An error occurred: {e}")
\ No newline at end of file
+ parser.error(f"An error occurred: {e}")
diff --git a/validators/config.py b/validators/config.py
new file mode 100644
index 0000000..2280fd0
--- /dev/null
+++ b/validators/config.py
@@ -0,0 +1,76 @@
+import bittensor as bt
+
+from dotenv import load_dotenv
+import argparse
+import os
+from pathlib import Path
+
+load_dotenv() # Load environment variables from .env file
+
+
+class Config:
+ def __init__(self):
+ super().__init__()
+
+ self.ENV = os.getenv('ENV')
+ self.ASYNC_TIME_OUT = int(os.getenv('ASYNC_TIME_OUT', 60))
+ self.BT_SUBTENSOR_NETWORK = 'test' if self.ENV == 'test' else 'finney'
+ self.SLEEP_PER_ITERATION = 1
+ self.IMAGE_VALIDATOR_CHOOSE_PROBABILITY = 0.03
+
+ @staticmethod
+ def check_required_env_vars():
+ AWS_ACCESS_KEY = os.getenv('AWS_ACCESS_KEY')
+ AWS_SECRET_KEY = os.getenv('AWS_SECRET_KEY')
+ if all([AWS_SECRET_KEY, AWS_ACCESS_KEY]):
+ pass
+ else:
+ bt.logging.info("AWS_KEY is not provided correctly. so exit system")
+ exit(0)
+
+
+def get_config() -> bt.config:
+ Config.check_required_env_vars()
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument("--subtensor.chain_endpoint", type=str)
+ parser.add_argument("--wallet.name", type=str)
+ parser.add_argument("--wallet.hotkey", type=str)
+ parser.add_argument("--netuid", type=int)
+ parser.add_argument("--wandb_off", action="store_true", dest="wandb_off")
+ parser.add_argument("--max_miners_cnt", type=int, default=30)
+ parser.add_argument("--axon.port", type=int, default=8000)
+ parser.add_argument('--logging.info', action='store_true')
+ parser.add_argument('--logging.debug', action='store_true')
+ parser.add_argument('--logging.trace', action='store_true')
+
+ # Activating the parser to read any command-line inputs.
+ # To print help message, run python3 template/miner.py --help
+ bt_config_ = bt.config(parser)
+ bt.configs.append(bt_config_)
+ bt_config_ = bt.config.merge_all(bt.configs)
+
+ # Logging captures events for diagnosis or understanding miner's behavior.
+ full_path = Path(f"{bt_config_.logging.logging_dir}/{bt_config_.wallet.name}/{bt_config_.wallet.hotkey}"
+ f"/netuid{bt_config_.netuid}/miner").expanduser()
+ bt_config_.full_path = str(full_path)
+ # Ensure the directory for logging exists, else create one.
+ full_path.mkdir(parents=True, exist_ok=True)
+
+ bt.axon.check_config(bt_config_)
+ bt.logging.check_config(bt_config_)
+
+ local_host_str = ['local', '127.0.0.1', '0.0.0.0']
+ if 'test' in bt_config_.subtensor.chain_endpoint:
+ bt_config_.subtensor.network = 'test'
+ elif any(word in bt_config_.subtensor.chain_endpoint for word in local_host_str):
+ bt_config_.subtensor.network = 'local'
+ else:
+ bt_config_.subtensor.network = 'finney'
+
+ bt.logging.info(bt_config_)
+ return bt_config_
+
+
+app_config = Config()
+bt_config = get_config()
diff --git a/validators/services/__init__.py b/validators/services/__init__.py
index 0fc0233..9fe505e 100644
--- a/validators/services/__init__.py
+++ b/validators/services/__init__.py
@@ -1,2 +1,2 @@
from validators.services.validators import *
-from .capacity import CapacityService
\ No newline at end of file
+from .bittensor import bt_validator
\ No newline at end of file
diff --git a/validators/services/bittensor.py b/validators/services/bittensor.py
new file mode 100644
index 0000000..8dc1ef2
--- /dev/null
+++ b/validators/services/bittensor.py
@@ -0,0 +1,34 @@
+from validators.config import bt_config
+import bittensor as bt
+import sys
+
+
+class BittensorValidator:
+ def __init__(self):
+ self.config = bt_config
+ bt.logging(config=self.config, logging_dir=self.config.full_path)
+ self.logging = bt.logging
+ self.logging.info(
+ f"Running validator for subnet: {self.config.netuid} on network: {self.config.subtensor.network}")
+ self.wallet = bt.wallet(config=self.config)
+ self.subtensor = bt.subtensor(config=self.config, network=self.config.subtensor.network)
+ self.metagraph = self.subtensor.metagraph(netuid=self.config.netuid)
+ self.axon = bt.axon(wallet=self.wallet, port=self.config.axon.port)
+ self.dendrite = bt.dendrite(wallet=self.wallet)
+ self.my_uid = self.metagraph.hotkeys.index(self.wallet.hotkey.ss58_address)
+ self.check_wallet_registered_in_network()
+
+
+ def check_wallet_registered_in_network(self):
+ if self.wallet.hotkey.ss58_address not in self.metagraph.hotkeys:
+ bt.logging.error(
+ f"Your validator: {self.wallet} is not registered to chain connection: "
+ f"{self.subtensor}. Run btcli register --netuid 18 and try again."
+ )
+ sys.exit()
+
+ def refresh_network(self):
+ pass
+
+
+bt_validator = BittensorValidator()
diff --git a/validators/services/capacity.py b/validators/services/capacity.py
deleted file mode 100644
index 51a26f4..0000000
--- a/validators/services/capacity.py
+++ /dev/null
@@ -1,32 +0,0 @@
-import asyncio
-
-from cortext.protocol import Bandwidth
-import bittensor as bt
-
-
-class CapacityService:
- def __init__(self, metagraph, dendrite):
- self.metagraph = metagraph
- self.dendrite: bt.dendrite = dendrite
- self.timeout = 4
-
- async def query_capacity_to_miners(self, available_uids):
- capacity_query_tasks = []
-
- # Query all images concurrently
- for uid in available_uids:
- syn = Bandwidth()
- bt.logging.info(f"querying capacity to uid = {uid}")
- task = self.dendrite.call(self.metagraph.axons[uid], syn,
- timeout=self.timeout)
- capacity_query_tasks.append(task)
-
- # Query responses is (uid. syn)
- query_responses = await asyncio.gather(*capacity_query_tasks, return_exceptions=True)
- uid_to_capacity = {}
- for uid, resp in zip(available_uids, query_responses):
- if isinstance(resp, Exception):
- bt.logging.error(f"exception happens while querying capacity to miner {uid}, {resp}")
- else:
- uid_to_capacity[uid] = resp
- return uid_to_capacity
diff --git a/validators/services/validators/__init__.py b/validators/services/validators/__init__.py
index d461d47..27e4483 100644
--- a/validators/services/validators/__init__.py
+++ b/validators/services/validators/__init__.py
@@ -1,3 +1,4 @@
+from .text_validator import TextValidator
from .image_validator import ImageValidator
from .embeddings_validator import EmbeddingsValidator
from .base_validator import BaseValidator
\ No newline at end of file
diff --git a/validators/services/validators/base_validator.py b/validators/services/validators/base_validator.py
index 50e7d7c..5451ec8 100644
--- a/validators/services/validators/base_validator.py
+++ b/validators/services/validators/base_validator.py
@@ -4,25 +4,27 @@ from datasets import load_dataset
import random
from typing import List, Tuple
-import bittensor as bt
+import bittensor
from cortext.metaclasses import ValidatorRegistryMeta
from cortext import utils
+from validators.services.bittensor import bt_validator as bt
+from validators.config import app_config
dataset = None
class BaseValidator(metaclass=ValidatorRegistryMeta):
- def __init__(self, config, metagraph):
- self.config = config
- self.metagraph = metagraph
- self.dendrite = config.dendrite
- self.wallet = config.wallet
- self.timeout = config.async_time_out
+ def __init__(self):
+ self.dendrite = bt.dendrite
+ self.config = bt.config
+ self.subtensor = bt.subtensor
+ self.wallet = bt.wallet
+ self.metagraph = bt.metagraph
+ self.timeout = app_config.ASYNC_TIME_OUT
self.streaming = False
self.provider = None
self.model = None
- self.seed = random.randint(1111, 9999)
self.uid_to_questions = dict()
self.available_uids = []
self.num_samples = 100
@@ -41,7 +43,7 @@ class BaseValidator(metaclass=ValidatorRegistryMeta):
for index, uid in enumerate(available_uids):
if item_type == "images":
- content = await utils.get_question("images", len(available_uids))
+ content = await utils.get_question("images", len(available_uids))
self.uid_to_questions[uid] = content # Store messages for each UID
elif item_type == "text":
question = await utils.get_question("text", len(available_uids), vision)
@@ -69,13 +71,13 @@ class BaseValidator(metaclass=ValidatorRegistryMeta):
bt.logging.error(f"Exception during query for uid {uid}: {e}")
return uid, None
- async def handle_response(self, uid, response) -> Tuple[int, bt.Synapse]:
+ async def handle_response(self, uid, response) -> Tuple[int, bittensor.Synapse]:
if type(response) == list and response:
response = response[0]
return uid, response
@abstractmethod
- async def start_query(self, available_uids: List[int]) -> bt.Synapse:
+ async def start_query(self, available_uids: List[int]) -> bittensor.Synapse:
pass
@abstractmethod
@@ -99,6 +101,7 @@ class BaseValidator(metaclass=ValidatorRegistryMeta):
uid_scores_dict = {}
scored_response = []
+
for uid, syn in responses:
task = self.get_answer_task(uid, syn)
answering_tasks.append((uid, task))
@@ -111,8 +114,7 @@ class BaseValidator(metaclass=ValidatorRegistryMeta):
# Await all scoring tasks
scored_responses = await asyncio.gather(*[task for _, task in scoring_tasks])
- average_score = sum(0 if score is None else score for score in scored_responses) / len(
- scored_responses) if scored_responses else 0
+ average_score = sum(scored_responses) / len(scored_responses) if scored_responses else 0
bt.logging.debug(f"scored responses = {scored_responses}, average score = {average_score}")
for (uid, _), scored_response in zip(scoring_tasks, scored_responses):
@@ -123,12 +125,12 @@ class BaseValidator(metaclass=ValidatorRegistryMeta):
if uid_scores_dict != {}:
bt.logging.info(f"text_scores is {uid_scores_dict}")
- bt.logging.trace("score_responses process completed.")
+ bt.logging.info("score_responses process completed.")
return uid_scores_dict, scored_response, responses
async def get_and_score(self, available_uids: List[int]):
- bt.logging.trace("starting query")
+ bt.logging.info("starting query")
query_responses = await self.start_query(available_uids)
- bt.logging.trace("scoring query with query responses")
+ bt.logging.info("scoring query with query responses")
return await self.score_responses(query_responses)
diff --git a/validators/services/validators/constants.py b/validators/services/validators/constants.py
index fb75163..5ad2e2b 100644
--- a/validators/services/validators/constants.py
+++ b/validators/services/validators/constants.py
@@ -3,19 +3,23 @@ TEXT_PROVIDER = "OpenAI"
TEXT_MAX_TOKENS = 4096
TEXT_TEMPERATURE = 0.001
TEXT_WEIGHT = 1
+TEXT_SEED = 1234
TEXT_TOP_P = 0.01
TEXT_TOP_K = 1
VISION_MODELS = ["gpt-4o", "claude-3-opus-20240229", "anthropic.claude-3-sonnet-20240229-v1:0",
"claude-3-5-sonnet-20240620"]
+DEFAULT_NUM_UID_PICK = 30
+DEFAULT_NUM_UID_PICK_ANTHROPIC = 1
TEXT_VALI_MODELS_WEIGHTS = {
"AnthropicBedrock": {
"anthropic.claude-v2:1": 1
},
"OpenAI": {
"gpt-4o": 1,
- "gpt-3.5-turbo": 1000,
- "o1-preview": 1,
- "o1-mini": 1,
+ "gpt-4-1106-preview": 1,
+ "gpt-3.5-turbo": 1,
+ "gpt-3.5-turbo-16k": 1,
+ "gpt-3.5-turbo-0125": 1,
},
"Gemini": {
"gemini-pro": 1,
@@ -26,23 +30,23 @@ TEXT_VALI_MODELS_WEIGHTS = {
"claude-3-5-sonnet-20240620": 1,
"claude-3-opus-20240229": 1,
"claude-3-sonnet-20240229": 1,
- "claude-3-haiku-20240307": 1000,
+ "claude-3-haiku-20240307": 1
},
"Groq": {
- "gemma-7b-it": 500,
+ "gemma-7b-it": 1,
"llama3-70b-8192": 1,
- "llama3-8b-8192": 500,
+ "llama3-8b-8192": 1,
"mixtral-8x7b-32768": 1,
},
"Bedrock": {
- # "anthropic.claude-3-sonnet-20240229-v1:0": 1,
+ "anthropic.claude-3-sonnet-20240229-v1:0": 1,
"cohere.command-r-v1:0": 1,
- # "meta.llama2-70b-chat-v1": 1,
- # "amazon.titan-text-express-v1": 1,
+ "meta.llama2-70b-chat-v1": 1,
+ "amazon.titan-text-express-v1": 1,
"mistral.mistral-7b-instruct-v0:2": 1,
"ai21.j2-mid-v1": 1,
- # "anthropic.claude-3-5-sonnet-20240620-v1:0": 1,
- # "anthropic.claude-3-opus-20240229-v1:0": 1,
- # "anthropic.claude-3-haiku-20240307-v1:0": 1
+ "anthropic.claude-3-5-sonnet-20240620-v1:0": 1,
+ "anthropic.claude-3-opus-20240229-v1:0": 1,
+ "anthropic.claude-3-haiku-20240307-v1:0": 1
}
}
diff --git a/validators/services/validators/embeddings_validator.py b/validators/services/validators/embeddings_validator.py
index 53d8926..99494c2 100644
--- a/validators/services/validators/embeddings_validator.py
+++ b/validators/services/validators/embeddings_validator.py
@@ -1,7 +1,8 @@
from __future__ import annotations
+from bittensor import Synapse
import random
import asyncio
-import bittensor as bt
+from validators.services.bittensor import bt_validator as bt
import cortext.reward
from cortext import client
from cortext.protocol import Embeddings
@@ -9,10 +10,9 @@ from validators.services.validators.base_validator import BaseValidator
class EmbeddingsValidator(BaseValidator):
- def __init__(self, config):
- super().__init__(config)
+ def __init__(self):
+ super().__init__()
self.streaming = False
- self.config = config
self.query_type = "embeddings"
self.model = "text-embedding-ada-002"
self.weight = 1
@@ -63,7 +63,7 @@ class EmbeddingsValidator(BaseValidator):
# bt.logging.error(f"Error in processing batch: {e}")
return all_embeddings
- async def start_query(self, available_uids) -> tuple[(int, bt.Synapse)] | None:
+ async def start_query(self, available_uids) -> tuple[(int, Synapse)] | None:
if not available_uids:
return None
diff --git a/validators/services/validators/image_validator.py b/validators/services/validators/image_validator.py
index 0bcd243..46e41f3 100644
--- a/validators/services/validators/image_validator.py
+++ b/validators/services/validators/image_validator.py
@@ -5,15 +5,15 @@ import wandb
import cortext.reward
from cortext.protocol import ImageResponse
+from validators.services.bittensor import bt_validator as bt
from validators.services.validators.base_validator import BaseValidator
from validators import utils
from validators.utils import error_handler
-import bittensor as bt
class ImageValidator(BaseValidator):
- def __init__(self, config, metagraph=None):
- super().__init__(config, metagraph)
+ def __init__(self):
+ super().__init__()
self.num_uids_to_pick = 30
self.streaming = False
self.query_type = "images"
@@ -26,6 +26,7 @@ class ImageValidator(BaseValidator):
self.quality = "standard"
self.style = "vivid"
self.steps = 30
+ self.seed = 123456
self.wandb_data = {
"modality": "images",
"prompts": {},
diff --git a/validators/services/validators/text_validator.py b/validators/services/validators/text_validator.py
index e739e3f..8adf3af 100644
--- a/validators/services/validators/text_validator.py
+++ b/validators/services/validators/text_validator.py
@@ -1,9 +1,9 @@
import asyncio
import random
-import bittensor as bt
from typing import AsyncIterator
from cortext.reward import model
+from validators.services.bittensor import bt_validator as bt
from . import constants
import cortext.reward
from validators.services.validators.base_validator import BaseValidator
@@ -12,23 +12,22 @@ from typing import Optional
from cortext.protocol import StreamPrompting
from cortext.utils import (call_anthropic_bedrock, call_bedrock, call_anthropic, call_gemini,
call_groq, call_openai, get_question)
-from validators.utils import get_should_i_score_arr_for_text
class TextValidator(BaseValidator):
- gen_should_i_score = get_should_i_score_arr_for_text()
- def __init__(self, config, provider: str = None, model: str = None, metagraph=None):
- super().__init__(config, metagraph)
+ def __init__(self, provider: str = None, model: str = None):
+ super().__init__()
self.streaming = True
self.query_type = "text"
- self.metagraph = metagraph
self.model = model or constants.TEXT_MODEL
self.max_tokens = constants.TEXT_MAX_TOKENS
self.temperature = constants.TEXT_TEMPERATURE
self.weight = constants.TEXT_WEIGHT
+ self.seed = constants.TEXT_SEED
self.top_p = constants.TEXT_TOP_P
self.top_k = constants.TEXT_TOP_K
self.provider = provider or constants.TEXT_PROVIDER
+ self.num_uids_to_pick = constants.DEFAULT_NUM_UID_PICK
self.wandb_data = {
"modality": "text",
@@ -78,7 +77,7 @@ class TextValidator(BaseValidator):
if isinstance(chunk, str):
bt.logging.trace(chunk)
full_response += chunk
- bt.logging.trace(f"full_response for uid {uid}: {full_response}")
+ bt.logging.debug(f"full_response for uid {uid}: {full_response}")
break
return uid, full_response
@@ -89,7 +88,7 @@ class TextValidator(BaseValidator):
await self.load_questions(available_uids, "text", is_vision_model)
query_tasks = []
- bt.logging.trace(f"provider = {self.provider} model = {self.model}")
+ bt.logging.info(f"provider = {self.provider}\nmodel = {self.model}")
for uid, question in self.uid_to_questions.items():
prompt = question.get("prompt")
image = question.get("image")
@@ -118,17 +117,22 @@ class TextValidator(BaseValidator):
def select_random_provider_and_model(self):
# AnthropicBedrock should only be used if a validators' anthropic account doesn't work
- providers = ["OpenAI"] * 55 + ["AnthropicBedrock"] * 0 + ["Gemini"] * 1 + ["Anthropic"] * 20 + [
+ providers = ["OpenAI"] * 55 + ["AnthropicBedrock"] * 0 + ["Gemini"] * 2 + ["Anthropic"] * 20 + [
"Groq"] * 30 + ["Bedrock"] * 0
self.provider = random.choice(providers)
+ self.num_uids_to_pick = constants.DEFAULT_NUM_UID_PICK
model_to_weights = constants.TEXT_VALI_MODELS_WEIGHTS[self.provider]
self.model = random.choices(list(model_to_weights.keys()),
weights=list(model_to_weights.values()), k=1)[0]
- @classmethod
- def should_i_score(cls):
- return next(cls.gen_should_i_score)
+ return self.num_uids_to_pick