Repository navigation
Expand file tree
/
Copy pathcomms.py
More file actions
2051 lines (1767 loc) · 78.4 KB
/
Copy pathcomms.py
File metadata and controls
2051 lines (1767 loc) · 78.4 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.
# type: ignore
import asyncio
import concurrent.futures
import json
import math
import os
import random
import re
import time
from datetime import datetime, timezone
# from .hparams import HParams
from types import SimpleNamespace
from typing import Any, Dict, List, Literal, Optional, Tuple
import aiofiles
import bittensor as bt
import botocore
import numpy as np
import torch
from aiobotocore.client import AioBaseClient
from aiobotocore.session import get_session
from botocore.exceptions import ClientError, ConnectionClosedError
from torch.optim import SGD
from torch.optim.lr_scheduler import SequentialLR
from tqdm import tqdm as std_tqdm
from transformers import LlamaForCausalLM
import tplr as tplr
from . import __version__
from .chain import ChainManager
from .compress import CompressDCT, TransformDCT
from .config import BUCKET_SECRETS, client_config
from .schemas import Bucket
# Constants
CF_REGION_NAME: str = "enam"
LOCAL_TMP_DIR = "/tmp/local_store"
PEERS_FILE_PREFIX = "peers_"
CPU_COUNT = os.cpu_count() or 4
CPU_MAX_CONNECTIONS = min(100, max(30, CPU_COUNT * 4))
# Types
PeerArray = np.ndarray[Any, np.dtype[np.int64]]
class Comms(ChainManager):
def __init__(
self,
wallet: "bt.wallet",
save_location: str = "/tmp",
key_prefix: str = "model",
config=None,
netuid=None,
metagraph=None,
hparams=None,
uid=None,
**kwargs,
):
self.wallet = wallet
self.uid = uid
# Create temp directory for this instance
self.temp_dir = os.path.join("/tmp", f"templar_{self.uid}")
os.makedirs(self.temp_dir, exist_ok=True)
# Get the bucket directly
self.bucket = self.get_own_bucket("gradients", "write")
# Now initialize ChainManager with the bucket
super().__init__(
config=config,
netuid=netuid,
metagraph=metagraph,
hparams=hparams,
wallet=self.wallet,
bucket=self.bucket,
)
# Use the hotkey directly in the save_location
hotkey = self.wallet.hotkey.ss58_address
self.save_location = os.path.join("/tmp", f"hotkey_{hotkey}")
os.makedirs(self.save_location, exist_ok=True)
self.key_prefix = key_prefix
## a single aiobotocore session and a dictionary of clients
self.session = get_session()
self._s3_clients: dict[
tuple[str, str, str], AioBaseClient
] = {} # (acc_key, sec_key, account_id) -> s3_client
self.lock = asyncio.Lock()
self.active_peers = set() # Set to store active peers
self.active_check_interval = (
self.hparams.active_check_interval
) # Interval in seconds
self.recent_windows = (
self.hparams.recent_windows
) # Number of recent windows to check
self.client_semaphore = asyncio.Semaphore(CPU_MAX_CONNECTIONS)
# keep a reference to the *whole* ckpt that was loaded once, so
# miners / validators can consult keys such as `start_window`.
self.last_checkpoint_data: dict[str, Any] | None = None
async def _get_s3_client(self, bucket: Bucket):
"""
Returns a persistent s3_client for the given bucket credentials.
We create it if we haven't already, else reuse the existing client.
"""
key = (bucket.access_key_id, bucket.secret_access_key, bucket.account_id)
if key in self._s3_clients:
return self._s3_clients[key]
# Create the base URL
endpoint_url = self.get_base_url(bucket.account_id)
# Create the client (equivalent to `async with`, but we store the client persistently)
new_client = self.session.create_client(
"s3",
endpoint_url=endpoint_url,
region_name=CF_REGION_NAME,
config=client_config,
aws_access_key_id=bucket.access_key_id,
aws_secret_access_key=bucket.secret_access_key,
)
# We must manually do an async enter
new_client = await new_client.__aenter__()
self._s3_clients[key] = new_client
return new_client
async def close_all_s3_clients(self):
"""
Closes all S3 clients that have been created and stored
"""
for key, client in list(self._s3_clients.items()):
try:
await client.__aexit__(None, None, None)
except Exception as e:
tplr.logger.warning(f"Error closing s3_client {key}: {e}")
self._s3_clients.clear()
async def _purge_s3_client(self, bucket: Bucket) -> None:
key = (bucket.access_key_id, bucket.secret_access_key, bucket.account_id)
if key in self._s3_clients:
del self._s3_clients[key]
def start_background_tasks(self):
self.loop = asyncio.get_running_loop()
self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=CPU_COUNT)
self.loop.set_default_executor(self.executor)
# Start background tasks
self.loop.create_task(self.track_active_peers())
def get_own_bucket(
self,
bucket_type: Literal["gradients", "dataset", "aggregator"],
access_type=None,
) -> Bucket:
"""Gets bucket configuration from environment variables via config.BUCKET_SECRETS.
Args:
bucket_type: Either "gradients" or "dataset" to determine which bucket to use
access_type: For gradients bucket, either "read" or "write" to determine access level
"""
try:
if bucket_type not in ["gradients", "dataset", "aggregator"]:
raise ValueError("bucket_type must be either 'gradients' or 'dataset'")
if bucket_type in ["gradients", "aggregator"]:
if access_type not in ["read", "write"]:
raise ValueError(
f"For {bucket_type} bucket, access_type must be either 'read' or 'write'"
)
bucket_config = BUCKET_SECRETS[bucket_type]
credentials = bucket_config["credentials"][access_type] # type: ignore
else: # dataset bucket
bucket_config = BUCKET_SECRETS["dataset"]
# For dataset, we'll use read credentials by default
credentials = bucket_config["credentials"]["read"] # type: ignore
# Create a Bucket object using specified credentials
bucket = Bucket(
name=bucket_config["name"],
account_id=bucket_config["account_id"],
access_key_id=credentials["access_key_id"],
secret_access_key=credentials["secret_access_key"],
)
tplr.logger.debug(
f"Created {bucket_type} bucket with {'read/write' if bucket_type == 'dataset' else access_type} access: {bucket}"
)
return bucket
except KeyError as e:
tplr.logger.error(f"Missing required R2 configuration: {e}")
raise
except Exception as e:
tplr.logger.error(f"Error creating bucket: {e}")
raise
def get_base_url(self, account_id):
"""Constructs the base URL for the R2 storage endpoint."""
return f"https://{account_id}.r2.cloudflarestorage.com"
def delete_local_directory(self, path: str):
"""Safely remove a local directory and all its contents."""
if not os.path.exists(path):
return
for root, dirs, files in os.walk(path, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
os.rmdir(path)
# Convert all the existing functions to methods
async def cleanup_local_data(
self, uid: str, current_window: int, stale_retention: int
):
"""Clean up stale local data for a given uid."""
user_dir = os.path.join(LOCAL_TMP_DIR, str(uid))
if not os.path.exists(user_dir):
return
min_allowed_window = current_window - stale_retention
for wdir in os.listdir(user_dir):
if wdir.isdigit():
w = int(wdir)
if w < min_allowed_window:
old_path = os.path.join(user_dir, wdir)
tplr.logger.debug(f"Removing stale local directory: {old_path}")
try:
self.delete_local_directory(old_path)
except Exception as e:
tplr.logger.debug(
f"Error removing stale directory {old_path}: {e}"
)
async def cleanup_s3_data(
self, uid: str, current_window: int, stale_retention: int
):
"""Clean up stale S3 data for a given uid."""
try:
min_allowed_window = current_window - stale_retention
# Regex pattern to match filenames of the form:
# gradient-<window>-<uid>-v<version>.pt
pattern = re.compile(rf"^gradient-(\d+)-{uid}-v{tplr.__version__}.pt$")
prefix = "gradient"
# so we get the same credentials as `self.bucket`
s3_client = await self._get_s3_client(self.bucket)
continuation_token = None
while True:
list_args = {
"Bucket": self.bucket.name,
"Prefix": prefix,
"MaxKeys": 1000,
}
if continuation_token:
list_args["ContinuationToken"] = continuation_token
response = await s3_client.list_objects_v2(**list_args)
contents = response.get("Contents", [])
# Identify stale objects to delete
stale_objects = []
for obj in contents:
key = obj["Key"]
# Attempt to match our known filename pattern
match = pattern.match(key)
if match is None:
continue
try:
file_window = int(match.group(1))
except ValueError:
continue
if file_window < min_allowed_window:
stale_objects.append({"Key": key})
# Batch delete stale objects
if len(stale_objects) > 0:
tplr.logger.debug(
f"Removing stale S3 objects for {uid}: {stale_objects}"
)
await s3_client.delete_objects(
Bucket=self.bucket.name,
Delete={"Objects": stale_objects},
)
if response.get("IsTruncated"):
continuation_token = response.get("NextContinuationToken")
else:
break
except (ConnectionClosedError, ClientError):
await self._purge_s3_client(self.bucket)
async def s3_put_object(
self,
key: str,
file_path: Optional[str] = None,
):
"""
Puts an object into S3 storage, handling different file types appropriately.
Args:
key (str): The key/path to store the data under
file_path (str, optional): The local file path to upload
bucket (Bucket, optional): The bucket to use. Defaults to self.bucket
"""
try:
bucket = self.bucket
s3_client = await self._get_s3_client(bucket)
# Handle JSON files
if key.endswith(".json") or "start_window" in key:
if file_path:
async with aiofiles.open(file_path, "r") as f:
data = await f.read()
data_bytes = json.dumps(json.loads(data)).encode("utf-8")
else:
raise ValueError(f"file_path required for JSON file: {key}")
await s3_client.put_object(Bucket=bucket.name, Key=key, Body=data_bytes)
return
# Otherwise, likely PyTorch files
file_size = os.path.getsize(file_path)
multipart_threshold = 100 * 1024 * 1024 # 100MB
if file_size <= multipart_threshold:
# Simple upload for small files
async with aiofiles.open(file_path, "rb") as f:
data = await f.read()
await s3_client.put_object(Bucket=bucket.name, Key=key, Body=data)
else:
# Multipart upload for large files
await self.upload_large_file(file_path, key, s3_client)
except (ConnectionClosedError, ClientError):
await self._purge_s3_client(bucket)
except Exception as e:
tplr.logger.error(f"Error uploading {key} to S3: {e}")
raise
async def s3_get_object(
self,
key: str,
bucket: Bucket = None,
timeout: int = 15,
time_min: datetime = None,
time_max: datetime = None,
):
"""Download object from S3 using asynchronous streaming."""
import uuid
temp_file_path = os.path.join(
self.temp_dir, f"temp_{key}_{uuid.uuid4().hex}.pt"
)
s3_client = await self._get_s3_client(bucket)
try:
# Normalize timezone info
if time_min is not None and not time_min.tzinfo:
time_min = time_min.replace(tzinfo=timezone.utc)
if time_max is not None and not time_max.tzinfo:
time_max = time_max.replace(tzinfo=timezone.utc)
# HEAD the object
try:
response = await asyncio.wait_for(
s3_client.head_object(Bucket=bucket.name, Key=key),
timeout=timeout,
)
last_modified = response.get("LastModified")
if last_modified is None:
tplr.logger.info(f"Object does not exist: {key}")
return None
if time_min is not None and last_modified < time_min:
time_diff = (time_min - last_modified).total_seconds()
tplr.logger.info(
f"Object {key} was uploaded {time_diff:.2f}s before time_min."
)
return {"__status": "TOO_EARLY"}
if time_max is not None and last_modified > time_max:
time_diff = (last_modified - time_max).total_seconds()
tplr.logger.info(
f"Object {key} was uploaded {time_diff:.2f}s after time_max."
)
return {"__status": "TOO_LATE"}
except asyncio.TimeoutError:
tplr.logger.debug(f"Timeout checking for {key}")
return None
except (ConnectionClosedError, ClientError) as e:
await self._purge_s3_client(bucket)
if "404" in str(e):
tplr.logger.debug(f"Object {key} not found in bucket {bucket.name}")
return None
file_size = response["ContentLength"] # type: ignore
# Download the object
if file_size <= 5 * 1024 * 1024 * 1024: # 5GB
response = await asyncio.wait_for(
s3_client.get_object(Bucket=bucket.name, Key=key),
timeout=timeout,
)
async with aiofiles.open(temp_file_path, "wb") as f:
async with response["Body"] as stream:
data = await asyncio.wait_for(stream.read(), timeout=timeout)
await f.write(data)
else:
success = await self.download_large_file(
s3_client=s3_client,
bucket=bucket,
key=key,
file_size=file_size,
temp_file_path=temp_file_path,
)
if not success:
return None
# Now load the data
if key.endswith(".json") or "start_window" in key:
async with aiofiles.open(temp_file_path, "r") as f:
data = await f.read()
loaded_data = json.loads(data)
else:
loaded_data = torch.load(
temp_file_path,
map_location=self.config.device,
weights_only=False,
)
return loaded_data
except asyncio.TimeoutError:
tplr.logger.debug(f"Timeout downloading {key}")
return None
except Exception as e:
tplr.logger.error(f"Error in s3_get_object for {key}: {e}")
return None
finally:
if os.path.exists(temp_file_path):
os.remove(temp_file_path)
# Large File Operations
async def upload_large_file(self, file_path: str, key: str, s3_client):
"""Uploads a large file to S3 using asynchronous multipart upload with 5MB chunks."""
upload_id = None
MAX_RETRIES = 3
PART_SIZE = 5 * 1024 * 1024 # 5MB
try:
async with self.client_semaphore:
for attempt in range(MAX_RETRIES):
try:
response = await s3_client.create_multipart_upload(
Bucket=self.bucket.name, Key=key
)
upload_id = response["UploadId"]
break
except Exception:
if attempt == MAX_RETRIES - 1:
raise
await asyncio.sleep(2**attempt)
file_size = os.path.getsize(file_path)
total_parts = math.ceil(file_size / PART_SIZE)
parts = []
async def upload_part(part_number: int):
byte_range_start = (part_number - 1) * PART_SIZE
byte_range_end = min(byte_range_start + PART_SIZE, file_size)
for attempt in range(MAX_RETRIES):
try:
async with aiofiles.open(file_path, "rb") as f:
await f.seek(byte_range_start)
data = await f.read(byte_range_end - byte_range_start)
response = await s3_client.upload_part(
Bucket=self.bucket.name,
Key=key,
PartNumber=part_number,
UploadId=upload_id,
Body=data,
)
return {
"ETag": response["ETag"],
"PartNumber": part_number,
}
except Exception as e:
if attempt == MAX_RETRIES - 1:
tplr.logger.error(
f"Failed to upload part {part_number} after {MAX_RETRIES} attempts: {e}"
)
raise
await asyncio.sleep(2**attempt)
# Launch one coroutine per part
try:
part_results = await asyncio.gather(
*[
upload_part(part_number)
for part_number in range(1, total_parts + 1)
]
)
parts.extend(part_results)
except Exception as e:
tplr.logger.error(f"Multipart upload failed: {e}")
raise
parts.sort(key=lambda x: x["PartNumber"])
for attempt in range(MAX_RETRIES):
try:
await s3_client.complete_multipart_upload(
Bucket=self.bucket.name,
Key=key,
UploadId=upload_id,
MultipartUpload={"Parts": parts},
)
tplr.logger.info(f"Successfully uploaded {key}")
break
except Exception:
if attempt == MAX_RETRIES - 1:
raise
await asyncio.sleep(2**attempt)
except (ConnectionClosedError, ClientError):
await self._purge_s3_client(self.bucket)
except Exception as e:
tplr.logger.error(f"Error during multipart upload of {key}: {e}")
if upload_id:
try:
await s3_client.abort_multipart_upload(
Bucket=self.bucket.name, Key=key, UploadId=upload_id
)
except Exception as abort_e:
tplr.logger.error(f"Failed to abort multipart upload: {abort_e}")
raise
async def download_large_file(
self, s3_client, bucket: Bucket, key: str, file_size: int, temp_file_path: str
):
"""Download large file using multipart download with concurrent chunks."""
try:
# Determine optimal chunk size and concurrency
gpu_available = torch.cuda.is_available()
if gpu_available:
gpu_mem = torch.cuda.get_device_properties(0).total_memory
max_workers = min(torch.cuda.device_count() * 4, 16)
chunk_size = min(
max(
5 * 1024 * 1024, # Minimum 5MB for S3 multipart
gpu_mem // (max_workers * 4),
),
5 * 1024 * 1024 * 1024, # Maximum 5GB
)
else:
cpu_count = os.cpu_count() or 1
max_workers = min(cpu_count * 4, 16)
chunk_size = min(
max(
5 * 1024 * 1024,
file_size // (max_workers * 2),
),
5 * 1024 * 1024 * 1024,
)
total_chunks = math.ceil(file_size / chunk_size)
max_workers = min(max_workers, total_chunks)
semaphore = asyncio.Semaphore(max_workers)
# Create the file with the correct size
async with aiofiles.open(temp_file_path, "wb") as f:
await f.truncate(file_size)
# Create progress bar
pbar = std_tqdm(
total=file_size,
unit="B",
unit_scale=True,
desc=f"Downloading {key} ({max_workers} workers)",
)
downloaded_chunks = {}
async def download_chunk(chunk_number: int, max_retries: int = 3):
"""Download a specific chunk with retries."""
for attempt in range(max_retries):
async with semaphore:
start = chunk_number * chunk_size
end = min(start + chunk_size, file_size) - 1
try:
response = await s3_client.get_object(
Bucket=bucket.name,
Key=key,
Range=f"bytes={start}-{end}",
)
async with response["Body"] as stream: # type: ignore
chunk_data = await stream.read()
# Verify chunk size matches expected
chunk_len = len(chunk_data)
expected_len = end - start + 1
if chunk_len != expected_len:
raise Exception(
f"Chunk size mismatch: got {chunk_len}, expected {expected_len}"
)
async with aiofiles.open(temp_file_path, "rb+") as f2:
await f2.seek(start)
await f2.write(chunk_data)
pbar.update(chunk_len)
downloaded_chunks[chunk_number] = {
"start": start,
"end": end + 1,
"size": chunk_len,
}
return chunk_number
except Exception as e:
tplr.logger.error(
f"Error downloading chunk {chunk_number} (attempt {attempt + 1}/{max_retries}): {e}"
)
if attempt == max_retries - 1: # Last attempt
raise
await asyncio.sleep(
1 * (attempt + 1)
) # Exponential backoff
try:
tasks = [
asyncio.create_task(download_chunk(i)) for i in range(total_chunks)
]
await asyncio.gather(*tasks)
if len(downloaded_chunks) != total_chunks:
missing_chunks = set(range(total_chunks)) - set(
downloaded_chunks.keys()
)
raise Exception(f"Missing chunks: {missing_chunks}")
downloaded_size = sum(
chunk["size"] for chunk in downloaded_chunks.values()
)
if downloaded_size != file_size:
raise Exception(
f"Downloaded size ({downloaded_size}) != expected size ({file_size})"
)
return True
finally:
pbar.close()
except (ConnectionClosedError, ClientError):
await self._purge_s3_client(bucket)
except Exception as e:
tplr.logger.error(f"Error in download_large_file for {key}: {e}")
return False
async def put(
self,
state_dict: dict,
uid: str | None,
window: int,
key: Literal["checkpoint", "debug", "gradient", "aggregator"],
global_step: int = 0,
local: bool = True,
stale_retention: int = 10,
) -> float:
"""
Saves the data locally or uploads to S3, then cleans up stale files.
Args:
state_dict (dict): Data to save.
uid (str): Target user/miner identifier.
window (int): Current training window.
key (str): Label for the data (e.g., "gradient").
global_step (int, optional): Global step counter. Defaults to 0.
local (bool, optional): If True, store locally; otherwise upload to S3. Defaults to True.
stale_retention (int, optional): Number of windows to keep before cleanup. Defaults to 10.
Returns:
float: The elapsed time (in seconds) for the PUT operation.
"""
if key == "aggregator":
filename = f"{key}-{window}-v{__version__}.pt"
else:
filename = f"{key}-{window}-{uid}-v{__version__}.pt"
tplr.logger.debug(f"PUT {filename} -->")
put_start = tplr.T()
# Create per-uid temp directory
temp_dir = os.path.join("/tmp", str(self.uid))
os.makedirs(temp_dir, exist_ok=True)
temp_file_path = os.path.join(temp_dir, f"temp_{filename}")
try:
# Prepare the data to be saved
if key == "checkpoint":
save_data = state_dict
else:
save_data = {
"state_dict": state_dict,
"global_step": global_step,
}
# Save to temp file
torch.save(save_data, temp_file_path)
if local:
# Local storage with per-uid directories
await self.cleanup_local_data(
uid=uid, current_window=window, stale_retention=stale_retention
)
local_dir = os.path.join(LOCAL_TMP_DIR, str(uid), str(window))
os.makedirs(local_dir, exist_ok=True)
final_path = os.path.join(local_dir, filename)
os.replace(temp_file_path, final_path)
else:
await self.s3_put_object(filename, temp_file_path)
# Remote storage with automatic handling of large files
asyncio.create_task(
self.cleanup_s3_data(
uid=uid, current_window=window, stale_retention=stale_retention
)
)
finally:
if os.path.exists(temp_file_path):
os.remove(temp_file_path)
put_end = tplr.T()
tplr.logger.info(f"{tplr.P(window, put_end - put_start)} PUT {filename} <--")
return put_end - put_start
async def get(
self,
uid: str,
window: int,
key: str,
local: bool = True,
stale_retention: int = 10,
time_min: datetime = None,
time_max: datetime = None,
) -> Optional[tuple[dict, int]]:
"""GET operation."""
filename = f"{key}-{window}-{uid}-v{__version__}.pt"
tplr.logger.debug(f"GET {filename} -->")
try:
if local:
# Local storage logic remains unchanged
await self.cleanup_local_data(
uid=uid, current_window=window, stale_retention=stale_retention
)
local_path = os.path.join(
LOCAL_TMP_DIR, str(uid), str(window), filename
)
if not os.path.exists(local_path):
tplr.logger.debug(f"Local file not found: {local_path}")
return None
loaded_data = torch.load(local_path, weights_only=True)
if key == "checkpoint":
return loaded_data, None
state_dict = loaded_data.get("state_dict")
global_step = loaded_data.get("global_step", 0)
return state_dict, global_step
# Remote storage logic
peer_bucket = self.commitments.get(int(uid))
tplr.logger.debug(f"Peer bucket : {peer_bucket}")
if not peer_bucket:
return None
loaded_data = await self.s3_get_object(
key=filename,
bucket=peer_bucket,
time_min=time_min,
time_max=time_max,
)
if loaded_data is None:
return None
# Check for TOO_LATE/TOO_EARLY marker
if isinstance(loaded_data, dict):
if loaded_data.get("__status") == "TOO_LATE":
tplr.logger.info(
f"Object for UID {uid}, window {window}, key {key} was uploaded too late. Skipping."
)
return {"__status": "TOO_LATE"}
elif loaded_data.get("__status") == "TOO_EARLY":
tplr.logger.info(
f"Object for UID {uid}, window {window}, key {key} was uploaded too early. Skipping."
)
return {"__status": "TOO_EARLY"}
if key == "checkpoint":
return loaded_data, None
state_dict = loaded_data.get("state_dict")
global_step = loaded_data.get("global_step", 0)
return state_dict, global_step
except Exception as e:
tplr.logger.debug(f"GET error {filename}: {e}")
return None
finally:
tplr.logger.debug(f"GET {filename} <--")
async def get_with_retry(
self,
uid: str,
window: int,
key: str,
timeout: int,
local: bool = True,
stale_retention: int = 10,
time_min: datetime = None,
time_max: datetime = None,
) -> Optional[dict]:
"""GET with retry operation."""
start_time = time.time()
end_time = start_time + timeout
tried_after_time_max = False # Track if we've tried once after passing time_max
while True:
# Check if we've timed out
if time.time() >= end_time:
tplr.logger.debug(f"GET {uid}/{window}/{key} timed out.")
return None
# Check if we're past time_max
now = datetime.now(timezone.utc)
past_time_max = time_max is not None and now > time_max
# If we're past time_max and already tried once, don't retry again
if past_time_max and tried_after_time_max:
tplr.logger.debug(
f"Already tried once after time_max for UID {uid}, window {window}. Stopping retries."
)
return None
# Make the request
state_dict = await self.get(
uid=uid,
window=window,
key=key,
local=local,
stale_retention=stale_retention,
time_min=time_min,
time_max=time_max,
)
# Check for TOO_LATE/TOO_EARLY markers
if isinstance(state_dict, dict):
if state_dict.get("__status") == "TOO_LATE":
tplr.logger.info(
f"Gradient for UID {uid}, window {window} exists but was uploaded too late. Skipping."
)
return None
elif state_dict.get("__status") == "TOO_EARLY":
tplr.logger.info(
f"Gradient for UID {uid}, window {window} exists but was uploaded too early. Skipping."
)
return None
# If we got a result, return it
if state_dict is not None:
return state_dict
# If we're past time_max, mark that we've tried once
if past_time_max:
tried_after_time_max = True
tplr.logger.debug(
f"Past time_max for UID {uid}, window {window}. This is the final retry."
)
# Short delay before retrying
await asyncio.sleep(0.1)
async def gather(
self,
my_uid: int | None,
uids: List[int],
window: int,
key: str,
timeout: int,
device: str,
totalks: dict,
local: bool = True,
stale_retention: int = 10,
time_min: datetime = None,
time_max: datetime = None,
) -> Optional[SimpleNamespace]:
"""Gather operation with individual gradient normalization and connection management."""
start_time = time.time()
metrics = {"upload_bytes": 0, "download_bytes": 0, "successes": []}
tplr.logger.debug(
f"Starting gather for window {window} with time window: {time_min} to {time_max}"
)
tplr.logger.debug(
f"Gather operation - my_uid: {my_uid}, window: {window}, key: {key}, timeout: {timeout}"
)
tplr.logger.debug(f"Target UIDs for gathering: {uids}")
aggregated_state_dict = {}
valid_uids = []
skipped_uids = [] # Retain UIDs that are skipped.
global_steps = []
async with self.client_semaphore:
batch_tasks = [
self.get_with_retry(
uid=uid,
window=window,
key=key,
timeout=timeout,
local=local,
stale_retention=stale_retention,
time_min=time_min,
time_max=time_max,
)
for uid in uids
]
try:
batch_responses = await asyncio.gather(
*batch_tasks, return_exceptions=True
)
for uid, response in zip(uids, batch_responses):
if isinstance(response, Exception):
tplr.logger.debug(f"Error from UID {uid}: {str(response)}")
skipped_uids.append(uid)
continue
if response is None:
tplr.logger.info(f"Skipped UID {uid} - gradient not found.")
skipped_uids.append(uid)
continue
try:
state_dict_resp, global_step_resp = response
tplr.logger.debug(
f"Received state dict and global step {global_step_resp} from UID {uid}"
)
except (TypeError, ValueError) as e:
tplr.logger.debug(f"Invalid response from UID {uid}: {e}")
skipped_uids.append(uid)
continue
if state_dict_resp is None:
tplr.logger.debug(f"Empty state dict from UID {uid}")
skipped_uids.append(uid)
continue
# ---------- Begin Compressed Indices and Values Check ----------
valid_response = True
for param_name, tensor in state_dict_resp.items():