-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathtest_comms.py
More file actions
2815 lines (2343 loc) · 92.5 KB
/
Copy pathtest_comms.py
File metadata and controls
2815 lines (2343 loc) · 92.5 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
# ruff: noqa
import os
import random
from unittest.mock import patch, MagicMock, AsyncMock
import pytest
import torch
from types import SimpleNamespace
from dotenv import load_dotenv
import asyncio
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from tplr import load_hparams
hparams = load_hparams()
# Set required environment variables
os.environ["R2_GRADIENTS_ACCOUNT_ID"] = "test_account"
os.environ["R2_GRADIENTS_BUCKET_NAME"] = "test-bucket"
os.environ["R2_GRADIENTS_READ_ACCESS_KEY_ID"] = "test_read_key"
os.environ["R2_GRADIENTS_READ_SECRET_ACCESS_KEY"] = "test_read_secret"
os.environ["R2_GRADIENTS_WRITE_ACCESS_KEY_ID"] = "test_write_key"
os.environ["R2_GRADIENTS_WRITE_SECRET_ACCESS_KEY"] = "test_write_secret"
os.environ["R2_DATASET_BUCKET_NAME"] = "test-dataset-bucket"
# -----------------------------------------------------------------------------
# Helper functions
# -----------------------------------------------------------------------------
def create_xshapes_totalks(model):
xshapes = {}
totalks = {}
for name, param in model.named_parameters():
xshapes[name] = param.shape
totalks[name] = param.numel()
return xshapes, totalks
def create_valid_state_dict(model):
state_dict = {}
for name, _ in model.named_parameters():
state_dict[name + "idxs"] = torch.tensor([0, 1], dtype=torch.long)
state_dict[name + "vals"] = torch.tensor([0.1, 0.2], dtype=torch.float32)
return state_dict
def create_missing_idxs(model):
d = {}
for name, _ in model.named_parameters():
# Omit the "idxs" key intentionally.
d[name + "vals"] = torch.tensor([0.1, 0.2], dtype=torch.float32)
return d
# Mock Bucket class
@dataclass
class Bucket:
name: str
account_id: str
access_key_id: str
secret_access_key: str
# Mock the config module
@pytest.fixture(autouse=True)
def mock_config():
with (
patch(
"tplr.config.BUCKET_SECRETS",
{
"gradients": {
"account_id": "test_account",
"bucket_name": "test-bucket",
"read": {
"access_key_id": "test_read_key",
"secret_access_key": "test_read_secret",
},
"write": {
"access_key_id": "test_write_key",
"secret_access_key": "test_write_secret",
},
},
"dataset": {"bucket_name": "test-dataset-bucket"},
},
),
patch("tplr.config.client_config", {}),
):
yield
from tplr.schemas import Bucket
from tplr.compress import TransformDCT, CompressDCT
# Load environment variables from .env file
load_dotenv()
from tplr.comms import Comms
import tplr
from tplr import logger, debug
debug()
# Test fixture for comms instance
@pytest.fixture
async def comms_instance():
# Mock wallet
mock_wallet = MagicMock()
mock_wallet.hotkey.ss58_address = "test_address"
# Mock config and other dependencies
mock_config = MagicMock()
mock_metagraph = MagicMock()
mock_hparams = MagicMock()
mock_hparams.active_check_interval = 60
mock_hparams.recent_windows = 3
# Create comms instance with mocked get_own_bucket
with patch(
"tplr.comms.Comms.get_own_bucket",
return_value=Bucket(
name="test-bucket",
account_id="test-account",
access_key_id="test-key",
secret_access_key="test-secret",
),
):
comms = tplr.comms.Comms(
wallet=mock_wallet,
save_location="/tmp",
key_prefix="test",
config=mock_config,
netuid=1,
metagraph=mock_metagraph,
hparams=mock_hparams,
uid="test_uid",
)
yield comms
# Cleanup
if os.path.exists(comms.temp_dir):
import shutil
shutil.rmtree(comms.temp_dir)
if os.path.exists(comms.save_location):
shutil.rmtree(comms.save_location)
# Existing mock functions
def mock_bittensor_wallet():
wallet = MagicMock()
wallet.hotkey.ss58_address = "test_hotkey_address"
return wallet
def mock_bittensor_subtensor():
subtensor = MagicMock()
subtensor.block = MagicMock(return_value=1000)
return subtensor
class MockMetagraph:
"""Unified mock metagraph for all tests"""
def __init__(self):
self.hotkeys = [f"hotkey{i}" for i in range(10)]
self.uids = list(range(10))
self.n = len(self.uids)
self.S = torch.ones(self.n) # Stake values
self.block = 1000
self.netuid = 1
self.name = "mock_network"
def __getattr__(self, name):
"""Handle any unexpected attribute access"""
tplr.logger.debug(f"Accessing undefined metagraph attribute: {name}")
return None
@pytest.fixture
def mock_metagraph():
return MockMetagraph()
@pytest.fixture
async def comms_instance(mock_wallet, mock_metagraph):
return Comms(
wallet=mock_wallet,
save_location="/tmp",
key_prefix="test",
config=SimpleNamespace(netuid=1),
metagraph=mock_metagraph,
hparams=MockHParams(),
uid=1,
)
"""
Tests for the Comms class functionality focusing on local storage, data retrieval,
and gradient gathering operations.
"""
async def test_put_local(comms_instance):
"""Test 1: Local Storage Functionality
Tests the ability to store data locally by:
- Verifying data can be correctly stored in local filesystem
- Checking directory cleanup operations work properly
- Ensuring correct file creation with proper naming
- Validating storage location and structure
"""
test_state_dict = {"param": torch.tensor([1, 2, 3])}
uid = "0"
window = 1
key = "gradient"
expected_dir = os.path.join("/tmp/local_store", uid, str(window))
base_dir = os.path.dirname(expected_dir) # /tmp/local_store/0
if os.path.exists(base_dir):
for root, dirs, files in os.walk(base_dir, 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(base_dir)
with patch.object(comms_instance, "cleanup_local_data") as mock_cleanup:
await comms_instance.put(
state_dict=test_state_dict,
uid=uid,
window=window,
key=key,
local=True,
)
mock_cleanup.assert_called_once()
files = os.listdir(expected_dir)
assert len(files) == 1
assert files[0].startswith(key)
async def test_get_local(comms_instance):
"""Test 2: Local Data Retrieval
Validates the retrieval of locally stored data by:
- Testing correct loading of stored state dictionaries
- Verifying proper handling of global step information
- Ensuring cleanup operations are called during retrieval
- Checking data integrity after retrieval
"""
test_state_dict = {
"state_dict": {"param": torch.tensor([1, 2, 3])},
"global_step": 10,
}
uid = "0"
window = 1
key = "gradient"
filename = f"{key}-{window}-{uid}-v{tplr.__version__}.pt"
local_dir = os.path.join("/tmp/local_store", uid, str(window))
os.makedirs(local_dir, exist_ok=True)
local_path = os.path.join(local_dir, filename)
torch.save(test_state_dict, local_path)
with patch.object(comms_instance, "cleanup_local_data") as mock_cleanup:
state_dict, global_step = await comms_instance.get(
uid=uid,
window=window,
key=key,
local=True,
)
mock_cleanup.assert_called_once()
assert torch.equal(state_dict["param"], test_state_dict["state_dict"]["param"])
assert global_step == test_state_dict["global_step"]
@pytest.mark.asyncio
async def test_gather_basic_functionality(comms_instance):
"""Test 3: Basic Gradient Gathering
Tests fundamental gradient gathering operations by:
- Validating correct handling of multiple peer responses
- Verifying proper aggregation of gradients
- Checking accurate tracking of UIDs and global steps
- Ensuring correct structure of aggregated results
"""
comms_instance.check_compressed_indices = (
lambda param_name, idxs, totalk, allowed_topk=None: None
)
comms_instance.get_with_retry = AsyncMock()
totalk_value = 100
peer1_response = (
{
"0.weightidxs": torch.tensor([0, 1, 2]),
"0.weightvals": torch.tensor([0.4, 0.5, 0.6]),
"totalks": {"0.weight": totalk_value},
},
1,
)
peer2_response = (
{
"0.weightidxs": torch.tensor([0, 1, 2]),
"0.weightvals": torch.tensor([0.7, 0.8, 0.9]),
"totalks": {"0.weight": totalk_value},
},
2,
)
comms_instance.get_with_retry.side_effect = [peer1_response, peer2_response]
totalks = {"0.weight": totalk_value}
result = await comms_instance.gather(
my_uid="0",
uids=["1", "2"],
window=1,
key="gradient",
timeout=5,
device="cpu",
local=True,
stale_retention=10,
totalks=totalks,
)
assert result is not None, "Expected a non-None result"
assert result.uids == [
"1",
"2",
], f"Expected valid_uids ['1', '2'], got {result.uids}"
assert result.global_steps == [
1,
2,
], f"Expected global_steps [1, 2], got {result.global_steps}"
aggregated = result.state_dict.__dict__
for key in ["0.weightidxs", "0.weightvals"]:
assert key in aggregated, f"Expected key {key} in aggregated state_dict"
assert len(aggregated[key]) == 2, (
f"Expected 2 tensors for key {key}, got {len(aggregated[key])}"
)
@pytest.mark.asyncio
async def test_gather_normalization(comms_instance):
"""Test 4: Gradient Normalization
Validates gradient normalization functionality by:
- Testing proper handling of normalized gradients
- Verifying correct processing of single peer response
- Ensuring normalization maintains data integrity
"""
comms_instance.check_compressed_indices = (
lambda param_name, idxs, totalk, allowed_topk=None: None
)
comms_instance.get_with_retry = AsyncMock()
totalk_value = 100
peer_response = (
{
"0.weightidxs": torch.tensor([0, 1, 2]),
"0.weightvals": torch.tensor([0.4, 0.5, 0.6]),
"totalks": {"0.weight": totalk_value},
},
1,
)
comms_instance.get_with_retry.side_effect = [peer_response]
result = await comms_instance.gather(
my_uid="0",
uids=["1"],
window=1,
key="gradient",
timeout=5,
device="cpu",
local=True,
stale_retention=10,
totalks={"0.weight": totalk_value},
)
assert result is not None
@pytest.mark.asyncio
async def test_gather_empty_responses(comms_instance):
"""Test 5: Empty Response Handling
Tests system behavior with empty responses by:
- Verifying proper handling when peers return no data
- Ensuring system gracefully handles null responses
- Checking appropriate error states and return values
"""
comms_instance.check_compressed_indices = (
lambda param_name, idxs, totalk, allowed_topk=None: None
)
comms_instance.get_with_retry = AsyncMock(return_value=(None, None))
result = await comms_instance.gather(
my_uid="0",
uids=["1"],
window=1,
key="gradient",
timeout=5,
device="cpu",
local=True,
stale_retention=10,
totalks={"0.weight": 100},
)
assert result is None
@pytest.mark.asyncio
async def test_gather_averaging(comms_instance):
"""Test 6: Gradient Averaging
Validates gradient averaging functionality by:
- Testing correct averaging of gradients from multiple peers
- Verifying proper handling of global steps during averaging
- Ensuring averaged gradients maintain mathematical correctness
"""
comms_instance.check_compressed_indices = (
lambda param_name, idxs, totalk, allowed_topk=None: None
)
comms_instance.get_with_retry = AsyncMock()
totalk_value = 100
peer1_response = (
{
"0.weightidxs": torch.tensor([0, 1, 2]),
"0.weightvals": torch.tensor([0.4, 0.5, 0.6]),
"totalks": {"0.weight": totalk_value},
},
1,
)
peer2_response = (
{
"0.weightidxs": torch.tensor([0, 1, 2]),
"0.weightvals": torch.tensor([0.8, 0.9, 1.0]),
"totalks": {"0.weight": totalk_value},
},
2,
)
comms_instance.get_with_retry.side_effect = [peer1_response, peer2_response]
result = await comms_instance.gather(
my_uid="0",
uids=["1", "2"],
window=1,
key="gradient",
timeout=5,
device="cpu",
local=True,
stale_retention=10,
totalks={"0.weight": totalk_value},
)
assert result.global_steps == [1, 2]
@pytest.mark.asyncio
async def test_gather_complex_normalization(comms_instance):
"""Test 7: Complex Normalization Scenarios
Tests advanced normalization cases by:
- Validating handling of multiple keys in gradient responses
- Verifying normalization behavior with complex data structures
- Ensuring proper handling of multi-dimensional tensors
"""
comms_instance.check_compressed_indices = (
lambda param_name, idxs, totalk, allowed_topk=None: None
)
comms_instance.get_with_retry = AsyncMock()
totalk_value = 100
peer_response = (
{
"0.weightidxs": torch.tensor([0, 1, 2]),
"0.weightvals": torch.tensor([0.3, 0.4, 0.5]),
"totalks": {"0.weight": totalk_value},
},
3,
)
comms_instance.get_with_retry.side_effect = [peer_response]
result = await comms_instance.gather(
my_uid="0",
uids=["1"],
window=1,
key="gradient",
timeout=5,
device="cpu",
local=True,
stale_retention=10,
totalks={"0.weight": totalk_value},
)
assert result is not None
# TODO: Move to analyser when refactored
# async def test_gather_store_gathers(comms_instance):
# """Test that gradients are stored when store_gathers=True"""
# # Setup test data
# state_dict = {
# "layer.idxs": torch.tensor([0, 1]),
# "layer.vals": torch.tensor([0.1, 0.2]),
# }
# # Mock methods
# comms_instance.get_with_retry = AsyncMock()
# peer_response = (state_dict, 1)
# comms_instance.get_with_retry.side_effect = [peer_response]
# comms_instance.s3_put_object = AsyncMock()
# # Call gather with store_gathers=True
# await comms_instance.gather(
# state_dict=None,
# my_uid="0",
# uids=["1"],
# window=1,
# key="gradient",
# timeout=5,
# device="cpu",
# global_step=0,
# store_gathers=True,
# )
# # Wait a bit for async tasks to be created
# await asyncio.sleep(0.1)
# # Verify s3_put_object was called
# assert comms_instance.s3_put_object.called
# # Verify correct arguments
# call_args = comms_instance.s3_put_object.call_args
# assert call_args is not None
# kwargs = call_args.kwargs
# assert kwargs["bucket"] == comms_instance.bucket
# assert kwargs["key"].startswith("gathers/")
# assert kwargs["key"].endswith(".npz")
@pytest.mark.asyncio
async def test_gather_averaging(comms_instance):
"""Test 8: Verify gradient averaging with multiple peers
Tests that gradients from multiple peers are properly averaged during gather operation.
Checks:
- Proper handling of totalks parameter
- Correct aggregation of peer responses
- Validation of UIDs and global steps
- Tensor shape and size validation
"""
# Mock check_compressed_indices as specified.
comms_instance.check_compressed_indices = (
lambda param_name, idxs, totalk, allowed_topk=None: None
)
# Patch get_with_retry to simulate two peer responses.
comms_instance.get_with_retry = AsyncMock()
totalk_value = 2 # For key "layer.", allowed_topk = min(3, 2) == 2.
# Use key with trailing dot so that stripping "idxs" from "layer.idxs" produces "layer."
peer1_response = (
{
"layer.idxs": torch.tensor([0, 1]),
"layer.vals": torch.tensor([0.6, 0.8]),
"totalks": {"layer.": totalk_value}, # totalk keyed as "layer."
},
1, # global_step for peer "1"
)
peer2_response = (
{
"layer.idxs": torch.tensor([0, 1]),
"layer.vals": torch.tensor([0.6, 0.8]),
"totalks": {"layer.": totalk_value}, # totalk keyed as "layer."
},
2, # global_step for peer "2"
)
comms_instance.get_with_retry.side_effect = [peer1_response, peer2_response]
# Pass totalks via the gather call with key "layer.".
totalks_arg = {"layer.": totalk_value}
result = await comms_instance.gather(
my_uid="0",
uids=["1", "2"],
window=1,
key="gradient",
timeout=5,
device="cpu",
totalks=totalks_arg,
)
# Validate the aggregated result.
assert result is not None, "Expected a non-None gather result"
assert result.uids == ["1", "2"], f"Expected UIDs ['1', '2'], got {result.uids}"
assert result.global_steps == [
1,
2,
], f"Expected global_steps [1, 2] got {result.global_steps}"
aggregated = result.state_dict.__dict__
for key in ["layer.idxs", "layer.vals"]:
assert key in aggregated, f"Expected key {key} in state_dict"
assert len(aggregated[key]) == 2, (
f"Expected 2 tensors for key {key}, got {len(aggregated[key])}"
)
async def test_gather_complex_normalization(comms_instance):
"""Test 8: Verify complex gradient normalization with multiple peers
Tests normalization of gradients with different scales and signs.
Checks:
- Proper normalization of tensors with different magnitudes
- Correct handling of different signs in gradients
- Validation of aggregated results against expected values
- Proper handling of multiple peer responses
"""
# Bypass the compressed indices validation for this test.
comms_instance.check_compressed_indices = (
lambda param_name, idxs, totalk, allowed_topk=None: None
)
totalk_value = (
3 # For three indices, allowed_topk = min(topk_compression, totalk_value) = 3
)
# Include totalks in each peer response using the key "layer." (so that stripping "idxs"/"vals" returns the same base key).
peer1_response = (
{
"layer.idxs": torch.tensor([0, 1, 2]),
"layer.vals": torch.tensor([1.0, 2.0, 2.0]), # norm ≈ 3
"totalks": {"layer.": totalk_value},
},
1,
)
peer2_response = (
{
"layer.idxs": torch.tensor([0, 1, 2]),
"layer.vals": torch.tensor([10.0, 20.0, 20.0]), # Larger scale
"totalks": {"layer.": totalk_value},
},
2,
)
peer3_response = (
{
"layer.idxs": torch.tensor([0, 1, 2]),
"layer.vals": torch.tensor([-5.0, 5.0, 5.0]), # Different sign
"totalks": {"layer.": totalk_value},
},
3,
)
comms_instance.get_with_retry = AsyncMock()
comms_instance.get_with_retry.side_effect = [
peer1_response,
peer2_response,
peer3_response,
]
result = await comms_instance.gather(
my_uid="0",
uids=["1", "2", "3"],
window=1,
key="gradient",
timeout=5,
device="cpu",
totalks={"layer.": totalk_value},
)
assert result is not None
# Get all normalized tensors from the aggregated state dictionary.
normalized_tensors = getattr(result.state_dict, "layer.vals")
actual_vals = torch.stack(normalized_tensors).mean(dim=0)
# Calculate expected normalized values.
eps = 1e-8 # Small epsilon to avoid division by zero.
norm1 = torch.norm(peer1_response[0]["layer.vals"])
norm2 = torch.norm(peer2_response[0]["layer.vals"])
norm3 = torch.norm(peer3_response[0]["layer.vals"])
normalized1 = peer1_response[0]["layer.vals"] / (norm1 + eps)
normalized2 = peer2_response[0]["layer.vals"] / (norm2 + eps)
normalized3 = peer3_response[0]["layer.vals"] / (norm3 + eps)
expected_vals = torch.stack([normalized1, normalized2, normalized3]).mean(dim=0)
# Debug prints (optional)
print(f"Peer 1 normalized: {normalized1}")
print(f"Peer 2 normalized: {normalized2}")
print(f"Peer 3 normalized: {normalized3}")
print(f"Expected average: {expected_vals}")
print(f"Actual result: {actual_vals}")
# Floating point comparisons with tolerances.
assert torch.allclose(actual_vals, expected_vals, rtol=1e-3, atol=1e-3)
# Additional assertions to verify that all peers were processed.
assert len(normalized_tensors) == 3, (
f"Expected 3 normalized tensors, got {len(normalized_tensors)}"
)
assert len(result.uids) == 3, f"Expected 3 valid UIDs, got {len(result.uids)}"
# Test Initialization and Cleanup
async def test_comms_init(comms_instance):
"""Test 10: Verify proper initialization of Comms instance
Tests that all required components are properly initialized.
Checks:
- Temporary directory creation
- Save location existence
- Lock initialization
- Active peers set initialization
"""
assert os.path.exists(comms_instance.temp_dir)
assert os.path.exists(comms_instance.save_location)
assert comms_instance.lock is not None
assert isinstance(comms_instance.active_peers, set)
async def test_cleanup_local_data(comms_instance):
"""Test 11: Verify cleanup of stale local data
Tests the cleanup functionality for old local data.
Checks:
- Proper removal of old data based on window
- Retention of recent data
- Directory structure maintenance
"""
# Setup test directories and files
uid = "test_uid"
test_dir = os.path.join("/tmp/local_store", uid)
os.makedirs(os.path.join(test_dir, "10"), exist_ok=True)
os.makedirs(os.path.join(test_dir, "20"), exist_ok=True)
await comms_instance.cleanup_local_data(uid, 25, 5)
assert not os.path.exists(os.path.join(test_dir, "10"))
assert os.path.exists(os.path.join(test_dir, "20"))
# Test S3 Operations
async def test_s3_put_small_file(comms_instance):
"""Test 12: Verify S3 upload for small files
Tests the basic S3 upload functionality for small files.
Checks:
- Proper file creation
- S3 client initialization
- Upload operation execution
- Cleanup after upload
"""
# Create test file
with open("test_file.txt", "w") as f:
f.write("test data")
# Mock S3 client with proper async context manager
mock_client = AsyncMock()
mock_client.put_object = AsyncMock()
comms_instance.session.create_client = MagicMock(return_value=mock_client)
# Create proper Bucket instance instead of string
comms_instance.bucket = Bucket(
name="test-bucket",
account_id="test-account",
access_key_id="test-key",
secret_access_key="test-secret",
)
await comms_instance.s3_put_object("test_key", "test_file.txt")
# Cleanup
os.remove("test_file.txt")
@pytest.mark.asyncio
async def test_s3_put_large_file(comms_instance):
"""Test 13: Verify S3 multipart upload for large files
Tests the multipart upload functionality for large files.
Checks:
- Multipart upload initialization
- Proper part uploading
- Upload completion
- Part number ordering
- Cleanup operations
"""
mock_client = AsyncMock()
mock_client.create_multipart_upload = AsyncMock(
return_value={"UploadId": "test_id"}
)
mock_client.upload_part = AsyncMock(return_value={"ETag": "test_etag"})
mock_client.complete_multipart_upload = AsyncMock()
mock_client.abort_multipart_upload = AsyncMock()
comms_instance.session.create_client = MagicMock(return_value=mock_client)
comms_instance.bucket = Bucket(
name="test-bucket",
account_id="test-account",
access_key_id="test-key",
secret_access_key="test-secret",
)
with open("large_file.txt", "wb") as f:
f.write(os.urandom(100 * 1024 * 1024))
await comms_instance.s3_put_object("test_key", "large_file.txt")
upload_part_calls = mock_client.upload_part.call_args_list
assert len(upload_part_calls) <= 20
part_numbers = [call.kwargs["PartNumber"] for call in upload_part_calls]
assert part_numbers == sorted(part_numbers)
os.remove("large_file.txt")
async def test_download_large_file(comms_instance):
"""Test 14: Verify downloading of large files
Tests the chunked download functionality for large files.
Checks:
- Proper content length handling
- Chunk size calculations
- Range request handling
- Download completion
"""
# Mock S3 client with proper responses
mock_client = AsyncMock()
mock_client.head_object = AsyncMock(
return_value={"ContentLength": 10 * 1024 * 1024}
)
# Mock get_object to return proper chunk data
async def mock_get_object(**kwargs):
range_header = kwargs.get("Range", "")
start, end = map(int, range_header.replace("bytes=", "").split("-"))
chunk_size = end - start + 1
return {
"Body": AsyncMock(
**{
"__aenter__.return_value": AsyncMock(
**{"read.return_value": os.urandom(chunk_size)}
)
}
)
}
mock_client.get_object = AsyncMock(side_effect=mock_get_object)
comms_instance.session.create_client = MagicMock(return_value=mock_client)
# download_large_file expects an object with a .name attr (like boto3 Bucket)
bucket_stub = type("Bucket", (), {"name": "test-bucket"})() # Simple stand‑in
success = await comms_instance.download_large_file(
mock_client,
bucket_stub,
"test_key",
10 * 1024 * 1024,
"test_output.txt",
)
mock_client.get_object.assert_called()
# Test Checkpoint Operations
@pytest.mark.asyncio
async def test_load_checkpoint_success(monkeypatch):
"""
Verifies that `load_checkpoint`:
• accepts the correct positional/keyword args
• returns exactly five values
• propagates the momentum & sync_window fields from the checkpoint
"""
comms = Comms.__new__(Comms)
comms.wallet = MagicMock()
# --- Build a tiny, real model, optimiser & scheduler -------------------
model = torch.nn.Linear(4, 2)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1)
# --- Fake checkpoint data in exactly the structure the impl expects ----
checkpoint_data = {
"model_state_dict": model.state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"scheduler_state_dict": scheduler.state_dict(),
"momentum": {"beta1": 0.9},
"start_window": 0,
"current_window": 1,
"sync_window": 7, # any int works
}
# get_latest_checkpoint -> (checkpoint_data, checkpoint_window)
# It's called with init_version, so the mock needs to accept it.
async def _fake_get_latest_checkpoint(version: str):
# TODO: Consider asserting the value of 'version' if it's important for the test logic.
return checkpoint_data, 1
monkeypatch.setattr(comms, "get_latest_checkpoint", _fake_get_latest_checkpoint)
# --- Call & unpack (must be 5 returns) ---------------------------------
success, momentum, sync_window, opt_out, sched_out = await comms.load_checkpoint(
model=model,
optimizer=optimizer,
scheduler=scheduler,
current_window=1,
device="cpu",
)
# --- Assertions --------------------------------------------------------
assert success is True
assert momentum == {"beta1": 0.9}
assert sync_window == 7
# Optimiser & scheduler objects are returned unchanged
assert opt_out is optimizer
assert sched_out is scheduler
@pytest.mark.asyncio
async def test_load_checkpoint_missing_data(comms_instance):
"""Test 16: Verify checkpoint loading with missing data
Tests the checkpoint loading behavior when data is missing.
Checks:
- Proper handling of missing checkpoint data
- Default value returns
- Error handling
- State preservation
"""
# Mock the get_latest_checkpoint method to return None without error
comms_instance.get_latest_checkpoint = AsyncMock(return_value=None)
# Mock get_validator_with_highest_stake to avoid bucket access
comms_instance.get_validator_with_highest_stake = AsyncMock(return_value=(0, 1.0))
# Create mock model and optimizer
mock_model = MagicMock()
mock_optimizer = MagicMock()
mock_scheduler = MagicMock()
# load_checkpoint returns: success, momentum, sync_window, optimizer, scheduler
(
success,
momentum,
sync_window,
optimizer,
scheduler,
) = await comms_instance.load_checkpoint(
model=mock_model,
optimizer=mock_optimizer,
scheduler=mock_scheduler,
current_window=1,
device="cpu",
)
assert not success
assert momentum == {}
assert sync_window == 0
assert (
optimizer == mock_optimizer
) # Check it returns the same optimizer we passed in
assert (
scheduler == mock_scheduler
) # Check it returns the same scheduler we passed in
async def test_gather_timeout(comms_instance):
"""Test 17: Verify gather operation timeout handling
Tests the timeout mechanism in gather operations.
Checks:
- Proper timeout handling
- Error response
- Resource cleanup
"""
async def slow_get(*args, **kwargs):
await asyncio.sleep(2)
return None
comms_instance.get_with_retry = AsyncMock(side_effect=Exception("Test error"))
# Mock logger to avoid actual logging
with (
patch("tplr.logger.error"),
patch("tplr.logger.debug"),
patch("tplr.logger.info"),
patch("tplr.logger.warning"),
):
result = await comms_instance.gather(
my_uid="0",
uids=["1"],
window=1,
key="gradient",
timeout=5,
device="cpu",
local=True, # Use local=True to avoid S3 operations
stale_retention=10,
totalks={},
)
# Should return None on error
assert result is None
async def test_gather_timeout(comms_instance):