forked from mlfoundations/open_flamingo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_optim_utils.py
1741 lines (1578 loc) · 69.1 KB
/
_optim_utils.py
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
import copy
import functools
import warnings
from dataclasses import dataclass
from typing import (
Any,
cast,
Dict,
Iterable,
Iterator,
List,
NamedTuple,
Optional,
Sequence,
Set,
Tuple,
Union,
)
import torch
import torch.distributed as dist
import torch.distributed.fsdp._traversal_utils as traversal_utils
import torch.nn as nn
from torch.distributed._shard.sharded_tensor import ShardedTensor
from torch.distributed.fsdp._common_utils import (
_apply_to_modules,
_FSDPState,
_get_module_fsdp_state_if_fully_sharded_module,
_get_param_to_fqns,
_module_handles,
clean_tensor_name,
)
from torch.distributed.fsdp._fsdp_extensions import _ext_chunk_tensor
from torch.distributed.fsdp._runtime_utils import _clear_grads_if_needed, _lazy_init
from torch.distributed.fsdp._shard_utils import _gather_state_dict
from torch.distributed.fsdp.api import ShardingStrategy
from torch.distributed.fsdp.flat_param import FlatParameter, FlatParamHandle
@dataclass
class FSDPParamInfo:
state: _FSDPState
flat_param: FlatParameter
param_indices: Dict[str, int]
def sorted_items(dictionary: Dict[str, Any]) -> Iterator[Tuple[str, Any]]:
keys = sorted(dictionary.keys())
for k in keys:
yield k, dictionary[k]
class _ConsolidatedOptimState:
"""
This holds the consolidated optimizer state on the target rank. Positive-
dimension tensor state is communicated across ranks, while zero-dimension
tensor state and non-tensor state is taken directly from the target rank.
PyTorch version 1.12 moved to using zero-dimension tensors for scalar
values, but user implemented optimizers may still use float (i.e. a
non-tensor). Thus, we support both and handle them identically.
Attributes:
tensor_state (Dict[str, torch.Tensor]): Mapping from positive-dimension
tensor state name to the unsharded flattened tensor representing
the state.
zero_dim_tensor_state (Dict[str, torch.Tensor]): Mapping from zero-
dimension tensor state name to its value.
non_tensor_state (Dict[str, Any]): Mapping from non-tensor state
name to its value.
"""
tensor_state: Dict[str, torch.Tensor] = {}
zero_dim_tensor_state: Dict[str, torch.Tensor] = {}
non_tensor_state: Dict[str, Any] = {}
class _PosDimTensorInfo(NamedTuple):
"""
Meatadata for positive-dimension tensors used internally for
:meth:`scatter_full_optim_state_dict`.
Attributes:
shape (torch.Size): Sharded tensor shape (which is equal to the
unsharded tensor shape if the tensor is optimizer state for a
non-FSDP parameter and is hence not sharded).
dtype (torch.dtype): Data type of the tensor.
"""
shape: torch.Size
dtype: torch.dtype
class _OptimStateKey(NamedTuple):
"""
This represents an optimizer state key that may be used commonly across
ranks. It is based on the unflattened parameter names rather than parameter
IDs to make it indepenendent of each rank's own optimizer construction.
"""
unflat_param_names: Tuple[str, ...]
is_fsdp_managed: bool
def _unflatten_optim_state(
fsdp_param_info: FSDPParamInfo,
flat_param_state: Dict[str, Any],
to_save: bool,
shard_state: bool,
) -> List[Dict[str, Any]]:
"""
Unflattens the optimizer state, consisting of the "state" part and the
"param_groups" part. Unflattening the "state" part involves consolidating
the state on the target rank and remapping from flattened to unflattened
parameter IDs, and the "param_groups" part only involves remapping from
flattened to unflattened parameter IDs.
Args:
fsdp_param_info (FSDPParamInfo): The fsdp state and the target flatten
parameter.
flat_param_state (Dict[str, Any]): Entry for the flattened parameter
in the "state" part of the optimizer state dict.
to_save (bool): Whether to save the state on this rank.
Returns:
List[Dict[str, Any]]: A :class:`list` holding the entries in the
"state" part of the optimizer state dict corresponding to the
unflattened parameters comprising the flattened parameter if on the
target rank or an empty :class:`list` otherwise. The final optimizer
state dict will need to map these entries using the proper unflattened
parameter IDs.
"""
assert (
not shard_state or to_save
), "If ``shard_state`` is True, ``to_save`` has to be True."
consolidated_state = _communicate_optim_state(
fsdp_param_info,
flat_param_state,
)
if to_save:
unflat_param_state = _unflatten_communicated_optim_state(
fsdp_param_info,
consolidated_state,
shard_state,
)
for optim_state in unflat_param_state:
for key in list(optim_state.keys()):
state = optim_state[key]
if isinstance(state, torch.Tensor):
optim_state[key] = state.cpu()
return unflat_param_state
else:
return []
def _is_zero_dim_tensor(x: Any) -> bool:
return torch.is_tensor(x) and x.dim() == 0
def _communicate_optim_state(
fsdp_param_info: FSDPParamInfo,
flat_param_state: Dict[str, Any],
) -> _ConsolidatedOptimState:
"""
Communicates the optimizer state for a flattened parameter across ranks.
All ranks will hold the entire non-sharded optimizer state on GPU.
If ``N`` is the number of tensor optimizer states in the optimizer state
dict, then the communication complexity is 0 if ``N = 0`` and ``N + 1``
otherwise (where the plus 1 comes from all-gathering the padding per rank).
Args:
fsdp_param_info (FSDPParamInfo): The fsdp state and the target flatten
parameter.
flat_param_state (Dict[str, Any]): The entry in the "state" part of the
optimizer state dict corresponding to the flattened parameter.
Returns:
ConsolidatedOptimState: Consolidated optimizer state for the target
flattened parameter.
"""
fsdp_state = fsdp_param_info.state
flat_param = fsdp_param_info.flat_param
state = _ConsolidatedOptimState()
tensor_state, zero_dim_tensor_state, non_tensor_state = (
state.tensor_state,
state.zero_dim_tensor_state,
state.non_tensor_state,
)
for state_name, value in sorted_items(flat_param_state):
# Positive-dimension tensor state: communicate across ranks
if torch.is_tensor(value) and value.dim() > 0:
# If the parameter is not sharded, then neither is the
# positive-dimension tensor state, so no need to communicate it --
# we take the target rank's value
if (
fsdp_state.world_size == 1
or fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD
):
tensor_state[state_name] = value
continue
if not value.is_cuda:
value = value.to(fsdp_state.compute_device)
# Assume that positive-dimension tensor optimizer state
# has the same shape as the sharded flattened parameter
buffer_size = flat_param._full_param_padded.size() # type: ignore[attr-defined]
tensor_buffer = value.new_zeros(*buffer_size)
dist.all_gather_into_tensor(
tensor_buffer, value, group=fsdp_state.process_group
)
torch.cuda.synchronize()
unpadded_numel = cast(
nn.Parameter, flat_param._unpadded_unsharded_size
).numel()
tensor_state[state_name] = tensor_buffer[:unpadded_numel]
# Zero-dimension tensor state and non-tensor state: take this rank's
# value directly
else:
if _is_zero_dim_tensor(value):
zero_dim_tensor_state[state_name] = value
else:
non_tensor_state[state_name] = value
return state
def _unflatten_communicated_optim_state(
fsdp_param_info: FSDPParamInfo,
state: _ConsolidatedOptimState,
shard_state: bool,
) -> List[Dict[str, Any]]:
"""
Unflattens the communicated optimizer state (given by ``tensor_state``,
``non_tensor_state``, and ``zero_dim_tensor_state``) for a single flattened
parameter. This should only be called on the target rank.
Args:
fsdp_param_info (FSDPParamInfo): The fsdp state and the target flatten
parameter.
state (_ConsolidatedOptimState): Consolidated optimizer state.
Returns:
List[Dict[str, Any]]: A :class:`list` holding the entries in the
"state" part of the optimizer state dict corresponding to the
unflattened parameters comprising the flattened parameter. The final
optimizer state dict will need to map these entries using the proper
unflattened parameter IDs.
"""
fsdp_state = fsdp_param_info.state
flat_param = fsdp_param_info.flat_param
unflat_param_state: List[Dict[str, Any]] = []
flat_param_views: Dict[str, Iterator] = {}
num_unflat_params = flat_param._num_params
tensor_state, zero_dim_tensor_state, non_tensor_state = (
state.tensor_state,
state.zero_dim_tensor_state,
state.non_tensor_state,
)
for _ in range(num_unflat_params):
unflat_state_param = {}
# Add positive-dimension tensor state: unflatten with views
for state_name, flat_tensor in sorted_items(tensor_state):
views_generated = state_name in flat_param_views
if not views_generated:
views = FlatParamHandle._get_unflat_views(flat_param, flat_tensor)
flat_param_views[state_name] = views
else:
views = flat_param_views[state_name]
optim_state: Union[torch.Tensor, ShardedTensor] = next(views)
if shard_state:
assert fsdp_state.process_group is not None
optim_state = _ext_chunk_tensor(
optim_state,
fsdp_state.rank,
fsdp_state.world_size,
torch.cuda.device_count(),
fsdp_state.process_group,
)
unflat_state_param[state_name] = optim_state
# Add zero-dimension tensor state: take the target rank's value
for state_name, zero_dim_tensor in sorted_items(zero_dim_tensor_state):
unflat_state_param[state_name] = zero_dim_tensor
# Add non-tensor state: take the target rank's value
for state_name, non_tensor in sorted_items(non_tensor_state):
unflat_state_param[state_name] = non_tensor
unflat_param_state.append(unflat_state_param)
return unflat_param_state
def _flatten_optim_state_dict(
optim_state_dict: Dict[str, Any],
model: nn.Module,
shard_state: bool,
use_orig_params: bool = False,
optim: Optional[torch.optim.Optimizer] = None,
) -> Dict[str, Any]:
"""
Flattens the full optimizer state dict, still keying by unflattened
parameter names. If ``shard_state=True``, then FSDP-managed
``FlatParameter`` 's optimizer states are sharded, and otherwise, they are
kept unsharded.
If ``use_orig_params`` is True, each rank will have all FSDP-managed
parameters but some of these parameters may be empty due to the sharding.
For a regular optim.Optimizer, states for those empty parameters will
not be initialized. So, when aggregating the FQNs across ranks, no assert
will be raised on a rank even if it does not have all the states -- it is
valid and FSDP know how to aggregate them. However, FSDP has to ignore
handling those parameters that are not managed by FSDP and do not exist on
the local rank -- it is managed by other parallelism and FSDP does not
know ho to handle/aggregate them.
Note that ``_flatten_tensor_optim_state`` does not need ``optim`` to
flatten/shard the state. However, NamedOptimizer and KeyedOptimizer require
all the states even if the corresponding parameters are empty. To this end,
``optim`` will be used to to get the initial state of the empty parameters.
``optim`` should only be non-None if the ``optim` is KeyedOptimizer or
NamedOptimizer.
Returns:
Dict[str, Any]: The flattened optimizer state dict.
"""
unflat_osd = optim_state_dict
if "state" not in unflat_osd or "param_groups" not in unflat_osd:
raise ValueError(
'`optim_state_dict` must have the keys "state" and '
'"param_groups" to be a valid optimizer state dict'
)
param_to_fqns = _get_param_to_fqns(model)
fqn_to_fsdp_param_info = _get_fqn_to_fsdp_param_info(model)
# Construct the "state" part
flat_osd_state: Dict[Union[_OptimStateKey, str], Any] = {}
unflat_osd_state = unflat_osd["state"]
all_state_keys = set(unflat_osd_state.keys())
# local_state_dict is used to construct states of empty parameters.
# This should only be used if is_named_optimizer=True.
local_state_dict: Dict[str, Any] = {}
local_state_clean_fqns: Dict[str, str] = {}
if optim is not None:
local_state_dict = optim.state_dict()["state"]
for fqn in local_state_dict.keys():
clean_fqn = clean_tensor_name(fqn)
local_state_clean_fqns[clean_fqn] = fqn
for param, unflat_param_names in param_to_fqns.items():
fqn = unflat_param_names[0]
if fqn not in unflat_osd_state:
continue
all_state_keys.difference_update(unflat_param_names)
if fqn in fqn_to_fsdp_param_info:
fsdp_param_info = fqn_to_fsdp_param_info[fqn]
if use_orig_params:
assert (
shard_state
), "If use_orig_params is True, shard_state must be True."
flat_state = _shard_orig_param_state(
fsdp_param_info,
fqn,
unflat_osd_state[fqn],
)
else:
flat_state = _flatten_optim_state(
fsdp_param_info,
unflat_osd_state,
unflat_param_names,
shard_state,
)
key = _OptimStateKey(tuple(unflat_param_names), True)
# Only include non-empty states since as expected by
# `torch.optim.Optimizer` s unless the optimizer is KeyedOptimizer
# or NamedOptimizer.
if flat_state:
flat_osd_state[key] = flat_state
elif optim is not None: # NamedOptimizer or KeyedOptimizer case.
assert len(unflat_param_names) == 1
local_wrapped_fqn = local_state_clean_fqns.get(fqn, "")
if local_wrapped_fqn:
flat_osd_state[key] = copy.deepcopy(
local_state_dict[local_wrapped_fqn]
)
else: # do not flatten non-FSDP parameters' states
assert len(unflat_param_names) == 1
key = _OptimStateKey(tuple(unflat_param_names), False)
flat_osd_state[key] = copy.copy(unflat_osd_state[fqn])
# Handle user-defined state, states that are not accosiated with parameters.
for key in all_state_keys:
flat_osd_state[key] = copy.copy(unflat_osd_state[key])
# Construct the "param_groups" part -- copy as is since it will be
# rekeyed later according to the target rank's optimizer
flat_osd_param_groups = copy.deepcopy(unflat_osd["param_groups"])
return {"state": flat_osd_state, "param_groups": flat_osd_param_groups}
def _flatten_optim_state(
fsdp_param_info: FSDPParamInfo,
unflat_osd_state: Dict[str, Dict[str, Any]],
unflat_param_names: List[str],
shard_state: bool,
) -> Dict[str, Any]:
"""
Flattens the optimizer state in ``full_optim_state_dict`` for a single
flattened parameter in ``fsdp_param_info`` corresponding to the unflattened
parameter names in ``unflat_param_names``.
Args:
unflat_osd_state (Dict[str, Dict[str, Any]]): The "state" part of the
optimizer state dict corresponding to the unflattened parameters.
unflat_param_names (List[str]): A :class:`list` of unflattened
parameter names corresponding to the flattened parameter
``flat_param``.
fsdp_param_info (FSDPParamInfo): The fsdp state and the target flatten
parameter.
shard_state (bool): Whether to shard flattened positive-dimension
tensor state; if ``False``, then the full flattened tensor is
kept in the returned :class:`dict.
Returns:
Dict[str, Any]: A :class:`dict` mapping state names to their values for
a particular flattened parameter. The sharded optimizer state dict's
"state" part will map a key to this returned value.
"""
fsdp_state = fsdp_param_info.state
flat_param = fsdp_param_info.flat_param
num_unflat_params = len(unflat_param_names)
assert num_unflat_params > 0, (
"Expects at least one unflattened parameter corresponding to the "
"flattened parameter"
)
unflat_param_shapes = flat_param._shapes
num_unflat_param_shapes = len(unflat_param_shapes)
assert (
num_unflat_params == num_unflat_param_shapes
), f"Expects {num_unflat_params} shapes but got {num_unflat_param_shapes}"
# Check if these unflattened parameters have any optimizer state
has_state = [
bool(unflat_param_name in unflat_osd_state)
for unflat_param_name in unflat_param_names
]
# If none of the unflattened parameters comprising this flattened parameter
# have any state, then we do not want an entry in the optimizer state dict
if not any(has_state):
return {} # no need to flatten any state
# There may still be some unflattened parameters with state and some
# without
unflat_param_states = [
_gather_state_dict(
unflat_osd_state[unflat_param_name], pg=fsdp_state.process_group
)
if unflat_param_name in unflat_osd_state
else None
for unflat_param_name in unflat_param_names
]
# Check that the unflattened parameters have the same state names
state_names = None
for unflat_param_state in unflat_param_states:
if unflat_param_state is None:
continue
if state_names is None:
state_names = set(unflat_param_state.keys())
else:
if state_names != set(unflat_param_state.keys()):
raise ValueError(
"Differing optimizer state names for the unflattened "
f"parameters: {unflat_param_names}"
)
assert state_names is not None
# Flatten the state
flat_state: Dict[str, Any] = {}
for state_name in state_names:
state_values = [
unflat_param_state[state_name] if unflat_param_state is not None else None
for unflat_param_state in unflat_param_states
]
non_none_state_values = [v for v in state_values if v is not None]
are_pos_dim_tensors = are_zero_dim_tensors = are_non_tensors = True
for v in non_none_state_values:
are_pos_dim_tensors &= torch.is_tensor(v) and v.dim() > 0
are_zero_dim_tensors &= _is_zero_dim_tensor(v)
are_non_tensors &= not torch.is_tensor(v)
types = {type(v) for v in non_none_state_values}
if len(types) != 1 or not (
are_pos_dim_tensors or are_zero_dim_tensors or are_non_tensors
):
raise ValueError(
f"Differing optimizer state types for state {state_name}, "
f"values {non_none_state_values}, and unflattened parameter "
f"names {unflat_param_names}"
)
if are_pos_dim_tensors:
flat_tensor = _flatten_tensor_optim_state(
state_name,
state_values,
unflat_param_names,
unflat_param_shapes,
flat_param,
)
if shard_state:
# Shard the flattened tensor immediately to minimize max memory
# usage
sharded_flat_tensor, _ = FlatParamHandle._get_shard(
flat_tensor,
fsdp_state.rank,
fsdp_state.world_size,
)
flat_state[state_name] = sharded_flat_tensor
else:
flat_state[state_name] = flat_tensor
elif are_zero_dim_tensors:
flat_state[state_name] = _flatten_zero_dim_tensor_optim_state(
state_name,
state_values,
unflat_param_names,
)
else:
assert are_non_tensors
flat_state[state_name] = _flatten_non_tensor_optim_state(
state_name,
state_values,
unflat_param_names,
)
return flat_state
def _flatten_tensor_optim_state(
state_name: str,
pos_dim_tensors: List[torch.Tensor],
unflat_param_names: List[str],
unflat_param_shapes: Sequence[torch.Size],
flat_param: FlatParameter,
) -> torch.Tensor:
"""
Flattens the positive-dimension tensor optimizer state given by the values
``tensors`` for the state ``state_name`` for a single flattened parameter
``flat_param`` corresponding to the unflattened parameter names
``unflat_param_names`` and unflatted parameter shapes
``unflat_param_shapes``. This flattens each unflattened parameter's tensor
state into one tensor.
NOTE: We use zero tensors for any unflattened parameters without state
since some value is required to fill those entries. This assumes that the
zero tensor is mathematically equivalent to having no state, which is true
for Adam's "exp_avg" and "exp_avg_sq" but may not be true for all
optimizers.
Args:
state_name (str): Optimizer state name.
pos_dim_tensors (List[torch.Tensor]): Positive-dimension tensor
optimizer state values for the unflattened parameters corresponding
to the single flattened parameter.
unflat_param_names (List[str]): A :class:`list` of unflattened
parameter names corresponding to the single flattened parameter.
unflat_param_shapes (List[torch.Size]): Unflattened parameter shapes
corresponding to the single flattened parameter.
flat_param (FlatParameter): The flattened parameter.
Returns:
torch.Tensor: A flattened tensor containing the optimizer state
corresponding to ``state_name`` constructed by concatenating the
unflattened parameter tensor states in ``pos_dim_tensors`` (using zero
tensors for any unflattened parameters without the state).
"""
non_none_tensors = [t for t in pos_dim_tensors if t is not None]
# Check that all are tensors with the same dtype
dtypes = {t.dtype for t in non_none_tensors}
if len(dtypes) != 1:
raise ValueError(
"All unflattened parameters comprising a single flattened "
"parameter must have positive-dimension tensor state with the "
f"same dtype but got dtypes {dtypes} for state {state_name} and "
f"unflattened parameter names {unflat_param_names}"
)
dtype = next(iter(dtypes))
# Check that each tensor state matches its parameter's shape
for tensor, shape in zip(pos_dim_tensors, unflat_param_shapes):
if tensor is None and len(shape) == 0:
raise ValueError("Flattening a zero-dimension parameter is not supported")
elif tensor is not None and tensor.shape != shape:
raise ValueError(
"Tensor optimizer state does not have same shape as its "
f"parameter: {tensor.shape} {shape}"
)
# Flatten the tensor states: we do not need to add any padding since the
# flattened optimizer state tensor sharded via `_get_shard()`, which pads
# the shard as needed (just like for the flattened parameter)
cpu_device = torch.device("cpu")
tensors = [
torch.flatten(state_value.to(cpu_device))
if state_value is not None
else torch.flatten(
torch.zeros(
size=shape,
dtype=dtype,
device=cpu_device,
)
)
for state_value, shape in zip(pos_dim_tensors, unflat_param_shapes)
]
flat_tensor = torch.cat(tensors)
flat_param_shape = flat_param._unpadded_unsharded_size # type: ignore[attr-defined]
assert flat_tensor.shape == flat_param_shape, (
f"tensor optim state: {flat_tensor.shape} "
f"flattened parameter: {flat_param_shape}"
)
return flat_tensor
def _flatten_zero_dim_tensor_optim_state(
state_name: str,
zero_dim_tensors: List[torch.Tensor],
unflat_param_names: List[str],
) -> torch.Tensor:
"""
Flattens the zero-dimension tensor optimizer state given by the values
``zero_dim_tensors`` for the state ``state_name`` for a single flattened
parameter corresponding to the unflattened parameter names
``unflat_param_names`` by enforcing that all tensors are the same and using
that common value.
NOTE: The requirement that the tensors are the same across all unflattened
parameters comprising the flattened parameter is needed to maintain the
invariant that FSDP performs the same computation as its non-sharded
equivalent. This means that none of the unflattened parameters can be
missing this state since imposing a value may differ from having no value.
For example, for Adam's "step", no value means maximum bias correction,
while having some positive value means less bias correction.
Args:
state_name (str): Optimizer state name.
zero_dim_tensors (List[torch.Tensor]): Zero-dimension optimizer state
for the unflattened parameters corresponding to the single
flattened parameter.
unflat_param_names (List[str]): A :class:`list` of unflattened
parameter names corresponding to the single flattened parameter.
Returns:
torch.Tensor: A zero-dimensional tensor giving the value of the state
``state_name`` for all unflattened parameters corresponding to the
names ``unflat_param_names``.
"""
non_none_tensors = [t for t in zero_dim_tensors if t is not None]
# Enforce that all have the same value and dtype
values_set = {t.item() if t is not None else None for t in zero_dim_tensors}
dtypes = {t.dtype if t is not None else None for t in zero_dim_tensors}
if (
len(non_none_tensors) != len(zero_dim_tensors)
or len(values_set) != 1
or len(dtypes) != 1
):
raise ValueError(
"All unflattened parameters comprising a single flattened "
"parameter must have scalar state with the same value and dtype "
f"but got values {values_set} and dtypes {dtypes} for state "
f"{state_name} and unflattened parameter names "
f"{unflat_param_names}"
)
value = next(iter(values_set))
dtype = next(iter(dtypes))
return torch.tensor(value, dtype=dtype, device=torch.device("cpu"))
def _flatten_non_tensor_optim_state(
state_name: str,
non_tensors: List[Any],
unflat_param_names: List[str],
) -> Any:
"""
Flattens the non-tensor optimizer state given by the values ``non_tensors``
for the state ``state_name`` for a single flattened parameter corresponding
to the unflattened parameter names ``unflat_param_names`` by enforcing that
all values are the same and using that common value.
See the note in :func:`_flatten_zero_dim_tensor_optim_state`.
Args:
state_name (str): Optimizer state name.
non_tensors (List[Any]): Non-tensor optimizer state for the unflattened
parameters corresponding to the single flattened parameter.
unflat_param_names (List[str]): A :class:`list` of unflattened
parameter names corresponding to the single flattened parameter.
Returns:
Any: A non-tensor giving the value of the state ``state_name`` for all
unflattened parameters corresponding to the names
``unflat_param_names``.
"""
non_none_non_tensors = [nt for nt in non_tensors if nt is not None]
# Enforce that all have the same value (same type already checked)
non_tensor_set = set(non_tensors)
if len(non_none_non_tensors) != len(non_tensors) or len(non_tensor_set) != 1:
raise ValueError(
"All unflattened parameters comprising a single flattened "
"parameter must have scalar state with the same value and dtype "
f"but got values {non_tensor_set} for state {state_name} and "
f"unflattened parameter names {unflat_param_names}"
)
non_tensor = next(iter(non_tensor_set))
return non_tensor
def _process_pos_dim_tensor_state(
flat_optim_state_dict: Dict[str, Any],
world_size: int,
) -> Dict[str, Any]:
"""
Processes positive-dimension tensor states in ``flat_optim_state_dict`` by
replacing them with metadata. This is done so the processed optimizer state
dict can be broadcast from rank 0 to all ranks without copying those tensor
states, and thus, this is meant to only be called on rank 0.
Args:
flat_optim_state_dict (Dict[str, Any]): Flattened optimizer state dict
with the positive-dimension tensor states unsharded.
Returns:
Dict[str, Any]: The flattened optimizer state dict with positive-
dimension tensor states replaced by metadata.
"""
flat_osd = flat_optim_state_dict # alias
no_tensor_osd: Dict[str, Any] = {"state": {}}
for key, param_state in flat_osd["state"].items():
no_tensor_osd["state"][key] = {}
for state_name, value in sorted_items(param_state):
is_pos_dim_tensor_state = torch.is_tensor(value) and value.dim() > 0
if not is_pos_dim_tensor_state:
no_tensor_osd["state"][key][state_name] = value
continue
if key.is_fsdp_managed: # FSDP parameter
sharded_size = FlatParamHandle._get_sharded_size(
value, rank=0, world_size=world_size
)
assert len(sharded_size) == 1, f"{sharded_size}"
info = _PosDimTensorInfo(sharded_size, value.dtype)
else: # non-FSDP parameter
info = _PosDimTensorInfo(value.shape, value.dtype)
no_tensor_osd["state"][key][state_name] = info
no_tensor_osd["param_groups"] = flat_osd["param_groups"]
return no_tensor_osd
def _broadcast_processed_optim_state_dict(
processed_optim_state_dict: Optional[Dict[str, Any]],
rank: int,
group,
) -> Dict[str, Any]:
"""
Broadcasts the processed optimizer state dict from rank 0 to all ranks.
Args:
processed_optim_state_dict (Optional[Dict[str, Any]]): The flattened
optimizer state dict with positive-dimension tensor states replaced
with metadata if on rank 0; ignored otherwise.
Returns:
Dict[str, Any]: The processed optimizer state dict.
"""
# Broadcast the two data structures rank 0 to all ranks
obj_list = [processed_optim_state_dict] if rank == 0 else [None]
dist.broadcast_object_list(obj_list, src=0, group=group)
processed_optim_state_dict = obj_list[0] # type: ignore[assignment]
assert processed_optim_state_dict is not None
# Keep zero-dimension tensors on CPU
return processed_optim_state_dict
def _broadcast_pos_dim_tensor_states(
processed_optim_state_dict: Dict[str, Any],
flat_optim_state_dict: Optional[Dict[str, Any]],
rank: int,
world_size: int,
group,
broadcast_device: torch.device,
) -> Dict[str, Any]:
"""
Takes ``processed_optim_state_dict``, which has metadata in place of
positive-dimension tensor states, and broadcasts those tensor states from
rank 0 to all ranks. For tensor states corresponding to FSDP parameters,
rank 0 shards the tensor and broadcasts shard-by-shard, and for tensor
states corresponding to non-FSDP parameters, rank 0 broadcasts the full
tensor.
Args:
processed_optim_state_dict (Dict[str, Any]): The flattened optimizer
state dict with positive-dimension tensor states replaced with
metadata; this should be returned by
:meth:`_process_pos_dim_tensor_state` and non-empty on all ranks.
flat_optim_state_dict (Optional[Dict[str, Any]]): The flattened
unsharded optimizer state dict with the actual positive-dimension
tensor states if on rank 0; ignored on nonzero ranks.
Returns:
Dict[str, Any]: The optimizer state dict with the positive-dimension
tensor state correctly populated via ``broadcast()`` s from rank 0.
"""
assert (
rank != 0 or flat_optim_state_dict is not None
), "Expects rank 0 to pass in the flattened optimizer state dict"
no_tensor_osd = processed_optim_state_dict # alias
flat_osd = flat_optim_state_dict # alias
for key, param_state in no_tensor_osd["state"].items():
for state_name, value in sorted_items(param_state):
is_pos_dim_tensor_state = isinstance(value, _PosDimTensorInfo)
if not is_pos_dim_tensor_state:
continue
if rank == 0:
assert flat_osd is not None
unsharded_tensor = flat_osd["state"][key][state_name]
else:
unsharded_tensor = None
shape, dtype = value.shape, value.dtype
if key.is_fsdp_managed: # FSDP parameter
_broadcast_sharded_pos_dim_tensor_state(
unsharded_tensor,
param_state,
state_name,
shape,
dtype,
broadcast_device,
rank,
world_size,
group,
) # modify `param_state` destructively
else: # non-FSDP parameter
_broadcast_unsharded_pos_dim_tensor_state(
unsharded_tensor,
param_state,
state_name,
shape,
dtype,
broadcast_device,
rank,
group,
) # modify `param_state` destructively
return no_tensor_osd
def _broadcast_sharded_pos_dim_tensor_state(
unsharded_tensor: Optional[torch.Tensor],
param_state: Dict[str, Any],
state_name: str,
shape: torch.Size,
dtype: torch.dtype,
broadcast_device: torch.device,
rank: int,
world_size: int,
group,
) -> None:
"""
Broadcasts positive-dimension tensor state for the state ``state_name``
corresponding to an FSDP parameter shard-by-shard, only to be saved on the
relevant rank. This modifies ``param_state`` destructively.
Args:
unsharded_tensor (Optional[torch.Tensor]): Unsharded tensor from which
to broadcast shards if on rank 0; ignored otherwise.
shape (torch.Size): Shape of the sharded tensor; same on all ranks.
"""
get_shard: Optional[functools.partial[Tuple[torch.Tensor, int]]] = None
if rank == 0:
assert (
unsharded_tensor is not None
), "Expects rank 0 to pass in the unsharded tensor"
get_shard = functools.partial(
FlatParamHandle._get_shard,
unsharded_tensor,
)
for target_rank in range(1, world_size):
if rank == 0:
assert get_shard is not None
sharded_tensor = get_shard(target_rank, world_size)[0].to(broadcast_device)
else:
sharded_tensor = torch.zeros(
shape,
requires_grad=False,
dtype=dtype,
device=broadcast_device,
)
dist.broadcast(sharded_tensor, src=0, group=group)
# Only keep the shard on the target rank and keep it on the broadcast
# device, which is typically GPU
if rank == target_rank:
param_state[state_name] = sharded_tensor
else:
del sharded_tensor
# Lastly, shard on rank 0
if rank != 0:
return
param_state[state_name] = get_shard(0, world_size)[0].to(broadcast_device) # type: ignore[misc]
def _broadcast_unsharded_pos_dim_tensor_state(
unsharded_tensor: Optional[torch.Tensor],
param_state: Dict[str, Any],
state_name: str,
shape: torch.Size,
dtype: torch.dtype,
broadcast_device: torch.device,
rank: int,
group,
) -> None:
"""
Broadcasts positive-dimension tensor state for the state ``state_name``
corresponding to an unsharded non-FSDP parameter from rank 0 to all ranks.
This modifies ``param_state`` destructively.
Args:
unsharded_tensor (Optional[torch.Tensor]): Unsharded tensor to
broadcast if on rank 0; ignored otherwise.
"""
if rank == 0:
assert (
unsharded_tensor is not None
), "Expects rank 0 to pass in the unsharded tensor"
assert (
shape == unsharded_tensor.shape
), f"Shape mismatch: {shape} {unsharded_tensor.shape}"
assert (
dtype == unsharded_tensor.dtype
), f"dtype mismatch: {dtype} {unsharded_tensor.dtype}"
unsharded_tensor = unsharded_tensor.to(broadcast_device)
else:
unsharded_tensor = torch.zeros(
shape,
requires_grad=False,
dtype=dtype,
device=broadcast_device,
)
dist.broadcast(unsharded_tensor, src=0, group=group)
# Keep the tensor on the broadcast device, which is typically GPU
param_state[state_name] = unsharded_tensor
def _rekey_sharded_optim_state_dict(
sharded_osd: Dict[str, Any],
model: nn.Module,
optim: torch.optim.Optimizer,
optim_input: Optional[
Union[
List[Dict[str, Any]],
Iterable[nn.Parameter],
]
],
using_optim_input: bool,
is_named_optimizer: bool = False,
) -> Dict[str, Any]:
"""
Rekeys the optimizer state dict from unflattened parameter names to
flattened parameter IDs according to the calling rank's ``optim``, which
may be different across ranks. In particular, the unflattened parameter
names are represented as :class:`_OptimStateKey` s.
"""
param_to_fqns = _get_param_to_fqns(model)
flat_param_to_fqn = _get_flat_param_to_fqn(model)
param_to_param_key: Dict[nn.Parameter, Union[int, str]] = cast(
Dict[nn.Parameter, Union[int, str]],
(
_get_param_to_param_id_from_optim_input(model, optim_input)
if using_optim_input
else _get_param_to_param_key(
optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn
)
),
)
# All parameter keys in `param_to_param_key` should be in
# `param_to_fqns` -- strict inequality follows when not all parameters are
# passed to the optimizer
assert len(param_to_param_key) <= len(param_to_fqns)
unflat_param_names_to_flat_param_key: Dict[
Tuple[str, ...], Union[int, str]
] = {} # for "state"
unflat_param_name_to_flat_param_key: Dict[
str, Union[int, str]
] = {} # for "param_groups"
for param, unflat_param_names in param_to_fqns.items():
if param not in param_to_param_key:
# This parameter was not passed to the optimizer
continue
flat_param_key = param_to_param_key[param]
unflat_param_names_to_flat_param_key[tuple(unflat_param_names)] = flat_param_key
for unflat_param_name in unflat_param_names:
unflat_param_name_to_flat_param_key[unflat_param_name] = flat_param_key
sharded_osd_state = sharded_osd["state"]
rekeyed_osd_state: Dict[Union[str, int], Any] = {}
for key, param_state in sharded_osd_state.items():
if isinstance(key, str):
rekeyed_osd_state[key] = param_state
continue
flat_param_key = unflat_param_names_to_flat_param_key.get(
key.unflat_param_names, key.unflat_param_names
)