20
20
import threading
21
21
from abc import ABC
22
22
from datetime import timedelta
23
- from typing import TYPE_CHECKING , Dict , List , Optional , Type
23
+ from typing import TYPE_CHECKING , Dict , List , Optional , Tuple , Type , Union
24
24
25
25
import torch
26
26
import torch .distributed as dist
38
38
Store ,
39
39
TCPStore ,
40
40
get_rank ,
41
+ init_device_mesh ,
41
42
)
42
43
from torch .distributed .distributed_c10d import Work , _world
43
44
from torch .futures import Future
@@ -130,17 +131,7 @@ def size(self) -> int:
130
131
def getBackendName (self ) -> str :
131
132
raise NotImplementedError ("not implemented" )
132
133
133
- def register (self , name : str ) -> "ProcessGroup" :
134
- """
135
- Registers the process group with the global registry. This enables usage
136
- with things like functional_collectives which are compilable.
137
-
138
- This should only be called once.
139
-
140
- Args:
141
- name: name must be a unique name for this process group
142
- """
143
-
134
+ def _register (self , name : str ) -> str :
144
135
group_name = f"{ self .getBackendName ()} :{ name } "
145
136
146
137
# This is needed for DeviceMesh and functional collectives to work.
@@ -158,6 +149,21 @@ def create_pg(
158
149
devices = ["cpu" ]
159
150
dist .Backend .register_backend (group_name , create_pg , devices = devices )
160
151
152
+ return group_name
153
+
154
+ def register (self , name : str ) -> "ProcessGroup" :
155
+ """
156
+ Registers the process group with the global registry. This enables usage
157
+ with things like functional_collectives which are compilable.
158
+
159
+ This should only be called once.
160
+
161
+ Args:
162
+ name: name must be a unique name for this process group
163
+ """
164
+
165
+ group_name = self ._register (name )
166
+
161
167
return dist .new_group (
162
168
ranks = [dist .get_rank ()],
163
169
backend = group_name ,
@@ -496,6 +502,9 @@ def allreduce(self, tensors: List[torch.Tensor], opts: object) -> Work:
496
502
def size (self ) -> int :
497
503
return self ._manager .num_participants ()
498
504
505
+ def getBackendName (self ) -> str :
506
+ return self ._manager ._pg .getBackendName ()
507
+
499
508
500
509
class _BabyWork (Work ):
501
510
def __init__ (
@@ -689,7 +698,6 @@ def _future_handler(self, future_queue: mp.Queue) -> None:
689
698
logger .exception (f"got unexpected error in future handler: { e } " )
690
699
691
700
def _get_future (self , op_id : int ) -> Future [object ]:
692
-
693
701
with self ._futures_lock :
694
702
fut = Future () # pyre-fixme[29]: is not a function
695
703
self ._futures [op_id ] = fut
@@ -797,3 +805,228 @@ def extend_device_mesh(
797
805
mesh = mesh .mesh .unsqueeze (dim ),
798
806
mesh_dim_names = tuple (mesh_dim_names ),
799
807
)
808
+
809
+
810
+ class ManagedDeviceMesh (DeviceMesh ):
811
+ def __init__ (
812
+ self ,
813
+ mesh : Optional [DeviceMesh ],
814
+ mesh_dim_names : Tuple [str , ...],
815
+ replicate_pg : ManagedProcessGroup ,
816
+ replicate_dim : int ,
817
+ parent : Optional ["ManagedDeviceMesh" ],
818
+ ) -> None :
819
+ if mesh is None and parent is not None :
820
+ raise ValueError (
821
+ "ManagedDeviceMesh doesn't support both mesh and parent are None."
822
+ )
823
+ self .mesh = mesh
824
+ self .mesh_dim_names = mesh_dim_names
825
+ self .replicate_pg = replicate_pg
826
+ self .replicate_dim = replicate_dim
827
+ self .replicate_dim_name : str = mesh_dim_names [replicate_dim ]
828
+ self .parent = parent
829
+ self .flatten_meshes : Dict [str , DeviceMesh ] = {}
830
+ self .device_type : str
831
+ if mesh is not None :
832
+ self .device_type = mesh .device_type
833
+ else :
834
+ assert parent is not None
835
+ self .device_type = parent .device_type
836
+ self ._flatten_mesh_list : Tuple [DeviceMesh , ...] = tuple ()
837
+ self ._thread_id : Optional [int ] = None
838
+
839
+ def __getitem__ (self , mesh_dim_names : Union [str , Tuple [str , ...]]) -> DeviceMesh :
840
+ if isinstance (mesh_dim_names , str ):
841
+ if mesh_dim_names == self .replicate_dim_name :
842
+ return ManagedDeviceMesh (
843
+ mesh = None ,
844
+ mesh_dim_names = (mesh_dim_names ,),
845
+ replicate_pg = self .replicate_pg ,
846
+ replicate_dim = 0 ,
847
+ parent = self ,
848
+ )
849
+ elif mesh_dim_names in self .flatten_meshes :
850
+ return self .flatten_meshes [mesh_dim_names ]
851
+ else :
852
+ assert self .mesh is not None
853
+ return self .mesh [mesh_dim_names ]
854
+ else :
855
+ assert isinstance (mesh_dim_names , tuple )
856
+ if self .replicate_dim_name in mesh_dim_names :
857
+ assert self .mesh is not None
858
+ return self .mesh [mesh_dim_names ]
859
+ else :
860
+ return ManagedDeviceMesh (
861
+ self .mesh [mesh_dim_names ],
862
+ mesh_dim_names ,
863
+ self .replicate_pg ,
864
+ mesh_dim_names .index (self .replicate_dim_name ),
865
+ parent = self ,
866
+ )
867
+
868
+ def _real_mesh_dim (self , mesh_dim : int ) -> int :
869
+ return mesh_dim - 1 if mesh_dim > self .replicate_dim else mesh_dim
870
+
871
+ def get_group (self , mesh_dim : Optional [Union [int , str ]] = None ) -> BaseProcessGroup :
872
+ if isinstance (mesh_dim , str ):
873
+ dim = self .mesh_dim_names .index (mesh_dim )
874
+ else :
875
+ dim = 0 if mesh_dim is None else int (mesh_dim )
876
+
877
+ if mesh_dim is None :
878
+ assert self .mesh is not None
879
+ return self .replicate_pg
880
+ elif dim == self .replicate_dim :
881
+ return self .replicate_pg
882
+ else :
883
+ assert self .mesh is not None
884
+ return self .mesh .get_group (self ._real_mesh_dim (dim ))
885
+
886
+ def _flatten (self , mesh_dim_name : str ) -> "DeviceMesh" :
887
+ flatten_mesh = _FlattenDeviceMesh (self )
888
+ if self .parent is None :
889
+ self .flatten_meshes [mesh_dim_name ] = flatten_mesh
890
+ else :
891
+ self .parent .flatten_meshes [mesh_dim_name ] = flatten_mesh
892
+ return flatten_mesh
893
+
894
+ def size (self , mesh_dim : Optional [int ] = None ) -> int :
895
+ if mesh_dim is None :
896
+ if self .mesh is None :
897
+ return self .replicate_pg .size ()
898
+ else :
899
+ assert self .mesh is not None
900
+ return self .mesh .size () * self .replicate_pg .size ()
901
+ elif mesh_dim == self .replicate_dim :
902
+ return self .replicate_pg .size ()
903
+ else :
904
+ return self .mesh .size (self ._real_mesh_dim (mesh_dim ))
905
+
906
+ @property
907
+ def ndim (self ) -> int :
908
+ assert self .mesh is not None
909
+ return self .mesh .ndim + 1
910
+
911
+ @property
912
+ def shape (self ) -> Tuple [int , ...]:
913
+ assert self .mesh is not None
914
+ ret : List [int ] = list (self .mesh .shape )
915
+ ret .insert (self .replicate_dim , self .replicate_pg .size ())
916
+ return tuple (ret )
917
+
918
+ def get_rank (self ) -> int :
919
+ assert self .mesh is not None
920
+ return self .mesh .get_rank ()
921
+
922
+ def get_local_rank (self , mesh_dim : Optional [Union [int , str ]] = None ) -> int :
923
+ if isinstance (mesh_dim , str ):
924
+ dim = self .mesh_dim_names .index (mesh_dim )
925
+ else :
926
+ dim = 0 if mesh_dim is None else int (mesh_dim )
927
+
928
+ if mesh_dim is None :
929
+ if self .mesh is None :
930
+ return get_rank (self .replicate_pg )
931
+
932
+ assert self .replicate_dim == 0 , "replicate_dim must be the first one"
933
+ assert self .mesh is not None
934
+ other_dim_size = self .mesh .size ()
935
+ assert self .mesh is not None
936
+ other_dim_rank = self .mesh .get_local_rank ()
937
+ replicate_pg_rank = get_rank (self .replicate_pg )
938
+ return other_dim_size * replicate_pg_rank + other_dim_rank
939
+ elif dim == self .replicate_dim :
940
+ return get_rank (self .replicate_pg )
941
+ else :
942
+ assert self .mesh is not None
943
+ return self .mesh .get_local_rank (self ._real_mesh_dim (dim ))
944
+
945
+ def get_coordinate (self ) -> Optional [List [int ]]:
946
+ """
947
+ Return the relative indices of this rank relative to all
948
+ dimensions of the mesh. If this rank is not part of the mesh, return None.
949
+ """
950
+ assert self .mesh is not None
951
+ return self .mesh ._coordinate_on_dim if self .mesh ._coordinate_on_dim else None
952
+
953
+ def get_all_groups (self ) -> List [BaseProcessGroup ]:
954
+ raise NotImplementedError
955
+
956
+
957
+ class _FlattenDeviceMesh (DeviceMesh ):
958
+ def __init__ (self , managed_mesh : ManagedDeviceMesh ) -> None :
959
+ self .managed_mesh = managed_mesh
960
+
961
+ def __getitem__ (self , mesh_dim_names : Union [str , Tuple [str , ...]]) -> DeviceMesh :
962
+ raise NotImplementedError
963
+
964
+ def get_group (self , mesh_dim : Optional [Union [int , str ]] = None ) -> BaseProcessGroup :
965
+ raise NotImplementedError
966
+
967
+ def _flatten (self , mesh_dim_name : Optional [str ]) -> "DeviceMesh" :
968
+ raise NotImplementedError
969
+
970
+ def size (self , mesh_dim : Optional [int ] = None ) -> int :
971
+ assert mesh_dim is None
972
+ return self .managed_mesh .size ()
973
+
974
+ @property
975
+ def ndim (self ) -> int :
976
+ raise NotImplementedError
977
+
978
+ @property
979
+ def shape (self ) -> Tuple [int , ...]:
980
+ raise NotImplementedError
981
+
982
+ def get_rank (self ) -> int :
983
+ raise NotImplementedError
984
+
985
+ def get_local_rank (self , mesh_dim : Optional [Union [int , str ]] = None ) -> int :
986
+ assert mesh_dim is None
987
+ return self .managed_mesh .get_local_rank ()
988
+
989
+ def get_all_groups (self ) -> List [BaseProcessGroup ]:
990
+ raise NotImplementedError
991
+
992
+
993
+ def ft_init_device_mesh (
994
+ * ,
995
+ device_type : str ,
996
+ mesh_shape : Tuple [int , ...],
997
+ mesh_dim_names : Tuple [str , ...],
998
+ replicate_dim : int ,
999
+ manager : "Manager" ,
1000
+ ) -> "ManagedDeviceMesh" :
1001
+ # We need to mislead DeviceMesh into thinking that replicate_dim has only
1002
+ # 1 rank.
1003
+ _mesh_shape = list (mesh_shape )
1004
+ _mesh_shape .pop (replicate_dim )
1005
+ _mesh_dim_names = list (mesh_dim_names )
1006
+ _mesh_dim_names .pop (replicate_dim )
1007
+ mesh = init_device_mesh (
1008
+ device_type ,
1009
+ mesh_shape = tuple (_mesh_shape ),
1010
+ mesh_dim_names = tuple (_mesh_dim_names ),
1011
+ )
1012
+
1013
+ if device_type == "cpu" :
1014
+ pg = ProcessGroupGloo ()
1015
+ elif device_type == "cuda" :
1016
+ pg = ProcessGroupNCCL ()
1017
+ else :
1018
+ raise ValueError ()
1019
+
1020
+ manager ._pg = pg
1021
+ replicate_pg = ManagedProcessGroup (manager )
1022
+ # We have to use MultiProcessTestCase, otherwise c10d will complain
1023
+ # the same backend has been registered.
1024
+ replicate_pg .register (mesh_dim_names [replicate_dim ])
1025
+
1026
+ return ManagedDeviceMesh (
1027
+ mesh = mesh ,
1028
+ mesh_dim_names = mesh_dim_names ,
1029
+ replicate_pg = replicate_pg ,
1030
+ replicate_dim = replicate_dim ,
1031
+ parent = None ,
1032
+ )
0 commit comments