a
    d'                     @   s   d Z ddlZddlmZ ddlmZ ddlZddlmZ ddlm	Z	 ddl
mZ deeed	d
dZeedddZeedddZeedddZeedddZddddZeedddZdS )zUtilities related to memory.    N)BytesIO)Any)apply_to_collection)Tensor)ModuleF)in_dictto_cpureturnc                 C   s"   t tt ddd}t| t ||dS )a  Detach all tensors in `in_dict`.

    May operate recursively if some of the values in `in_dict` are dictionaries
    which contain instances of `Tensor`. Other types in `in_dict` are
    not affected by this utility function.

    Args:
        in_dict: Dictionary with tensors to detach
        to_cpu: Whether to move tensor to cpu

    Return:
        out_dict: Dictionary with detached tensors
    )tr   r	   c                 S   s   |   } |r|  } | S N)detachcpu)r
   r    r   k/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/pytorch_lightning/utilities/memory.pydetach_and_move)   s    z)recursive_detach.<locals>.detach_and_move)r   )r   boolr   )r   r   r   r   r   r   recursive_detach   s    r   )	exceptionr	   c                 C   s   t | pt| pt| S r   )is_cuda_out_of_memoryis_cudnn_snafuis_out_of_cpu_memoryr   r   r   r   is_oom_error2   s    r   c                 C   s4   t | to2t| jdko2d| jd v o2d| jd v S )N   ZCUDAr   zout of memory
isinstanceRuntimeErrorlenargsr   r   r   r   r   7   s    
r   c                 C   s&   t | to$t| jdko$d| jd v S )Nr   z(cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.r   r   r   r   r   r   r   A   s
    
r   c                 C   s&   t | to$t| jdko$d| jd v S )Nr   z*DefaultCPUAllocator: can't allocate memoryr   r   r   r   r   r   r   K   s
    
r   )r	   c               
   C   sJ   t   ztj  W n. tyD }  zt| s0 W Y d} ~ n
d} ~ 0 0 dS )z'Garbage collection Torch (CUDA) memory.N)gcZcollecttorchZcudaZempty_cacher   r   r   r   r   r   garbage_collection_cudaT   s    r!   )modelr	   c                 C   s(   t  }t|  | | jd }|S )a	  Calculates the size of a Module in megabytes.

    The computation includes everything in the :meth:`~torch.nn.Module.state_dict`,
    i.e., by default the parameters and buffers.

    Returns:
        Number of megabytes in the parameters of the input module.
    g    .A)r   r    saveZ
state_dict	getbuffernbytes)r"   Z
model_sizeZsize_mbr   r   r   get_model_size_mb`   s    	r&   )F)__doc__r   ior   typingr   r    Z#lightning_utilities.core.apply_funcr   r   Ztorch.nnr   r   r   BaseExceptionr   r   r   r   r!   floatr&   r   r   r   r   <module>   s   

	