r"""This package adds support for CUDA tensor types, that implement the samefunction as CPU tensors, but they utilize GPUs for computation.It is lazily initialized, so you can always import it, and use:func:`is_available()` to determine if your system supports CUDA.:ref:`cuda-semantics` has more details about working with CUDA."""importcontextlibimportosimporttorchimporttracebackimportwarningsimportthreadingfromtypingimportList,Optional,Tuple,Union,Anyfrom._utilsimport_get_device_index,_dummy_typefrom.graphsimportCUDAGraph,graph_pool_handle,graph,make_graphed_callablesfrom.streamsimportStream,Eventfrom..importdeviceas_deviceimporttorch._Ctry:fromtorch._Cimport_cudart# type: ignore[attr-defined]exceptImportError:_cudart=None_initialized=False_tls=threading.local()_initialization_lock=threading.Lock()_queued_calls=[]# don't invoke these until initialization occurs_is_in_bad_fork=getattr(torch._C,"_cuda_isInBadFork",lambda:False)_device_t=Union[_device,str,int,None]class_LazySeedTracker:# Since seeding is memory-less, only track the latest seed.# Note: `manual_seed_all` followed by `manual_seed` overwrites# the seed on current device. We track the order of **latest**# calls between these two API.def__init__(self):self.manual_seed_all_cb=Noneself.manual_seed_cb=Noneself.call_order=[]defqueue_seed_all(self,cb,traceback):self.manual_seed_all_cb=(cb,traceback)# update seed_all to be latestself.call_order=[self.manual_seed_cb,self.manual_seed_all_cb]defqueue_seed(self,cb,traceback):self.manual_seed_cb=(cb,traceback)# update seed to be latestself.call_order=[self.manual_seed_all_cb,self.manual_seed_cb]defget_calls(self)->List:returnself.call_order_lazy_seed_tracker=_LazySeedTracker()# Define dummy _CudaDeviceProperties type if PyTorch was compiled without CUDAifhasattr(torch._C,'_CudaDeviceProperties'):_CudaDeviceProperties=torch._C._CudaDevicePropertieselse:_CudaDeviceProperties=_dummy_type('_CudaDeviceProperties')# type: ignore[assignment, misc]# Global variables dynamically populated by native codehas_magma:bool=Falsehas_half:bool=Falsedefault_generators:Tuple[torch._C.Generator]=()# type: ignore[assignment]
[docs]defis_available()->bool:r"""Returns a bool indicating if CUDA is currently available."""ifnothasattr(torch._C,'_cuda_getDeviceCount'):returnFalse# This function never throws and returns 0 if driver is missing or can't# be initializedreturntorch._C._cuda_getDeviceCount()>0
defis_bf16_supported():r"""Returns a bool indicating if the current CUDA device supports dtype bfloat16"""cu_vers=torch.version.cudaifcu_versisnotNone:cuda_maj_decide=int(cu_vers.split('.')[0])>=11else:cuda_maj_decide=Falsereturntorch.cuda.get_device_properties(torch.cuda.current_device()).major>=8andcuda_maj_decidedef_sleep(cycles):torch._C._cuda_sleep(cycles)def_check_capability():incorrect_binary_warn=""" Found GPU%d%s which requires CUDA_VERSION >= %d to work properly, but your PyTorch was compiled with CUDA_VERSION %d. Please install the correct PyTorch binary using instructions from https://pytorch.org """old_gpu_warn=""" Found GPU%d%s which is of cuda capability %d.%d. PyTorch no longer supports this GPU because it is too old. The minimum cuda capability supported by this library is %d.%d. """iftorch.version.cudaisnotNone:# on ROCm we don't want this checkCUDA_VERSION=torch._C._cuda_getCompiledVersion()fordinrange(device_count()):capability=get_device_capability(d)major=capability[0]minor=capability[1]name=get_device_name(d)current_arch=major*10+minormin_arch=min((int(arch.split("_")[1])forarchintorch.cuda.get_arch_list()),default=35)ifcurrent_arch<min_arch:warnings.warn(old_gpu_warn.format(d,name,major,minor,min_arch//10,min_arch%10))elifCUDA_VERSION<=9000andmajor>=7andminor>=5:warnings.warn(incorrect_binary_warn%(d,name,10000,CUDA_VERSION))def_check_cubins():incompatible_device_warn="""{} with CUDA capability sm_{} is not compatible with the current PyTorch installation.The current PyTorch install supports CUDA capabilities {}.If you want to use the {} GPU with PyTorch, please check the instructions at https://pytorch.org/get-started/locally/"""iftorch.version.cudaisNone:# on ROCm we don't want this checkreturnarch_list=get_arch_list()iflen(arch_list)==0:returnsupported_sm=[int(arch.split('_')[1])forarchinarch_listif'sm_'inarch]foridxinrange(device_count()):cap_major,cap_minor=get_device_capability(idx)# NVIDIA GPU compute architectures are backward compatible within major versionsupported=any([sm//10==cap_majorforsminsupported_sm])ifnotsupported:device_name=get_device_name(idx)capability=cap_major*10+cap_minorwarnings.warn(incompatible_device_warn.format(device_name,capability," ".join(arch_list),device_name))
[docs]defis_initialized():r"""Returns whether PyTorch's CUDA state has been initialized."""return_initializedandnot_is_in_bad_fork()
def_lazy_call(callable,**kwargs):ifis_initialized():callable()else:# TODO(torch_deploy): this accesses linecache, which attempts to read the# file system to get traceback info. Patch linecache or do something# else here if this ends up being important.global_lazy_seed_trackerifkwargs.get("seed_all",False):_lazy_seed_tracker.queue_seed_all(callable,traceback.format_stack())elifkwargs.get("seed",False):_lazy_seed_tracker.queue_seed(callable,traceback.format_stack())else:# Don't store the actual traceback to avoid memory cycle_queued_calls.append((callable,traceback.format_stack()))_lazy_call(_check_capability)_lazy_call(_check_cubins)classDeferredCudaCallError(Exception):pass
[docs]definit():r"""Initialize PyTorch's CUDA state. You may need to call this explicitly if you are interacting with PyTorch via its C API, as Python bindings for CUDA functionality will not be available until this initialization takes place. Ordinary users should not need this, as all of PyTorch's CUDA methods automatically initialize CUDA state on-demand. Does nothing if the CUDA state is already initialized. """_lazy_init()
def_lazy_init():global_initialized,_queued_callsifis_initialized()orhasattr(_tls,'is_initializing'):returnwith_initialization_lock:# We be double-checked locking, boys! This is OK because# the above test was GIL protected anyway. The inner test# is for when a thread blocked on some other thread which was# doing the initialization; when they get the lock, they will# find there is nothing left to do.ifis_initialized():return# It is important to prevent other threads from entering _lazy_init# immediately, while we are still guaranteed to have the GIL, because some# of the C calls we make below will release the GILif_is_in_bad_fork():raiseRuntimeError("Cannot re-initialize CUDA in forked subprocess. To use CUDA with ""multiprocessing, you must use the 'spawn' start method")ifnothasattr(torch._C,'_cuda_getDeviceCount'):raiseAssertionError("Torch not compiled with CUDA enabled")if_cudartisNone:raiseAssertionError("libcudart functions unavailable. It looks like you have a broken build?")# This function throws if there's a driver initialization error, no GPUs# are found or any other error occurstorch._C._cuda_init()# Some of the queued calls may reentrantly call _lazy_init();# we need to just return without initializing in that case.# However, we must not let any *other* threads in!_tls.is_initializing=Trueforcallsin_lazy_seed_tracker.get_calls():ifcalls:_queued_calls.append(calls)try:forqueued_call,orig_tracebackin_queued_calls:try:queued_call()exceptExceptionase:msg=(f"CUDA call failed lazily at initialization with error: {str(e)}\n\n"f"CUDA call was originally invoked at:\n\n{orig_traceback}")raiseDeferredCudaCallError(msg)fromefinally:delattr(_tls,'is_initializing')_initialized=Truedefcudart():_lazy_init()return_cudartclasscudaStatus(object):SUCCESS:int=0ERROR_NOT_READY:int=34classCudaError(RuntimeError):def__init__(self,code:int)->None:msg=_cudart.cudaGetErrorString(_cudart.cudaError(code))super(CudaError,self).__init__('{0} ({1})'.format(msg,code))defcheck_error(res:int)->None:ifres!=_cudart.cudaError.success:raiseCudaError(res)
[docs]classdevice(object):r"""Context-manager that changes the selected device. Args: device (torch.device or int): device index to select. It's a no-op if this argument is a negative integer or ``None``. """def__init__(self,device:Any):self.idx=_get_device_index(device,optional=True)self.prev_idx=-1def__enter__(self):ifself.idx==-1:returnself.prev_idx=torch.cuda.current_device()ifself.prev_idx!=self.idx:torch.cuda.set_device(self.idx)ifnottorch.jit.is_scripting():_lazy_init()def__exit__(self,type:Any,value:Any,traceback:Any):ifself.prev_idx!=self.idx:torch.cuda.set_device(self.prev_idx)returnFalse
[docs]classdevice_of(device):r"""Context-manager that changes the current device to that of given object. You can use both tensors and storages as arguments. If a given object is not allocated on a GPU, this is a no-op. Args: obj (Tensor or Storage): object allocated on the selected device. """def__init__(self,obj):idx=obj.get_device()ifobj.is_cudaelse-1super(device_of,self).__init__(idx)
[docs]defset_device(device:_device_t)->None:r"""Sets the current device. Usage of this function is discouraged in favor of :any:`device`. In most cases it's better to use ``CUDA_VISIBLE_DEVICES`` environmental variable. Args: device (torch.device or int): selected device. This function is a no-op if this argument is negative. """device=_get_device_index(device)ifdevice>=0:torch._C._cuda_setDevice(device)
[docs]defget_device_name(device:Optional[_device_t]=None)->str:r"""Gets the name of a device. Args: device (torch.device or int, optional): device for which to return the name. This function is a no-op if this argument is a negative integer. It uses the current device, given by :func:`~torch.cuda.current_device`, if :attr:`device` is ``None`` (default). Returns: str: the name of the device """returnget_device_properties(device).name
[docs]defget_device_capability(device:Optional[_device_t]=None)->Tuple[int,int]:r"""Gets the cuda capability of a device. Args: device (torch.device or int, optional): device for which to return the device capability. This function is a no-op if this argument is a negative integer. It uses the current device, given by :func:`~torch.cuda.current_device`, if :attr:`device` is ``None`` (default). Returns: tuple(int, int): the major and minor cuda capability of the device """prop=get_device_properties(device)returnprop.major,prop.minor
[docs]defget_device_properties(device:_device_t)->_CudaDeviceProperties:r"""Gets the properties of a device. Args: device (torch.device or int or str): device for which to return the properties of the device. Returns: _CudaDeviceProperties: the properties of the device """_lazy_init()# will define _get_device_propertiesdevice=_get_device_index(device,optional=True)ifdevice<0ordevice>=device_count():raiseAssertionError("Invalid device id")return_get_device_properties(device)# type: ignore[name-defined]
[docs]defcan_device_access_peer(device:_device_t,peer_device:_device_t)->bool:r"""Checks if peer access between two devices is possible. """_lazy_init()device=_get_device_index(device,optional=True)peer_device=_get_device_index(peer_device)ifdevice<0ordevice>=device_count():raiseAssertionError("Invalid device id")ifpeer_device<0orpeer_device>=device_count():raiseAssertionError("Invalid peer device id")returntorch._C._cuda_canDeviceAccessPeer(device,peer_device)
[docs]classStreamContext(object):r"""Context-manager that selects a given stream. All CUDA kernels queued within its context will be enqueued on a selected stream. Args: Stream (Stream): selected stream. This manager is a no-op if it's ``None``. .. note:: Streams are per-device. """cur_stream:Optional['torch.cuda.Stream']def__init__(self,stream:Optional['torch.cuda.Stream']):self.stream=streamself.idx=_get_device_index(None,True)ifnottorch.jit.is_scripting():ifself.idxisNone:self.idx=-1self.src_prev_stream=Noneifnottorch.jit.is_scripting()elsetorch.cuda.default_stream(None)self.dst_prev_stream=Noneifnottorch.jit.is_scripting()elsetorch.cuda.default_stream(None)def__enter__(self):# Local cur_stream variable for type refinementcur_stream=self.stream# Return if stream is None or CUDA device not availableifcur_streamisNoneorself.idx==-1:returnself.src_prev_stream=torch.cuda.current_stream(None)# If the stream is not on the current device, then# set the current stream on the deviceifself.src_prev_stream.device!=cur_stream.device:withdevice(cur_stream.device):self.dst_prev_stream=torch.cuda.current_stream(cur_stream.device)torch.cuda.set_stream(cur_stream)def__exit__(self,type:Any,value:Any,traceback:Any):# Local cur_stream variable for type refinementcur_stream=self.stream# If stream is None or no CUDA device available, returnifcur_streamisNoneorself.idx==-1:return# Reset the stream on the original device# and destination deviceifself.src_prev_stream.device!=cur_stream.device:# type: ignore[union-attr]torch.cuda.set_stream(self.dst_prev_stream)# type: ignore[arg-type]torch.cuda.set_stream(self.src_prev_stream)# type: ignore[arg-type]
[docs]defstream(stream:Optional['torch.cuda.Stream'])->StreamContext:r"""Wrapper around the Context-manager StreamContext that selects a given stream. Arguments: stream (Stream): selected stream. This manager is a no-op if it's ``None``. ..Note:: In eager mode stream is of type Stream class while in JIT it is an object of the custom class ``torch.classes.cuda.Stream``. """returnStreamContext(stream)
[docs]defset_stream(stream:Stream):r"""Sets the current stream.This is a wrapper API to set the stream. Usage of this function is discouraged in favor of the ``stream`` context manager. Args: stream (Stream): selected stream. This function is a no-op if this argument is ``None``. """ifstreamisNone:returntorch._C._cuda_setStream(stream._cdata)
[docs]defdevice_count()->int:r"""Returns the number of GPUs available."""ifis_available():returntorch._C._cuda_getDeviceCount()else:return0
[docs]defget_arch_list()->List[str]:r"""Returns list CUDA architectures this library was compiled for."""ifnotis_available():return[]arch_flags=torch._C._cuda_getArchFlags()ifarch_flagsisNone:return[]returnarch_flags.split()
[docs]defget_gencode_flags()->str:r"""Returns NVCC gencode flags this library was compiled with."""arch_list=get_arch_list()iflen(arch_list)==0:return""arch_list_=[arch.split("_")forarchinarch_list]return" ".join([f"-gencode compute=compute_{arch},code={kind}_{arch}"for(kind,arch)inarch_list_])
[docs]defcurrent_device()->int:r"""Returns the index of a currently selected device."""_lazy_init()returntorch._C._cuda_getDevice()
[docs]defsynchronize(device:_device_t=None)->None:r"""Waits for all kernels in all streams on a CUDA device to complete. Args: device (torch.device or int, optional): device for which to synchronize. It uses the current device, given by :func:`~torch.cuda.current_device`, if :attr:`device` is ``None`` (default). """_lazy_init()withtorch.cuda.device(device):returntorch._C._cuda_synchronize()
[docs]defipc_collect():r"""Force collects GPU memory after it has been released by CUDA IPC. .. note:: Checks if any sent CUDA tensors could be cleaned from the memory. Force closes shared memory file used for reference counting if there is no active counters. Useful when the producer process stopped actively sending tensors and want to release unused memory. """_lazy_init()returntorch._C._cuda_ipc_collect()
[docs]defcurrent_stream(device:Optional[_device_t]=None)->Stream:r"""Returns the currently selected :class:`Stream` for a given device. Args: device (torch.device or int, optional): selected device. Returns the currently selected :class:`Stream` for the current device, given by :func:`~torch.cuda.current_device`, if :attr:`device` is ``None`` (default). """_lazy_init()returnStream(_cdata=torch._C._cuda_getCurrentStream(_get_device_index(device,optional=True)))
[docs]defdefault_stream(device:Optional[_device_t]=None)->Stream:r"""Returns the default :class:`Stream` for a given device. Args: device (torch.device or int, optional): selected device. Returns the default :class:`Stream` for the current device, given by :func:`~torch.cuda.current_device`, if :attr:`device` is ``None`` (default). """_lazy_init()returnStream(_cdata=torch._C._cuda_getDefaultStream(_get_device_index(device,optional=True)))
[docs]defcurrent_blas_handle():r"""Returns cublasHandle_t pointer to current cuBLAS handle"""_lazy_init()returntorch._C._cuda_getCurrentBlasHandle()
[docs]defset_sync_debug_mode(debug_mode:Union[int,str])->None:r"""Sets the debug mode for cuda synchronizing operations. Args: debug_mode(str or int): if "default" or 0, don't error or warn on synchronizing operations, if "warn" or 1, warn on synchronizing operations, if "error" or 2, error out synchronizing operations. Warning: This is an experimental feature, and not all synchronizing operations will trigger warning or error. In particular, operations in torch.distributed and torch.sparse namespaces are not covered yet. """_lazy_init()ifisinstance(debug_mode,str):ifdebug_mode=="default":debug_mode=0elifdebug_mode=="warn":debug_mode=1elifdebug_mode=="error":debug_mode=2else:raiseRuntimeError("invalid value of debug_mode, expected one of `default`, `warn`, `error`")torch._C._cuda_set_sync_debug_mode(debug_mode)
[docs]defget_sync_debug_mode()->int:r"""Returns current value of debug mode for cuda synchronizing operations."""_lazy_init()returntorch._C._cuda_get_sync_debug_mode()
from.memoryimport*# noqa: F403from.randomimport*# noqa: F403################################################################################# Define Storage and Tensor classes################################################################################from..storageimport_StorageBaseifnothasattr(torch._C,'CudaDoubleStorageBase'):# Define dummy base classesfortin['Double','Float','Long','Int','Short','Char','Byte','Half','Bool','BFloat16','ComplexDouble','ComplexFloat']:storage_name='Cuda{0}StorageBase'.format(t)tensor_name='Cuda{0}TensorBase'.format(t)torch._C.__dict__[storage_name]=_dummy_type(storage_name)torch._C.__dict__[tensor_name]=_dummy_type(tensor_name)torch._C.__dict__['_CudaStreamBase']=_dummy_type('CudaStreamBase')torch._C.__dict__['_CudaEventBase']=_dummy_type('CudaEventBase')@staticmethod# type: ignore[misc]def_lazy_new(cls,*args,**kwargs):_lazy_init()# We may need to call lazy init again if we are a forked child# del _CudaBase.__new__returnsuper(_CudaBase,cls).__new__(cls,*args,**kwargs)class_CudaBase(object):is_cuda=Trueis_sparse=Falsedeftype(self,*args,**kwargs):# We could use a Protocol here to tell mypy that self has `get_device` method# but it is only available in the typing module on Python >= 3.8# or on typing_extensions module on Python >= 3.6withdevice(self.get_device()):# type: ignore[attr-defined]returnsuper(_CudaBase,self).type(*args,**kwargs)# type: ignore[misc]__new__=_lazy_newclassDoubleStorage(_CudaBase,torch._C.CudaDoubleStorageBase,_StorageBase):passclassFloatStorage(_CudaBase,torch._C.CudaFloatStorageBase,_StorageBase):passclassLongStorage(_CudaBase,torch._C.CudaLongStorageBase,_StorageBase):passclassIntStorage(_CudaBase,torch._C.CudaIntStorageBase,_StorageBase):passclassShortStorage(_CudaBase,torch._C.CudaShortStorageBase,_StorageBase):passclassCharStorage(_CudaBase,torch._C.CudaCharStorageBase,_StorageBase):passclassByteStorage(_CudaBase,torch._C.CudaByteStorageBase,_StorageBase):passclassHalfStorage(_CudaBase,torch._C.CudaHalfStorageBase,_StorageBase):passclassBoolStorage(_CudaBase,torch._C.CudaBoolStorageBase,_StorageBase):passclassBFloat16Storage(_CudaBase,torch._C.CudaBFloat16StorageBase,_StorageBase):passclassComplexDoubleStorage(_CudaBase,torch._C.CudaComplexDoubleStorageBase,_StorageBase):passclassComplexFloatStorage(_CudaBase,torch._C.CudaComplexFloatStorageBase,_StorageBase):passtorch._storage_classes.add(DoubleStorage)torch._storage_classes.add(FloatStorage)torch._storage_classes.add(LongStorage)torch._storage_classes.add(IntStorage)torch._storage_classes.add(ShortStorage)torch._storage_classes.add(CharStorage)torch._storage_classes.add(ByteStorage)torch._storage_classes.add(HalfStorage)torch._storage_classes.add(BoolStorage)torch._storage_classes.add(BFloat16Storage)torch._storage_classes.add(ComplexDoubleStorage)torch._storage_classes.add(ComplexFloatStorage)from.importsparsefrom.importprofilerfrom.importnvtxfrom.importamp
Docs
Access comprehensive developer documentation for PyTorch
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. As the current maintainers of this site, Facebook’s Cookies Policy applies. Learn more, including about available controls: Cookies Policy.