
    ^j                       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mZm	Z	 ddl
mZ ddlmZmZmZmZmZ ddlmZ ddlZddlZddlZddlZddlmc mZ ddlmZ ddlmZ dd	lm Z  dd
l!m"Z" ddl#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z.m/Z/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7 ddl8m9Z9 ddl:m;Z;m<Z<m=Z=m>Z>m?Z? ddl@mAZAmBZB ddlCmDZDmEZEmFZFmGZGmHZH ddlmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZR ddlSmTZTmUZU ddlVmWZWmXZXmYZYmZZZ ddl[m\Z\ ddl]m^Z^m_Z_m`Z` ddlambZbmcZc ddldmeZe ddlfmgZg dd lhmiZimjZjmkZkmlZl dd!lmmnZn 	 ddloZp	 dd"lrmsZs erdd#ltmuZu dd$lvmwZw dd%lmxZx  ed&      Zy ed'      Zz ej                  e|      Z}e~j                  ej                   j                   j                  ej                  j                  j                  ej                  j                  j
                  ej                  j                   j                  ej                  j                   j                  ej                  j                  ej                  j                  ej                  j                  j                  ej                  j                  j                  ej                  j                  j                  ej                  j                  j                   ej"                  j$                  j&                  ej                  j(                  j*                  ej                  j(                  j,                  ej                  j(                  j.                  ej                  j(                  j0                  ej                  j2                  j4                  ej6                  j"                  j$                  j&                  ej8                  j"                  j$                  j&                  ej:                  j<                  j>                  ej:                  j<                  j>                  j@                  ejB                  jD                  jF                  j@                  g      Ze~j                  ejJ                  g      Zej                  j                  jN                  ejP                  jR                  ejP                  jT                  ej8                  jV                  ej8                  jX                  ejZ                  jV                  ejZ                  jX                  ej\                  j^                  gZejb                  ejd                  jf                  ej                  jh                  ej                  jj                  ejP                  jl                  ej8                  jn                  ej8                  jl                  ej                  jl                  ejp                  ejr                  ejt                  ejv                  ejx                  ejz                  ej|                  ej~                  ejB                  j                  j                  j                  ej                  ej                  j                  ej                  j                  ejZ                  jn                  ejZ                  jl                  gez   Zej                  jm                         rTeƐj                  ej                  jX                  ej                  j                  ej                  j                  g       e~j                  e      Ze~j                  eƫ      Z eh ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                        Zeed(ef      ed)<    ed* eD              Zee   ed+<   ej                  d,e~eg ef   edz  f   fd-       Ze~j                  g d.      Zej                  j                  ej                  j                  ej                  j                  hZd/eUd0ed,dfd1Zd2ej                  d,eej                  j2                  j                     fd3Zd/eUd,eeej                  edz  f      fd4Zd/d5d,eej:                  j                     fd6Z ej                  d,eed(ef      fd7       Z G d8 d9eU      Z G d: d;e      Z G d< d=ej                        Z G d> d?e      Z G d@ dAe      Z G dB dCe      Zy# eq$ r dZpY 	w xY w# eq$ r dZsY 	w xY w)Dak  
This module implements variable tracking for torch functions and operations during Dynamo tracing.

It provides classes to handle different types of torch operations:

TorchInGraphFunctionVariable: Handles torch.* functions that should be captured in the FX graph.
Provides special handling for constant folding, tensor methods, and torch function overrides.
Manages complex cases like out= variants and parameter construction.

TorchCtxManagerClassVariable: Handles torch context managers like torch.no_grad(), autocast, etc.
Provides implementations for entering/exiting these contexts during tracing.

DispatchKeySetVariable: Represents torch.DispatchKeySet for managing dispatch keys and
device-specific operations during tracing.

The module includes special handling for:
- Constant folding of pure functions
- Tensor method calls
- torch.nn.Parameter construction
- __torch_function__ overrides
- Context manager state tracking
- Device and dtype management

This is a core part of Dynamo's tracing system, translating torch operations into
traceable graph nodes while preserving correct semantics and handling edge cases.
    N)CallableIterable)nullcontext)AnyNoReturnTYPE_CHECKINGTypeVarUnion)TypeIs)DispatchKeySetConstantVariable)StreamVariable)TorchFunctionModeVariable)GuardSourceTracingContext)warning_once)GradientEdge)"is_traceable_wrapper_subclass_type   )configgraph_break_hints	polyfills	variables)	PyCodegen)!can_convert_to_tracable_parameternew_parameter_placeholdertracable_create_parameter) get_registered_device_interfaces)raise_observed_exceptionraise_type_errorunimplemented	UserErrorUserErrorType)GuardBuilderinstall_guard)
AttrSourceCallFunctionNoArgsSourceGlobalStateSourceImportSourceSyntheticLocalSource)
_is_tensorify_enabledcheck_unspec_or_constant_argsguard_if_dynhas_torch_functionhashableis_wrapper_or_member_descriptorproductproxy_args_kwargsunpack_iterableunwrap_if_wrapper   )typestrVariableTracker)AutocastModeVariableProfilerContextVariable%ProfilerRecordFunctionContextVariableTorchFunctionDisableVariable)DistributedVariable)bind_args_cachedClosureConversionErrorNestedUserFunctionVariable)ListVariableTupleVariable)vt_is_iterable)TorchScriptObjectVariable)can_dispatch_torch_functiondispatch_torch_functionTensorWithTFOverrideVariableTorchFunctionModeStackVariable)UserDefinedTupleVariable)_fsdp_param_group)InstructionTranslatorBase)
OpaqueBase)TreeSpecVT.ops_consuming_unbacked_scalarsc              #      K   | ]@  }|j                   |j                   d z   fD ]   }t        t        j                  |      r| " B yw)_N)__name__hasattrtorchTensor).0fnnames      h/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/torch/_dynamo/variables/torch.py	<genexpr>r\     sM      ?
bkkC/0? 	u||T" 	??s   AA"methods_consuming_unbacked_scalarsreturnc                  "   t         j                  j                  dt         j                  j                  dt         j                  j
                  d t         j                  j                  j                  dt         j                  j                  j                  dt         j                  j                  dt         j                  j                  j                  dt         j                  j                  dt         j                   j                  dt         j                   j"                  dt         j                   j$                  dt         j                  j&                  j(                  dt         j*                  j,                  j.                  j0                  diS )NFT)rV   jitis_scripting
is_tracing_C_get_tracing_statefx_symbolic_traceis_fx_tracingis_fx_symbolic_tracingonnxis_in_onnx_export_dynamoexternal_utilsis_compiling_utilscompileris_dynamo_compilingis_exporting
eval_frame_is_in_optimized_modulennmodules
activation_is_make_fx_tracing     r[   tracing_state_functionsrz     s     					e##T  ..  77

$$e$$114!!4##T**D##T  88$ 	##77# ry   )addsubmuldivsqrtvararg_namec                    ddl m} ddlm} t	        | t
              rpt        | j                        t        u rU| j                  r| j                  j                  nd}d| }|r|d| z  }t        d|dd	d
gt        j                         yt	        | |      r0t        | j                        D ]  \  }}t!        || d| d        yt	        | |      r| j                  j                         D ]m  \  }}|j"                  j%                         s"t        dd| dg t        j                         |j"                  j'                         }	t!        || d|	d       o yy)zCheck if var contains a GradientEdge from outside the compiled region.

    Used by handle_autograd_grad to reject external GradientEdge objects that
    cannot be traced through.
    r7   ConstDictVariableBaseListVariableNzGradientEdge in z: z(autograd.grad with external GradientEdgea  torch.autograd.grad() cannot be used with GradientEdge inputs passed from outside the compiled region. The GradientEdge contains a reference to an autograd node that was created before torch.compile started tracing, so Dynamo cannot trace through its computation.z?Move the autograd.grad() call outside the torch.compile region.z>Or use tensor inputs directly instead of GradientEdge objects.gb_typecontextexplanationhints[]z(autograd.grad with non-constant dict keyznon-constant key in z;autograd.grad/backward dict inputs must have constant keys.)dictsr   listsr   
isinstancerJ   typevaluer   sourcerZ   r#   r   SUPPORTABLE	enumerateitems_check_for_gradient_edgevtis_python_constantas_python_constant)
r   r   r   r   source_infor   iitemhash_keykey_reprs
             r[   r   r   =  s]    )'#/0T#))_5T),cjjoo$XJ/K=))G>S RP #..	
 
C)	* + 	?GAt$ThZq1+=>	?	C*	+!iioo/ 		HNHd;;113F28*= ]:-99:	  {{557H$ThZqA+FG		H 
,ry   tensorc                    ddl m} ddlm} t	               }g } ||       r || |       n|j                  |        |D ]  }t        |t        j                        s|j                  |j                  |j                         |j                  R|j                  j                  i|j                  |j                  j                          |S )Nr   )get_plain_tensorsis_traceable_wrapper_subclassout)torch._subclasses.fake_tensorr   torch.utils._python_dispatchr   setappendr   rV   rW   grad_fnr{   _base)r   r   r   grad_fnsplain_tensorsts         r[   _collect_all_grad_fnsr   l  s    ?J/2uHJLM$V,&m4V$ 	*!U\\*99 LL# 77177??#>LL)	* Ory   c           	         ddl m} ddlm} ddlm} ddlm} ddlm	} g }t        | |      rO| j                         j                  j                  j                  d      }t        |t        j                         st#        d	t%        |             t        |t        j&                  j(                  j*                        rn ||      rdg }t        j&                  j(                  j-                  ||
       t/        d |D              s<t#        d|D 	cg c]  }	t%        |	       c}	       t#        dt%        |             | j0                  r| j0                  j2                  nd}
|j5                  ||
f       |S t        | |      r*|j7                  t9        | j;                                      |S t        | |      r-| j<                  D ]  }|j7                  t9        |              |S t        | |      r;| j<                  j?                         D ]  }|j7                  t9        |              |S tA        ddt%        |       jB                   dt%        |       jB                   ddg       |S c c}	w )zExtract (fake_tensor, source_name) pairs from a VariableTracker.

    Used by handle_autograd_grad to collect tensors from the outputs and inputs
    arguments for grad_fn reachability analysis.
    r   r   r7   r   LazyVariableTrackerr   TensorVariableexample_value/Expected fake_tensor to be a torch.Tensor, got r   c              3      K   | ]L  }t        |t        j                        r0t        |t        j                  j                  j
                         N y wN)r   rV   rW   _subclassesfake_tensor
FakeTensor)rX   r   s     r[   r\   z0_collect_tensors_with_sources.<locals>.<genexpr>  s?      a. 1e//;;FFGs   AAz2Expected all plain tensors to be FakeTensors, got z%Expected FakeTensor or subclass, got Nz,autograd.grad with unsupported argument typegot z3torch.autograd.grad() received an argument of type @ which is not supported. Expected tensor or sequence of tensors.HEnsure outputs and inputs arguments are tensors or sequences of tensors.r   )"r   r   r   r   lazyr   r   r   r   r   r   as_proxynodemetagetrV   rW   AssertionErrorr   r   r   r   r   allr   rZ   r   extend_collect_tensors_with_sourcesrealizer   valuesr#   rT   )r   r   r   r   r   r   resultsr   plainr   source_namer   s               r[   r   r     sZ    K()'&57G#~&lln))..22?C+u||4 A${BSATU  k5#4#4#@#@#K#KL*;7 #%E));; <    
 %H[`IaVW$q'IaHbc  !7[8I7JK  *-cjjoo[12, N+ 
C,	-4S[[]CD& N% 
C)	*II 	@DNN8>?	@" N 
C*	+II$$& 	@DNN8>?	@ N 	B49--./Ed3iFXFXEY ZR R [
	
 N; Jbs   I2
r9   c                    ddl m} ddlm} ddlm} g }t        | |      r<| j                         j                  }|j                  dk(  r|j                  |       |S t        | |      r*|j                  t        | j                                      |S t        | |      r-| j                  D ]  }|j                  t        |              |S t        ddt!        |       j"                   dt!        |       j"                   d	d
g       |S )ud  Recursively collect FX placeholder nodes from a VariableTracker.

    The returned placeholder nodes carry grapharg.example (real tensor) and
    example_value (FakeTensor) metadata — comparing these reveals lost
    autograd linkage (e.g., grad_fn dropped during tracing).
    See NOTE [Detecting lost autograd linkage in closure-captured tensors].
    r7   r   r   r   placeholderz-_autograd_grad with unsupported argument typer   z._autograd_grad() received an argument of type r   r   r   )r   r   r   r   r   r   r   r   r   opr   r   _collect_placeholder_nodesr   r   r#   r   rT   )r   r   r   r   resultr   r   s          r[   r   r     s    *'&"$F#~&||~""77m#MM$$ M# 
C,	-0?@  M 
C)	*II 	<DMM4T:;	< M 	C49--./@cASAS@T UR R [
	
 Mry   c                  N   ddl m}  ddlm} ddlm} t        | j                   |       j                                     }|j                   |              t        j                  t        j                  t        j                  t        j                  h}|j                  |       |S )Nr   )chain)get_overridable_functions)_device_constructors)	itertoolsr   torch.overridesr   torch.utils._devicer   r   from_iterabler   updaterV   	ones_like
zeros_like
empty_like	full_like)r   get_overridable_functions_r   funcsmores        r[   r   r     sw    W8##$>$@$G$G$IJKE	LL%'(	%D 
LLLry   c                   $    e Zd ZdZedededd fd       Zdededdf fdZdd	Z	defd
Z
defdZdefdZ	 ddddededefdZ	 ddddededefdZdddededededefdZdedeeef   fdZdddededefdZdddedefdZdefdZ xZS )BaseTorchVariablezHcommon base for all torch.* functions, classes, modules and other thingsr   r   r^   c                 J   t        j                  |      r*t        |j                  t        j
                               n[t        j                  |      r*t        |j                  t        j                               nt        j                  |      r)t        |j                  t        j                               nt        j                  |      s>t        |t        j                  j                  t        j                  j                  f      r)t        |j                  t        j                                nbt#        |      s.t        |t        j$                  j&                  j(                        rn(t        |j                  t        j*                                | ||      S Nr   )inspectisclassr'   
make_guardr&   CLASS_MATCHismoduleMODULE_MATCH
isfunctionCLOSURE_MATCH	isbuiltinr   rV   _ops
OpOverloadOpOverloadPacketBUILTIN_MATCHr2   rk   compiled_autogradOpFUNCTION_MATCHclsr   r   s      r[   create_with_sourcez$BaseTorchVariable.create_with_source	  s   ??5!&++L,D,DEFe$&++L,E,EFG&&++L,F,FGHu%EJJ))5::+F+FG*
 &++L,F,FGH,U3z5==22558
 &++L,G,GHI5((ry   kwargsNc                 2    t        |   di | || _        y )Nrx   )super__init__r   )selfr   r   	__class__s      r[   r   zBaseTorchVariable.__init__  s    "6"
ry   c                 <   	 | j                   j                   d| j                   j                   }dt        j                  dd|      z   }|j                  |j                  || j                                y # t        $ r dt	        | j                          }Y iw xY w)N.
torch_obj___z[^a-zA-Z0-9_]+rS   )	r   
__module__rT   	Exceptionidrer|   extend_outputsetup_globally_cached)r   codegenrZ   unique_var_names       r[   reconstructzBaseTorchVariable.reconstruct"  s    	1jj++,Adjj.A.A-BCD (93!EE))/4::F	
  	14::/0D	1s   /A7 7!BBc                     | j                   S r   r   r   s    r[   r   zBaseTorchVariable.as_proxy,      zzry   c                     | j                   S r   r  r  s    r[   r   z$BaseTorchVariable.as_python_constant/  r  ry   c                     | j                   S r   r  r  s    r[   get_real_python_backed_valuez.BaseTorchVariable.get_real_python_backed_value2  r  ry   txrL   otherreversec                 ,    | j                  ||dd|      S )N__or____ror___nb_binop_implr   r  r  r  s       r[   
nb_or_implzBaseTorchVariable.nb_or_impl5  s     ""2uh	7KKry   c                 ,    | j                  ||dd|      S )N__sub____rsub__r  r  s       r[   nb_subtract_implz"BaseTorchVariable.nb_subtract_impl=  s     ""2uiWMMry   forwardreverse_dunderc                    |r|n|}t        t        | j                        |d       }|t        j                  |t
              S 	 |j                         } || j                  |      }	|	t
        u rt        j                  |t
              S t        j                  ||	      S # t        $ r t        j                  |t
              cY S w xY wr   )getattrr   r   r9   buildNotImplementedr   NotImplementedError)
r   r  r  r#  r$  r  dundermethod	other_valr   s
             r[   r  z BaseTorchVariable._nb_binop_implE  s     $+djj)648>"((^<<	=002I 

I.^#"((^<<$$R00 # 	="((^<<	=s   B #CCc                 0    t        | j                        dfS NF)hashr   r   r  s     r[   	hash_implzBaseTorchVariable.hash_implZ  s    DJJ&&ry   r   c                 $    ddl m}  || |||      S )Nr7   )object_richcompare)object_protocolr3  )r   r  r  r   r3  s        r[   richcompare_implz"BaseTorchVariable.richcompare_impl]  s     	8!$E266ry   rZ   c                 Z    t        | j                  |      }t        j                  ||      S r   )rU   r   r9   r'  )r   r  rZ   r   s       r[   call_obj_hasattrz"BaseTorchVariable.call_obj_hasattrd  s'     T*$$R00ry   c                     | j                   t        v ry| j                   t        j                  j                  u rt
        j                  ryt        | j                   dd       dk(  S )NTr  math)r   constant_fold_functionsrV   autograd_profiler_enabledr   'constant_fold_autograd_profiler_enabledr&  r  s    r[   can_constant_fold_throughz+BaseTorchVariable.can_constant_fold_throughj  sP    ::00 JJ%..:::>> tzz<6&@@ry   )r  r   r^   NF)rT   r  __qualname____doc__classmethodr   r   r   r   r  r   r   r  r9   boolr  r"  strr  tupleintr1  r5  r   r7  r>  __classcell__r   s   @r[   r   r     s   R)s )F )?R ) )(c S T 
# C c  	L'L L 	L
 
L 	N'N N 	N
 
N1'1 1 	1
 1 1 
1*'C 'E#t)$4 '7-76E7KN7	71-1581	1A4 Ary   r   c                   `     e Zd ZdZdefdZededefd       Z	ddde
e   d	d
ddf fdZ xZS )TorchCtxManagerClassVariablezLPoints to a context manager class in torch.* that dynamo has implementationsr^   c                 "    d| j                    dS )NzTorchCtxManagerClassVariable()r  r  s    r[   __repr__z%TorchCtxManagerClassVariable.__repr__  s    .tzzl!<<ry   r   c                 \    t        |       } t        |       xr t        |       xr | t        v S r   )r6   callabler1   supported_ctx_manager_classesr  s    r[   is_matching_clsz,TorchCtxManagerClassVariable.is_matching_cls  s6     "%( UO  ;::	
ry   r  rL   argsr   dict[str, VariableTracker]r9   c           
      >   ddl m}m}m}m}m}m}	m}
m}m	}m
}m}m}m} | j                  t        j                   u rlt#        |      dk(  rLt%        |d   t&        j(                  j*                        r%|
j-                  |d      }|j/                  |||      S |
j-                  |d      S | j                  t        j0                  u rlt#        |      dk(  rLt%        |d   t&        j(                  j*                        r%|
j-                  |d      }|j/                  |||      S |
j-                  |d      S | j                  t        j2                  u r3t#        |      dk(  r%|
j-                  ||d   j5                         d      S | j                  t        j6                  u rt#        |      dkD  rt9        dt#        |             t#        |      dk7  rt9        dt#        |             t#        |      dk(  r|d   j5                         nd}|j-                  ||      S | j                  t        j:                  j<                  j>                  t        j:                  j<                  j>                  j@                  fv rot#        |      dkD  rt9        d	t#        |             t#        |      dk7  rt9        d
t#        |              ||d   j5                         | jB                        S tE        jF                  | j                        rZtI        | j                  t        jJ                        r6ddl&m'}  ||||jP                  jS                  d| j                  di             S | j                  t        jT                  jV                  jX                  t        jZ                  jT                  jX                  t        j\                  jT                  jX                  fv r!t_        j,                  | j                  ||      S | j                  t        j`                  jb                  t        jd                  j`                  jb                  fv r"tg        j,                  | j                  ||      S | j                  t        j`                  jh                  t        jd                  j`                  jh                  fv r%tk        tl        d| j                         to               S | j                  t        jp                  jr                  u s&| j                  t        jp                  jt                  u rJ|s|rt9        d      tw        j,                  || j                  t        jp                  jr                  u       S | j                  t        jx                  jz                  j|                  u r7t#        |      dk7  rt9        dt#        |             |j-                  ||      S | j                  t        jx                  j~                  j                  u r6t#        |      dk7  rt9        dt#        |             |j-                  |      S | j                  t        jd                  j                  j                  u rNt#        |      dk7  rt9        dt#        |             |j-                  ||D cg c]  }t        |       c}      S | j                  t        jd                  j                  j                  u r6t#        |      dk7  rt9        dt#        |             |j-                  |      S | j                  t        jx                  j~                  j                  u r6t#        |      dk7  rt9        dt#        |             |j-                  |      S | j                  t        jx                  j~                  j                  u rNt#        |      dk7  rt9        dt#        |             |	j-                  ||D cg c]  }t        |       c}      S | j                  t        jd                  j                  j                  u rHt#        |      dk7  rt9        dt#        |             |j-                  ||d   j5                               S t        r| j                  t        j                  j                  u rLt#        |      dk7  rt9        dt#        |             |j-                  ||d   |d   j5                               S | j                  t        j                  j                  j                  j@                  u r\t        | j                  || jB                  ||      }|d   j5                         }|d   j5                         }|j-                  |||      S t        | ]  |||      S c c}w c c}w )Nr7   )!DisabledSavedTensorsHooksVariableDualLevelContextManager&FSDPParamGroupUseTrainingStateVariableFxTracebackAnnotateVariable&GradIncrementNestingCtxManagerVariable)GradInplaceRequiresGradCtxManagerVariableGradModeVariableInferenceModeVariable%JvpIncrementNestingCtxManagerVariableSDPAKernelVariableSetFwdGradEnabledContextManagerr   &VmapIncrementNestingCtxManagerVariabler   FT)initializedz0torch.inference_mode expects at most 1 arg, got z,torch.inference_mode expects no kwargs, got z7torch.fx.traceback.annotate expects at most 1 arg, got z3torch.fx.traceback.annotate expects no kwargs, got r   )wrap_fx_proxy_clscall_functionrx   )funcrecord_argsrecord_kwargsz$Profiler function %s will be ignoredzKDisableTorchFunctionSubclass/DisableTorchFunction expects no args or kwargs)only_subclassr   z+vmap_increment_nesting expects 2 args, got z*jvp_increment_nesting expects 0 args, got z)_set_fwd_grad_enabled expects 1 arg, got zdual_level expects 0 args, got z+grad_increment_nesting expects 0 args, got z0enable_inplace_requires_grad expects 1 arg, got z/disable_saved_tensors_hooks expects 1 arg, got z6FSDPParamGroup.use_training_state expects 2 args, got backendsset_priority)Q rU  rV  rW  rX  rY  rZ  r[  r\  r]  r^  r_  r   r`  r   rV   no_gradlenr   r   	functionsBaseUserFunctionVariablecreaterc  enable_gradset_grad_enabledr   inference_moder   re   	tracebackannotate__wrapped__r   r   r   
issubclassStreamtorch._dynamo.variables.builderrb  outputcreate_proxyampautocast_modeautocastcudacpur:   profilerrecord_functionr;  r<   profiler   logr;   rc   DisableTorchFunctionSubclassDisableTorchFunctionr=   
_functorchvmapvmap_increment_nestingeager_transformsjvp_increment_nesting
forward_ad_set_fwd_grad_enabledr/   
dual_levelgrad_increment_nestingenable_inplace_requires_gradgraphdisable_saved_tensors_hooksrK   FSDPParamGroupuse_training_statert   	attentionsdpa_kernelr?   r   )r   r  rR  r   rU  rV  rW  rX  rY  rZ  r[  r\  r]  r^  r_  r   r`  ctxinf_moderb  xname_to_arg_maprh  ri  r   s                           r[   rc  z*TorchCtxManagerClassVariable.call_function  s   	
 	
 	
 	
  ::&4yA~*Q,,EE# '--b%8((T6::'..r599ZZ5,,,4yA~*Q,,EE# '--b$7((T6::#**2t44ZZ5111c$i1n#**DG..0d +   ZZ5///4y1}$Fs4ykR  6{a$B3v;-P  8;4yA~tAw1134H(//H==ZZHH''HH''33
 
 4y1}$McRVi[Y  6{a$I#f+W  /Q**,T[[  __TZZ(Z

ELL-QI$		&&#JJ		 	 ZZII##,,JJNN##IIMM""
 
 (..tzz4HHZZNN**NN##33
 
 9??ZZT  ZZNN""NN##++
 
 DdjjQ*,,JJ%((???zzUXX:::v$a  066$**0U0U"U  ZZ5++00GGG4yA~$A#d)M  :@@  ZZ5++<<RRR4yA~$@TL  9??CCZZ5>>44JJJ4yA~$?D	{K  399*./Qa/  ZZ5>>44???4yA~$'Fs4yk%RSS*11"55ZZ5++<<SSS4yA~$A#d)M  :@@DDJJ%**;;XXX4yA~$Fs4ykR  =CC*./Qa/  ZZ5>>//KKK4yA~$Ec$i[Q  5;;DG..0  )

/>>QQQ4yA~$LSQUYKX  :@@DGT!W779  ZZ588--99EEE.

O 'z2EEGH*>:MMOL%,,R<HHw$Rv66m 0* 0s   f
%f
)rT   r  r@  rA  rD  rM  staticmethodr   rC  rQ  listr9   rc  rG  rH  s   @r[   rJ  rJ    so    V=# = 
s 
t 
 
{7'{7 ?#{7 -	{7
 
{7 {7ry   rJ  c                       e Zd ZdZdZdZy)AllowInGraphKinddefaultnonstrict_traceleaf_functionN)rT   r  r@  DEFAULTNONSTRICT_TRACELEAF_FUNCTIONrx   ry   r[   r  r  X  s    G'O#Mry   r  c            
       6    e Zd ZdZ	 ddedef   dedz  deddf fdZdefd	Z	dedef   fd
Z
eej                  deedef   edef   f   fd              Zdddee   ddddfdZdddee   dddefdZdddee   deeef   deeef   fdZdddee   deeef   defdZdddee   deeef   defdZe	 	 d dddedz  dedefd       Zedddededefd       Zdddee   deeef   defdZdefdZdddee   deeef   defdZde defdZ! xZ"S )!TorchInGraphFunctionVariablez@Points to a torch function/method that should be put in FX graphNr   .kindr   r^   c                     t        |   |fi | ddlm}m} |P ||      rt
        j                  }|| _	        y  ||      rt
        j                  }|| _	        y t
        j                  }|| _	        y )Nr   )is_leaf_functionis_nonstrict_trace_callable)
r   r   trace_rulesr  r  r  r  r  r  r  )r   r   r  r   r  r  r   s         r[   r   z%TorchInGraphFunctionVariable.__init__a  sm     	)&)O<&'55 	 -U3'77 	 (//	ry   c                 <    d| j                    d| j                   dS )NzTorchInGraphFunctionVariable(z, kind=rL  )r   r  r  s    r[   rM  z%TorchInGraphFunctionVariable.__repr__t  s    .tzzl'$))ANNry   c                     | j                   S r   r  r  s    r[   get_functionz)TorchInGraphFunctionVariable.get_functionw  r  ry   c                  /  _`abcdefghijkl i jdt         dt        f   dt         t         dt        f   gt         dt        f   f   fjfd} ddlm} ddlm_m`mambm	cm
dme dd	lmkml  | t                d
ddt         dt         dt         fd       } | t"         d
ddt         dt         dt         fd       } | t$        j&                  j(                  j*                        d
ddt         dt         dt         fd       } | t$        j,                  j.                  j0                  j2                        d
ddt         dt         dt         f_fd       } | t4        j6                        d
ddt         dt         dt         dz  fd       }t9        t4        d      r4 | t4        j:                        d
ddt         dt         dt         dz  fd       } | t$        j<                        d
ddt>        fd       } | t$        j@                  t$        j&                  jB                        d
ddt         dt         f_efd       }	 | t$        jD                  t$        jF                        d
ddt        dt         dz  fd       }
 | t$        jH                        d
ddt        dt         dz  fd       } | t$        jJ                        d
ddt         dt         dt         fd       } | t$        jL                  jN                  t$        jP                  jR                        d
ddt         dt         dt         fd       } | tT         d
ddt         dt         fd       } | t$        jV                  jX                  jZ                  j\                  t$        jV                  jX                  jZ                  j^                  t$        jV                  jX                  jZ                  j`                  t$        jV                  jX                  jZ                  jb                  t$        jV                  jX                  jZ                  jd                        d
ddt         dt         dt         fd       } | t$        jf                        d
dd_f`fd        } | t$        jh                  jj                  jl                        d
dd!t         dafafd"       } | t$        jh                  jj                  jn                        d
dd!adt         fd#       } | t$        jp                        	 dd
dd!t        d$t         tr        z  dt         f_fd%       } | t$        jt                        d
ddt         fd&       } | t$        jv                        d
ddt         fd'       } | t$        jx                        d
dd(t         d)t         dt         f_fd*       } | t$        jz                        d
dd)t         dt         f_fd+       } | t$        j|                  j~                  j                        d
ddt         fd,       } | t$        j|                  j~                  j                        d
ddt         fd-       } | t$        j|                  j~                  j                        d
ddt         fd.       } | t$        j|                  j~                  j                        d
dd/t         dt         f_fd0       } | t$        j                  j|                  j                        d
ddt         fd1       } | t$        j                  j|                  j                        d
ddt         fd2       } | t$        j                  j|                  j                        d
dd3t         dt         f_fd4       } | t$        j                        d
dd_fd5       } | t$        j                  j                        d
dd_fd6       }  | t$        j                  j                        d
dd_fd7       }! | t$        j                  j                        d
dd_fd8       }" | t$        j&                  j                  t$        j&                  j                  t$        j&                  j                        d
ddt         d_fd9       }# | t$        j                  j                        d
dd:t         d;t         dt         dt         dt         fd<       }$ | t        j                  d= t               D               d
dd>d?dbfbfd@       }% | t$        j                        d
ddt         ddfdlfdA       }& | t$        j                  j                        d
ddBt        dCt        dt        fdD       }' | t$        j                  j                  j                        d
ddEt        dFt        d_fdG       }( | t$        jZ                  j                  j                        d
ddt         dt         dt         fdH       }) | t$        jV                  j                        d
ddt         dt         dt         fdI       }* | t$        j,                  j                  j                  t$        j,                  j                  j                  j                        	 ddJt        d
ddKt        dz  dt         dz  fdL       }+ | t$        j,                  j                  j                  t$        j,                  j                  j                  j                        	 ddJt        d
ddKt        dz  dt         dz  fdM       }, | t$        j                        d
ddt         dt         dt         dz  fdN       }- | t$        j                        d
ddOt         dPt         dt         dt         dz  f
dQ       }. | t$        j                        dRt        d
ddt         dt         dt         dz  f
dS       }/ | t$        j                        dRt        d
ddt         dt         dt         dz  f
dT       }0 | t$        j                  j                        dRt        d
ddt         dt         dt         f
dU       }1 | t$        j                        d
ddVt         dWt         dt         dz  f_fdX       }2 | |      d
ddt         dt         dt         fkfdY       }3t        j                         r;ddZlimj}4mk}5ml}6mm}7mn}8mo}9mp}:  | |4|5|6|8|7|9|:      d
ddt         dt         dt         fd[       }; | t$        j                  j                        	 ddd\d
dd]t         dz  dt         d^t        dz  dt         ddfd_       }< | t$        jV                  j                  j                        d
ddt         dt         ddfd`       }= | t$        j                  j                  j                  j                        d
ddat         dt         dz  fcfdb       }> | t$        j                  j                  j                  j                        	 dd
ddat         dct         dz  dt         dz  fcfdd       }? | t$        j                  j                  j                  j                        d
ddat         dt         dz  fcfde       }@ | t$        j                  j                  j                  j                        d
ddat         dt         dz  fcfdf       }A | t$        j                  j                  j                  j                        d
ddat         dt         dz  fcfdg       }B | t$        j                  j                  j                  j                        d
ddat         dt         dz  fcfdh       }C | t$        j                  j                  j                  j                        d
ddit         dt         dz  fdj       }D | t$        j                  j                  j                  j                        d
ddat         dt         fcfdk       }E | t$        j                  j                  j                  j                         d
ddat         dt         dz  fcfdl       }F | t$        j                  j                  j                  j                        d
ddmt         dt         dz  fcfdn       }G | t$        j                  j                  j                  j                        d
ddmt         dt         dz  fcfdo       }H | t$        j                  j                  j                  j                        d
ddat         dt         dz  fcfdp       }I | t$        j                  j                  j
                        d
ddt         dt         dt         fdq       }J | t$        j                  j|                  j                        d
ddt         dt         defefdr       }K | t$        j|                  j                  j                        d
ddt         dt         dt        fds       }L | t$        j                        d
ddt         dt         dt         dz  fcfdt       }M | t$        j                  j                        d
ddt         dt         dt        fdu       }N | t$        j                  j                        d
ddt         dt         dt         f_fdv       }O | t$        j                  j                        d
ddt         dt         dt         fdw       }P | t$        j                  j                        d
ddt         dt         dt        fdx       }Q | t$        j                   j*                        d
ddt         dt         dt         fdy       }R | t$        j"                  j$                  t$        j&                  j$                  t$        j(                  j$                        d
ddt         dt         dt*        fdz       }St$        j&                  j,                  d{t$        j(                  j,                  d|t$        j.                  j,                  d}t$        j0                  j,                  d~if | t$        j"                  j,                  t$        j&                  j,                  t$        j(                  j,                  t$        j.                  j,                  t$        j0                  j,                        d
ddt         dt         dt         f_ffd       }T | t$        j2                        d
ddt         dt         dt         f_fd       }Uddlmh  | h      d
ddt         dt         dt         fdhfd       }Vt8        fd
ddt         dz  dt         dz  dt:        t<           dt         f
_kfdg | t$        j>                        d
ddt         dt         dt         fgfd       }W | t$        j@                  t$        jB                  t$        jD                  t$        jF                  t$        jH                        d
ddt         dt         dt         fgfd       }X | t$        jJ                  t$        jL                        d
ddt         dt         dt         fgfd       }Yd
ddtN        t            dt        tP        t         f   dt         t        gt        dz  f   dt         f
di | t$        j&                  jR                        d
ddt         dt         dt         fifd       }Z | t$        j&                  jT                        d
ddt         dt         dt         fifd       }[ | t$        jV                  jX                  jZ                        d
ddt         dt         dt         fd       }\ | t$        jh                  j\                        	 	 dd       }] | t$        j|                  j^                  j`                        d
ddt         dt         dt         dz  fd       }^jS )zBuild a dict from function -> method to handle it so that we are O(1)
        in terms of the number of function with special handling.fns.r^   c                       dt         dt        f   dt         dt        f   f fd}t         d         st        dt	         d                |S )Nhandler.r^   c                 D    D ]  }|v rt        d|       | |<    | S )NzHandler already registered for r   )r  rY   r  handlerss     r[   	_registerzOTorchInGraphFunctionVariable._get_handlers.<locals>.register.<locals>._register  s<     +BX~,/Nrd-STT#*HRL+ ry   r   z,Expected first argument to be callable, got )r   r   rO  r   r   )r  r  r  s   ` r[   registerz<TorchInGraphFunctionVariable._get_handlers.<locals>.register  s]    8CH#5 (38:L  CF#$B4A<.Q  ry   r   )
SDPAParamsr7   )r   r[  r\  StreamContextVariableSymNodeVariabler   UserDefinedObjectVariable)wrap_fx_proxyrb  r  rL   rR  r   c                    |rt        dt        |             |rt        dt        |             | j                  t        j                  j
                  t        j                  j                  j
                  t        j                  j
                  t        j                  j                  t        j                  j                  t        j                  j                  j                  fv r|j                          | j                  t        j                  j                  u r.t        j                  |t        j                  j                         S t        j                  |t#               | j                           S )Nz,Tracing state functions expect no args, got z.Tracing state functions expect no kwargs, got )r   rl  r   rV   rn   rm   rk   rl   ro   rp   rq   rr   rs   mark_inconsistent_side_effectsr9   r'  _is_exporting_flagrz   r   r  rR  r   s       r[   handle_tracing_state_functionszRTorchInGraphFunctionVariable._get_handlers.<locals>.handle_tracing_state_functions  s    $B3t9+N  $DS[MR  zz)),,99++22++((@@	 	 113 zzU^^888&,,R1R1RSS"((-D-Ftzz-RSSry   c                 l   |rt        dt        |             | j                  t        j                  j
                  u r9t        |      dk7  rt        dt        |             |d   j                         st        d      |d   j                  j                  j                  d   }| j                  |      }t        |t        j                  j                        r|t        j                  j                  t        j                  j                  j                        z
  t        j                  j                  t        j                  j                  j                         z
  }t"        j%                  |      S |rt        dt        |             t"        j%                  | j                               S )Nz1Dispatch key set functions expect no kwargs, got r7   z"_dispatch_keys expects 1 arg, got r   z8Expected first argument to _dispatch_keys to be a tensorr   z/Dispatch key set function expects no args, got )r   rl  r   rV   rc   _dispatch_keys	is_tensorproxyr   r   r   r   r   r   DispatchKeyPythonPythonTLSSnapshotDispatchKeySetVariablero  )r   r  rR  r   r   dkss         r[   !handle_dispatch_key_set_functionszUTorchInGraphFunctionVariable._get_handlers.<locals>.handle_dispatch_key_set_functions  sl    $GF}U  zzUXX444t9>(<SYKH  Aw((*(R  !%Q 2 2 7 7 Hjj/ mU->->-I-IJ((11%((2F2F2M2MNO((11!HH00BB  .44S99(I#d)U  .44TZZ\BBry   c                 f    t        j                  |t        j                  j	                               S r   )r9   r'  rV   	overridesget_default_nowrap_functionsr  s       r[   #handle_get_default_nowrap_functionszWTorchInGraphFunctionVariable._get_handlers.<locals>.handle_get_default_nowrap_functions  s)     #((EOO@@B ry   c                    t        |      dk(  r|s|\  }}t        |t        j                        r|j	                         }|j                         st        d      |j                  |d      }|j                  t        j                  |t        j                        |||g|      }|j                  d d       }|j                  j                  j!                  |d|        j"                  d       S t        |      dk(  r|s|\  }}}t        |t        j                        r|j	                         }|j                         st        d      |j                  t        j                  |t        j$                        |||g|      }|j                  j                  j!                  |d|j                  d d              |S |j                  t        j                  |t        j$                        t'        |      |      S )Nr   z:Expected first argument to accumulate_grad_ to be a tensorgrad)r   mutation_type   )rl  r   r   r   r   r  r   var_getattrinline_user_function_returnr9   r'  r   accumulate_gradclonery  side_effects
store_attrro  accumulate_grad_no_aliasr  )	r   r  rR  r   variablenew_gradvariable_gradupdated_gradr   s	           r[   handle_accumulate_grad_zKTorchInGraphFunctionVariable._get_handlers.<locals>.handle_accumulate_grad_  s    4yA~f%)"(h	(E(EF'//1H))+(T  !) 4 4R @!==#))"i.G.GH}h7 
  ,11T1R		&&11(FLQ.'..t444yA~f481-h	(E(EF'//1H))+(T   "==#))"i.P.PQ}h7 
 		&&11 &&d$&G
 $#11%%b)*L*LMT
 ry   Nc                     t        ||      s>|j                  t        j                  |t        j
                        t        |      |      S y r   )r.   r  r9   r'  r   radiansr  r  s       r[   handle_radianszBTorchInGraphFunctionVariable._get_handlers.<locals>.handle_radians,  sF     1v>55#))"i.?.?@J  ?ry   fmac                     t        |      dk7  s|ry t        d |D              r5|\  }}}t        t        j                        }|j                  ||||gi       S y )Nr  c              3   <   K   | ]  }|j                           y wr   )r  )rX   args     r[   r\   zQTorchInGraphFunctionVariable._get_handlers.<locals>.handle_fma.<locals>.<genexpr>G  s     73s}}7   )rl  r   r  rV   addcmulrc  )r   r  rR  r   r  yz
addcmul_fns           r[   
handle_fmaz>TorchInGraphFunctionVariable._get_handlers.<locals>.handle_fma=  s[     t9>V7$77"GAq!!=emm!LJ%33BAq	2FF ry   c                 b    t        dddg t        j                  t        j                         y )Nz:Encountered torch.is_inference_mode_enabled during tracingrj  z2torch.is_inference_mode_enabled() is not supportedr   )r#   r   FUNDAMENTALINFERENCE_MODEr0  s     r[    handle_is_inference_mode_enabledzTTorchInGraphFunctionVariable._get_handlers.<locals>.handle_is_inference_mode_enabledO  s6     TP&22&55	ry   r  c                     |j                         sH| j                  t        j                  j                  u r4t        |      r(t        |j                  d      r j                  d      S  j                  d      S )N__torch_function__TF)r  r   rV   r  is_tensor_liker   rU   ro  )r   r  r  r   r  s      r[   handle_is_tensorzDTorchInGraphFunctionVariable._get_handlers.<locals>.handle_is_tensor]  sf     }}

eoo<<<s$=>CII';<.'..t44.'..u55ry   inputc                    |}|j                         r|j                  | j                  t        j                  u r*t        j                  ||j                  j                        S | j                  t        j                  u r*t        j                  ||j                  j                        S t        d| j                         y )Nzcalling )	r  dtyper   rV   is_floating_pointr9   r'  
is_complexr   )r   r  r  	input_args       r[   handle_is_floating_pointzLTorchInGraphFunctionVariable._get_handlers.<locals>.handle_is_floating_pointj  s     I""$)D::!8!88*00Y__5V5VWWZZ5#3#33*00Y__5O5OPP(8DJJ<)@AAry   c                     |j                         r9|j                         r)t        j                  |t	        |j
                              S |j                         r|j                  |dg i       S y )Nnumel)r  
valid_sizer9   r'  r3   sizecall_methodr   r  r  s      r[   handle_numelz@TorchInGraphFunctionVariable._get_handlers.<locals>.handle_numel{  sY      U%5%5%7&,,R1DEE"((Wb"==ry   c                 v    t        |      dk(  r|d   S t        dd| d| ddgt        j                         y )	Nr7   r   z torch.compile call with > 1 argsargs=	, kwargs=zNAttempted to call `torch.compile` with > 1 args. Dynamo does not support this.z5Remove the torch.compile call or its additional args.r   rl  r#   r   r   r  s       r[   handle_torch_compilezHTorchInGraphFunctionVariable._get_handlers.<locals>.handle_torch_compile  sL     4yA~Aw:vYvh7lK&22	ry   c                 v    t        |      dk(  r|d   S t        dd| d| ddgt        j                         y )	Nr7   r   z,torch.library.wrap_triton call with > 1 argsr  r  z]Attempted to call `wrap_triton`/`capture_triton` with > 1 args. Dynamo does not support this.zBRemove the wrap_triton/capture_triton call or its additional args.r   r  r  s       r[   handle_wrap_tritonzFTorchInGraphFunctionVariable._get_handlers.<locals>.handle_wrap_triton  sR     4yA~AwFvYvh7@ Y&22	ry   c                 `    |j                         st        d      |j                  |dg i       S )Nz4Expected input to tensor size rewrite to be a tensorr  )r  r   r  r   s      r[   handle_tensor_size_rewriteszOTorchInGraphFunctionVariable._get_handlers.<locals>.handle_tensor_size_rewrites  s7     ??$$J  $$RR88ry   c                 (    | j                  |||      S r   )_call_ntupler  s       r[   handle_ntuplezATorchInGraphFunctionVariable._get_handlers.<locals>.handle_ntuple  s     $$Rv66ry   c                 ~    t        j                         t        j                  |t	        j
                               S r   )r'   _guards_singletonr9   r'  rV   is_grad_enabled)r   r  r[  s     r[   handle_is_grad_enabledzJTorchInGraphFunctionVariable._get_handlers.<locals>.handle_is_grad_enabled  s0     *<<="((U-B-B-DEEry   modec                 j    j                  ||j                               }|j                  |       |S r   )ro  r   enter)r   r  r  r  r\  s       r[   handle_enter_inference_modezOTorchInGraphFunctionVariable._get_handlers.<locals>.handle_enter_inference_mode  s0     (..r43J3J3LMCIIbMJry   c                 $    |j                  |      S r   )exit)r   r  r  s      r[   handle_exit_inference_modezNTorchInGraphFunctionVariable._get_handlers.<locals>.handle_exit_inference_mode  s     99R= ry   	warn_onlyc                 @   |j                         }t        |t              r|j                         n|}|j                  j	                  dt
        j                  j                  |fd|i       t
        j                  j                  ||        j                  d       S )Nrc  r  )r  )	r   r   r9   ry  create_noderV   rc   _set_deterministic_algorithmsro  )r   r  r  r  r   warn_only_valuer   s         r[   #handle_use_deterministic_algorithmszWTorchInGraphFunctionVariable._get_handlers.<locals>.handle_use_deterministic_algorithms  s     ++-E i9 ,,. 
 II!!66o.	 HH225O2T*#**400ry   c                     |j                   j                  dt        j                  di        t        j                         }|j                   j	                  d        t        j                  ||      S )Nrc  rx   c                  *    t        j                         S r   )rV   autocast_decrement_nestingrx   ry   r[   <lambda>zgTorchInGraphFunctionVariable._get_handlers.<locals>.handle_autocast_increment_nesting.<locals>.<lambda>      u/O/O/Q ry   )ry  r  rV   autocast_increment_nestingadd_cleanup_hookr9   r'  r   r  prevs      r[   !handle_autocast_increment_nestingzUTorchInGraphFunctionVariable._get_handlers.<locals>.handle_autocast_increment_nesting  [     II!!!A!A2r 335DII&&'QR"((T22ry   c                     |j                   j                  dt        j                  di        t        j                         }|j                   j	                  d        t        j                  ||      S )Nrc  rx   c                  *    t        j                         S r   )rV   r$  rx   ry   r[   r"  zgTorchInGraphFunctionVariable._get_handlers.<locals>.handle_autocast_decrement_nesting.<locals>.<lambda>  r#  ry   )ry  r  rV   r!  r%  r9   r'  r&  s      r[   !handle_autocast_decrement_nestingzUTorchInGraphFunctionVariable._get_handlers.<locals>.handle_autocast_decrement_nesting   r)  ry   device_typeenabledc                    |j                   j                  dt        j                  |j	                         |j	                         f       |j                         t        j                        t        j                  |j                                |j                   j                  fd        j                  d       S )Nrc  c                  0    t        j                         S r   )rV   set_autocast_enabled)dev_py_constr'  s   r[   r"  zaTorchInGraphFunctionVariable._get_handlers.<locals>.handle_set_autocast_enabled.<locals>.<lambda>  s    22<F ry   )	ry  r  rV   r1  r   r   is_autocast_enabledr%  ro  )r   r  r-  r.  r2  r'  r   s       @@r[   handle_set_autocast_enabledzOTorchInGraphFunctionVariable._get_handlers.<locals>.handle_set_autocast_enabled  s     II!!**%%')9)9);<
 '99;L,,\:D&&|W5O5O5QRII&&F +#**400ry   c                 H   |j                   j                  dt        j                  |j	                         f       t        j
                         t        j                  |j                                |j                   j                  fd        j                  d       S )Nrc  c                  .    t        j                         S r   )rV   set_autocast_cache_enabledr'  s   r[   r"  zgTorchInGraphFunctionVariable._get_handlers.<locals>.handle_set_autocast_cache_enabled.<locals>.<lambda>(  s    u/O/OPT/U ry   )	ry  r  rV   r7  r   is_autocast_cache_enabledr   r%  ro  )r   r  r.  r'  r   s      @r[   !handle_set_autocast_cache_enabledzUTorchInGraphFunctionVariable._get_handlers.<locals>.handle_set_autocast_cache_enabled  s~     II!!!A!AGDTDTDVCX 224D,,W-G-G-IJII&&'UV*#**400ry   c                 t   |j                   j                  dt        j                  j                  j
                         t        j                  j                  j                         }|j                   j                  t        j                  j                  j                         t        j                  ||      S Nrc  )
ry  r  rV   r  predispatch_jvp_increment_nestingr%  _jvp_decrement_nestingr9   r'  r   r  levels      r[   handle_jvp_increment_nestingzPTorchInGraphFunctionVariable._get_handlers.<locals>.handle_jvp_increment_nesting+       II!!!1!1!=!=!T!T $$00GGIEII&&  ,,CC #((U33ry   c                 t   |j                   j                  dt        j                  j                  j
                         t        j                  j                  j                         }|j                   j                  t        j                  j                  j                         t        j                  ||      S r<  )
ry  r  rV   r  r=  r?  r%  r>  r9   r'  r@  s      r[   handle_jvp_decrement_nestingzPTorchInGraphFunctionVariable._get_handlers.<locals>.handle_jvp_decrement_nesting8  rC  ry   c                 8   |j                   j                  dt        j                  j                  j
                         t        j                  j                  j                         |j                   j                  fd       t        j                  |      S )Nrc  c                  X    t         j                  j                  j                         S )NrA  )rV   r  r=  _exit_dual_levelrH  s   r[   r"  z]TorchInGraphFunctionVariable._get_handlers.<locals>.handle_enter_dual_level.<locals>.<lambda>N  s!    ((44EEEER ry   )	ry  r  rV   r  r=  _enter_dual_levelr%  r9   r'  r@  s     @r[   handle_enter_dual_levelzKTorchInGraphFunctionVariable._get_handlers.<locals>.handle_enter_dual_levelE  st     II!!!1!1!=!=!O!O $$00BBDEII&&R #((U33ry   rA  c                 b   |j                         |j                  j                  dt        j                  j
                  j                  ddi       t        j                  j
                  j                         fd}|j                  j                  |        j                  d       S )Nrc  rx   rA  rH  c                  v    t         j                  j                  j                         } | k7  rt	        d      y )NzInvalid _exit_dual_level)rV   r  r=  rJ  r   )	new_levellevel_consts    r[   cleanupz[TorchInGraphFunctionVariable._get_handlers.<locals>.handle_exit_dual_level.<locals>.cleanupa  s6    !,,88JJL	+()CDD ,ry   )	r   ry  r  rV   r  r=  rI  r%  ro  )r   r  rA  rP  rO  r   s       @r[   handle_exit_dual_levelzJTorchInGraphFunctionVariable._get_handlers.<locals>.handle_exit_dual_levelR  s      224KII!!  ,,==[	 ((999LE
 II&&w/*#**400ry   c                 t   |j                   j                  dt        j                  j                  j
                         t        j                  j                  j                         }|j                   j                  t        j                  j                  j                         t        j                  ||      S r<  )
ry  r  rV   rc   r  _grad_increment_nestingr%  _grad_decrement_nestingr9   r'  r@  s      r[   handle_grad_increment_nestingzQTorchInGraphFunctionVariable._get_handlers.<locals>.handle_grad_increment_nestingi  z     II!!!4!4!L!L HH''??AEII&&uxx':':'R'RS"((U33ry   c                 t   |j                   j                  dt        j                  j                  j
                         t        j                  j                  j                         }|j                   j                  t        j                  j                  j                         t        j                  ||      S r<  )
ry  r  rV   rc   r  rT  r%  rS  r9   r'  r@  s      r[   handle_grad_decrement_nestingzQTorchInGraphFunctionVariable._get_handlers.<locals>.handle_grad_decrement_nestingt  rV  ry   allowedc                    |j                   j                  dt        j                  j                  j
                  |j                         f       t        j                  j                  j                         t        j                  j                  j                  |j                                |j                   j                  fd        j                  d       S )Nrc  c                  V    t         j                  j                  j                         S r   )rV   rc   r  !set_inplace_requires_grad_allowedr8  s   r[   r"  znTorchInGraphFunctionVariable._get_handlers.<locals>.handle_set_inplace_requires_grad_allowed.<locals>.<lambda>  s    ++MMdS ry   )ry  r  rV   rc   r  r\  r   !get_inplace_requires_grad_allowedr   r%  ro  )r   r  rY  r'  r   s      @r[   (handle_set_inplace_requires_grad_allowedz\TorchInGraphFunctionVariable._get_handlers.<locals>.handle_set_inplace_requires_grad_allowed  s     II!!##EE!!#%
 88&&HHJDHHAA**, II&&S +#**400ry   c                     t        t               t        j                        }t	        |       t        j                  |t        j                               S r   )	r   r*   r&   DETERMINISTIC_ALGORITHMSr'   r9   r'  rV   $are_deterministic_algorithms_enabled)r   r  guards      r[   +handle_are_deterministic_algorithms_enabledz_TorchInGraphFunctionVariable._get_handlers.<locals>.handle_are_deterministic_algorithms_enabled  sH     !#55E % "((E>>@ ry   c                     t        t        j                         t        j                  ||j
                  j                        S r   )r'   r=   r  r9   r'  symbolic_torch_function_statetorch_function_subclass_enabledr0  s     r[    handle_is_torch_function_enabledzTTorchInGraphFunctionVariable._get_handlers.<locals>.handle_is_torch_function_enabled  s9     6HHI #((B44TT ry   c                     t        t        j                         t        j                  ||j
                  j                         S r   )r'   r=   r  r9   r'  re  torch_function_mode_enabledr0  s     r[   %handle_is_torch_function_all_disabledzYTorchInGraphFunctionVariable._get_handlers.<locals>.handle_is_torch_function_all_disabled  s:     6HHI"((88TTT ry   c                     t        t        j                         t        j                  ||j
                  j                  xr |j
                  j                               S r   )r'   r=   r  r9   r'  re  ri  in_torch_function_moder0  s     r[   %handle_is_torch_function_mode_enabledzYTorchInGraphFunctionVariable._get_handlers.<locals>.handle_is_torch_function_mode_enabled  sR     6HHI #((00LL N44KKM ry   c                    |j                   }|j                  rd|_        t        j                  |d      S t	        |      dk(  r"t        |d   t              rt        ||d         n|}t        j                  |t        d |D                    S )NFr7   r   c              3   2   K   | ]  }t        |        y wr   )r0   rX   r  s     r[   r\   z`TorchInGraphFunctionVariable._get_handlers.<locals>.handle_has_torch_function.<locals>.<genexpr>  s     0V11CA1F0Vs   )	re  	skip_nextr9   r'  rl  r   rC   r5   any)r   r  rR  tf_stateelemss        r[   handle_has_torch_functionzMTorchInGraphFunctionVariable._get_handlers.<locals>.handle_has_torch_function  s     77H!!%*"&,,R77 t9>ja-&H  DG, 
 #((S0VPU0V-VWWry   rd  typesc                 h   |j                   }|j                  rddlm}  |t        |dg       d|_        |xj
                  dz  c_        	 |j                  |t        ||      |j                               |xj
                  dz  c_        d|_        S # |xj
                  dz  c_        d|_        w xY w)Nr   )r!   zyou cannot skip two levels of __torch_function__, you need to run one level of __torch_function__ before being able to skip again.rR  Tr7   F)	re  rq  torch._dynamo.excr!   RuntimeError!skip_one_hop_torch_function_depthrc  r5   keys_as_python_constant)r   r  rd  rv  rR  r   rs  r!   s           r[   "handle_skip_one_hop_torch_functionzVTorchInGraphFunctionVariable._get_handlers.<locals>.handle_skip_one_hop_torch_function  s     77H!!F( ; "&H00A50+))#B-224 4494%*" 4494%*"s   *B B1c              3   :   K   | ]  \  }}|j                     y wr   )stream)rX   rS   device_interfaces      r[   r\   z=TorchInGraphFunctionVariable._get_handlers.<locals>.<genexpr>  s#      'A' !''s   r  r   c                 (    j                  ||      S r   )ro  )r   r  r  r  s      r[   handle_device_interface_streamzRTorchInGraphFunctionVariable._get_handlers.<locals>.handle_device_interface_stream  s     )//F;;ry   c                 2   t         j                  s!t        ddt         j                   ddg       t        s t        dddd	gt        j
                          | |j                  j                  d
t        j                  gt        |i        d       S )NzEcall `torch.from_numpy` with `torch._dynamo.config.trace_numpy=False`ztrace_numpy=zcAttempted to call `torch.from_numpy` with config `torch._dynamo.config.trace_numpy` set to `False`.z4Change `torch._dynamo.config.trace_numpy` to `True`.r   z)`torch.from_numpy` with NumPy unavailablerj  z@Attempted to call `torch.numpy` but NumPy could not be imported.z9Check NumPy version and installation in your environment.rc  )
target_clsr  r  r   )r   trace_numpyr#   npr   
USER_ERRORry  rz  rV   	as_tensorr4   )r   r  rR  r   rb  s      r[   handle_from_numpyzETorchInGraphFunctionVariable._get_handlers.<locals>.handle_from_numpy   s     %%c*6+=+=*>?M O
 G bS*55	 %),bii,,#OO 'tR0
 #	 	ry   the_type	the_valuec                     |S r   rx   )r   r  r  r  s       r[   handle_jit_annotatezGTorchInGraphFunctionVariable._get_handlers.<locals>.handle_jit_annotate%  s
     ry   r   extrac                 $   |rt        d      |j                         st        d      t        j                  d|j                  |j
                        }t        j                  |t        j                  j                  j                  |            S )Nz%Expect 1 input to cudnn.is_acceptablez2Expect input to cudnn.is_acceptable to be a tensorr   )r  device)r   r  rV   r   r  r  r9   r'  rh  cudnnis_acceptable)r   r  r   r  
tensor_inps        r[   handle_cudnn_is_acceptablezNTorchInGraphFunctionVariable._get_handlers.<locals>.handle_cudnn_is_acceptable+  sx     $%LMM##%$H  av||FMMRJ"((ENN((66zB ry   c                 H    t        j                  j                  |g|i |S r   )r   BackwardHookVariablero  r  s       r[   handle_backward_hookzHTorchInGraphFunctionVariable._get_handlers.<locals>.handle_backward_hook?  s%     1188MdMfMMry   c                 .     | j                   |g|i |S r   )call_nn_parameterr  s       r[   handle_parameterzDTorchInGraphFunctionVariable._get_handlers.<locals>.handle_parameterH  s!     *4))">t>v>>ry   self_dimc                 2    ||j                  |d|gi       S y )Nr  r  r  r  r   r  s       r[   handle_sym_sizezCTorchInGraphFunctionVariable._get_handlers.<locals>.handle_sym_sizeQ  s%    
 ''FSE2>>ry   c                 2    ||j                  |d|gi       S y )Nstrider  r  s       r[   handle_sym_stridezETorchInGraphFunctionVariable._get_handlers.<locals>.handle_sym_strideZ  s%     ''HseR@@ry   c                 ^   t        |      dk(  rd|v rt        |      dk(  rt        t        j                        j	                  |g |dd  i       }t        t        j
                        j	                  |||d   gi       }t        t        j                        j	                  ||d   |gi       S y )Nr  r   r7   r   )rl  r  rV   r~   rc  r}   r{   )r   r  rR  r   r   s        r[   handle_addcdivzBTorchInGraphFunctionVariable._get_handlers.<locals>.handle_addcdivb  s     4yA~'V"3Fq8H 6eii@NN$qr(R 6eii@NN12 4EII>LLa&)2  ry   r  
fill_valuec                    |j                         rrt        |j                         t        j                  j
                        s@t        t        j                        j                  ||g|      }|j                  |d|gi       S y )Nfill_)
r  rv  python_typerV   rt   	Parameterr  emptyrc  r  )r   r  r  r  r   empty_results         r[   handle_fullz?TorchInGraphFunctionVariable._get_handlers.<locals>.handle_fullw  sq     ##%j&&(%((*<*</
  <EKKHVV  $//Gj\2NNry   rS   c                     t        |      dk(  rSt        |d   t              s@|s>|j                  t	        j
                  |t        j                        t        |      |      S y )Nr  r   )	rl  r   rB   r  r9   r'  r   foreach_lerp_inplacer  rS   r  rR  r   s       r[   "handle_inplace_foreach_lerp_scalarzVTorchInGraphFunctionVariable._get_handlers.<locals>.handle_inplace_foreach_lerp_scalar  sW     4yA~ja,&GPV55#))"i.L.LMJ 
 ry   c                     t         j                  sy t        |      dk(  rS|d   j                         r@|s>|j	                  t        j                  |t        j                        t        |      |      S y )Nr   r   )
r   enable_dynamo_decompositionsrl  r  r  r9   r'  r   foreach_pow_scalarr  r  s       r[   handle_foreach_pow_scalarzMTorchInGraphFunctionVariable._get_handlers.<locals>.handle_foreach_pow_scalar  sf     66 4yA~$q'"3"3"5f55#))"i.J.JKJ 
 ry   c                 ~    |j                  t        j                  |t        j                        t        |      |      S r   )r  r9   r'  r   !group_tensors_by_device_and_dtyper  r  s       r[   (handle_group_tensors_by_device_and_dtypez\TorchInGraphFunctionVariable._get_handlers.<locals>.handle_group_tensors_by_device_and_dtype  s7     11%%b)*U*UVT
 ry   	conditionmessagec                     |j                         r|j                         s*t        |t        j                        r"|j                         r j                  d       S y r   )r   r   r   r   r  evaluate_exprro  )r   r  r  r  r   s       r[   handle_assertzATorchInGraphFunctionVariable._get_handlers.<locals>.handle_assert  sO     ,,.93O3O3Q9i&?&?@++-.'..t44ry   c           
           | |j                   j                  dt        j                  j                  gt        ||       |      S )Nrc  )r  
param_vars)ry  rz  rV   rc   _SDPAParamsr4   )r   r  rR  r   r  s       r[   handle_sdpa_paramszFTorchInGraphFunctionVariable._get_handlers.<locals>.handle_sdpa_params  sO     !,bii,,#HH(( 'tV4
   ry   )_get_group_size_by_name_get_group_tag_rank_not_in_group$_resolve_group_name_by_ranks_and_tagget_process_group_ranksget_rankget_world_sizec                 b   t        |      dk(  rt        |      dk(  rnt        |      dk(  rat        |      dk(  rS|d   j                         st        |d   t              r|d   j                  j
                  dk(  st        d|d          t        |      dk(  rYt        |      dk(  rKt        |d   t              st        dt        |d                |d   j                         sFt        d      t        |      dk(  rt        |      dkD  rnt        d| d	| d
| j                         dt        dt        fd}|D cg c]
  } ||       }}|j                         D ci c]  \  }}| ||       }	}} | j                  |i |	}
t        j                  ||
      S c c}w c c}}w )Nr   r7   z/torch.distributed.distributed_c10d.ProcessGroupz@Expected group arg to be a python constant or ProcessGroup, got r   z5Expected first arg to be a ListVariable (ranks), got z1Expected second arg (tag) to be a python constantzInvalid group value (, z) for constant pg function r  r^   c                 n    t        | t              r| j                  j                  S | j	                         S r   )r   rE   r   real_objr   )r  s    r[   get_arg_valuezqTorchInGraphFunctionVariable._get_handlers.<locals>.handle_constant_processgroup_functions.<locals>.get_arg_value  s.     "#'@A"yy1111133ry   )rl  r   r   rE   r   script_class_namer   rB   r   r9   r   r   r'  )r   r  rR  r   r  r  args_as_valuekvkwargs_as_valueinvocation_results              r[   &handle_constant_processgroup_functionszZTorchInGraphFunctionVariable._get_handlers.<locals>.handle_constant_processgroup_functions  s   " t9>c&kQ&6Y!^Fq(8 Q224&tAw0IJ $ !!#e$5$5P!Q -^_cde_f^gh  Y!^Fq(8%d1g|<,STXY]^_Y`TaSbc   7557,O  Y!^Fa(/vRx @$$(JJ<1 
4 43 4 @D Ds!3 D DCI<<>"R41a1mA&6#6"R"R$.DJJ$Q$Q!
 ',,R1BCC !E"Rs   F&(F+)layouttensor_listr  c                    ddl m} |rB|j                  t        j                        r#t        dd| ddgt        j                         t        ||      s#t        dd	| dd
gt        j                         y )Nr7   r   z%Attempted to use strided NestedTensorzlayout=Dynamo does not support this.zChange layout=torch.jagged.r   z4Attempted to use `nested_tensor` with non-list inputztensor_list=z'Change `nested_tensor` with list input.)
r   r   is_constant_matchrV   stridedr#   r   r   r   r  )r   r  r  r  rR  r   r   s          r[   handle_nested_tensorzHTorchInGraphFunctionVariable._get_handlers.<locals>.handle_nested_tensor.  s     0&225==AC%fX. ?5*66	 k+;<R*;-8 ?A*55	 ry   c                     t        |      t        |      z   dk(  s"t        |      dk(  r*|d   j                  d      rt        dd| d| ddg	       y )
Nr7   r   zOAttempted to use `torch.nn.functional.one_hot` with data-dependent output shaper  r  r  zuExplicitly set the `num_classes` param of the function call `torch.nn.functional.one_hot` to something other than -1.r   )rl  r  r#   r  s       r[   handle_one_hotzBTorchInGraphFunctionVariable._get_handlers.<locals>.handle_one_hotO  sc     4y3v;&!+D	Q47#<#<R#@m#D66(; ?T	 ry   exprc                     t        |      rQt        j                  |t        j                  j
                  j                  j                  |j                              S |j                         r|S y r   )
r   r9   r'  rV   re   experimentalsymbolic_shapesguarding_hint_or_throwsym_numr   r   r  r  r  s      r[   handle_guarding_hint_or_throwzQTorchInGraphFunctionVariable._get_handlers.<locals>.handle_guarding_hint_or_throwd  s`     $0&,,HH))99PP  ((*ry   fallbackc                    |r|j                         nd }t        |      rRt        j                  |t        j
                  j                  j                  j                  |j                  |            S |j                         r|S y r   )r   r   r9   r'  rV   re   r  r  optimization_hintr  r   )r   r  r  r  fallback_intr  s        r[   handle_optimization_hintzLTorchInGraphFunctionVariable._get_handlers.<locals>.handle_optimization_hintv  su     =E8668$L$0&,,HH))99KKl  ((*ry   c                     t        |      rQt        j                  |t        j                  j
                  j                  j                  |j                              S |j                         r|S y r   )
r   r9   r'  rV   re   r  r  guard_size_obliviousr  r   r  s      r[   handle_guard_size_obliviouszOTorchInGraphFunctionVariable._get_handlers.<locals>.handle_guard_size_oblivious  sb     $0 ',,HH))99NN  ((*ry   c                     t        |      rQt        j                  |t        j                  j
                  j                  j                  |j                              S |j                         r|S y r   )
r   r9   r'  rV   re   r  r  guard_or_truer  r   r  s      r[   handle_guard_or_truezHTorchInGraphFunctionVariable._get_handlers.<locals>.handle_guard_or_true  s_     $0 ',,HH))99GGU  ((*ry   c                     t        |      rQt        j                  |t        j                  j
                  j                  j                  |j                              S |j                         r|S y r   )
r   r9   r'  rV   re   r  r  guard_or_falser  r   r  s      r[   handle_guard_or_falsezITorchInGraphFunctionVariable._get_handlers.<locals>.handle_guard_or_false  s_     $0 ',,HH))99HHV  ((*ry   c                     t        |      rQt        j                  |t        j                  j
                  j                  j                  |j                              S |j                         r|S y r   )
r   r9   r'  rV   re   r  r  statically_known_falser  r   r  s      r[   handle_statically_known_falsezQTorchInGraphFunctionVariable._get_handlers.<locals>.handle_statically_known_false  s`     $0&,,HH))99PP  ((*ry   r  c                 2   ddl m} t        ||      r|j                         j                  j
                  j                  d      }|Pt        j                  j                  t        j                  j                  j                  j                  |            S y )Nr7   r   r   )r   r   r   r   r   r   r   r   r   ro  rV   re   r  r  has_free_unbacked_symbols)r   r  r  r   r   s        r[    handle_has_free_unbacked_symbolszTTorchInGraphFunctionVariable._get_handlers.<locals>.handle_has_free_unbacked_symbols  sx     /!^, !

 1 1 6 6 : :? K ,$55<<--==WW) 
 ry   c                 *   t        |      r|j                  }n3|j                         r|j                         }nt	        dd| dg        t        j                  |t        j                  j                  j                  j                              S )NzGtorch.fx.experimental.symbolic_shapes.guard_scalar branch not supportedzexpr: z6Expected `expr` to be a symbolic variable or constant.r   )r   r  r   r   r#   r9   r'  rV   re   r  r  guard_scalarr   r  r  valr  s       r[   r  z@TorchInGraphFunctionVariable._get_handlers.<locals>.guard_scalar  s     $0ll((*--/e$TFO X	 #((%%55BB3G ry   c                     t        |      rQt        j                  |t        j                  j
                  j                  j                  |j                              S |j                         r|S y r   )
r   r9   r'  rV   re   r  r  statically_known_truer  r   r  s      r[   handle_statically_known_truezPTorchInGraphFunctionVariable._get_handlers.<locals>.handle_statically_known_true  s`     $0&,,HH))99OO  ((*ry   termsc                     t        fd|D              rIj                  |t        j                  j                  j
                  j                  d |D         d       S y )Nc              3   6   K   | ]  }t        |        y wr   r   rX   r  r  s     r[   r\   zUTorchInGraphFunctionVariable._get_handlers.<locals>.handle_sym_and.<locals>.<genexpr>       Aa:a1A   c              3   <   K   | ]  }|j                           y wr   r   rp  s     r[   r\   zUTorchInGraphFunctionVariable._get_handlers.<locals>.handle_sym_and.<locals>.<genexpr>	       61!**,6r  r  )r   ro  rV   re   r  r  sym_andr   r  r  r  s      r[   handle_sym_andzBTorchInGraphFunctionVariable._get_handlers.<locals>.handle_sym_and  s^     A5AA&--HH))99AA66 ! .   ry   c                     t        fd|D              rIj                  |t        j                  j                  j
                  j                  d |D         d       S y )Nc              3   6   K   | ]  }t        |        y wr   r  r  s     r[   r\   zTTorchInGraphFunctionVariable._get_handlers.<locals>.handle_sym_or.<locals>.<genexpr>  r  r  c              3   <   K   | ]  }|j                           y wr   r
  rp  s     r[   r\   zTTorchInGraphFunctionVariable._get_handlers.<locals>.handle_sym_or.<locals>.<genexpr>  r  r  r  )r   ro  rV   re   r  r  sym_orr  s      r[   handle_sym_orzATorchInGraphFunctionVariable._get_handlers.<locals>.handle_sym_or  s^     A5AA&--HH))99@@66 ! .   ry   c                    t        |      r|j                  }n"|j                         r|j                         }ny t	        j
                  |t        j                  j                  j                  j                  |            S r   )r   r  r   r   r9   r'  rV   re   r  r  has_static_valuer  s       r[   handle_has_static_valuezKTorchInGraphFunctionVariable._get_handlers.<locals>.handle_has_static_value  sh     $0ll((*--/"((EHH))99JJ3O ry   c                 J    ddl m} t        |      j                  |g ||      S )Nr   )_unsafe_set_version_counter)tensor_version_opr  r  rc  )r   r  rR  r   r  s        r[   !handle_unsafe_set_version_counterzUTorchInGraphFunctionVariable._get_handlers.<locals>.handle_unsafe_set_version_counter,  s*     H/+mB$01ry   c                 `     t         j                  j                  j                               S r   )rV   rc   r  peek_interpreter_stack)r   r  rR  r   r  s       r[   'handle_functorch_peek_interpreter_stackz[TorchInGraphFunctionVariable._get_handlers.<locals>.handle_functorch_peek_interpreter_stack9  s(     -##::< ry   c                     |d   j                   }t        t        j                  j                  j                  |            S Nr   )r   FuncTorchInterpreterVariablerV   r  pyfunctorchcoerce_cinterpreter)r   r  rR  r   cinterpreters        r[   0handle_functorch_pyfunctorch_coerce_cinterpreterzdTorchInGraphFunctionVariable._get_handlers.<locals>.handle_functorch_pyfunctorch_coerce_cinterpreterF  s8      7==L/  ,,@@N ry   c                     dt         dt        ffdd }|r|d   }n	d|v r|d   }|N|j                         s> |      r6t        t        j
                  j                        j                  |g ||      S y )Nr  r^   c                     | j                         st        |       ryt        | t        t        f      rt	        fd| j
                  D              S y)NTc              3   .   K   | ]  } |        y wr   rx   )rX   r  check_any_unspecs     r[   r\   ztTorchInGraphFunctionVariable._get_handlers.<locals>.handle_torch_tensor.<locals>.check_any_unspec.<locals>.<genexpr>_  s     Dq/2Ds   F)r  r   rB   rC   rr  r   )r  r  r)  s    r[   r)  zaTorchInGraphFunctionVariable._get_handlers.<locals>.handle_torch_tensor.<locals>.check_any_unspecZ  sA    ;;=Jq/$BL-#@ADAGGDDD !ry   r   data)r9   rC  r  r  rV   _refsr   rc  )r   r  rR  r   data_argr)  r  s        @r[   handle_torch_tensorzGTorchInGraphFunctionVariable._get_handlers.<locals>.handle_torch_tensorS  s    	!O 	! 	! H76!!&> $ **,$X. 4EKK4F4FGUU$  ry   c                 0   |rt        dt        |             |rt        dt        |             |j                  j                  s t	        ddddgt
        j                         t        j                  |       |j                  j                         S )Nz/_pop_torch_function_stack expects no args, got z1_pop_torch_function_stack expects no kwargs, got z5Attempted to pop from empty torch function mode stackrj  zTCalled `torch._C._pop_torch_function_stack` when torch function mode stack is empty.z0Do not pop from empty torch function mode stack.r   )
r   rl  re  
mode_stackr#   r   r  rI   register_mutationpop_torch_function_moder  s       r[   handle_pop_torch_functionzMTorchInGraphFunctionVariable._get_handlers.<locals>.handle_pop_torch_functiony  s     $Ec$i[Q  $GF}U  33>>S vJ*55	 +<<R@33KKMMry   c                     t        |      dk7  s|rt        |dt        |       d       t        j                  |       |j                  j                  |d           j                  d       S )Nr7   z0push_torch_function takes exactly one argument ( given)r   )rl  r"   rI   r0  re  push_torch_function_modero  r   r  rR  r   r   s       r[   handle_push_torch_functionzNTorchInGraphFunctionVariable._get_handlers.<locals>.handle_push_torch_function  sj     4yA~ Fs4ykQXY +<<R@,,EEd1gN*#**400ry   c                     |s|rt        |d       t        j                  |t        |j                  j
                              S )Nz+len_torch_function_stack takes no arguments)r"   r9   r'  rl  re  r/  r  s       r[   handle_len_torch_functionzMTorchInGraphFunctionVariable._get_handlers.<locals>.handle_len_torch_function  s=     v %RS"((C88CCD ry   c                 r   t        |      dk7  s|rt        |dt        |       d       |d   j                         }|dk  rt        d|       |t        |j                  j
                        k\  r.t        d| dt        |j                  j
                               |j                  j
                  |   S )Nr7   z2get_function_stack_at takes exactly one argument (r4  r   z;Expected non-negative index for get_function_stack_at, got zIndex z6 out of range for torch function mode stack of length )rl  r"   r   r   re  r/  )r   r  rR  r   inds        r[   handle_get_stack_atzGTorchInGraphFunctionVariable._get_handlers.<locals>.handle_get_stack_at  s     4yA~ HTSZ[ q',,.CQw$QRUQVW  c"::EEFF$SE "!!$R%E%E%P%P!Q RT  33>>sCCry   c                    t        |      t        |      z   dkD  s|r)d|vr%t        dd| d| dg t        j                         	 |r|d   j	                         }n|r|d   j	                         }nd }t        j                  |      }=t        | j                        }t        |j                  t        j                               t        t        d      j                   j#                  dd      d         }t%        j&                  |||      S # t        $ r0}t        d	d| d| d
g t        j                  |       Y d }~d }~ww xY w)Nr7   r  z*improper torch.get_device_module argumentsr  r  z<torch.get_device_module accepts 1 optional argument `device`r   r   z.bad device argument to torch.get_device_moduleAExpected valid string/torch.device argument ('cpu', 'cuda', etc.)r   r   r   r   from_excrV   r  )maxsplitr  )rl  r#   r   r  r   rV   get_device_moduler  r)   r   r'   r   r&   ID_MATCHr(   r+   rT   rsplitr9   r'  )	r   r  rR  r   r  moduleer   
new_sources	            r[   handle_get_device_modulezLTorchInGraphFunctionVariable._get_handlers.<locals>.handle_get_device_module  sR    4y3v;&*v(&:PH#D66(; ^*55	#H-@@BF!!W779F!F008 ~1$++>f//0E0EFG#W%&&sQ&7;J #((VZ@@%  L#D66(; c9-889 s   AD 	E&EEc                    ddl m} t        |      t        |      z   dkD  s|r)d|vr%t        dd| d| dg t        j
                         	 |r't        j                  |d   j                               }n+|r't        j                  |d	   j                               }nd }|j                  j                  |      } || j                        }|@t        ||      s4 ||j                  |j                  |j                  |j                  
      }|S # t         $ r0}t        dd| d| dg t        j
                  |       Y d }~y d }~ww xY w)Nr7   )_get_stream_variable_clsr  z9unsupported arguments to torch.accelerator.current_streamr  r  zGtorch.accelerator.current_stream accepts one optional argument `device`r   r   r   z7bad device argument to torch.accelerator.current_streamr>  r?  )streamsrJ  rl  r#   r   r  rV   r  r   symbolic_stream_state
cur_streamr   r   r  user_object_indexr   r  )	r   r  rR  r   rJ  r  
stream_varstream_variable_clsrF  s	            r[   handle_current_streamzITorchInGraphFunctionVariable._get_handlers.<locals>.handle_current_stream  sR    :4y3v;&*v(&:PW#D66(; i*55	"\\&*:*M*M*OPF"\\$q'*D*D*FGF!F55@@H
&>tzz&J#&2: 3< "5"(("(("44)00	"J "! U#D66(; c9-889 s   CD 	E&EEr~  xpumpsr  c                    d }|r+d|v r't        j                  |d   j                               }n(|r&t        j                  |d   j                               }|ij                  | j                        }|7t         j
                  j                         }|t        d      |j                  }t        j                  |      }|j                  dk(  r j                  d       S |j                  j                  dt         j                  j                  j                  |j                  |j                  xs dfi         j                  d       S )Nr  r   z:No accelerator available for torch.accelerator.synchronizer  rc  )rV   r  r   r   r   acceleratorcurrent_acceleratorr   r   ro  ry  rz  opsrK  synchronize_deviceindex)	r   r  rR  r   r  r-  rU  r   _synchronize_fn_to_device_types	          r[   handle_synchronizezFTorchInGraphFunctionVariable._get_handlers.<locals>.handle_synchronize1	  s*    F(f,fX&6&I&I&KLd1g&@&@&BC~<@@L&"'"3"3"G"G"IK"*,X  #."2"2Kk2 {{e#.'..t44II""		!!44fll/a0	 +#**400ry   c                     t        j                  |       |d   j                         rt        j                  |       nt        j                  |        j
                  d       S r   )rI   r0  is_constant_noneclear_default_device!register_device_context_insertionro  r6  s       r[   handle_set_default_devicezMTorchInGraphFunctionVariable._get_handlers.<locals>.handle_set_default_device\	  sT     +<<R@Aw'').CCBG.PPQST*#**400ry   )elementwise_dtypesc           	         ddl m} |d   j                         }g }|D ]  }t        |	      r7|j	                  |j                         j                  j                  d          F|j                         r |j	                  |j                                vt        dt        |      dt        |      j                   g t        j                           
|d|i}|j                  ||      S )Nr7   )SourcelessBuildertype_promotion_kindr   z'elementwise_dtypes unsupported arg typez>elementwise_dtypes requires tensor or constant arguments, got r   )builderrc  r   r   r   r   r   r   r   r#   rD  r   rT   r   r   ro  )r   r  rR  r   rc  rd  	real_argsr  r   r   ra  s            r[   handle_elementwise_dtypeszMTorchInGraphFunctionVariable._get_handlers.<locals>.handle_elementwise_dtypest	  s     3"()>"?"R"R"TI c>2$$S\\^%8%8%=%=o%NO++-$$S%;%;%=>! I #C##'9#5#5"68 ? 1 = => (0CF %++B77ry   predicate_vt
message_vt
error_typec           	          |#t        || j                  j                   d       |j                         rt        |d       d }d }|et	        |t
              s(t        dt        |      dg t        j                         	 |j                         }|j                  j                  d	|      }|j                         r<|j                         r 
j                   d       S | |       nd
}t#        |||g       |j%                         }||f}	n||f}	 ||j                  j'                  dt(        j*                  |	i             S # t        $ r, t        dt        |      ddgt        j                         Y w xY w)Nz1() missing 1 required positional argument: 'cond'zcond must be a bool, but got a Tensor. For tensor conditions, use torch._check_tensor_all() to assert that all elements are true.z*Can't extract message from torch._check*()zcThe message argument of torch._check*() must be a function defined within the torch.compile region.r   z-Can't convert torch._check*() message closurezhThe message argument of torch._check*() must be a function whose closure variables are Python constants.zRemove closure variables that reference non-constant values, e.g. remove references to tensor `x` in `lambda: f'{x} failed check'`_check_messagez(Expected cond to be True, but got False.rx  rc  r  r  )r"   r   rT   r  r   rA   r#   rD  r   r   r  r@   ry  %register_static_attr_and_return_proxyr   r   ro  r!   r   rz  rV   _check)r   r  rh  ri  rj  message_eagermessage_graph_proxymsgpredicate_proxy
proxy_argsr   r  s             r[   
check_implz>TorchInGraphFunctionVariable._get_handlers.<locals>.check_impl	  s    # zz**++\]
 %%' < !M"&%!*.HI! L #JG.::
$.$;$;$=M  ')ii&U&U$m'# ..02242+22488 %0 "OD 
 )RseD*335O #*-/
-/BC
 ii,,#LL	 K . ! O #JL_ /::s   E 2E=<E=c                     |r|d   n|j                  d      }|r|dd  nd}|r|d   n|j                  d      } | |||      S )Nr   condr7   rx   r  )r   )r   r  rR  r   rh  	rest_argsri  ru  s          r[   handle_checkz@TorchInGraphFunctionVariable._get_handlers.<locals>.handle_check	  sQ     '+47

60BL$(QRbI)21

98MJdBjAAry   c                    | j                   t        j                  u r"|r|d   n|j                  d      }|r|dd  nd}nd }|}t        j                  t
        t        j                  t        t        j                  t        t        j                  t        i}||j                         n|j                  | j                   t              }|r|d   n|j                  d      }|r|dd  nd}|r|d   n|j                  d      }	 
| |||	|      S )Nr   rj  r7   rx   rw  r  )r   rV   _check_withr   _check_index
IndexError_check_value
ValueError_check_type	TypeError_check_not_implementedr)  r   rz  )r   r  rR  r   error_type_vtrx  _CHECK_ERROR_TYPESrj  rh  ri  ru  s             r[   handle_check_withzETorchInGraphFunctionVariable._get_handlers.<locals>.handle_check_with	  s     zzU...+/QVZZ5M(,DH"	 $ 	 ""J""J!!9,,.A	A !, 002'++DJJE  ,59Q<&**V:LL)2	!"I)21

98MJdBj*MMry   c                    | j                   t        j                  u r:|r|d   n|j                  d      }|r|dd  nd}||j	                         nt
        }n|}t
        }|r|d   n|j                  d      }|r|dd  nd}|r|d   n|j                  d      }| 
| |d ||      S |j                  |dg i       j                  |dg i       }	 
| ||	||      S )	Nr   rj  r7   rx   rw  r  _is_all_truer   )r   rV   _check_tensor_all_withr   r   rz  r  )r   r  rR  r   r  rx  rj  cond_vtri  	scalar_vtru  s             r[   handle_check_tensor_allzKTorchInGraphFunctionVariable._get_handlers.<locals>.handle_check_tensor_all
  s     zzU999+/QVZZ5M(,DH"	 %0 "446%  !	)
&/ilVZZ5GG)2	!"I)21

98MJ!$D*jII++BBGSSFBI dB	:zJJry   rY   c           	         t        |      dk7  s|r%t        | |j                   dt        |       d       t        t	        t	        t        d      d      d            }t        |j                  t        j                               |d   j                         } ||      | j                  j                  d||fi        | j                  j                  fd	       t        j                  |       S )
Nr7   z takes exactly one argument (r4  rV   r~  current_devicer   rc  c                  B    t         j                  j                         S r   )rV   r~  
set_devicer8  s   r[   r"  z\TorchInGraphFunctionVariable._get_handlers.<locals>.exchange_device_helper.<locals>.<lambda>T
  s    uzz/D/DT/J ry   )rl  r"   rT   r)   r(   r+   r'   r   r&   EQUALS_MATCHr   ry  r  r%  r9   r'  )r  rR  r   rY   current_device_sourcer  r'  s         @r[   exchange_device_helperzJTorchInGraphFunctionVariable._get_handlers.<locals>.exchange_device_helper=
  s     4yA~ {{m#@T7S %=:l7&;VDFVW%! /::<;T;TUVq',,.Cc7DII!!	 II&&'JK"((T22ry   c                 \     |t        |      |t        j                  j                        S r   )r  rV   r~  _exchange_devicer   r  rR  r   r  s       r[   handle_exchange_devicezJTorchInGraphFunctionVariable._get_handlers.<locals>.handle_exchange_deviceW
  s)     *DJ

(C(C ry   c                 \     |t        |      |t        j                  j                        S r   )r  rV   r~  _maybe_exchange_devicer  s       r[   handle_maybe_exchange_devicezPTorchInGraphFunctionVariable._get_handlers.<locals>.handle_maybe_exchange_deviceb
  s)     *DJ

(I(I ry   c                    ddl m} ddlm} |d   }|d   }|j	                         }|j                         rJt        j                  j                  j                  |j	                         |        |j                  d       S t        ||      rFt        j                  j                  j                  |j                  |        |j                  d       S t        t        j                  dt!        |      j"                         )Nr7   r   r  r   zAoverride_optimization_hint expects a SymInt or int argument, got )constantr   r   r  r   r   rV   rk   
decoratorsoverride_optimization_hintro  r   r  r$   r%   INVALID_INPUTr   rT   )	r   r  rR  r   r   r  x_vtval_vtr  s	            r[   !handle_override_optimization_hintzUTorchInGraphFunctionVariable._get_handlers.<locals>.handle_override_optimization_hintm
  s     3/7D!WF++-C&&(((CC++-s /'..t44$0((CCDLLRUV.'..t44++Dz**+- ry   c           	         ddl m}m} ddlm} ddlm} ddlm} ddl	m
}	 ddlm}
 |j                  st        d	d
|j                   ddg       |j                  j                   rM|j                  j"                  }|rdj%                  |      nd}t        dd| d| |r	d|d    dnddg       |j&                  rt        dddg d       t)        |      dk\  rt+        |d   d       t)        |      dk\  rt+        |d   d       t-               }i }|j.                  j0                  j3                         D ]  }t5        ||
      s|j7                         j8                  j:                  j=                  d      }t5        |t>        j@                        stC        dtE        |             tG        |      }|jI                  |       |jJ                  |D ]  }|jJ                  jL                  ||<     dd!l'm(} t)        |      dk\  rtS        |d         ng }t)        |      dk\  rtS        |d         ng }t-               }|D ]H  \  }}t5        |t>        j@                        s!|jT                  .|jW                  |jT                         J  |||"      }||z  }|r@|D cg c]  }||v r||    }}|rd#| nd$}t        d%|d&d'd(gtX        jZ                         |j=                  d)      }|j=                  d*      }t5        ||      xr |j\                  d+u xs t5        ||      xr |j\                  d+u }|s|D ch c]  }tE        |      j^                  d,k7  r| } }|j.                  j`                  }!| |!z  }"|"rt        d-d.t)        |"       d/d0g       |j.                  j`                  jI                  |        t)        |      dk\  r|d   n|j=                  d      }#t5        |#|      rPtc        te        |#jf                  j3                                     }$t)        |      dk\  r|d   |$g|dd  }ni |d|$i}t>        jh                  jj                  jm                         5  t>        jh                  jj                  jo                         5   |j.                  jp                  d1t>        jr                  jt                  gtw        ||       }%d d d        d d d         ||%2      }&t5        |#|      rit5        |&|	      stC        d3tE        |&             ty        t{        |#jf                  j}                         |&jf                  d+4            }' ||'tx              S |&S c c}w c c}w # 1 sw Y   xY w# 1 sw Y   xY w)5a	  
            Handle torch.autograd.grad() calls within compiled regions.

            NOTE [Tracing autograd.grad in dynamo]

            We validate two things:

            1. External grad_fns cannot be consumed: The grad_fn on external inputs
               could change at runtime, so we would need to guard on it if we wanted
               to trace through it. For now, we reject this case.
               We compute "consumed" grad_fns (reachable from outputs, excluding
               autograd.grad inputs parameter) and verify no graph input's grad_fn is in this set.

            2. Returned tensors cannot have consumed grad_fns: If autograd.grad
               consumes a grad_fn and we return a tensor connected to it, the user
               would get "backward through graph a second time" error. We track
               consumed grad_fns and check at output time. If violated, we retry
               with a graph break at autograd.grad.

            Safe vs Unsafe Cases:

            Case 1 - Safe (external tensor is autograd.grad input):
                x = torch.randn(4, requires_grad=True)
                external = x * 2  # has external grad_fn

                @torch.compile
                def fn(external_input):
                    loss = external_input.sum()
                    return torch.autograd.grad(loss, external_input)

                Safe because autograd.grad stops at external_input, never consuming
                its external grad_fn.

            Case 2 - Unsafe (external grad_fn in path):
                @torch.compile
                def fn(external_input):
                    loss = mod(external_input).sum()
                    return torch.autograd.grad(loss, mod.weight)

                Unsafe because autograd.grad must traverse through external_input's
                grad_fn to reach mod.weight. The external grad_fn could change at
                runtime, so we would need to guard on it (like AOTAutograd does).
                For now, we reject this case.

            Case 3 - Unsafe (returning tensor with consumed grad_fn):
                @torch.compile
                def fn(x):
                    y = x * 2
                    grad = torch.autograd.grad(y.sum(), x)
                    return y, grad  # y's grad_fn was consumed!

                Unsafe because y's grad_fn was consumed by autograd.grad. Trying to
                backward through y later would error.
            r   )r   r   r7   r  r   r   r   r   zPusing `torch.autograd.grad` with `torch._dynamo.config.trace_autograd_ops=False`ztrace_autograd_ops=zmAttempted to call `torch.autograd.grad` with config `torch._dynamo.config.trace_autograd_ops` set to `False`.z;Change `torch._dynamo.config.trace_autograd_ops` to `True`.r   r  unknownz0autograd.grad consumed returned tensor's grad_fnzLeaked output tensors: ztorch.autograd.grad() consumes grad_fns that are needed by tensors returned from this compiled function. This would cause 'backward through graph a second time' errors.
  The following returned tensors have consumed grad_fns: z9Detach the problematic tensor(s) before returning: e.g. `r   z
.detach()`z.Call .detach() on the tensor before returning.z^If you need to backward through the returned tensor, use retain_graph=True in autograd.grad().z$autograd.grad with compiled autogradz&compiled_autograd is currently enabledztorch.autograd.grad() inside torch.compile is not supported when compiled autograd is enabled. These two features have conflicting requirements for how the autograd graph is traced.)zLDisable compiled autograd by removing the compiled_autograd context manager.zBOr move the autograd.grad() call outside the torch.compile region.zPOr restructure your code so autograd.grad() and compiled_autograd don't overlap.outputsinputsr   r   N)collect_reachable_grad_fns)stop_atzinputs with external grad_fn: rj  z#autograd.grad with external grad_fna	  torch.autograd.grad() cannot trace through the autograd graph because it's output depends on a tensor that was created outside the compiled region and has a grad_fn attached. The autograd graph extends beyond the compiled region boundary, which Dynamo cannot trace.zIf you don't need gradients to flow back to the original tensor outside the compiled region, detach the input: `tensor.detach().requires_grad_(True)`.zEOtherwise, move the autograd.grad() call outside the compiled region.retain_graphcreate_graphTAccumulateGradz+autograd.grad with already consumed grad_fnzdouble consumed grad_fns: ztorch.autograd.grad() is trying to consume grad_fns that were already consumed by a previous autograd.grad() call. This would cause 'backward through graph a second time' errors at runtime.zUse retain_graph=True in the first autograd.grad() call if you need to compute gradients through the same graph multiple times.rc  rm  zCExpected BaseListVariable from autograd.grad with dict inputs, got )strict)?rj  r   r   re  r  r  r   r   r   r   r   r   r   trace_autograd_opsr#   speculation_loggraph_break_on_autograd_gradautograd_grad_leaked_tensorsjoincompiled_autograd_enabledrl  r   r   ry  input_source_to_varr   r   r   r   r   r   rV   rW   r   r   r   r   r   rZ   output_graphr  r   r   r{   r   r   r   rT   autograd_grad_consumed_grad_fnsrC   r  r   re   rs  preserve_node_meta_set_autograd_backwardrz  r;  r  r4   dictzipkeys)(r   r  rR  r   r   r   r  r   r   r   r   leaked
leaked_strexternal_grad_fnsgrad_fn_to_sourcer   r   tensor_grad_fnsgfr  outputs_with_sourcesinputs_with_sourcesinputs_grad_fnsr   rS   consumed_grad_fnsexternal_in_consumedsourcesr   r  r  graph_preservednon_leaf_consumedalready_consumeddouble_consumed
inputs_varinputs_as_tupler  r   r   s(                                           r[   handle_autograd_gradzHTorchInGraphFunctionVariable._get_handlers.<locals>.handle_autograd_grad
  s   t 5.20/.,,n1&2K2K1LMT V
 !!>>++HH28TYYv.i
N5j\BT U_S_a " TTZ[\T]S^^hiMx	( !::BDM" 4yA~(a)<4yA~(a(; ADFHyy44;;= Dc>2"%,,."5"5":":">">"OK%k5<<@,MdS^N_M`a  '<K&HO%,,_=zz-"1 DB47JJOO-b1DD B ;>d)q.-d1g6b ! ;>d)q.-d1g6b   ?BeO0 8	fell38R#''78 !;$o! $57H#H # 3.. &b) 
 IP:7)DUWA#bi_ +66	* "::n5L!::n5L<)9: / &&$. <)9: / &&$.  # 0%Bx((,<< %! % $&99#L#L "36F"F"! M"<S=Q<R S^
_ 		99@@ARS %(INa

88LJ*&78"/Z5E5E5L5L5N0O"Pt9> G_@tABx@DBB/BF ""557""99; /		..#NN'' 'tV4	  #b6F*&78!&*:;(#F|n.  AE"((--/#A )55MKP%H   s1   'U)!U..)U?AU3U?3U<	8U??Vc                    t        |      dk\  r|d   nd}t        |      dk\  r|d   nd}||yt        |      }t        |      }|r|r|D ]  }|j                  j                  d      }	|j                  j                  d      }
|
<t	        |	t
        j                        sW|	j                  d|
j                  }t	        |t
        j                        s|j                  t        ddd	d
gt        j                          y)a  Graph-break when closure-captured tensors lose their grad_fn.

            NOTE [Detecting lost autograd linkage in closure-captured tensors]

            Functorch transforms (vjp, grad, jacrev) return closures that capture
            tensors with grad_fn. When such a closure is compiled separately, those
            tensors become graph placeholders whose FakeTensors lose grad_fn,
            causing _autograd_grad to silently return zeros.

            _collect_placeholder_nodes gathers placeholder nodes from the
            outputs/inputs args. For each, we compare grapharg.example (the real
            tensor, retains grad_fn) against example_value (FakeTensor, grad_fn
            is None). A mismatch means autograd linkage was lost, so we
            graph-break.

            This is a pre-check only: kwargs (retain_graph, create_graph,
            grad_outputs) don't affect linkage detection and are handled by
            the default proxy path when this returns None.
            r7   r   Nr   r   graphargz(_autograd_grad with lost grad_fn linkagez,outputs lost autograd linkage during tracingzp_autograd_grad() received tensors whose grad_fn was lost during tracing - this silently produces zero gradients.ziCompile the full transform instead of the returned closure: torch.compile(lambda x: torch.func.vjp(f, x))r   )rl  r   r   r   r   rV   rW   r   exampler#   r   r   )r   r  rR  r   outputs_varr  output_placeholder_nodesinput_placeholder_nodesr   faker  reals               r[   handle_functorch_autograd_gradzRTorchInGraphFunctionVariable._get_handlers.<locals>.handle_functorch_autograd_grad  s    4 &)Y!^$q'K$'INaJ"j&8'A+'N$&@&L#',C4 D99==9D#yy}}Z8H ,&tU\\: LL0'//%dELL9dll>V)(R(V%6
%]'" &7%B%B'"0 ry   r?  r   )r  rL   )r   r   torch.backends.cudar  rj  r   r[  r\  r  r  r   r  re  r  rb  rz   r9   dispatch_key_set_functionsrV   r  r  ru  rW  inductoraccumulate_grad_r  r9  r  rU   r  is_inference_mode_enabledr   r  r  r  r  r  compilelibrarywrap_triton_librarycapture_triton!REWRITE_OPS_TO_TENSOR_SIZE_METHODrt   ru   utils_single_pair_triple
_quadruple_ntupler  r;  	grad_mode_enter_inference_mode_exit_inference_modeuse_deterministic_algorithmsrC  r$  r!  r1  r7  r  r=  r>  r?  rJ  rI  rc   rS  rT  r\  ra  _is_torch_function_enabled_is_torch_function_all_disabled_is_torch_function_mode_enabledr0   has_torch_function_variadichas_torch_function_unary_skip_one_hop_torch_functionr  fromkeysr    
from_numpyr`   rt  rO   rh  r  r  hooksBackwardHookr  atensym_sizerF  
sym_strideaddcdivfull_foreach_lerp__foreach_pow"_group_tensors_by_device_and_dtype_assertr>   is_available"torch.distributed.distributed_c10dr  r  r  r  r  r  r  nestednested_tensor
functionalone_hotre   r  r  r  r  r  r  r  r  r  r  r   r  r  r  	_autogradr  r  r"  r#  r!  r   _pop_torch_function_stackr   _push_on_torch_function_stack_len_torch_function_stack_get_function_stack_atrB  rU  current_streamr~  rR  r   synchronizerS  r  set_default_devicetorch._prims_commonra  rz  r   r  ro  r{  r|  r~  r  r  r  _check_tensor_allr  rD  r  r  rk   r  r  r  r  _autograd_grad)mr  r  r  r  r  r  r  r  r  r  r  r  r  r  r
  r  r  r  r  r  r(  r,  r4  r:  rB  rE  rK  rQ  rU  rX  r^  rc  rg  rj  rm  ru  r}  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r%  r-  r2  r7  r9  r<  rH  rQ  r[  r`  rg  ry  r  r  r  r  r  r  r  r   r[  r\  r  r  r   r  rZ  ru  ra  r  r  r  rb  sm                                                                                                  @@@@@@@@@@@@@@r[   _get_handlersz*TorchInGraphFunctionVariable._get_handlersz  s    	38$	xS)*HS#X,>>?	  	3	
 	
 	
 	>	*,	-	T+	T #	T &		T
 	T 
.	T@ 
-	.)	C+)	C #)	C &	)	C
 )	C 
/)	CV 
%//>>JJ	K	+	 #	 &		
 	 
L	 
%))$$55==	>.	+.	 #.	 &	.	
 .	 
?.	` 
$,,		+	 #	 &		
 t#	 
 	 4dhh/ ' *	
 !4'  " 
%11	2	1		 
3	 
%//5??#A#A	B
	61
	68G
	6
	6 
C
	6 
##

	1	:=	t#		

	 
%++		1	:=	t#	 
	 
%--	 	+	 #	 &		
 	 
!	( 
%--++U^^-J-J	K	+	 #	 &		
 	 
L	* 
4	5	91	9:I	9	9 
6	9 
HH""**HH""((HH""**HH""--HH""**

	7+	7 #	7 &		7
 	7

	7 
%''	(	F1	F	F 
)	F 
%..**@@	A	1	9H	"	 
B	 
%..**??	@	!1	!9N	!	! 
A	!
 
%44	5
 16		1+	1 	1 '-		1
 	1 
6	1* 
%22	3	31	3	3 
4	3 
%22	3	31	3	3 
4	3 
%,,	-	1+	1 )	1 %		1
 	1 
.	1& 
%22	3		11		1<K		1		1 
4		1 
%""..EE	F
	41
	4
	4 
G
	4 
%""..EE	F
	41
	4
	4 
G
	4 
%""..@@	A
	41
	4
	4 
B
	4 
%""..??	@	11	1:I	1	1 
A	1, 
%((%%==	>	41	4	4 
?	4 
%((%%==	>	41	4	4 
?	4 
%((%%GG	H	11	1<K	1	1 
I	1" 
%<<	=
	1
	
	 
>
	 
%((55	6	1		 
7	 
%((::	;	1		 
<	 
%((::	;	1		 
<	 
OO..OO77OO44


	X1	X:I	X	X


	X 
%((77	8	++	+ "	+ #		+
 "	+ $	+ 	+ 
9	+B 
]] +K+M 

	<1	<;K	<"	<

	<
 
%""	#"	1"	:I"	"	 
$"	H 
%))$$	%	1	=@	MN		 
&	
 
%..&&44	5	1	;>	HK		 
6	& 
%++##00	1	N+	N #	N &		N
 	N 
2	N 
%(($$	%	?+	? #	? &		?
 	? 
&	? 
%))..))599>>+B+B+F+F	GQU		7	DG$J	t#	 
H	 
%))..++UYY^^-F-F-J-J	KQU		7	DG$J	t#	 
L	 
%--	 	+	 #	 &		
 t#	 
!	( 
%**		+	 "	 (		
 &	 t#	 
	& 
%&&	'		+	 #	 &		
 t#	 
(	" 
%$$	%		+	 #	 &		
 t#	 
&	& 
%((==	>
	
	+
	 #
	 &	
	
 
	 
?
	 
%--	 	+	 '	 %		
 t#	 
!	 
*		+	 #	 &		
 	 
	  ++-   '"'4;D/;D ';D *	;D
 !;D;Dz 
%,,,,	- 37	
 "&	+	 )4/	 #		
 $J	 &	 	 
.	@ 
%((%%--	.	+	 #	 &		
 	 
/	( 
%((''77NN	O	+	 "	 t#		 
P	" 
%((''77II	J
 04		+	 "	 &,		
 t#	 
K	& 
%((''77LL	M	1	9H	t#	 
N	" 
%((''77EE	F	1	9H	t#	 
G	 
%((''77FF	G	1	9H	t#	 
H	 
%((''77NN	O	1	9H	t#	 
P	 
%((''77QQ	R	1	6E	t#	 
S	 
%((''77DD	E	1	9H		 
F	( 
%((''77MM	N	1	9H	t#	 
O	 
%((''77??	@	1	;J	t#	 
A	 
%((''77>>	?	1	;J	t#	 
@	 
%((''77HH	I	1	9H	t#	 
J	 
%(($$@@	A
	1+
	1 #
	1 &	
	1
 
	1 
B
	1 
%((%%<<	=
	+
	 #
	 &	
	
 '
	 
>
	 
%""..BB	C
	+
	 #
	 &	
	
 *
	 
D
	 
%,,	#	+#	 ##	 &	#	
 t##	 
 #	J 
%((44	5	N+	N #	N &		N
 '	N 
6	N6 
%((88	9	1+	1 #	1 &		1
 	1 
:	1  
%((44	5
	+
	 #
	 &	
	
 
	 
6
	 
%((11	2	D+	D #	D &		D
 '	D 
3	D. 
%))55	6)	A+)	A #)	A &	)	A
 )	A 
7)	AV 
,,JJ%%II$$


,	+,	 #,	 &	,	
 ,	


,	^ JJ""FII!!5II!!5II!!5	*
& 
))JJ""II!!II!!II!!

"	1+"	1 #"	1 &	"	1
 "	1

"	1H 
%**	+	1+	1 #	1 &		1
 	1 
,	1* 	;	$	%	8+	8 #	8 &		8
 	8 
&	8F +7S	+S	 *D0S	 ($.	S	
 YS	 S	j 
%,,			B+		B #		B &			B
 		B 
 		B 
((

	N+	N #	N &		N
 	N

	N> 
((##

	K+	K #	K &		K
 	K	

	K>	3+	3'	3 o-.	3 #d
*+		3
 	34 
%**--	.	+	 #	 &		
 	 
/	 
%**33	4	+	 #	 &		
 	 
5	 
%--**EE	F	+	 #	 &		
 	 
G	: 
%..%%	&_	1_	 
'_	B	 
%""33BB	C;	+;	 #;	 &	;	
 t#;	 
D;	z ry   r  rL   rR  rS  r9   c                    ddl m ddlm} | j                  t
        j                  k(  r| j                  |||      S | j                  t
        j                  k(  r| j                  |||      S | j                  |||      rt        || ||      S | j                         rt        ||      r| j                  t        v rT| j                   t#        d      t%        | j                         }t'        |j)                  t*        j,                               	 t/        j0                  | | j3                         |D cg c]  }|j3                          c}i |j5                         D ci c]  \  }}||j3                          c}}      S | jE                         rC| j                  jF                  }
|r|d   jI                         r|d   }|j                   tK        tL        jN                  jP                  |
      rtS        tL        jN                  jP                  |
      }tK        |d      rtK        ||jU                         d         rytL        jV                  jX                  tS        ||jU                         d         jZ                  v r8t]        dd	d
t_        | j                         dg t`        jb                  d       | je                  |tA        |      |      S | jg                         ji                  | j                        }|r || |g|i |}|r|S tk        fd|D              }tm        fd|D              }tS        | j                  dd	      dk(  r| j                  jF                  tn        v r|r|rtq               swdts        | j                         d}tt        jw                  |       t]        dd| j                   d| d| dts        | j                         dg t`        jb                         | j                  }|rSd| j                  jF                   }tS        | j                  dd       dk(  r tK        tL        |      rtS        tL        |      }d }d }d|v r|d   }ty        |tz        t|        f      rhg }|j4                  D ]W  }|jI                         r2|j                         j                  j                  d   j                  }nd }|j                  |       Y |jI                         r1|j                         j                  j                  d   j                  }t        }|t        v rB|j                  r6|j                  j                  r |j                  j                  j                  } |       5   || |j                  j                  d|gt        ||             }d d d        jI                         rKd |v rG|d    j3                         r4t]        d!d| j                   d| d| d"d#d$gt`        jb                         |Sty        |t@              rt        |j4                  |      D ]  \  }}|	|jI                         st#        d%      |j                  j                  j                  d   }||j                  k7  rPt]        d&d| j                   d| d| d'| j                   d(| d)|j                   dg t`        jb                         tL        j                  j                  |      rt]        d*d+| j                   d| d| d"g t`        jb                          |S |t#        d,      |jI                         st#        d-      d|j                         j                  j                  vrt#        d.      |j                         j                  j                  d   }||j                  k7  rPt]        d/d| j                   d| d| d'| j                   d(| d)|j                   dg t`        jb                         tL        j                  j                  |      s2t]        d0d+| j                   d| d| d"g t`        jb                         |S c c}w c c}}w # t6        t8        t:        f$ r5}	t=        t?        |	      |tA        |	jB                               Y d }	~	2d }	~	ww xY w# 1 sw Y   xY w)1Nr7   r  r  zCExpected source to be set for constant fold function needing guardsrx  r   	overloadszInplace op on input tensorrj  z6Attempted to trace an inplace view op on input tensor r  z/Ensure you do not modify input tensor in place.r   c              3   6   K   | ]  }t        |        y wr   r  r  s     r[   r\   z=TorchInGraphFunctionVariable.call_function.<locals>.<genexpr>9  s     &T!z!_'E&Tr  c              3   Z   K   | ]"  }t        |      xs |j                          $ y wr   )r   r   r  s     r[   r\   z=TorchInGraphFunctionVariable.call_function.<locals>.<genexpr>;  s.      !
IJJq/*Da.B.B.DD!
s   (+r  rV   zCalling z on only torch.SymInt arguments is not yet supported.
To support this behavior, we need to allow const-propping tensors that store symint data.
For now, dynamo will explicitly graph break when it encounters user code with this behavior.
zHAttempted to call torch in-graph function on only torch.SymInt argumentszfn=z, args=r  zAttempted to call zc (that should be put in the FX graph) on only torch.SymInt arguments. Dynamo does not support this._sym_r9  r   r   rc  rm  requires_gradzAAttempted to use tensor creation function with requires_grad=Truer  z.Create the tensor outside the compiled region.z Do not set `requires_grad=True`.z)Expected out= list element to be a tensorz0Shape mismatch with out= list of tensor variantszShape mismatch when calling z% with `out=`. Provided `out=` shape: z. Actual shape: z?Attempted to call op with non-contiguous `out=` list of tensorszself.value=zExpected out= kwarg to be setz"Expected out= kwarg to be a tensorz=Expected out= kwarg proxy node to have example_value metadataz'Shape mismatch with out= tensor variantz6Attempted to call op with non-contiguous `out=` tensor)Qrj  r  re  r  r  r  r  "_call_nonstrict_traceable_functionr  _call_leaf_functiontorch_function_override_enabledrG   r>  r.   r   #constant_fold_functions_need_guardsr   r   r)   r'   r   r&   r  r9   r'  r   r   OverflowErrorr  r  r!   r   r  rR  is_tensor_methodrT   r  rU   rV   rW  r  r&  r  Taginplace_viewtagsr#   r8   r   r   call_tensor_methodr  r   rr  r   bin_opsr-   rD  r  warningr   rC   rB   r   r   r   shaper   r   rQ   	fake_mode	shape_envignore_fresh_unbacked_symbolsry  rz  r4   r  r  _prims_commonis_contiguousis_contiguous_or_false)r   r  rR  r   r  r   r  r  r  excrZ   
tensor_varrY   special_handlerr   any_symints_or_symfloatsall_ints_or_floatsrr  fn_torch_sym_opsaved_out_shapesout_kwarg_vtr   r$  r  tensor_variableout_tensor_vtsaved_out_shapefake_outr  s                                @r[   rc  z*TorchInGraphFunctionVariable.call_function  sw    	&*99(888::2tVLL99(666++Bf==//D&A*2tT6BB))+0M&1
 zz@@;;&(]  2$++>f//0I0IJK&,,-D++-:>?Q!..0?AGPA1a2244P    "::&&DQ))+!!W
$$0WUYY^^T5R 6BK0#Bq(9:!II22"2r||~a'89>>? &$@$&*`ahimisisat`uuv(w#!2!>!># Q#	 **2tDz6BB,,.224::>$T2???F#&&Tt&T#T   !
NR!
 
 DJJb1W<

##w.(")+		TZZ C
 KKbdjj\ixH(TZZ(9 :4 4&22
 jj#"4::#6#6"78Ltzz<6&@W|F e\2  F?!%=L ,(EF#% &,, 3B||~ " 2 2 7 7 H N N $$++E23 %%' ))+0055oFLL ! 00|| 6 6ll,,JJU 	+,bii,,# 'tV4O	 %%'6)'::<[djj\ixH;D6 '22		 ' *D169 &&$7 '2M? '. !(224,G   -2277<<_MH&(..8 &$V&)$**WTF)F8$T">tzzl K::I9JJZ[c[i[iZjjk!m#!2!>!>#
 !..<<XF &$e&1$**WTF)TZS[$\(G#!2!>!>#	A'X G  '()HII#--/()MNN",*?*?*A*F*F*K*KK(W  (00277<<_M#x~~5 " I"%djj\ix P:4::, G66F5GGWX`XfXfWgghj.::
 **AA(K " X"-djj\iPVx X$C.::	 g @P "9j9 (Ichh t	 	sB   $a6 6a+a6 #a0>	a6 ?1c+a6 6b?
*b::b?cc           
        !"#$%& ddl m} ddlm#m}m%m& ddlm} ddl	m
" ddlm} ddlm} dd	lm}	m}
 | j%                  |||      \  }}t'        |  |||      t)        j*                  |||f                  \  }}t-        |t.              st1        d
t3        |             |j4                  D ]I  }|j7                         } ||      r|j7                         j8                  }t;        dd| dddg       K |j4                  D cg c]  }|j=                          }}	 |j?                         }| jL                  $dt(        dt(        d t(        f"$fd!} ||      }|jN                  jQ                  $jR                   d"|      }|jN                  jQ                  $jR                  d#z         }t3        |      |jT                  _        t3        |      |jT                  _        ||g|}d !dtV        d tX        tZ           f!#%&fd$}|jN                  j]                  d%||i       }	  |
||      }!t1        d*      t)        j*                  |!      }|	ji                  |tD        jj                        jm                  |||gi       } | S c c}w # |$ r}|j@                  j7                         }|j8                  }dd lm!c m"} |jG                  |      r-t;        dd| d| dd| ddgtH        jJ                  |       n1t;        dd| d| dd| ddd| dgtH        jJ                  |       Y d }~d }~ww xY w# t^        j`                  jb                  jd                  t^        j`                  jb                  jf                  f$ r8 t;        d&d'$jR                   d(g tH        jJ                         t1        d)      w xY w)+Nr   _make_inlined)
flat_applyis_graphable_typeis_valid_outputto_graphable)_LeafCallable)fake_tensor_tls)tree_flattenr7   )#AsPythonConstantNotImplementedError)rc  r  z1Expected flat_args_vts to be a ListVariable, got z2Invalid input type for nonstrict_trace-ed functionzEncountered input of type <z>.zFor `nonstrict_trace`-ed functions, only basic types (e.g., torch.Tensor, int, float) or pytree containers of those are allowed as inputs. The provided argument contains an unsupported type.zUse one of the following to register the type with pytree:
* `torch.utils._pytree.register_constant`
* `torch.utils._pytree.register_dataclass`
* `torch.utils._pytree.register_pytree_node`r   zVInput marked with `pytree.register_constant` constructed in the `torch.compile` regionzInput=z, offending type <zWCalling a `nonstrict_trace`-ed function with an input that contains an object of type <z>, which was marked with `pytree.register_constant`. However, the object was constructed _inside_ the `torch.compile` region. This is not supported.zXConstruct the object _outside_ the `torch.compile` region, or submit an issue to GitHub.r?  z>Invalid use of pytree_flatten with nonstrict_trace-ed functionzCalling a `nonstrict_trace`-ed function where one of the inputs has been registered with a `pytree_flatten` that places an object of type <z> into the context.zLModifying the `pytree_flatten` to avoid placing the object into the context.zApply one of the following to <z>:
* `torch.utils._pytree.register_constant`
* `torch.utils._pytree.register_dataclass`
* `torch.utils._pytree.register_pytree_node`rR  r   r^   c                  f    j                   }d_         	  | i |}|_         |S # |_         w xY wNT)allow_non_fake_inputs_override)rR  r   old_valresr@  rY   s       r[   
patched_fnzSTorchInGraphFunctionVariable._call_nonstrict_traceable_function.<locals>.patched_fnv  sH     &DDG=AO:I$)&)AH>J BI>s   ' 	0	_callable_input_specc                       | ddi} |      \  }}|n|k7  rt        d|d       |      st        d      |S )Nchecked_outputFzTError: nonstrict-traced functions must return the same output shape every time. got z vs but expected z1Nonstrict-traced function returned invalid outputr  )rR  r   flat_outspeccaptured_specr;  r=  r>  s       r[   flat_apply_capturez[TorchInGraphFunctionVariable._call_nonstrict_traceable_function.<locals>.flat_apply_capture  s|    d959C
 *#.NHd$ $ D((88<x?PQ^Pac  #8,$G  Ory   rc  z7Unsupported output type for nonstrict_trace-ed functionz
Function: zFor `nonstrict_trace`-ed functions, only basic types (e.g., torch.Tensor, int, list) are allowed as output. The result of this call contains an unsupported type.unreachablez0captured_spec was not set during nonstrict trace)7torch._dynamo.utilsr:  "torch._higher_order_ops.flat_applyr;  r<  r=  r>  ,torch._higher_order_ops.invoke_leaf_functionr?  r   r@  torch.utils._pytreerA  baserB  re  rc  r  _extract_nn_module_statesr5   r9   r'  r   rB   r   r   r   r  r@  r#   r   r   r   r  _pytreeis_constant_classr   r   r   ry  rn  rT   r   r   r  objectrz  rV   rk   r+  UnsupportedTorchRuntimeErrorro  tree_unflattenrc  )'r   r  rR  r   r:  r<  r?  rA  rB  rc  r  args_with_stateskwargs_with_statesflat_args_vtsinput_spec_vtflat_arg_vtarg_type	type_nameproxified_flat_args
input_specrF  typpytreerH  
f_callablef_callable_proxyinput_spec_proxyall_argsrP  r  proxy_list_vtout_spec_vtout_vtrO  r@  r;  rY   r=  r>  s'                                    @@@@@@r[   r  z?TorchInGraphFunctionVariable._call_nonstrict_traceable_function  s=    	6	
 	
 	OA4== 04/M/Mf0
,, (7+M"l+%%b+;=O*PQ(
$} -6 CDDWCXY 
 ).. 	K"..0H$X.'335BB	P9)BG/
G		. 7D6I6I
'2K  "
 
'	&99;JP ZZ	"	.=		 #:.
99JJ{{m9%z
 99JJKK-'

 &**%5"%)*%5"$&6M9LM *.	c 	d6l 	 	, 		&&/2
	0)"e4M&   !STT%++B> #))"g.D.DESS,b
 s
 3 %	$$""$C((I00'',t$]O3Ei[PRS$$-; /ff
 s*66  \$]O3Ei[PRSRR[Q\\oq g9) EG G +66 +%	j MM))MM//	
 	0 Q$R[[M2d 7)556 !//!	0s,   J(J /	M MBL>>MBO	c           
      J   ddl mc m} ddlm} ddlm} ddlm} ddl	m
m dt        d	t        t        d      ffd
}t        |  |||j                         t        j"                  |||f                  \  }	}
i }t        ||	      D ]  } ||      s|j$                  1t'        ddt)        |j*                        j,                   dddg       |j$                  t/        d       ||j*                  |j$                        |t1        |j*                        <    |s9t        j"                  |t3        |            }t        j"                  ||      }||fS t        j"                  ||      }  |||      t        j"                  |||f      |      }t        ||      S )z
        Extract nn.Module states from arguments for leaf function invocation.

        Replaces nn.Module arguments with LeafModuleState objects containing
        the module's index (for later retrieval), parameters, and buffers.
        r   N)register_user_objectr9  )convert_modules_to_statesr7   )NNModuleVariableUnspecializedNNModuleVariabler   r^   c                      t        | f      S r   r  )r   rs  rt  s    r[   is_module_variablezRTorchInGraphFunctionVariable._extract_nn_module_states.<locals>.is_module_variable  s     c$46S#TUUry   z0leaf_function: nn.Module argument without sourcezmodule type: zleaf_function received an nn.Module argument that cannot be traced back to its origin. This typically happens when the module is created dynamically inside the compiled region.zXEnsure the nn.Module is created outside the compiled function and passed as an argument.zCIf the module is a class attribute, access it via self.module_name.r   zExpected arg.source to be set)rU  r  rX  #torch._dynamo.graph_bytecode_inputsrq  rR  r:  rT  rr  	nn_modulers  rt  r9   r   r
   r5   rA  r'  r   r#   r   r   rT   r   r  rE  )r   r  rR  r   rh  rq  r:  rr  rv  flat_args_vartree_spec_varmodule_to_indexr  args_var
kwargs_varmodule_to_index_var
result_varrs  rt  s                    @@r[   rW  z6TorchInGraphFunctionVariable._extract_nn_module_states  s    	-,L5	
 	O	V 	VEMNO	V
 (72M"f112%%b4.9(
$} +-"2}5 	C!#&::%! R"/SYY0H0H/I JX
9a ::%()HII1EIIszz2399.'	. &,,Rt=H(..r6:JZ''-33BHA]2'@A!!"tVn57J

 r:..ry   c           
         dd l mc m} ddlm} ddlm}m}m} ddl	m
}	 | j                  }
|
j                  }|
j                  }|
j                  }|t        dt!        |
d|
       d      | j#                  ||      \  }}t%          ||j&                        t)        j*                  ||f                  \  }}t%        |      D cg c]  }|j-                          }}|j/                         }d	}|rdd
lm} 	  |||t3        |      |      }d g} ||||      \  }} ||      } ||      }t!        |
dd       }|t!        |
dd       }||_        ||_        dt:        dt@        dt@        ffd} |d|      }  |d|      }! |d|      }"| |!|"|g|}#jB                  jE                  d||#i       }$ |	|$      }%|d   tG        d      t)        j*                  |d         }&  |t        jH                        |%|&      S c c}w # t        $ r)}t5        t6        j8                  t;        |            |d }~ww xY w)Nr   r9  )r?  invoke_leaf_functionmake_leaf_function_wrappersr7   r  zleaf_function 'rT   z' requires a fake implementation. Please provide one using the @<func>.register_fake decorator. See the leaf_function docstring for details.rj  )_resolve_mutated_flat_indices_torchdynamo_leaf_hook_fn_torchdynamo_leaf_hook_fake_fnrZ   rN  r^   c                 t    j                   j                  | |      }t        |      |j                  _        |S r   )ry  rn  r   r   )rZ   rN  r  r  s      r[   make_callable_proxyzMTorchInGraphFunctionVariable._call_leaf_function.<locals>.make_callable_proxyj  s-    IICCD$OE"4jEJJOLry   real_fnfake_fnrf  rc  zjOutput spec was not captured during fake tensor propagation. This should not happen - please report a bug.)%rU  r  rX  rR  r:  rT  r?  r  r  re  r  r   _torchdynamo_leaf_real_fn_torchdynamo_leaf_fake_fn_torchdynamo_leaf_mutates_argsr  r&  rW  r5   rA  r9   r'  r   r   r  rl  r$   r%   r  rD  _leaf_hook_real_fn_leaf_hook_fake_fnr   ry  rz  r   r]  )'r   r  rR  r   rh  r:  r?  r  r  r  decorated_fn	real_impl	fake_implmutates_argsr^  r_  ry  input_spec_varr  flat_arg_proxiesrf  mutated_flat_indicesr  rF  captured_out_specwrapped_real_implwrapped_fake_implreal_impl_callablefake_impl_callablehook_fnhook_fake_fnr  real_impl_proxyfake_impl_proxyrk  invoke_argsresult_proxyflat_output_vtrn  s'    `                                     r[   r  z0TorchInGraphFunctionVariable._call_leaf_function#  s    	-,5	
 	
 	+zz ::	 ::	#BB!',
L"Q!R SJ J  04/M/Mf0
,, )82M"f112%%b+;=O*PQ)
%~ '6b-&H
"CLLN
 
 $668
!L'D|S1A-BJ($ <@&/Jy"30
,, ++<=*+<=,(CTJ"<1QSWXL4;14@1	c 	 	 	
 .i9KL-i9KL.|ZH  	

 
 yy--1;
 'r<8Q' @  &++B0A!0DE8}R!7!78UU{
  L ; ;SVD!KLs   H	H 	I $H;;I c                 B   | j                   t        j                  j                  j                  j
                  u r|d   j                         n#| j                   j                  d   j                  t        t              st        dt                     |rt        dt        |             dt        dt        ffd}| j                   t        j                  j                  j                  j
                  u rt        j                   |      S  ||d         S )z1inline behavior of torch.nn.modules.utils._ntupler   z,Expected count to be an int in _ntuple, got z_ntuple expects no kwargs, got r   r^   c                 T   t        |       rt        j                  t        |             S | j	                         rZt        j                  t        j                  j                  j                  j                        | j                                     S t        dd|  ddg       y )NzPAttempted to use `torch.nn.modules.utils._ntuple` with unsupported argument typezvalue=r  z:Change use of _ntuple with argument as constant or tensor.r   )rD   r   rC   r5   r   r9   r'  rV   rt   ru   r  r  r   r#   )r   countr  s    r[   r  z@TorchInGraphFunctionVariable._call_ntuple.<locals>.handle_ntuple  s    e$ ..r5/IJJ))+&,,HH$$**2259%:R:R:TU 
 n$UG, ?T	ry   )r   rV   rt   ru   r  r  r   __closure__cell_contentsr   rF  r   r   rl  r9   r   LambdaVariable)r   r  rR  r   r  r  s    `   @r[   r  z)TorchInGraphFunctionVariable._call_ntuple  s     ::))//777G..0EJJ**1-;;E%% >tE{mL   #B3v;-!PQQ	 	_ 	& ::))//777++M:: a))ry   r*  r  c           
      b   |j                   r t        ddddgt        j                         t	        |t
        j                        r	 |j                         }||j                         s#t        d
d| ddgt        j                         |j                  r| j                  |||      S t        j                  r!t        dddddgt        j                         t	        |t              st!        |j"                        r(t        dt%        |      dg t        j                         t'               s t        ddddgt        j(                         	 t+        |j-                  |d      j                               }|j-                  |d      j                         }|j-                  |d      j                         }|j.                  j1                  t2        |f      }|j4                  r|j7                  |dg i       }ddlm}	  |	||j.                  j=                  dt>        |jA                         |jA                         fi       |j                         }
|
j                         stC        d!      tD        jF                  jH                  |
_        d"|
_%        |j.                  jL                  jO                  |
       |
S # t        $ r' t        dd| ddgt        j                         Y w xY w# t        $ r/}t        dd| ddgt        j                  |       Y d	}~kd	}~ww xY w)#z>A call to torch.nn.Parameter() gets lifted to before the graphz3Attempted to use `torch.nn.Parameter()` with exportrj  r  z.Do not use `torch.nn.Parameter()` with export.r   z=non-constant `requires_grad` argument to `torch.nn.Parameter`zrequires_grad=z$Change `requires_grad` to be a bool.Nz1`torch.nn.Parameter()` with unsupported data typezdata=z7Called `torch.nn.Parameter()` with non-Tensor argument.zBEnsure the argument to `torch.nn.Parameter()` is a `torch.Tensor`.z?Attempted to use `torch.nn.Parameter()` constructor with DynamozDynamo does not support thiszDTry to construct `torch.nn.Parameter()` outside the compiled region.z@If this is not possible, turn `graph_break_on_nn_param_ctor` offzDAttempted to use torch.nn.Parameter constructor with tensor subclassz:`torch.nn.Parameter`: cannot convert to traceable tracablez+convert_tracable_parameter is set to False.zDCheck usage of context manager: do_not_convert_to_tracable_parameterr$  r  r  z8`torch.nn.Parameter` with non-constant Tensor attributeszBEnsure the Tensor argument's shape, dtype, and device are correct.r?  detachr7   r  rc  r   z<Expected result of traceable_create_parameter to be a tensorF)(exportr#   r   r   r   r   r9   r   r)  r  r  r   _nn_param_via_prefix_insertr   graph_break_on_nn_param_ctorrH   r   
class_typerD  r   	DIFFICULTrE  r  ry  synthetic_graph_inputr   r  r  re  r  rz  r   r   r   rV   rt   r  has_grad_fnleaf_var_creation_orderr   )r   r  r*  r  r$  r  r  rF  r   r  r   s              r[   r  z.TorchInGraphFunctionVariable.call_nn_parameter  s5    99M;D&22	 mY%>%>? - @ @ B <t~~/KvUX&11	 ;;222t]KK..Y:ZV '22		 (
 0@^D	;&22	 12TIZ&00		$**2w7JJLME$$R1DDFE%%b(3FFHF ii55%E6=1
 ##B"b9D*II"")+"6"6"89	 %%
 ! N  "HH.. #
 			))008 q ' 	[,]O< ?>*55	 	H # 
	Rv;X&11 	 	
	s+   K A)K6 ,K32K36	L.?$L))L.c                 
   | j                   j                         }| j                   j                  t        d      t	        | j                   j                        j                  fd        |j                          t        j                  | |             j                  dd       j                  |       | j                   j                  j                  j                                |j                         j                  }|j                   dvr,t#        dd|j                    dg t$        j&                  	       t)        |      }t*        j,                  j/                  | j                   j1                  |j                         j                        |
      }t        j                  | ||      }|j3                         }t5        j6                         j8                  j:                  j=                  |       |S )Nz$Expected tx.output.root_tx to be setc                  (     j                  dd      S )Nztorch.nnr  )load_import_from)cgs   r[   r"  zJTorchInGraphFunctionVariable._nn_param_via_prefix_insert.<locals>.<lambda>M  s    !4!4Z!M ry   r   F)r   get_attrzAUnexpected type of data placeholder op for parameter constructionzdata_node.op=z/Data node op should be placeholder or get_attr.r   )r  )ry  new_varroot_txr   r   add_push_nullr   r9   r'  rc  storepregraph_bytecoder   get_instructionsr   r   r   r#   r   r  r,   rV   rt   r  example_value_from_input_noder   r   r   guards_contextdynamo_guardsremove_guards_with_source)	r  r*  r  varname	data_noder   r   r   r  s	           @r[   r  z8TorchInGraphFunctionVariable._nn_param_via_prefix_insertB  s   
 ))##% 99$ !GHHryy(()
MN
4;;
?  ]34
E"

		##**2+>+>+@AMMO((	<<::['	~6M&00	 &g.**II33DMMO4H4HI' + 
 !&&r=&A! 	++99SS	
 ry   c                 f    |d   j                  || j                         j                  |dd  |      S )Nr   r7   )r  r  rT   r  s       r[   r!  z/TorchInGraphFunctionVariable.call_tensor_methodo  s4     Aw""2t'8'8':'C'CT!"XvVVry   c                 ,   ddl m} t        j                  | j	                               xrQ t        | j	                         d      xr5 | j	                         j                  t        j                  j                  k(  xs | j	                          |       v S )Nr   )get_tensor_method__objclass__)
r  r  r   ismethoddescriptorr  rU   r  rV   rc   
TensorBase)r   r  s     r[   r  z-TorchInGraphFunctionVariable.is_tensor_methodw  s    3 &&t'8'8':; H))+^<H !!#00EHH4G4GG	8
  $5$77	8ry   c                     | j                         t               v xsL t        | j                         t        j                  j
                  t        j                  j                  f      xr t        |||      S r   )r  r   r   rV   r   r   r   rF   r  s       r[   r  z<TorchInGraphFunctionVariable.torch_function_override_enabled  sf     #<#>> !!#&&

(C(CD< *"dF;	<ry   r  c                 f    t        |t              sy| j                         |j                         k(  S r.  )r   r9   r   )r   r  s     r[   is_python_equalz,TorchInGraphFunctionVariable.is_python_equal  s,    %1&&(E,D,D,FFFry   r   rD  )#rT   r  r@  rA  r   r   r  r   rD  rM  r  r  	functoolscacher  r  r  r9   rc  r  rE  rW  r  r  rB  rC  r  r  r!  r  r   r  rZ  r  rG  rH  s   @r[   r  r  ^  s   J
 )-S! % 	
 
&O# OhsCx0  __o!4c 2HS#X4F FG o!  o!bCU'U ?#U -	U
 
UnX'X ?#X -	X
 
XtC/'C/ ?#C/ S/)*	C/
 
/	0C/JcV'cV ?#cV S/)*	cV
 
cVJ(*'(* ?#(* S/)*	(*
 
(*T   "	M'M DjM 	M
 
M M^ *'*/2*CG*	* *XW'W ?#W S/)*	W
 
W8$ 8<'< sm< S#X	<
 
<GV G Gry   r  c            
            e Zd ZdZedededd fd       Zedede	dd fd       Z
dd	d
ededefdZdedefdZdd	dedee   deeef   ddf
 fdZ xZS )r  zrepresents torch.DispatchKeySetr   r   r^   c                     t        | fi |S r   )r  )r   r   s     r[   ro  zDispatchKeySetVariable.create  s    %e6v66ry   r   c                 f    t        |j                  t        j                                | ||      S r   )r'   r   r&   DISPATCH_KEY_SET_MATCHr   s      r[   r   z)DispatchKeySetVariable.create_with_source  s*     	f''(K(KLM5((ry   r  rL   r  r   c                 $    ddl m}  || |||      S )Nr7   ) python_constant_richcompare_impl)r4  r  )r   r  r  r   r  s        r[   r5  z'DispatchKeySetVariable.richcompare_impl  s     	F/b%DDry   rZ   c                     |dk(  S )Nhasrx   )r   rZ   s     r[   is_constant_fold_methodz.DispatchKeySetVariable.is_constant_fold_method  s    u}ry   rR  r9   c                    | j                  |      rt        ||      r~t        | j                  |      }t	        j
                  | ||D cg c]  }|j                          c}i |j                         D ci c]  \  }}||j                          c}}      S |dk(  r.t	        j
                  || j                  j                               S t        	| )  ||||      S c c}w c c}}w )NhighestPriorityTypeId)r  r.   r&  r   r9   r'  r   r   r  r   r  )
r   r  rZ   rR  r   r+  r  r  r  r   s
            r[   r  z"DispatchKeySetVariable.call_method  s     ''-2O&3
 TZZ.F"((6:;a**,;=C\\^LTQq!..00L  ,,"((TZZ-M-M-OPPw"2tT6:: <Ls   C"8C')rT   r  r@  rA  r  r   r   ro  rB  r   r   r9   rD  r5  rC  r  r  r  r  rG  rH  s   @r[   r  r    s    )7n 7 78P 7 7 )"),2)	!) )E-E6EEKNE	EC D ;'; ; ?#	;
 S/)*; 
; ;ry   r  c            
       f     e Zd ZdZedededd fd       Zddded	e	e
   d
eee
f   ddf
 fdZ xZS )r!  z<represents torch._functorch.pyfunctorch.FuncTorchInterpreterr   r   r^   c                 f    t        |j                  t        j                                | ||      S r   )r'   r   r&   rC  r   s      r[   r   z/FuncTorchInterpreterVariable.create_with_source  s*     	f''(=(=>?5((ry   r  rL   rZ   rR  r   r9   c                 >   |dk(  r.t        j                  || j                  j                               S |dk(  rI|j	                  t        j                  || j                  j
                  j                        | g|z   |      S |dv r/t        j                  | t        | j                  |                   S |dk(  rR|rt        dt        |             |rt        dt        |             t        j                  j                  |d       S t        | 9  ||||      S )Nkeyprocess)rA  
batch_size
randomnesslowerzlower() expects no args, got zlower() expects no kwargs, got )r9   r'  r   r  r  r  __func__r&  r   rl  r   0TemporarilyPopInterpreterStackCtxManagerVariablero  r   r  )r   r  rZ   rR  r   r   s        r[   r  z(FuncTorchInterpreterVariable.call_method  s    5="((TZZ^^-=>>Y11%%b$***<*<*E*EF 
 ::"((-FWTZZ-F-HIIW_$'DSYK%PQQ$'Fs6{m%TUUMMTTD  w"2tT6::ry   )rT   r  r@  rA  rB  r   r   r   rD  r  r9   r  r  rG  rH  s   @r[   r!  r!    sy    F))!')	') );'; ; ?#	;
 S/)*; 
; ;ry   r!  (	  rA  enumr  r   loggingr9  r  collections.abcr   r   
contextlibr   typingr   r   r   r	   r
   typing_extensionsr   torch._CrV   torch._refstorch.fxtorch.nnrU  r  rX  r    torch._dynamo.variables.constantr   torch._dynamo.variables.streamsr   &torch._dynamo.variables.torch_functionr   torch._guardsr   r   r   torch._loggingr   torch.autograd.graphr   r   r   rj  r   r   r   r   r  r   create_parameter_opr   r   r   r  r    r+  r!   r"   r#   r$   r%   guardsr&   r'   r   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   rV  r8   r9   ctx_managerr:   r;   r<   r=   distributedr>   rm  r?   r@   rA   r   rB   rC   r4  rD   script_objectrE   torch_functionrF   rG   rH   rI   user_definedrJ   numpyr  ModuleNotFoundError#torch.distributed.fsdp._fully_shardrK   torch._dynamo.symbolic_convertrL   torch._opaque_baserM   rN   rO   rP   	getLoggerrT   r  r  r  r  r  r;  r  r  r  r  rc   r  r  r  r  r  r  r  r  r  r{  r|  r}  r  rp  rr  rk  rq  r  r  r  r~  re   rs  rt  ru  rt   r  r  rP  _shape_as_tensorr  get_dynamic_layer_stack_depthrU  current_device_indexrV  r  is_initializedrR  
__future__)get_overwrite_module_params_on_conversionr  r  rn   _get_device_index_get_cublas_allow_tf32_is_any_autocast_enabledr   get_device_propertiesget_autocast_dtypeget_autocast_gpu_dtypeget_default_dtyper9  is_autocast_cpu_enabledr3  r  r  r  
_Reductionget_enumpromote_types_get_privateuse1_backend_name_is_checkpoint_validr:  r   r  r  	frozensetr{   r|   addmmaddmvaddraddbmmbaddbmmr  r  _foreach_add_foreach_add__foreach_sub_foreach_sub__foreach_mul_foreach_mul__foreach_div_foreach_div__foreach_clamp_max_foreach_clamp_max__foreach_clamp_min_foreach_clamp_min__foreach_maximum_foreach_maximum__foreach_minimum_foreach_minimum_r  _foreach_pow__foreach_lerpr  _foreach_addcmul_foreach_addcmul__foreach_addcdiv_foreach_addcdiv_rQ   __annotations__r]   rD  r  rC  rz   r"  r  _dispatch_tls_local_include_set_dispatch_tls_local_exclude_setr  r   rW   r   Noder   r  rE  r   r   r   r   rJ  Enumr  r  r  r!  rx   ry   r[   <module>r4     s.	  6      	 . " ? ? $     % % # = : L 7 7 ' - K > >  
 @  1    +  - 
 / + 4  3E
 H-, CLCLg! $''!!77!!,,''//--%%44))@@))??))FF		((  ,,  //  ((  1188		##,,

$$--####// 	&&22; ! F %)MM% ! 
HH55	**	))	JJ	JJ	II	II	>>	' # 
MM	LL""	HH##	HH%%	""	JJ$$	JJ	""		  		##	!!				HH""++		HH**	NN''	II##	II-. (/( 0 	!!#"",,&&,,	
 '+mm4W&X #--(?@  AJ$		$ 			$ 		$
 	$ 	

$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$  	!$" 	#$$ 	%$& 	'$( 	  )$* 	!!+$, 	  -$. 	!!/$0 	1$2 	3$4 	5$6 	7$8 	9$: 	;$< 	=$> 	?$@ 	A$B 	C$D 	E$F 	G$&A 	(38*< = &X 6? ?,? 6 "IcN  hr3w&7&D!E  . --<
= 
HH	HH,,	HH,, ,H/ ,HS ,HT ,H^%,, 3u~~7K7K7P7P3Q 6D	D	%cDj(
)*DN"$5 "$uxx}}:M "J 3xS'9#:  ${A {A|Q7#4 Q7h$tyy $t0G#4 t0Gna,;. ,;^#;#4 #;cz  	B
  s$   4k/ 9k= /k:9k:=ll