
    Pg                       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 d dlm	Z	 d dl
mZmZmZmZmZm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 Z!d	 Z"d
 Z# G d dej&                  jH                        Z%d Z&y)    N)OrderedDict)deepcopy)Number)AnyDictListOptionalTupleUnion)check_serializing_named_tensoris_ellipsisresolve_ellipsissingle_ellipsis_indexunzip_namedshapeupdate_names)get_default_nowrap_functionshandle_torch_functionhas_torch_functionhas_torch_function_unaryhas_torch_function_variadicc                 j     t         j                  }t        j                   |       fd       S )N)assignedc                  v    	 t        |       rt        | g| i |S  | i |S # t        $ r	 t        cY S w xY wN)r   r   	TypeErrorNotImplemented)argskwargsfwrappeds     T/var/www/html/suriana-translation/venv/lib/python3.12/site-packages/torch/_tensor.pyr    zN_handle_torch_function_and_wrap_type_error_to_not_implemented.<locals>.wrapped!   sL    	"!$',WdLTLVLLd%f%% 	"!!	"s   & & 88)	functoolsWRAPPER_ASSIGNMENTSwraps)r   r   r    s   ` @r!   =_handle_torch_function_and_wrap_type_error_to_not_implementedr%      s2    ,,H__Q*" +" N    c                 V    |t         u r | | S  | | j                  |      }||_        |S r   )Tensoras_subclass__dict__)functyper   dictrets        r!   _rebuild_from_typer/   /   s3    v~T{
+
!
!$
'CCLJr&   c                     | | }t        |      |ur|j                  |      }t        |j                  dt        j
                        t        j
                  ur|j                  |       |S t        j                  j                  ||      }|S )N__setstate__)	r,   r)   getattr	__class__r(   r1   torch_utils_set_obj_state)r+   new_typer   stater.   s        r!   _rebuild_from_type_v2r9   8   s    
+CCy ooh'
 	~v/B/BC""	# 	 J ll))#u5Jr&   c                       e Zd ZU eed<   d Zd Zd Zd Zd Z	d Z
d Zd	d
dZ	 dTdZd Zd Zd Z ej$                  ej&                  j(                  d      Z ej$                  ej&                  j*                  d      Zd Zd ZdUdZd Z	 	 	 	 dVdeeeef      fdZd Zd Z dUdZ!dUdZ"dWdZ#	 	 	 	 	 	 	 	 dXde$dee$   d ee$   d!d"d#ed$ed%ed&ee   d'ee   fd(Z%	 	 	 	 	 	 	 	 dYde$dee$   d ee$   d!d"d#ed%ed&ee   d)ee$   d'efd*Z&d+ Z'd, Z(dZd-Z)d[d.Z*d\d/Z+e,d0        Z-e,d1        Z.e.Z/ej&                  j`                  Z1 e,ej&                  jd                        Z3 e,ej&                  jh                        Z5e,d2        Z6d3 Z7e,d4        Z8e,d5        Z9e,d6        Z:e,d7        Z;e,d8        Z<e,d9        Z=ej&                  j|                  Z?ej&                  j                  ZAej&                  j                  ZCd: ZDd; ZEd< ZFd= ZGd>ZHd]d?ZId@ ZJdAeKdBefdCZLeMdD        ZNdE ZO fdFZP fdGZQ fdHZRdI ZSdJ ZTdK ZUddLdMeeeVeWj                     f   fdNZY fdOZZe[d^dP       Z\ej                  Z^d]dQZ_dBe`eaj                  e$f   fdRZcdSZ xZdS )_r(   	_is_paramc                     t        |       rt        t        j                  | f|       S g d}|D ]  }| j                  j                  |d         y)aM  Clears any data cached in the tensor's ``__dict__`` that would prevent the tensor
        from being serialized.

        For example, subclasses with custom dispatched sizes / strides cache this info in
        non-serializable PyCapsules within the ``__dict__``, and this must be cleared out for
        serialization to function.

        Any subclass that overrides this MUST call ``super()._clear_non_serializable_cached_data().``
        Additional data cleared within the override must be able to be re-cached transparently
        to avoid breaking subclass functionality.
        )_sym_sizes_capsule_sym_sizes_capsule_len_sym_strides_capsule_sym_strides_capsule_lenN)r   r   r(   #_clear_non_serializable_cached_datar*   pop)selfCACHED_SIZES_STRIDES_KEYSkeys      r!   rA   z*Tensor._clear_non_serializable_cached_dataS   sU     $D)(::TGT 
%
! - 	)CMMc4(	)r&   c                 	   t        |       rt        t        j                  | f| |      S | j                  st        d      t        |       |v r|t        |          S t        j                         5  | j                  s| j                  j                  dv sxt        j                  j                  |       s5| j                  j                  t        j                  j                         k(  s$t        |       t        urE| j                         dk(  r2| j!                         }t        |      t        |       ur|t        d      | j#                         j%                  |      }| j&                  r| j)                         t        j*                  k(  r0| j)                         | j-                         | j/                         f}n| j)                         t        j0                  t        j2                  fv r?| j)                         | j5                         | j7                         | j9                         f}nt        d| j)                          d      t        j:                  j=                  t        j>                  jA                  |jB                  | jD                  d      | jG                         | jI                         | jK                         || jL                  | jN                        }t        |      t        |       urt        d	      | jQ                  g       }t        |      t        |       urt        d
      |jS                  || jG                         | jI                         | jK                                | jU                         r|jW                         }| jY                         r|j[                         }| jL                  r|j]                          | j^                   | j^                  j                  |      |_/        t        |       t        urut        |      t        |       urt        d      ta        jb                  | jd                        }|D ]0  }tg        | |      sti        ||tk        tm        | |      |             2 | jo                          tk        | jp                  |      |_8        ||t        |       <   |cd d d        S # 1 sw Y   y xY w)Na  Only Tensors created explicitly by the user (graph leaves) support the deepcopy protocol at the moment.  If you were attempting to deepcopy a module, this may be because of a torch.nn.utils.weight_norm usage, see https://github.com/pytorch/pytorch/pull/103001)lazyxlamtiampsmaiametaipur   ai  The default implementation of __deepcopy__() for wrapper subclasses only works for subclass types that implement clone() and for which cloning returns another instance of the same subclass. You should either properly implement clone() for your subclass or override __deepcopy__() if it is intended behavior for clone() to return an instance of a different type.zUnsupported qscheme z in deepcopyTwrap_storagedtype	_internalzThe default implementation of __deepcopy__() for quantized tensors expects the tensor returned by torch._utils._rebuild_qtensor() to match the type of the instance being copied. If you encounter this, please open an issue on PyTorch's GitHub.a  The default implementation of __deepcopy__() for non-wrapper subclasses only works for subclass types that implement new_empty() and for which that function returns another instance of the same subclass. You should either properly implement new_empty() for your subclass or override __deepcopy__() if it is intended behavior for new_empty() to return an instance of a different type.zType of deepcopy result does not match the type of the source tensor. If you encounter this, please open an issue on PyTorch's GitHub.)9r   r   r(   __deepcopy__is_leafRuntimeErroridr4   no_grad	is_sparsedevicer,   _C_has_storage_get_privateuse1_backend_namedata_ptrclone_typed_storage	_deepcopy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_axisr5   _rebuild_qtensorstorageTypedStorage_untyped_storagerP   storage_offsetsizestriderequires_grad_backward_hooks	new_emptyset_is_conjconj_physicalis_negnegrequires_grad_gradcopyreg
_slotnamesr3   hasattrsetattrr   r2   rA   r*   )rC   memo
new_tensornew_storagequantizer_paramsslots_to_saveslots          r!   rR   zTensor.__deepcopy__n   s   #D)()<)<tgtTRR||E  d8t4>!]]_ u	 ;;##HI --d3((EHH,R,R,TTJf,A1E!ZZ\

#4:5&*  #113==dC$$ ||~)@)@@ LLN LLN --/,(
 00>>, 
 !LLN 557 ::< 335	,( +24<<>2B,O 
 "'!>!>22)4)E)E"&**&* 3 
 ++-		(**,,"J J'tDz9*H  "&!3JJ'tDz9*?  OO#T%8%8%:DIIK ||~%/%=%=%?
{{}%/^^%5
!!))+yy$"&))"8"8">
Dz'
#4:5&[  !( 2 24>> B) WDtT*
D(74;NPT2UVW
 446"*4==$"?J'DDNku	 u	 u	s   /O*SASS
c                    t         j                  j                  j                  }t         j                  j                  |       }t        t         d      r1t        |       t         j                  j                  j                  u r|st        |       t        u r|s| j                  |      S t        |       rt        t        j                  | f| |      S | j                  |      \  }}| j!                          t"        |t        |       ||ffS )N_subclasses)r4   serialization_serialization_tlsmaterialize_fake_tensorsr5   _get_obj_stater}   r,   r   fake_tensor
FakeTensorr(   _reduce_ex_internalr   r   __reduce_ex__rA   r9   )rC   protor   r8   r+   r   s         r!   r   zTensor.__reduce_ex__   s    22KK 	! ++D1 E=)T
e//;;FFF(4jF"5++E22#D)()=)=weTT--e4
d 	002%d4j$'FGGr&   c                     t        |       rt        t        j                  | f|       S t        j                  j                  d       | j                         S )a|  
        storage() -> torch.TypedStorage

        Returns the underlying :class:`TypedStorage`.

        .. warning::

            :class:`TypedStorage` is deprecated. It will be removed in the future, and
            :class:`UntypedStorage` will be the only storage class. To access the
            :class:`UntypedStorage` directly, use :attr:`Tensor.untyped_storage()`.
           )
stacklevel)r   r   r(   rk   r4   _warn_typed_storage_removalr^   rC   s    r!   rk   zTensor.storage
  sE     $D)($$GG11Q1?""$$r&   c                 f    | j                         }t        j                  || j                  d      S )NTrN   )untyped_storager4   rl   rP   )rC   r   s     r!   r^   zTensor._typed_storage  s.    ..0!!(

d
 	
r&   c                    t        |        ddlm}  ||        t               }t        j
                  j                  j                  }t        j
                  j                  j                  }| j                  j                  dv sTt        j                  j                  |       s| j                  j                  t        j                  j                         k(  rd|rt        d      | j                         }t        j                   j"                  || j$                  t'        | j                        | j(                  ffS | j                  j                  dv r|rt        d      | j$                  t        j*                  k7  r| j                         j-                         n:| j                         j/                  t        j0                        j-                         }t        j                   j2                  || j$                  t'        | j                        | j(                  ffS | j                  j                  dk(  rr|rt5        j6                  d       | j$                  t9        | j;                               | j=                         | j(                  f}t        j                   j>                  |fS | j@                  r|rt        d      | jC                         t        jD                  k(  r0t        jD                  | jG                         | jI                         f}	n| jC                         t        jJ                  t        jL                  fv r?t        jJ                  | jO                         | jQ                         | jS                         f}	nt        d	| jC                                t        jT                  jW                  | jY                         jZ                  | j$                  d
      | j]                         t9        | j;                               | j=                         |	| j(                  |f}
t        j                   j^                  |
fS | j`                  r| jb                  t        jd                  k(  rK| jb                  | jg                         | ji                         | j;                         | jk                         ff}ntm        d| jb                   d      t        j                   jn                  |fS | jb                  t        jp                  t        jr                  t        jt                  t        jv                  hv r| jb                  t        jp                  t        jt                  hv r!| jy                         | j{                         }}n | j}                         | j                         }}| jb                  ||| j                         | j;                         ff}t        j                   jn                  |fS | j                  rg|rt        d      | j                         | j                         | j                         | j                         f}t        j                   j                  |fS t        |       t        j                  ur(t        |       j                  t        j                  j                  urt        | t        j                  j                  j                        sAt        | t        j                  j                  j                        s| j                         dk(  rt        |       | j$                  t9        | j;                               | j=                         | j]                         | jb                  | j                  | j(                  f}t        j                   j                  |fS t        |       t        j                  urt        |       j                  t        j                  j                  urt        | t        j                  j                  j                        r|r|st        |       | j$                  t9        | j;                               | j=                         | j]                         | jb                  | j                  | j(                  f}t        j                   j                  |fS t        jT                  j                         }| j$                  |v r+t        j                   j                  }| j                         }n^t        j                   j                  }t        jT                  jW                  | jY                         jZ                  | j$                  d
      }t        t        d      rAt        | t        j                  j                  j                        r|r| j                  |_U        || j]                         t9        | j;                               | j=                         | j(                  |f}t        |t        jT                  j                        r|| j$                  fz   }t        j                   j                  |       }|r||fz   }||fS )Nr   )warn_if_has_hooks)rH   rK   zTCannot serialize tensors on backends with no storage under skip_data context manager)rI   rL   zQSerializing tensors on the meta device under skip_data context manager is a no-opz`Cannot serialize qtensor under skip_data context manager, file an issue if you need this featurez3Serialization is not supported for tensors of type TrN   z(sparse tensor __reduce_ex__ for layout ``zfCannot serialize nested tensor under skip_data context manager, file an issue if you need this featurer   )Xr   torch.utils.hooksr   r   r4   r   r   	skip_datar   rX   r,   rY   rZ   r[   rT   cpur5   &_rebuild_device_tensor_from_cpu_tensorrP   strrq   bfloat16numpytofloat32!_rebuild_device_tensor_from_numpywarningswarntuplero   rp   _rebuild_meta_tensor_no_storager`   ra   rb   rc   rd   re   rf   rg   rh   ri   rk   rl   r^   rm   rn   rj   rW   layout
sparse_coo_indices_valuesis_coalescedNotImplementedError_rebuild_sparse_tensor
sparse_csr
sparse_csc
sparse_bsr
sparse_bsccrow_indicescol_indicesccol_indicesrow_indicesvalues	is_nested_nested_tensor_size_nested_tensor_strides_nested_tensor_storage_offsets_rebuild_nested_tensorr(   __torch_dispatch__
isinstancer   functional_tensorFunctionalTensorr   r   r\   _rebuild_wrapper_subclass_new_dtypes_rebuild_tensor_v3r   _rebuild_tensor_v2r}   _fake_deviceUntypedStorageget_tensor_metadata)rC   r   r   backward_hooksr   r   
cpu_tensornumpy_tensorarg_metar   args_qtensorargs_sparsecompressed_indicesplain_indicesargs_sparse_compressedargs_nestedarg_wrapper_subclass	v3_dtypesrebuild_funcrk   r   metadatas                         r!   r   zTensor._reduce_ex_internal#  s   &t,7 	$)4''::DD	22KK 	! ;;.%%d+  EHH$J$J$LL"j  JCCTZZT[[)94;M;MN  ;;x' "j 
 ::/ 
  "XXZ]]5==1779  >>tzz3t{{+;T=O=OP  ;;v% g 

diik"""	H LL@@(KK"v  ||~!8!88++LLN%%'$ 
 ((66$  ,,--/224++-	$  #I$,,.IYZ  **!%!4!4!6!G!G**" + 
 ##%diik" ""L LL11<@@^^{{e...KK]]_dllndiik4CTCTCVW
 *>t{{m1M  LL77EE[[	
 
 {{u//1A1ABB%%'$$& %2" %%'$$& %2"
 &!KKMIIK	&" LL779OPP^^"|  ((*++-335K LL77EEJell*T
--U\\5T5TT4!2!2!D!D!U!UV"4):):)F)F)Q)QR1,
 T


diik"##%""	$  LL::<PQQJell*T
--U\\5T5TT4!2!2!>!>!I!IJ"'? T


diik"##%""	$  LL::<PQQ113IzzY&$||>>..0  %||>>--44!%!4!4!6!G!G**" 5  }-tU%6%6%B%B%M%MN'+{{$ ##%diik"""D '5==#?#?@tzzm+||77=Hxk) $''r&   c                 *   t        |       rt        t        j                  | f| |      S | j                  st        d      t        |      dk(  r | j                  |  y t        |      dk(  r|d   | _        |d   |d   |d   f}|\  | _	        }| _
        y )Nz/__setstate__ can be only called on leaf Tensors      r      r   )r   r   r(   r1   rS   rT   lenrt   datarq   rr   )rC   r8   _s      r!   r1   zTensor.__setstate__  s    #D)()<)<tgtUSS ||PQQu:?DIIuZ1_aDI1XuQxq2E 7<3At3r&   Ntensor_contentsc                    t        |       rt        t        j                  | f| |      S t        j
                  j                  | |      S )Nr   )r   r   r(   __repr__r4   _tensor_str_str)rC   r   s     r!   r   zTensor.__repr__2  sD    #D)($$    %%dO%LLr&   Fc           	          t        |       r!t        t        j                  | f| ||||      S t        j
                  j                  | ||||       y)a	  Computes the gradient of current tensor wrt 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 a ``gradient``.
        It should be a tensor of matching type and shape, that represents
        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, optional): The gradient of the function
                being differentiated w.r.t. ``self``.
                This argument can be omitted if ``self`` is a scalar.
            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, optional): 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(   backwardr4   autograd)rC   r   r   r   r   s        r!   r   zTensor.backward:  sY    \ $D)(!))  	(L,v 	  	
r&   c                 j   t        |       rt        t        j                  | f| |      S | j                  st        d      | j                  6t               | _        | j                  | j                  j                  |        ddl
m}  || j                        }|| j                  |j                  <   |S )a3  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.

        .. note::
            See :ref:`backward-hooks-execution` for more information on how when this hook
            is executed, and how its execution is ordered relative to other hooks.

        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
        @cannot register a hook on a tensor that doesn't require gradientr   RemovableHandle)r   r   r(   register_hookrq   rT   rr   r   grad_fn_register_hook_dictr   r   rU   rC   hookr   handles       r!   r   zTensor.register_hookv  s    B $D)()=)=wdSS!!R  '#.=D ||'0065 !5!56*.VYY'r&   c                 J   t        |       rt        t        j                  | f| |      S | j                  st        d      | j                  t        d      | j                  t               | _        ddl	m
}  || j                        }|| j                  |j                  <   |S )a  Registers a backward hook that runs after grad accumulation.

        The hook will be called after all gradients for a tensor have been accumulated,
        meaning that the .grad field has been updated on that tensor. The post
        accumulate grad hook is ONLY applicable for leaf tensors (tensors without a
        .grad_fn field). Registering this hook on a non-leaf tensor will error!

        The hook should have the following signature::

            hook(param: Tensor) -> None

        Note that, unlike other autograd hooks, this hook operates on the tensor
        that requires grad and not the grad itself. The hook can in-place modify
        and access its Tensor argument, including its .grad field.

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

        .. note::
            See :ref:`backward-hooks-execution` for more information on how when this hook
            is executed, and how its execution is ordered relative to other hooks. Since
            this hook runs during the backward pass, it will run in no_grad mode (unless
            create_graph is True). You can use torch.enable_grad() to re-enable autograd
            within the hook if you need it.

        Example::

            >>> v = torch.tensor([0., 0., 0.], requires_grad=True)
            >>> lr = 0.01
            >>> # simulate a simple SGD update
            >>> h = v.register_post_accumulate_grad_hook(lambda p: p.add_(p.grad, alpha=-lr))
            >>> v.backward(torch.tensor([1., 2., 3.]))
            >>> v
            tensor([-0.0100, -0.0200, -0.0300], requires_grad=True)

            >>> h.remove()  # removes the hook
        r   zCpost accumulate grad hooks cannot be registered on non-leaf tensorsr   r   )r   r   r(   "register_post_accumulate_grad_hookrq   rT   r   _post_accumulate_grad_hooksr   r   r   rU   r   s       r!   r   z)Tensor.register_post_accumulate_grad_hook  s    L $D)(99D7D$  !!R  <<#U  ++3?J}D,5 !A!AB6:((3r&   c                 *    d }t         |d            )Nc                     dj                  | j                  d      D cg c]  }|j                          c}      S c c}w )N
)joinsplitstrip)r   lines     r!   trimzTensor.reinforce.<locals>.trim  s-    99syyGtdjjlGHHGs   =a  reinforce() was removed.
            Use torch.distributions instead.
            See https://pytorch.org/docs/main/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()
        )rT   )rC   rewardr   s      r!   	reinforcezTensor.reinforce  s$    	I 
 	
r&   a  
    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.
    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                     t        |       rt        t        j                  | f|       S | j	                         j                         S )zaChecks if tensor is in shared memory.

        This is always ``True`` for CUDA tensors.
        )r   r   r(   	is_sharedr^   
_is_sharedr   s    r!   r  zTensor.is_shared  s;    
 $D)()9)9D7DII""$//11r&   c                     t        |       rt        t        j                  | f|       S | j	                         j                          | S )a  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.

        See :meth:`torch.UntypedStorage.share_memory_` for more details.
        )r   r   r(   share_memory_r^   _share_memory_r   s    r!   r  zTensor.share_memory_(  s=     $D)()=)=wMM,,.r&   c                     t        | |      r t        t        j                  | |f| ||      S |r|j	                         S | j                  |      j	                         S )a  Defines how to transform ``other`` when loading it into ``self`` in :meth:`~nn.Module.load_state_dict`.

        Used when :func:`~torch.__future__.get_swap_module_params_on_conversion` is ``True``.

        It is expected that ``self`` is a parameter or buffer in an ``nn.Module`` and ``other`` is the
        value in the state dictionary with the corresponding key, this method defines
        how ``other`` is remapped before being swapped with ``self`` via
        :func:`~torch.utils.swap_tensors` in :meth:`~nn.Module.load_state_dict`.

        .. note::
            This method should always return a new object that is not ``self`` or ``other``.
            For example, the default implementation returns ``self.copy_(other).detach()``
            if ``assign`` is ``False`` or ``other.detach()`` if ``assign`` is ``True``.

        Args:
            other (Tensor): value in state dict with key corresponding to ``self``
            assign (bool): the assign argument passed to :meth:`nn.Module.load_state_dict`

        )assign)r   r   r(   module_loaddetachcopy_)rC   otherr  s      r!   r	  zTensor.module_load5  sY    ( 'tU3(""T5M4v  <<>!::e$++--r&   c                     t        |       rt        t        j                  | f|       S | j	                         dk(  r| S | j                  d      S )z&Reverses the tensor along dimension 0.r   )r   r   r(   __reversed__dimflipr   s    r!   r  zTensor.__reversed__S  sA    #D)()<)<tgtLL88:?K99Q<r&   pc           	          t        |       r!t        t        j                  | f| ||||      S t	        j                  | ||||      S )zSee :func:`torch.norm`)r  r  keepdimrP   rP   )r   r   r(   normr4   )rC   r  r  r  rP   s        r!   r  zTensor.norm\  sH     $D)(dWdaS'QV  zz$3u==r&   c                      ddl m}  || |      S )Nr   )solve)torch._linalg_utilsr  )rC   r  r  s      r!   r  zTensor.solvej      -T5!!r&   c                      ddl m}  || |      S )Nr   )lstsq)r  r  )rC   r  r  s      r!   r  zTensor.lstsqo  r  r&   c                 "    ddl m}  || |      S )Nr   )eigeigenvectors)r  r  )rC   r  r  s      r!   r  z
Tensor.eigt  s    +4l33r&   c                 "    ddl m}  || |      S )Nr   )_symeigr  )r  r!  )rC   r  r!  s      r!   symeigzTensor.symeigy  s    /t,77r&   c                     t        |       rt        t        j                  | f| ||      S t	        j
                  | ||       \  }}}|r|||fS ||fS )zSee :func:`torch.lu`)pivot	get_infos)r$  check_errors)r   r   r(   lur4   _lu_with_info)rC   r$  r%  LUpivotsinfoss         r!   r'  z	Tensor.lu~  sh     $D)(		D7D  "//]
FE vu$$v:r&   n_fft
hop_length
win_lengthwindowzOptional[Tensor]centerpad_mode
normalizedonesidedreturn_complexc
                     t        |       r&t        t        j                  | f| |||||||||	      S t	        j                  | |||||||||	
      S )zSee :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/  r0  r1  r2  r3  r4  r4  )r   r   r(   stftr4   )
rC   r,  r-  r.  r/  r0  r1  r2  r3  r4  s
             r!   r7  zTensor.stft  st    $ $D)(%%!%!-  zz)
 	
r&   lengthc
                     t        |       r&t        t        j                  | f| |||||||||	      S t	        j                  | |||||||||	
      S )zSee :func:`torch.istft`)r-  r.  r/  r0  r2  r3  r8  r4  r6  )r   r   r(   istftr4   )
rC   r,  r-  r.  r/  r0  r2  r3  r8  r4  s
             r!   r:  zTensor.istft  st     $D)(%%%!-  {{)
 	
r&   c                     t        |       rt        t        j                  | f| g| S t	        j
                  d       ddlm} |j                  | |      S )Nz non-inplace resize is deprecatedr   Resize)	r   r   r(   resizer   r   torch.autograd._functionsr=  apply)rC   sizesr=  s      r!   r>  zTensor.resize  sE    #D)(NNN894||D%((r&   c                     t        | |      rt        t        j                  | |f| |      S t	        j
                  d       ddlm} |j                  | |j                               S )Nz#non-inplace resize_as is deprecatedr   r<  )
r   r   r(   	resize_asr   r   r?  r=  r@  ro   )rC   tensorr=  s      r!   rC  zTensor.resize_as  sO    &tV4()9)9D&>4QWXX;<4||D&++-00r&   c                 p   t        |       rt        t        j                  | f| ||      S t	        |t              r	 t        |      }t	        |t
        t        j                  f      r!t        j                  j                  | ||      S t        j                  j                  | ||      S # t        $ r Y mw xY w)zSee :func:`torch.split`)r  )r   r   r(   r   r   int
ValueErrorr4   SymInt_VFsplit_with_sizes)rC   
split_sizer  s      r!   r   zTensor.split  s    #D)(tgtZS  j&) _
 j3"5699??4S9999--dJDD  s   B) )	B54B5c           	          t        |       r!t        t        j                  | f| ||||      S t	        j                  | ||||      S )z[Returns the unique elements of the input tensor.

        See :func:`torch.unique`
        )sortedreturn_inversereturn_countsr  )r   r   r(   uniquer4   )rC   rM  rN  rO  r  s        r!   rP  zTensor.unique  sV    
 $D)(-+  ||)'
 	
r&   c                     t        |       r t        t        j                  | f| |||      S t	        j                  | |||      S )zEliminates all but the first element from every consecutive group of equivalent elements.

        See :func:`torch.unique_consecutive`
        )rN  rO  r  )r   r   r(   unique_consecutiver4   )rC   rN  rO  r  s       r!   rR  zTensor.unique_consecutive  sR    
 $D)())-+  ''}RU
 	
r&   c                 B    t         j                  j                  | |      S r   )rY   _VariableFunctionsrsubrC   r  s     r!   __rsub__zTensor.__rsub__/  s    $$))$66r&   c                 (    | j                         |z  S r   )
reciprocalrV  s     r!   __rdiv__zTensor.__rdiv__3  s     5((r&   c                 .    t        j                  ||       S r   )r4   	remainderrV  s     r!   __rmod__zTensor.__rmod__A  s    ud++r&   c                    t        |       rt        t        j                  | f| |      S | j	                         dk(  r<| j
                  s0t        |       t        u r| j                         j                  |      S t        j                  | |      S )Nr   )	r   r   r(   
__format__r  is_metar,   itemobject)rC   format_specs     r!   r_  zTensor.__format__E  sk    #D)():):TGT;WW88:?4<<DJ&4H99;))+66  {33r&   c                 .    t        j                  ||       S r   )r4   powrV  s     r!   __rpow__zTensor.__rpow__L  s    yy%%r&   c                 .    t        j                  | |      S r   r4   floor_dividerV  s     r!   __floordiv__zTensor.__floordiv__P  s    !!$..r&   c                 .    t        j                  ||       S r   rh  rV  s     r!   __rfloordiv__zTensor.__rfloordiv__T  s    !!%..r&   c                 .    t        j                  ||       S r   )r4   bitwise_left_shiftrV  s     r!   __rlshift__zTensor.__rlshift__X  s    ''t44r&   c                 .    t        j                  ||       S r   )r4   bitwise_right_shiftrV  s     r!   __rrshift__zTensor.__rrshift__\  s    ((55r&   c                 .    t        j                  ||       S r   )r4   matmulrV  s     r!   __rmatmul__zTensor.__rmatmul__`  s    ||E4((r&   c                 F   t        |       rt        t        j                  | f|       S | j	                         dk(  rt        d      t        j                  j                         r0t        j                  dt        j                  j                  d       | j                  d   S )Nr   zlen() of a 0-d tensorzUsing 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   r4   rY   _get_tracing_stater   r   jitTracerWarningshaper   s    r!   ry  zTensor.__len__h  s{    #D)($$GG88:?34488&&(MM% 00 zz!}r&   c                    | j                         dk(  rt        d      t        j                  j	                         r0t        j                  dt        j                  j                  d       t        | j                  d            S )Nr   ziteration over a 0-d tensorzIterating 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   rw  )r  r   r4   rY   rz  r   r   r{  r|  iterunbindr   s    r!   __iter__zTensor.__iter__x  se     88:?9::88&&(MM& 00 DKKN##r&   c                     t        |       S r   )rU   r   s    r!   __hash__zTensor.__hash__  s    
 $xr&   c                 T   t        |       rt        t        j                  | f|       S t	        | j
                        }|j                  d       t        | j                  j                               }||z   }| j                  r| j                  r|j                  d       t        |      S )Nvolatile__cuda_array_interface__)r   r   r(   __dir__dirr3   removelistr*   keysis_cudarW   rM  )rC   tensor_methodsattrsr  s       r!   r  zTensor.__dir__  s    #D)($$GGT^^,j)T]]'')*% KK23d|r&   i  c                     t        |       rt        t        j                  | f| |      S || j	                         S | j	                         j                  |d      S )Nr  F)copy)r   r   r(   	__array__r   astype)rC   rP   s     r!   r  zTensor.__array__  sQ    #D)()9)9D7DPUVV=::<::<&&u5&99r&   c                     t        |       rt        t        j                  | f| |      S |j                  t
        k(  r|j                  d      }t        j                  |      S )N)arrayuint8)	r   r   r(   __array_wrap__rP   boolr  r4   
from_numpy)rC   r  s     r!   r  zTensor.__array_wrap__  sU    #D)(%%wE  ;;$LL)E&&r&   elementreturnc                p   t        |       rt        t        j                  | f| |      S t	        |t
        j                  t        t
        j                  t
        j                  t
        j                  f      r*t        || k(  j                         j                               S t        dt        |       d      )zCheck if `element` is present in tensor

        Args:
            element (Tensor or scalar): element to be checked
                for presence in current tensor"
        zHTensor.__contains__ only supports Tensor or scalar, but you passed in a .)r   r   r(   __contains__r   r4   r   rH  SymFloatSymBoolr  anyra  rT   r,   )rC   r  s     r!   r  zTensor.__contains__  s     $D)()<)<tgtWUUellFELL%..%--X
 D--/44677VW[\cWdVeefg
 	
r&   c                 \   t        |       r&t        t        j                  j                  | f|       S | j
                  st        d| j                          d      | j                  rt        d| j                          d      | j                  rt        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t        j,                  dt        j.                  dt        j0                  dt        j2                  dt        j4                  di| j6                     }| j9                         t;        | j<                        }| j?                         rd}n"t;        fd| jA                         D              }| jC                         dkD  r| jE                         nd}|df}tG        ||||d      S )zArray 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: zL If CUDA data is required use tensor.cuda() to copy tensor to device memory.z3Can't get __cuda_array_interface__ on sparse type: z: Use Tensor.to_dense() to convert to a dense tensor first.zCan'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<u2z<i2z<u4z<i4z<u8z<i8z|b1Nc              3   (   K   | ]	  }|z    y wr    ).0sitemsizes     r!   	<genexpr>z2Tensor.__cuda_array_interface__.<locals>.<genexpr>  s     @QAL@s   r   Fr   )typestrr}  stridesr   version)$r   r   r(   r  __get__r  AttributeErrorr,   rW   rq   rT   r4   	complex64
complex128r   float16r   float64r  int8uint16int16uint32int32uint64int64r  rP   element_sizer   r}  is_contiguousrp   numelr\   r-   )rC   r  r}  r  r\   r   r  s         @r!   r  zTensor.__cuda_array_interface__  s    $D)(//77  || Ntyy{m \^ ^ 
 >> Ediik] SL L  l  OOUfNNEMM5MM5MM5KKJJLL%KKLL%KKLL%KKJJ
  **!$ $$&djj! G@$++-@@G&*jjlQ&64==?A% G5'VWXXr&   c                     t        |       rt        t        j                  | f|       S t        j
                  j                          | j                         j                         S )zUstorage_type() -> type

        Returns the type of the underlying storage.

        )	r   r   r(   storage_typer4   rk   r   r^   _get_legacy_storage_classr   s    r!   r  zTensor.storage_type  sK     $D)()<)<tgtLL113""$>>@@r&   c                     t        |       rt        t        j                  | f| g| S t	        || j
                  d      }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   namessuper)rC   r  r3   s     r!   r  zTensor.refine_names   sL    N $D)()<)<tgtTeTT 

NCw#E**r&   c                     t        |       rt        t        j                  | f| g| S t	        |d      }|t
        |   |      S t
        |   |D cg c]  }t        |      r| c}|      S c c}w )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_to)r   r   r(   r  r   r  r   )rC   r  ellipsis_idxnamer3   s       r!   r  zTensor.align_toL  sv    H $D)(4'4P%PP,UJ?7#E**w#=d;t+<T=|
 	
=s   A1%A1c                 P   t        |       rt        t        j                  | f| ||      S |st	        d      d}t        |t              s/t        |t        t        f      r8t        |d   t        t        f      rt        |      \  }}t        |   |||      S t        |   ||      S )zX
        unflatten(dim, sizes) -> Tensor

        See :func:`torch.unflatten`.

        z"unflatten: sizes must be non-emptyNr   )r   r   r(   	unflattenrT   r   r   r   r  r   r  )rC   r  rA  r  r3   s       r!   r  zTensor.unflatteny  s     $D)()9)9D7D#uUUCDDe[)uudm,E!Hudm1T+E2LE57$S%777$S%00r&   c                 v    t        |       r t        t        j                  | f| g|i |S t	        | ||d      S )z+In-place version of :meth:`~Tensor.rename`.Tinplace)r   r   r(   rename_r   rC   r  
rename_maps      r!   r  zTensor.rename_  sI     $D)(059C  D%TBBr&   c                 v    t        |       r t        t        j                  | f| g|i |S t	        | ||d      S )a~  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, None, None, 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  s      r!   r  zTensor.rename  sJ    D $D)(w/48B 
 D%UCCr&   c                 "    | j                         S )zConvert a tensor to :ref:`coordinate format <sparse-coo-docs>`.

        Examples::

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

        )	to_sparser   s    r!   to_sparse_coozTensor.to_sparse_coo  s     ~~r&   )ambiguity_checkr  c                   t        |       rt        t        j                  | f|       S t	        |t
              sGt	        |t              st        d      |D ]'  }t	        |t        j                        rt        d       d }d }t	        |t              r|ng }t	        |t
              r|nd}|r ||       r || |      rt        d      ddlm} t        |j                  |             S )a  
        dim_order(ambiguity_check=False) -> tuple

        Returns the uniquely determined tuple of int describing the dim order or
        physical layout of :attr:`self`.

        The dim order represents how dimensions are laid out in memory,
        starting from the outermost to the innermost dimension.

        Note that the dim order may not always be uniquely determined.
        If `ambiguity_check` is True, this function raises a RuntimeError when the dim order cannot be uniquely determined;
        If `ambiguity_check` is a list of memory formats, this function raises a RuntimeError when tensor can not be interpreted
        into exactly one of the given memory formats, or it cannot be uniquely determined.
        If `ambiguity_check` is False, it will return one of legal dim order(s) without checking its uniqueness.
        Otherwise, it will raise TypeError.

        Args:
            ambiguity_check (bool or List[torch.memory_format]): The check method for ambiguity of dim order.

            >>> torch.empty((2, 3, 5, 7)).dim_order()
            (0, 1, 2, 3)
            >>> torch.empty((2, 3, 5, 7)).transpose(1, 2).dim_order()
            (0, 2, 1, 3)
            >>> torch.empty((2, 3, 5, 7), memory_format=torch.channels_last).dim_order()
            (0, 2, 3, 1)
            >>> torch.empty((1, 2, 3, 4)).dim_order()
            (0, 1, 2, 3)
            >>> try:
            ...     torch.empty((1, 2, 3, 4)).dim_order(ambiguity_check=True)
            ... except RuntimeError as e:
            ...     print(e)
            The tensor does not have unique dim order, or cannot map to exact one of the given memory formats.
            >>> torch.empty((1, 2, 3, 4)).dim_order(
            ...     ambiguity_check=[torch.contiguous_format, torch.channels_last]
            ... )  # It can be mapped to contiguous format
            (0, 1, 2, 3)
            >>> try:
            ...     torch.empty((1, 2, 3, 4)).dim_order(ambiguity_check="ILLEGAL")
            ... except TypeError as e:
            ...     print(e)
            The ambiguity_check argument must be a bool or a list of memory formats.
        .. warning::
            The dim_order tensor API is experimental and subject to change.
        zHThe ambiguity_check argument must be a bool or a list of memory formats.c                 N    d}|D ]  }| j                  |      s|dz  } |dk7  S )z
            Returns True if the tensor cannot be uniquely mapped to any of the given memory formats, False otherwise.
            r   )memory_format   )r  )rD  valid_memory_formats
n_legalityr  s       r!   invalid_unique_memory_formatz6Tensor.dim_order.<locals>.invalid_unique_memory_format  s>    
 J!5 $''m'D!OJ$ ?"r&   c           	          | j                         }| j                         }t        d t        ||dd       D              }t        d |D              }|xs |S )aG  
            Returns True if there're multiple legal dim orders for given tensor, False otherwise.

            The tensor is considered to have multiple legal dim orders if either of the following conditions is met:

            * Singleton Dimensions: There's at least one singleteon dimension in the tensor.
              Since their size is 1, they don't affect the memory offset (stride * index
              is zero because index is always zero). Therefore, they can be placed anywhere
              in the dimension order without changing how data is accessed.
            * Same strides: Strides reflect how the tensor is stored in memory.
              If any two dimensions have the same stride, swapping these dimensions won't
              change how data is accessed, leading to multiple correct dimension orders.
            c              3   ,   K   | ]  \  }}||k(    y wr   r  )r  earlierlaters      r!   r  zCTensor.dim_order.<locals>.has_multiple_dim_order.<locals>.<genexpr>3  s      (%3We5 (s   r  Nc              3   &   K   | ]	  }|d k(    yw)r  Nr  )r  ro   s     r!   r  zCTensor.dim_order.<locals>.has_multiple_dim_order.<locals>.<genexpr>8  s     $A4TQY$As   )ro   rp   r  zip)rD  rA  r  has_duplicate_strideshas_singleton_dimss        r!   has_multiple_dim_orderz0Tensor.dim_order.<locals>.has_multiple_dim_order   s`     KKMEmmoG %( (7:7GABK7P( %!
 "%$A5$A!A(>,>>r&   TzbThe tensor does not have unique dim order, or cannot map to exact one of the given memory formats.r   N)r   r   r(   	dim_orderr   r  r  r   r4   r  rT   torch._prims_common_prims_commonr   3compute_elementwise_output_logical_to_physical_perm)rC   r  r  r  r  r  check_multiple_dim_orderutilss           r!   r  zTensor.dim_order  s    ^ $D)()9)9D7DII /40ot4^  "1 !-1D1DE#b 	#	?:  */4@Ob 	  */4@Od 	!
 %)?)E*41EFt  	,UNNtTUUr&   c                     t        |       rt        t        j                  | f| ||      S |rt        |   |      S t        |   |      S r   )r   r   r(   _update_namesr  r  r  )rC   r  r  r3   s      r!   r  zTensor._update_namesN  sN    #D)($$tgtUG 
 7?5))7>%((r&   c                      |i }t         fd|D              st        S t        j                         5   ||i |}|t	               v r|cddd       S t        |       cddd       S # 1 sw Y   yxY w)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   6   K   | ]  }t        |        y wr   )
issubclass)r  tclss     r!   r  z,Tensor.__torch_function__.<locals>.<genexpr>l  s     5!:c1%5   )allr   rY   DisableTorchFunctionSubclassr   _convert)r  r+   typesr   r   r.   s   `     r!   __torch_function__zTensor.__torch_function__Z  sx     >F5u55!!,,. 	*''C355	* 	*
  S)	* 	* 	*s   A)A))A2c                    t        |       rt        t        j                  | f| |      S | j                  rt        d      | j                         rt        d      | j                  t        j                  k7  rt        d      |t        |      t        urt        d      ||dk7  r| j                  j                  dk(  r|dk(  r9t        j                  j                  t        j                   j#                         }n]|d	k(  r9t        j                  j                  t        j                   j#                         }nt        j                   j%                  |      }t        j                   j'                         }||k7  r@t        j                   j)                         }|j+                  |       |j-                  |       | j                  j                  d
k(  rhd	dl}d	dlmc m} t7        |j9                               d	k  s#d|j9                         d	   j;                         vrt        d      |j=                  |       S t        j<                  |       S )a  
        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.
            If 1 (on CUDA) or 0 (on ROCM) then the default stream is used for
            synchronization.
        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``cudar  r   rH   z9Can't export to dlpack an XLA tensor that is not on CUDA.)r   r   r(   
__dlpack__rq   rT   ru   r   r4   stridedr,   rF  r   rX   r  hipr  default_streamExternalStreamcurrent_streamEventrecord
wait_event	torch_xlatorch_xla.utils.dlpackr  dlpackr   real_deviceslower	to_dlpack)rC   streamsync_streameventr  
xla_dlpacks         r!   r  zTensor.__dlpack__x  s   $ $D)():):TGT6RR
 Q  <<>PQQ;;%--'K  $v,c"9 @AAFbL{{6) Q;5==#4#4#<"ZZ668Fq[U]]%6%6%B"ZZ668F"ZZ66v>F#jj779[(!JJ,,.ELL-%%e,;;u$77 I**,-2!7!7!9!!<!B!B!DD"O  ''--t$$r&   c                 $   t        |       rt        t        j                  | f|       S ddlm} | j                  }|j                  |j                  nd}|j                  }|dk(  r*t        j                  j                  |j                  }||fS |dk(  r | j                         r|j                  }||fS |dk(  r|j                  }||fS |dk(  r|j                   }||fS |dk(  r|j"                  }||fS | j                  j                  dk(  r|j$                  }||fS |dk(  rbdd l}t)        |j+                               dk  s#d|j+                         d   j-                         vrt/        d| d	      |j                  }||fS t/        d| d	      )
Nr   )DLDeviceTyper  r   xpuprivateuse1rH   zUnknown device type z for Dlpack)r   r   r(   __dlpack_device__torch.utils.dlpackr  rX   indexr,   r4   r  r  kDLROCM	is_pinnedkDLCPUPinnedkDLGPUkDLCPU	kDLOneAPI	kDLExtDevr  r   r  r  rG  )rC   r  rX   idxtorch_device_typedevice_typer  s          r!   r  zTensor.__dlpack_device__  s   #D)()A)AD7DQQ3$ll6fllA"KK&5==+<+<+H&..K. S!!- %'DNN,<&33K* S!!) &(&--K& S!!% %'&--K" S!!! %'&00K S!! [[.&00K S!! %' I**,-2!7!7!9!!<!B!B!DD #78I7J+!VWW&--K S!! 34E3FkRSSr&   r4   )NNFN)F)froNFN)TF)NNNTreflectFNN)NNNTFNNF)r   )TFFN)FFNr   )r  N)e__name__
__module____qualname__r  __annotations__rA   rR   r   rk   r^   r   r1   r   r   r   r   r   rY   _add_docstr
TensorBaser
  detach_r  r  r	  r  r	   r   floatr   r  r  r  r  r"  r'  rF  r7  r:  r>  rC  r   rP  rR  r%   rW  rZ  __rtruediv____idiv____itruediv__re  __pow__pow___ipow__r]  r_  rf  rj  rl  ro  rr  ru  positive__pos__rx   __neg__abs__abs__ry  r  r  r  __array_priority__r  r  r   r  propertyr  r  r  r  r  r  r  r  r   r4   r  r  r  classmethodr  _disabled_torch_dispatch_implr   r  r
   enumIntEnumr  __classcell__)r3   s   @r!   r(   r(   P   s[   O)6BHH0%&
z(x<& +/ M LP:
x0d9v
> R^^
	F$ bnn
		G2.<  */>E%*%&>"
"
4
8
& %)$(%)! #')-,
,
 SM,
 SM	,

 #,
 ,
 ,
 ,
 4.,
 !,
b %)$(%) #' $$'
'
 SM'
 SM	'

 #'
 '
 '
 4.'
 '
 '
R)1E"
.
$ C7 C7 C) C) L==))LK
G M
H C, C,4 C& C& C/ C/ C/ C/ C5 C5 C6 C6 C) C) mm$$GmmGmmG $, :'
C 
t 
& CY CYJA*+X+
Z1,C(DT  LQwV"'d53F3F.G(G"HwVr
) * *6 99D%L!"5s):#; !"F Jr&   r(   c                     t         u r| S t        | t               rt        |       s| j                        } t        | t        t        f      r t        |       fd| D              } | S )Nc              3   6   K   | ]  }t        |        y wr   )r  )r  rr  s     r!   r  z_convert.<locals>.<genexpr>  s     6QC(6r  )r(   r   r)   r   r  r,   )r.   r  s    `r!   r  r    sY    
f}
#vz#s';ooc"#t}%d3i6#66Jr&   )'r{   r7  r"   r   collectionsr   r  r   numbersr   typingr   r   r   r	   r
   r   r4   torch._CrY   torch._namedtensor_internalsr   r   r   r   r   r   torch.overridesr   r   r   r   r   r%   r/   r9   r%  r(   r  r  r&   r!   <module>rC     sg        #   : :    "0QUXX   Qh4r&   