
    YTh                        % S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKJ	r	  SSK
JrJrJrJr  SSKJr  SSKrSSKJrJrJrJr  SSKJr  SSKJrJrJr  SS	KJrJr  SS
K J!r!  SSK"J#r#  \RH                  RJ                  r&\RH                  RN                  r(\" SSS9r)\" S5      r*S8S jr+S9S jr, " S S\RZ                  RB                  5      r.S r/\R`                  Rc                  SS5      r2\R`                  Rc                  SS5      r3\R`                  Rc                  SS5      r4\Rj                  S:S j5       r6\Rn                  S4S jr8S r9S r: " S S\;5      r<\Rz                  " 5        S9S j5       r> " S  S!\?5      r@\@R                  5         \RH                  R                  5         S" rCS# rDS$ rES% rFSSSSS&SSS\SS4S' jrG " S( S)\H\	5      rI " S* S+\H\	5      rJSSSSS&SSS\SS4S, jrKSrL\\M\\4      \NS-'   SSSS&SSS\SS4
S. jrOS/ rP " S0 S1\5      rQ " S2 S3\Q5      rRS4\\*\)4   S5\\*\)4   4S6 jrS      S;S7 jrTg)<zTracing.

This module contains functionality to support the JIT's tracing frontend, notably:
    * torch.jit.trace
    * torch.jit.trace_module

This is not intended to be imported directly; please use the exposed
functionalities in `torch.jit`.
    N)Enum)AnyCallableOptionalTypeVar)	ParamSpec)_get_model_id_qualified_nameget_callable_argument_namesis_scripting)function)_CachedForwardscriptScriptModule)_enabled
_python_cu)Module)default_tolerancesRT)	covariantPc                    ^  U 4S jnU$ )Nc                 v  > [         R                  " 5       nU(       d  [        S5      eSnUTS-   :  a.  UR                  nU(       d  [        S5      eUS-  nUTS-   :  a  M.  UR                  nUR                  5        H8  u  pE[        U[        R                  5      (       d  M&  XL d  M,  US:w  a  Us  $ Ss  $    g)Nzfailed to inspect framer      zfailed to get frameself )	inspectcurrentframeRuntimeErrorf_backf_localsitems
isinstancetorchTensor)varframeir!   kv	frames_ups         H/var/www/auris/envauris/lib/python3.13/site-packages/torch/jit/_trace.py_get_interpreter_name_for_varI_create_interpreter_name_lookup_fn.<locals>._get_interpreter_name_for_var-   s    $$&899)a-LLE"#899FA	 )a- >>NN$DA!U\\**sxKq/R/ %      )r+   r-   s   ` r,   "_create_interpreter_name_lookup_fnr1   ,   s    & )(r/   Fc                    U R                  SS9n[        U5      " 5       n[        5       nUR                  5        HO  u  pV[	        U5      U;   a  M  UR                  [	        U5      5        U(       a  XcU'   M=  UR                  5       X5'   MQ     U$ )NT	keep_vars)
state_dicttypesetr"   idadddetach)moduler4   r5   filtered_dictseen_idsr)   r*   s          r,   _unique_state_dictr>   C   s     ""T"2J$&MH  "a5HRU ! xxzM # r/   c                   V   ^  \ rS rSr    SU 4S jjrS\R                  4S jrSrU =r	$ )ONNXTracedModuleU   c                 ^   > [         TU ]  5         Xl        X l        X0l        X@l        XPl        g N)super__init__innerstrict_force_outplace_return_inputs_return_inputs_states)r   rF   rG   force_outplacereturn_inputsreturn_inputs_states	__class__s         r,   rE   ONNXTracedModule.__init__V   s.     	 
-+%9"r/   argsc                   ^ ^^^^	^
 [        U5      u  mm[        [        T SS9R                  5       5      n/ m
/ m/ m	UUUU	U
U 4S jn[        R
                  R                  UTU-   [        5       T R                  T R                  5      u  pET R                  (       a  UT	S   T
S   4$ T R                  (       a  UT	S   TS   4$ UT	S   4$ )NTr3   c                  Z  > / n[        [        T5      5       HB  n[        X   [        R                  5      (       d  [        S5      eUR                  X   5        MD     [        UT5      nTR                  (       a!  T
R                  [        S U  5       5      5        TR                  (       a  TR                  [        UT5      5        T	R                  TR                  " U6 5        TR                  (       a
  TS   U4TS'   [        T	5      u  pE[        U5      S:X  a  US   $ [        U5      $ )NzExpected Tensor argumentc              3   Z   #    U  H!  oR                  [        R                  S 9v   M#     g7f)memory_formatN)cloner$   preserve_format).0xs     r,   	<genexpr><ONNXTracedModule.forward.<locals>.wrapper.<locals>.<genexpr>}   s!     UPT1''0E0E'FPTs   )+r   r   )rangelenr#   r$   r%   r   append
_unflattenrI   tuplerJ   rF   _flatten)rP   in_argsr(   trace_inputsout_vars_in_descin_varsinputs_statesouts
ret_inputsr   s         r,   wrapper)ONNXTracedModule.forward.<locals>.wrapperr   s    *,G3w<(!$'5<<88&'ABBtw' )
 &gw7L""!!UPTUU ))$$Z%ABKK

L12))$1!$4l#Ca "4.KH8}!{"X&r/   r   )ra   listr>   valuesr$   _C_create_graph_by_tracingr1   rG   rH   rI   rJ   )r   rP   module_staterk   graph_outrf   rg   rh   ri   rj   s   `     @@@@@r,   forwardONNXTracedModule.forwardh   s    #D> .ttDKKMN
	' 	'0 hh77l".0KK  
 $q':a=00%%$q'=#333$q'>!r/   )rH   rI   rJ   rF   rG   )TFFF)
__name__
__module____qualname____firstlineno__rE   r$   r%   rt   __static_attributes____classcell__rN   s   @r,   r@   r@   U   s+     ":$/"U\\ /" /"r/   r@   c                 J   ^ U4S jm[         R                  " S TSS9" U 5      $ )Nc                 ~  > U c  g [        U [        R                  5      (       a}  U R                  5       R	                  U R
                  (       a  S O[        R                  S9R                  U R                  5      nU R                  b  T" UR                  5      Ul	        U$ U R	                  [        R                  S9$ )NrT   )
r#   r$   r%   r:   rV   	is_mkldnnrW   requires_grad_requires_gradgrad)ar*   clone_inputs     r,   r   "_clone_inputs.<locals>.clone_input   s    95<<(( 
Q[[Te>S>ST0 
 vv!$QVV,H77)>)>7??r/   c                 6    [        U [        R                  5      $ rC   )r#   r$   r%   rY   s    r,   <lambda>_clone_inputs.<locals>.<lambda>   s    *Q-r/   tensors)condition_msg)r   _nested_map)rP   r   s    @r,   _clone_inputsr      s-    @  -{)
 r/   PYTORCH_JIT_TIMEPYTORCH_JIT_DISABLEPYTORCH_JIT_STATSc              #   v  #    [         (       d  U(       a#  [        R                  R                  5       (       d  S v   g [        R                  R	                  5       n[        R                  R                  SS9n[        R                  R                  SS9nUR                  U5         S v   UR                  U5        UR                  5         [        U  SU SUR                  U5       S35        g ! UR                  U5        UR                  5         [        U  SU SUR                  U5       S35        f = f7f)NT)enable_timing z time: z ms)
	_JIT_TIMEr$   cudais_availablecurrent_streamEventrecord_eventsynchronizeprintelapsed_time)
trace_namenametimestreamstartends         r,   _timer      s     Id5::+B+B+D+DZZ&&(FJJ40E
**



.C
IC AdV75+=+=c+B*C3GH 	C AdV75+=+=c+B*C3GHs    B$D9'C0 +AD90AD66D9c                 N  ^ ^^
 [        T [        R                  R                  5      (       d  [	        S5      e[        T [
        5      m
[        U[        5      (       d  U4nT
(       a$  [        R                  " T R                  5       5      nS	U
UU 4S jjn[        R                  R                  USS9   U" USS9u  pgT R                  " U6 (       d   e SSS5        T
(       a  T R                  W5        U" USS9u  p[        WU5        [        WU	5        g! , (       d  f       NH= f)
a  
Verify that a JIT compiled model has the same behavior as its uncompiled version along with its backwards pass.

If your model returns multiple outputs,
you must also specify a `loss_fn` to produce a loss for which
the backwards will be computed.

This function has side-effects (e.g., it executes your model / saves and loads
parameters), so don't expect the model to come out exactly the same as what
you passed in.

Args:
    model (compiled torch.nn.Module or function): the module/function to be
        verified.  The module/function definition MUST have been decorated with
        `@torch.jit.compile`.
    args (tuple or Tensor): the positional arguments to pass to the
        compiled function/module to be verified.  A non-tuple is assumed to
        be a single positional argument to be passed to the model.
    loss_fn (function, optional): the loss function to be applied to
        the output of the model, before backwards is invoked.  By default,
        we assume that a model returns a single result, and we :func:`torch.sum`
        before calling backwards; if this is inappropriate, you can pass your
        own loss function.  Note that if a model returns a tuple of results,
        these are passed as separate positional arguments to `loss_fn`.
    devices (iterable of device IDs, optional): the GPU devices which the
        compiled module will be run on.  This determines the RNG state we
        must save when running both compiled and uncompiled versions of the model.
zICannot verify an uncompiled module.  Add @torch.jit.compile to compile itc                   > T(       a  [        TR                  5       5      O/ n[        X45      u  pETnU(       a  UR                  5         U(       a  UR                  nT" U 6 nU(       a  UR                  W:X  a  [        S5      e[        U[        5      (       d  U4nT[        R                  :X  a'  [        U5      S:w  a  [        S[        U5       S35      e[        U5      u  pU	 V
s/ s H-  oR                  5       R                  [        R                  S9PM/     nn
T" U6 n[        R                  R!                  U/U5      nU V
s/ s H-  oR                  5       R                  [        R                  S9PM/     nn
X4$ s  sn
f s  sn
f )Nz#failed to use the compiled functionr   zModel returns zO outputs, but default loss function (torch.sum) can only handle a single outputrT   )rm   
parametersra   clear_cachehitsr   r#   r`   r$   sumr]   
ValueErrorr:   rV   rW   autogradr   )rP   force_traceassert_compiledparamsrg   re   compiled_fnr   outrd   r*   
saved_outslossgradssaved_grads	is_moduleloss_fnmodels                  r,   run_fwd_bwdverify.<locals>.run_fwd_bwd   sl   -6e&&()Btn-
##%##DTl{//47DEE#u%%&CeiiCHM S
 +> >  smKS
KSaHHJ5+@+@A8 	 
 }##TFG4 LQ
KPaHHJ5+@+@A5 	 
 ((

s   )4F	4Fztorch.jit.verify)_callerT)r   N)r   )FF)r#   r$   ro   CompiledFunction	TypeErrorr   r`   copydeepcopyr5   randomfork_rnghas_trace_forload_state_dict_verify_equal)r   rP   r   devicessaved_stater   uncompiled_outsuncompiled_gradscompiled_outscompiled_gradsr   s   ` `       @r,   verifyr      s    F eUXX6677W
 	
 5&)IdE""wmmE$4$4$67) )> 
		w0B		C,7$,O)""D))) 
D k*$/d$K!M/=1"N3 
D	Cs   3 D
D$c                     [        X5       HA  u  p#UR                  U5      R                  5       R                  5       S:  d  M8  [	        S5      e   g )Ngư>z!JIT and real computation mismatch)zipsubabsmaxr   )xsysrY   ys       r,   r   r   !  s=    B558<<>$&BCC r/   c                 r    SR                  U R                  5        Vs/ s H  nSU-   PM
     sn5      $ s  snf )N
	)join
splitlines)slines     r,   indentr   '  s-    99alln=nddTkn=>>=s   4c                   ,   ^  \ rS rSrSU 4S jjrSrU =r$ )TracingCheckErrori+  c                 `  > SU l         Ub  U =R                   US-   -  sl         Ub6  U =R                   S-  sl         U =R                   [        U5      S-   -  sl         Ub6  U =R                   S-  sl         U =R                   [        U5      S-   -  sl         [        TU ]  U R                   5        g )NzTracing failed sanity checks!
r   z+ERROR: Graphs differed across invocations!
zERROR: Tensor-valued Constant nodes differed in value across invocations. This often indicates that the tracer has encountered untraceable code.
)messager   rD   rE   )r   graph_diff_errortensor_compare_error	extra_msgrN   s       r,   rE   TracingCheckError.__init__,  s    8 LLI,,L'LLJJLLLF#34t;;L+LL3L
 LLF#784??L&r/   )r   rC   )rv   rw   rx   ry   rE   rz   r{   r|   s   @r,   r   r   +  s    ' 'r/   r   c	                   ^^^^^^^^ U  GH  n	[        U	[        R                  5      (       a  U	4n	U(       a  0 n
U	R                  5        H  u  p[	        U5      X'   M     [        R
                  R                  [        USU5      U
SUUU[        R                  R                  5       TSS9	nUR                  R                  TR                  5      mU	TR                     n	[        U	[        R                  5      (       d  [        U	[        5      (       a
  T(       d  U	4n	ObT(       a-  [        R
                  R                  USUUU[	        U	5      SS9nO,[        R
                  R                  U[	        U	5      SUUUSS9nUmUU4S jmS mUUU4S jnS/mUU4S	 jmUU4S
 jnU" TU	S5      nU" XS5      nU" UUS5      (       a  U" TU	S5      nU" UUS5        T" 5       n[        S U 5       5      (       d  GM  [!        U6 e   g )N__self__F)check_tracerG   rH   _module_class_compilation_unitexample_inputs_is_kwarg_store_inputs)r   rG   rH   r   example_kwarg_inputsr   )r   rG   rH   r   r   c            	      T  > [         R                  R                  TR                  5      n [         R                  R	                  U 5        [         R                  R                  U 5        [        U 5      n[        R                  " SSU5      n[         R                  R                  TR                  5      n[         R                  R	                  U5        [         R                  R                  U5        [        U5      n[        R                  " SSU5      nS nX:w  Ga`  SS K	nUR                  UR                  S5      UR                  S5      5      nS[        SR                  U5      5      -   S-   n[        U R                  5       UR                  5       5       H  u  px[        U5      [        U5      :w  d  M  US-  nUR                  [        U5      R                  S5      [        U5      R                  S5      5      n	S[        SR                  U	5      5      -   S-   n
UR!                  5       nU(       a  U
S	[        U5      -   S-   -  n
UR!                  5       nU(       a  U
S
[        U5      -   S-   -  n
XJ-  n  O   S n[        U R                  5       UR                  5       5       H  u  pxUR#                  5       UR#                  5       :w  a    XM4$ UR#                  5       S:X  d  MA  UR%                  5       (       a  MX  UR%                  5       (       a  Mo  UR'                  S5      (       d  M  UR)                  S5      S:w  d  UR)                  S5      S:w  a  M  UR+                  S5      nUR+                  S5      n [         R,                  R/                  XSS9  M     XM4$ ! [0        [2        4 at  nUc  SnUS[        [        U5      5      -   S-   -  nUR!                  5       nU(       a  US[        U5      -   S-   -  nUS[        [        U5      5      -   -  n S nA  XM4$ S nAff = f)Nz___torch_mangle_[0-9]+\.r   r   TzGraph diff:
r   zFirst diverging operator:
zNode diff:
zTrace source location:
zCheck source location:
zprim::Constantvaluet)	equal_nanzNode:
zSource Location:
zComparison exception: )r$   ro   _jit_pass_canonicalizerr   _jit_pass_inline!_jit_pass_erase_shape_informationstrrer   difflibndiffr   r   r   r   nodessourceRangekind
mustBeNonehasAttributekindOfr   testingassert_closer   AssertionError)mod_canonicalizedmod_strcheck_canonicalized	check_strgraph_diff_errorsr   
graph_diffn_modn_check	node_diffsource_printout	mod_stackcheck_stacktensor_compare_errorsmod_tensor_valcheck_tensor_valecompare_stackcheck_mod_functraced_funcs                     r,   graph_diagnostic_info+_check_trace.<locals>.graph_diagnostic_info}  s    % ? ?@Q@Q RHH%%&78HH667HI+,Gff8"gFG"'(("A"A.BVBV"WHH%%&9:HH667JK/0I:B	JI $#$]]&&t,i.B.B4.H
 %4fRWWZ=P6Q$QTX$X!&)%++-/B/H/H/J'NE 5zS\1)-JJ)$+MMJ11$7W9P9PQU9V%	 +VBGGI4F-GG$N ( %*$5$5$7	$+ :VI=N NQU UO '.&9&9&;&+ :VK=P PSW WO *<)/'2 %)!"%!'')+>+D+D+F# ::<7<<>1@ %;;= ::<#33$$&&'*<*<*>*> --g66 ||G,3w~~g7NRU7U %*WWW%5N'.yy'9$22* 3 %#H %;; ).9 08461-VCJ=O1ORV1VV-(-(9(9(;(1 4vm7L Lt S1 .1IFFM 2 - $;;s   >N##P'3A'P""P'c                 6    [        U [        5      (       a  U $ U 4$ rC   )r#   r`   r   s    r,   wrap_retval!_check_trace.<locals>.wrap_retval  s    "1e,,161$6r/   c           	      z  >  [        U[        5      (       a  T	(       a  T" U " S0 UD65      nOT" U " [        U5      6 5      nU Vs/ s H&  n[        U[        R                  5      (       d  M$  UPM(     nnU$ s  snf ! [
         a4  nT
" 5       u  pgSU S[        [        U5      5       3n[        UUUS9UeS nAff = f)Nz+encountered an exception while running the z with test inputs.
Exception:
)r   r0   )	r#   dictr   r$   r%   	Exceptionr   r   r   )modinputsrunning_whatri   r   r  r  r  msgr   r  r  s            r,   !run_mod_and_filter_tensor_outputs7_check_trace.<locals>.run_mod_and_filter_tensor_outputs  s    fd++0G&s}V}5D&sM&,A'BCD'+Mtz#u||/LtM N ;P;R8!CL>Qqrxy|}~y  sA  rB  C'%)! 	s0   AA< #A7-A73A< 7A< <
B:/B55B:c                    > TS   (       a  g STS'   TR                   R                  5        V s/ s H  o R                  5       (       d  M  U PM     nn [        U5      S:  aa  SnUS-  nUSR	                  U V s/ s H  n [        [        U 5      5      PM     sn S S 5      -  nUS-  n[        R                  " U[        SS	9  g g s  sn f s  sn f )
Nr   Tz"Trace had nondeterministic nodes. z2Did you forget call .eval() on your model? Nodes:
r      zp
This may cause errors in trace checking. To disable trace checking, pass check_trace=False to torch.jit.trace()   category
stacklevel)
rr   r   isNondeterministicr]   r   r   r   warningswarnTracerWarning)opnondeterm_opsnondeterministic_ops_warning
has_warnedr  s      r,   maybe_warn_nondeterministic1_check_trace.<locals>.maybe_warn_nondeterministic  s    !} JqM(..4466r:O:O:Q6   =!A%/S,,I, -		/<=}VCG_}=crB1 , -C, 0=UV & >s   C
C8C
c                 .  > Sn[        [        X5      5       GH  u  nu  pV UR                  (       a  UR                  5       nUR                  (       a  UR                  5       nUR                  (       a  UR                  5       nUR                  (       a  UR                  5       nUR                  5       (       d  UR                  5       (       aj  [        R                  R                  UR                  [        R                  5      UR                  [        R                  5      T
[        XV5      S   SS9  GM"  UR                  (       d  UR                  (       aL  [        R                  R                  UR                  5       UR                  5       T
[        XV5      S   SS9  GM  [        USS 5      (       d  [        USS 5      (       a  [        USS 5      [        USS 5      :X  d   e[        UR!                  5       UR!                  5       5       HN  u  px[        R                  R                  UR#                  5       UR#                  5       T
[        Xx5      S   SS9  MP     GMO  [        R                  R                  UR#                  5       UR#                  5       T
[        XV5      S   SS9  GM     U$ ! [$         aS  n	T" 5         [&        R(                  " S[+        US-   5      -   S-   U-   S-   [+        U	5      -   [,        SS	9  S
n S n	A	GM  S n	A	ff = f)NTr   )rtolatolr   	is_nestedz
Output nr zH. of the traced function does not match the corresponding output of the z. Detailed error:
   r#  F)	enumerater   is_quantized
dequantizer   to_dense
is_complexr$   r   r   tocdoubler   is_mpsfloatgetattrunbinddoubler   r'  r(  r   r)  )original	reference
match_whatall_okr(   origreft_origt_refr  check_tolerancer.  s             r,   compare_outputs%_check_trace.<locals>.compare_outputs   s   F"+C,D"E;D=#((#0''!nn.~~#}}}}!lln~~''4??+<+<22 GGEMM2FF5==1!0!3D!>q!A&* 3   ;;#**!MM66 $

 #		%4%7%B1%E*. 7  %T;==dB B $+4d#Cw #[$H $  $ 25T[[]CJJL1Q % : :$*MMO$)LLN)8);F)J1)M.2 !; !" 2R "MM66 $ #

%4%7%B1%E*. 7 U #F@ M & #/1MM$a!e*%;; %	%
 00 a&! "/#$
 #F#s.   DJ7:A+J7(B<J7'A	J77
LALLtracezPython functionzrepeated tracec              3   (   #    U  H  oS Lv   M
     g 7frC   r0   )rX   infos     r,   rZ   _check_trace.<locals>.<genexpr>M  s     6ID4Is   )r#   r$   r%   r"   r   jittrace_moduler>  ro   CompilationUnit_c_get_methodr   r  rL  anyr   )check_inputsfuncr  rI  rG   rK   is_trace_moduler   r   r  copied_dictr   data	check_modr  rJ  traced_outsfn_outs
check_outs	diag_infor  r  r-  r.  r  s     ``    `           @@@@@r,   _check_tracer`  >  s    fell++YFK$lln
$1$$7! -		..j$/! .+"'((":":"<(?# / 
I '\\55k6F6FGNK,,-F6ELL22fd++/ &!IIOO %!$2"/)6v)>"' , 	 "IIOO!&) %!$2"/"' , 	 'NT	<l	7	" W
	.B	H 8VWU3DBST;1BCC:(8J K5EF)+	6I666#Y//G r/   c                   $    \ rS rSr\S 5       rSrg)r)  iQ  c                  f    [         R                  " S[        SS9  [         R                  " SS5        g )Nignoreztorch.(?!jit))r$  r;   ztorch::jit::fuser::cuda)r'  filterwarningsr)  r0   r/   r,   ignore_lib_warnings!TracerWarning.ignore_lib_warningsR  s,     	}_	
 	*CDr/   r0   N)rv   rw   rx   ry   staticmethodre  rz   r0   r/   r,   r)  r)  Q  s    E Er/   r)  c                     [        U [        R                  [        45      (       a  U 4$ [        U [        5      (       d  [	        U 5      $ U $ rC   )r#   r$   r%   r  r`   )example_inputss    r,   
make_tuplerj  a  s?    .5<<"677  ne,,^$$r/   c                 0   [        U [        5      (       a  U $ [        R                  R	                  U 5      (       aM  [        R
                  R                  R                  n[        R
                  R                  R                  XSSS9$ Uc  [        nU" XS9$ )NFTshare_types
is_tracingr   )
r#   r   r$   _jit_internalmodule_has_exportsrP  
_recursive make_stubs_from_exported_methodscreate_script_moduleTopLevelTracedModule)r  r   r   infer_methods_stubs_fns       r,   make_modulerw  j  s    #|$$
				/	/	4	4!&!5!5!V!Vyy##88Ut 9 
 	
  0MSFFr/   c                 >    U c  g U  Vs/ s H  nSU0PM	     sn$ s  snf )Nrt   r0   )rV  cs     r,   wrap_check_inputsrz  x  s'    $01LqYNL111s   c                 F   SS K Js  Jn  UR                  U 5      nUR                  U5      n[	        X45       H  u  pVUR
                  UR
                  :w  a    gUR
                  [        R                  :X  a    g[        U5      [        U5      :w  a    g[        U[        R                  R                  5      (       a    g[        U[        R                  5      (       a;  UR                  UR                  :w  a    g[        R                  " XV5      (       d    gM  XV:w  d  M    g   g)Nr   FT)torch.utils._pytreeutils_pytreetree_leavesr   layoutr$   _mkldnnr6   r#   _subclasses
FakeTensorr%   dtypeallclose)exportrL  pytreeflat_export
flat_tracerE  loadeds          r,   $analyze_ts_result_with_export_resultr    s    (($$V,K##E*JK4;;&--';;%--':f%dE--8899ell++zzV\\)>>$// 0 ~' 5( r/   gh㈵>c                    [        U [        R                  R                  5      (       a  [        R
                  " S5        U $ [        U [        R                  R                  5      (       aR  Uc#  [        U
[        5      (       a  U
nO[        S5      e[        U SU0S U[        U5      UUUU[        U
[        5      US9$ [        U S5      (       a  [        U R                  [        R                  R                  5      (       al  U R                  S:X  a\  Uc#  [        U
[        5      (       a  U
nO[        S5      e[        U R                  SU0S U[        U5      UUUU[        U
[        5      US9$ [        U[        R                  [        45      (       a  U
c  U4nO#U
c   [        U[         5      (       d  [!        U5      n[#        S5      n[        U S5      (       a>  [        U R                  [        R                  R                  5      (       a  [%        S5      e['        U 5      n[        U
[        5      (       a1  U
n[        R(                  R+                  UU U
UUU[-        U 5      5      nO.[        R(                  R/                  UU UUUU[-        U 5      5      nU(       aC  Ub   [1        UU UUUUSU[        U
[        5      S	9	  O [1        U/U UUUUSU[        U
[        5      S	9	  Xl        U$ )
Nz`The input to trace is already a ScriptModule, tracing it is a no-op. Returning the object as is.z%example_kwarg_inputs should be a dictrt   )r   r   r   r   zVtrace doesn't support compiling individual module's functions.
Please use trace_moduleFr   )r#   r$   rP  r   r'  r(  nnr   r  r   rQ  rz  hasattrr   rv   r%   r`   r1   AttributeErrorr
   ro   %_create_function_from_trace_with_dictr   _create_function_from_tracer`  _torchdynamo_inline)rW  ri  optimizer   rV  rI  rG   rH   r   r   r   r   var_lookup_fnr   traceds                  r,   _trace_implr    s    $		..// 	n	
 $((!.55!5"#JKK'l+$./CT$J'
 	
 	j!!t}}ehhoo66MMY&!.55!5"#JKKMM'l+$./CT$J'
 	
  	>ELL$#788 ((*		%j.O.O~.6q9MtZ  Zuxx%O%O&
 	

 4 D&---?? '-
 55'-
 #(23G(N
  (23G(N
 "&Mr/   c                   .    \ rS rSrSrSrSrS\4S jrSr	g)	_ExportTypei&  DIRECT_EXPORTTRACE_AND_EXPORTSOURCE_TO_SOURCEreturnc                     U R                   $ rC   r   r   s    r,   __str___ExportType.__str__+      zzr/   r0   N)
rv   rw   rx   ry   r  r  r  r   r  rz   r0   r/   r,   r  r  &  s    #M)) r/   r  c                   2    \ rS rSrSrSrSrSrS\4S jr	Sr
g	)
_ExportOutcomei/  SUCCESSFAILED_TO_EXPORTFAILED_TO_RUNACCURACY_ERRORr  c                     U R                   $ rC   r  r  s    r,   r  _ExportOutcome.__str__5  r  r/   r0   N)rv   rw   rx   ry   r  r  r  r  r   r  rz   r0   r/   r,   r  r  /  s#    G)#M%N r/   r  c                 6  ^^ [         (       d  U $ Ub  [        R                  " S[        SS9  SSKJnJmJn  [        U UUUUUUUUU	U
U5      nU" S[        U5      S9  U" 5       (       a  SSK
Jm  SS	KJnJn  [        U UUS
UUUUUU	U
US9nU" X5      u  nnU4S jnS nU4S jn[        U[         R"                  R$                  5      (       d  U" UUU[&        R(                  5        U" UUU[&        R*                  5        U" UUU[&        R,                  5        U$ )a  
Trace a function and return an executable  or :class:`ScriptFunction` that will be optimized using just-in-time compilation.

Tracing is ideal for code that operates only on
``Tensor``\\s and lists, dictionaries, and
tuples of ``Tensor``\\s.

Using `torch.jit.trace` and `torch.jit.trace_module`, you can turn an
existing module or Python function into a TorchScript
:class:`ScriptFunction` or :class:`ScriptModule`. You must provide example
inputs, and we run the function, recording the operations performed on all
the tensors.

* The resulting recording of a standalone function produces `ScriptFunction`.
* The resulting recording of `nn.Module.forward` or `nn.Module` produces
  `ScriptModule`.

This module also contains any parameters that the original
module had as well.

Warning:
    Tracing only correctly records functions and modules which are not data
    dependent (e.g., do not have conditionals on data in tensors) and do not have
    any untracked external dependencies (e.g., perform input/output or
    access global variables). Tracing only records operations done when the given
    function is run on the given tensors. Therefore, the returned
    `ScriptModule` will always run the same traced graph on any input. This
    has some important implications when your module is expected to run
    different sets of operations, depending on the input and/or the module
    state. For example,

    * Tracing will not record any control-flow like if-statements or loops.
      When this control-flow is constant across your module, this is fine
      and it often inlines the control-flow decisions. But sometimes the
      control-flow is actually part of the model itself. For instance, a
      recurrent network is a loop over the (possibly dynamic) length of an
      input sequence.
    * In the returned :class:`ScriptModule`, operations that have different
      behaviors in ``training`` and ``eval`` modes will always behave as if
      it is in the mode it was in during tracing, no matter which mode the
      `ScriptModule` is in.

    In cases like these, tracing would not be appropriate and
    :func:`scripting <torch.jit.script>` is a better choice. If you trace
    such models, you may silently get incorrect results on subsequent
    invocations of the model. The tracer will try to emit warnings when
    doing something that may cause an incorrect trace to be produced.

Args:
    func (callable or torch.nn.Module):  A Python function or `torch.nn.Module`
        that will be run with `example_inputs`. `func` arguments and return
        values  must be tensors or (possibly nested) tuples that contain
        tensors. When a module is passed `torch.jit.trace`, only the
        ``forward`` method is run and traced (see :func:`torch.jit.trace
        <torch.jit.trace_module>` for details).

Keyword arguments:
    example_inputs (tuple or torch.Tensor or None, optional): A tuple of example
        inputs that will be passed to the function while tracing.
        Default: ``None``. Either this argument or ``example_kwarg_inputs``
        should be specified. The resulting trace can be run with inputs of
        different types and shapes assuming the traced operations support those
        types and shapes. `example_inputs` may also be a single Tensor in which
        case it is automatically wrapped in a tuple. When the value is None,
        ``example_kwarg_inputs`` should be specified.

    check_trace (``bool``, optional): Check if the same inputs run through
        traced code produce the same outputs. Default: ``True``. You might want
        to disable this if, for example, your network contains non-
        deterministic ops or if you are sure that the network is correct despite
        a checker failure.

    check_inputs (list of tuples, optional): A list of tuples of input
        arguments that should be used to check the trace against what is
        expected. Each tuple is equivalent to a set of input arguments that
        would be specified in ``example_inputs``. For best results, pass in
        a set of checking inputs representative of the space of shapes and
        types of inputs you expect the network to see.  If not specified,
        the original ``example_inputs`` are used for checking
    check_tolerance (float, optional): Floating-point comparison tolerance
        to use in the checker procedure.  This can be used to relax the
        checker strictness in the event that results diverge numerically
        for a known reason, such as operator fusion.
    strict (``bool``, optional): run the tracer in a strict mode or not
        (default: ``True``). Only turn this off when you want the tracer to
        record your mutable container types (currently ``list``/``dict``)
        and you are sure that the container you are using in your
        problem is a ``constant`` structure and does not get used as
        control flow (if, for) conditions.
    example_kwarg_inputs (dict, optional): This parameter is a pack of keyword
        arguments of example inputs that will be passed to the function while
        tracing. Default: ``None``. Either this argument or ``example_inputs``
        should be specified. The dict will be unpacking by the arguments name
        of the traced function. If the keys of the dict don't not match with
        the traced function's arguments name, a runtime exception will be raised.

Returns:
    If `func` is `nn.Module` or ``forward`` of `nn.Module`, `trace` returns
    a :class:`ScriptModule` object with a single ``forward`` method
    containing the traced code.  The returned `ScriptModule` will
    have the same set of sub-modules and parameters as the original
    ``nn.Module``.  If ``func`` is a standalone function, ``trace``
    returns `ScriptFunction`.

Example (tracing a function):

.. testcode::

    import torch

    def foo(x, y):
        return 2 * x + y

    # Run `foo` with the provided inputs and record the tensor operations
    traced_foo = torch.jit.trace(foo, (torch.rand(3), torch.rand(3)))

    # `traced_foo` can now be run with the TorchScript interpreter or saved
    # and loaded in a Python-free environment

Example (tracing an existing module)::

    import torch
    import torch.nn as nn


    class Net(nn.Module):
        def __init__(self) -> None:
            super().__init__()
            self.conv = nn.Conv2d(1, 1, 3)

        def forward(self, x):
            return self.conv(x)


    n = Net()
    example_weight = torch.rand(1, 1, 3, 3)
    example_forward_input = torch.rand(1, 1, 3, 3)

    # Trace a specific method and construct `ScriptModule` with
    # a single `forward` method
    module = torch.jit.trace(n.forward, example_forward_input)

    # Trace a module (implicitly traces `forward`) and construct a
    # `ScriptModule` with a single `forward` method
    module = torch.jit.trace(n, example_forward_input)

^`optimize` is deprecated and has no effect. Use `with torch.jit.optimized_execution()` instead   r%  r   )check_if_torch_exportable!log_torch_jit_trace_exportabilitylog_torchscript_usagerL  )model_id)TS2EPConverter)"_convert_ts_to_export_experimental$_process_jit_trace_inputs_for_exportF)ri  r  r   rV  rI  rG   rH   r   r   r   r   c           	        >  U " U6 n U" X5      n U" U6 n[        X5      (       d,  T	" S[        U5      [        [        R                  5      S5        g T	" S[        U5      [        [        R                  5      S5        g ! [          a7  nUnT	" S[        U5      [        [        R                  5      S5         S nAg S nAff = f! [          a>  nT	" S[        U5      [        [        R                  5      [        U5      5         S nAg S nAff = f! [          a>  nT	" S[        U5      [        [        R
                  5      [        U5      5         S nAg S nAff = f)NrL  	succeededzaccuracy error)r  r   r  r  r  r  r  r  )
func_to_exportexport_funcexport_argsexport_typetraced_resultr  re   	ep_moduler  r  s
            r,   _log_exportability!trace.<locals>._log_exportability  sA    . <	'D	"K0 8NN1$556$	 -[)3~/E/E+FG  1S-s>3I3I/JK   1$778F	   1S-s>3O3O/PRUVWRX 	sE   A? C D ?
C 	-B;;C 
D4DD
E4EEc                 Z    [         R                  R                  XSS9R                  5       $ )NF)rG   )r$   r  r;   )rW  r  s     r,   _direct_export_and_lower'trace.<locals>._direct_export_and_lower>  s%    <<&&t&GNNPPr/   c                 L   > T" X5      R                  5       R                  5       $ rC   )convertr;   )rW  r  r  s     r,   &_convert_ts_to_export_source_to_source5trace.<locals>._convert_ts_to_export_source_to_sourceA  s     !$4<<>EEGGr/   )r   r'  r(  FutureWarningtorch._utils_internalr  r  r  r  r	   torch._export.converterr  torch.export._tracer  r  r#   r$   rP  r   r  r  r  r  )rW  ri  r  r   rV  rI  rG   rH   r   r   r   r   r  r  r  r  r  traced_func_for_exportr  re   r  r  r  r  r  s                          @@r,   rL  rL  9  sT   B 8A		
  K 'M+,FG "":	

 "-)%++'/!5'"
 >
Q(	T	Q	H 0%))2H2HII&())	 	".((		
 	"2((		
 r/   _trace_module_mapc                   ^^ [         (       d  U $ Ub  [        R                  " S[        SS9  [	        S5      n[        U [        R                  R                  5      (       d  [        S5      e[        U[        5      (       d  [        S5      e[        R                  R                  R                  n 0 mUU4S jmU TS'   T[        R                  R                  l        T" U S5        [        XU	5      nUR                  5        GH-  u  nnUS	:X  a  U n[!        X5      n[#        U5      nO[!        X5      n[#        U5      n[        U[        5      (       aa  U
(       aZ  U H1  nUU;  d  M  S
SR%                  U5      -   S-   n['        SU SU 35      e   UR(                  R+                  UUUUUUUU5        O-[-        U5      nUR(                  R/                  UUUUUUUU5        UR(                  R1                  U5      nU(       d  GM  Ub  [3        UUUUUUSUU
S9	  GM  [3        U/UUUUUSUU
S9	  GM0     U[        R                  R                  l        U$ ! U[        R                  R                  l        f = f)a   
Trace a module and return an executable :class:`ScriptModule` that will be optimized using just-in-time compilation.

When a module is passed to :func:`torch.jit.trace <torch.jit.trace>`, only
the ``forward`` method is run and traced. With ``trace_module``, you can specify a dictionary of
method names to example inputs to trace (see the ``inputs``) argument below.

See :func:`torch.jit.trace <torch.jit.trace>` for more information on tracing.

Args:
    mod (torch.nn.Module):  A ``torch.nn.Module`` containing methods whose names are
                            specified in ``inputs``. The given methods will be compiled
                            as a part of a single `ScriptModule`.
    inputs (dict):  A dict containing sample inputs indexed by method names in ``mod``.
                            The inputs will be passed to methods whose names correspond to inputs'
                            keys while tracing.
                            ``{ 'forward' : example_forward_input, 'method2': example_method2_input}``
Keyword arguments:
    check_trace (``bool``, optional): Check if the same inputs run through
                                  traced code produce the same outputs. Default: ``True``. You might want
                                  to disable this if, for example, your network contains non-
                                  deterministic ops or if you are sure that the network is correct despite
                                  a checker failure.

    check_inputs (list of dicts, optional): A list of dicts of input arguments that should be used
                                             to check the trace against what is expected. Each tuple
                                             is equivalent to a set of input arguments that would
                                             be specified in ``inputs``. For best results, pass in a
                                             set of checking inputs representative of the space of
                                             shapes and types of inputs you expect the network to see.
                                             If not specified, the original ``inputs`` are used for checking
    check_tolerance (float, optional): Floating-point comparison tolerance to use in the checker procedure.
                                       This can be used to relax the checker strictness in the event that
                                       results diverge numerically for a known reason, such as operator fusion.
    example_inputs_is_kwarg (``bool``, optional): This parameter indicate whether the example inputs is a pack
                                       pack of keyword arguments. Default: ``False``.

Returns:
    A :class:`ScriptModule` object with a single ``forward`` method containing the traced code.
    When ``func`` is a ``torch.nn.Module``, the returned :class:`ScriptModule` will have the same set of
    sub-modules and parameters as ``func``.

Example (tracing a module with multiple methods)::

    import torch
    import torch.nn as nn


    class Net(nn.Module):
        def __init__(self) -> None:
            super().__init__()
            self.conv = nn.Conv2d(1, 1, 3)

        def forward(self, x):
            return self.conv(x)

        def weighted_kernel_sum(self, weight):
            return weight * self.conv.weight


    n = Net()
    example_weight = torch.rand(1, 1, 3, 3)
    example_forward_input = torch.rand(1, 1, 3, 3)

    # Trace a specific method and construct `ScriptModule` with
    # a single `forward` method
    module = torch.jit.trace(n.forward, example_forward_input)

    # Trace a module (implicitly traces `forward`) and construct a
    # `ScriptModule` with a single `forward` method
    module = torch.jit.trace(n, example_forward_input)

    # Trace specific methods on a module (specified in `inputs`), constructs
    # a `ScriptModule` with `forward` and `weighted_kernel_sum` methods
    inputs = {"forward": example_forward_input, "weighted_kernel_sum": example_weight}
    module = torch.jit.trace_module(n, inputs)

r  r  r  r   z.expected torch.nn.Module as the first argumentz3expected a dictionary of (method_name, input) pairsc                 b   > U R                  5        H  u  p#US-   U-   nUTU'   T" X45        M     g )N.)named_children)r  prefixr   childsubmod_qualnameregister_submodstrace_module_maps        r,   r  &trace_module.<locals>.register_submods  s9    "113"(3,"5*9 ' 8  4r/   __modulert   [,]'z\' is not in forward() method's arguments,
                         valid arguments name are Tr  )r   r'  r(  r  r1   r#   r$   r  r   r  r  rP  _tracer  rw  r"   r>  r   r   	NameErrorrS  #_create_method_from_trace_with_dictrj  _create_method_from_tracerT  r`  )r  r  r  r   rV  rI  rG   rH   r   r   r   r   r  old_module_mapr;   method_nameri  rW  forward_methodargument_nameskeyvalid_argumentscheck_trace_methodr  r  s                          @@r,   rQ  rQ  `  s|   x 8
A		
 7q9Mc588??++MNNfd##RSSYY%%77NX<+-	9 (+$-=		*j)S1BC+1<<>'Ki' !(!:!<^!Ls0!<T!B.$//4K)C.0*-0H*H3*N' !# '33B2CG  * 		=="!#"!	 ",N!;		33"!#"!	 "(!6!6{!C {+ $*''%0G
 !*''%0G
{ ,:R .<		*M .<		*s   1B3I (BI .I !I7c                  ^    [        5       (       a  g[        R                  R                  5       $ )zReturn a boolean value.

Returns ``True`` in tracing (if a function is called during the
tracing of code with ``torch.jit.trace``) and ``False`` otherwise.
F)r   r$   ro   _is_tracingr0   r/   r,   rn  rn  ,  s!     ~~88!!r/   c                   Z   ^  \ rS rSrSrS
U 4S jjrS rU 4S jrU 4S jrS r	S r
S	rU =r$ )TracedModulei7  Tc                   >^ [         TU ]  5         [        U[        R                  R
                  5      (       d   e[        5       m " S S[        R                  R
                  5      n[        R                  R                  [        U5      5      Ul
        U" 5       nU4S jnUR                  Ul        UR                  R                  5        H   u  pxUc  M
  XR                  U'   U" U5        M"     UR                  R                  5        H   u  pyU	c  M
  XR                  U'   U" U	5        M"     UR                  R                  5        HY  u  pz[        R                   R#                  U
5      (       d  M+  XqR                  ;  d  M<  XqR                  ;  d  MM  [%        XWU
5        M[     UR&                  (       a  [)        S[+        U5      -   5      eUR,                  R                  5        H&  u  p{Uc  M
  [/        U[0        S S9UR,                  U'   M(     [        R2                  R4                  R7                  US SSS	9n[        U5      R8                  U R                  S
'   XR                  S'   S H  n[;        X5        M     g )Nc                       \ rS rSrSrg).TracedModule.__init__.<locals>.QualnameWrapperiG  r0   N)rv   rw   rx   ry   rz   r0   r/   r,   QualnameWrapperr  G  s    r/   r  c                 J   > U T;   a  [        S5      eTR                  U 5        g )Nz=TracedModules don't support parameter sharing between modules)r   r9   )paramid_sets    r,   check_unique+TracedModule.__init__.<locals>.check_uniqueP  s(     S  JJur/   z=Modules that have backward hooks assigned can't be compiled: ro  c                     g)Nr0   r0   )r;   s    r,   r   'TracedModule.__init__.<locals>.<lambda>w  s    rr/   FTrl  _name_actual_script_module)_parameters_buffers_modulestraining)rD   rE   r#   r$   r  r   r7   rp  r
   r6   _jit_override_qualnamer  r  r"   r  __dict__ro   _jit_is_script_objectsetattr_backward_hooksr   r   r  rw  r  rP  rr  rt  rv   delattr)r   rE  r  r   r  
tmp_moduler  r   r  bufval	submodulescript_modulerN   s     `          r,   rE   TracedModule.__init__:  s   $0000 	ehhoo 	 271D1D1T1TJ2
. %&
	 #mm
++113KD /4&&t,U# 4 ,,.ID,/##D)S! / ,,.ID..s33 0 00-
#. / Od) 
  $}}224OD (3<4)J%  5 		,,AA)u B 
 "&d!4!4g1>-.GDD Hr/   c                     [        S5      e)Nz"Trace submodules cannot be called.)r   )r   rP   kwargss      r,   rt   TracedModule.forward  s    ?@@r/   c                 n   > SU R                   ;  a  [        TU ]	  U5      $ [        U R                  U5      $ Nr  )r  rD   __getattr__r>  r  )r   attrrN   s     r,   r  TracedModule.__getattr__  s2    "$--77&t,,t11488r/   c                 p   > SU R                   ;  a  [        TU ]	  X5      $ [        U R                  X5        g r  )r  rD   __setattr__r   r  )r   r  r   rN   s      r,   r  TracedModule.__setattr__  s/    "$--77&t33**D8r/   c                     U R                   $ rC   r  r  s    r,   	_get_nameTracedModule._get_name  r  r/   c                      SU R                    3$ )Nzoriginal_name=r  r  s    r,   
extra_reprTracedModule.extra_repr  s    

|,,r/   r0   )NN)rv   rw   rx   ry   _disable_script_metarE   rt   r  r  r  r  rz   r{   r|   s   @r,   r  r  7  s/    C JA9
9
- -r/   r  c                   >    \ rS rSr% \" 5       r\S\4   \S'   S r	Sr
g)ru  i  .rt   c                 @    U R                   S   R                  U5        g)z
Re-construct an instance of TopLevelTracedModule using an instance of a C++ module.

Args:
    cpp_module: The C++ module that this TopLevelTracedModule will be rebuilt around.
r  N)r  _reconstruct)r   
cpp_modules     r,   r  !TopLevelTracedModule._reconstruct  s     	-.;;JGr/   r0   N)rv   rw   rx   ry   r   rt   r   r   __annotations__r  rz   r0   r/   r,   ru  ru    s    "0"2GXc3h2Hr/   ru  fnr  c                    ^ ^ [         R                  " T 5      S[        R                  S[        R                  S[
        4U U4S jj5       mT Tl        STl        T$ )NrP   r
  r  c                  l   > [        5       (       d  T" U 0 UD6$ [        TR                  5      nU" U 0 UD6$ rC   )rn  r   __original_fn)rP   r
  r   r"  rk   s      r,   rk   #_script_if_tracing.<locals>.wrapper  s:    ||t&v&&&,W-B-B&CD+F++r/   T)	functoolswrapsr   rP   r
  r   r%  __script_if_tracing_wrapper)r"  rk   s   `@r,   _script_if_tracingr*    sR    __R,qvv , ,a , , G*.G'Nr/   c                 f    Uc  0 n[        U[        5      (       d  U4n[        XXEU5      " U0 UD6nU$ )aa  Return a tuple on tracing a function or model.

.. warning::
    This function is internal-only and should only be used by the ONNX
    exporter. If you are trying to get a graph through tracing, please go
    through the public API instead::

        trace = torch.jit.trace(nn.LSTMCell(), (input, hidden))
        trace_graph = trace.graph

Trace a function or model, returning a tuple consisting of the both the
*trace* of an execution, as well as the original return value. If return_inputs,
also returns the trace inputs as part of the tuple

Tracing is guaranteed not to change the semantics of the function/module
that is traced.

Args:
    f (torch.nn.Module or function): the function or module
        to be traced.
    args (tuple or Tensor): the positional arguments to pass to the
        function/module to be traced.  A non-tuple is assumed to
        be a single positional argument to be passed to the model.
    kwargs (dict): the keyword arguments to pass to the function/module
        to be traced.

Example (trace a cell):

.. testcode::

    trace = torch.jit.trace(nn.LSTMCell(), (input, hidden))
)r#   r`   r@   )frP   r
  rG   rH   rL   rJ   ri   s           r,   _get_trace_graphr-    sL    R ~dE""w	?3HD Kr/   )r   )F)T)r0   NTFFF)U__doc__
contextlibr   r'  r   osr   r'  enumr   typingr   r   r   r   typing_extensionsr   r$   torch._jit_internalr	   r
   r   r   torch.autogradr   torch.jit._scriptr   r   r   torch.jit._stater   r   torch.nnr   torch.testing._comparisonr   ro   _jit_flattenra   _jit_unflattenr_   r   r   r1   r>   r  r@   r   environgetr   _JIT_DISABLE
_JIT_STATScontextmanagerr   r   r   r   r   r  r   no_gradr`  Warningr)  re  _tracer_warn_use_pythonrj  rw  rz  r  r  r   r  r  rL  r  r  r!  rQ  rn  r  ru  r*  r-  r0   r/   r,   <module>rD     s       	 	   3 3 '   $ B B 1  8 88  XX$$
C4 cN).$B"uxx B"J. JJNN-u5	zz~~3U;ZZ^^/7
 I I  !&		4 W4tD?'	 '&  "O0 O0dEG E  ! ! #      "G2>  GT#t S$   aH	 /3 8DcN+ 2  !IX"Y-< Y-x
H< 
H8AqD> hq!tn $ 
0r/   