
    Ph+?                       d Z ddlmZ ddlZddlmZmZmZmZm	Z	m
Z
mZ ddlZddlmZ ddlZddlZddlmZ ddlmZmZ ddlmZ dd	lmZmZmZ dd
lmZ ej>                  	 	 	 	 	 	 	 	 dd       Z ej>                   ejB                  ejD                  jF                  e       	 	 	 	 	 	 	 	 	 	 	 	 dd              Z$ej>                  dd       Z%ej>                  dd       Z&ej>                  	 	 	 	 	 	 dd       Z'ej>                  	 	 	 	 	 	 	 	 dd       Z(ej>                  	 d	 	 	 	 	 	 	 	 	 dd       Z)ej>                  dd       Z*y)z9Module for handling op-level validation during exporting.    )annotationsN)AnyCallableDictListSequenceTupleUnion)	evaluator)symbolic_shapes)
_constants_type_utils)	_beartype)diagnosticsfx_onnx_interpreter
type_utils)_pytreec                    d|j                    d|j                   d|j                   d|j                   d|j                   dS )Nz	FX Node: z::z[name=z]. 
ONNX Node: z[opset=z].)optargetnameopset)fnselfnodesymbolic_fnargskwargss         pC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\torch/onnx/_internal/fx/op_validation.py!_op_level_debug_message_formatterr       sN     DGG9Bt{{m6$)) =!&&'w{/@/@.A	E    )diagnostic_message_formatterc           	        	 t        |||      \  }}t        j                  t        j                        5  	  |j                  |i |}
	 t!        |j#                         ||d      \  }}t%        j&                  |      }	  ||i |}t+        j,                  |
      \  }}t+        j,                  |      \  }}|sJ t/        |      t/        |      k(  sJ t1        ||      D ]"  \  }}t3        |t4        j6                        rBt9        j:                  |j<                        r#t5        j>                  |jA                               }	 t3        |tB        jD                  j6                        r|jF                  }t4        jH                  jK                  t5        jD                  |      jM                         t3        |t4        j6                        r|jM                         n"t5        jD                  |      jM                         dd	
       % 	 ddd       y# t        $ r}| j                         }	|	j                  t        j
                  d      5  |	j                  t        j
                  |       ddd       n# 1 sw Y   nxY wt        j                  j
                  |	_	        Y d}~yd}~ww xY w# t        $ r}| j                         }	|	j                  t        j
                  d      5  |	j                  t        j
                  |       ddd       n# 1 sw Y   nxY wt        j                  j
                  |	_	        Y d}~ddd       yd}~wt        $ r}| j                         }	|	j                  t        j
                  d      5  |	j                  t        j
                  |       ddd       n# 1 sw Y   nxY wt        j                  j
                  |	_	        Y d}~ddd       yd}~ww xY w# t(        $ r}| j                         }	|	j                  t        j
                  d      5  |	j                  t        j
                  |       ddd       n# 1 sw Y   nxY wt        j                  j
                  |	_	        Y d}~ddd       yd}~ww xY w# t        $ r}| j                         }	|	j                  t        j
                  d      5  |	j                  t        j
                  |       ddd       n# 1 sw Y   nxY wt        j                  j
                  |	_	        Y d}~ddd       yd}~ww xY w# tN        $ r}| j                         }	|	j                  t        j
                  d      5  |	j                  t        j
                  |       ddd       n# 1 sw Y   nxY wt        j                  j
                  |	_	        Y d}~d}~ww xY w# 1 sw Y   yxY w)a  Validate the op between ONNX Runtime and PyTorch.

    The function will run the op in ONNX Runtime and PyTorch and compare the
    results. It doesn't break the exporting process, but saves each op validated
    result into SARIF, under the section of `fx_onnx_interpreter`.

    There are three signs can be found:
    1. Blue: Pass
    2. Yellow: Bypass

    Args:
        node (torch.fx.Node): The validated fx.node
        symbolic_fn (Union[onnxscript.OnnxFunction, onnxscript.TracedOnnxFunction]): The corresponded ONNX node
        torch_args (list): torch argument inputs
        torch_kwargs (dict): torch keyword argument inputs
        fx_graph_module (torch.fx.GraphModule): The fx.GraphModule that contains the nodes
    z3Op level debug fails due to unsupported input typesNzOp level debug is bypassedzOp level debug fails on PyTorchT)allow_extra_kwargsz#Op level debug fails on ONNXRUNTIMEg-C6?gMbP?)rtolatolzValidation failed)(_wrap_fx_args_as_torch_args
ValueErrorinflight_diagnosticlog_sectionloggingWARNINGlog_source_exceptionr   levelslevelr   
default_asort_evaluatorr   
IndexErrorRuntimeError(_convert_torch_args_to_onnxfunction_argsparam_schemasr   ,filter_incompatible_and_dtype_convert_kwargs	TypeErrorr   tree_flattenlenzip
isinstancetorchTensorfx_type_utilsis_torch_complex_dtypedtypeview_as_realresolve_conj
onnxscripttensorvaluetestingassert_closecpuAssertionError)diagnostic_contextr   r   fx_args	fx_kwargsfx_graph_module
torch_argstorch_kwargsvalue_error
diagnosticexpected_outputsindex_errorruntime_errorfunction_eager_inputsfunction_eager_attributes
type_errorort_outputsflattened_torch_outputs_flattened_function_outputstorch_outputfunction_outputes                          r   validate_op_between_ort_torchr_   )   s   B#>Y$
 
L 
		i55	6	*t{{JG,G&	 9))+#'	%) $PP- &	%&*CK &-%9%9:J%K"(/(<(<[(I%"A&&&*+s3M/NNNN-0#%?.
)L/ ell66|7I7IJ$11,2K2K2MN>oz/@/@/G/GH&5&;&;O **LL1557!,= !$$&l3779 + .
A 
7	6  ';;=
##OOR
 ++GOO[I
 
 
 '--55
  	+??AJ''9UV//M WVV*1199J 
7	6  	+??AJ''!B //O    +1199J' 
7	6	4  	+??AJ''9UV//L WVV*1199JW 
7	6L	  	+??AJ''!F //O    +1199Jq 
7	6b	F " >/CCE
++GOO=PQ33GOOQG RQQ#.#5#5#=#=
  	>i 
7	6sa  H WJ,
5O- RB<WB?T3W	J)0J$
!I4+	J$4I=	9&J$$J),	O*50M%!L	ML&M:WO*0O%!N-$	O%-N62&O%W%O**W-	R60R&!Q	RQ&R;WRW	T00T+	!S3*	T+3S<8&T+W+T00W3	W<0W,!V		WV&WWWWWc                ,   g }| D ]y  }t        |t        j                        rLt        j                  |      r%|j                  t        j                  |             Wt        d| d|  d      |j                  |       { t        j                  |      S )zConvert SymInt to int in shape

    Args:
        shape (torch.Size): The shape of a tensor
    Raises:
        ValueError: When SymInt is found in shape
    Returns:
        torch.Size: The shape of a tensor with SymInt converted to int

    z+An unbacked SymInt found in shape. SymInt: z; torch.Size: z. There is no hint for SymInt.)	r;   r<   SymIntr   has_hintappendhint_intr(   Size)shapelist_int_shapedims      r   _convert_symint_to_int_in_shaperi      s     Nc5<<('',%%o&>&>s&CD A# G##(')GI 
 !!#&  ::n%%r!   c                   t        |       } |t        j                  k(  r5t        j                  t        j
                  t        j                  | |      S |t        j                  k(  r5t        j                  t        j                  t        j                  | |      S |t        j                  k(  r5t        j                  t        j                  t        j                  | |      S |t        j                  k(  r5t        j                  t        j                  t        j                  | |      S |t        j                   k(  r5t        j                  t        j"                  t        j$                  | |      S |t        j&                  k(  rUt        j(                  |       }t        j*                  |dkD  t        j,                  d      t        j,                  d            S t/        j0                  |      rBt        j2                  t        j4                  g | dt/        j6                  |                  S t        j4                  | |      S )N)lowhighsizer@   g      ?TF   r@   )ri   r<   uint8randintr   	UINT8_MIN	UINT8_MAXint8INT8_MININT8_MAXint16	INT16_MIN	INT16_MAXint32	INT32_MIN	INT32_MAXint64	INT64_MIN	INT64_MAXboolrandwhererD   r>   r?   view_as_complexrandnfrom_complex_to_float)rf   r@   random_numberss      r   generate_random_tensorsr      s   +E2E}}$$:+?+?eSX
 	
 

}}##**=*=EQV
 	
 }}$$:+?+?eSX
 	
 }}$$:+?+?eSX
 	
 }}$$:+?+?eSX
 	
 

E*{{S %,,t"4ell56I
 	
 ++E2$$KK%=+N+Nu+UV
 	
 ;;uE**r!   c                   g }| D ]  }t        |t        j                  j                        r|j                  j                  d      }|%|j                  dk(  rt        ||j                        }t        |t        j                        r2t        |j                  |j                        }|j                  |       t        |t        t        t         f      r|j                  |       t#        j$                  |      r&|j                  t#        j&                  |             t)        d| d| dt+        |       d      t        |t,              r|j                  t/        ||             jt        |t        t        t        j                  f      s||j                  |       t        |t        j0                        r|j                  t3        |             t)        d| d       |S )	z)Recursively convert fx args to torch argsvalget_attrz:Unexpected input argument type found inside fx.Node. arg: z; arg.meta['val']/get_attr: z"; type(arg.meta['val']/get_attr): .z@Unexpected input argument type is found in node arguments. arg: z; )r;   r<   fxNodemetagetr   getattrr   r=   r   rf   r@   rc   intfloatr   r   rb   rd   r(   typer   _fx_args_to_torch_argsdevicestr)rK   rM   wrapped_argsargfake_tensorreal_tensors         r   r   r      s   
 24Lc588==)((,,u-K"svv';%oszzB +u||45%%{'8'8 ##K0K#ud);<##K0 ))+6##O$<$<[$IJ PQTPU V11<=_K(), 
 X& 6sO LMc5%++673;$U\\*C)RSVRWWYZ = D r!   c                "    t        | |      }||fS )zvPrepare torch format args and kwargs for op-level validation by using fake tensor to create real tensor to feed in ops)r   )rK   rL   rM   rN   s       r   r'   r'     s!     0F0J y  r!   c                   | D ch c]  }|j                    }}t        |      j                  |      }|r|st        d| d      g }i }t	        |       D ]  \  }	}|j
                  r|j                  d ||	d D               g }1|	t        |      k  r\|j                  st        ||	   t        j                        r|j                  t        ||	                |j                  ||	          |j                   |v rO|j                  r&t        ||j                            ||j                   <   ||j                      ||j                   <   |j                  st        d| d       ||fS c c}w )a  Convert Python args and kwargs to OnnxFunction acceptable with matching ONNX ParamSchema.

    NOTE: This is different from the param_schema separating in dispatcher, since at this point
    we are already sure that the args and kwargs are in order and matched.

    Args:
        param_schemas: The parameter schemas of an Op or a OnnxFunction.
        args: The Python positional arguments supplied by the caller.
        kwargs: The Python keyword arguments supplied by the caller.
        allow_extra_kwargs: Whether to allow extra keyword arguments.
            When set to True, extra/unknown arguments will be ignored.

    Returns:
        A tuple of two elements:
        - A list of Python positional argument.
        - An ordered dictionary of Python keyword argument names and its values.

    Raises:
        TypeError: When allow_extra_kwargs is False and there are unknown kwargs.
        TypeError: When a required input is not provided.
    zUnexpected keyword arguments ''c              3      K   | ]  }|  y w)N ).0r   s     r   	<genexpr>z;_convert_torch_args_to_onnxfunction_args.<locals>.<genexpr>W  s     7hsshs   NzRequired input/attribute 'z' was not provided)r   set
differencer7   	enumerateis_variadic_inputextendr9   is_inputr;   r<   r@   rc   _convert_tensor_to_numpyrequired)
r5   r   r   r$   paramall_param_namesextra_kwargstagged_argstagged_kwargsis
             r   r4   r4   -  sU   > 0==}euzz}O=v;))/:L.8aHIIK$&Mm,5""7d12h77Ds4y=~~DGU[[!A""#;DG#DE""47+ZZ6!~~,DVEJJEW,Xejj),25::,>ejj)^^8?QRSS# -& %%7 >s   E0c                   	 dd l }t        | t        j
                        rdt	        j                  |       r#t	        j                  | j                               } | j                         j                         j                         S t        | t        j                        r6t        t        j                  j                  |       j!                               S t        | t"        t$        f      rt'        |       dk(  r|j)                  d|j*                        S t        | d   t        j
                        r| D cg c]  }t-        |       c}S t        | d   t.              r|j)                  | |j0                        S t        | d   t              r|j)                  | |j*                        S t        | d   t2              r|j)                  |       S | S # t        $ r}t        t         d      |d }~ww xY wc c}w )Nr   z% needs numpy, but it's not installed.r   ro   )numpyImportError__name__r;   r<   r=   
is_complexrA   rB   detachrH   r@   r   jit_type_utilsJitScalarType
from_dtype	onnx_typetuplelistr9   arrayr}   r   r   bool_r   )inputnpexcxs       r   r   r   j  s   W %&E"&&u'9'9';<E||~!!#))++%%>//::5AKKMNN%%'u:?88Bbhh8//eAh-9>?A,Q/??eAh%88E822 eAh$88E822eAh&88E?"L/  WXJ&KLMSVVW @s   G 6G5	G2G--G2)r   r   r   torch.fx.Noder   =Union[onnxscript.OnnxFunction, onnxscript.TracedOnnxFunction]returnr   )rJ   zdiagnostics.DiagnosticContextr   r   r   r   rK   List[fx_type_utils.Argument]rL   !Dict[str, fx_type_utils.Argument]rM   torch.fx.GraphModule)rf   
torch.Sizer   r   )rf   r   r@   ztorch.dtype)rK   r   rM   r   r   r   )rK   r   rL   r   rM   r   r   zFTuple[List[fx_type_utils.Argument], Dict[str, fx_type_utils.Argument]])F)
r5   z'Sequence[onnxscript.values.ParamSchema]r   r   r   r   r$   r   r   z Tuple[List[Any], Dict[str, Any]])r   zfx_type_utils.Argumentr   r   )+__doc__
__future__r   r+   typingr   r   r   r   r   r	   r
   rC   r   r<   torch.fxtorch.fx.experimentalr   
torch.onnxr   r   r   torch.onnx._internalr   torch.onnx._internal.fxr   r   r   r>   torch.utilsr   beartyper    diagnose_callrulesop_level_debuggingr_   ri   r   r   r'   r4   r   r   r!   r   <module>r      s   ? "  D D D      1 @ * 
     O	 	  ((!BA>5A>
A> OA> *	A>
 1A> *A>	 
A>H & &4 !+ !+H ')'<P'!' 'T !)!0! *! L	! ! 
  %	9&:9&
&9& .9& 	9&
 '9& 9&x  r!   