U
    9%e                 >   @   s*  U d Z ddlZddlZddlZddlZddlZddlZddlZdd Zddl	m
Z
mZ ddlmZmZmZmZ e rzdZndd	lmZ dd
lmZmZmZmZmZmZmZmZmZmZ ddlZdddddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHg>ZejdIkre dJdKZ!ej"#ej$dLdMZ%ej"#ej"&e'dNZ(ej$ej)krej"#ej)dLdMZ*ndOZ*e+e,ej"j-e(e%e*gZ.e/dPdQ e.D rej"#e dRej"#e!dSdTdMdUZ0ndOZ0ddVl1m2Z3 ddl4Z4e3rje/dWdQ e.D rje35dXdYZ6dZe6 Z7ej"#e!d[d\d]e3 Z8ej"#e e7e8dMZ9ndOZ9e.:e,ej"j-e0e9g ej;d^d_d`Z<e=e<daZ>e<?dZ@ejAe<jB_Ce>rejAe<jD_Ce.D ]ZEeFeE qz"eGdb eGdc eGdd W n eHk
r   eIde Y nX e44ej"#e(dfZJdgZKeJD ]ZLdgZMe>re<DeLddhZNeO ZPeNdkrePdikreQePZReR jSdjeL dk7  _SeRneNdk	rd_ZMeMs6eKsdl#e.ejTdm g ejTdm< d_ZKe<BeLZNeNdkr6eQeO ZReR jSdjeL dk7  _SeRq6e<?e@ dndo ZUddpdqdrZVes@e dsre sVeW dtkreX ZYeZej[ej\B  ddul]T eZeY [YnereV  ddul]T erddl]m^Z^ G dvd> d>Z_G dwd? d?Z`G dxd@ d@ZadydA ZbdzdC Zcd{dB Zdd|dD Zed}dE Zfzdd~l]mgZg W nD ehk
rR   ddl]m^Zi eij'dkrLehejdk d Y nX ele^D ]hZmemd dYkr\emnds\eoem epe^emZqereqeseseqr\eqjtdkr\emdkr\deq_tq\esele^D ]DZuepe^euZvewevewe^krdeu ejxkrevejxdeu < qdd Zydd Zzdd Z{da|dd Z}dd Z~dd Zdgdejejdddd5Zejdpdd6Zejdpdd7Zeejef dddd8Zejdpdd9Zejdpdd;Zedddd:Zejdddd<Zejdpdd=Zeejeaf eg ef dddZdddZd ddZd!ddZd"ddZd#ddZd$ddZd%ddZddlmZmZmZmZ e:ddddg ddlmZ ddlmZmZmZmZmZ G dd' d'eZG dd! d!eZG dd" d"eZG dd deZG dd# d#eZG dd$ d$eZG dd% d%eZG dd& d&eZG dd( d(eZG dd deZG dd deZG dd deZG dd deZG ddĄ deZG ddƄ deZG ddȄ deZG ddʄ deZeeeeeeeeeeeeeeeeeeehZe Zee ed< ddlmZmZmZmZmZ ddlmZmZ ddlmZ ddЄ ZddlmZ eZeZe^ge  [e	rddulT eZ[dZele^jʃD ]nZmemdӡ	semek	r	qepe^jemZqdeq_temdk	reqẽ em< dYem Zmeqẽ em< emdY	seoem 	qddlmZ ddulT [[ddׄ ZddVlm2Z2 ddlmZ ddlmZ ddlmZ ddlmZmZmZmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlZddlmZ ddlmZ ddlmZ ddlZddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlZddlmZ ddlmZ ddlmZ ddlmZ ddlZddlZddlZddlZe^e+ej ddlmZmZmZ [[[ejdpddZddlmZ ddlmZ ddlѐm Z  ddlѐmZ eZddlmZ eeѐj [ddlmZ ejj	j
Z
ejj	jZddlmZmZ ddlmZ ddlmZmZmZmZ ddlmZ G dd dZG d d dZd&dgdddddgdee ejeej eeef eedf eeeeeejejf f  ejedddFZddlѐmZ dd Zdd	lmZ dd
lmZ esddlmZ dejTkrddlm2  m Z! e!"  ddl#Zddlѐm$Z$ ddl%m&Z& dd Z'ejjӐ(  e srddlѐm)Z) G dd dZ*ejjӐj+ejj2j+ejj,j-ejj.j-dZ/erddlѐm0Z0 ddlѐm1Z1 ddlѐm2Z2 ddddhZ3dd Z4ddlm5Z5 e56  dS ('  a  
The torch package contains data structures for multi-dimensional
tensors and defines mathematical operations over these tensors.
Additionally, it provides many utilities for efficient serialization of
Tensors and arbitrary types, and other useful utilities.

It has a CUDA counterpart, that enables you to run your tensor computations
on an NVIDIA GPU with compute capability >= 3.0.
    Nc                   C   s   t jdd tkS )Nztorch._meta_registrations)sysmodulesgetobject r   r   M/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/torch/__init__.py_running_with_deploy   s    r      )_import_dotted_nameclassproperty)get_file_path#prepare_multiprocessing_environmentUSE_RTLD_GLOBAL_WITH_LIBTORCHUSE_GLOBAL_DEPSztorch-deploy-1.8)__version__)
AnyCallableDictOptionalSetTupleTypeTYPE_CHECKINGUnionListtypename	is_tensor
is_storageset_default_tensor_typeset_default_deviceset_rng_stateget_rng_statemanual_seedinitial_seedseedsaveloadset_printoptionschunksplitstackmatmulno_gradenable_gradZrandZrandninference_modeDoubleStorageFloatStorageLongStorage
IntStorageShortStorageCharStorageByteStorageBoolStorageTypedStorageUntypedStorageZDoubleTensorZFloatTensorZ
LongTensorZ	IntTensorZShortTensorZ
CharTensorZ
ByteTensorZ
BoolTensorTensorlobpcguse_deterministic_algorithms$are_deterministic_algorithms_enabled-is_deterministic_algorithms_warn_only_enabledset_deterministic_debug_modeget_deterministic_debug_modeset_float32_matmul_precisionget_float32_matmul_precisionset_warn_alwaysis_warn_always_enabledSymIntSymFloatSymBoolsym_notsym_int	sym_floatsym_maxsym_mincompilevmapexportwin32ZProgramFileszC:\Program FilesLibrarybinlib c                 c   s&   | ]}t jt j|d  V  qdS )znvToolsExt64_1.dllN)ospathexistsjoin.0pr   r   r   	<genexpr>Q   s     r[   ZNVTOOLSEXT_PATHzNVIDIA CorporationZ
NvToolsExtx64)cudac                 c   s$   | ]}t  tj|d  V  qdS )zcudart64*.dllN)globrT   rU   rW   rX   r   r   r   r[   Y   s     ._ZCUDA_PATH_VzNVIDIA GPU Computing ToolkitCUDAvzkernel32.dllT)Zuse_last_errorZAddDllDirectoryzvcruntime140.dllzmsvcp140.dllzvcruntime140_1.dllzMicrosoft Visual C++ Redistributable is not installed, this may lead to the DLL load failure.
                 It can be downloaded at https://aka.ms/vs/16/release/vc_redist.x64.exez*.dllFi   ~   z Error loading "z" or one of its dependencies.;PATHc              	   C   s   t  dkstdddl}d}tjD ]P}tj|d}tj|sFq&|tj|| d|}|rn|sn|d }|r& qxq&|st	| dtj t
| dS )z8Preloads cuda deps if they could not be found otherwise.LinuxzShould only be called on Linuxr   NZnvidiarR   z not found in the system path )platformsystemAssertionErrorr^   r   rU   rT   rW   rV   
ValueErrorctypesCDLL)
lib_folderlib_namer^   lib_pathrU   Znvidia_pathZcandidate_lib_pathsr   r   r   _preload_cuda_deps   s    
rp   returnc                     s   t  st dkrd S dt dkr(dnd } tjt}tjtj|d| }zt	j
|t	jd W n tk
r   zjdd	d
ddddddddd} fdd| D }|s | D ]\}} t||  qt	j
|t	jd W 5 d   X Y nX d S )NWindowsZlibtorch_global_depsDarwinz.dylibz.sorR   modezlibcublas.so.*[0-9]zlibcudnn.so.*[0-9]zlibnvrtc.so.*[0-9]zlibcudart.so.*[0-9]zlibcupti.so.*[0-9]zlibcufft.so.*[0-9]zlibcurand.so.*[0-9]zlibcusolver.so.*[0-9]zlibcusparse.so.*[0-9]zlibnccl.so.*[0-9]zlibnvToolsExt.so.*[0-9])ZcublascudnnZ
cuda_nvrtcZcuda_runtimeZ
cuda_cuptiZcufftZcurandZcusolverZcusparseZncclZnvtxc                    s(   g | ] }| d d  jd kr|qS )r_   r   )r)   args)rY   rR   errr   r   
<listcomp>   s      z%_load_global_deps.<locals>.<listcomp>)r   rg   rh   rT   rU   abspath__file__rW   dirnamerk   rl   RTLD_GLOBALOSErrorvaluesitemsrp   )rn   herero   Z	cuda_libsZis_cuda_lib_errrm   r   ry   r   _load_global_deps   s4    r   ZTORCH_USE_RTLD_GLOBALrs   )*c                   @   s   e Zd ZdZdd Zdd Zdd Zdd	 Zee	j
d
ddZe	j
dddZe	j
dddZe	j
dddZe	j
dddZdd Zdd Zdd Zdd ZdS )rD   z
    Like an int (including magic methods), but redirects all operations on the
    wrapped node. This is used in particular to symbolically record operations
    in the symbolic shape workflow.
    c                 C   s
   || _ d S Nnodeselfr   r   r   r   __init__   s    zSymInt.__init__c                 C   s   t | dkS )Nr   )builtinsboolr   r   r   r   __bool__   s    zSymInt.__bool__c                 C   s
   | j  S r   r   int_r   r   r   r   __int__  s    zSymInt.__int__c                 C   s
   | j  S r   r   r   r   r   r   	__index__  s    zSymInt.__index__otherrr   c                 C   s   t dd S Nztype stub not overriddenri   r   r   r   r   r   __eq__	  s    zSymInt.__eq__rq   c                 C   s   t dd S r   r   r   r   r   r   __lt__  s    zSymInt.__lt__c                 C   s   t dd S r   r   r   r   r   r   __gt__  s    zSymInt.__gt__c                 C   s   t dd S r   r   r   r   r   r   __le__  s    zSymInt.__le__c                 C   s   t dd S r   r   r   r   r   r   __ge__  s    zSymInt.__ge__c                 C   s   t dd S r   r   r   r   r   r   __sym_max__  s    zSymInt.__sym_max__c                 C   s   t dd S r   r   r   r   r   r   __sym_min__  s    zSymInt.__sym_min__c                 C   s   t dd S r   r   r   r   r   r   __sym_float__  s    zSymInt.__sym_float__c                 C   s
   t | jS r   )strr   r   r   r   r   __repr__!  s    zSymInt.__repr__N)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rD      s   c                   @   s   e Zd ZdZdd Zdd ZeejdddZ	ejd	d
dZ
ejd	ddZejd	ddZejd	ddZdd Zdd Zdd Zdd ZdS )rE   z
    Like an float (including magic methods), but redirects all operations on the
    wrapped node. This is used in particular to symbolically record operations
    in the symbolic shape workflow.
    c                 C   s
   || _ d S r   r   r   r   r   r   r   +  s    zSymFloat.__init__c                 C   s
   | j  S r   r   bool_r   r   r   r   r   0  s    zSymFloat.__bool__r   c                 C   s   t dd S r   r   r   r   r   r   r   5  s    zSymFloat.__eq__rq   c                 C   s   t dd S r   r   r   r   r   r   r   8  s    zSymFloat.__lt__c                 C   s   t dd S r   r   r   r   r   r   r   ;  s    zSymFloat.__gt__c                 C   s   t dd S r   r   r   r   r   r   r   >  s    zSymFloat.__le__c                 C   s   t dd S r   r   r   r   r   r   r   A  s    zSymFloat.__ge__c                 C   s   t dd S r   r   r   r   r   r   r   D  s    zSymFloat.__sym_max__c                 C   s   t dd S r   r   r   r   r   r   r   G  s    zSymFloat.__sym_min__c                 C   s   t dd S r   r   r   r   r   r   __sym_int__J  s    zSymFloat.__sym_int__c                 C   s
   | j  S r   r   r   r   r   r   r   r   M  s    zSymFloat.__repr__N)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rE   $  s   c                   @   sZ   e Zd ZdZdd Zdd Zdd Zd dd	d
Zd dddZd dddZ	dd Z
dS )rF   an  
    Like an bool (including magic methods), but redirects all operations on the
    wrapped node. This is used in particular to symbolically record operations
    in the symbolic shape workflow.

    Unlike regular bools, regular boolean operators will force extra guards instead
    of symbolically evaluate.  Use the bitwise operators instead to handle this.
    c                 C   s
   || _ d S r   r   r   r   r   r   r   Z  s    zSymBool.__init__c                 C   s
   | j  S r   r   r   r   r   r   r   _  s    zSymBool.__bool__c                 C   s   t | j S r   )r   intr   r   r   r   r   r   r   b  s    zSymBool.__int__rq   c                 C   s   t dd S r   r   r   r   r   r   __and__f  s    zSymBool.__and__c                 C   s   t dd S r   r   r   r   r   r   __or__i  s    zSymBool.__or__c                 C   s   t dd S r   r   r   r   r   r   __sym_not__}  s    zSymBool.__sym_not__c                 C   s
   | j  S r   r   r   r   r   r   r     s    zSymBool.__repr__N)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rF   P  s   	c                 C   s   t | dr|  S |  S )zi SymInt-aware utility for logical negation.

    Args:
        a (SymBool or bool): Object to negate
    r   )hasattrr   ar   r   r   rG     s    
c                 C   s(   t | tr| S t| dr |  S t| S )zp SymInt-aware utility for float casting.

    Args:
        a (SymInt, SymFloat, or object): Object to cast
    r   )
isinstancerE   r   r   py_floatr   r   r   r   rI     s
    

c                 C   s<   t | tr| S t | tr4| dkr*t| S t| S t| S )zn SymInt-aware utility for int casting.

    Args:
        a (SymInt, SymFloat, or object): Object to cast
    r   )r   rD   rE   mathfloorceilpy_intr   r   r   r   rH     s
    

c                 C   s<   t | ttfr| |S t |ttfr0|| S t| |S z  SymInt-aware utility for max().)r   rD   rE   r   r   maxr   br   r   r   rJ     s
    

c                 C   s<   t | ttfr| |S t |ttfr0|| S t| |S r   )r   rD   rE   r   r   minr   r   r   r   rK     s
    

)_initExtensiona  
            Failed to load PyTorch C extensions:
                It appears that PyTorch has loaded the `torch/_C` folder
                of the PyTorch repository rather than the C extensions which
                are expected in the `torch._C` namespace. This can occur when
                using the `install` workflow. e.g.
                    $ python setup.py install && python -c "import torch"

                This error can generally be solved using the `develop` workflow
                    $ python setup.py develop && python -c "import torch"  # This should succeed
                or by running Python from a different directory.
            ZBasetorch)ZDisableTorchFunctionSubclassZDisableTorchFunction	Generatorz	torch._C.c                 C   s   t | tjr|  S d}d}t| drN| jdkrN| jdkrN| jd k	rN| jd }t| dr`| j}nt| drr| j}n| jj}|| S )NrS   r   r   __builtin__r_   r   r   )	r   r   r9   typer   r   r   r   	__class__)omodule
class_namer   r   r   r     s     


c                 C   s   t | tjS )a  Returns True if `obj` is a PyTorch tensor.

    Note that this function is simply doing ``isinstance(obj, Tensor)``.
    Using that ``isinstance`` check is better for typechecking with mypy,
    and more explicit - so it's recommended to use that instead of
    ``is_tensor``.

    Args:
        obj (Object): Object to test
    Example::

        >>> x = torch.tensor([1, 2, 3])
        >>> torch.is_tensor(x)
        True

    )r   r   r9   objr   r   r   r     s    c                 C   s   t | tkS )zgReturns True if `obj` is a PyTorch storage object.

    Args:
        obj (Object): Object to test
    )r   _storage_classesr   r   r   r   r     s    c                 C   sF   t dk	rt ddd | dkr&da dS ddlm} || a t   dS )a  Sets the default ``torch.Tensor`` to be allocated on ``device``.  This
    does not affect factory function calls which are called with an explicit
    ``device`` argument.  Factory calls will be performed as if they
    were passed ``device`` as an argument.

    To only temporarily change the default device instead of setting it
    globally, use ``with torch.device(device):`` instead.

    The default device is initially ``cpu``.  If you set the default tensor
    device to another device (e.g., ``cuda``) without a device index, tensors
    will be allocated on whatever the current device for the device type,
    even after :func:`torch.cuda.set_device` is called.

    .. warning::

        This function imposes a slight performance cost on every Python
        call to the torch API (not just factory functions).  If this
        is causing problems for you, please comment on
        https://github.com/pytorch/pytorch/issues/92701

    Args:
        device (device or string): the device to set as default

    Example::

        >>> # xdoctest: +SKIP("requires cuda, changes global state")
        >>> torch.tensor([1.2, 3]).device
        device(type='cpu')
        >>> torch.set_default_device('cuda')  # current device is 0
        >>> torch.tensor([1.2, 3]).device
        device(type='cuda', index=0)
        >>> torch.set_default_device('cuda:1')
        >>> torch.tensor([1.2, 3]).device
        device(type='cuda', index=1)

    Nr   )DeviceContext)_GLOBAL_DEVICE_CONTEXT__exit__Ztorch.utils._devicer   	__enter__)devicer   r   r   r   r      s    &c                 C   s    t | trt| } t|  dS )a  Sets the default ``torch.Tensor`` type to floating point tensor type
    ``t``. This type will also be used as default floating point type for
    type inference in :func:`torch.tensor`.

    The default floating point tensor type is initially ``torch.FloatTensor``.

    Args:
        t (type or string): the floating point tensor type or its name

    Example::

        >>> # xdoctest: +SKIP("Other tests may have changed the default type. Can we reset it?")
        >>> torch.tensor([1.2, 3]).dtype    # initial default for floating point is torch.float32
        torch.float32
        >>> torch.set_default_tensor_type(torch.DoubleTensor)
        >>> torch.tensor([1.2, 3]).dtype    # a new floating point tensor
        torch.float64

    N)r   r   r
   _CZ_set_default_tensor_type)tr   r   r   r   P  s    
c                 C   s   t |  dS )a  

    Sets the default floating point dtype to :attr:`d`. Supports torch.float32
    and torch.float64 as inputs. Other dtypes may be accepted without complaint
    but are not supported and are unlikely to work as expected.

    When PyTorch is initialized its default floating point dtype is torch.float32,
    and the intent of set_default_dtype(torch.float64) is to facilitate NumPy-like
    type inference. The default floating point dtype is used to:

    1. Implicitly determine the default complex dtype. When the default floating point
       type is float32 the default complex dtype is complex64, and when the default
       floating point type is float64 the default complex type is complex128.
    2. Infer the dtype for tensors constructed using Python floats or complex Python
       numbers. See examples below.
    3. Determine the result of type promotion between bool and integer tensors and
       Python floats and complex Python numbers.

    Args:
        d (:class:`torch.dtype`): the floating point dtype to make the default.
                                  Either torch.float32 or torch.float64.

    Example:
        >>> # xdoctest: +SKIP("Other tests may have changed the default type. Can we reset it?")
        >>> # initial default for floating point is torch.float32
        >>> # Python floats are interpreted as float32
        >>> torch.tensor([1.2, 3]).dtype
        torch.float32
        >>> # initial default for floating point is torch.complex64
        >>> # Complex Python numbers are interpreted as complex64
        >>> torch.tensor([1.2, 3j]).dtype
        torch.complex64

        >>> torch.set_default_dtype(torch.float64)

        >>> # Python floats are now interpreted as float64
        >>> torch.tensor([1.2, 3]).dtype    # a new floating point tensor
        torch.float64
        >>> # Complex Python numbers are now interpreted as complex128
        >>> torch.tensor([1.2, 3j]).dtype   # a new complex tensor
        torch.complex128

    N)r   Z_set_default_dtype)dr   r   r   set_default_dtypei  s    ,r   	warn_only)rv   r   rr   c                C   s   t j| |d dS )aJ   Sets whether PyTorch operations must use "deterministic"
    algorithms. That is, algorithms which, given the same input, and when
    run on the same software and hardware, always produce the same output.
    When enabled, operations will use deterministic algorithms when available,
    and if only nondeterministic algorithms are available they will throw a
    :class:`RuntimeError` when called.

    .. note:: This setting alone is not always enough to make an application
        reproducible. Refer to :ref:`reproducibility` for more information.

    .. note:: :func:`torch.set_deterministic_debug_mode` offers an alternative
        interface for this feature.

    The following normally-nondeterministic operations will act
    deterministically when ``mode=True``:

        * :class:`torch.nn.Conv1d` when called on CUDA tensor
        * :class:`torch.nn.Conv2d` when called on CUDA tensor
        * :class:`torch.nn.Conv3d` when called on CUDA tensor
        * :class:`torch.nn.ConvTranspose1d` when called on CUDA tensor
        * :class:`torch.nn.ConvTranspose2d` when called on CUDA tensor
        * :class:`torch.nn.ConvTranspose3d` when called on CUDA tensor
        * :func:`torch.bmm` when called on sparse-dense CUDA tensors
        * :func:`torch.Tensor.__getitem__` when attempting to differentiate a CPU tensor
          and the index is a list of tensors
        * :func:`torch.Tensor.index_put` with ``accumulate=False``
        * :func:`torch.Tensor.index_put` with ``accumulate=True`` when called on a CPU
          tensor
        * :func:`torch.Tensor.put_` with ``accumulate=True`` when called on a CPU
          tensor
        * :func:`torch.Tensor.scatter_add_` when called on a CUDA tensor
        * :func:`torch.gather` when called on a CUDA tensor that requires grad
        * :func:`torch.index_add` when called on CUDA tensor
        * :func:`torch.index_select` when attempting to differentiate a CUDA tensor
        * :func:`torch.repeat_interleave` when attempting to differentiate a CUDA tensor
        * :func:`torch.Tensor.index_copy` when called on a CPU or CUDA tensor
        * :func:`torch.Tensor.scatter` when `src` type is Tensor and called on CUDA tensor
        * :func:`torch.Tensor.scatter_reduce` when ``reduce='sum'`` or ``reduce='mean'`` and called on CUDA tensor
        * :func:`torch.Tensor.resize_`, when called with a tensor that is not
          quantized, sets new elements to a known value.  Floating point or
          complex values are set to NaN. Integer values are set to the maximum
          value.
        * :func:`torch.empty`, :func:`torch.empty_like`, :func:`torch.empty_strided`,
          and :func:`torch.empty_permuted` will fill the output tensor with a known
          value. Floating point or complex dtype tensors are filled with NaN. Integer
          dtype tensors are filled with the maximum value.

    The following normally-nondeterministic operations will throw a
    :class:`RuntimeError` when ``mode=True``:

        * :class:`torch.nn.AvgPool3d` when attempting to differentiate a CUDA tensor
        * :class:`torch.nn.AdaptiveAvgPool2d` when attempting to differentiate a CUDA tensor
        * :class:`torch.nn.AdaptiveAvgPool3d` when attempting to differentiate a CUDA tensor
        * :class:`torch.nn.MaxPool3d` when attempting to differentiate a CUDA tensor
        * :class:`torch.nn.AdaptiveMaxPool2d` when attempting to differentiate a CUDA tensor
        * :class:`torch.nn.FractionalMaxPool2d` when attempting to differentiate a CUDA tensor
        * :class:`torch.nn.FractionalMaxPool3d` when attempting to differentiate a CUDA tensor
        * :class:`torch.nn.MaxUnpool1d`
        * :class:`torch.nn.MaxUnpool2d`
        * :class:`torch.nn.MaxUnpool3d`
        * :func:`torch.nn.functional.interpolate` when attempting to differentiate a CUDA tensor
          and one of the following modes is used:

          - ``linear``
          - ``bilinear``
          - ``bicubic``
          - ``trilinear``

        * :class:`torch.nn.ReflectionPad1d` when attempting to differentiate a CUDA tensor
        * :class:`torch.nn.ReflectionPad2d` when attempting to differentiate a CUDA tensor
        * :class:`torch.nn.ReflectionPad3d` when attempting to differentiate a CUDA tensor
        * :class:`torch.nn.ReplicationPad1d` when attempting to differentiate a CUDA tensor
        * :class:`torch.nn.ReplicationPad2d` when attempting to differentiate a CUDA tensor
        * :class:`torch.nn.ReplicationPad3d` when attempting to differentiate a CUDA tensor
        * :class:`torch.nn.NLLLoss` when called on a CUDA tensor
        * :class:`torch.nn.CTCLoss` when attempting to differentiate a CUDA tensor
        * :class:`torch.nn.EmbeddingBag` when attempting to differentiate a CUDA tensor when
          ``mode='max'``
        * :func:`torch.Tensor.put_` when ``accumulate=False``
        * :func:`torch.Tensor.put_` when ``accumulate=True`` and called on a CUDA tensor
        * :func:`torch.histc` when called on a CUDA tensor
        * :func:`torch.bincount` when called on a CUDA tensor and ``weights``
          tensor is given
        * :func:`torch.kthvalue` with called on a CUDA tensor
        * :func:`torch.median` with indices output when called on a CUDA tensor
        * :func:`torch.nn.functional.grid_sample` when attempting to differentiate a CUDA tensor
        * :func:`torch.cumsum` when called on a CUDA tensor when dtype is floating point or complex
        * :func:`torch.Tensor.scatter_reduce` when ``reduce='prod'`` and called on CUDA tensor
        * :func:`torch.Tensor.resize_` when called with a quantized tensor

    A handful of CUDA operations are nondeterministic if the CUDA version is
    10.2 or greater, unless the environment variable ``CUBLAS_WORKSPACE_CONFIG=:4096:8``
    or ``CUBLAS_WORKSPACE_CONFIG=:16:8`` is set. See the CUDA documentation for more
    details: `<https://docs.nvidia.com/cuda/cublas/index.html#cublasApi_reproducibility>`_
    If one of these environment variable configurations is not set, a :class:`RuntimeError`
    will be raised from these operations when called with CUDA tensors:

        * :func:`torch.mm`
        * :func:`torch.mv`
        * :func:`torch.bmm`

    Note that deterministic operations tend to have worse performance than
    nondeterministic operations.

    .. note::

        This flag does not detect or prevent nondeterministic behavior caused
        by calling an inplace operation on a tensor with an internal memory
        overlap or by giving such a tensor as the :attr:`out` argument for an
        operation. In these cases, multiple writes of different data may target
        a single memory location, and the order of writes is not guaranteed.

    Args:
        mode (:class:`bool`): If True, makes potentially nondeterministic
            operations switch to a deterministic algorithm or throw a runtime
            error. If False, allows nondeterministic operations.

    Keyword args:
        warn_only (:class:`bool`, optional): If True, operations that do not
            have a deterministic implementation will throw a warning instead of
            an error. Default: ``False``

    Example::

        >>> # xdoctest: +SKIP
        >>> torch.use_deterministic_algorithms(True)

        # Forward mode nondeterministic error
        >>> torch.randn(10, device='cuda').kthvalue(0)
        ...
        RuntimeError: kthvalue CUDA does not have a deterministic implementation...

        # Backward mode nondeterministic error
        >>> torch.nn.AvgPool3d(1)(torch.randn(3, 4, 5, 6, requires_grad=True).cuda()).sum().backward()
        ...
        RuntimeError: avg_pool3d_backward_cuda does not have a deterministic implementation...
    r   N)r   _set_deterministic_algorithms)rv   r   r   r   r   r;     s     c                   C   s   t  S )zReturns True if the global deterministic flag is turned on. Refer to
    :func:`torch.use_deterministic_algorithms` documentation for more details.
    )r   _get_deterministic_algorithmsr   r   r   r   r<   #  s    c                   C   s   t  S )zReturns True if the global deterministic flag is set to warn only.
    Refer to :func:`torch.use_deterministic_algorithms` documentation for more
    details.
    )r   '_get_deterministic_algorithms_warn_onlyr   r   r   r   r=   )  s    )
debug_moderr   c                 C   s   t | tjtfs"tdt|  t | trd| dkr:d} n*| dkrHd} n| dkrVd} ntd|  | dkrxtd	 n:| dkrtjd
d
d n"| dkrtd
 ntd|  dS )a  Sets the debug mode for deterministic operations.

    .. note:: This is an alternative interface for
        :func:`torch.use_deterministic_algorithms`. Refer to that function's
        documentation for details about affected operations.

    Args:
        debug_mode(str or int): If "default" or 0, don't error or warn on
            nondeterministic operations. If "warn" or 1, warn on
            nondeterministic operations. If "error" or 2, error on
            nondeterministic operations.
    z'debug_mode must be str or int, but got defaultr   warnr	   error   zQinvalid value of debug_mode, expected one of `default`, `warn`, `error`, but got FTr   z:invalid value of debug_mode, expected 0, 1, or 2, but got N)	r   r   r   r   	TypeErrorr   RuntimeErrorr   r   )r   r   r   r   r>   0  s*    
c                   C   s"   t  rt  rdS dS ndS dS )zReturns the current value of the debug mode for deterministic
    operations. Refer to :func:`torch.set_deterministic_debug_mode`
    documentation for more details.
    r	   r   r   N)r   r   r   r   r   r   r   r?   Z  s
    c                   C   s   t  S )zReturns the current value of float32 matrix multiplication precision. Refer to
    :func:`torch.set_float32_matmul_precision` documentation for more details.
    )r   Z_get_float32_matmul_precisionr   r   r   r   rA   h  s    )	precisionrr   c                 C   s   t |  dS )a  Sets the internal precision of float32 matrix multiplications.

    Running float32 matrix multiplications in lower precision may significantly increase
    performance, and in some programs the loss of precision has a negligible impact.

    Supports three settings:

        * "highest", float32 matrix multiplications use the float32 datatype (24 mantissa
          bits) for internal computations.
        * "high", float32 matrix multiplications either use the TensorFloat32 datatype (10
          mantissa bits) or treat each float32 number as the sum of two bfloat16 numbers
          (approximately 16 mantissa bits), if the appropriate fast matrix multiplication
          algorithms are available.  Otherwise float32 matrix multiplications are computed
          as if the precision is "highest".  See below for more information on the bfloat16
          approach.
        * "medium", float32 matrix multiplications use the bfloat16 datatype (8 mantissa
          bits) for internal computations, if a fast matrix multiplication algorithm
          using that datatype internally is available. Otherwise float32
          matrix multiplications are computed as if the precision is "high".

    When using "high" precision, float32 multiplications may use a bfloat16-based algorithm
    that is more complicated than simply truncating to some smaller number mantissa bits
    (e.g. 10 for TensorFloat32, 8 for bfloat16).  Refer to [Henry2019]_ for a complete
    description of this algorithm.  To briefly explain here, the first step is to realize
    that we can perfectly encode a single float32 number as the sum of three bfloat16
    numbers (because float32 has 24 mantissa bits while bfloat16 has 8, and both have the
    same number of exponent bits).  This means that the product of two float32 numbers can
    be exactly given by the sum of nine products of bfloat16 numbers.  We can then trade
    accuracy for speed by dropping some of these products.  The "high" precision algorithm
    specifically keeps only the three most significant products, which conveniently excludes
    all of the products involving the last 8 mantissa bits of either input.  This means that
    we can represent our inputs as the sum of two bfloat16 numbers rather than three.
    Because bfloat16 fused-multiply-add (FMA) instructions are typically >10x faster than
    float32 ones, it's faster to do three multiplications and 2 additions with bfloat16
    precision than it is to do a single multiplication with float32 precision.

    .. [Henry2019] http://arxiv.org/abs/1904.06376

    .. note::

        This does not change the output dtype of float32 matrix multiplications,
        it controls how the internal computation of the matrix multiplication is performed.

    .. note::

        This does not change the precision of convolution operations. Other flags,
        like `torch.backends.cudnn.allow_tf32`, may control the precision of convolution
        operations.

    .. note::

        This flag currently only affects one native device type: CUDA.
        If "high" or "medium" are set then the TensorFloat32 datatype will be used
        when computing float32 matrix multiplications, equivalent to setting
        `torch.backends.cuda.matmul.allow_tf32 = True`. When "highest" (the default)
        is set then the float32 datatype is used for internal computations, equivalent
        to setting `torch.backends.cuda.matmul.allow_tf32 = False`.

    Args:
        precision(str): can be set to "highest" (default), "high", or "medium" (see above).

    N)r   Z_set_float32_matmul_precision)r   r   r   r   r@   n  s    ?)r   rr   c                 C   s   t |  dS )a  When this flag is False (default) then some PyTorch warnings may only
    appear once per process. This helps avoid excessive warning information.
    Setting it to True causes these warnings to always appear, which may be
    helpful when debugging.

    Args:
        b (:class:`bool`): If True, force warnings to always be emitted
                           If False, set to the default behaviour
    N)r   Z_set_warnAlways)r   r   r   r   rB     s    
c                   C   s   t  S )zReturns True if the global warn_always flag is turned on. Refer to
    :func:`torch.set_warn_always` documentation for more details.
    )r   Z_get_warnAlwaysr   r   r   r   rC     s    condmessagec                 C   s   t |tjtjfs$tdt| tjjj	
|r8d S t| trLt| trPt|d kr^d}nt|sntdt| }| |d S )Nzcond must be a bool, but got zExpected cond to be True, but got False. (Could this error message be improved? If so, please report an enhancement request to PyTorch.)zmessage must be a callable)r   r   r   r   rF   r   r   ZfxZexperimentalZsymbolic_shapesZexpect_true
issubclass	ExceptionWarningri   callabler   )
error_typer   r   Zmessage_evaluatedr   r   r   _check_with  s    
r   c                 C   s   t t| | dS )a  Throws error containing an optional message if the specified condition
    is False.

    Error type: ``RuntimeError``

    C++ equivalent: ``TORCH_CHECK``

    Args:
        cond (:class:`bool`): If False, throw error

        message (Callable, optional): Callable that returns either a string or
            an object that has a ``__str__()`` method to be used as the error
            message. Default: ``None``
    N)r   r   r   r   r   r   _check  s    r   c                 C   s   t t| | dS )a  Throws error containing an optional message if the specified condition
    is False.

    Error type: ``IndexError``

    C++ equivalent: ``TORCH_CHECK_INDEX``

    Args:
        cond (:class:`bool`): If False, throw error

        message (Callable, optional): Callable that returns either a string or
            an object that has a ``__str__()`` method to be used as the error
            message. Default: ``None``
    N)r   
IndexErrorr   r   r   r   _check_index  s    r   c                 C   s   t t| | dS )a  Throws error containing an optional message if the specified condition
    is False.

    Error type: ``ValueError``

    C++ equivalent: ``TORCH_CHECK_VALUE``

    Args:
        cond (:class:`bool`): If False, throw error

        message (Callable, optional): Callable that returns either a string or
            an object that has a ``__str__()`` method to be used as the error
            message. Default: ``None``
    N)r   rj   r   r   r   r   _check_value  s    r   c                 C   s   t t| | dS )a  Throws error containing an optional message if the specified condition
    is False.

    Error type: ``TypeError``

    C++ equivalent: ``TORCH_CHECK_TYPE``

    Args:
        cond (:class:`bool`): If False, throw error

        message (Callable, optional): Callable that returns either a string or
            an object that has a ``__str__()`` method to be used as the error
            message. Default: ``None``
    N)r   r   r   r   r   r   _check_type  s    r   c                 C   s   t t| | dS )a  Throws error containing an optional message if the specified condition
    is False.

    Error type: ``NotImplementedError``

    C++ equivalent: ``TORCH_CHECK_NOT_IMPLEMENTED``

    Args:
        cond (:class:`bool`): If False, throw error

        message (Callable, optional): Callable that returns either a string or
            an object that has a ``__str__()`` method to be used as the error
            message. Default: ``None``
    N)r   NotImplementedErrorr   r   r   r   _check_not_implemented$  s    r   c                 C   sP   t |stdt| |jt jks8td|j t| |  | d S )Nzcond must be a tensor, but got z0cond tensor must have dtype torch.bool, but got )	r   r   r   r   dtyper   r   Z_is_all_trueitem)r   r   r   r   r   r   _check_tensor_all_with5  s    

r   c                 C   s   t t| | dS )a  Throws error containing an optional message if the specified condition
    is False.

    Error type: ``RuntimeError``

    C++ equivalent: ``TORCH_CHECK_TENSOR_ALL``

    Args:
        cond (:class:`torch.Tensor`): Tensor of dtype ``torch.bool``. If any
            element is ``False``, throw error

        message (Callable, optional): Callable that returns either a string or
            an object that has a ``__str__()`` method to be used as the error
            message. Default: ``None``
    N)r   r   r   r   r   r   _check_tensor_all@  s    r   )enaninfpir   r   r   r   )r9   )_StorageBaser7   _LegacyStorager8   _warn_typed_storage_removalc                   @   s$   e Zd Zedd Zedd ZdS )r5   c                 C   s   t   | jS r   r   _dtyper   r   r   r   r   f  s    zByteStorage.dtypec                 C   s   t jS r   )r   Zuint8r   r   r   r   r   k  s    zByteStorage._dtypeNr   r   r   r   r   r   r   r   r   r   r5   e  s   
c                   @   s$   e Zd Zedd Zedd ZdS )r/   c                 C   s   t   | jS r   r   r   r   r   r   r   p  s    zDoubleStorage.dtypec                 C   s   t jS r   )r   doubler   r   r   r   r   u  s    zDoubleStorage._dtypeNr   r   r   r   r   r/   o  s   
c                   @   s$   e Zd Zedd Zedd ZdS )r0   c                 C   s   t   | jS r   r   r   r   r   r   r   z  s    zFloatStorage.dtypec                 C   s   t jS r   )r   floatr   r   r   r   r     s    zFloatStorage._dtypeNr   r   r   r   r   r0   y  s   
c                   @   s$   e Zd Zedd Zedd ZdS )HalfStoragec                 C   s   t   | jS r   r   r   r   r   r   r     s    zHalfStorage.dtypec                 C   s   t jS r   )r   Zhalfr   r   r   r   r     s    zHalfStorage._dtypeNr   r   r   r   r   r     s   
r   c                   @   s$   e Zd Zedd Zedd ZdS )r1   c                 C   s   t   | jS r   r   r   r   r   r   r     s    zLongStorage.dtypec                 C   s   t jS r   )r   longr   r   r   r   r     s    zLongStorage._dtypeNr   r   r   r   r   r1     s   
c                   @   s$   e Zd Zedd Zedd ZdS )r2   c                 C   s   t   | jS r   r   r   r   r   r   r     s    zIntStorage.dtypec                 C   s   t jS r   )r   r   r   r   r   r   r     s    zIntStorage._dtypeNr   r   r   r   r   r2     s   
c                   @   s$   e Zd Zedd Zedd ZdS )r3   c                 C   s   t   | jS r   r   r   r   r   r   r     s    zShortStorage.dtypec                 C   s   t jS r   )r   shortr   r   r   r   r     s    zShortStorage._dtypeNr   r   r   r   r   r3     s   
c                   @   s$   e Zd Zedd Zedd ZdS )r4   c                 C   s   t   | jS r   r   r   r   r   r   r     s    zCharStorage.dtypec                 C   s   t jS r   )r   Zint8r   r   r   r   r     s    zCharStorage._dtypeNr   r   r   r   r   r4     s   
c                   @   s$   e Zd Zedd Zedd ZdS )r6   c                 C   s   t   | jS r   r   r   r   r   r   r     s    zBoolStorage.dtypec                 C   s   t jS r   )r   r   r   r   r   r   r     s    zBoolStorage._dtypeNr   r   r   r   r   r6     s   
c                   @   s$   e Zd Zedd Zedd ZdS )BFloat16Storagec                 C   s   t   | jS r   r   r   r   r   r   r     s    zBFloat16Storage.dtypec                 C   s   t jS r   )r   Zbfloat16r   r   r   r   r     s    zBFloat16Storage._dtypeNr   r   r   r   r   r    s   
r  c                   @   s$   e Zd Zedd Zedd ZdS )ComplexDoubleStoragec                 C   s   t   | jS r   r   r   r   r   r   r     s    zComplexDoubleStorage.dtypec                 C   s   t jS r   )r   Zcdoubler   r   r   r   r     s    zComplexDoubleStorage._dtypeNr   r   r   r   r   r    s   
r  c                   @   s$   e Zd Zedd Zedd ZdS )ComplexFloatStoragec                 C   s   t   | jS r   r   r   r   r   r   r     s    zComplexFloatStorage.dtypec                 C   s   t jS r   )r   Zcfloatr   r   r   r   r     s    zComplexFloatStorage._dtypeNr   r   r   r   r   r    s   
r  c                   @   s$   e Zd Zedd Zedd ZdS )QUInt8Storagec                 C   s   t   | jS r   r   r   r   r   r   r     s    zQUInt8Storage.dtypec                 C   s   t jS r   )r   Zquint8r   r   r   r   r     s    zQUInt8Storage._dtypeNr   r   r   r   r   r    s   
r  c                   @   s$   e Zd Zedd Zedd ZdS )QInt8Storagec                 C   s   t   | jS r   r   r   r   r   r   r     s    zQInt8Storage.dtypec                 C   s   t jS r   )r   Zqint8r   r   r   r   r     s    zQInt8Storage._dtypeNr   r   r   r   r   r    s   
r  c                   @   s$   e Zd Zedd Zedd ZdS )QInt32Storagec                 C   s   t   | jS r   r   r   r   r   r   r     s    zQInt32Storage.dtypec                 C   s   t jS r   )r   Zqint32r   r   r   r   r     s    zQInt32Storage._dtypeNr   r   r   r   r   r    s   
r  c                   @   s$   e Zd Zedd Zedd ZdS )QUInt4x2Storagec                 C   s   t   | jS r   r   r   r   r   r   r     s    zQUInt4x2Storage.dtypec                 C   s   t jS r   )r   Zquint4x2r   r   r   r   r     s    zQUInt4x2Storage._dtypeNr   r   r   r   r   r    s   
r  c                   @   s$   e Zd Zedd Zedd ZdS )QUInt2x4Storagec                 C   s   t   | jS r   r   r   r   r   r   r     s    zQUInt2x4Storage.dtypec                 C   s   t jS r   )r   Zquint2x4r   r   r   r   r     s    zQUInt2x4Storage._dtypeNr   r   r   r   r   r	    s   
r	  _tensor_classes)r    r!   r"   r#   r$   )r%   r&   )r'   c                  C   sP   t  st dkrdS tddd} ttd tj| sFtd|  | 	dS )Nrs       r   rQ   Ztorch_shm_managerz$Unable to find torch_shm_manager at zutf-8)
r   rg   rh   r   r   rT   rU   rV   r   encode)rU   r   r   r   manager_path#  s    r  )autocast)Z
unique_dim__segment_reduce)_disable_dynamoc                 C   sH   ddl m}m} t| tjk	r8|| fr8|t| f| |S | sDt|dS )zFA wrapper around Python's assert which is symbolically traceable.
    r	   )has_torch_functionhandle_torch_functionN)Z	overridesr  r  r   r   r9   _assertri   )	conditionr   r  r  r   r   r   r  u  s    r  )cpu)mps)autograd)r,   r-   set_grad_enabledr.   )fft)futures)_awaits)nested)nn)windows)optim)multiprocessing)sparse)special)jit)linalg)hub)random)distributions)testing)backends)
__config__)
__future__)profiler)ao)_torch_docs_tensor_docs_storage_docsc                   C   s   t jS )z?Returns whether PyTorch was built with _GLIBCXX_USE_CXX11_ABI=1)r   Z_GLIBCXX_USE_CXX11_ABIr   r   r   r   compiled_with_cxx11_abi  s    r2  )ops)classes)quantization)quasirandom)register_after_fork)r:   )from_dlpack	to_dlpack)masked)matrix_rankeigsolvelstsq)_symeigc                   @   sd   e Zd ZdZdd Zdd Zee dddZee	ee
f  d	d
dZdd Zdd Zdd ZdS )_TorchCompileInductorWrapperinductorc                 C   s>   t  | _|| _| | | | | jddr:dtjd< d S )Ntriton.cudagraphsF1ZDISABLE_CUPTI_LAZY_REINIT)dictconfigdynamic
apply_modeapply_optionsr   rT   environ)r   rv   optionsrF  r   r   r   r     s    

z%_TorchCompileInductorWrapper.__init__c                 C   s"   t |to | j|jko | j|jkS r   )r   r@  rE  rF  r   r   r   r   r     s
    


z#_TorchCompileInductorWrapper.__eq__ru   c                 C   sN   |d ksJ|dkrn8|dkr:ddl m} | ||| j ntd| dd S )Nr   )zreduce-overheadzmax-autotunezmax-autotune-no-cudagraphsr   )list_mode_optionszUnrecognized mode=zV, should be one of: default, reduce-overhead, max-autotune, max-autotune-no-cudagraphs)torch._inductorrK  rH  rF  r   )r   rv   rK  r   r   r   rG    s    
z'_TorchCompileInductorWrapper.apply_mode)rJ  c           	      C   s   |sd S ddl m} | }| D ]\}}|dd}||kr\td| dt|  t|t|| k	rt|j	}t|| j	}td| d| d	| || j|< q$d S )
Nr   rE  -r`   zUnexpected optimization option z, known options are zUnexpected type of attr z, got z should be )
rL  rE  to_dictr   replacer   listkeysr   r   )	r   rJ  rE  Zcurrent_configkeyval	attr_nameZval_type_strZexpected_type_strr   r   r   rH    s"    
z*_TorchCompileInductorWrapper.apply_optionsc                 C   s   ddl m} |||| jdS )Nr   )
compile_fxZconfig_patches)torch._inductor.compile_fxrV  rE  )r   model_inputs_rV  r   r   r   __call__  s    z%_TorchCompileInductorWrapper.__call__c                 C   s   ddl m} || jdS )Nr   )get_patched_config_dictrW  )rX  r\  rE  )r   r\  r   r   r   get_compiler_config"  s    z0_TorchCompileInductorWrapper.get_compiler_configc                 C   sB   ddl m} d| jks|jjr>| jddr>ddlm} |  d S )Nr   rM  rB  T)reset_cudagraph_trees)rL  rE  tritonZ
cudagraphsr   Ztorch._inductor.cudagraph_treesr^  )r   rE  r^  r   r   r   reset&  s
    z"_TorchCompileInductorWrapper.resetN)r   r   r   compiler_namer   r   r   r   rG  r   r   rH  r[  r]  r`  r   r   r   r   r@    s   
r@  c                   @   s$   e Zd Zdd Zdd Zdd ZdS )_TorchCompileWrapperc                 C   sz   ddl m} t|tr|| _nt|dr2|j| _n
t|| _|| _||| _i | _	|rh|dkrh|| j	d< |rv|| j	d< d S )Nr   )lookup_backendr   r   rv   rJ  )
Ztorch._dynamo.backends.registryrc  r   r   ra  r   r   rF  compiler_fnkwargs)r   backendrv   rJ  rF  rc  r   r   r   r   .  s    





z_TorchCompileWrapper.__init__c                 C   s.   t |to,| j|jko,| j|jko,| j|jkS r   )r   rb  rd  re  rF  r   r   r   r   r   @  s    



z_TorchCompileWrapper.__eq__c                 C   s   | j ||f| jS r   )rd  re  )r   rY  rZ  r   r   r   r[  F  s    z_TorchCompileWrapper.__call__N)r   r   r   r   r   r[  r   r   r   r   rb  -  s   rb  rA  	fullgraphrF  rf  rv   rJ  disable)modelrh  rF  rf  rv   rJ  ri  rr   c                   s   t d tjdkrtd| dkrDtd fdd}|S dk	r\dk	r\tddkrpdkrpd	 d
krt nt  tj	j
 d| S )a  
    Optimizes given model/function using TorchDynamo and specified backend.

    Concretely, for every frame executed within the compiled region, we will attempt
    to compile it and cache the compiled result on the code object for future
    use.  A single frame may be compiled multiple times if previous compiled
    results are not applicable for subsequent calls (this is called a "guard
    failure), you can use TORCH_LOGS=guards to debug these situations.
    Multiple compiled results can be associated with a frame up to
    ``torch._dynamo.config.cache_size_limit``, which defaults to 64; at which
    point we will fall back to eager.  Note that compile caches are per
    *code object*, not frame; if you dynamically create multiple copies of a
    function, they will all share the same code cache.

    Args:
       model (Callable): Module/function to optimize
       fullgraph (bool): Whether it is ok to break model into several subgraphs
       dynamic (bool or None): Use dynamic shape tracing.  When this is True, we will up-front attempt
        to generate a kernel that is as dynamic as possible to avoid recompilations when
        sizes change.  This may not always work as some operations/optimizations will
        force specialization; use TORCH_LOGS=dynamic to debug overspecialization.
        When this is False, we will NEVER generate dynamic kernels, we will always specialize.
        By default (None), we automatically detect if dynamism has occurred and compile a more
        dynamic kernel upon recompile.
       backend (str or Callable): backend to be used

        - "inductor" is the default backend, which is a good balance between performance and overhead

        - Non experimental in-tree backends can be seen with `torch._dynamo.list_backends()`

        - Experimental or debug in-tree backends can be seen with `torch._dynamo.list_backends(None)`

        - To register an out-of-tree custom backend: https://pytorch.org/docs/main/compile/custom-backends.html
       mode (str): Can be either "default", "reduce-overhead", "max-autotune" or "max-autotune-no-cudagraphs"

        - "default" is the default mode, which is a good balance between performance and overhead

        - "reduce-overhead" is a mode that reduces the overhead of python with CUDA graphs,
          useful for small batches.  Reduction of overhead can come at the cost of more memory
          usage, as we will cache the workspace memory required for the invocation so that we
          do not have to reallocate it on subsequent runs.  Reduction of overhead is not guaranteed
          to work; today, we only reduce overhead for CUDA only graphs which do not mutate inputs.
          There are other circumstances where CUDA graphs are not applicable; use TORCH_LOG=perf_hints
          to debug.

        - "max-autotune" is a mode that leverages Triton based matrix multiplications and convolutions
          It enables CUDA graphs by default.

        - "max-autotune-no-cudagraphs" is a mode similar to "max-autotune" but without CUDA graphs

        - To see the exact configs that each mode sets you can call `torch._inductor.list_mode_options()`

       options (dict): A dictionary of options to pass to the backend. Some notable ones to try out are

        - `epilogue_fusion` which fuses pointwise ops into templates. Requires `max_autotune` to also be set

        - `max_autotune` which will profile to pick the best matmul configuration

        - `fallback_random` which is useful when debugging accuracy issues

        - `shape_padding` which pads matrix shapes to better align loads on GPUs especially for tensor cores

        - `triton.cudagraphs` which will reduce the overhead of python with CUDA graphs

        - `trace.enabled` which is the most useful debugging flag to turn on

        - `trace.graph_diagram` which will show you a picture of your graph after fusion

        - For inductor you can see the full list of configs that it supports by calling `torch._inductor.list_options()`
       disable (bool): Turn torch.compile() into a no-op for testing

    Example::

        @torch.compile(options={"triton.cudagraphs": True}, fullgraph=True)
        def foo(x):
            return torch.sin(x) + torch.cos(x)

    ztorch.compile)      z'Dynamo is not supported on Python 3.12+Nrj  c              	      s&   | d krt dt|  dS )NzModel can't be Nonerg  )r   rL   rm  rf  ri  rF  rh  rv   rJ  r   r   fn  s    zcompile.<locals>.fnzVEither mode or options can be specified, but both can't be specified at the same time.r   rA  )rf  ZnopythonrF  ri  )r   Z_log_api_usage_oncer   version_infor   r   r@  rb  r   _dynamooptimize)rj  rh  rF  rf  rv   rJ  ri  ro  r   rn  r   rL   J  s    U


)rN   c                 C   sd   t | j} tjt }t|| r<td|  dt||  dt	|| | d
t| g}|tj|< dS )zRegister an external runtime module of the specific :attr:`device_type`
    supported by torch.

    After the :attr:`module` is registered correctly, the user can refer
    the external runtime module as part of torch with attribute torch.xxx.
    zThe runtime module of 'z$' has already been registered with ''r_   N)r   r   r   r   r   r   r   r   getattrsetattrrW   )Zdevice_typer   mZtorch_module_namer   r   r   _register_device_module  s    

rw  )return_types)library)_meta_registrationsZTORCH_CUDA_SANITIZER)func)rM   c                  O   s&   dd l }|d d|d< tj| |S )Nr   zptorch._sparse_coo_tensor_unsafe is deprecated, use torch.sparse_coo_tensor(..., check_invariants=False) instead.FZcheck_invariants)warningsr   r   Zsparse_coo_tensor)rx   re  r|  r   r   r   _sparse_coo_tensor_unsafe  s    
r}  )compilerc                   @   sD   e Zd ZU ejddZi Zee	e
e
f ef ed< edd ZdS )_TritonLibraryr_  ZDEF	ops_tablec                 C   sJ   ||f| j kr<| j| | jd| || || j ||f< | j ||f S )Nztriton::)r  rR   Zdefineimpl)clsZop_keyZfull_schemaZop_implZdispatch_keyr   r   r   
registerOp  s
    z_TritonLibrary.registerOpN)r   r   r   r   ry  rP   rR   r  r   r   r   r   __annotations__classmethodr  r   r   r   r   r    s   
r  )Zhas_mpsZhas_cudaZ	has_cudnnZ
has_mkldnn)rq  )	_inductor)onnxrq  r  Z_exportr  c                 C   s   t | }|d k	rFdd l}|jd|  d|j d|j ddd | S | tkrhdd l}|d|  tS t	dt d	|  dd S )
Nr   rs  z' is deprecated, please use 'r_   z()'r   )
stacklevelzmodule 'z' has no attribute ')
_deprecated_attrsr   r|  r   r   r   _lazy_modules	importlibimport_moduleAttributeError)namereplacementr|  r  r   r   r   __getattr__  s    
&r  )_logging)N)N)N)N)N)N)N)N(7  r   r   rT   r   rg   textwraprk   inspectr   _utilsr
   r   Z_utils_internalr   r   r   r   r   Ztorch_versiontypingr   r   r   r   r   r   r   r   r   r   r   __all__getenvZpfiles_pathrU   rW   exec_prefixZpy_dll_pathr~   r}   Zth_dll_pathbase_exec_prefixZbase_py_dll_pathrQ  filterrV   Z	dll_pathsallZnvtoolsext_dll_pathversionr]   Zcuda_versionr^   rP  Zcuda_version_1Zcuda_path_varZdefault_pathZ	cuda_pathextendZWinDLLkernel32r   Zwith_load_library_flagsZSetErrorModeZprev_error_modeZc_void_pZLoadLibraryWrestypeZLoadLibraryExWZdll_pathZadd_dll_directoryrl   r   printZdllsZpath_patchedZdllZ	is_loadedresZget_last_errorZ
last_errorZWinErrorrz   strerrorrI  rp   r   rh   getdlopenflagsZ	old_flagssetdlopenflagsr   	RTLD_LAZYZtorch._Cr   rD   rE   rF   rG   rI   rH   rJ   rK   r   ImportErrorZ_C_for_compiled_checkdedentstripdirr  endswithappendrt  r   r   isclassr   attr	candidater   r   r   r   r   r   r   r   r   r   r;   r<   r=   r   r   r>   r?   rA   r@   rB   rC   r   r   r   r   r   r   r   r   r   r   r   r   Z_tensorr9   Zstorager   r7   r   r8   r   r5   r/   r0   r   r1   r2   r3   r4   r6   r  r  r  r  r  r  r  r	  r   setr
  r  r'  r    r!   r"   r#   r$   Zserializationr%   r&   Z_tensor_strr'   r  Z	torch.ampr  r   r   r   Ztorch._C._VariableFunctionsr  Z_segment_reduceZPRIVATE_OPSZ_VariableFunctions
startswithglobals_compiler  Z
functionalr  r   r  r  r  Ztorch.autogradr,   r-   r  r.   r  r  r  r  r  Ztorch.signalr  r   Ztorch.optim._multi_tensorr!  r"  r#  Ztorch.utils.backcompatr$  r%  r&  r(  r)  r*  Ztorch.utils.datar+  r,  r-  r.  Ztorch.nn.quantizableZtorch.nn.quantizedZtorch.nn.qatZtorch.nn.intrinsicZ_init_namesrS   r/  r0  r1  r2  Z
torch._opsr3  Ztorch._classesr4  r5  r6  Zcontiguous_formatZlegacy_contiguous_formatZtorch.multiprocessing._atforkr7  Zget_num_threadsZ_lobpcgr:   ZatenZquantized_lstmZquantized_gruZtorch.utils.dlpackr8  r9  r:  Z_linalg_utilsr;  r<  r=  r>  r?  Zsymeigr@  rb  rL   rN   rw  rx  ry  rz  Ztorch.cuda._sanitizerZ
_sanitizerZcsanZenable_cuda_sanitizerZ%torch.fx.experimental.symbolic_shapesr{  Z
torch.funcrM   r}  _initr~  r  Zis_builtrw   Zis_availableZmkldnnr  rq  r  r  r  r  r  Z
_init_logsr   r   r   r   <module>   s  
0                                             










"

2,3






	0. *A"















              		


	*B

 t



