a
    –¥»a¦Æ  ã                   @   sî   d dl m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 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mZmZmZmZ d dlm  m Z  dd„ Z!d	d
„ Z"dd„ Z#G dd„ dejj$ƒZ%dd„ Z&dS )é    )ÚOrderedDictN)ÚNumber)ÚAnyÚDictÚOptionalÚTupleÚUnion)Úupdate_namesÚcheck_serializing_named_tensorÚresolve_ellipsisÚunzip_namedshapeÚsingle_ellipsis_indexÚis_ellipsis)Úhas_torch_functionÚhas_torch_function_unaryÚhas_torch_function_variadicÚhandle_torch_functionÚget_default_nowrap_functionsc                    s*   d}t j}t jˆ |d�‡ ‡fdd„ƒ‰ˆS )N)Ú__name__Ú__doc__)Úassignedc                     sL   t | ƒr tˆ| g| ¢R i |¤ŽS zˆ | i |¤ŽW S  tyF   t Y S 0 d S ©N)r   r   Ú	TypeErrorÚNotImplemented)ÚargsÚkwargs©ÚfÚwrapped© úG/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/_tensor.pyr      s    z4_wrap_type_error_to_not_implemented.<locals>.wrapped)Ú	functoolsÚWRAPPER_ASSIGNMENTSÚwraps)r   Zmethod_assignmentsr   r   r   r    Ú#_wrap_type_error_to_not_implemented   s
    r$   c                 C   s(   |t u r| |Ž S | |Ž  |¡}||_|S r   )ÚTensorÚas_subclassÚ__dict__)ÚfuncÚtyper   ÚdictÚretr   r   r    Ú_rebuild_from_type$   s
    r,   c           	      C   sÂ   |t u r| |Ž S | |Ž  |¡}t|jdt jƒt jur@| |¡ n~t|tƒrvt|ƒdksdtd|› �ƒ‚|d }|d }n|}d }| 	¡ D ]\}}t
|||ƒ q†|r¾| 	¡ D ]\}}t
|||ƒ q¨|S )NÚ__setstate__é   zInvalid serialized state: r   é   )r%   r&   ÚgetattrÚ	__class__r-   Ú
isinstanceÚtupleÚlenÚRuntimeErrorÚitemsÚsetattr)	r(   Únew_typer   Ústater+   Z
dict_stateZslots_stateÚkÚvr   r   r    Ú_rebuild_from_type_v2,   s$    

r<   c                       sÊ  e Zd Zdd„ Zdd„ Zdd„ Zdd„ Zd	d
„ Zdvdd„Zdd„ Z	dd„ Z
e ejjd¡Ze ejjd¡Zdd„ Zdd„ Zdd„ Zdwdd„Zdxdd „Zdyeee ee d"eeeee ee d#œ	d$d%„Zdzeee ee d"eeee ee ed&œ	d'd(„Zd)d*„ Zd+d,„ Zd{‡ fd.d/„	Zd|d0d1„Zd}d2d3„Ze d4d5„ ƒZ!e d6d7„ ƒZ"e"Z#ejj$Z%e ejj&ƒZ'e d8d9„ ƒZ(d:d;„ Z)d<d=„ Z*e d>d?„ ƒZ+e d@dA„ ƒZ,e dBdC„ ƒZ-e dDdE„ ƒZ.e dFdG„ ƒZ/e dHdI„ ƒZ0ejj1Z2ejj3Z4ejj5Z6dJdK„ Z7dLdM„ Z8dNdO„ Z9dPdQ„ Z:dRZ;d~dSdT„Z<dUdV„ Z=dWdX„ Z>e?dYdZ„ ƒZ@‡ fd[d\„ZA‡ fd]d^„ZB‡ fd_d`„ZCdadb„ ZDdcdd„ ZEdedf„ ZF‡ fdgdh„ZGe?didj„ ƒZHeHjIdkdj„ ƒZHeHjJdldj„ ƒZHeKddndo„ƒZLd€dpdq„ZMeNeOjPef drœdsdt„ZQduZ‡  ZRS )�r%   c              
   C   s´  t | ƒrttj| f| |ƒS | js(tdƒ‚t| ƒ|v r@|t| ƒ S t ¡ ��T | j	s^| j
jdv rh|  ¡ }nþ|  ¡  |¡}| j�r|  ¡ tjkr¤|  ¡ |  ¡ |  ¡ f}nF|  ¡ tjtjfv rÖ|  ¡ |  ¡ |  ¡ |  ¡ f}ntd|  ¡ › d�ƒ‚tj ||  ¡ |  ¡ |  ¡ || j| j¡}nR|  g ¡}|  ||  ¡ |  ¡ |  ¡ ¡ |  !¡ �rL| "¡ }|  #¡ �r^| $¡ }| j|_| j%d u�r€| j% |¡|_%||t| ƒ< |W  d   ƒ S 1 �s¦0    Y  d S )NzfOnly Tensors created explicitly by the user (graph leaves) support the deepcopy protocol at the moment)ÚxlaÚmlcÚortÚmetazUnsupported qscheme z in deepcopy)&r   r   r%   Ú__deepcopy__Úis_leafr5   ÚidÚtorchZno_gradÚ	is_sparseÚdevicer)   ÚcloneÚstorageÚis_quantizedÚqschemeÚper_tensor_affineÚq_scaleÚq_zero_pointÚper_channel_affineÚ per_channel_affine_float_qparamsÚq_per_channel_scalesÚq_per_channel_zero_pointsÚq_per_channel_axisÚ_utilsÚ_rebuild_qtensorÚstorage_offsetÚsizeÚstrideÚrequires_gradÚ_backward_hooksZ	new_emptyÚset_Úis_conjZconj_physicalZis_negÚnegÚgrad)ÚselfÚmemoZ
new_tensorZnew_storageÚquantizer_paramsr   r   r    rA   Q   sP    
ýù	


zTensor.__deepcopy__c                    sš   t ˆ ƒtu rˆ  |¡S tˆ ƒr0ttjˆ fˆ |ƒS ˆ  |¡\}}tˆ dd ƒ}|rV|ƒ }n0t ˆ j	¡}|r€ˆ j
‡ fdd„|D ƒf}nˆ j
}t|t ˆ ƒ||ffS )NÚ__getstate__c                    s"   i | ]}t ˆ |ƒr|tˆ |ƒ“qS r   )Úhasattrr0   ©Ú.0Úname©r^   r   r    Ú
<dictcomp>“   ó    z(Tensor.__reduce_ex__.<locals>.<dictcomp>)r)   r%   Ú_reduce_ex_internalr   r   Ú__reduce_ex__r0   ÚcopyregÚ
_slotnamesr1   r'   r<   )r^   Úprotor(   r   Zgetstate_fnr9   Zslots_to_saver   rf   r    rj   ƒ   s    
zTensor.__reduce_ex__c                 C   s¨  t | ƒ tjj | ¡ tƒ }| jjdv rNtjj	|  
¡  ¡ | jt| jƒ| jffS | jjdkr‚| jt|  ¡ ƒ|  ¡ | jf}tjj|fS | j�r$|  ¡ tjkr®tj|  ¡ |  ¡ f}nB|  ¡ tjtjfv rÞtj|  ¡ |  ¡ |  ¡ f}ntd|  ¡ › �ƒ‚|  ¡ |  ¡ t|  ¡ ƒ|  ¡ || j|f}tjj |fS | j!�rr| j"tj#k�rX| j"|  $¡ |  %¡ |  ¡ ff}nt&d| j" ƒ‚tjj'|fS |  ¡ |  ¡ t|  ¡ ƒ|  ¡ | j|f}tjj(|fS d S )N)r=   r?   r>   r@   z3Serialization is not supported for tensors of type z+sparse tensor __reduce_ex__ for layout `%s`))r
   rD   ÚutilsÚhooksZwarn_if_has_hooksr   rF   r)   rS   Z!_rebuild_device_tensor_from_numpyÚcpuÚnumpyÚdtypeÚstrrX   r3   rV   rW   Z_rebuild_meta_tensor_no_storagerI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   r5   rH   rU   rT   rE   ÚlayoutZ
sparse_cooZ_indicesZ_valuesÚNotImplementedErrorZ_rebuild_sparse_tensorZ_rebuild_tensor_v2)r^   rm   Zbackward_hooksZarg_metar`   Zargs_qtensorZargs_sparser   r   r   r    ri   ˜   st    ý
üþý
úþÿÿ
ûzTensor._reduce_ex_internalc                 C   s€   t | ƒrttj| f| |ƒS | js(tdƒ‚t|ƒdkrB| j|Ž  d S t|ƒdkrn|d | _|d |d |d f}|\| _	}| _
d S )Nz/__setstate__ can be only called on leaf Tensorsé   é   r   é   r.   )r   r   r%   r-   rB   r5   r4   rZ   ÚdatarX   rY   )r^   r9   Ú_r   r   r    r-   â   s    

zTensor.__setstate__c                 C   s$   t | ƒrttj| f| ƒS tj | ¡S r   )r   r   r%   Ú__repr__rD   Z_tensor_strÚ_strrf   r   r   r    r{   õ   s    zTensor.__repr__NFc              	   C   s<   t | ƒr"ttj| f| ||||d�S tjj| ||||d� dS )ar
  Computes the gradient of current tensor w.r.t. graph leaves.

        The graph is differentiated using the chain rule. If the tensor is
        non-scalar (i.e. its data has more than one element) and requires
        gradient, the function additionally requires specifying ``gradient``.
        It should be a tensor of matching type and location, that contains
        the gradient of the differentiated function w.r.t. ``self``.

        This function accumulates gradients in the leaves - you might need to zero
        ``.grad`` attributes or set them to ``None`` before calling it.
        See :ref:`Default gradient layouts<default-grad-layouts>`
        for details on the memory layout of accumulated gradients.

        .. note::

            If you run any forward ops, create ``gradient``, and/or call ``backward``
            in a user-specified CUDA stream context, see
            :ref:`Stream semantics of backward passes<bwd-cuda-stream-semantics>`.

        .. note::

            When ``inputs`` are provided and a given input is not a leaf,
            the current implementation will call its grad_fn (though it is not strictly needed to get this gradients).
            It is an implementation detail on which the user should not rely.
            See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details.

        Args:
            gradient (Tensor or None): Gradient w.r.t. the
                tensor. If it is a tensor, it will be automatically converted
                to a Tensor that does not require grad unless ``create_graph`` is True.
                None values can be specified for scalar Tensors or ones that
                don't require grad. If a None value would be acceptable then
                this argument is optional.
            retain_graph (bool, optional): If ``False``, the graph used to compute
                the grads will be freed. Note that in nearly all cases setting
                this option to True is not needed and often can be worked around
                in a much more efficient way. Defaults to the value of
                ``create_graph``.
            create_graph (bool, optional): If ``True``, graph of the derivative will
                be constructed, allowing to compute higher order derivative
                products. Defaults to ``False``.
            inputs (sequence of Tensor): Inputs w.r.t. which the gradient will be
                accumulated into ``.grad``. All other Tensors will be ignored. If not
                provided, the gradient is accumulated into all the leaf Tensors that were
                used to compute the attr::tensors.
        )ÚgradientÚretain_graphÚcreate_graphÚinputs)r€   N)r   r   r%   ÚbackwardrD   Zautograd)r^   r}   r~   r   r€   r   r   r    r�   û   s    /ùzTensor.backwardc                 C   sl   t | ƒrttj| f| |ƒS | js(tdƒ‚| jdu rPtƒ | _| jdurP| j 	| ¡ t
 | j¡}|| j|j< |S )ar  Registers a backward hook.

        The hook will be called every time a gradient with respect to the
        Tensor is computed. The hook should have the following signature::

            hook(grad) -> Tensor or None


        The hook should not modify its argument, but it can optionally return
        a new gradient which will be used in place of :attr:`grad`.

        This function returns a handle with a method ``handle.remove()``
        that removes the hook from the module.

        Example::

            >>> v = torch.tensor([0., 0., 0.], requires_grad=True)
            >>> h = v.register_hook(lambda grad: grad * 2)  # double the gradient
            >>> v.backward(torch.tensor([1., 2., 3.]))
            >>> v.grad

             2
             4
             6
            [torch.FloatTensor of size (3,)]

            >>> h.remove()  # removes the hook
        z@cannot register a hook on a tensor that doesn't require gradientN)r   r   r%   Úregister_hookrX   r5   rY   r   Zgrad_fnZ_register_hook_dictro   ZRemovableHandlerC   )r^   ÚhookÚhandler   r   r    r‚   5  s    

zTensor.register_hookc                 C   s   dd„ }t |dƒƒ‚d S )Nc                 S   s   d  dd„ |  d¡D ƒ¡S )NÚ
c                 S   s   g | ]}|  ¡ ‘qS r   )Ústrip)rd   Úliner   r   r    Ú
<listcomp>a  rh   z2Tensor.reinforce.<locals>.trim.<locals>.<listcomp>)ÚjoinÚsplit)rs   r   r   r    Útrim`  s    zTensor.reinforce.<locals>.trimaÙ  reinforce() was removed.
            Use torch.distributions instead.
            See https://pytorch.org/docs/master/distributions.html

            Instead of:

            probs = policy_network(state)
            action = probs.multinomial()
            next_state, reward = env.step(action)
            action.reinforce(reward)
            action.backward()

            Use:

            probs = policy_network(state)
            # NOTE: categorical is equivalent to what used to be called multinomial
            m = torch.distributions.Categorical(probs)
            action = m.sample()
            next_state, reward = env.step(action)
            loss = -m.log_prob(action) * reward
            loss.backward()
        )r5   )r^   Zrewardr‹   r   r   r    Ú	reinforce_  s    zTensor.reinforcea¿  
    Returns a new Tensor, detached from the current graph.

    The result will never require gradient.

    This method also affects forward mode AD gradients and the result will never
    have forward mode AD gradients.

    .. note::

      Returned Tensor shares the same storage with the original one.
      In-place modifications on either of them will be seen, and may trigger
      errors in correctness checks.
      IMPORTANT NOTE: Previously, in-place size / stride / storage changes
      (such as `resize_` / `resize_as_` / `set_` / `transpose_`) to the returned tensor
      also update the original tensor. Now, these in-place changes will not update the
      original tensor anymore, and will instead trigger an error.
      For sparse tensors:
      In-place indices / values changes (such as `zero_` / `copy_` / `add_`) to the
      returned tensor will not update the original tensor anymore, and will instead
      trigger an error.
    zì
    Detaches the Tensor from the graph that created it, making it a leaf.
    Views cannot be detached in-place.

    This method also affects forward mode AD gradients and the result will never
    have forward mode AD gradients.
    c                 C   s$   t | ƒrttj| f| ƒS |  ¡  ¡ S )zaChecks if tensor is in shared memory.

        This is always ``True`` for CUDA tensors.
        )r   r   r%   Ú	is_sharedrH   rf   r   r   r    r�   ™  s    zTensor.is_sharedc                 C   s(   t | ƒrttj| f| ƒS |  ¡  ¡  | S )zÐMoves the underlying storage to shared memory.

        This is a no-op if the underlying storage is already in shared memory
        and for CUDA tensors. Tensors in shared memory cannot be resized.
        )r   r   r%   Úshare_memory_rH   rf   r   r   r    rŽ   ¢  s    zTensor.share_memory_c                 C   s6   t | ƒrttj| f| ƒS |  ¡ dkr(| S |  d¡S dS )z&Reverses the tensor along dimension 0.r   N)r   r   r%   Ú__reversed__ÚdimZfliprf   r   r   r    r�   ­  s
    zTensor.__reversed__Úfroc              	   C   s6   t | ƒr"ttj| f| ||||d�S tj| ||||d�S )zSee :func:`torch.norm`)Úpr�   Úkeepdimrr   ©rr   )r   r   r%   ÚnormrD   )r^   r’   r�   r“   rr   r   r   r    r•   ¶  s    zTensor.normTc                 C   sP   t | ƒrttj| f| ||d�S tj| || d�\}}}|rD|||fS ||fS dS )zSee :func:`torch.lu`)ÚpivotÚ	get_infos)r–   Zcheck_errorsN)r   r   r%   ÚlurD   Z_lu_with_info)r^   r–   r—   ZLUZpivotsÚinfosr   r   r    r˜   ¼  s    
z	Tensor.luÚreflectzOptional[Tensor])	Ún_fftÚ
hop_lengthÚ
win_lengthÚwindowÚcenterÚpad_modeÚ
normalizedÚonesidedÚreturn_complexc
           
      C   sJ   t | ƒr,ttj| f| |||||||||	d�S tj| |||||||||	d�
S )zËSee :func:`torch.stft`

        .. warning::
          This function changed signature at version 0.4.1. Calling with
          the previous signature may cause error or return incorrect result.
        )rœ   r�   rž   rŸ   r    r¡   r¢   r£   ©r£   )r   r   r%   ÚstftrD   )
r^   r›   rœ   r�   rž   rŸ   r    r¡   r¢   r£   r   r   r    r¥   È  s    

ýÿzTensor.stft)	r›   rœ   r�   rž   rŸ   r¡   r¢   Úlengthr£   c
           
      C   sJ   t | ƒr,ttj| f| |||||||||	d�S tj| |||||||||	d�
S )zSee :func:`torch.istft`)rœ   r�   rž   rŸ   r¡   r¢   r¦   r£   r¤   )r   r   r%   ÚistftrD   )
r^   r›   rœ   r�   rž   rŸ   r¡   r¢   r¦   r£   r   r   r    r§   Û  s    
ýÿzTensor.istftc                 G   sB   t | ƒr ttj| f| g|¢R Ž S t d¡ ddlm} | | |¡S )Nz non-inplace resize is deprecatedr   ©ÚResize)	r   r   r%   ÚresizeÚwarningsÚwarnÚtorch.autograd._functionsr©   Úapply)r^   Úsizesr©   r   r   r    rª   ê  s
    
zTensor.resizec                 C   sD   t | |ƒrttj| |f| |ƒS t d¡ ddlm} | | | 	¡ ¡S )Nz#non-inplace resize_as is deprecatedr   r¨   )
r   r   r%   Ú	resize_asr«   r¬   r­   r©   r®   rV   )r^   Útensorr©   r   r   r    r°   ñ  s
    

zTensor.resize_asr   c                    sž   t | ƒrttj| f| ||d�S t|tƒr:tt| ƒ ||¡S t|tƒrˆzt|ƒ}tt| ƒ ||¡W S  ty„   tt| ƒ ||¡ Y S 0 ntt| ƒ ||¡S dS )z See :func:`torch.split`
        )r�   N)	r   r   r%   rŠ   r2   ÚintÚsuperÚ
ValueErrorZsplit_with_sizes)r^   Z
split_sizer�   ©r1   r   r    rŠ   ø  s    

zTensor.splitc              	   C   s6   t | ƒr"ttj| f| ||||d�S tj| ||||d�S )z[Returns the unique elements of the input tensor.

        See :func:`torch.unique`
        )ÚsortedÚreturn_inverseÚreturn_countsr�   )r   r   r%   ÚuniquerD   )r^   r¶   r·   r¸   r�   r   r   r    r¹     s    þzTensor.uniquec                 C   s2   t | ƒr ttj| f| |||d�S tj| |||d�S )z�Eliminates all but the first element from every consecutive group of equivalent elements.

        See :func:`torch.unique_consecutive`
        )r·   r¸   r�   )r   r   r%   Úunique_consecutiverD   )r^   r·   r¸   r�   r   r   r    rº     s    þzTensor.unique_consecutivec                 C   s,   t | |ƒrttj| |f| |ƒS tj | |¡S r   )r   r   r%   Ú__rsub__Ú_CZ_VariableFunctionsZrsub©r^   Úotherr   r   r    r»      s    
zTensor.__rsub__c                 C   s*   t | |ƒrttj| |f| |ƒS |  ¡ | S r   )r   r   r%   Ú__rdiv__Z
reciprocalr½   r   r   r    r¿   &  s    
zTensor.__rdiv__c                 C   s*   t | |ƒrttj| |f| |ƒS t || ¡S r   )r   r   r%   Ú__rmod__rD   Ú	remainderr½   r   r   r    rÀ   1  s    
zTensor.__rmod__c                 C   s@   t | ƒrttj| f| |ƒS |  ¡ dkr4|  ¡  |¡S t | |¡S )Nr   )r   r   r%   Ú
__format__r�   ÚitemÚobject)r^   Úformat_specr   r   r    rÂ   7  s
    zTensor.__format__c                 C   s"   t | |ƒrttj| |f| |ƒS tS r   )r   r   r%   Ú__ipow__r   r½   r   r   r    rÆ   >  s    
zTensor.__ipow__c                 C   s"   t  || ¡}t j||| jd�|  S )N)rr   rF   )rD   Zresult_typer±   rF   )r^   r¾   rr   r   r   r    Ú__rpow__C  s    zTensor.__rpow__c                 C   s   t jddd� tj| |dd�S )Naj  __floordiv__ is deprecated, and its behavior will change in a future version of pytorch. It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). This results in incorrect rounding for negative values. To keep the current behavior, use torch.div(a, b, rounding_mode='trunc'), or for actual floor division, use torch.div(a, b, rounding_mode='floor').rx   ©Ú
stacklevelÚtrunc©Zrounding_mode©r«   r¬   rD   Údivr½   r   r   r    Ú__floordiv__H  s    üzTensor.__floordiv__c                 C   s   t jddd� tj|| dd�S )Nak  __rfloordiv__ is deprecated, and its behavior will change in a future version of pytorch. It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). This results in incorrect rounding for negative values. To keep the current behavior, use torch.div(a, b, rounding_mode='trunc'), or for actual floor division, use torch.div(a, b, rounding_mode='floor').rx   rÈ   rÊ   rË   rÌ   r½   r   r   r    Ú__rfloordiv__Q  s    üzTensor.__rfloordiv__c                 C   s   t  || ¡S r   )rD   Zbitwise_left_shiftr½   r   r   r    Ú__rlshift__Z  s    zTensor.__rlshift__c                 C   s   t  || ¡S r   )rD   Zbitwise_right_shiftr½   r   r   r    Ú__rrshift__^  s    zTensor.__rrshift__c                 C   s*   t | |ƒrttj| |f| |ƒS t || ¡S r   )r   r   r%   Ú__rmatmul__rD   Úmatmulr½   r   r   r    rÒ   b  s    
zTensor.__rmatmul__c                 C   sT   t | ƒrttj| f| ƒS |  ¡ dkr,tdƒ‚tj ¡ rJt	j
dtjjdd� | jd S )Nr   zlen() of a 0-d tensorzÍUsing len to get tensor shape might cause the trace to be incorrect. Recommended usage would be tensor.shape[0]. Passing a tensor of different shape might lead to errors or silently give incorrect results.r.   ©ÚcategoryrÉ   )r   r   r%   Ú__len__r�   r   rD   r¼   Ú_get_tracing_stater«   r¬   ÚjitÚTracerWarningÚshaperf   r   r   r    rÖ   l  s    
ýzTensor.__len__c                 C   s@   |   ¡ dkrtdƒ‚tj ¡ r2tjdtjjdd� t	|  
d¡ƒS )Nr   ziteration over a 0-d tensorzÐIterating over a tensor might cause the trace to be incorrect. Passing a tensor of different shape won't change the number of iterations executed (and might lead to errors or silently give incorrect results).r.   rÔ   )r�   r   rD   r¼   r×   r«   r¬   rØ   rÙ   ÚiterZunbindrf   r   r   r    Ú__iter__x  s    	
ýzTensor.__iter__c                 C   s    t | ƒrttj| f| ƒS t| ƒS r   )r   r   r%   Ú__hash__rC   rf   r   r   r    rÝ   Š  s    zTensor.__hash__c                 C   sp   t | ƒrttj| f| ƒS | jr(t d¡ t| jƒ}| 	d¡ t
| j ¡ ƒ}|| }| jr^| jrh| 	d¡ t|ƒS )NzCOnly a small subset of methods are supported for quantized tensors.ZvolatileÚ__cuda_array_interface__)r   r   r%   Ú__dir__rI   r«   r¬   Údirr1   ÚremoveÚlistr'   ÚkeysÚis_cudarE   r¶   )r^   Ztensor_methodsÚattrsrã   r   r   r    rß   �  s    



zTensor.__dir__iè  c                 C   sB   t | ƒrttj| f| |d�S |d u r,|  ¡ S |  ¡ j|dd�S d S )Nr”   F)Úcopy)r   r   r%   Ú	__array__rq   Úastype)r^   rr   r   r   r    rç   ¢  s
    zTensor.__array__c                 C   s:   t | ƒrttj| f| |d�S |jtkr0| d¡}t |¡S )N)ÚarrayÚuint8)	r   r   r%   Ú__array_wrap__rr   Úboolrè   rD   Z
from_numpy)r^   ré   r   r   r    rë   ¬  s
    

zTensor.__array_wrap__c                 C   sN   t | ƒrttj| f| |ƒS t|tjtfƒr:|| k ¡  ¡ S t	dt
|ƒ ƒ‚dS )z­Check if `element` is present in tensor

        Args:
            element (Tensor or scalar): element to be checked
                for presence in current tensor"
        zKTensor.__contains__ only supports Tensor or scalar, but you passed in a %s.N)r   r   r%   Ú__contains__r2   rD   r   ÚanyrÃ   r5   r)   )r^   Úelementr   r   r    rí   ´  s    ÿÿzTensor.__contains__c                    s
  t | ƒrttjj| f| ƒS | js0td|  ¡  ƒ‚| jrFtd|  ¡  ƒ‚| j	rTt
dƒ‚tjdtjdtjdtjdtjdtjd	tjd
tjdtjdtjdi
| j }|  ¡  ¡ ‰ t| jƒ}|  ¡ r¾d}nt‡ fdd„|  ¡ D ƒƒ}|  ¡ dkrì|  ¡ nd}|df}t||||dd�S )z�Array view description for cuda tensors.

        See:
        https://numba.pydata.org/numba-doc/latest/cuda/cuda_array_interface.html
        zŠCan't get __cuda_array_interface__ on non-CUDA tensor type: %s If CUDA data is required use tensor.cuda() to copy tensor to device memory.zoCan't get __cuda_array_interface__ on sparse type: %s Use Tensor.to_dense() to convert to a dense tensor first.zœCan't get __cuda_array_interface__ on Variable that requires grad. If gradients aren't required, use var.detach() to get Variable that doesn't require grad.z<c8z<c16z<f2z<f4z<f8z|u1z|i1z<i2z<i4z<i8Nc                 3   s   | ]}|ˆ  V  qd S r   r   )rd   Ús©Úitemsizer   r    Ú	<genexpr>ÿ  rh   z2Tensor.__cuda_array_interface__.<locals>.<genexpr>r   Fr.   )ÚtypestrrÚ   Ústridesry   Úversion) r   r   r%   rÞ   Ú__get__rä   ÚAttributeErrorr)   rE   rX   r5   rD   Z	complex64Z
complex128Úfloat16Úfloat32Úfloat64rê   Zint8Úint16Úint32Úint64rr   rH   Zelement_sizer3   rÚ   Zis_contiguousrW   ZnumelÚdata_ptrr*   )r^   rô   rÚ   rõ   rÿ   ry   r   rñ   r    rÞ   Æ  sN    þÿþÿÿöõ
zTensor.__cuda_array_interface__c                    s>   t | ƒr ttj| f| g|¢R Ž S t|| jdƒ}tt| ƒ |¡S )aÆ  Refines the dimension names of :attr:`self` according to :attr:`names`.

        Refining is a special case of renaming that "lifts" unnamed dimensions.
        A ``None`` dim can be refined to have any name; a named dim can only be
        refined to have the same name.

        Because named tensors can coexist with unnamed tensors, refining names
        gives a nice way to write named-tensor-aware code that works with both
        named and unnamed tensors.

        :attr:`names` may contain up to one Ellipsis (``...``).
        The Ellipsis is expanded greedily; it is expanded in-place to fill
        :attr:`names` to the same length as ``self.dim()`` using names from the
        corresponding indices of ``self.names``.

        Python 2 does not support Ellipsis but one may use a string literal
        instead (``'...'``).

        Args:
            names (iterable of str): The desired names of the output tensor. May
                contain up to one Ellipsis.

        Examples::

            >>> imgs = torch.randn(32, 3, 128, 128)
            >>> named_imgs = imgs.refine_names('N', 'C', 'H', 'W')
            >>> named_imgs.names
            ('N', 'C', 'H', 'W')

            >>> tensor = torch.randn(2, 3, 5, 7, 11)
            >>> tensor = tensor.refine_names('A', ..., 'B', 'C')
            >>> tensor.names
            ('A', None, None, 'B', 'C')

        .. warning::
            The named tensor API is experimental and subject to change.

        Úrefine_names)r   r   r%   r   r   Únamesr³   )r^   r  rµ   r   r    r     s    'zTensor.refine_namesc                    s^   t | ƒr ttj| f| g|¢R Ž S t|dƒ}|du rBtt| ƒ |¡S tt| ƒ dd„ |D ƒ|¡S )að  Permutes the dimensions of the :attr:`self` tensor to match the order
        specified in :attr:`names`, adding size-one dims for any new names.

        All of the dims of :attr:`self` must be named in order to use this method.
        The resulting tensor is a view on the original tensor.

        All dimension names of :attr:`self` must be present in :attr:`names`.
        :attr:`names` may contain additional names that are not in ``self.names``;
        the output tensor has a size-one dimension for each of those new names.

        :attr:`names` may contain up to one Ellipsis (``...``).
        The Ellipsis is expanded to be equal to all dimension names of :attr:`self`
        that are not mentioned in :attr:`names`, in the order that they appear
        in :attr:`self`.

        Python 2 does not support Ellipsis but one may use a string literal
        instead (``'...'``).

        Args:
            names (iterable of str): The desired dimension ordering of the
                output tensor. May contain up to one Ellipsis that is expanded
                to all unmentioned dim names of :attr:`self`.

        Examples::

            >>> tensor = torch.randn(2, 2, 2, 2, 2, 2)
            >>> named_tensor = tensor.refine_names('A', 'B', 'C', 'D', 'E', 'F')

            # Move the F and E dims to the front while keeping the rest in order
            >>> named_tensor.align_to('F', 'E', ...)

        .. warning::
            The named tensor API is experimental and subject to change.

        Úalign_toNc                 S   s   g | ]}t |ƒs|‘qS r   )r   rc   r   r   r    rˆ   [  rh   z#Tensor.align_to.<locals>.<listcomp>)r   r   r%   r  r   r³   )r^   r  Zellipsis_idxrµ   r   r    r  1  s    $

þzTensor.align_toc                    sv   t | ƒrttj| f| ||ƒS |s(tdƒ‚d}t|tƒsVt|ttfƒrbt|d ttfƒrbt	|ƒ\}}t
t| ƒ |||¡S )aõ  Expands the dimension :attr:`dim` of the :attr:`self` tensor over multiple dimensions
        of sizes given by :attr:`sizes`.

        * :attr:`sizes` is the new shape of the unflattened dimension and it can be a `Tuple[int]` as well
          as `torch.Size` if :attr:`self` is a `Tensor`, or `namedshape` (Tuple[(name: str, size: int)])
          if :attr:`self` is a `NamedTensor`. The total number of elements in sizes must match the number
          of elements in the original dim being unflattened.

        Args:
            dim (Union[int, str]): Dimension to unflatten
            sizes (Union[Tuple[int] or torch.Size, Tuple[Tuple[str, int]]]): New shape of the unflattened dimension

        Examples:
            >>> torch.randn(3, 4, 1).unflatten(1, (2, 2)).shape
            torch.Size([3, 2, 2, 1])
            >>> torch.randn(3, 4, 1).unflatten(1, (-1, 2)).shape # the size -1 is inferred from the size of dimension 1
            torch.Size([3, 2, 2, 1])
            >>> torch.randn(2, 4, names=('A', 'B')).unflatten('B', (('B1', 2), ('B2', 2)))
            tensor([[[-1.1772,  0.0180],
                    [ 0.2412,  0.1431]],
                    [[-1.1819, -0.8899],
                    [ 1.5813,  0.2274]]], names=('A', 'B1', 'B2'))
            >>> torch.randn(2, names=('A',)).unflatten('A', (('B1', -1), ('B2', 1)))
            tensor([[-0.8591],
                    [ 0.3100]], names=('B1', 'B2'))

        .. warning::
            The named tensor API is experimental and subject to change.

        z"unflatten: sizes must be non-emptyNr   )r   r   r%   Ú	unflattenr5   r2   r   r3   râ   r   r³   )r^   r�   r¯   r  rµ   r   r    r  ^  s    *zTensor.unflattenc                 O   s6   t | ƒr&ttj| f| g|¢R i |¤ŽS t| ||dd�S )z+In-place version of :meth:`~Tensor.rename`.T©Úinplace)r   r   r%   Úrename_r	   ©r^   r  Z
rename_mapr   r   r    r  ‰  s    zTensor.rename_c                 O   s6   t | ƒr&ttj| f| g|¢R i |¤ŽS t| ||dd�S )am  Renames dimension names of :attr:`self`.

        There are two main usages:

        ``self.rename(**rename_map)`` returns a view on tensor that has dims
        renamed as specified in the mapping :attr:`rename_map`.

        ``self.rename(*names)`` returns a view on tensor, renaming all
        dimensions positionally using :attr:`names`.
        Use ``self.rename(None)`` to drop names on a tensor.

        One cannot specify both positional args :attr:`names` and keyword args
        :attr:`rename_map`.

        Examples::

            >>> imgs = torch.rand(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
            >>> renamed_imgs = imgs.rename(N='batch', C='channels')
            >>> renamed_imgs.names
            ('batch', 'channels', 'H', 'W')

            >>> renamed_imgs = imgs.rename(None)
            >>> renamed_imgs.names
            (None,)

            >>> renamed_imgs = imgs.rename('batch', 'channel', 'height', 'width')
            >>> renamed_imgs.names
            ('batch', 'channel', 'height', 'width')

        .. warning::
            The named tensor API is experimental and subject to change.

        Fr  )r   r   r%   Úrenamer	   r  r   r   r    r  –  s    "zTensor.renamec                 C   s¨   |   ¡ }d}t|ƒdkr"td|ƒ‚| jrŽ|  ¡ }| ¡ d }| ¡ j}tj	|| j
d |jtjkd�}tj|| ¡ d  ¡ | ¡ |j
|j|d�S | jr˜| S |  ¡  ¡ S dS )zô Convert a tensor to compressed row storage format. Only works with 2D tensors.

        Examples::

            >>> dense = torch.randn(5, 5)
            >>> sparse = dense.to_sparse_csr()
            >>> sparse._nnz()
            25

        r   r.   zBOnly 2D tensors can be converted to the CSR format but got shape: )Z	out_int32r/   )rV   rr   rF   N)rV   r4   r5   rE   ZcoalesceÚindicesÚvaluesrF   rD   Z _convert_indices_from_coo_to_csrrÚ   rr   rý   Zsparse_csr_tensorÚ
contiguousZis_sparse_csrZ	to_sparseÚto_sparse_csr)r^   rÚ   Z
fill_valueZcoalesced_selfZrow_indicesrF   Zcrow_indicesr   r   r    r  ¾  s*    

ÿûzTensor.to_sparse_csrc                    sD   t | ƒrttj| f| ||ƒS |r0tt| ƒ |¡S tt| ƒ |¡S d S r   )r   r   r%   Ú_update_namesr³   r  r  )r^   r  r  rµ   r   r    r  ß  s
    zTensor._update_namesc                 C   s    t | ƒrttjj| f| ƒS | jS )a4  
        This attribute is ``None`` by default and becomes a Tensor the first time a call to
        :func:`backward` computes gradients for ``self``.
        The attribute will then contain the gradients computed and future calls to
        :func:`backward` will accumulate (add) gradients into it.
        )r   r   r%   r]   r÷   Ú_gradrf   r   r   r    r]   é  s    zTensor.gradc                 C   s&   t | ƒrttjj| f| |ƒS || _d S r   )r   r   r%   r]   Ú__set__r  )r^   Znew_gradr   r   r    r]   ÷  s    c                 C   s"   t | ƒrttjj| f| ƒS | `d S r   )r   r   r%   r]   Ú
__delete__r  rf   r   r   r    r]   þ  s    r   c                    s”   |du ri }t ‡ fdd„|D ƒƒs&tS t ¡ �R ||i |¤Ž}|tƒ v rZ|W  d  ƒ S t|ˆ ƒW  d  ƒ S W d  ƒ n1 s†0    Y  dS )a  
        This __torch_function__ implementation wraps subclasses such that
        methods called on subclasses return a subclass instance instead of
        a ``torch.Tensor`` instance.

        One corollary to this is that you need coverage for torch.Tensor
        methods if implementing __torch_function__ for subclasses.

        We recommend always calling ``super().__torch_function__`` as the base
        case when doing the above.

        While not mandatory, we recommend making `__torch_function__` a classmethod.
        Nc                 3   s   | ]}t ˆ |ƒV  qd S r   )Ú
issubclass)rd   Út©Úclsr   r    ró     rh   z,Tensor.__torch_function__.<locals>.<genexpr>)Úallr   r¼   ZDisableTorchFunctionr   Ú_convert)r  r(   Útypesr   r   r+   r   r  r    Ú__torch_function__  s    

zTensor.__torch_function__c                 C   sÎ   t | ƒrttj| f| |ƒS | jr(tdƒ‚|  ¡ r8tdƒ‚| jtj	krLtdƒ‚|durjt
|ƒturjtdƒ‚nZ|durÄ|dkrÄ| jj
dkrÄtjj |¡}|tjjkrÄtj ¡ }| tj ¡ ¡ | |¡ t | ¡S )aD  
        Creates a DLpack `capsule https://data-apis.org/array-api/latest/design_topics/data_interchange.html#data-interchange`_
        of the current tensor to be exported to other libraries.

        This function will be called from the `from_dlpack` method
        of the library that will consume the capsule. `from_dlpack` passes the current
        stream to this method as part of the specification.

        Args:
            stream (integer or None): An optional Python integer representing a
            pointer to a CUDA stream. The current stream is synchronized with
            this stream before the capsule is created, and since the capsule
            shares its storage with the tensor this make it safe to access from
            both streams.  If None or -1 is passed then no synchronization is performed.
        z?Can't export tensors that require gradient, use tensor.detach()z/Can't export tensors with the conjugate bit setz9Can't export tensors with layout other than torch.stridedNz"stream must be ``int`` or ``none``éÿÿÿÿÚcuda)r   r   r%   Ú
__dlpack__rX   r5   r[   rt   rD   Zstridedr)   r²   r   rF   r  ZstreamsZExternalStreamZcurrent_streamÚEventÚrecordZ
wait_eventZ	to_dlpack)r^   ÚstreamÚeventr   r   r    r  !  s$    


zTensor.__dlpack__)Úreturnc                 C   sº   ddl m} t| ƒr$ttj| f| ƒS | jjd ur8| jjnd}| jjdkr\t	j
jd ur\|j}nV| jjdkrx|  ¡ rx|j}n:| jjdkrŒ|j}n&| jjdkr |j}ntd | jj¡ƒ‚||fS )Nr   )ÚDLDeviceTyper  rp   z!Unknown device type {} for Dlpack)Ztorch.utils.dlpackr!  r   r   r%   Ú__dlpack_device__rF   Úindexr)   rD   rö   ZhipZkDLROCMÚ	is_pinnedZkDLCPUPinnedZkDLGPUZkDLCPUr´   Úformat)r^   r!  ÚidxZdevice_typer   r   r    r"  L  s    zTensor.__dlpack_device__rD   )NNFN)r‘   NFN)TF)NNNTrš   FNN)NNNTFNNF)r   )TFFN)FFN)N)r   N)N)Sr   Ú
__module__Ú__qualname__rA   rj   ri   r-   r{   r�   r‚   rŒ   r¼   Z_add_docstrÚ_TensorBaseÚdetachZdetach_r�   rŽ   r�   r•   r˜   r²   r   rì   rs   r¥   r§   rª   r°   rŠ   r¹   rº   r$   r»   r¿   Ú__rtruediv__Z__idiv__Ú__itruediv__ÚpowÚ__pow__rÀ   rÂ   rÆ   rÇ   rÎ   rÏ   rÐ   rÑ   rÒ   ZpositiveÚ__pos__r\   Ú__neg__ÚabsÚ__abs__rÖ   rÜ   rÝ   rß   Z__array_priority__rç   rë   rí   ÚpropertyrÞ   r   r  r  r  r  r  r  r]   ÚsetterÚdeleterÚclassmethodr  r  r   ÚenumÚIntEnumr"  Ú__classcell__r   r   rµ   r    r%   P   s¼   2J
:*		

    ý
ý     ü
ü













>,-+(!




+r%   c                    sV   ˆ t u r| S t| t ƒr*t| ˆ ƒs*|  ˆ ¡} t| ttfƒrRt| ƒ‡ fdd„| D ƒƒ} | S )Nc                 3   s   | ]}t |ˆ ƒV  qd S r   )r  )rd   Úrr  r   r    ró   i  rh   z_convert.<locals>.<genexpr>)r%   r2   r&   r3   râ   r)   )r+   r  r   r  r    r  `  s    
r  )'Úcollectionsr   r7  r!   Znumbersr   Útypingr   r   r   r   r   r«   rk   rD   Ztorch._Cr¼   Ztorch._namedtensor_internalsr	   r
   r   r   r   r   Ztorch.overridesr   r   r   r   r   Ztorch.utils.hooksrn   ro   r$   r,   r<   r)  r%   r  r   r   r   r    Ú<module>   s0    $        