Source code for pytorch_lightning.strategies.parallel
# Copyright The PyTorch Lightning 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.fromabcimportABC,abstractmethodfromcontextlibimportcontextmanagerfromtypingimportAny,Dict,Generator,List,OptionalimporttorchfromtorchimportTensorimportpytorch_lightningasplfromlightning_lite.pluginsimportCheckpointIO,ClusterEnvironmentfromlightning_lite.utilities.distributedimport_all_gather_ddp_if_available,ReduceOpfrompytorch_lightning.pluginsimportLayerSyncfrompytorch_lightning.plugins.precisionimportPrecisionPluginfrompytorch_lightning.strategies.strategyimportStrategy
[docs]classParallelStrategy(Strategy,ABC):"""Plugin for training with multiple processes in parallel."""def__init__(self,accelerator:Optional["pl.accelerators.Accelerator"]=None,parallel_devices:Optional[List[torch.device]]=None,cluster_environment:Optional[ClusterEnvironment]=None,checkpoint_io:Optional[CheckpointIO]=None,precision_plugin:Optional[PrecisionPlugin]=None,):super().__init__(accelerator=accelerator,checkpoint_io=checkpoint_io,precision_plugin=precision_plugin)self.parallel_devices=parallel_devicesself.cluster_environment:Optional[ClusterEnvironment]=cluster_environmentself._layer_sync:Optional[LayerSync]=None@property@abstractmethoddefroot_device(self)->torch.device:"""Return the root device."""@propertydefglobal_rank(self)->int:returnself.cluster_environment.global_rank()ifself.cluster_environmentisnotNoneelse0@propertydeflocal_rank(self)->int:returnself.cluster_environment.local_rank()ifself.cluster_environmentisnotNoneelse0@propertydefnode_rank(self)->int:returnself.cluster_environment.node_rank()ifself.cluster_environmentisnotNoneelse0@propertydefworld_size(self)->int:returnself.cluster_environment.world_size()ifself.cluster_environmentisnotNoneelse1@propertydefis_global_zero(self)->bool:returnself.global_rank==0@propertydefparallel_devices(self)->Optional[List[torch.device]]:returnself._parallel_devices@parallel_devices.setterdefparallel_devices(self,parallel_devices:Optional[List[torch.device]])->None:self._parallel_devices=parallel_devices@propertydefdistributed_sampler_kwargs(self)->Dict[str,Any]:distributed_sampler_kwargs=dict(num_replicas=len(self.parallel_devices)ifself.parallel_devicesisnotNoneelse0,rank=self.global_rank)returndistributed_sampler_kwargs
[docs]defreconciliate_processes(self,trace:str)->None:"""Function to re-conciliate processes on failure."""
[docs]defall_gather(self,tensor:Tensor,group:Optional[Any]=None,sync_grads:bool=False)->Tensor:"""Perform a all_gather on all processes."""return_all_gather_ddp_if_available(tensor,group=group,sync_grads=sync_grads)
[docs]@contextmanagerdefblock_backward_sync(self)->Generator:"""Blocks ddp sync gradients behaviour on backwards pass. This is useful for skipping sync when accumulating gradients, reducing communication overhead Returns: context manager with sync behaviour off """ifisinstance(self.model,pl.utilities.types.DistributedDataParallel):withself.model.no_sync():yieldNoneelse:yieldNone
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.