
    Pg                       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lZddl	Z	ddl
Z
ddlZddlmZmZmZmZmZmZmZmZmZmZm Z!m"Z# ddl$m%Z& erddl'm(Z( dejR                  fdZ*dd	l+m,Z-m.Z.m/Z/ dd
l0m1Z1m2Z2m3Z3m4Z4  e*       rdZ5es$ddl$Z$e$jl                  Z7e7e$_8        nddl$m8Z7 ddl9m5Z5 g dZ:e: e;e:      k(  sJ e	j                  dk(  rddZ< e<        [<de=de=ddfdZ>ddZ?e4s ej                  d      rn e*       s ej                         dk7  rS e	j                         ZC e	j                  ej                  ej                  z         ddlG  e	j                  eC       [Cne3r e?        ddlG  G d d      ZH G d d      ZI G d d      ZJd ZKd ZLd  ZMd! ZNdeeed"f   eed"f   f   fd#ZOd$ ZPd% ZQd& ZRd'\  ZSZTZUd(D ]'  ZTd)eT ZU eReT      ZSeUxeS_V        eS_W        eS eX       eU<   ) [S[T[U[R eX       d*   ZYe:j                  d+       d, Z[d- Z\	 dd.lGm]Z] dd0ldm_Z_ d1\  ZTZe efe_      D ]  ZTeTd   d2k7  rceTj                  d3      sRe:j                  eT        ehe_eT      Ze eiee      s ej                  ee      sQeej                  eWk7  saeTd4vsfeWee_k        neTd5k(  st ele	j                  eW   eT        [T[eesdd6Zn ene_       [nd7ede=fd8Zod7ede7d9   fd:Zpd7ede7e#d;      fd<Zq ej                         asdd>Ztd?ee#d=e=ej                  f      ddfd@ZvdAe#ed9   e=f   ddfdBZwddCZxdDdEdFejR                  dGejR                  ddfdHZydejR                  fdIZzdejR                  fdJZ{dKe#ej                  e=f   ddfdLZ|dej                  fdMZ}de=fdNZ~dOe=ddfdPZdQejR                  ddfdRZdejR                  fdSZdTe#ejR                  eJf   dUeg e=f   fdVZddWZddXZddYZddZZdd[Zdd\Zdd]Zdd^Zdd_lmZmZmZmZ dZded`<   e:j#                  g da       ddblmZ ddcldmZ dddlmZmZmZmZmZ  G de dfe      Z G dg dhe      Z G di dje      Z G dk dle      Z G dm dne      Z G do dpe      Z G dq dre      Z G ds dte      Z G du dve      Z G dw dxe      Z G dy dze      Z G d{ d|e      Z G d} d~e      Z G d de      Z G d de      Z G d de      Z G d de      ZeeeeeeeeeeeeeeeeeeehZeee#eef         ed<    e       Zeed9      ed<   ddldmZmZmZ ddlmZ ddlmZmZ ddlmZmZmZmZmZ ddlmZmZ d Z e_j                   e              [erddl eZ[dZd1\  ZTZe efe_j                        D ]v  ZTeTj                  d      seTev r ehe_j                  eT      ZeeWee_k        eTdk(  ree eX       eT<   d2eTz   ZTee eX       eT<   eTj                  d2      rfe:j                  eT       x [T[eddldZde:j#                  d  efed      D               ddlmZ ddldmZmZ ddl˭ [[d ZddlmZmZmZmZ ddldmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm'Z'mZmZ ddlmZ ddldmZ ddlZdddlZdddlZdddlZd e_j                   ee             ddldmZmZmZmZ [[[[dejR                  fdZddldmZmZ ddlmZ ddl mZ e	j                  j                  eW de       e	j                  j                  eW de       ddldmZ ddldmZ eZddlmZ  eedj                         [ddl
mZ ej                  j                  Zej                  j                  ZddldmZ ddlmZmZmZmZmZ ddlmZmZ  G d d      Z G d d      Z e&d      Z e!d      ZedDdddddDddeeef   dejR                  deejR                     de#e=ef   dFe#e=df   deee=e#e=ej                  ejR                  f   f      dejR                  deeef   fd       Ze	 ddDdddddDddddejR                  deejR                     de#e=ef   dFe#e=df   deee=e#e=ej                  ejR                  f   f      dejR                  deeeef   geeef   f   fd       Z	 ddDdddddDddee   dejR                  deejR                     de#e=ef   dFe#e=df   deee=e#e=ej                  ejR                  f   f      dejR                  de#eeeef   geeef   f   eeef   f   fdZd Zddldm Z m!Z!m"Z"m#Z# ddl$m%Z%m&Z& ddl'm(Z( esddldm)Z) dejT                  v rddl+mc m,Z-  e-j\                          ddl/Zdddldm0Z0 edj                  j                  jc                           e*       sddldm2Z2  G d d«      Z3edj                  j                  jh                  edj                  j                  jh                  edj                  jj                  jl                  edj                  jn                  jl                  dÜZ8erddldm9Z9m:Z:m;Z;m<Z< n	h dţZ=dƄ Z>dd?ee#edj~                  e=f      fdǄZ@	 	 ddeej                     deej                     fdʄZAddldmBZB  eBj                          d̄ ZDdejR                  fd̈́ZE eE       r eD        d΄ ZFy# e^$ r; ddlGm_Z` e`j                  ' e^ e
j                  d/      j                               d w xY w)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.
    N)AnyCallableDict
get_originOptionaloverloadSetTupleTypeTYPE_CHECKINGTypeVarUnion)	ParamSpec   )IntLikeTypereturnc                  N    t         j                  j                  dd       t        u S )Nztorch._meta_registrations)sysmodulesgetobject     U/var/www/html/suriana-translation/venv/lib/python3.12/site-packages/torch/__init__.py_running_with_deployr   0   s    ;;??6=GGr   )_functionalize_sync_import_dotted_nameclassproperty)get_file_path#prepare_multiprocessing_environmentUSE_GLOBAL_DEPSUSE_RTLD_GLOBAL_WITH_LIBTORCHztorch-deploy-1.8)TypeIs)__version__)GBoolStorage
BoolTensorByteStorage
ByteTensorCharStorage
CharTensorDoubleStorageDoubleTensorFloatStorageFloatTensor
GradScaler
IntStorage	IntTensorLongStorage
LongTensorShortStorageShortTensorSymBoolSymFloatSymIntTensorTypedStorageUntypedStorage$are_deterministic_algorithms_enabledautocastchunkcompilecondenable_gradexportget_default_deviceget_deterministic_debug_modeget_device_moduleget_float32_matmul_precisionget_rng_stateinference_modeinitial_seed-is_deterministic_algorithms_warn_only_enabled
is_storage	is_tensoris_warn_always_enabledloadlobpcgmanual_seedmatmulno_gradrandrandnsaveseedset_default_deviceset_default_tensor_typeset_deterministic_debug_modeset_float32_matmul_precisionset_printoptionsset_rng_stateset_warn_alwayssplitstack	sym_floatsym_fresh_sizesym_intsym_itesym_maxsym_minsym_notsym_sumtypenameunravel_indexuse_deterministic_algorithmsvmapwin32c            
      	   dd l } ddlm} t        j                  dd      }t        j
                  j                  t        j                  dd      }t        j
                  j                  t        j
                  j                  t              d      }t        j
                  j                  | j                  d      dd      }t        j                  t        j                  k7  r0t        j
                  j                  t        j                  dd      }nd	}||||fD cg c]#  }t        j
                  j                  |      r|% }}t        j                  d
 |D              sUt        j
                  j                  t        j                  dt        j
                  j                  |dd            dd      }	nd	}	|rt        j                   d |D              rq|j#                  dd      }
d|
z   }t        j
                  j                  |ddd|       }t        j
                  j                  t        j                  ||      d      }nd	}|j%                  d |	|fD               t'        j(                  dd      }t+        |d      }|j-                  d      }t&        j.                  |j0                  _        |rt&        j.                  |j4                  _        |D ]  }t        j6                  |        	 t'        j8                  d       t'        j8                  d       t;        j<                         dk7  rt'        j8                  d       tI        jH                  t        j
                  j                  |d!            }d"}|D ]  }d"}|rb|j5                  |d d#      }t'        jJ                         }|5|d$k7  r0t'        jL                  |      }|xjN                  d%| d&z  c_'        ||d}|rl|s9d'j                  |t        jP                  d(   gz         t        jP                  d(<   d}|j1                  |      }|t'        jL                  t'        jJ                               }|xjN                  d%| d&z  c_'        | |j-                  |       y c c}w # t>        $ r0 tA        tC        jD                  d       jG                                Y w xY w))Nr   )cudaProgramFileszC:\Program FilesLibrarybinlibuserbase c              3      K   | ]A  }t         j                  j                  t         j                  j                  |d              C yw)znvToolsExt64_1.dllN)ospathexistsjoin.0ps     r   	<genexpr>z&_load_dll_libraries.<locals>.<genexpr>   s2      
FGBGGNN277<<+?@A
s   AA	NVTOOLSEXT_PATHzNVIDIA Corporation
NvToolsExtx64c              3      K   | ]8  }t        j                   t        j                  j                  |d               : yw)zcudart64*.dllN)globrv   rw   ry   rz   s     r   r}   z&_load_dll_libraries.<locals>.<genexpr>   s0      )
@A		"'',,q/:;;)
s   >A ._CUDA_PATH_VzNVIDIA GPU Computing ToolkitCUDAvc              3   `   K   | ]&  }t         j                  j                  |      s#| ( y wN)rv   rw   rx   rz   s     r   r}   z&_load_dll_libraries.<locals>.<genexpr>   s$      
277>>!;LA
s   $..zkernel32.dllT)use_last_errorAddDllDirectoryr   zvcruntime140.dllzmsvcp140.dllARM64zvcruntime140_1.dllz
                    Microsoft 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.exe
                    z*.dllFi   ~   z Error loading "z" or one of its dependencies.;PATH))	sysconfigtorch.versionrn   rv   getenvrw   ry   r   exec_prefixdirname__file__get_config_varbase_exec_prefixrx   builtinsanyallreplaceextendctypesWinDLLhasattrSetErrorModec_void_pLoadLibraryWrestypeLoadLibraryExWadd_dll_directoryCDLLplatformmachineOSErrorprinttextwrapdedentstripr   get_last_errorWinErrorstrerrorenviron)r   cuda_versionpfiles_pathpy_dll_pathth_dll_pathusebase_pathbase_py_dll_pathr|   	dll_pathsnvtoolsext_dll_pathcuda_version_1cuda_path_vardefault_path	cuda_pathkernel32with_load_library_flagsprev_error_modedll_pathdllspath_patcheddll	is_loadedres
last_errorerrs                            r   _load_dll_librariesr      s   6ii0CDggll3??IuEggll277??8#<eDww||$$Z0)U
 ??c222!ww||C,@,@)US! ";0@,O
ww~~a  
	 
 || 
KT
 
 #%'',,		%GGLL.BLQ # #%HLL )
EN)
 
 *11#s;N)N:M77<<;VqEWL RYY}l%KUSII 
+Y7
 	
 ==E")(4E"F"//7(.%".4ooH##+! 	+H  *	+	KK*+KK'!W,01 yyk7;< 	CI&--c4D#224
;:#4 //*5CLL*3%/LML I_ $I#),)rzz&?Q>R2R)SBJJv&#'L++C0; //&*?*?*ABCLL*3%/LML I/	2 	o.s
h  	
 %'	s   (R5AR 5SS
lib_folderlib_namec           	      J   t        j                         dk(  sJ d       d}t        j                  D ]  }t        j                  j                  |d      }t        j                  j                  |      sCt        j                  t        j                  j                  || d|            }|s5t        j                  t        j                  j                  || d|            }|r|s|d   }|s n |st        | dt        j                         t        j                  |       y)z8Preloads cuda deps if they could not be found otherwise.LinuxzShould only be called on LinuxNnvidiarr   r   z not found in the system path )r   systemr   rw   rv   ry   rx   r   
ValueErrorr   r   )r   r   lib_pathrw   nvidia_pathcandidate_lib_pathss         r   _preload_cuda_depsr     s     ??'I)II'H ggll42ww~~k*"iiGGLLj%B
 #"&))T:uh?# x*1-H!" H:%CCHH:NOO
KKr   c                     t               st        j                         dk(  ry t        j                         dk(  rdnd} d|  }t        j                  j                  t              }t        j                  j                  t        j                  j                  |      d|      }	 t        j                  |t        j                         	 t        d      5 }|j                         }d d d        d	vry t        d
d       t        dd       y # 1 sw Y   'xY w# t        $ r Y y w xY w# t         $ r}dddddddddddddd}|j#                         D cg c](  }|j%                  d      d   |j&                  d   v s'|* nc c}w }	}|	s||j)                         D ]  \  }
}t        |
|        t        j                  |t        j                         Y d }~y d }~ww xY w)NWindowsDarwinz.dylibz.solibtorch_global_depsrr   )modez/proc/self/mapsz$nvidia/cuda_runtime/lib/libcudart.so
cuda_nvrtczlibnvrtc.so.*[0-9]	nvjitlinkzlibnvJitLink.so.*[0-9]zlibcublas.so.*[0-9]zlibcudnn.so.*[0-9]zlibcudart.so.*[0-9]zlibcupti.so.*[0-9]zlibcufft.so.*[0-9]zlibcurand.so.*[0-9]zlibcusparse.so.*[0-9]zlibcusparseLt.so.*[0-9]zlibcusolver.so.*[0-9]zlibnccl.so.*[0-9]zlibnvToolsExt.so.*[0-9])cublascudnnr   cuda_runtime
cuda_cupticufftcurandr   cusparse
cusparseltcusolverncclnvtxr   r   )r   r   r   rv   rw   abspathr   ry   r   r   r   RTLD_GLOBALopenreadr   	Exceptionr   valuesr^   argsitems)lib_extr   hereglobal_deps_lib_pathf_mapsr   	cuda_libsrr   is_cuda_lib_errr   s              r   _load_global_depsr   3  s   !2i!? #//+x7hUG%gY/H77??8$D77<<(=uhO.C(v/A/AB	'( !A! 6UB |-AB{,DE! !  		  C ,).1.)+1/3/'-&
	  %++-
31Bchhqk1QC
 
 
 I$-OO$5 	5 Jz84	5(v/A/ABB3Csg   %%D( D D'D 4D DD 	D%"D( $D%%D( (	G1"G(F<F AGGTORCH_USE_RTLD_GLOBALr   )*c                      e Zd ZdZd Zd Zd Zd Zd.dZd Z	d	 Z
d
 Zd Zd Zd Zdedej"                  fdZdej"                  fdZdej"                  fdZdej"                  fdZdej"                  fdZd/dZd/dZd/dZd0dZd/dZd/dZd/dZd1dZd1dZd1dZ d1dZ!d  Z"d! Z#d" Z$d# Z%d0d$Z&d0d%Z'd/d&Z(d/d'Z)d( Z*d) Z+dejX                  fd*Z-de.d ejX                  f   fd+Z/dejX                  fd,Z0d/d-Z1y)2r8   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                     || _         y r   nodeselfr   s     r   __init__zSymInt.__init__       	r   c                 2    t        j                  | dk7        S Nr   )r   boolr   s    r   __bool__zSymInt.__bool__  s    }}TQY''r   c                 6    | j                   j                         S r   r   int_r  s    r   __int__zSymInt.__int__      yy~~r   c                 6    | j                   j                         S r   r  r  s    r   	__index__zSymInt.__index__  r
  r   Nc                     | S r   r   )r   ndigitss     r   	__round__zSymInt.__round__      r   c                     t        |t        j                  t        f      rt	        |       j                  |      S t        |t        j                  t        f      st        S | j                  |      S r   )

isinstancer   floatr7   r`   __float_truediv__intr8   NotImplemented__int_truediv__r   others     r   __truediv__zSymInt.__truediv__  sT    ehnnh78T?44U;;%(,,!78!!##E**r   c                     t        |t        j                  t        f      rt	        |       j                  |      S t        |t        j                  t        f      st        S | j                  |      S r   )
r  r   r  r7   r`   __rfloat_truediv__r  r8   r  __rint_truediv__r  s     r   __rtruediv__zSymInt.__rtruediv__  sT    ehnnh78T?55e<<%(,,!78!!$$U++r   c                    t        |t        j                  t        f      r*t	        t        j                  t	        |       |z              S t        |t        j                  t        f      st        S | j                  |      S r   )r  r   r  r7   r`   mathfloorr  r8   r  __int_floordiv__r  s     r   __floordiv__zSymInt.__floordiv__  s\    ehnnh78TZZ	$%(?@AA%(,,!78!!$$U++r   c                    t        |t        j                  t        f      r*t	        t        j                  |t	        |       z              S t        |t        j                  t        f      st        S | j                  |      S r   )r  r   r  r7   r`   r   r!  r  r8   r  __rint_floordiv__r  s     r   __rfloordiv__zSymInt.__rfloordiv__  s\    ehnnh78TZZ	$(?@AA%(,,!78!!%%e,,r   c                 4   t        |t        j                  t        f      rt	        |       j                  |      S t        |t        j                  t        f      st        S |dk\  r| j                  |      S t	        |       j                  t	        |            S r  )
r  r   r  r7   r`   __pow__r  r8   r  __pow_by_natural__r  s     r   r(  zSymInt.__pow__  sy    ehnnh78T?**511%(,,!78!! A:**511 T?**9U+;<<r   c                 4   t        |t        j                  t        f      rt	        |       j                  |      S t        |t        j                  t        f      st        S | dk\  r| j                  |      S t	        |       j                  t	        |            S r  )
r  r   r  r7   r`   __rpow__r  r8   r  __rpow_by_natural__r  s     r   r+  zSymInt.__rpow__  su    ehnnh78T?++E22%(,,!78!!19++E22T?++Ie,<==r   r  r   c                     t        d      Ntype stub not overridden	TypeErrorr  s     r   __eq__zSymInt.__eq__      233r   c                     t        d      r.  r0  r  s     r   __lt__zSymInt.__lt__  r3  r   c                     t        d      r.  r0  r  s     r   __gt__zSymInt.__gt__  r3  r   c                     t        d      r.  r0  r  s     r   __le__zSymInt.__le__  r3  r   c                     t        d      r.  r0  r  s     r   __ge__zSymInt.__ge__   r3  r   c                     t        d      r.  r0  r  s     r   __add__zSymInt.__add__  r3  r   c                     t        d      r.  r0  r  s     r   __radd__zSymInt.__radd__  r3  r   c                     t        d      r.  r0  r  s     r   __rmul__zSymInt.__rmul__	  r3  r   c                     t        d      r.  r0  r  s     r   __mod__zSymInt.__mod__  r3  r   c                     t        d      r.  r0  r  s     r   __mul__zSymInt.__mul__  r3  r   c                     t        d      r.  r0  r  s     r   r)  zSymInt.__pow_by_natural__  r3  r   c                     t        d      r.  r0  r  s     r   r,  zSymInt.__rpow_by_natural__  r3  r   c                     t        d      r.  r0  r  s     r   r  zSymInt.__int_truediv__  r3  r   c                     t        d      r.  r0  r  s     r   r  zSymInt.__rint_truediv__  r3  r   c                     t        d      r.  r0  r  s     r   r"  zSymInt.__int_floordiv__  r3  r   c                     t        d      r.  r0  r  s     r   r%  zSymInt.__rint_floordiv__!  r3  r   c                     t        d      r.  r0  r  s     r   __sym_max__zSymInt.__sym_max__$  r3  r   c                     t        d      r.  r0  r  s     r   __sym_min__zSymInt.__sym_min__'  r3  r   c                     t        d      r.  r0  r  s    r   __sym_float__zSymInt.__sym_float__*  r3  r   c                     t        d      r.  r0  r  s    r   __neg__zSymInt.__neg__-  r3  r   c                     t        d      r.  r0  r  s     r   __sub__zSymInt.__sub__0  r3  r   c                     t        d      r.  r0  r  s     r   __rsub__zSymInt.__rsub__3  r3  r   c                     t        d      r.  r0  r  s     r   __and__zSymInt.__and__6  r3  r   c                     t        d      r.  r0  r  s     r   __or__zSymInt.__or__9  r3  r   c                 6    | j                   j                         S r   r   _graph_reprr  s    r   __repr__zSymInt.__repr__<      yy$$&&r   c                 .    | j                   j                  S r   r   exprr  s    r   _sympy_zSymInt._sympy_?      yy~~r   c                     | j                   j                         r#t        | j                   j                               S t	        d      )Nz"unhashable type: non-nested SymInt)r   is_nested_inthash
nested_intr1  r  s    r   __hash__zSymInt.__hash__B  s8    99""$		,,.// @AAr   c                 
    | dfS )z,Represent this int as an exact integer ratior   r   r  s    r   as_integer_ratiozSymInt.as_integer_ratioN  s    Qwr   c                 H    t        j                  |       j                         S r   )r   r  
bit_lengthr  s    r   rn  zSymInt.bit_lengthR  s    
 ||D!,,..r   c                     | S r   r   r  s    r   	conjugatezSymInt.conjugateY  r  r   r   )r   r8   )r  r   r   r8   r   r7   )2__name__
__module____qualname____doc__r   r  r	  r  r  r  r  r#  r&  r(  r+  r   r   r  r2  r5  r7  r9  r;  r=  r?  rA  rC  rE  r)  r,  r  r  r"  r%  rM  rO  rQ  rS  rU  rW  rY  r[  r_  rd  r  rj  _Tuplerl  rn  rp  r   r   r   r8   r8     s?   
(  
+,,-=0>4F 4x}} 44x}} 44x}} 44x}} 44x}} 44444444444444444444'B(,, B&8<<)?"@ /HLL /r   r8   c                      e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zdedej                  fdZdej                  fdZdej                  fdZdej                  fdZdej                  fdZd"dZd"dZd"dZd"dZd Zd Zd Zd Zd Zdeej>                  ej>                  f   fdZ d Z!d Z"d Z#d"dZ$de%fd Z&y!)#r7   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                     || _         y r   r   r   s     r   r   zSymFloat.__init__d  r   r   c                     t        |t        j                  t        j                  t        t
        f      st        S | j                  t        |            S r   )	r  r   r  r  r8   r7   r  r  r`   r  s     r   r  zSymFloat.__truediv__i  s9    %(,,!QR!!%%i&677r   c                     t        |t        j                  t        j                  t        t
        f      st        S | j                  t        |            S r   )	r  r   r  r  r8   r7   r  r  r`   r  s     r   r  zSymFloat.__rtruediv__n  s9    %(,,!QR!!&&y'788r   c                     t        |t        j                  t        j                  t        t
        f      st        S t        t        j                  | t        |      z              S r   
r  r   r  r  r8   r7   r  r`   r   r!  r  s     r   r#  zSymFloat.__floordiv__s  sA    %(,,!QR!!D9U+;$;<==r   c                     t        |t        j                  t        j                  t        t
        f      st        S t        t        j                  t        |      | z              S r   r|  r  s     r   r&  zSymFloat.__rfloordiv__x  sA    %(,,!QR!!Ie$4t$;<==r   c                 6    | j                   j                         S r   r   bool_r  s    r   r  zSymFloat.__bool__}      yy  r   c                 :    | j                   j                  dd      S )Nrt   r   )r   guard_floatr  s    r   	__float__zSymFloat.__float__  s    yy$$R++r   c                     t        |t        j                  t        j                  t        t
        f      st        S t        j                  | dk\         | j                  |      S r  )
r  r   r  r  r8   r7   r  torch_check__float_pow__r  s     r   r(  zSymFloat.__pow__  sD    %(,,!QR!!TQY!!%((r   c                     t        |t        j                  t        j                  t        t
        f      st        S t        j                  |dk\         | j                  |      S r  )
r  r   r  r  r8   r7   r  r  r  __rfloat_pow__r  s     r   r+  zSymFloat.__rpow__  sD    %(,,!QR!!UaZ ""5))r   r  r   c                     t        d      r.  r0  r  s     r   r2  zSymFloat.__eq__  r3  r   c                     t        d      r.  r0  r  s     r   r5  zSymFloat.__lt__  r3  r   c                     t        d      r.  r0  r  s     r   r7  zSymFloat.__gt__  r3  r   c                     t        d      r.  r0  r  s     r   r9  zSymFloat.__le__  r3  r   c                     t        d      r.  r0  r  s     r   r;  zSymFloat.__ge__  r3  r   c                     t        d      r.  r0  r  s     r   r  zSymFloat.__float_pow__  r3  r   c                     t        d      r.  r0  r  s     r   r  zSymFloat.__rfloat_pow__  r3  r   c                     t        d      r.  r0  r  s     r   r  zSymFloat.__float_truediv__  r3  r   c                     t        d      r.  r0  r  s     r   r  zSymFloat.__rfloat_truediv__  r3  r   c                     t        d      r.  r0  r  s    r   	__trunc__zSymFloat.__trunc__  r3  r   c                     t        d      r.  r0  r  s     r   rM  zSymFloat.__sym_max__  r3  r   c                     t        d      r.  r0  r  s     r   rO  zSymFloat.__sym_min__  r3  r   c                     t        d      r.  r0  r  s    r   __sym_int__zSymFloat.__sym_int__  r3  r   c                     t        d      )z'Return True if the float is an integer.r/  r0  r  s    r   
is_integerzSymFloat.is_integer  s    233r   c                 H    t        j                  |       j                         S )z.Represent this float as an exact integer ratio)r   r  rl  r  s    r   rl  zSymFloat.as_integer_ratio  s    ~~d#4466r   c                 6    | j                   j                         S r   r]  r  s    r   r_  zSymFloat.__repr__  r`  r   c                 .    | j                   j                  S r   rb  r  s    r   rd  zSymFloat._sympy_  re  r   c                 >    t        t        j                  |             S r   )rh  r   r  r  s    r   rj  zSymFloat.__hash__  s    HNN4())r   c                     | S )z+Returns the complex conjugate of the float.r   r  s    r   rp  zSymFloat.conjugate  s    r   c                 V    | j                   j                  dd      j                         S )z4Returns the hexadecimal representation of the float.rt   r   )r   r  hexr  s    r   r  zSymFloat.hex  s"    yy$$R+//11r   Nrq  )'rr  rs  rt  ru  r   r  r  r#  r&  r  r  r(  r+  r   r   r  r2  r5  r7  r9  r;  r  r  r  r  r  rM  rO  r  r  rv  r  rl  r_  rd  rj  rp  strr  r   r   r   r7   r7   ]  s    
8
9
>
>
!,
)*4F 4x}} 44x}} 44x}} 44x}} 44x}} 44444444447&x||)C"D 7'*2S 2r   r7   c                   r    e Zd ZdZd Zd Zd ZddZddZddZ	d	 Z
dej                  fd
Zd Zd Zd Zy)r6   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                     || _         y r   r   r   s     r   r   zSymBool.__init__  r   r   c                 6    | j                   j                         S r   r  r  s    r   r  zSymBool.__bool__  r  r   c                 \    t        j                  | j                  j                               S r   )r   r  r   r  r  s    r   r	  zSymBool.__int__  s    ||DIIOO-..r   r   c                     t        d      r.  r0  r  s     r   rY  zSymBool.__and__  r3  r   c                     t        d      r.  r0  r  s     r   r[  zSymBool.__or__  r3  r   c                     t        d      r.  r0  r  s    r   __sym_not__zSymBool.__sym_not__  r3  r   c                     t        d      r.  r0  )r   then_valelse_vals      r   __sym_ite__zSymBool.__sym_ite__  r3  r   c                     t        d      r.  r0  r  s     r   r2  zSymBool.__eq__  r3  r   c                 6    | j                   j                         S r   r]  r  s    r   r_  zSymBool.__repr__
  r`  r   c                 .    | j                   j                  S r   rb  r  s    r   rd  zSymBool._sympy_  re  r   c                     | j                   j                         r#t        | j                   j                               S t        t	        j
                  |             S r   )r   is_constantrh  r  r   r  r  s    r   rj  zSymBool.__hash__  s>    99  "		)** d+,,r   N)r   r6   )rr  rs  rt  ru  r   r  r	  rY  r[  r  r  r   r  r2  r_  rd  rj  r   r   r   r6   r6     sI    
!/44(444x}} 4'-r   r6   c                     ddl }t        j                  |       rt        j                  t        | f|       S t        | d      r| j                         S t        | |j                        r|  S |  S )zhSymInt-aware utility for logical negation.

    Args:
        a (SymBool or bool): Object to negate
    r   Nr  )	sympy	overrideshas_torch_function_unaryhandle_torch_functionrf   r   r  r  Basic)ar  s     r   rf   rf     s^     ))!,..wa@@q- }}!U[[!r	5Lr   c                     t        j                  |       rt        j                  t        | f|       S t	        | t
              r| S t        | d      r| j                         S t        j                  |       S )zoSymInt-aware utility for float casting.

    Args:
        a (SymInt, SymFloat, or object): Object to cast
    rQ  )
r  r  r  r`   r  r7   r   rQ  r   r  r  s    r   r`   r`   )  s^     ))!,..y1$BB!X	O	$  >>!r   c                     t        j                  |       rt        j                  t        | f|       S t	        | t
              r| S t	        | t              rt        j                  |       S t        j                  |       S )zmSymInt-aware utility for int casting.

    Args:
        a (SymInt, SymFloat, or object): Object to cast
    )r  r  r  rb   r  r8   r7   r   truncr   r  r  s    r   rb   rb   8  s^     ))!,..wa@@!V	Ax	 zz!}<<?r   c                 @   t        j                  | |f      rt        j                  t        | |f| |      S t	        | t
        t        f      r| j                  |      S t	        |t
        t        f      r|j                  |       S t               \  }}t	        | |      sJ t        |              t	        ||      sJ t        |             t	        | |      st	        ||      r)t        j                  t        j                  | |            S t        j                  | |      S )a  
    SymInt-aware utility for max which avoids branching on a < b.
    Unlike builtins.max(), this only works for int/float, and it always
    promotes to float if any argument is float (unlike builtins.max, which
    will faithfully preserve the type of the input argument).
    )r  has_torch_functionr  rd   r  r8   r7   rM  __all_and_float_typestyper   r  maxr  b	all_typesfloat_typess       r   rd   rd   G  s     ##QF+..wA1EE!fh'(}}Q	A)	* }}Q 34I{a#,T!W,#a#,T!W,#![!Z;%?~~hll1a011||Aq!!r   .c                  >   	 dd l } | j                  | j                  t        j                  t        j
                  f}| j                  t        j
                  f}||fS # t        $ r7 t        j                  t        j
                  f}t        j
                  f}Y ||fS w xY wr  )numpyintegerfloatingr   r  r  ModuleNotFoundError)npr  r  s      r   r  r  b  s    ( JJKKLLNN	)
	 ,.;;*G
 k!!	  (\\8>>2	~~'k!!	(s   AA :BBc                 @   t        j                  | |f      rt        j                  t        | |f| |      S t	        | t
        t        f      r| j                  |      S t	        |t
        t        f      r|j                  |       S t               \  }}t	        | |      sJ t        |              t	        ||      sJ t        |             t	        | |      st	        ||      r)t        j                  t        j                  | |            S t        j                  | |      S )zSymInt-aware utility for min().)r  r  r  re   r  r8   r7   rO  r  r  r   r  minr  s       r   re   re   t  s    ##QF+..wA1EE!fh'(}}Q	A)	*}}Q24I{a#,T!W,#a#,T!W,#![!Z;%?~~hll1a011||Aq!!r   c                    t        j                  |       rt        j                  t        | |       S d| D ]V  }t	        |t
        t        j                  f      st        j                  |       c S t	        |t
              sK|j                  X t        j                  |       S ddl
mm}  |j                  t        fd| D                          S )z
    N-ary add which is faster to compute for long lists than iterated binary
    addition.  Only does something special for integers.
    Nr   )to_node	wrap_nodec              3   0   K   | ]  } |        y wr   r   )r{   r  foundr  s     r   r}   zsym_sum.<locals>.<genexpr>  s     (Iq):(Is   )r  r  r  rg   r  r8   r   r  sumr   torch.fx.experimental.sym_noder  r  tuple)r   r  r  r  r  s      @@r   rg   rg     s    
 ##D)..wdCCE !fhll34<<%%a FFE	
 }||D!!AU]]5(ID(I#IJKKr   c                       fdS )Nc                    t        j                  |       rt        j                  | f|       S t        | t              rt        j                  |       } t        | d d      r t        | d d             S  t        t              |       S )N__sym___)
r  r  r  r  r8   r  r`   r   getattrr   )r  fnnames    r   r  z_get_sym_math_fn.<locals>.fn  s    --a0222tQ??a "A1tfB'(071tfB/022"wtT"1%%r   r   )r  r  s   `@r   _get_sym_math_fnr    s    & Ir   )Nrt   rt   )sqrtcoscoshsinsinhtantanhasinacosatanlog2_sym_	_sym_sqrtsym_sqrtc                 4   t        j                  | ||f      r t        j                  t        | ||f| ||      S t	        | t
        t        j                  f      rt        |      t        |      k(  sJ t	        | t
              r| j                  ||      S | r|S |S r   )
r  r  r  rc   r  r6   r   r  r  r  )r  tr   s      r   rc   rc     s    ##Q1I...wAq	1aKKa'8==12tAw$q'7III!W}}Q""1qr   c                 H    t        j                  |       j                         S r   )r  tensoritem)rc  s    r   ra   ra     s    <<""$$r   )_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.
                )_C)rt   Nr   Base>   	GeneratorDisableTorchFunctionDisableTorchFunctionSubclass
TensorBasec                 Z   |
t               }| |v ry |j                  |        | j                  }t        |       D ]o  }t	        | |      }t	        |dd      }t        j                  |      s2|j                  |      sDt        j                  j                  ||       t        ||       q y )Nrr  rt   )setaddrr  dirr  inspectismodule
startswithr   r   
setdefault _import_extension_to_sys_modules)modulememomodule_namer  membermember_names         r   r  r    s    <5DT>ooK 	?DVT*F!&*b9K'K,B,B;,O&&{F;0>	?r   objc                Z   t        | t        j                        r| j                         S t	        | dd      xs d}d}t        | d      r| j                  }nIt        | d      r| j                  }n0| j                  j                  xs d}| j                  j                  }|dv r|S | d| S )a  
    String representation of the type of an object.

    This function returns a fully qualified string representation of an object's type.
    Args:
        obj (object): The object whose type to represent
    Returns:
        str: the type of the object `o`
    Example:
        >>> x = torch.tensor([1, 2, 3])
        >>> torch.typename(x)
        'torch.LongTensor'
        >>> torch.typename(torch.nn.Parameter)
        'torch.nn.parameter.Parameter'
    rs  rt   rt  rr  >   rt   r   r   )
r  r  r9   r  r  r   rt  rr  	__class__rs  )r	  r  qualnames      r   rh   rh   %  s      #u||$xxzS,+1rFHsN###	j	!<<))/R==--!!XQxj!!r   ztorch.Tensorc                6    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   r	  s    r   rL   rL   H  s    " c5<<((r   )r:   r;   c                $    t        |       t        v S )zgReturns True if `obj` is a PyTorch storage object.

    Args:
        obj (Object): Object to test
    )r  _storage_classesr  s    r   rK   rK   \  s     9(((r   torch.devicec                      t        t        d      rGt        j                  j                  } | j                  | S t        j                  g       j                  S t        j                  d      S )z?Gets the default ``torch.Tensor`` to be allocated on ``device``device_contextcpu)r   _GLOBAL_DEVICE_CONTEXTr  deviceindexr  r  )r  s    r   rC   rC   h  sV     %'78'66==<<#M <<#***||E""r   r  c                     t        t        d      r%t        j                  }||j                  ddd       | d}|t        _        yddlm}  ||       }|j                          |t        _        y)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

    .. note::

        This doesn't affect functions that create tensors that share the same memory as the input, like:
        :func:`torch.from_numpy` and :func:`torch.frombuffer`

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

    Example::

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

    r  Nr   )DeviceContext)r   r  r  __exit__torch.utils._devicer  	__enter__)r  r  r  s      r   rW   rW   x  sm    b %'78/>>%##D$5~ -;)	 	6&v.  ",:)r   r  c                d    t        | t              rt        |       } t        j                  |        y)a  
    .. warning::

        This function is deprecated as of PyTorch 2.1, please use :func:`torch.set_default_dtype()` and
        :func:`torch.set_default_device()` as alternatives.

    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   r  _set_default_tensor_type)r  s    r   rX   rX     s&    4 !S""r   c                .    t        j                  |        y)a	  

    Sets the default floating point dtype to :attr:`d`. Supports floating point dtype
    as inputs. Other dtypes will cause torch to raise an exception.

    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 type is float16,
       the default complex dtype is complex32. For float32, the default complex dtype is complex64.
       For float64, it is complex128. For bfloat16, an exception will be raised because
       there is no corresponding complex type for bfloat16.
    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.

    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

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

    N)r  _set_default_dtype)ds    r   set_default_dtyper"    s    d !r   F	warn_onlyr   r$  c                2    t        j                  | |       y)a  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
        * :class:`torch.nn.ReplicationPad2d` when attempting to differentiate a 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

    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.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

    In addition, several operations fill uninitialized memory when this setting
    is turned on and when
    :attr:`torch.utils.deterministic.fill_uninitialized_memory` is turned on.
    See the documentation for that attribute for more information.

    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#results-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(1)
        ...
        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)r   r$  s     r   rj   rj     s    V $$TY?r   c                  *    t        j                         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<          ++--r   c                  *    t        j                         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   rJ   rJ     s    
 5577r   
debug_modec                    t        | t        j                  t        f      st	        dt        |              t        | t              r&| dk(  rd} n| dk(  rd} n| dk(  rd} nt        d|        | dk(  rt        j                  d	       y| dk(  rt        j                  d
d
       y| dk(  rt        j                  d
       yt        d|        )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  r1  r  RuntimeErrorr  r&  )r,  s    r   rY   rY     s      j8<<"56A$zBRASTUU*c""J6!J7"J,,6<9 
 Q
((/	q
((>	q
((.KJ<X
 	
r   c                  X    t        j                         rt        j                         ryyy)zReturns the current value of the debug mode for deterministic
    operations. Refer to :func:`torch.set_deterministic_debug_mode`
    documentation for more details.
    r   r1  r   )r  r(  r+  r   r   r   rD   rD     s%     
'')557r   c                  *    t        j                         S )zReturns the current value of float32 matrix multiplication precision. Refer to
    :func:`torch.set_float32_matmul_precision` documentation for more details.
    )r  _get_float32_matmul_precisionr   r   r   rF   rF     r)  r   	precisionc                 .    t        j                  |        y)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 with 23 bits explicitly stored) for internal computations.
        * "high", float32 matrix multiplications either use the TensorFloat32 datatype (10
          mantissa bits explicitly stored) or treat each float32 number as the sum of two bfloat16 numbers
          (approximately 16 mantissa bits with 14 bits explicitly stored), 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 with 7 bits explicitly stored) 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, 7 for bfloat16 explicitly stored).  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 23 mantissa bits while bfloat16 has 7 explicitly stored, 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  _set_float32_matmul_precision)r6  s    r   rZ   rZ     s    ~ $$Y/r   r  c                .    t        j                  |        y)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  _set_warnAlways)r  s    r   r]   r]   -  s     qr   c                  *    t        j                         S )zReturns True if the global warn_always flag is turned on. Refer to
    :func:`torch.set_warn_always` documentation for more details.
    )r  _get_warnAlwaysr   r   r   rM   rM   :  s     r   r@   messagec                 8   t        |t        j                  t        f      st	        dt        |             ddlm}  ||      ry t        | t              rt        | t              rJ |d}n&t        |      st	        d      t         |             } | |      )Nzcond must be a bool, but got r   )expect_truezExpected 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  r6   r1  r  %torch.fx.experimental.symbolic_shapesr?  
issubclassr   Warningcallabler  )
error_typer@   r=  r?  message_evaluateds        r   _check_withrF  I  s    
 dX]]G457T
|DEEA4 j),Z
G5TTT 	  899	N
&
''r   c                 &    t        t        | |       y)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)rF  r2  r@   r=  s     r   r  r  i  s     dG,r   c                 >    t        | dk\  |       ddlm}  ||        y)a  Checks that a given integer is a valid size (i.e., is non-negative).
    You should use this over _check(i >= 0) because we can use the semantic
    information (that i is a size) to make some further inferences in case
    i is an unbacked SymInt.

    NB: Do NOT use this in contexts where a -1 size would be valid (indicating
    to infer the size from context, or if you should wrap-around or truncate).
    Only use this if the only valid value is an honest to goodness size.
    r   )_advise_is_sizeN)r  r@  rJ  )ir=  rJ  s      r   _check_is_sizerL  {  s     167EAr   c                 &    t        t        | |       y)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)rF  
IndexErrorrH  s     r   _check_indexrO         
D'*r   c                 &    t        t        | |       y)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)rF  r   rH  s     r   _check_valuerR    rP  r   c                 &    t        t        | |       y)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)rF  r1  rH  s     r   _check_typerT    s     	4)r   c                 &    t        t        | |       y)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)rF  NotImplementedErrorrH  s     r   _check_not_implementedrW    s     #T73r   c                    t        |      st        dt        |             |j                  t        j
                  k(  st        d|j                         t        |  |j                         j                         |       y )Nzcond must be a tensor, but got z0cond tensor must have dtype torch.bool, but got )	rL   r1  r  dtyper  r  rF  _is_all_truer  )rD  r@   r=  s      r   _check_tensor_all_withr[    sh    T?9$t*FGG::#J4::,WXX
-D--/446@r   c                 &    t        t        | |       y)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[  r2  rH  s     r   _check_tensor_allr]    s      <w7r   )einfnanpinewaxis)r^  ra  r`  r_  rb  )r9   )storage)_LegacyStorage_StorageBase_warn_typed_storage_removalr:   r;   c                   ,    e Zd Zed        Zed        Zy)r'   c                 2    t        d       | j                  S N   
stacklevelrf  _dtyper  s    r   rY  zByteStorage.dtype      #q1{{r   c                 "    t         j                  S r   )r  uint8r  s    r   rn  zByteStorage._dtype      {{r   Nrr  rs  rt  r   rY  rn  r   r   r   r'   r'     (       r   r'   c                   ,    e Zd Zed        Zed        Zy)r+   c                 2    t        d       | j                  S ri  rm  r  s    r   rY  zDoubleStorage.dtype  ro  r   c                 "    t         j                  S r   )r  doubler  s    r   rn  zDoubleStorage._dtype#      ||r   Nrs  r   r   r   r+   r+     (       r   r+   c                   ,    e Zd Zed        Zed        Zy)r-   c                 2    t        d       | j                  S ri  rm  r  s    r   rY  zFloatStorage.dtype)  ro  r   c                 "    t         j                  S r   )r  r  r  s    r   rn  zFloatStorage._dtype.  rr  r   Nrs  r   r   r   r-   r-   (  rt  r   r-   c                   ,    e Zd Zed        Zed        Zy)HalfStoragec                 2    t        d       | j                  S ri  rm  r  s    r   rY  zHalfStorage.dtype4  ro  r   c                 "    t         j                  S r   )r  halfr  s    r   rn  zHalfStorage._dtype9      zzr   Nrs  r   r   r   r  r  3  (       r   r  c                   ,    e Zd Zed        Zed        Zy)r2   c                 2    t        d       | j                  S ri  rm  r  s    r   rY  zLongStorage.dtype?  ro  r   c                 "    t         j                  S r   )r  longr  s    r   rn  zLongStorage._dtypeD  r  r   Nrs  r   r   r   r2   r2   >  r  r   r2   c                   ,    e Zd Zed        Zed        Zy)r0   c                 2    t        d       | j                  S ri  rm  r  s    r   rY  zIntStorage.dtypeJ  ro  r   c                 "    t         j                  S r   )r  r  r  s    r   rn  zIntStorage._dtypeO  s    yyr   Nrs  r   r   r   r0   r0   I  s(       r   r0   c                   ,    e Zd Zed        Zed        Zy)r4   c                 2    t        d       | j                  S ri  rm  r  s    r   rY  zShortStorage.dtypeU  ro  r   c                 "    t         j                  S r   )r  shortr  s    r   rn  zShortStorage._dtypeZ  rr  r   Nrs  r   r   r   r4   r4   T  rt  r   r4   c                   ,    e Zd Zed        Zed        Zy)r)   c                 2    t        d       | j                  S ri  rm  r  s    r   rY  zCharStorage.dtype`  ro  r   c                 "    t         j                  S r   )r  int8r  s    r   rn  zCharStorage._dtypee  r  r   Nrs  r   r   r   r)   r)   _  r  r   r)   c                   ,    e Zd Zed        Zed        Zy)r%   c                 2    t        d       | j                  S ri  rm  r  s    r   rY  zBoolStorage.dtypek  ro  r   c                 "    t         j                  S r   )r  r  r  s    r   rn  zBoolStorage._dtypep  r  r   Nrs  r   r   r   r%   r%   j  r  r   r%   c                   ,    e Zd Zed        Zed        Zy)BFloat16Storagec                 2    t        d       | j                  S ri  rm  r  s    r   rY  zBFloat16Storage.dtypev  ro  r   c                 "    t         j                  S r   )r  bfloat16r  s    r   rn  zBFloat16Storage._dtype{      ~~r   Nrs  r   r   r   r  r  u  (       r   r  c                   ,    e Zd Zed        Zed        Zy)ComplexDoubleStoragec                 2    t        d       | j                  S ri  rm  r  s    r   rY  zComplexDoubleStorage.dtype  ro  r   c                 "    t         j                  S r   )r  cdoubler  s    r   rn  zComplexDoubleStorage._dtype  s    }}r   Nrs  r   r   r   r  r    s(       r   r  c                   ,    e Zd Zed        Zed        Zy)ComplexFloatStoragec                 2    t        d       | j                  S ri  rm  r  s    r   rY  zComplexFloatStorage.dtype  ro  r   c                 "    t         j                  S r   )r  cfloatr  s    r   rn  zComplexFloatStorage._dtype  ry  r   Nrs  r   r   r   r  r    rz  r   r  c                   ,    e Zd Zed        Zed        Zy)QUInt8Storagec                 2    t        d       | j                  S ri  rm  r  s    r   rY  zQUInt8Storage.dtype  ro  r   c                 "    t         j                  S r   )r  quint8r  s    r   rn  zQUInt8Storage._dtype  ry  r   Nrs  r   r   r   r  r    rz  r   r  c                   ,    e Zd Zed        Zed        Zy)QInt8Storagec                 2    t        d       | j                  S ri  rm  r  s    r   rY  zQInt8Storage.dtype  ro  r   c                 "    t         j                  S r   )r  qint8r  s    r   rn  zQInt8Storage._dtype  rr  r   Nrs  r   r   r   r  r    rt  r   r  c                   ,    e Zd Zed        Zed        Zy)QInt32Storagec                 2    t        d       | j                  S ri  rm  r  s    r   rY  zQInt32Storage.dtype  ro  r   c                 "    t         j                  S r   )r  qint32r  s    r   rn  zQInt32Storage._dtype  ry  r   Nrs  r   r   r   r  r    rz  r   r  c                   ,    e Zd Zed        Zed        Zy)QUInt4x2Storagec                 2    t        d       | j                  S ri  rm  r  s    r   rY  zQUInt4x2Storage.dtype  ro  r   c                 "    t         j                  S r   )r  quint4x2r  s    r   rn  zQUInt4x2Storage._dtype  r  r   Nrs  r   r   r   r  r    r  r   r  c                   ,    e Zd Zed        Zed        Zy)QUInt2x4Storagec                 2    t        d       | j                  S ri  rm  r  s    r   rY  zQUInt2x4Storage.dtype  ro  r   c                 "    t         j                  S r   )r  quint2x4r  s    r   rn  zQUInt2x4Storage._dtype  r  r   Nrs  r   r   r   r  r    r  r   r  r  _tensor_classes)amprandomserialization)r[   )r=   r/   )rG   rI   rP   rV   r\   )rN   rU   c                     t               st        j                         dk(  ryt        ddd      } t	        t        d             t
        j                  j                  |       st        d| z         | j                  d      S )Nr   r   r  rq   torch_shm_managerz$Unable to find torch_shm_manager at zutf-8)
r   r   r   r   r    rv   rw   rx   r2  encode)rw   s    r   _manager_pathr    se    !2i!?%)<=D'g(>?77>>$ADHII;;wr   )
unique_dimr  segment_reducec              #   r   K   | ]/  }t        t        t        |      t        j                        s,| 1 y wr   )r  r  r  rY  )r{   r  s     r   r}   r}   ,  s)      :geT.BEKK#PDs   -77)_disable_dynamo)_VF
functionalc                     t        |       t        j                  ur3t        j                  | f      rt        j
                  t        | f| |      S | sJ |       y)zAA wrapper around Python's assert which is symbolically traceable.N)r  r  r9   r  r  r  _assert)	conditionr=  s     r   r  r  L  sS    Iell*y/K/K	0 ..i\9g
 	
 g9r   )rA   rH   rR   set_grad_enabled)
__config__
__future___awaitsacceleratorautogradbackendsr  rn   distributeddistributionsfftfutureshubjitlinalgmpsmtiamultiprocessingnestednnoptimr  profilersparsespecialtestingtypesutilsxpu)windows)ao)
_size_docs_storage_docs_tensor_docs_torch_docsc                  "    t         j                  S )z?Returns whether PyTorch was built with _GLIBCXX_USE_CXX11_ABI=1)r  _GLIBCXX_USE_CXX11_ABIr   r   r   compiled_with_cxx11_abir    s    $$$r   )_library_ops)ops)classesz.opsz.classes)quantization)quasirandom)register_after_fork)rO   )masked)_symeigeiglstsqmatrix_ranksolve)from_dlpack	to_dlpackc                   \    e Zd ZdZd Zd Zdee   fdZdee	ee
f      fdZd Zd	 Zd
 Zy)_TorchCompileInductorWrapperinductorc                     i | _         || _        | j                  |       | j                  |       | j                   j	                  dd      r'dt
        j                  d<   dt
        j                  d<   y y )Ntriton.cudagraphsF1DISABLE_CUPTI_LAZY_REINIT0TEARDOWN_CUPTI)configdynamic
apply_modeapply_optionsr   rv   r   )r   r   optionsr  s       r   r   z%_TorchCompileInductorWrapper.__init__  sb    (*7#;;??.669BJJ23
 ,/BJJ'( 7r   c                     t        |t              xr4 | j                  |j                  k(  xr | j                  |j                  k(  S r   )r  r  r  r  r  s     r   r2  z#_TorchCompileInductorWrapper.__eq__  s<    u:; .u||+.-	
r   r   c                     ||dk(  ry |dv r)ddl m} | j                   ||| j                               y t	        d| d      )Nr.  >   max-autotunereduce-overheadmax-autotune-no-cudagraphsr   )list_mode_optionszUnrecognized mode=zV, should be one of: default, reduce-overhead, max-autotune, max-autotune-no-cudagraphs)torch._inductorr  r  r  r2  )r   r   r  s      r   r  z'_TorchCompileInductorWrapper.apply_mode  sW    <49,VV90t||DE$TF  +A  B r   r  c           
      *   ddl m} |j                  d      x}r|i n|}|i |ni ||}|sy ddlm} |j                         }|j                         D ]  \  }}|j                  dd      }||vr(t        d| dt        |j                                      |j                  |      }	t        |	      at        ||	      sAt        |      j                  }
t        ||         j                  }t        d	| d
|
 d|       || j                  |<    y )Nr   CompilerBisectorr  r  -r   zUnexpected optimization option z, known options are zUnexpected type of attr z, got z should be )!torch._inductor.compiler_bisectorr  get_config_changer  r  get_config_copyr   r   r2  listkeysget_type_get_originr  r  rr  )r   r  r  bisect_changesr  current_configkeyval	attr_name	attr_typeval_type_strexpected_type_strs               r   r  z*_TorchCompileInductorWrapper.apply_options  s>   F-??
KK>K#ObG&-o">";Xg;X;X  *+1+A+A+C 	-HCC-I."5cU:NtTbTgTgTiOjNkl  	2I 9%-!#y1#'9#5#5L(,^I-F(G(P(P%&23%vl^;WhVij  *-I&#	-r   c                 8    ddl m}  |||| j                        S )Nr   )
compile_fxconfig_patches)torch._inductor.compile_fxr/  r  )r   model_inputs_r/  s       r   __call__z%_TorchCompileInductorWrapper.__call__!	  s    9&'$++FFr   c                 4    ddl m}  || j                        S )Nr   )get_patched_config_dictr0  )r2  r7  r  )r   r7  s     r   get_compiler_configz0_TorchCompileInductorWrapper.get_compiler_config&	  s    F&dkkBBr   c                     ddl m} d| j                  v s|j                  j                  r+| j                  j	                  dd      rddlm}  |        y y y )Nr   r  r	  T)reset_cudagraph_trees)r  r  triton
cudagraphsr   torch._inductor.cudagraph_treesr:  )r   r  r:  s      r   resetz"_TorchCompileInductorWrapper.reset+	  sD    *$++-1I1I{{2D9Q%' : 2Jr   N)rr  rs  rt  compiler_namer   r2  	_Optionalr  r  _Dict_Anyr  r5  r8  r>  r   r   r   r  r    sM    M/

y~ 
!-YuS$Y/?%@ !-FG
C
(r   r  c                   $    e Zd Zd Zd Zd Zd Zy)_TorchCompileWrapperc                 "   ddl m} t        |t              r|| _        n.t        |d      r|j                  | _        nt        |      | _        || _         ||      | _        i | _	        |r|dk7  r|| j                  d<   |r|| j                  d<   y y )Nr   )lookup_backendrr  r.  r   r  )
torch._dynamo.backends.registryrF  r  r  r?  r   rr  r  compiler_fnkwargs)r   backendr   r  r  rF  s         r   r   z_TorchCompileWrapper.__init__6	  s    Bgs#!(DWj)!(!1!1D!$WD)'2DI%"&DKK%,DKK	" r   c                     t        |t              xrO | j                  |j                  k(  xr4 | j                  |j                  k(  xr | j                  |j                  k(  S r   )r  rD  rH  rI  r  r  s     r   r2  z_TorchCompileWrapper.__eq__H	  sW    u23 .  E$5$55.u||+. -		
r   c                 >     | j                   ||fi | j                  S r   )rH  rI  )r   r3  r4  s      r   r5  z_TorchCompileWrapper.__call__P	  s     t?4;;??r   c                 f    t        | j                  d      r| j                  j                          y y )Nr>  )r   rH  r>  r  s    r   r>  z_TorchCompileWrapper.resetS	  s)    4##W-""$ .r   N)rr  rs  rt  r   r2  r5  r>  r   r   r   rD  rD  5	  s    -$
@%r   rD  _InputT_RetTr  	fullgraphr  rJ  r   r  disablemodelrQ  r  rJ  r  rR  c                     y r   r   rS  rQ  r  rJ  r   r  rR  s          r   r?   r?   \	  s     !$r   c                     y r   r   rU  s          r   r?   r?   i	  s	     ILr   c                   ddl }t        j                  d       t        j                  dk\  rt        d      |j                  d      dk(  rt        d      | 3d	t        t        t        f   d
t        t        t        f   ffd}|S t        d      dddl
m}	 |	j                         x}
r|
dk(  rt              nt              t        j                   j#                        |       S )a  
    Optimizes given model/function using TorchDynamo and specified backend.
    If you are compiling an :class:`torch.nn.Module`, you can also use :meth:`torch.nn.Module.compile`
    to compile the module inplace without changing its structure.

    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 8; 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): If False (default), torch.compile attempts to discover compileable regions
        in the function that it will optimize. If True, then we require that the entire function be
        capturable into a single graph. If this is not possible (that is, if there are graph breaks),
        then this will raise an error.
       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/torch.compiler_custom_backends.html#registering-custom-backends
       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 or template based matrix multiplications
          on supported devices and Triton based convolutions on GPU.
          It enables CUDA graphs by default on GPU.

        - "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)

    r   Nztorch.compile)rj     z.torch.compile is not supported on Python 3.14+Py_GIL_DISABLEDr   z@torch.compile is not supported on Python built with GIL disabledrS  r   c           	      B    | t        d      t        |       S )NzModel can't be NonerP  )r2  r?   )rS  rJ  rR  r  rQ  r   r  s    r   r  zcompile.<locals>.fn	  s6    }"#899# r   zVEither mode or options can be specified, but both can't be specified at the same time.r.  r  r  )rJ  nopythonr  rR  )r   r  _log_api_usage_oncer   version_infor2  r   	_CallablerN  rO  r  r  get_backendr  rD  r  _dynamooptimize)rS  rQ  r  rJ  r   r  rR  r   r  r  bisect_backends    ``````    r   r?   r?   v	  s,   D ?+
7"KLL		!	!"3	4	9N
 	

 }	i/ 	Igun4M 	 	 	G/d
 	
 |B)5577~7 *.tWgF&wgwG==!!	 " 
  r   c           	      .   t        j                  |       j                  } t        j                  t
           }t        ||       rt        d|  dt        ||        d      t        || |       dj                  t
        | g      }|t        j                  |<   y)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   rr  r   r2  r  setattrry   )device_typer  mtorch_module_names       r   _register_device_moduleri  
  s     ,,{+00KHAq+%k] 3%%,Q%<$=Q@
 	
 A{F#(K!89%+CKK!"r   )rB   funclibraryreturn_types)r@   
while_loop)rk   )_meta_registrationsTORCH_CUDA_SANITIZER)fx)compilerc                   x    e Zd ZU ej                  j                  dd      Zi Zee	e
e
f   ef   ed<   ed        Zy)_TritonLibraryr;  DEF	ops_tablec                     ||f| j                   vrL| j                  j                  |       | j                  j                  d|z   ||       || j                   ||f<   | j                   ||f   S )Nztriton::)ru  rr   defineimpl)clsop_keyfull_schemaop_impldispatch_keys        r   
registerOpz_TritonLibrary.registerOpC
  sc    %S]]:{+Z&0'<H8?v|45==&,!788r   N)rr  rs  rt  r  rk  rp   rr   ru  rA  rv  r  r^  __annotations__classmethodr~  r   r   r   rs  rs  ?
  sG    mm##He48:	5S)945:		9 
	9r   rs  )has_mpshas_cuda	has_cudnn
has_mkldnn)r`  	_inductor_subclassesonnx>   r  r`  _exportr  c           	         t         j                  |       }|<dd l}|j                  d|  d|j                   d|j
                   dd        |       S | t        v rt        j                  d|  t
              S t        dt
         d	|  d      )
Nr   rd  z' is deprecated, please use 'r   z()'r1  rk  zmodule 'z' has no attribute ')
_deprecated_attrsr   warningsr/  rs  rr  _lazy_modules	importlibimport_moduleAttributeError)r  replacementr  s      r   __getattr__r  i
  s    '++D1"MMD66{7M7M6NaP[PdPdOeehi   =  = **Qtf:x@@xz1EdV1MNNr   c                 r   t        | t        j                        r| j                  }njt        | t              r t        j                  |       j                  }n:| )t        j
                  j                         j                  }nt        d|  d      t        t        |d      }|t        d| d| d      |S )z
    Returns the module associated with a given device(e.g., torch.device('cuda'), "mtia:0", "xpu", ...).
    If no device is given, return the module for the current accelerator or CPU if none is present.
    NzInvalid value of device 'z$', expect torch.device, str, or NonezDevice 'z<' does not have a corresponding module registered as 'torch.z'.)	r  r  r  r  r  r  _get_acceleratorr2  r  )r  device_module_namedevice_modules      r   rE   rE   |
  s    
 &%,,'#[[	FC	 "\\&166	"XX668=='x/ST
 	
 E#5t<M)**fgyfzz|}
 	
 r   r  r  c                 4    t        j                  | ||       y)ae  
    This indicates that a given int is size-like, and can be used in any context where a size is expected.
    You will typically use this when reading out integers from Tensors, e.g., max.item() or lengths.tolist()
    which then need to be used as tensor constructors. Providing these assertions to PyTorch can help resolve
      GuardOnDataDependentSymNode errors upon export, since we cannot guard on unbacked SymInts.

    This function has unusual semantics in some circumstances in framework
    code, we will treat this int as >= 2 (when we do a size-oblivious guard).
    This makes it easier to use the unbacked int in size contexts,
    as we will often attempt to guard on a size being zero/one
    (e.g., when computing the contiguity of a tensor, or testing if
    broadcasting can occur), which will not work on unbacked SymInts.
    However, if we conservatively assume that the size is not zero/one, we will
    end up with a graph that will still work even if the size is zero/one.

    For more details, see https://docs.google.com/document/d/1HSuTTVvYH1pTew89Rtpeu84Ht3nQEFTYhAX3Ypa_xJs/edit
    ```
    )r  r  N)r  sym_constrain_range_for_size)symbolr  r  s      r   _constrain_as_sizer  
  s    . 
&&v3C@r   )_loggingc                     ddl m}  d}t        j                  dk  r |        j	                  |d      }n	 | |      }|D ]  }	 |j                         } |         y	# t        $ r}t        d|j                   d      |d	}~ww xY w)
z
    Leverage the Python plugin mechanism to load out-of-the-tree device extensions.
    See this RFC: https://github.com/pytorch/pytorch/issues/122468
    r   )entry_pointsztorch.backends)rj  
   r   )groupz&Failed to load the backend extension: zN. You can disable extension auto-loading with TORCH_DEVICE_BACKEND_AUTOLOAD=0.N)	importlib.metadatar  r   r]  r   rN   r   r2  r  )r  
group_namebackend_extensionsbackend_extension
entrypointr   s         r   _import_device_backendsr  
  s    
 0!J
'!)^//
B?)
;/ 
		*//1JL
  	89J9O9O8P Q_ ` 	s   A	B&B  Bc                  4    t        j                  dd      dk(  S )ab  
    Whether autoloading out-of-the-tree device extensions is enabled.
    The switch depends on the value of the environment variable
    `TORCH_DEVICE_BACKEND_AUTOLOAD`.

    Returns:
        bool: Whether to enable autoloading the extensions. Enabled by default.

    Examples:
        >>> torch._is_device_backend_autoload_enabled()
        True
    TORCH_DEVICE_BACKEND_AUTOLOADr
  )rv   r   r   r   r   #_is_device_backend_autoload_enabledr  
  s     994c:cAAr   c                    t        |       }|t        j                  u r%t        j                  | t        j
                        S |t        j                  u r%t        j                  | t        j                        S t        j                  |       S )z
    Like torch.as_tensor, but when given Python data types it will keep
    them in full precision.  Used for calling convention for Dynamo.
    )rY  )r  r   r  r  	as_tensorfloat64r  int64)r  tys     r   _as_tensor_fullprecr  
  s^    
 
aB	X^^q66	x||	q44q!!r   )r   Nr   )r   r  )r!  ztorch.dtyper   N)NN(G  ru  r   r   r   r  r  r   rv   r   r   r   	threadingtypingr   rB  r   r^  r   rA  r   r%  r   r@  r   	_overloadr	   _Setr
   rv  r   _Typer   r   _TypeVarr   _Uniontyping_extensionsr   
_ParamSpecr  r   r  r   torch._utilsr   _syncr   r   torch._utils_internalr   r    r!   r"   r$   	TypeGuard_TypeIsr#   torch.torch_version__all__sortedr   r  r   r   r   r   getdlopenflags	old_flagssetdlopenflagsr   	RTLD_LAZYtorch._Cr8   r7   r6   rf   r`   rb   rd   r  re   rg   r  __fn__name
__sym_namert  rr  globalsr  appendrc   ra   r  ImportErrorr  _C_for_compiled_checkr   r   r   r  __objr  endswithr  rC  isclassrs  delattrr   r  rh   rL   rK   localr  rC   r  rW   rX   r"  rj   r<   rJ   rY   rD   rF   rZ   r]   rM   rF  r  rL  rO  rR  rT  rW  r[  r]  r^  r_  r`  ra  rb  r  r   torch._tensorr9   rc  torch.storagerd  re  rf  r:   r;   r'   r+   r-   r  r2   r0   r4   r)   r%   r  r  r  r  r  r  r  r  r  r  r  r  r  r  torch._tensor_strr[   	torch.ampr=   r/   torch.randomrG   rI   rP   rV   r\   torch.serializationrN   rU   r  torch._C._VariableFunctionsr  _segment_reducePRIVATE_OPS_VariableFunctionsr  torch._compiler  r  r  torch.functionalr  torch.autogradrA   rH   rR   r  r  r  r  r  r  r  r  rn   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  torch.signalr  r  torch.nn.intrinsictorch.nn.qattorch.nn.quantizabletorch.nn.quantized_init_namesr"  r  r  r  r  r  r  r  
torch._opsr  torch._classesr  r  r  r  contiguous_formatlegacy_contiguous_formattorch.multiprocessing._atforkr  get_num_threadstorch._lobpcgrO   atenquantized_lstmquantized_grur  torch._linalg_utilsr  symeigr  r   r  r  torch.utils.dlpackr  r  r  rD  rN  rO  r?   ri  rB   rj  rk  rl  torch._higher_order_opsr@   rm  
torch.funcrk   rn  r   torch.cuda._sanitizer
_sanitizercsanenable_cuda_sanitizerr  rp  _initrq  rs  is_builtr   is_availablemkldnnr  r`  r  r  r  r  r  r  rE   r  r  
_init_logsr  r  r  r   r   r   <module>r     s         	  
      6 "Hhmm H 
  $K #--#* 3>HV &/! !! <<7n/` 3 # $ :8Cv "YRYY/F%Gohoo/9<$ #""$ICr~~45Cy! B BJt2 t2nA- A-H""6"vfUCZ&8&:L&LM "$"&L.
 ( fj !F !JF#D(22D GIj!!& 	&*. 9[! z %
'4  "g /FayC 7vF#E?ogooe48+ " 
 (0E$	<	H%v./" E
? %R(( "$  "c  "F)4 )w~6 )()D )/O(P Q ) )* # =;f^S(,,>?@=;	=;@#veN&;S&@A # #>2p  %K@
--K@ }}K@ 
	K@\.hmm .8x}} 8)
VHLL#4E-F )
4 )
Xhll .c .?0C ?0D ?0D
x}} 
D 
   (
'
(( r3w(@-$"+$+$*$4$A82 !     3 4 ! % . N > . .  > . . n > . N > N n n  'G $uVL.$@ABC . 03ueN+, 4 O N . * V V *    -/ "  . %O "''( F&K"7B))62EE!!!	&vGIfS!v E   Z  + 7  (        > ,
      t$% & G F }j% %
 5 " - -   (4(# .   (8,g 6 / -
 -  > = E)) * + * ((&&
 #    6 5X( X(v %  %F Y
   %(,&0"OS"	$We^$	$ }}	$ x}}%		$
 CN#	$ d
	$ uS&hllHMM)I"JJKL	$ ]]	$ w~	$ 	$ 	L  %(,&0"OS"	L	L }}	L x}}%		L
 CN#	L d
	L uS&hllHMM)I"JJKL	L ]]	L 	'5.)*Igun,EEF	L 	L #'T  %(,&0"OS"TYT }}T x}}%	T
 CN#T d
T uS&hllHMM)I"JJKLT ]]T y%()9We^+DDEgunTn,(   K J # # ) RZZ'((D  &       *9 9  ~~!!**##,,%%22..''44	    MO&iu||S/@(AB 4 $(#'A	8<<	 A 
8<<	 A4     4BX]] B" '("U8  
, %%-HOO eg
 	  
+
s   n A o