-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtest_checkpoint_saver.py
More file actions
2091 lines (1811 loc) · 89.1 KB
/
Copy pathtest_checkpoint_saver.py
File metadata and controls
2091 lines (1811 loc) · 89.1 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
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import builtins
import concurrent.futures
import io
import os
import pickle
import shutil
import struct
import tempfile
from typing import Any
import pytest
import torch
from torch.distributed.checkpoint import metadata as torchdistmeta
from torch.distributed.checkpoint.planner import (
BytesIOWriteData,
MetadataIndex,
TensorWriteData,
WriteItem,
WriteItemType,
)
from torch.distributed.checkpoint.storage import WriteResult
from ml_flashpoint.checkpoint_object_manager.buffer_io import BufferIO
from ml_flashpoint.checkpoint_object_manager.checkpoint_object_manager import CheckpointObjectManager
from ml_flashpoint.checkpoint_object_manager.object_manager import object_manager_ext
from ml_flashpoint.core.checkpoint_id_types import CheckpointContainerId, CheckpointObjectId
from ml_flashpoint.core.checkpoint_saver import DefaultMLFlashpointCheckpointSaver, WriteItemResolver
from ml_flashpoint.core.defaults import CheckpointFormat
from ml_flashpoint.replication.replication_manager import ReplicationManager
def _load_tensor_maybe_optimized(data, header=None):
if isinstance(data, bytes):
data = io.BytesIO(data)
pos = data.tell()
if header:
try:
raw_data = data.read()
# If header provided, trust it.
tensor = torch.frombuffer(bytearray(raw_data), dtype=header.dtype).reshape(header.shape)
return tensor.clone()
except Exception:
data.seek(pos)
return torch.load(data, weights_only=False)
try:
len_bytes = data.read(4)
if len(len_bytes) < 4:
raise ValueError("Too short")
header_len = struct.unpack("<I", len_bytes)[0]
if header_len > 1024 * 1024:
raise ValueError("Header too large")
pickle_bytes = data.read(header_len)
tensor_header = pickle.loads(pickle_bytes)
dtype = tensor_header.dtype
shape = tensor_header.shape
raw_data = data.read()
tensor = torch.frombuffer(bytearray(raw_data), dtype=dtype).reshape(shape)
return tensor.clone()
except Exception:
data.seek(pos) # Reset position for torch.load fallback
return torch.load(data, weights_only=False)
class StubWriteItemResolver(WriteItemResolver):
def __init__(self, data_map):
self.data_map = data_map
def resolve_data(self, write_item: WriteItem):
if write_item.index in self.data_map:
return self.data_map[write_item.index]
raise KeyError(f"Index {write_item.index} not found in data map")
class TestDefaultMLFlashpointCheckpointSaver:
@pytest.fixture
def temp_dir_path(self):
_temp_dir = tempfile.mkdtemp()
yield _temp_dir
shutil.rmtree(_temp_dir)
@pytest.fixture
def chkpt_object_manager(self):
return CheckpointObjectManager()
@pytest.fixture
def replication_manager(self, mocker):
return mocker.MagicMock(spec=ReplicationManager)
@pytest.fixture(autouse=True)
def mock_accelerator_count(self, mocker):
return mocker.patch("ml_flashpoint.core.checkpoint_saver.get_accelerator_count", return_value=1)
@staticmethod
def _tensor_write_data_for(tensor: torch.Tensor):
return TensorWriteData(
chunk=None, properties=torchdistmeta.TensorProperties(dtype=tensor.dtype), size=tensor.shape
)
@pytest.mark.parametrize(
"tensor_data",
[
torch.tensor([1, 2, 3], dtype=torch.int32),
torch.tensor([[1, 2], [3, 4]], dtype=torch.float32),
torch.tensor([[[1], [2]], [[3], [4]]], dtype=torch.float16),
torch.tensor([1, 2, 3], dtype=torch.int64),
torch.tensor([1.5, 2.5], dtype=torch.bfloat16),
torch.tensor([[1.0, 2.0, 3.0]], dtype=torch.float32),
torch.tensor([], dtype=torch.float32),
torch.tensor([[[]]], dtype=torch.int32),
],
)
def test_save_optimized_tensor_format_if_enabled(
self, chkpt_object_manager, replication_manager, temp_dir_path, mocker, tensor_data
):
# Given
saver = DefaultMLFlashpointCheckpointSaver(
global_rank_getter=lambda: 0,
local_rank_getter=lambda: 0,
global_barrier_func=lambda: None,
ckpt_obj_manager=chkpt_object_manager,
replication_manager=replication_manager,
use_optimized_save=True,
)
checkpoint_id = CheckpointContainerId(os.path.join(temp_dir_path, "ckpt_opt_true"))
item_index = MetadataIndex(fqn="item_0")
resolver = StubWriteItemResolver({item_index: tensor_data})
write_items = [
WriteItem(index=item_index, type=WriteItemType.TENSOR, tensor_data=self._tensor_write_data_for(tensor_data))
]
# Prepare bucket
buckets = saver.prepare_write_data(
checkpoint_id, write_items, resolver, object_name_prefix="data", bucket_count=1
)
# When
saver.write_data(checkpoint_id, buckets, replicate_after_write=False)
# Then
# Read using BufferIO to skip metadata
object_id = buckets[0].object_id
buffer_io = chkpt_object_manager.get_buffer(object_id)
assert buffer_io is not None
with buffer_io:
# Verify no MAGIC_BYTES at start, but a valid header len
len_bytes = buffer_io.read(4)
header_len = struct.unpack("<I", len_bytes)[0]
assert header_len > 0
# Verify Pickle header
pickle_bytes = buffer_io.read(header_len)
tensor_header = pickle.loads(pickle_bytes)
assert tensor_header.dtype == tensor_data.dtype
assert tensor_header.shape == tensor_data.shape
def test_write_data_with_optimized_save_false(self, chkpt_object_manager, replication_manager, temp_dir_path):
# Given
saver = DefaultMLFlashpointCheckpointSaver(
global_rank_getter=lambda: 0,
local_rank_getter=lambda: 0,
global_barrier_func=lambda: None,
ckpt_obj_manager=chkpt_object_manager,
replication_manager=replication_manager,
use_optimized_save=False,
)
checkpoint_id = CheckpointContainerId(os.path.join(temp_dir_path, "ckpt_opt_false"))
tensor_data = torch.tensor([1, 2, 3], dtype=torch.int32)
item_index = MetadataIndex(fqn="item_0")
resolver = StubWriteItemResolver({item_index: tensor_data})
write_items = [
WriteItem(index=item_index, type=WriteItemType.TENSOR, tensor_data=self._tensor_write_data_for(tensor_data))
]
# Prepare bucket
buckets = saver.prepare_write_data(
checkpoint_id, write_items, resolver, object_name_prefix="data", bucket_count=1
)
# When
saver.write_data(checkpoint_id, buckets, replicate_after_write=False)
# Then
# Read using BufferIO to skip metadata
object_id = buckets[0].object_id
buffer_io = chkpt_object_manager.get_buffer(object_id)
assert buffer_io is not None
with buffer_io:
magic = buffer_io.read(8)
assert magic != CheckpointFormat.MLF_FORMAT
# Reset position for loading
buffer_io.seek(0)
data = buffer_io.read()
# Should be loadable by torch.load
data_io = io.BytesIO(data)
loaded_tensor = torch.load(data_io, weights_only=False)
assert torch.equal(loaded_tensor, tensor_data)
@pytest.mark.parametrize(
"exception_in_worker",
[
None,
RuntimeError("Worker failed"),
],
)
def test_write_data_resets_num_threads(
self, chkpt_object_manager, replication_manager, temp_dir_path, mocker, exception_in_worker
):
# Given
saver = DefaultMLFlashpointCheckpointSaver(
global_rank_getter=lambda: 0,
local_rank_getter=lambda: 0,
global_barrier_func=lambda: None,
ckpt_obj_manager=chkpt_object_manager,
replication_manager=replication_manager,
)
checkpoint_id = CheckpointContainerId(os.path.join(temp_dir_path, "ckpt_threads"))
# Mock threading related calls
original_num_threads = 8
mocker.patch("torch.get_num_threads", return_value=original_num_threads)
mock_set_num_threads = mocker.patch("torch.set_num_threads")
# Mock worker to avoid actual writing and optionally raise exception
mock_worker = mocker.patch.object(saver, "_write_to_buffer_from_queue_worker")
if exception_in_worker:
mock_worker.side_effect = exception_in_worker
# When
if exception_in_worker:
with pytest.raises(RuntimeError, match="Worker failed"):
saver.write_data(checkpoint_id, [], replicate_after_write=False, thread_count=1)
else:
saver.write_data(checkpoint_id, [], replicate_after_write=False, thread_count=1)
# Then
# Verify it was reset to original_num_threads in finally block
assert mock_set_num_threads.call_args_list[-1] == mocker.call(original_num_threads)
@pytest.mark.parametrize(
"checkpoint_id_suffix",
[
"checkpoint_test",
"checkpoint_test/",
],
)
def test_get_dirty_marker_file_path(
self, checkpoint_id_suffix, chkpt_object_manager, replication_manager, temp_dir_path
):
# Given
local_rank = 123
saver = DefaultMLFlashpointCheckpointSaver(
global_rank_getter=lambda: 0,
local_rank_getter=lambda: local_rank,
global_barrier_func=lambda: None,
ckpt_obj_manager=chkpt_object_manager,
replication_manager=replication_manager,
)
checkpoint_id_str = f"{temp_dir_path}/{checkpoint_id_suffix}"
checkpoint_id = CheckpointContainerId(checkpoint_id_str)
expected_path = f"{checkpoint_id_str.rstrip('/')}__{local_rank}__unfinished"
# When/Then
assert saver._get_dirty_marker_file_path(checkpoint_id) == expected_path
def test_get_dirty_marker_file_path_root_error(self, mocker, chkpt_object_manager, replication_manager):
# Given
saver = DefaultMLFlashpointCheckpointSaver(
global_rank_getter=lambda: 0,
local_rank_getter=lambda: 123,
global_barrier_func=lambda: None,
ckpt_obj_manager=chkpt_object_manager,
replication_manager=replication_manager,
)
mock_checkpoint_id = mocker.MagicMock(spec=CheckpointContainerId)
mocker.patch.object(mock_checkpoint_id, "__str__", return_value="/")
# When/Then
with pytest.raises(ValueError, match="CheckpointContainerId cannot be the root path '/'"):
saver._get_dirty_marker_file_path(mock_checkpoint_id)
class TestInitializeCheckpoint:
@pytest.mark.parametrize("local_rank, global_rank", [(0, 0), (1, 0), (0, 1), (1, 1), (2, 5)])
def test_initialize_checkpoint_creates_dirty_marker(
self,
local_rank,
global_rank,
temp_dir_path: str,
chkpt_object_manager,
replication_manager,
):
# Given
saver = DefaultMLFlashpointCheckpointSaver(
global_rank_getter=lambda: global_rank,
local_rank_getter=lambda: local_rank,
global_barrier_func=lambda: None,
ckpt_obj_manager=chkpt_object_manager, # Not needed for this test
replication_manager=replication_manager,
)
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_init_{local_rank}_{global_rank}")
# When
saver.initialize_checkpoint(checkpoint_id)
# Then
expected_dirty_marker_path = f"{checkpoint_id}__{local_rank}__unfinished"
assert os.path.exists(expected_dirty_marker_path)
def test_initialize_checkpoint_dirty_marker_fail(
self,
mocker,
temp_dir_path,
chkpt_object_manager,
replication_manager,
):
# Given
local_rank = 0
saver = DefaultMLFlashpointCheckpointSaver(
global_rank_getter=lambda: 0,
local_rank_getter=lambda: local_rank,
global_barrier_func=lambda: None,
ckpt_obj_manager=chkpt_object_manager,
replication_manager=replication_manager,
)
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_init_fail")
# Mock open to raise an exception only for the dirty marker file
original_open = builtins.open
def mock_open(file, mode):
if file == f"{checkpoint_id}__{local_rank}__unfinished":
raise IOError("Test error: Failed to create dirty marker")
return original_open(file, mode)
mocker.patch("builtins.open", side_effect=mock_open)
# When/Then
with pytest.raises(IOError, match="Test error: Failed to create dirty marker"):
saver.initialize_checkpoint(checkpoint_id)
# Assert that the checkpoint directory was NOT created
assert not os.path.exists(checkpoint_id.data)
@pytest.mark.parametrize("local_rank", [0, 1, 8])
def test_initialize_checkpoint_creates_container_dir_when_not_exists_local_rank_0(
self,
local_rank,
temp_dir_path,
chkpt_object_manager,
replication_manager,
):
# Given
saver = DefaultMLFlashpointCheckpointSaver(
global_rank_getter=lambda: 0,
local_rank_getter=lambda: local_rank,
global_barrier_func=lambda: None,
ckpt_obj_manager=chkpt_object_manager, # Not needed for this test
replication_manager=replication_manager,
)
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_init_dir_{local_rank}")
# When
saver.initialize_checkpoint(checkpoint_id)
# Then
# Check for directory creation only on local rank 0
if local_rank == 0:
assert os.path.exists(checkpoint_id.data)
assert os.path.isdir(checkpoint_id.data)
else:
assert not os.path.exists(checkpoint_id.data)
@pytest.mark.parametrize("local_rank", [0, 1])
def test_initialize_checkpoint_leaves_container_dir_when_exists(
self,
local_rank,
temp_dir_path,
chkpt_object_manager,
replication_manager,
):
# Given
saver = DefaultMLFlashpointCheckpointSaver(
global_rank_getter=lambda: 0,
local_rank_getter=lambda: local_rank,
global_barrier_func=lambda: None,
ckpt_obj_manager=chkpt_object_manager, # Not needed for this test
replication_manager=replication_manager,
)
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_init_dir_{local_rank}")
# The checkpoint container dir already exists
os.makedirs(checkpoint_id.data)
chkpt_data_object_id = CheckpointObjectId.from_container(checkpoint_id, "test_file.txt")
chkpt_data_lines = ["hello\n", "world"]
# And it could even have something in it
with open(chkpt_data_object_id.data, "w") as file:
file.writelines(chkpt_data_lines)
# When
saver.initialize_checkpoint(checkpoint_id)
# Then
# The checkpoint directory and its contents are still in place
assert os.path.exists(checkpoint_id.data)
assert os.path.isdir(checkpoint_id.data)
with open(chkpt_data_object_id.data, "r") as file:
assert chkpt_data_lines == file.readlines()
@pytest.mark.parametrize("local_rank", [0, 1, 8])
def test_initialize_checkpoint_idempotent(
self,
temp_dir_path,
chkpt_object_manager,
local_rank,
replication_manager,
):
# Given
saver = DefaultMLFlashpointCheckpointSaver(
global_rank_getter=lambda: 0,
local_rank_getter=lambda: local_rank,
global_barrier_func=lambda: None,
ckpt_obj_manager=chkpt_object_manager, # Not needed for this test
replication_manager=replication_manager,
)
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_init_idem_{local_rank}")
expected_dirty_marker_path = f"{checkpoint_id}__{local_rank}__unfinished"
# When
saver.initialize_checkpoint(checkpoint_id) # First call
saver.initialize_checkpoint(checkpoint_id) # Second call
# Then
assert os.path.exists(expected_dirty_marker_path)
if local_rank == 0:
assert os.path.exists(checkpoint_id.data)
assert os.path.isdir(checkpoint_id.data)
else:
assert not os.path.exists(checkpoint_id.data)
class TestFinalizeCheckpoint:
@pytest.mark.parametrize(
"global_rank, local_rank, dirty_marker_file_exists",
[
(0, 0, True),
(0, 1, True),
(1, 0, True),
(1, 1, True),
(5, 2, True),
(0, 0, False),
(0, 1, False),
(1, 0, False),
(1, 1, False),
(5, 2, False),
],
)
def test_finalize_checkpoint_removes_dirty_marker(
self,
global_rank,
local_rank,
dirty_marker_file_exists,
temp_dir_path,
chkpt_object_manager,
replication_manager,
):
# Given
saver = DefaultMLFlashpointCheckpointSaver(
global_rank_getter=lambda: global_rank,
local_rank_getter=lambda: local_rank,
global_barrier_func=lambda: None,
ckpt_obj_manager=chkpt_object_manager, # Not needed for this test
replication_manager=replication_manager,
)
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_finalizetest_{local_rank}_{global_rank}")
random_chkpt_file_path = CheckpointObjectId.from_container(checkpoint_id, "test_file.txt")
chkpt_data_lines = ["hello\n", "world"]
expected_dirty_marker_path = f"{checkpoint_id}__{local_rank}__unfinished"
# Create file within checkpoint container for validations later (and its parent dir)
os.makedirs(checkpoint_id.data)
with open(random_chkpt_file_path.data, "w") as file:
file.writelines(chkpt_data_lines)
if dirty_marker_file_exists:
# Create the marker file directly to isolate the test
with open(expected_dirty_marker_path, "w") as _:
pass # empty marker file
assert os.path.exists(expected_dirty_marker_path)
# When
saver.finalize_checkpoint(checkpoint_id)
# Then
# The marker file is not present
assert not os.path.exists(expected_dirty_marker_path)
# The checkpoint directory and its contents are still in place
assert os.path.exists(checkpoint_id.data)
assert os.path.exists(random_chkpt_file_path.data)
with open(random_chkpt_file_path.data, "r") as file:
assert chkpt_data_lines == file.readlines()
def test_finalize_checkpoint_calls_barrier_and_removes_older_in_order(
self,
mocker,
temp_dir_path,
chkpt_object_manager,
replication_manager,
):
# Given
# Using a manager to assert on the sequence of calls.
manager = mocker.Mock()
mock_barrier_func = manager.barrier
mock_remove_dirty_marker = mocker.patch(
"ml_flashpoint.core.checkpoint_saver.DefaultMLFlashpointCheckpointSaver._remove_dirty_checkpoint_marker"
)
manager.attach_mock(mock_remove_dirty_marker, "remove_dirty")
mock_remove_older = mocker.patch(
"ml_flashpoint.core.checkpoint_saver.DefaultMLFlashpointCheckpointSaver._remove_older_checkpoints"
)
mock_future = mocker.MagicMock()
mock_remove_older.return_value = mock_future
manager.attach_mock(mock_remove_older, "remove_older")
saver = DefaultMLFlashpointCheckpointSaver(
global_rank_getter=lambda: 0,
local_rank_getter=lambda: 0,
global_barrier_func=mock_barrier_func,
ckpt_obj_manager=chkpt_object_manager,
replication_manager=replication_manager,
)
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_finalize_barrier")
# When
returned_future = saver.finalize_checkpoint(checkpoint_id)
# Then
expected_calls = [
mocker.call.remove_dirty(checkpoint_id),
mocker.call.barrier(),
mocker.call.remove_older(older_than=checkpoint_id),
]
assert manager.mock_calls == expected_calls
assert returned_future is mock_future
@pytest.mark.parametrize("local_rank", [0, 1, 5])
def test_finalize_checkpoint_removes_older_dirs_only_on_local_rank_0(
self,
temp_dir_path,
chkpt_object_manager,
local_rank,
replication_manager,
):
# Given
checkpoint_base_dir = os.path.join(temp_dir_path, "checkpoints")
older_ckpt_path1 = os.path.join(checkpoint_base_dir, "step-100_ckpt")
older_ckpt_path2 = os.path.join(checkpoint_base_dir, "step-200_ckpt")
current_ckpt_path = os.path.join(checkpoint_base_dir, "step-300_ckpt")
newer_ckpt_path = os.path.join(checkpoint_base_dir, "step-400_ckpt")
os.makedirs(older_ckpt_path1)
os.makedirs(older_ckpt_path2)
os.makedirs(current_ckpt_path)
os.makedirs(newer_ckpt_path)
saver = DefaultMLFlashpointCheckpointSaver(
global_rank_getter=lambda: 0,
local_rank_getter=lambda: local_rank,
global_barrier_func=lambda: None,
ckpt_obj_manager=chkpt_object_manager,
replication_manager=replication_manager,
)
checkpoint_id = CheckpointContainerId(current_ckpt_path)
# When
future = saver.finalize_checkpoint(checkpoint_id)
if local_rank == 0:
assert future is not None
future.wait()
else:
assert future is None
# Then
if local_rank == 0:
assert not os.path.exists(older_ckpt_path1)
assert not os.path.exists(older_ckpt_path2)
else:
assert os.path.exists(older_ckpt_path1)
assert os.path.exists(older_ckpt_path2)
# Current and newer checkpoints should always exist
assert os.path.exists(current_ckpt_path)
assert os.path.exists(newer_ckpt_path)
class TestStageData:
@pytest.fixture
def saver(self, chkpt_object_manager, replication_manager):
return DefaultMLFlashpointCheckpointSaver(
global_rank_getter=lambda: 0,
local_rank_getter=lambda: 0,
global_barrier_func=lambda: None,
ckpt_obj_manager=chkpt_object_manager, # Not needed for this test
replication_manager=replication_manager,
)
def test_stage_data_cpu_tensor(self, temp_dir_path, saver):
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_stage_cpu")
state_dict = {"a": torch.tensor([1, 2, 3], device="cpu"), "b": torch.randn(size=(3, 4, 5), device="cpu")}
staged_dict = saver.stage_data(checkpoint_id, state_dict)
assert staged_dict["a"].device == torch.device("cpu")
assert torch.equal(staged_dict["a"], state_dict["a"])
def test_stage_data_cuda_tensor(self, temp_dir_path, saver):
if not torch.cuda.is_available():
pytest.skip("CUDA not available")
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_stage_cuda")
state_dict = {"a": torch.tensor([1, 2, 3], device="cuda")}
staged_dict = saver.stage_data(checkpoint_id, state_dict)
assert staged_dict["a"].device == torch.device("cpu")
assert torch.equal(staged_dict["a"], state_dict["a"].cpu())
def test_stage_data_mixed(self, temp_dir_path, saver):
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_stage_mixed")
state_dict = {
"a": torch.tensor([1, 2, 3], device="cpu"),
"b": "a string",
"c": 123,
"d": torch.randn(size=(3, 4, 5), dtype=torch.float16, device="cpu"),
}
if torch.cuda.is_available():
state_dict["g1"] = torch.tensor([4, 5, 6], device="cuda")
state_dict["g2"] = torch.randn(size=(3, 4, 5), dtype=torch.float32, device="cuda")
staged_dict = saver.stage_data(checkpoint_id, state_dict)
assert staged_dict["a"].device == torch.device("cpu")
assert torch.equal(staged_dict["a"], state_dict["a"])
assert staged_dict["b"] == "a string"
assert staged_dict["c"] == 123
assert torch.equal(staged_dict["d"], state_dict["d"])
if torch.cuda.is_available():
assert staged_dict["g1"].device == torch.device("cpu")
assert torch.equal(staged_dict["g1"], state_dict["g1"].cpu())
assert staged_dict["g2"].device == torch.device("cpu")
assert torch.equal(staged_dict["g2"], state_dict["g2"].cpu())
def test_stage_data_defaults_to_non_blocking(self, temp_dir_path, saver, mocker):
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_stage_defaults")
mock_tensor = mocker.MagicMock(spec=torch.Tensor)
mock_tensor.device = torch.device("cuda:0")
state_dict = {"a": mock_tensor}
saver.stage_data(checkpoint_id, state_dict)
mock_tensor.to.assert_called_once_with(device="cpu", non_blocking=True)
@pytest.mark.parametrize("non_blocking", [True, False])
def test_stage_data_non_blocking_modes(self, temp_dir_path, saver, non_blocking):
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_stage_nonblock")
state_dict = {"a": torch.tensor([1, 2, 3], device="cpu")}
if torch.cuda.is_available():
state_dict["b"] = torch.tensor([4, 5, 6], device="cuda")
staged_dict = saver.stage_data(checkpoint_id, state_dict, non_blocking=non_blocking)
assert staged_dict["a"].device == torch.device("cpu")
if torch.cuda.is_available():
assert staged_dict["b"].device == torch.device("cpu")
assert torch.equal(staged_dict["b"], state_dict["b"].cpu())
@pytest.mark.parametrize("non_blocking", [True, False])
def test_stage_data_moves_all_to_cpu_mocked(self, temp_dir_path, saver, mocker, non_blocking):
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_stage_mocked")
# Mock torch.Tensor.to
mocker.patch.object(torch.Tensor, "to", wraps=torch.Tensor.to)
# Create mock tensors with different devices
mock_tensors_cpu = [mocker.MagicMock(spec=torch.Tensor) for _ in range(2)]
for t in mock_tensors_cpu:
t.device = torch.device("cpu")
t.to.return_value = t
mock_tensors_xla = [mocker.MagicMock(spec=torch.Tensor) for _ in range(2)]
for t in mock_tensors_xla:
t.device = torch.device("xla:0")
t.to.return_value = mock_tensors_cpu[0] # Simulate moving to CPU
mock_tensors_cuda = [mocker.MagicMock(spec=torch.Tensor) for _ in range(2)]
for t in mock_tensors_cuda:
t.device = torch.device("cuda:0")
t.to.return_value = mock_tensors_cpu[0] # Simulate moving to CPU
state_dict = {
"cpu_tensor_0": mock_tensors_cpu[0],
"cpu_tensor_1": mock_tensors_cpu[1],
"xla_tensor_0": mock_tensors_xla[0],
"xla_tensor_1": mock_tensors_xla[1],
"cuda_tensor_0": mock_tensors_cuda[0],
"cuda_tensor_1": mock_tensors_cuda[1],
"string_data": "hello",
"int_data": 123,
}
staged_dict = saver.stage_data(checkpoint_id, state_dict, non_blocking=non_blocking)
# Assert that .to() was called correctly for all tensors
for t in mock_tensors_cpu:
t.to.assert_called_once_with(device="cpu", non_blocking=non_blocking)
for t in mock_tensors_xla:
t.to.assert_called_once_with(device="cpu", non_blocking=non_blocking)
for t in mock_tensors_cuda:
t.to.assert_called_once_with(device="cpu", non_blocking=non_blocking)
# Assert that the staged dict contains the tensors returned by .to()
assert staged_dict["cpu_tensor_0"] is mock_tensors_cpu[0]
assert staged_dict["cpu_tensor_1"] is mock_tensors_cpu[1]
assert staged_dict["xla_tensor_0"] is mock_tensors_cpu[0]
assert staged_dict["xla_tensor_1"] is mock_tensors_cpu[0]
assert staged_dict["cuda_tensor_0"] is mock_tensors_cpu[0]
assert staged_dict["cuda_tensor_1"] is mock_tensors_cpu[0]
@pytest.mark.parametrize("non_blocking", [True, False])
@pytest.mark.parametrize("cuda_available", [True, False])
def test_stage_data_cuda_synchronization(self, temp_dir_path, saver, mocker, non_blocking, cuda_available):
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_stage_sync")
mocker.patch("torch.cuda.is_available", return_value=cuda_available)
mock_cuda_synchronize = mocker.patch("torch.cuda.synchronize")
state_dict = {"a": torch.tensor([[1, 2, 3], [4, 5, 6]])}
saver.stage_data(checkpoint_id, state_dict, non_blocking=non_blocking)
if non_blocking and cuda_available:
mock_cuda_synchronize.assert_called_once()
else:
# Should not invoke it unnecessarily, as it can cause unnecessary slowdowns
mock_cuda_synchronize.assert_not_called()
class TestPrepareWriteData:
@pytest.fixture
def saver(self, chkpt_object_manager, replication_manager):
return DefaultMLFlashpointCheckpointSaver(
global_rank_getter=lambda: 0,
local_rank_getter=lambda: 0,
global_barrier_func=lambda: None,
ckpt_obj_manager=chkpt_object_manager,
replication_manager=replication_manager,
)
@staticmethod
def _tensor_write_data_for(tensor: torch.Tensor):
return TensorWriteData(
chunk=None, properties=torchdistmeta.TensorProperties(dtype=tensor.dtype), size=tensor.shape
)
def test_prepare_write_data_single_tensor(self, saver, temp_dir_path):
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_prepare_single_tensor")
tensor_data = torch.tensor([1, 2, 3])
item_index = MetadataIndex(fqn="item_0")
data_map = {item_index: tensor_data}
resolver = StubWriteItemResolver(data_map)
write_items = [
WriteItem(
index=item_index, type=WriteItemType.TENSOR, tensor_data=self._tensor_write_data_for(tensor_data)
)
]
write_buckets = saver.prepare_write_data(
checkpoint_id, write_items, resolver, object_name_prefix="data", bucket_count=1
)
assert len(write_buckets) == 1
bucket = write_buckets[0]
assert bucket.object_name == "data_0_src0.distcp"
assert len(bucket.tensor_data) == 1
assert len(bucket.bytesio_data) == 0
assert torch.equal(bucket.tensor_data[0][1], tensor_data)
def test_prepare_write_data_single_byteio(self, saver, temp_dir_path):
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_prepare_single_byteio")
data_binary = b"test byte data"
bytesio_data = io.BytesIO(data_binary)
item_index = MetadataIndex(fqn="item_0")
data_map = {item_index: bytesio_data}
resolver = StubWriteItemResolver(data_map)
write_items = [
WriteItem(
index=item_index, type=WriteItemType.BYTE_IO, bytes_io_data=BytesIOWriteData(len(data_binary))
)
]
write_buckets = saver.prepare_write_data(
checkpoint_id, write_items, resolver, object_name_prefix="data", bucket_count=1
)
assert len(write_buckets) == 1
bucket = write_buckets[0]
assert bucket.object_name == "data_0_src0.distcp"
assert len(bucket.bytesio_data) == 1
assert len(bucket.tensor_data) == 0
assert bucket.bytesio_data[0][1].getvalue() == data_binary
@pytest.mark.parametrize(
"tensor",
[
torch.tensor([1, 2, 3], dtype=torch.int32),
torch.tensor([[1, 2], [3, 4]], dtype=torch.float32),
torch.tensor([[[1], [2]], [[3], [4]]], dtype=torch.float16),
torch.tensor([1, 2, 3], dtype=torch.int64),
torch.tensor([1.5, 2.5], dtype=torch.bfloat16),
torch.tensor([[1.0, 2.0, 3.0]], dtype=torch.float32),
torch.tensor([], dtype=torch.float32),
torch.tensor([[[]]], dtype=torch.int32),
],
)
def test_save_tensor_optimized_writes_correct_header_and_data(
self, saver, chkpt_object_manager, mocker, tensor
):
"""Test that _save_tensor_optimized writes the expected zero-copy format."""
# Given
buffer_io_mock = mocker.MagicMock(spec=BufferIO)
# Create a real memory view for the mock to return so torch.frombuffer works
real_buffer = bytearray(tensor.nbytes)
buffer_io_mock.next_buffer_slice.return_value = memoryview(real_buffer)
# When
saver._save_tensor_optimized(tensor, buffer_io_writer=buffer_io_mock)
# Then
# 1. Verify Header Write
buffer_io_mock.write.assert_called_once()
header_bytes = buffer_io_mock.write.call_args[0][0]
# Parse header manually to verify
# No MAGIC_BYTES at start
len_bytes = header_bytes[:4]
header_len = struct.unpack("<I", len_bytes)[0]
pickle_bytes = header_bytes[4:]
assert len(pickle_bytes) == header_len
tensor_header = pickle.loads(pickle_bytes)
assert tensor_header.dtype == tensor.dtype
assert tensor_header.shape == tensor.shape
# 2. Verify Data Copy
if tensor.nbytes > 0:
buffer_io_mock.next_buffer_slice.assert_called_once_with(tensor.nbytes)
else:
buffer_io_mock.next_buffer_slice.assert_not_called()
# Verify data in our side-buffer matches
if tensor.nbytes > 0:
written_tensor = torch.frombuffer(real_buffer, dtype=tensor.dtype).reshape(tensor.shape)
else:
written_tensor = torch.empty(tensor.shape, dtype=tensor.dtype)
assert torch.equal(written_tensor, tensor)
@pytest.mark.parametrize("bucket_count", [1, 2])
def test_prepare_write_data_multiple_tensors(self, saver, temp_dir_path, bucket_count):
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_prepare_multi_tensor")
tensor0 = torch.tensor([1, 2, 3])
tensor1 = torch.tensor([4, 5, 6])
item_index0 = MetadataIndex(fqn="item_0")
item_index1 = MetadataIndex(fqn="item_1")
data_map = {item_index0: tensor0, item_index1: tensor1}
resolver = StubWriteItemResolver(data_map)
write_items = [
WriteItem(
index=item_index0, type=WriteItemType.TENSOR, tensor_data=self._tensor_write_data_for(tensor0)
),
WriteItem(
index=item_index1, type=WriteItemType.TENSOR, tensor_data=self._tensor_write_data_for(tensor1)
),
]
write_buckets = saver.prepare_write_data(
checkpoint_id, write_items, resolver, object_name_prefix="data", bucket_count=bucket_count
)
assert len(write_buckets) == bucket_count
all_tensors = [item[1] for bucket in write_buckets for item in bucket.tensor_data]
assert len(all_tensors) == 2
assert any(torch.equal(t, tensor0) for t in all_tensors)
assert any(torch.equal(t, tensor1) for t in all_tensors)
@pytest.mark.parametrize("bucket_count", [1, 2, 3])
def test_prepare_write_data_mixed_types(self, saver, temp_dir_path, bucket_count):
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_prepare_mixed")
tensor0 = torch.tensor([1, 2, 3])
bytes1 = b"test byte data"
bytesio1 = io.BytesIO(bytes1)
tensor2 = torch.tensor([7, 8, 9])
item_index0 = MetadataIndex(fqn="item_0_tensor")
item_index1 = MetadataIndex(fqn="item_1_bytes")
item_index2 = MetadataIndex(fqn="item_2_tensor")
data_map = {item_index0: tensor0, item_index1: bytesio1, item_index2: tensor2}
resolver = StubWriteItemResolver(data_map)
write_items = [
WriteItem(
index=item_index0, type=WriteItemType.TENSOR, tensor_data=self._tensor_write_data_for(tensor0)
),
WriteItem(index=item_index1, type=WriteItemType.BYTE_IO, bytes_io_data=BytesIOWriteData(len(bytes1))),
WriteItem(
index=item_index2, type=WriteItemType.TENSOR, tensor_data=self._tensor_write_data_for(tensor2)
),
]
write_buckets = saver.prepare_write_data(
checkpoint_id, write_items, resolver, object_name_prefix="data", bucket_count=bucket_count
)
assert len(write_buckets) > 0
all_tensors = [item[1] for bucket in write_buckets for item in bucket.tensor_data]
all_bytes = [item[1] for bucket in write_buckets for item in bucket.bytesio_data]
assert len(all_tensors) == 2
assert len(all_bytes) == 1
assert any(torch.equal(t, tensor0) for t in all_tensors)
assert any(torch.equal(t, tensor2) for t in all_tensors)
assert all_bytes[0].getvalue() == bytes1
def test_prepare_write_data_empty_items(self, saver, temp_dir_path):
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_prepare_empty")
resolver = StubWriteItemResolver({})
write_items = []
write_buckets = saver.prepare_write_data(
checkpoint_id, write_items, resolver, object_name_prefix="data", bucket_count=1
)
assert write_buckets == []
def test_prepare_write_data_resolver_exception(self, saver, temp_dir_path):
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_prepare_resolver_exc")
tensor_data = torch.tensor([1, 2, 3])
item_index = MetadataIndex(fqn="item_0")
resolver = StubWriteItemResolver({}) # Empty data map
write_items = [
WriteItem(
index=item_index, type=WriteItemType.TENSOR, tensor_data=self._tensor_write_data_for(tensor_data)
)
]
with pytest.raises(KeyError):
saver.prepare_write_data(
checkpoint_id, write_items, resolver, object_name_prefix="data", bucket_count=1
)
def test_prepare_write_data_clone_if_needed_logic(self, saver, temp_dir_path, mocker):
# Given
checkpoint_id = CheckpointContainerId(f"{temp_dir_path}/checkpoint_clone_logic")
# 1. CPU tensor, contiguous, not a view
cpu_tensor_contig = torch.randn(10)
# 2. CPU tensor, non-contiguous
cpu_tensor_non_contig = torch.randn(10, 2).t()
# 3. CPU tensor, view (contiguous but view of larger storage)
base_tensor = torch.randn(20)
cpu_tensor_view = base_tensor[2:5] # length 3, contiguous
# 4. Mock CUDA tensor
cuda_tensor = mocker.MagicMock(spec=torch.Tensor)
cuda_tensor.device.type = "cuda"
# prepare_write_data calls .detach() on the resolved data
cuda_tensor.detach.return_value = cuda_tensor
item_indices = {
"contig": MetadataIndex(fqn="contig"),
"non_contig": MetadataIndex(fqn="non_contig"),
"view": MetadataIndex(fqn="view"),
"cuda": MetadataIndex(fqn="cuda"),
}
data_map = {
item_indices["contig"]: cpu_tensor_contig,
item_indices["non_contig"]: cpu_tensor_non_contig,
item_indices["view"]: cpu_tensor_view,
item_indices["cuda"]: cuda_tensor,
}
resolver = StubWriteItemResolver(data_map)