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,201 @@ 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
+ ):
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 = mesh_dim_names [replicate_dim ]
828
+ self .parent = parent
829
+ self .flatten_meshes = {}
830
+ self .device_type = mesh .device_type if mesh is not None else parent .device_type
831
+ self ._flatten_mesh_list = tuple ()
832
+ self ._thread_id = None
833
+
834
+ def __getitem__ (self , mesh_dim_names : Union [str , Tuple [str , ...]]) -> DeviceMesh :
835
+ if isinstance (mesh_dim_names , str ):
836
+ if mesh_dim_names == self .replicate_dim_name :
837
+ return _ManagedDeviceMesh (
838
+ mesh = None ,
839
+ mesh_dim_names = (mesh_dim_names ,),
840
+ replicate_pg = self .replicate_pg ,
841
+ replicate_dim = 0 ,
842
+ parent = self ,
843
+ )
844
+ elif mesh_dim_names in self .flatten_meshes :
845
+ return self .flatten_meshes [mesh_dim_names ]
846
+ else :
847
+ return self .mesh [mesh_dim_names ]
848
+ else :
849
+ assert isinstance (mesh_dim_names , tuple )
850
+ if self .replicate_dim_name in mesh_dim_names :
851
+ return self .mesh [mesh_dim_names ]
852
+ else :
853
+ return _ManagedDeviceMesh (
854
+ self .mesh [mesh_dim_names ],
855
+ mesh_dim_names ,
856
+ self .replicate_pg ,
857
+ mesh_dim_name .index (self .replicate_dim_name ),
858
+ parent = self ,
859
+ )
860
+
861
+ def _real_mesh_dim (self , mesh_dim : int ) -> int :
862
+ return mesh_dim - 1 if mesh_dim > self .replicate_dim else mesh_dim
863
+
864
+ def get_group (self , mesh_dim : Optional [str ] = None ) -> BaseProcessGroup :
865
+ if mesh_dim is None :
866
+ assert self .mesh is None
867
+ return self .replicate_pg
868
+ elif mesh_dim == self .replicate_dim_name :
869
+ return self .replicate_pg
870
+ else :
871
+ return self .mesh .get_group (self ._real_mesh_dim (mesh_dim ))
872
+
873
+ def _flatten (self , mesh_dim_name : str ) -> "DeviceMesh" :
874
+ flatten_mesh = _FlattenDeviceMesh (self )
875
+ if self .parent is None :
876
+ self .flatten_meshes [mesh_dim_name ] = flatten_mesh
877
+ else :
878
+ self .parent .flatten_meshes [mesh_dim_name ] = flatten_mesh
879
+ return flatten_mesh
880
+
881
+ def size (self , mesh_dim : Optional [int ] = None ) -> int :
882
+ if mesh_dim is None :
883
+ if self .mesh is None :
884
+ return self .replicate_pg .size ()
885
+ else :
886
+ return self .mesh .size () * self .replicate_pg .size ()
887
+ elif mesh_dim == self .replicate_dim :
888
+ return self .replicate_pg .size ()
889
+ else :
890
+ return self .mesh .size (self ._real_mesh_dim (mesh_dim ))
891
+
892
+ @property
893
+ def ndim (self ) -> int :
894
+ return self .mesh .ndim + 1
895
+
896
+ @property
897
+ def shape (self ) -> Tuple [int , ...]:
898
+ ret = list (self .mesh .shape )
899
+ ret .insert (self .replicate_dim , self .replicate_pg .size ())
900
+
901
+ def get_rank (self ) -> int :
902
+ return self .mesh .get_rank ()
903
+
904
+ def get_local_rank (self , mesh_dim : Optional [Union [int , str ]] = None ) -> int :
905
+ if mesh_dim is None :
906
+ if self .mesh is None :
907
+ return get_rank (self .replicate_pg )
908
+
909
+ assert self .replicate_dim == 0 , "replicate_dim must be the first one"
910
+ other_dim_size = self .mesh .size ()
911
+ other_dim_rank = self .mesh .get_local_rank ()
912
+ replicate_pg_rank = get_rank (self .replicate_pg )
913
+ return other_dim_size * replicate_pg_rank + other_dim_rank
914
+ elif mesh_dim in (self .replicate_dim , self .replicate_dim_name ):
915
+ return get_rank (self .replicate_pg )
916
+ else :
917
+ return self .mesh .get_local_rank (self ._real_mesh_dim (mesh_dim ))
918
+
919
+ def get_coordinate (self ) -> Optional [List [int ]]:
920
+ """
921
+ Return the relative indices of this rank relative to all
922
+ dimensions of the mesh. If this rank is not part of the mesh, return None.
923
+ """
924
+ return self .mesh ._coordinate_on_dim if self .mesh ._coordinate_on_dim else None
925
+
926
+ def get_all_groups (self ) -> List [ProcessGroup ]:
927
+ raise NotImplementedError
928
+
929
+
930
+ class _FlattenDeviceMesh (DeviceMesh ):
931
+ def __init__ (self , managed_mesh : _ManagedDeviceMesh ):
932
+ self .managed_mesh = managed_mesh
933
+
934
+ def __getitem__ (self , mesh_dim_names : Union [str , Tuple [str , ...]]) -> DeviceMesh :
935
+ raise NotImplementedError
936
+
937
+ def get_group (self , mesh_dim : Optional [str ] = None ) -> BaseProcessGroup :
938
+ raise NotImplementedError
939
+
940
+ def _flatten (self , mesh_dim_name : str ) -> "DeviceMesh" :
941
+ raise NotImplementedError
942
+
943
+ def size (self , mesh_dim : Optional [int ] = None ) -> int :
944
+ assert mesh_dim is None
945
+ return self .managed_mesh .size ()
946
+
947
+ @property
948
+ def ndim (self ) -> int :
949
+ raise NotImplementedError
950
+
951
+ @property
952
+ def shape (self ) -> Tuple [int , ...]:
953
+ raise NotImplementedError
954
+
955
+ def get_rank (self ) -> int :
956
+ raise NotImplementedError
957
+
958
+ def get_local_rank (self , mesh_dim : Optional [Union [int , str ]] = None ) -> int :
959
+ assert mesh_dim is None
960
+ return self .managed_mesh .get_local_rank ()
961
+
962
+ def get_all_groups (self ) -> List [ProcessGroup ]:
963
+ raise NotImplementedError
964
+
965
+
966
+ def ft_init_device_mesh (
967
+ * ,
968
+ device_type : str ,
969
+ mesh_shape : Tuple [int , ...],
970
+ mesh_dim_names : Tuple [str , ...],
971
+ replicate_dim : int ,
972
+ manager : "Manager" ,
973
+ ):
974
+ # We need to mislead DeviceMesh into thinking that replicate_dim has only
975
+ # 1 rank.
976
+ _mesh_shape = list (mesh_shape )
977
+ _mesh_shape .pop (replicate_dim )
978
+ _mesh_dim_names = list (mesh_dim_names )
979
+ _mesh_dim_names .pop (replicate_dim )
980
+ mesh = init_device_mesh (
981
+ device_type ,
982
+ mesh_shape = tuple (_mesh_shape ),
983
+ mesh_dim_names = tuple (_mesh_dim_names ),
984
+ )
985
+
986
+ if device_type == "cpu" :
987
+ pg = ProcessGroupGloo ()
988
+ elif device_type == "cuda" :
989
+ pg = ProcessGroupNCCL ()
990
+ else :
991
+ raise ValueError ()
992
+
993
+ manager ._pg = pg
994
+ replicate_pg = ManagedProcessGroup (manager )
995
+ # We have to use MultiProcessTestCase, otherwise c10d will complain
996
+ # the same backend has been registered.
997
+ replicate_pg .register (mesh_dim_names [replicate_dim ])
998
+
999
+ return _ManagedDeviceMesh (
1000
+ mesh = mesh ,
1001
+ mesh_dim_names = mesh_dim_names ,
1002
+ replicate_pg = replicate_pg ,
1003
+ replicate_dim = replicate_dim ,
1004
+ parent = None ,
1005
+ )
0 commit comments