-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathvalidator.py
More file actions
2632 lines (2333 loc) · 111 KB
/
Copy pathvalidator.py
File metadata and controls
2632 lines (2333 loc) · 111 KB
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
# The MIT License (MIT)
# © 2025 tplr.ai
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of
# the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
# THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# Standard library
import argparse
import asyncio
import concurrent.futures
import copy
import os
import random
import sys
import threading
import time
from collections import defaultdict
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from io import StringIO
from time import perf_counter
from types import SimpleNamespace
from typing import cast
import bittensor as bt
import numpy as np
# Third party
import torch
import uvloop
from openskill.models import PlackettLuce
from rich.console import Console
from rich.table import Table
from torch import autocast
from torch.optim import SGD
from torch.optim.lr_scheduler import (
CosineAnnealingWarmRestarts,
LinearLR,
SequentialLR,
)
from transformers import LlamaForCausalLM
# Local
import tplr
CPU_COUNT = os.cpu_count() or 4
CPU_MAX_CONNECTIONS = min(100, max(30, CPU_COUNT * 4))
# GPU optimizations.
torch.manual_seed(42)
torch.cuda.manual_seed_all(42)
np.random.seed(42)
random.seed(42)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
@contextmanager
def timer(name: str, wandb_obj=None, step=None, metrics_logger=None):
start = perf_counter()
yield
duration = perf_counter() - start
tplr.logger.debug(f"{name} took {duration:.2f}s")
if wandb_obj and step is not None:
wandb_obj.log({f"validator/{name}": duration}, step=step)
if metrics_logger and step is not None:
metrics_logger.log(
measurement="timing", tags={"window": step}, fields={name: duration}
)
class Validator:
@staticmethod
def config():
parser = argparse.ArgumentParser(description="Validator script")
parser.add_argument(
"--netuid", type=int, default=268, help="Bittensor network UID."
)
parser.add_argument(
"--project", type=str, default="templar", help="Wandb project."
)
parser.add_argument(
"--device", type=str, default="cuda", help="Device to use for training"
)
parser.add_argument("--debug", action="store_true", help="Enable debug logging")
parser.add_argument("--trace", action="store_true", help="Enable trace logging")
parser.add_argument(
"--store-gathers",
action="store_true",
help="Store gathered gradients in R2",
)
parser.add_argument(
"--test",
action="store_true",
help="Test mode - use all peers without filtering",
)
parser.add_argument(
"--local",
action="store_true",
help="Local run - use toy model, small enough for a laptop.",
)
bt.subtensor.add_args(parser)
bt.logging.add_args(parser)
bt.wallet.add_args(parser)
config = bt.config(parser)
if config.debug:
tplr.debug()
if config.trace:
tplr.trace()
return config
def __init__(self):
tplr.logger.debug("Starting initialization...")
# Init config and load hparams
self.config = Validator.config()
self.hparams = tplr.load_hparams(use_local_run_hparams=self.config.local)
# Init bittensor objects
self.wallet = bt.wallet(config=self.config)
self.subtensor = bt.subtensor(config=self.config)
self.metagraph = self.subtensor.metagraph(self.config.netuid)
if self.wallet.hotkey.ss58_address not in self.metagraph.hotkeys:
tplr.logger.error(
f"\n\t[bold]The wallet {self.wallet} is not registered on subnet: {self.metagraph.netuid}[/bold]"
)
sys.exit()
self.uid = self.metagraph.hotkeys.index(self.wallet.hotkey.ss58_address)
try:
version = tplr.__version__
tplr.logger = tplr.setup_loki_logger(
service="validator", uid=str(self.uid), version=version
)
tplr.logger.info(f"Loki logging enabled for validator UID: {self.uid}")
except Exception as e:
tplr.logger.warning(f"Failed to initialize Loki logging: {e}")
# Init model with hparams config
self.model = LlamaForCausalLM(self.hparams.model_config)
self.model.to(self.config.device)
self.tokenizer = self.hparams.tokenizer
# Init compression
self.transformer = tplr.compress.TransformDCT(
self.model, target_chunk=self.hparams.target_chunk
)
self.compressor = tplr.compress.CompressDCT()
# Init optimizer and momentum
self.optimizer = SGD(self.model.parameters(), lr=self.hparams.learning_rate)
self.momentum = {}
self.xshapes = {}
self.totalks = {}
for n, p in self.model.named_parameters():
self.momentum[n] = torch.zeros_like(p)
_, _, xshape, totalk = self.compressor.compress(
self.transformer.encode(self.momentum[n]), self.hparams.topk_compression
)
self.xshapes[n] = xshape
self.totalks[n] = totalk
# Set up scheduler setup
warmup_scheduler = LinearLR(
self.optimizer,
start_factor=0.1,
end_factor=1.0,
total_iters=250,
)
cosine_scheduler = CosineAnnealingWarmRestarts(
self.optimizer,
T_0=self.hparams.t_max,
T_mult=2,
eta_min=self.hparams.learning_rate * 0.1,
)
self.scheduler = SequentialLR(
self.optimizer,
schedulers=[warmup_scheduler, cosine_scheduler],
milestones=[250],
)
self.openskill_model = PlackettLuce(
beta=self.hparams.openskill_beta, tau=self.hparams.openskill_tau
)
self.openskill_ratings = {} # Dictionary to store peer ratings
self.bootstrap_version = getattr(self.hparams, "checkpoint_init_version", None)
tplr.logger.info(
f"[Miner] code_version={tplr.__version__} "
f"checkpoint_init_flag={self.bootstrap_version or '<none>'}"
)
# Init comms
self.comms = tplr.comms.Comms(
wallet=self.wallet,
save_location="/tmp",
key_prefix="model",
config=self.config,
netuid=self.config.netuid,
metagraph=self.metagraph,
hparams=self.hparams,
uid=self.uid,
)
self.bucket = self.comms.get_own_bucket("gradients", "read")
self.comms.try_commit(self.wallet, self.bucket)
# self.comms.fetch_commitments()
# Init state params
self.stop_event = asyncio.Event()
self.current_block = self.subtensor.block
self.current_window = int(self.current_block / self.hparams.blocks_per_window)
self.start_window = self.current_window # Record the start window
self.global_step = 0 # Initialize global_step to zero
self.comms.current_window = self.current_window
self.sync_window = self.current_window
# Init score tracking variables
self.loss_before_per_batch_own = 0.0
self.loss_after_per_batch_own = 0.0
self.loss_before_per_batch_random = 0.0
self.loss_after_per_batch_random = 0.0
self.loss_improvement_own = 0.0
self.loss_improvement_random = 0.0
self.relative_improvement_own = 0.0
self.relative_improvement_random = 0.0
# For better looking graphs if no eval peers could be evaluated
self.previous_avg_loss_before_own = 0.0
self.previous_avg_loss_after_own = 0.0
self.previous_avg_loss_before_random = 0.0
self.previous_avg_loss_after_random = 0.0
self.valid_score_indices = []
# Caching
self.state_path = f"validator-state-{tplr.__version__}.pt"
if os.path.isfile(self.state_path):
self.load_state()
else:
d = self.config.device
self.gradient_scores = torch.zeros(256, dtype=torch.float32, device=d)
self.sync_scores = torch.zeros(256, dtype=torch.float32, device=d)
self.binary_indicator_scores = torch.zeros(
256, dtype=torch.float32, device=d
)
self.final_scores = torch.zeros(256, dtype=torch.float32, device=d)
self.binary_moving_averages = torch.zeros(
256, dtype=torch.float32, device=d
)
self.weights = torch.zeros(256, dtype=torch.float32, device=d)
self.evaluated_uids = set()
# Add step tracking
self.window_step = 0
self.eval_count = 0
# Initialize WandB
self.wandb = tplr.initialize_wandb(
run_prefix="V",
uid=self.uid,
config=self.config,
group="validator",
job_type="validation",
)
# Initialize metrics logger for InfluxDB
self.metrics_logger = tplr.metrics.MetricsLogger(
prefix="V",
uid=self.uid,
config=self.config,
role="validator",
group="validator",
job_type="validation",
)
# Weighted selection counters for fair picking of eval peers
self.eval_peers = defaultdict(lambda: 1)
# Track inactive peer scores
self.inactive_scores = {} # {uid: (last_active_window, last_score)}
self.inactivity_slash_rate = 0.25 # 25% slash per window
self.missing_gradient_slash_rate = 0.75
self.sync_score_slash_rate = 0.75
# Initialize peer related attributes
self.next_peers: tplr.comms.PeerArray | None = None
self.peers_update_window = -1
def reset_peer(self, inactive_since: int, uid: int) -> bool:
if self.current_window - inactive_since > self.hparams.reset_inactivity_windows:
self.final_scores[uid] = 0.0
self.weights[uid] = 0.0
self.gradient_scores[uid] = 0.0
self.binary_moving_averages[uid] = 0.0
self.binary_indicator_scores[uid] = 0.0
self.sync_scores[uid] = 0.0
if uid in self.eval_peers:
del self.eval_peers[uid]
del self.inactive_scores[uid]
tplr.logger.info(f"UID {uid} fully reset after extended inactivity")
return True
return False
def log_sync_score(
self, eval_uid: int, sync_result: dict[str, bool | float | int | str]
) -> None:
l2_norm = float(sync_result.get("l2_norm", 99.0))
avg_l2_norm = float(sync_result.get("avg_l2_norm", 99.0))
avg_abs_diff = float(sync_result.get("avg_abs_diff", 99.0))
max_diff = float(sync_result.get("max_diff", 99.0))
avg_steps_behind = float(sync_result.get("avg_steps_behind", 99.0))
max_steps_behind = float(sync_result.get("max_steps_behind", 99.0))
self.wandb.log(
{
f"validator/sync/l2_norm/{eval_uid}": l2_norm,
f"validator/sync/avg_l2_norm/{eval_uid}": avg_l2_norm,
f"validator/sync/avg_abs_diff/{eval_uid}": avg_abs_diff,
f"validator/sync/sync_max_diff/{eval_uid}": max_diff,
f"validator/sync/avg_steps_behind/{eval_uid}": avg_steps_behind,
f"validator/sync/max_steps_behind/{eval_uid}": max_steps_behind,
},
step=self.global_step,
)
self.metrics_logger.log(
measurement="validator_sync_score",
tags={
"uid": str(eval_uid),
"window": int(self.sync_window),
"global_step": int(self.global_step),
},
fields={
"l2_norm": l2_norm,
"avg_l2_norm": avg_l2_norm,
"avg_abs_diff": avg_abs_diff,
"max_diff": max_diff,
"avg_steps_behind": avg_steps_behind,
"max_steps_behind": max_steps_behind,
},
with_system_metrics=True,
with_gpu_metrics=True,
)
def update_openskill_ratings(self):
"""
Update OpenSkill ratings based on gradient scores and recalculate final scores.
This method:
1. Processes all peers evaluated in the current window
2. Updates their OpenSkill ratings based on gradient performance
3. Recalculates final scores using OpenSkill mu value combined with binary and sync scores
4. Logs the updated ratings to monitoring systems
The OpenSkill rating system provides a probabilistic skill rating that accounts for
uncertainty and relative performance between peers. Ratings are updated using the
PlackettLuce model where higher gradient scores indicate better performance.
The final score calculation combines:
- OpenSkill mu (mean skill estimate)
- Binary moving average (filtered to non-negative values)
- Sync score (model synchronization quality)
"""
if (
hasattr(self, "current_window_scores")
and len(self.current_window_scores) > 1
):
# Get UIDs and scores
window_uids = list(self.current_window_scores.keys())
# Calculate ranks based on gradient scores (lower rank = better performance)
# In OpenSkill, ranks start at 1 (best) and increase for worse performers
scores = [self.current_window_scores[uid] for uid in window_uids]
# Create teams list for OpenSkill
teams = [[self.openskill_ratings[uid]] for uid in window_uids]
# Rate the teams using scores (higher score is better in OpenSkill)
rated_teams = self.openskill_model.rate(teams, scores=scores)
# Store updated ratings
for i, uid in enumerate(window_uids):
self.openskill_ratings[uid] = rated_teams[i][0]
# Log updated OpenSkill values
openskill_mu = float(self.openskill_ratings[uid].mu)
openskill_sigma = float(self.openskill_ratings[uid].sigma)
openskill_ordinal = float(self.openskill_ratings[uid].ordinal())
sync_score = float(
self.sync_scores[uid].item() if uid in self.evaluated_uids else 0.0
)
self.final_scores[uid] = (
openskill_ordinal
* max(0, self.binary_moving_averages[uid].item())
* sync_score
)
tplr.logger.info(
f"Computed Final Score for UID {uid}: {self.final_scores[uid]}"
)
# Log to WandB
self.wandb.log(
{
f"validator/openskill/mu/{uid}": openskill_mu,
f"validator/openskill/sigma/{uid}": openskill_sigma,
f"validator/openskill/ordinal/{uid}": openskill_ordinal,
},
step=self.global_step,
)
# Log to InfluxDB
self.metrics_logger.log(
measurement="validator_openskill",
tags={
"eval_uid": str(uid),
"window": int(self.sync_window),
"global_step": int(self.global_step),
},
fields={
"mu": openskill_mu,
"sigma": openskill_sigma,
"ordinal": openskill_ordinal,
},
)
tplr.logger.info(
f"Updated OpenSkill ratings for {len(window_uids)} peers based on gradient scores"
)
# Clear the current window scores
self.current_window_scores = {}
def update_weights(self) -> None:
"""
Update the weights for all evaluated peers using min power normalization.
This method:
1. Creates a mask for peers that have been evaluated
2. Creates a mask for evaluated peers with positive scores
3. Applies power normalization to only the positive scores
4. Verifies that weights sum to approximately 1.0
This approach only assigns weights to peers with positive scores.
"""
self.weights = torch.zeros_like(self.final_scores)
evaluated_mask = torch.zeros_like(self.final_scores, dtype=torch.bool)
evaluated_mask[list(self.evaluated_uids)] = True
# Create a mask for positive scores among evaluated peers
positive_mask = evaluated_mask.clone()
positive_mask[evaluated_mask] = self.final_scores[evaluated_mask] > 0
# Only consider peers with positive scores
positive_scores = self.final_scores[positive_mask]
if len(positive_scores) > 0:
# Apply power normalization to only the positive scores
normalized_weights = min_power_normalization(
positive_scores,
power=self.hparams.power_normalisation,
)
# Assign weights only to peers with positive scores
self.weights[positive_mask] = normalized_weights
weight_sum = self.weights.sum().item()
tplr.logger.debug(f"Weight sum: {weight_sum}")
if abs(weight_sum - 1.0) > 1e-6:
tplr.logger.warning(
f"Weights sum to {weight_sum}, expected close to 1.0"
)
else:
tplr.logger.warning(
"No positive scores found among evaluated peers. All weights set to zero."
)
def evaluate_model_on_batches(
self,
model: torch.nn.Module,
batches: list[list[int]],
sampled_indices: list[int],
) -> tuple[float, int]:
total_loss = 0.0
n_batches = 0
with torch.no_grad():
model.eval()
with autocast(device_type=self.model.device.type, dtype=torch.bfloat16):
for i, batch in enumerate(batches):
if i not in sampled_indices:
continue
input_ids = torch.tensor(batch, dtype=torch.long).to(model.device)
labels = input_ids.clone()
labels = torch.where(
labels == self.tokenizer.pad_token_id, -100, labels
)
outputs = model(input_ids=input_ids, labels=labels)
total_loss += outputs.loss.item()
n_batches += 1
del input_ids, labels, outputs
torch.cuda.empty_cache()
return total_loss, n_batches
async def run(self):
# Start background block listener
self.loop = asyncio.get_running_loop()
self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=CPU_COUNT)
self.loop.set_default_executor(self.executor)
self.listener = threading.Thread(
target=self.block_listener, args=(self.loop,), daemon=True
).start()
# Use config peers if provided
if self.config.peers:
self.comms.peers = self.config.peers
self.comms.commitments = await self.comms.get_commitments()
self.comms.update_peers_with_buckets()
tplr.logger.info("Loaded commitments")
# Only post start window if you are the highest stake validator
if self.uid == self.metagraph.S.argmax().item():
# Check if an existing start window already exists
try:
existing_start_window = await self.comms.get_start_window(retries=2)
except Exception as e:
tplr.logger.warning(f"Error fetching existing start_window: {e}")
existing_start_window = None
if existing_start_window is not None:
self.start_window = existing_start_window
tplr.logger.info(
f"Highest staked validator found existing start_window: {self.start_window}"
)
else:
# No existing start window, so post new start window to R2
await self.comms.post_start_window(self.start_window)
tplr.logger.info(
f"This validator is the highest staked. Posted start_window: {self.start_window}"
)
else:
tplr.logger.info(
"This validator is not the highest staked. Waiting to fetch start_window."
)
self.start_window = await self.comms.get_start_window()
if self.start_window is None:
raise RuntimeError(
"Could not find a valid start window. This should not be possible."
)
self.global_step = self.current_window - self.start_window
tplr.logger.info(
f"Using start_window: {self.start_window}, global_step: {self.global_step}"
)
checkpoint_window_buffer = 5
has_new_checkpoint = (
self.global_step
>= self.hparams.checkpoint_frequency + checkpoint_window_buffer
)
# Proceed to load checkpoint
(
success,
loaded_momentum,
loaded_checkpoint_window,
loaded_optimizer,
loaded_scheduler,
) = await self.comms.load_checkpoint(
model=self.model,
optimizer=self.optimizer,
scheduler=self.scheduler,
current_window=self.current_window,
device=self.config.device,
init_version=tplr.__version__
if has_new_checkpoint
else self.bootstrap_version,
)
if success:
self.momentum = loaded_momentum
self.optimizer = loaded_optimizer
self.scheduler = loaded_scheduler
tplr.logger.info(
f"Loaded checkpoint with global_step={self.global_step}, "
f"optimizer_step={self.optimizer.state_dict()['state'].get(0, {}).get('step', 0)}, "
f"scheduler_step={self.scheduler.last_epoch}"
)
# Only catch up if we're behind
if (
loaded_checkpoint_window < self.current_window
and self.global_step > checkpoint_window_buffer
):
tplr.logger.info(
f"Checkpoint is behind current window ({loaded_checkpoint_window} < {self.current_window}), starting catchup..."
)
await tplr.neurons.catchup_with_aggregation_server(
self, max(loaded_checkpoint_window, self.start_window)
)
else:
tplr.logger.info("Checkpoint is up-to-date, skipping catchup.")
else:
tplr.logger.info("Starting from scratch")
self.momentum = {
n: torch.zeros_like(p) for n, p in self.model.named_parameters()
}
self.model.to(self.config.device)
self.comms.start_commitment_fetcher()
self.comms.start_background_tasks()
time_min = None
self.last_peer_update_window = None
self.last_peer_post_window = None
while True:
# 1. Wait for the validator window offset
while self.sync_window >= (
self.current_window - self.hparams.validator_offset
):
tplr.logger.info(
f"Waiting for validator window offset, synced: {self.sync_window}, current:{self.current_window}, offset:{self.hparams.validator_offset}"
)
await asyncio.sleep(12)
# 2. Increment sync window and update peer lists
window_start = tplr.T()
self.sync_window += 1
tplr.logger.info(
f"Sync Window: {self.sync_window}, Scheduler epoch: {self.scheduler.last_epoch}, Global step: {self.global_step}"
)
tplr.logger.info(
f"Processing window: {self.sync_window} current: {self.current_window}"
)
# Save state
self.save_state()
# Create and post peers
initial_selection = False
if (
self.last_peer_update_window is None
or self.sync_window - self.last_peer_update_window
>= self.hparams.peer_replacement_frequency
):
reason = (
f"{self.last_peer_update_window=}"
if self.last_peer_update_window is None
else f"{self.sync_window=}>="
f"{self.last_peer_update_window}+"
f"{self.hparams.peer_replacement_frequency}="
"self.last_peer_update_window+"
"self.hparams.peer_replacement_frequency"
)
tplr.logger.info(
f"Time to create and post a new peer list because {reason}"
)
if self.last_peer_update_window is None:
selected_peers = self.select_initial_peers()
initial_selection = True
else:
selected_peers = self.select_next_peers()
if selected_peers is not None:
self.last_peer_update_window = self.sync_window
await self.comms.post_peer_list(
peers=selected_peers,
first_effective_window=self.current_window
+ self.hparams.peer_list_window_margin,
sync_window=self.sync_window,
weights=self.weights,
initial_selection=initial_selection,
)
self.comms.update_peers_with_buckets()
peer_start = tplr.T()
await tplr.neurons.update_peers(
instance=self, window=self.sync_window, peer_start=peer_start
)
self.eval_peers = self.comms.eval_peers
tplr.logger.info(
f"{tplr.P(self.sync_window, tplr.T() - peer_start)} Updated peers - eval:{len(self.eval_peers)}"
)
tplr.logger.info(f"Current gather peers: {self.comms.peers}")
tplr.logger.info(f"Current evaluation peers: {self.eval_peers}")
tplr.logger.info(f"Current gather peers: {self.comms.peers}")
tplr.logger.info(
f"Current evaluation peers: {list(self.eval_peers.keys())}"
)
newly_inactive = self.comms.inactive_peers
current_window = self.sync_window
# 3. Process inactive peers and apply penalties
for uid in newly_inactive:
if uid not in self.inactive_scores:
self.inactive_scores[uid] = (
current_window,
self.final_scores[uid].item(),
)
tplr.logger.info(
f"UID {uid} became inactive at window {current_window} with score {self.final_scores[uid].item():.4f}"
)
# Apply penalties to all inactive peers
for uid, (inactive_since, _) in list(self.inactive_scores.items()):
# If peer became active again, remove from inactive tracking
if uid in self.eval_peers.keys():
del self.inactive_scores[uid]
tplr.logger.info(f"UID {uid} became active again")
continue
peer_reset = self.reset_peer(inactive_since, uid)
if peer_reset:
continue
# Apply flat 25% penalty instead of exponential decay
old_score = self.final_scores[uid].item()
new_score = old_score # Initialize new_score with old_score value
if self.final_scores[uid] > 0:
self.final_scores[uid] *= (
0.75 # Apply flat 25% reduction for positive scores only
)
new_score = self.final_scores[uid].item()
tplr.logger.info(
f"UID {uid} penalized for inactivity: "
f"{old_score:.4f} -> {new_score:.4f}"
)
# Log slash metrics to WandB
self.wandb.log(
{
f"validator/inactivity/{uid}/score_before": old_score,
f"validator/inactivity/{uid}/score_after": new_score,
},
step=self.global_step,
)
# Log slash metrics to InfluxDB with primitive types
self.metrics_logger.log(
measurement="validator_inactivity",
tags={
"uid": str(uid),
"window": int(current_window),
"global_step": int(self.global_step),
},
fields={
"score_before": float(old_score),
"score_after": float(new_score),
},
with_system_metrics=True,
with_gpu_metrics=True,
)
# Calculate time window for this sync window
sync_block = (self.sync_window + 1) * self.hparams.blocks_per_window
retries = 0
delay = 1
max_retries = 2
max_delay = 60
while True:
try:
response = self.subtensor.query_module(
"Timestamp", "Now", block=sync_block
)
ts_value = response.value / 1000 # convert ms to seconds
break
except Exception as e:
tplr.logger.error(
f"Failed to query timestamp for block {sync_block}: {str(e)}. Retry {retries + 1}/{max_retries}"
)
retries += 1
if retries > max_retries:
tplr.logger.error(
"Exceeded maximum retries for timestamp query. Falling back to current system time."
)
ts_value = (
time.time()
) # Fallback: use current system time as timestamp
break
await asyncio.sleep(delay)
delay = min(delay * 2, max_delay)
time_min = datetime.fromtimestamp(ts_value, tz=timezone.utc)
time_max = time_min + timedelta(
seconds=self.hparams.time_window_delta_seconds
)
# Log the time window we're using
tplr.logger.info(f"Using time window for gather: {time_min} to {time_max}")
tplr.logger.info(f"We are using peers {self.comms.peers}")
# Refresh peers explicitly before starting gather to avoid missing updated active peers.
tplr.logger.info("Refreshing eval peers before gather task in validator...")
if self.config.test:
# In test mode, use all UIDs from metagraph except self
tplr.logger.info("Test mode active: Using all peers from metagraph.")
all_uids = list(range(len(self.metagraph.S)))
self.comms.peers = [uid for uid in all_uids if uid != self.uid]
# For evaluation, also use all peers but track separately with equal initial weight
self.eval_peers = {uid: 1 for uid in self.comms.peers}
else:
# Normal operation - update and filter peers
self.comms.update_peers_with_buckets()
self.eval_peers = self.comms.eval_peers
tplr.logger.info(f"Validator gather peers: {self.comms.peers}")
gather_start = tplr.T()
skipped_uids: list[int] = []
success_rate = 0.0
gather_result = None
aggregation_result = await self.comms.load_aggregation(self.sync_window)
if aggregation_result is None:
gather_result = await self.comms.gather(
my_uid=self.uid,
uids=self.comms.peers,
window=self.sync_window,
key="gradient",
timeout=35,
device=self.config.device,
local=False,
totalks=self.totalks,
time_min=time_min,
time_max=time_max,
)
if gather_result is None:
tplr.logger.error(
"Failed to gather gradients from peers. Waiting for next window."
)
self.global_step += 1
continue
skipped_uids = gather_result.skipped_uids
success_rate = gather_result.success_rate
else:
state_dict = cast(dict, aggregation_result.get("state_dict"))
skipped_uids = cast(list[int], state_dict.get("skipped_uids", []))
success_rate = cast(float, state_dict.get("success_rate", 0.0))
gather_time = tplr.T() - gather_start
from_aggregator = 1 if aggregation_result is not None else 0
tplr.logger.info(
f"Using gradient source: {'aggregator' if from_aggregator else 'gather'}"
)
self.wandb.log(
{
"validator/aggregator_gradient": from_aggregator,
},
step=self.global_step,
)
tplr.logger.info(f"Skipped UIDs: {skipped_uids}")
gather_sync_scores = await asyncio.gather(
*(self.evaluate_miner_sync(uid) for uid in self.comms.peers)
)
for score_info, uid in zip(gather_sync_scores, self.comms.peers):
avg_steps_behind = score_info.get("avg_steps_behind", 99.0)
success = score_info.get("success", False)
if not success or avg_steps_behind > self.hparams.sync_max_steps_behind:
tplr.logger.info(
"Slashing %s: avg_steps_behind=%.2f > max=%d",
uid,
avg_steps_behind,
self.hparams.sync_max_steps_behind,
)
if self.final_scores[uid] > 0:
self.final_scores[uid] *= self.sync_score_slash_rate
self.binary_moving_averages[uid] *= self.sync_score_slash_rate
# Slash peers failing to submit gradients
for uid in skipped_uids:
tplr.logger.info(
f"No gradient gathered from UID {uid}. Slashing moving average score by {1 - self.missing_gradient_slash_rate:.2%}."
)
if 0 <= uid < self.final_scores.size(0):
old_score = self.final_scores[uid].item()
# Only reduce positive scores
if self.final_scores[uid] > 0:
self.final_scores[uid] *= self.missing_gradient_slash_rate
self.binary_moving_averages[uid] *= (
self.missing_gradient_slash_rate
)
new_score = self.final_scores[uid].item()
tplr.logger.info(
f"Reduced score of UID {uid} from {old_score:.4f} to {new_score:.4f} "
f"due to missing gradient in gather."
)
else:
tplr.logger.info(
f"Skipped score of UID {uid} (current score: {old_score:.4f}) "
f"due to negative or zero value."
)
self.evaluated_uids.add(uid)
else:
tplr.logger.info(
f"UID {uid} not found in final_scores; skipping penalty."
)
# Add check for empty peers (evaluating all peer uids)
if len(self.comms.eval_peers) == 0:
tplr.logger.warning(
f"No peers available for evaluation in window {self.sync_window}. Waiting for next window."
)
self.global_step += 1
continue
# 5. Save original model state for evaluation
eval_start = tplr.T()
# 6. Select peers to evaluate
candidate_uids = list(self.eval_peers.keys())
candidate_weights = [self.eval_peers[uid] for uid in candidate_uids]
k = min(self.hparams.uids_per_window, len(candidate_uids))
evaluation_uids = self.comms.weighted_random_sample_no_replacement(
candidate_uids, candidate_weights, k
)
# Reset counters for chosen peers
for uid in evaluation_uids:
self.eval_peers[uid] = 1
# Increment counters for not chosen peers
for uid in candidate_uids:
if uid not in evaluation_uids:
self.eval_peers[uid] += 1
self.comms.eval_peers = self.eval_peers
tplr.logger.info(f"Evaluating random subset of peers: {evaluation_uids}")
avg_loss_before_per_batch_own = 0.0
avg_loss_after_per_batch_own = 0.0
avg_loss_before_per_batch_random = 0.0
avg_loss_after_per_batch_random = 0.0
evaluated_peers = 0
# Pre-load common random loader for all evaluated UIDs in this window.
data_start_random = tplr.T()
# Load the random loader directly
random_seed = random.randint(
1000, 10000000
) # Using high seed number for random context
tplr.logger.info(
f"Loading common random dataloader with seed {random_seed}"
)
try:
random_loader_data = await self.preload_dataloader(seed=random_seed)
if random_loader_data:
common_loader_random = random_loader_data["loader"]
tplr.logger.info(
f"{tplr.P(self.sync_window, tplr.T() - data_start_random)} Loaded common random loader for evaluation."
)
else:
tplr.logger.error(
"Random loader was None, cannot continue evaluation"
)
continue
except Exception as e:
tplr.logger.error(f"Error loading random loader: {str(e)}")
continue
# Setup for sliding window approach
evaluation_uids_queue = list(
evaluation_uids
) # Create a copy of the list to work with
next_uid_dataloader_task = None
next_uid = None
# If we have at least one UID to evaluate, start loading the first one
if evaluation_uids_queue:
next_uid = evaluation_uids_queue.pop(0)
tplr.logger.info(f"Starting preload for first UID: {next_uid}")
next_uid_dataloader_task = asyncio.create_task(
self.preload_dataloader(seed=next_uid)
)