# Copyright The Lightning AI team.## 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.fromcontextlibimportcontextmanagerfromdatetimeimporttimedeltafromtypingimportAny,Dict,Generator,List,Optional,Unionimporttorchimporttorch.distributedfromtorchimportTensorfromtorch.nnimportModulefromtorch.nn.parallel.distributedimportDistributedDataParallelfromtyping_extensionsimportLiteralfromlightning_fabric.accelerators.acceleratorimportAcceleratorfromlightning_fabric.plugins.collectives.torch_collectiveimportdefault_pg_timeoutfromlightning_fabric.plugins.environments.cluster_environmentimportClusterEnvironmentfromlightning_fabric.plugins.io.checkpoint_ioimportCheckpointIOfromlightning_fabric.plugins.precisionimportPrecisionfromlightning_fabric.strategies.launchers.multiprocessingimport_MultiProcessingLauncherfromlightning_fabric.strategies.launchers.subprocess_scriptimport_SubprocessScriptLauncherfromlightning_fabric.strategies.parallelimportParallelStrategyfromlightning_fabric.strategies.strategyimport_BackwardSyncControl,TBroadcastfromlightning_fabric.utilities.distributedimport(_distributed_available,_get_default_process_group_backend_for_device,_init_dist_connection,_sync_ddp_if_available,)fromlightning_fabric.utilities.distributedimportgroupas_groupfromlightning_fabric.utilities.distributedimportReduceOpfromlightning_fabric.utilities.rank_zeroimportrank_zero_only_DDP_FORK_ALIASES=("ddp_fork","ddp_notebook",)
[docs]classDDPStrategy(ParallelStrategy):"""Strategy for multi-process single-device training on one or multiple nodes."""def__init__(self,accelerator:Optional[Accelerator]=None,parallel_devices:Optional[List[torch.device]]=None,cluster_environment:Optional[ClusterEnvironment]=None,checkpoint_io:Optional[CheckpointIO]=None,precision:Optional[Precision]=None,process_group_backend:Optional[str]=None,timeout:Optional[timedelta]=default_pg_timeout,start_method:Literal["popen","spawn","fork","forkserver"]="popen",**kwargs:Any,)->None:super().__init__(accelerator=accelerator,parallel_devices=parallel_devices,cluster_environment=cluster_environment,checkpoint_io=checkpoint_io,precision=precision,)self._num_nodes=1self._process_group_backend:Optional[str]=process_group_backendself._timeout:Optional[timedelta]=timeoutself._start_method=start_methodself._backward_sync_control=_DDPBackwardSyncControl()self._ddp_kwargs=kwargs@propertydefroot_device(self)->torch.device:assertself.parallel_devicesisnotNonereturnself.parallel_devices[self.local_rank]@propertydefnum_nodes(self)->int:returnself._num_nodes@num_nodes.setterdefnum_nodes(self,num_nodes:int)->None:# note that world ranks is related to num_nodes, when resetting it, need to reset world ranksself._num_nodes=num_nodes@propertydefnum_processes(self)->int:returnlen(self.parallel_devices)ifself.parallel_devicesisnotNoneelse0@propertydefdistributed_sampler_kwargs(self)->Dict[str,Any]:returndict(num_replicas=(self.num_nodes*self.num_processes),rank=self.global_rank)@propertydefprocess_group_backend(self)->Optional[str]:returnself._process_group_backenddef_configure_launcher(self)->None:assertself.cluster_environmentisnotNoneifself._start_method=="popen":self._launcher=_SubprocessScriptLauncher(self.cluster_environment,self.num_processes,self.num_nodes)else:self._launcher=_MultiProcessingLauncher(self,start_method=self._start_method)
[docs]defsetup_module(self,module:Module)->DistributedDataParallel:"""Wraps the model into a :class:`~torch.nn.parallel.distributed.DistributedDataParallel` module."""returnDistributedDataParallel(module=module,device_ids=self._determine_ddp_device_ids(),**self._ddp_kwargs)
[docs]defall_reduce(self,tensor:Tensor,group:Optional[Any]=None,reduce_op:Optional[Union[ReduceOp,str]]="mean")->Tensor:"""Reduces a tensor from several distributed processes to one aggregated tensor. Args: tensor: the tensor to sync and reduce group: the process group to gather results from. Defaults to all processes (world) reduce_op: the reduction operation. Defaults to 'mean'/'avg'. Can also be a string 'sum' to calculate the sum during reduction. Return: reduced value, except when the input was not a tensor the output remains is unchanged """ifisinstance(tensor,Tensor):tensor=_sync_ddp_if_available(tensor,group,reduce_op=reduce_op)returntensor
@classmethoddefregister_strategies(cls,strategy_registry:Dict)->None:entries=(("ddp","popen"),("ddp_spawn","spawn"),("ddp_fork","fork"),("ddp_notebook","fork"),)forname,start_methodinentries:strategy_registry.register(name,cls,description=f"DDP strategy with `start_method={start_method!r}`",start_method=start_method,)def_setup_distributed(self)->None:self._set_world_ranks()rank_zero_only.rank=self.global_rankself._process_group_backend=self._get_process_group_backend()assertself.cluster_environmentisnotNone_init_dist_connection(self.cluster_environment,self._process_group_backend,timeout=self._timeout)def_get_process_group_backend(self)->str:returnself._process_group_backendor_get_default_process_group_backend_for_device(self.root_device)def_set_world_ranks(self)->None:ifself.cluster_environmentisNone:returnself.cluster_environment.set_global_rank(self.node_rank*self.num_processes+self.local_rank)self.cluster_environment.set_world_size(self.num_nodes*self.num_processes)rank_zero_only.rank=self.cluster_environment.global_rank()def_determine_ddp_device_ids(self)->Optional[List[int]]:ifself.root_device.type=="cpu":returnNonereturn[self.root_device.index]
class_DDPBackwardSyncControl(_BackwardSyncControl):@contextmanagerdefno_backward_sync(self,module:Module)->Generator:"""Blocks gradient synchronization inside the :class:`~torch.nn.parallel.distributed.DistributedDataParallel` wrapper."""ifnotisinstance(module,DistributedDataParallel):raiseTypeError("Blocking backward sync is only possible if the module passed to"f" `{self.__class__.__name__}.no_backward_sync` is wrapped in `DistributedDataParallel`."f" Got: {module.__class__.__name__}.")withmodule.no_sync():yield
To analyze traffic and optimize your experience, we serve cookies on this site. By clicking or navigating, you agree to allow our usage of cookies. Read PyTorch Lightning's Privacy Policy.