U
    E‹Ñhf�  ã                   @   sÐ  U d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlmZ d dl	m
Z
mZmZmZmZmZ d dlmZ d dlZd‡dd„Zdˆdd	„Zd
d„ Ze ¡ Zdd„ Zdd„ Zdd„ Zdd„ Zd‰dd„ZdŠdd„Zg Zed ed< dd„ Z dd„ Z!dd„ Z"d d!„ Z#e#Z$d"d#„ Z%d$d%„ Z&d&d'„ Z'd(d)„ Z(d*d+„ Z)d,d-„ Z*d.d/„ Z+d0d1„ Z,d2d3„ Z-d4d5„ Z.d6d7„ Z/d8d9„ Z0d:d;„ Z1d<d=„ Z2d>d?„ Z3d@dA„ Z4G dBdC„ dCe5ƒZ6G dDdE„ dEƒZ7dFdG„ Z8dHdI„ Z9dJdK„ Z:dLdM„ Z;dNdO„ Z<e=dPœdQdR„Z>d‹e
e?e?e=dSœdTdU„Z@dVdW„ ZAdXdY„ ZBG dZd[„ d[ƒZCd\d]„ ZDe?dPœd^d_„ZEd`da„ ZFe Gdb¡e5dcœddde„ƒZHe5eIdfœdgdh„ZJG didj„ djƒZKe LeM¡ZNedkƒZOG dldm„ dmeeO ƒZPdndodpdqdrdsdsdsdtdududvœZQdwdxdydzd{d|d}d~dd€d�d‚dƒd„d{d…d‚d†œZRdS )Œé    N)Údefaultdict)ÚAnyÚCallableÚDefaultDictÚGenericÚListÚOptional)Ú	ParamSpecFc           	      K   sÚ   t d||ƒ}|dkr&| jd | jj S t|tƒr8t|ƒ}|t| ƒkrH| S | jr¸|js\t	dƒ‚|j 
dd¡}|d |j }tj | ¡ ||¡}|d }tj | ¡ ||¡}||||  ¡ ƒS |jrÆt	dƒ‚||  ¡ ƒ | |¡S )	a©  Returns the type if `dtype` is not provided, else casts this object to
    the specified type.

    If this is already of the correct type, no copy is performed and the
    original object is returned.

    Args:
        dtype (type or string): The desired type
        non_blocking (bool): If ``True``, and the source is in pinned memory
            and destination is on the GPU or vice versa, the copy is performed
            asynchronously with respect to the host. Otherwise, the argument
            has no effect.
        **kwargs: For compatibility, may contain the key ``async`` in place of
            the ``non_blocking`` argument. The ``async`` arg is deprecated.
    ÚtypeNÚ.z)Cannot cast sparse tensor to dense tensorz.sparseÚ z.LongTensorz)Cannot cast dense tensor to sparse tensor)Ú_get_async_or_non_blockingÚ
__module__Ú	__class__Ú__name__Ú
isinstanceÚstrÚ_import_dotted_namer
   Ú	is_sparseÚRuntimeErrorÚreplaceÚtorchÚTensorÚ_valuesÚ_indicesÚsizeÚcopy_)	ÚselfÚdtypeÚnon_blockingÚkwargsZnew_module_nameZnew_values_type_nameZ
new_valuesZnew_indices_type_nameZnew_indices© r!   ú:/tmp/user/2202/pip-unpacked-wheel-bf9o3bgk/torch/_utils.pyÚ_type   s,    
 ÿr#   c              
   C   s  | j |kr| S tt|jdƒ}|dk	s8t|j ¡ › d�ƒ‚|  |¡�À | jr´t|dƒr´t|j| j	j
ƒ}ttj | ¡|jƒ||ƒ}ttj | ¡|jƒ||ƒ}||||  ¡ ƒW  5 Q R £ S | jrÐtd|j ¡ › d�ƒ‚tj|  ¡ |d�}| | |¡ |W  5 Q R £ S W 5 Q R X dS )aª  Returns a copy of this object in device memory.

    If this object is already on the correct device, then no copy is performed
    and the original object is returned.

    Args:
        device (int): The destination device.
        non_blocking (bool): If ``True`` and the source is in pinned memory,
            the copy will be asynchronous with respect to the host. Otherwise,
            the argument has no effect.
    Nz device module is not loadedÚsparsez$sparse storage is not supported for z tensors)Údevice)r%   Úgetattrr   r
   ÚAssertionErrorÚupperr   Úhasattrr$   r   r   r   r   r   r   ZUntypedStorager   )r   r%   r   Údevice_moduleÚnew_typeÚindicesÚvaluesZuntyped_storager!   r!   r"   Ú_to8   s4    
ÿþ ÿ ÿÿþr.   c                 C   sR   |s|S t |ƒdksd|kr@d}t| ¡ ƒ ¡ }t| | |¡ƒ‚t d¡ |d S )zþReturn the non-blocking flag given the function name and kwargs.

    Args:
        function_name (str): the name of the function being used.
        non_blocking (bool): the default value.
        **kwargs (dict): the kwargs passed to the function.
    é   Úasyncz,{}() got an unexpected keyword argument '{}'z)'async' is deprecated; use 'non_blocking')ÚlenÚlistÚkeysÚpopÚ	TypeErrorÚformatÚwarningsÚwarn)Zfunction_namer   r    ÚmessageÚargumentr!   r!   r"   r   ^   s    
r   c                 C   sZ   t tddƒ}|dkr| S t|tƒr.| | | ¡S t|ttjfƒrB|S t|ƒsNt	‚t
dƒ‚dS )z{Return the map_location location.

    Used for rebuild functions where the tensor device is distinct from the storage
    Úmap_locationNzgCallable map_location not supported with _rebuild_wrapper_subclass or _rebuild_device_tensor_from_numpy)r&   Ú_thread_local_stater   ÚdictÚgetr   r   r%   Úcallabler'   r   )r%   r;   r!   r!   r"   Ú_get_restore_locations   s    
ÿr@   c                 C   s(   t jd| j| jjd�}| | j|||¡S )N©r   ©r   r%   )r   Úemptyr   Ú_untyped_storager%   Úset_)ÚstorageÚstorage_offsetr   ÚstrideÚtr!   r!   r"   Ú_rebuild_tensor°   s    rJ   c                 C   s   t | tjƒst‚tj | ¡S ©N)r   r   r   r'   Ú_CZ_get_tensor_metadata©Útensorr!   r!   r"   Úget_tensor_metadata¶   s    rO   c                 C   s0   t |tƒst‚t | tjƒst‚tj | |¡ d S rK   )r   r=   r'   r   r   rL   Z_set_tensor_metadata)rN   Úmetadatar!   r!   r"   Úset_tensor_metadata¾   s    rQ   c                 C   s,   t | |||ƒ}||_|r"t||ƒ ||_|S rK   )rJ   Úrequires_gradrQ   Ú_backward_hooks)rF   rG   r   rH   rR   Úbackward_hooksrP   rN   r!   r!   r"   Ú_rebuild_tensor_v2Å   s    
rU   c           	      C   s@   t jd|| jj|d�}| | j|||¡ |r6t||ƒ ||_|S )NrA   ©r   r%   rR   )r   rC   rD   r%   rE   rQ   rS   )	rF   rG   r   rH   rR   rT   r   rP   rI   r!   r!   r"   Ú_rebuild_tensor_v3Ô   s    
ü
rW   ztorch.TensorÚ_sparse_tensors_to_validatec                  C   sÎ   z¾t D ]´} | jtjkr8t |  ¡ |  ¡ |  ¡ |  	¡ ¡ q| jtj
tjtjtjhkr¨| jtj
tjhkrx|  ¡ |  ¡  }}n|  ¡ |  ¡  }}t |||  ¡ |  ¡ | j¡ qtd| j› d�ƒ‚qW 5 t  ¡  X d S )Nz,_validate_loaded_sparse_tensors for layout `ú`)rX   ÚclearÚlayoutr   Ú
sparse_cooZ _validate_sparse_coo_tensor_argsr   r   r   Úis_coalescedÚ
sparse_csrÚ
sparse_cscÚ
sparse_bsrÚ
sparse_bscZcrow_indicesZcol_indicesZccol_indicesZrow_indicesZ'_validate_sparse_compressed_tensor_argsr-   ÚNotImplementedError)rI   Úcompressed_indicesÚplain_indicesr!   r!   r"   Ú_validate_loaded_sparse_tensorsø   sB       ÿüþþ    ÿÿ
re   c           	      C   s®   | t jkrTt|ƒdkr&|\}}}d}n|\}}}}t j|||d|d�}t |¡ |S | t jt jt jt j	hkrœ|\}}}}t j
||||| dd�}t |¡ |S td| › �ƒ‚dS )zÖ
    Rebuilds a sparse tensor from its sparse storage representation.

    Args:
        layout (str): The sparse storage layout of the tensor.
        data (tuple): The tensor's sparse storage representation.
    é   NF)Úcheck_invariantsr]   )r[   rg   z$rebuilding sparse tensor for layout )r   r\   r1   Zsparse_coo_tensorrX   Úappendr^   r_   r`   ra   Zsparse_compressed_tensorrb   )	r[   Údatar,   r-   r   r]   Úresultrc   rd   r!   r!   r"   Ú_rebuild_sparse_tensor  s@    

    ÿ
üú
rk   c                 C   s   t  | |||¡S rK   )r   Z_nested_view_from_buffer)ÚbufferZsizesÚstridesZstorage_offsetsr!   r!   r"   Ú_rebuild_nested_tensorG  s    rn   c                 C   s&   t |ƒ}t | ¡j||d�}||_|S )NrB   )r@   r   Z
from_numpyÚtorR   )ri   r   r%   rR   rN   r!   r!   r"   Ú!_rebuild_device_tensor_from_numpyK  s    rp   c                 C   s   t j||| d|d�S )NÚmetarV   )r   Zempty_strided)r   r   rH   rR   r!   r!   r"   Ú_rebuild_meta_tensor_no_storageV  s        ÿrr   c              
   C   s$   t |ƒ}tjj| |||||||d�S )N)rm   r   rG   r[   r%   rR   )r@   r   r   Z_make_wrapper_subclass)Úclsr   r   rH   rG   r[   r%   rR   r!   r!   r"   Ú_rebuild_wrapper_subclass\  s    ørt   c                 C   s  |d }|t jkr6|\}}	}
t j||	|
| j| jd�}nº|t jt jfkrâ|\}}}}t|ƒtkrÆt|ƒtkrÆ|t jkržt j	|t j
| jd�}t j	|t j| jd�}n(t j	|t j| jd�}t j	|t j| jd�}t j||||| j| jd�}ntd|› �ƒ‚| | |||¡ ||_||_|S )Nr   )ÚscaleÚ
zero_pointr   r%   rB   )ÚscalesÚzero_pointsÚaxisr   r%   z0Can't deserialize quantized tensor with qscheme )r   Zper_tensor_affineZ_empty_affine_quantizedr   r%   Zper_channel_affineZ per_channel_affine_float_qparamsr
   r2   rN   ÚdoubleÚlongÚfloatZ#_empty_per_channel_affine_quantizedr   rE   rR   rS   )rF   rG   r   rH   Zquantizer_paramsrR   rT   ZqschemeÚ_ru   rv   rN   rw   rx   ry   r!   r!   r"   Ú_rebuild_qtensorn  sN    	

û
  ÿ  ÿú	r~   c                 C   s   t j | |¡}||_|S rK   )r   ÚnnÚ	ParameterrS   )ri   rR   rT   Úparamr!   r!   r"   Ú_rebuild_parameter¡  s    r‚   c                 C   s"   t j | |¡}||_t||ƒ}|S rK   )r   r   r€   rS   Ú_set_obj_state)ri   rR   rT   Ústater�   r!   r!   r"   Ú_rebuild_parameter_with_state«  s    
r…   c                    sL   t ˆ dd ƒ}|r|ƒ }n0t ˆ j¡}|rBˆ j‡ fdd„|D ƒf}nˆ j}|S )NÚ__getstate__c                    s"   i | ]}t ˆ |ƒr|tˆ |ƒ“qS r!   )r)   r&   )Ú.0Úname©Úobjr!   r"   Ú
<dictcomp>Æ  s   
þ z"_get_obj_state.<locals>.<dictcomp>)r&   ÚcopyregÚ
_slotnamesr   Ú__dict__)rŠ   Zgetstate_fnr„   Zslots_to_saver!   r‰   r"   Ú_get_obj_state·  s    
þþ	r�   c                 C   s†   t |tƒr6t|ƒdks$td|› �ƒ‚|d }|d }n|}d }|r`| ¡ D ]\}}t| ||ƒ qJ|r‚| ¡ D ]\}}t| ||ƒ ql| S )Né   zInvalid serialized state: r   r/   )r   Útupler1   r   ÚitemsÚsetattr)rŠ   r„   Z
dict_stateZslots_stateÚkÚvr!   r!   r"   rƒ   Ò  s    

rƒ   c                 C   s6   |   d¡}t|d ƒ}|dd … D ]}t||ƒ}q"|S )Nr   r   r/   )ÚsplitÚ
__import__r&   )rˆ   Ú
componentsrŠ   Ú	componentr!   r!   r"   r   è  s
    
r   c                 C   s   t jj | ¡S )a¢  Flatten dense tensors into a contiguous 1D buffer. Assume tensors are of
    same dense type.

    Since inputs are dense, the resulting tensor will be a concatenated 1D
    buffer. Element-wise operation on this buffer will be equivalent to
    operating individually.

    Args:
        tensors (Iterable[Tensor]): dense tensors to flatten.

    Returns:
        A contiguous 1D buffer containing input tensors.
    ©r   rL   Ú_nnZflatten_dense_tensors)Útensorsr!   r!   r"   Ú_flatten_dense_tensorsð  s    r�   c                 C   s8   t jj dd„ | D ƒ¡}t jj dd„ | D ƒ¡}||fS )ab  Flatten sparse tensors into two contiguous 1D buffers, one of indices and
    one of values. Assume tensors are of same sparse type.

    Args:
        tensors (Iterable[Tensor]): sparse tensors to flatten.

    Returns:
        A tuple of two contiguous 1D buffers, one containing input tensors'
        indices and the other containing the values.
    c                 S   s   g | ]}t j |¡‘qS r!   ©r   r   r   ©r‡   rI   r!   r!   r"   Ú
<listcomp>  s     z+_flatten_sparse_tensors.<locals>.<listcomp>c                 S   s   g | ]}t j |¡‘qS r!   ©r   r   r   rŸ   r!   r!   r"   r      s     rš   )rœ   Úflat_indicesÚflat_valuesr!   r!   r"   Ú_flatten_sparse_tensors  s    ÿÿr¤   c                 C   s   t jj | |¡S )a®  View a flat buffer using the sizes of tensors. Assume that tensors are of
    same dense type, and that flat is given by _flatten_dense_tensors.

    Args:
        flat (Tensor): flattened dense tensors to unflatten.
        tensors (Iterable[Tensor]): dense tensors whose sizes will be used to
          unflatten flat.

    Returns:
        Unflattened dense tensors with sizes same as tensors and values from
        flat.
    )r   rL   r›   Úunflatten_dense_tensors)Úflatrœ   r!   r!   r"   Ú_unflatten_dense_tensors  s    r§   c           
   	   C   sx   | \}}t jj |dd„ |D ƒ¡}t jj |dd„ |D ƒ¡}g }t|||ƒD ]"\}}}	| | ||	| ¡ ¡¡ qLt|ƒS )a  View flat buffer (containing indices and values) using the sizes of
    tensors. Assume that tensors are of same sparse type, and that flat is given
    by _flatten_sparse_tensors.

    Args:
        flat (tuple(Tensor, Tensor)): flattened indices and values of sparse
          tensors to unflatten.
        tensors (Iterable[Tensor]): sparse tensors whose sizes will be used to
          unflatten flat.

    Returns:
        Unflattened sparse tensors with sizes same as tensors and values from
        flat.
    c                 S   s   g | ]}t j |¡‘qS r!   rž   rŸ   r!   r!   r"   r    6  s     z-_unflatten_sparse_tensors.<locals>.<listcomp>c                 S   s   g | ]}t j |¡‘qS r!   r¡   rŸ   r!   r!   r"   r    9  s     )	r   rL   r›   r¥   Úziprh   Únewr   r‘   )
r¦   rœ   r¢   r£   r,   r-   ÚoutputsrI   Úir•   r!   r!   r"   Ú_unflatten_sparse_tensors%  s     ÿ ÿr¬   c                    sL   t tƒ}| D ]}|| ¡   |¡ qdd„ | ¡ D ƒ‰ t‡ fdd„|D ƒƒS )a  Assume that tensors are of same order as ordered_tensors within their
    types, e.g., from _take_tensors. Reorder them to be of same order as
    ordered_tensors.

    Args:
        tensors (Iterable[Tensor]): tensors to be reordered. They should be of
          the same order as ordered_tensors within their own types.
        ordered_tensors (Iterable[Tensor]): tensors whose order will be the
          reference.

    Returns:
        Ordered tuple of tensors with contents from tensors and order of
        ordered_tensors.
    c                 S   s   i | ]\}}|t |ƒ“qS r!   )Úiter)r‡   rI   Zcollr!   r!   r"   r‹   S  s      z'_reorder_tensors_as.<locals>.<dictcomp>c                 3   s   | ]}t ˆ | ¡  ƒV  qd S rK   )Únextr
   )r‡   rN   ©Z
type_dict_r!   r"   Ú	<genexpr>T  s     z&_reorder_tensors_as.<locals>.<genexpr>)r   r2   r
   rh   r’   r‘   )rœ   Zordered_tensorsZ	type_dictrN   r!   r¯   r"   Ú_reorder_tensors_asA  s
    r±   c                 c   sò   t dd„ ƒ}| D ]¸}| ¡ }|jr\tj |¡}tj |¡}| ¡ | ¡  | ¡ | ¡   }n| ¡ | ¡  }|| }|d | |krª|d dkrª|d V  g dg }||< |d  	|¡ |d  |7  < q| 
¡ D ]\}	}
t|	ƒdkrÒ|	V  qÒdS )aÕ  Group tensors into chunks. This generator yields a chunk at each time,
    each containing tensors of same type up to certain byte limit in total size.

    Args:
        tensors (Sequence): A sequence of tensors to be separated into chunks.
        size_limit (int): The limit of each chunk in bytes.

    Yields:
        Blocks of tensors of same type and within size_limit. The yielded
        tensors are only ordered as the original sequence within its types.
    c                   S   s   g dgS )Nr   r!   r!   r!   r!   r"   Ú<lambda>c  ó    z_take_tensors.<locals>.<lambda>r/   r   N)r   r
   r   r   r   r   r   ZnumelZelement_sizerh   r-   r1   )rœ   Z
size_limitZbuf_dictrN   rI   r,   r-   r   Zbuf_and_sizeÚbufr}   r!   r!   r"   Ú_take_tensorsW  s(    ÿÿ
rµ   c                    s   ‡ ‡fdd„}|S )Nc                    s   t ˆ ƒ| _ˆ| jd< | S )NÚreturn)r=   Ú__annotations__)Zfun©r    Úretr!   r"   Údec}  s    

zannotate.<locals>.decr!   )r¹   r    rº   r!   r¸   r"   Úannotate|  s    r»   c              	   C   s‚   t j | ¡}|d krt| ƒ}g }t jjddd��H | dd„ |D ƒ¡ | dd„ | ¡ D ƒ¡ |› dd |¡› d�}W 5 Q R X |S )	Nr   )Ú	thresholdZ	edgeitemsc                 s   s   | ]}t |ƒV  qd S rK   ©Úrepr)r‡   Úar!   r!   r"   r°   Œ  s     zrender_call.<locals>.<genexpr>c                 s   s$   | ]\}}|› d t |ƒ› �V  qdS )ú=Nr½   )r‡   r”   r•   r!   r!   r"   r°   �  s     ú(z, ú))	r   Z	overridesÚresolve_namer   Z_tensor_strZprintoptionsÚextendr’   Újoin)ÚfnÚargsr    Zstr_fnZstr_argsÚrr!   r!   r"   Úrender_call…  s     rÉ   c                   @   s   e Zd ZdZdd„ ZdS )ÚKeyErrorMessagez(str subclass that returns itself in reprc                 C   s   | S rK   r!   ©r   r!   r!   r"   Ú__repr__ž  s    zKeyErrorMessage.__repr__N)r   r   Ú__qualname__Ú__doc__rÌ   r!   r!   r!   r"   rÊ   ›  s   rÊ   c                   @   s"   e Zd ZdZddd„Zdd„ ZdS )	ÚExceptionWrapperz?Wraps an exception plus traceback to communicate across threadsNúin backgroundc                 C   s6   |d krt  ¡ }|d | _d tj|Ž ¡| _|| _d S )Nr   r   )ÚsysÚexc_infoÚexc_typerÅ   Ú	tracebackÚformat_exceptionÚexc_msgÚwhere)r   rÒ   r×   r!   r!   r"   Ú__init__¥  s
    
zExceptionWrapper.__init__c                 C   s‚   d| j j› d| j› d| j› �}| j tkr2t|ƒ}nt| j ddƒrL| j |d�‚z|   |¡}W n tk
rx   t|ƒd‚Y nX |‚dS )z4Reraises the wrapped exception in the current threadzCaught ú z.
Original r9   N)r9   )	rÓ   r   r×   rÖ   ÚKeyErrorrÊ   r&   r5   r   )r   ÚmsgÚ	exceptionr!   r!   r"   Úreraise®  s    

zExceptionWrapper.reraise)NrÐ   )r   r   rÍ   rÎ   rØ   rÝ   r!   r!   r!   r"   rÏ   ¢  s   
	rÏ   c                  C   sh   t j ¡ rdS tt dƒr&t j ¡ r&dS tt dƒr>t j ¡ r>dS t j ¡ } tt | d ƒ}|rd| ¡ rd| S d S ©NÚcudaÚxpuÚmtia)	r   rß   Zis_availabler)   rà   rá   rL   Ú_get_privateuse1_backend_namer&   )Zcustom_backend_nameZcustom_device_modr!   r!   r"   Ú_get_available_device_typeÅ  s    

rã   c                 C   st   t ƒ }|r | ¡ dkr | tjƒS |r:| ¡ dkr:| tjƒS |rT| ¡ dkrT| tjƒS |tj ¡ krp| tt|ƒƒS d S rÞ   )	rã   Úlowerr   rß   rà   rá   rL   râ   r&   )Z
get_memberÚdevice_typer!   r!   r"   Ú_get_device_attrÔ  s    


ræ   c                   C   s   t dd„ ƒS )Nc                 S   s   |   ¡ S rK   )Úcurrent_device©Úmr!   r!   r"   r²   ä  r³   z+_get_current_device_index.<locals>.<lambda>©ræ   r!   r!   r!   r"   Ú_get_current_device_indexâ  s    rë   c                   C   s   t dd„ ƒS )Nc                 S   s   t t|  ¡ ƒƒS rK   )r2   ÚrangeÚdevice_countrè   r!   r!   r"   r²   é  r³   z)_get_all_device_indices.<locals>.<lambda>rê   r!   r!   r!   r"   Ú_get_all_device_indicesç  s    rî   c                 C   s   dd„ | D ƒS )Nc                    s   g | ]‰ t ‡ fd d„ƒ‘qS )c                    s
   |   ˆ ¡S rK   )Zget_device_propertiesrè   ©r«   r!   r"   r²   î  r³   z4_get_devices_properties.<locals>.<listcomp>.<lambda>rê   )r‡   r!   rï   r"   r    î  s     z+_get_devices_properties.<locals>.<listcomp>r!   )Z
device_idsr!   r!   r"   Ú_get_devices_propertiesì  s    rð   ©r¶   c                   C   s   t j ¡ dkrt j ¡ S dS )zÈChecks if there are CUDA devices available and
    returns the device index of the current default CUDA device.
    Returns -1 in case there are no CUDA devices available.
    Arguments: ``None``
    r   éÿÿÿÿ)r   rß   rí   rç   r!   r!   r!   r"   Úget_current_device_indexñ  s    
ró   )r%   ÚoptionalÚ	allow_cpur¶   c                 C   sš   t | tƒrt | ¡} d}t | tjƒrT|s@| jdkr@td| › �ƒ‚| jdkrNdn| j}t | tƒrb| }|dkr–|rˆtj 	¡ r€t
ƒ }q–tƒ }ntd| › �ƒ‚|S )a'  Gets the device index from :attr:`device`, which can be a torch.device
    object, a Python integer, or ``None``.

    If :attr:`device` is a torch.device object, returns the device index if it
    has index. Note that for a device without a specified index,
    i.e., ``torch.device('xxx')``, this will return the current default
    device of that type if :attr:`optional` is ``True``. If :attr:`allow_cpu` is ``True``,
    CPU devices will be accepted and ``-1`` will be returned in this case.

    If :attr:`device` is a Python integer, it is returned as is.

    If :attr:`device` is ``None``, this will return the current default
    device of the supported runtime platform if :attr:`optional` is ``True``.
    i.e., the current default CUDA device will be returned if CUDA runtime is supported.
    NÚcpuz$Expected a non cpu device, but got: rò   zFExpected a torch.device with a specified index or an integer, but got:)r   r   r   r%   r
   Ú
ValueErrorÚindexÚintZjitZis_scriptingró   rë   )r%   rô   rõ   Z
device_idxr!   r!   r"   Ú_get_device_indexü  s$    



ÿrú   c                 C   s$   t | tjjƒs |  ¡ r t | ¡S | S )zÀ
    Returns a real view of a tensor if complex dtype else just the tensor
    need to check if a UninitializedParameter because otherwise checking is_complex is an error for a LazyModule
    )r   r   r   ZUninitializedParameterÚ
is_complexZview_as_realrM   r!   r!   r"   Ú_handle_complex)  s    ÿþürü   c                 C   sl   t | tjƒstdt| ƒ› �ƒ‚| jr4t | ¡jd? S | jrJt | ¡jd? S | tj	krXdS t 
| ¡jd? S dS )z8
    Returns the element size for a dtype, in bytes
    zexpected torch.dtype, but got r�   rf   r/   N)r   r   r   r   r
   rû   ZfinfoÚbitsZis_floating_pointÚboolZiinfo)r   r!   r!   r"   Ú_element_size6  s    
rÿ   c                   @   s    e Zd Zddd„Zddd„ZdS )Ú_ClassPropertyDescriptorNc                 C   s
   || _ d S rK   )Úfget)r   r  Úfsetr!   r!   r"   rØ   I  s    z!_ClassPropertyDescriptor.__init__c                 C   s    |d krt |ƒ}| j ||¡ƒ S rK   )r
   r  Ú__get__)r   ÚinstanceÚownerr!   r!   r"   r  L  s    z _ClassPropertyDescriptor.__get__)N)N)r   r   rÍ   rØ   r  r!   r!   r!   r"   r   H  s   
r   c                 C   s   t | ttfƒst| ƒ} t| ƒS rK   )r   ÚclassmethodÚstaticmethodr   )Úfuncr!   r!   r"   ÚclasspropertyR  s    r	  c                   C   s
   t j ¡ S )zº
    Indicates whether we are tracing/compiling with torch.compile() or torch.export().

    TODO(khabinov): we should deprecate this function and use torch.compiler.is_compiling().
    )r   ÚcompilerÚis_compilingr!   r!   r!   r"   r  X  s    r  c              	   C   s`   ddl m} t| |ƒrRtj tjjj¡}zt 	| j
¡ W 5 |d k	rNtj |¡ X n
t 	| ¡ d S )Nr   )ÚFunctionalTensor)Z#torch._subclasses.functional_tensorr  r   r   rL   Z_unset_dispatch_modeZ_TorchDispatchModeKeyZ
FUNCTIONALZ_set_dispatch_modeÚ_functionalize_syncÚelem)rI   r  Zmaybe_functional_moder!   r!   r"   r  a  s    
ÿr  r�   )rå   c                 C   s.   t t| d ƒ}|d kr*td| › d| › d�ƒ‚|S )NzDevice 'z<' does not have a corresponding module registered as 'torch.z'.)r&   r   r   )rå   r*   r!   r!   r"   Ú_get_device_module  s    ÿr  )rˆ   r¶   c                 C   s*   t dœdd„}t| tf|dƒ|dƒdœƒS )N©Úis_initc                    s   ‡ fdd„}|S )Nc                    s&   ˆ r| j j}n| j}td|› �ƒ‚d S )Nz&Tried to instantiate dummy base class )r   r   r   )rŠ   rÇ   r    Ú
class_namer  r!   r"   Úerr_fn‹  s    
z/_dummy_type.<locals>.get_err_fn.<locals>.err_fnr!   )r  r  r!   r  r"   Ú
get_err_fnŠ  s    z_dummy_type.<locals>.get_err_fnTF)rØ   Ú__new__)rþ   r
   Úobject)rˆ   r  r!   r!   r"   Ú_dummy_type‰  s    
  ÿr  c                   @   s2   e Zd Zdd„ Zdd„ Zdd„ Zedœdd	„Zd
S )Ú_LazySeedTrackerc                 C   s   d | _ d | _g | _d S rK   ©Úmanual_seed_all_cbÚmanual_seed_cbÚ
call_orderrË   r!   r!   r"   rØ   ž  s    z_LazySeedTracker.__init__c                 C   s   ||f| _ | j| j g| _d S rK   r  ©r   ÚcbrÔ   r!   r!   r"   Úqueue_seed_all£  s    
z_LazySeedTracker.queue_seed_allc                 C   s   ||f| _ | j| j g| _d S rK   )r  r  r  r  r!   r!   r"   Ú
queue_seed¨  s    
z_LazySeedTracker.queue_seedrñ   c                 C   s   | j S rK   )r  rË   r!   r!   r"   Ú	get_calls­  s    z_LazySeedTracker.get_callsN)r   r   rÍ   rØ   r  r   r   r!  r!   r!   r!   r"   r  ™  s   r  ÚPc                   @   sH   e Zd Zedœdd„Zeedf ddœdd„Zejej	ddœd	d
„Z
dS )ÚCallbackRegistry)rˆ   c                 C   s   || _ g | _d S rK   )rˆ   Úcallback_list)r   rˆ   r!   r!   r"   rØ   ¶  s    zCallbackRegistry.__init__N)r  r¶   c                 C   s   | j  |¡ d S rK   )r$  rh   )r   r  r!   r!   r"   Úadd_callbackº  s    zCallbackRegistry.add_callback)rÇ   r    r¶   c                 O   sP   | j D ]D}z|||Ž W q tk
rH } zt d| j¡ W 5 d }~X Y qX qd S )Nz6Exception in callback for %s registered with gpu trace)r$  Ú	ExceptionÚloggerrÜ   rˆ   )r   rÇ   r    r  Úer!   r!   r"   Úfire_callbacks½  s    
 ÿzCallbackRegistry.fire_callbacks)r   r   rÍ   r   rØ   r   r"  r%  rÇ   r    r)  r!   r!   r!   r"   r#  µ  s   r#  ÚbuiltinsrŒ   ÚqueueÚreprlibzcollections.abcÚcollectionsÚdbmÚio)Ú__builtin__Úcopy_regÚQueuer¾   Ú_abcollÚUserDictÚUserListÚ
UserStringÚwhichdbÚStringIOÚ	cStringIO)r*  rì   )Ú	functoolsÚreduce)rÑ   Úintern)r*  Úchr)r*  r   )r*  rù   )r*  r¨   )r*  Úmap)r*  Úfilter)Ú	itertoolsÚfilterfalse)r@  Úzip_longest)r-  r4  )r-  r5  )r-  r6  )r*  r&  ))r0  Úxrange)r0  r;  )r0  r<  )r0  Úunichr)r0  Úunicode)r0  r{   )r@  Úizip)r@  Úimap)r@  Úifilter)r@  Úifilterfalse)r@  Úizip_longest)r4  ÚIterableUserDict)r5  r5  )r6  r6  )r0  Ú
basestring)Ú
exceptionsÚStandardError)r4  r4  )NF)F)N)N)FF)SrŒ   r:  ÚloggingrÑ   Ú	threadingrÔ   r7   r-  r   Útypingr   r   r   r   r   r   Ztyping_extensionsr	   r   r#   r.   r   Úlocalr<   r@   rJ   rO   rQ   rU   rW   rX   r·   re   rk   rn   rp   Z_rebuild_xla_tensorrr   rt   r~   r‚   r…   r�   rƒ   r   r�   r¤   r§   r¬   r±   rµ   r»   rÉ   r   rÊ   rÏ   rã   ræ   rë   rî   rð   rù   ró   rþ   rú   rü   rÿ   r   r	  r  r  Ú	lru_cacher  r
   r  r  Ú	getLoggerr   r'  r"  r#  ÚIMPORT_MAPPINGÚNAME_MAPPINGr!   r!   r!   r"   Ú<module>   sÐ     
(
&= ÿ
 ø
%*3
%	#   ÿ  þ-
		
ôî