o
    toiZ(                     @  s"  d dl m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 d dlmZmZmZmZmZ d dlmZ d dlmZmZ ed	d
 e D dd dZedd
 e D dd dZedd
 e D dd dZd%ddZ	d&d'd d!ZG d"d# d#ejZ e!d$kre"  dS dS )(    )annotationsN)TensorProto	TypeProto)ValidationError)OpSchemaget_all_schemas_with_history
get_schema)
make_graph	make_nodemake_opsetidmake_tensor_type_protomake_tensor_value_info
from_array)InferenceErrorinfer_node_outputsc                 c  (    | ]}|j d kr|jdkr|V  qdS )Add Nnamedomain.0s r   U/home/ubuntu/.local/lib/python3.10/site-packages/onnx/test/inference_function_test.py	<genexpr>      & r   c                 C     | j S Nsince_versionr   r   r   r   <lambda>       r$   )keyc                 c  r   )Reshaper   Nr   r   r   r   r   r      s    c                 C  r   r    r!   r#   r   r   r   r$   "   r%   c                 c  r   )Clipr   Nr   r   r   r   r   r   %   r   c                 C  r   r    r!   r#   r   r   r   r$   &   r%   tensor_types3dict[str, tuple[int, tuple[int | str | None, ...]]]returndict[str, TypeProto]c                 C  s   dd |   D S )Nc                 S  s   i | ]	\}}|t | qS r   )r   )r   r&   valuer   r   r   
<dictcomp>-       z$_to_tensor_types.<locals>.<dictcomp>)items)r)   r   r   r   _to_tensor_types*   s   r1   schemar   input_names	list[str]output_namesinput_types
input_datadict[str, np.ndarray] | Nonec                 C  s8   |d u ri }t | t| j||| jd|dd | D S )N)r   c                 S  s   i | ]	\}}|t |qS r   r   )r   r&   arrr   r   r   r.   =   r/   z_run_case.<locals>.<dictcomp>)r   r
   r   r   r0   )r2   r3   r5   r6   r7   r   r   r   	_run_case0   s   r:   c                   @  sR   e Zd ZdddZdddZdddZdd	d
ZdddZdddZdddZ	dS )TestInferenceFunctionCallr+   Nonec                 C  s   t jdft jdfddt jdfift jdft jdfddt jdfift jdft jdfddt jdfift jdft jdfddt jdfift jd	ft jd
fddt jdfifg}|D ]\}}ttddgdgt|t|ksoJ qYd S )Nr   ABC)N   )rA   )   rA   )nm)rB   rC   rD   )xrA   )yrA   r>   r?   )r   FLOATDOUBLEr:   
ADD_SCHEMAr1   )selfcasesinsoutsr   r   r   test_add_inferenceB   sD   			"
z,TestInferenceFunctionCall.test_add_inferencec                 C  sT   g d}dg}t tjdftjdfd}t dtjdfi}tt||||ks(J d S )N)Xr   maxY      r   )rO   rP   )r1   r   rG   r:   CLIP_SCHEMA)rJ   r3   r5   r6   expected_output_typesr   r   r   'test_clip_inference_with_optional_inputm   s   zATestInferenceFunctionCall.test_clip_inference_with_optional_inputc              	   C  s>  |  t ttdgdgtdtjdfi W d    n1 s w   Y  |  t ttddgdgttjdfdd W d    n1 sGw   Y  |  t ttddgdgttjdftjdfd W d    n1 sqw   Y  |  t ttddgdgtdtjdfi W d    d S 1 sw   Y  d S )Nr>   r@   rR   r?   )rA   rR   r=   )rA   rT   )	assertRaisesr   r:   rI   r1   r   rG   r   KeyErrorrJ   r   r   r    test_add_inference_raises_errorsz   sH   "z:TestInferenceFunctionCall.test_add_inference_raises_errorsc              
   C  sZ   t tddgdgttjdftjdfddtjg dtjditdtjdfiks+J d S )	NrE   trF   )   rT   )rS   )rE   r\   )rA   rA   r]   )dtype)	r:   RESHAPE_SCHEMAr1   r   rG   INT64nparrayint64rZ   r   r   r   test_reshape_inference   s   z0TestInferenceFunctionCall.test_reshape_inferencec              	   C  s  d}d}d}t dtjd t dtjd t dtjd g}t dtjd t dtj||fg}ttd	dgdgtd
ddgdggd||}ttddtdg dddgd|dttj|fftj||fftj|ffdt	ddgddttj|fftj||ffdksJ d S )NsequencerA   rS   loop_state_ininputouterloop_state_outoutputIdentityr   subgraphScan	   )loop_state_orig
scan_input
scan_outerloop_state_finalscan_outputrB   )num_scan_inputsbodyr   rT   )opset_imports
ir_version)rr   rs   )
r   r   	UNDEFINEDrG   r	   r
   r   r   r1   r   )rJ   seq_len
input_sizeloop_state_sizeinput_value_infosoutput_value_infosrl   r   r   r   !test_scan_inference_with_subgraph   sT   




z;TestInferenceFunctionCall.test_scan_inference_with_subgraphc                 C  sd   d}t j|}t jj|dd | t jj t jj|dd W d    d S 1 s+w   Y  d S )Na  
        <
            ir_version: 8,
            opset_import: ["" : 18, "onnxscript.atenlib" : 1],
            producer_name: "pytorch",
            producer_version: "2.1.0"
        >
        torch_jit (float input_0) => (float reault, int64 index)
        {
            reault, index = onnxscript.atenlib.aten_min_dim <dim = 0, keepdim = 1> (input_0)
        }
        <
            domain: "onnxscript.atenlib",
            opset_import: ["" : 18]
        >
        aten_min_dim <dim>(self) => (result_7, indices_6)
        {
            tmp = Shape (self)
            tmp_0 = Size (tmp)
            tmp_1 = Constant <value = int64 tmp_1 {0}> ()
            tmp_1_cast = CastLike (tmp_1, tmp_0)
            tmp_2 = Equal (tmp_0, tmp_1_cast)
            cond = Not (tmp_2)
            indices_6, result_7 = If (cond) <
                then_branch = thenGraph_4 () => ( indices,  result) {
                    dim = Constant <value_int: int = @dim> ()
                    tmp_3 = Constant <value_ints = [-1]> ()
                    dims = Reshape (dim, tmp_3)
                    result = ReduceMin <keepdims: int = @keepdim> (self, dims)
                    indices = ArgMin <axis: int = @dim, keepdims: int = @keepdim> (self)
                }, else_branch = elseGraph_4 () => ( indices_4,  result_5) {
                    indices_4 = Constant <value_int = 0> ()
                    result_5 = Identity (self)
                }
            >
        }
        Fstrict_modeT)onnxparserparse_modelshape_inferenceinfer_shapesrX   r   rJ   model_scriptmodelr   r   r   test_inference_with_conflow   s   %"z5TestInferenceFunctionCall.test_inference_with_conflowc                 C  s$   d}t j|}t jj|dd d S )Na  
        <
            ir_version: 8,
            opset_import: ["" : 18, "custom" : 1],
            producer_name: "",
            producer_version: "1.0"
        >
        MeanVarianceNormalization (float[N] x) => (float[M] y)
        {
            y = custom.custom_mvn <axes = [0]> (x)
        }
        <
            domain: "custom",
            opset_import: ["" : 18]
        >
        custom_mvn <axes>(X) => (Y)
        {
          Exponent = Constant <value = float {2.0}>()
          Epsilon = Constant <value = float {1e-9}>()
          axes = Constant <value_ints: ints = @axes>()
          X_RM = ReduceMean (X, axes)
          EX_squared = Pow (X_RM, Exponent)
          X_squared = Pow (X, Exponent)
          E_Xsquared = ReduceMean (X_squared, axes)
          Variance = Sub (E_Xsquared, EX_squared)
          STD = Sqrt (Variance)
          X_variance = Sub (X, X_RM)
          Processed_STD = Add (STD, Epsilon)
          Y = Div (X_variance, Processed_STD)
        }
        Tr   )r   r   r   r   r   r   r   r   r   test_inference_with_attribute	  s   z7TestInferenceFunctionCall.test_inference_with_attributeN)r+   r<   )
__name__
__module____qualname__rN   rW   r[   rd   r~   r   r   r   r   r   r   r;   A   s    

+

#

3+r;   __main__)r)   r*   r+   r,   r    )r2   r   r3   r4   r5   r4   r6   r,   r7   r8   r+   r,   )#
__future__r   unittestnumpyra   r   r   r   onnx.checkerr   	onnx.defsr   r   r   onnx.helperr	   r
   r   r   r   onnx.numpy_helperr   onnx.shape_inferencer   r   rP   rI   r_   rU   r1   r:   TestCaser;   r   mainr   r   r   r   <module>   s@   
 n