U
    qh(                     @  s2  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ddZd dddddddddZG dd dejZ e!dkr.e"  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  s&   | ]}|j d kr|jdkr|V  qdS )Add Nnamedomain.0s r   E/tmp/pip-unpacked-wheel-xnis5xre/onnx/test/inference_function_test.py	<genexpr>   s     
 
 r   c                 C  s   | j S NZsince_versionr   r   r   r   <lambda>       r    )keyc                 c  s&   | ]}|j d kr|jdkr|V  qdS )ZReshaper   Nr   r   r   r   r   r      s   
 
c                 C  s   | j S r   r   r   r   r   r   r    "   r!   c                 c  s&   | ]}|j d kr|jdkr|V  qdS )ZClipr   Nr   r   r   r   r   r   %   s     
 
 c                 C  s   | j S r   r   r   r   r   r   r    &   r!   z3dict[str, tuple[int, tuple[int | str | None, ...]]]zdict[str, TypeProto])tensor_typesreturnc                 C  s   dd |   D S )Nc                 S  s   i | ]\}}|t | qS r   )r   )r   r"   valuer   r   r   
<dictcomp>-   s      z$_to_tensor_types.<locals>.<dictcomp>)items)r#   r   r   r   _to_tensor_types*   s    r(   r   z	list[str]zdict[str, np.ndarray] | None)schemainput_namesoutput_namesinput_types
input_datar$   c                 C  s8   |d kri }t | t| j||| jd|dd | D S )N)r   c                 S  s   i | ]\}}|t |qS r   r   )r   r"   Zarrr   r   r   r&   =   s      z_run_case.<locals>.<dictcomp>)r   r
   r   r   r'   )r)   r*   r+   r,   r-   r   r   r   	_run_case0   s    r.   c                   @  sn   e Zd ZddddZddddZddddZddd	d
ZddddZddddZddddZ	dS )TestInferenceFunctionCallNone)r$   c                 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stqd S )Nr   ABC)N   )r5   )   r5   )nm)r6   r7   r8   )xr5   )yr5   r2   r3   )r   FLOATZDOUBLEr.   
ADD_SCHEMAr(   AssertionError)selfZcasesZinsZoutsr   r   r   test_add_inferenceB   s4    			"z,TestInferenceFunctionCall.test_add_inferencec                 C  sV   dddg}dg}t tjdftjdfd}t dtjdfi}tt||||ksRtd S )NXr   maxY      r   )r@   rA   )r(   r   r;   r.   CLIP_SCHEMAr=   )r>   r*   r+   r,   Zexpected_output_typesr   r   r   'test_clip_inference_with_optional_inputh   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 5 Q R X |  t* ttddgdgttjdfdd W 5 Q R X |  t0 ttddgdgttjdftjdfd W 5 Q R X |  t( ttddgdgtdtjdfi W 5 Q R X d S )Nr2   r4   rC   r3   )r5   rC   r1   )r5   rE   )	assertRaisesr   r.   r<   r(   r   r;   r   KeyErrorr>   r   r   r    test_add_inference_raises_errorsu   s@    z:TestInferenceFunctionCall.test_add_inference_raises_errorsc              
   C  s\   t tddgdgttjdftjdfddtjdddgtjd	itdtjd
fiksXt	d S )Nr9   tr:   )   rE   )rD   )r9   rL   r5   rM   )Zdtype)r5   r5   rM   )
r.   RESHAPE_SCHEMAr(   r   r;   ZINT64nparrayZint64r=   rJ   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dddg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st
d S )Nsequencer5   rD   Zloop_state_ininputouterZloop_state_outoutputZIdentityr   subgraphZScan	   loop_state_orig
scan_input
scan_outerloop_state_finalscan_outputr6   )Znum_scan_inputsbody)rX   rY   rZ   r   rE   )Zopset_importsZ
ir_version)r[   r\   )r   r   	UNDEFINEDr;   r	   r
   r   r   r(   r   r=   )r>   Zseq_lenZ
input_sizeZloop_state_sizeZinput_value_infosZoutput_value_infosrV   r   r   r   !test_scan_inference_with_subgraph   sT    




z;TestInferenceFunctionCall.test_scan_inference_with_subgraphc              	   C  sN   d}t j|}t jj|dd | t jj t jj|dd W 5 Q R X 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Zstrict_modeT)onnxparserparse_modelshape_inferenceinfer_shapesrH   r   r>   Z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`   )ra   rb   rc   rd   re   rf   r   r   r   test_inference_with_attribute  s    z7TestInferenceFunctionCall.test_inference_with_attributeN)
__name__
__module____qualname__r?   rG   rK   rQ   r_   rh   ri   r   r   r   r   r/   A   s   &#3+r/   __main__)N)#
__future__r   ZunittestZnumpyrO   ra   r   r   Zonnx.checkerr   Z	onnx.defsr   r   r   Zonnx.helperr	   r
   r   r   r   Zonnx.numpy_helperr   Zonnx.shape_inferencer   r   rA   r<   rN   rF   r(   r.   ZTestCaser/   rj   mainr   r   r   r   <module>   s<     i
