U
    qh                     @  s  U d dl mZ d dlZd dlZd dlZd dlmZ d dlm	Z	m
Z
mZmZmZmZmZmZmZmZ d dlZd dlZd dlmZ d dlmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- eee.e/e/e/f ee.e/e/e/e/f f Z0ee0 Z1eee.e.f  Z2dddd	d
dddddddddddddddddddgZ3de4d< eee.e/f e/f Z5dd d!d"d#Z6e6e3Z7dd%d&d'd(d)d*Z8dd+d,d,d-d-d-d-d.d/d0	d1d2Z9d+d'd3d4d5d6Z:dd7d+d8d8d9d-d:d;d<d=	d>d?Z;d+d'd3d4d@dAZ<dd+d+d,d,d7d%dBdCd-d-d:dDdEdFdGZ=d<d.dHdIdJdKZ>d<d.dHdIdLdMZ?dNdOdPdQdRdSZ@dHdOdPdTdUdVZAdWdXdYdZd[ZBdd\d&d'd]d^d_ZCdd\d\d&d&d&d'dbdcddZDdd\d\d&d&d&d'dbdedfZEdgd&dhdidjdkZFdd+d'dXd.d&dldmdndoZGdldldXdpdqdrdsZHd+dtdudvdwdxdyZId+d'dzdvd{d|d}d~ZJd+ddddddZKdddddZLdd+d.d-dddddZMdd+dd-ddddZNdd.dddZOd/d+d.dddZPd+ddddZQdd'ddddddZRdd+d'dd+dddddZSdd'ddddddZTd d+d'dd+dddddZUdddddZVdddddZWd'dddddZXdd+dd+ddddZYdd+dddZZdd+d'dd+dddddZ[ddd&ddddZ\dd+dddÄZ]dd+dĜddƄZ^dd+dǜddɄZ_dld+dĜdd˄Z`dd/d+d&dd̜dd΄Zadd<d+d+dϜddфZbddPdӜddՄZcd<dddddڜdd܄Zdd'ddޜddZed'd'dޜddZfd'd+dޜddZgd'd+dޜddZhdd'dddZiddddZjdd ejkl D Zmd'd+dddZndS (      )annotationsN)isnan)
AnyCallableDictKeysViewListSequenceTupleTypeVarUnioncast)
IR_VERSIONAttributeProtoFunctionProto
GraphProtoMapProto
ModelProto	NodeProtoOperatorSetIdProtoOptionalProtoSequenceProtoSparseTensorProtoTensorProtoTensorShapeProtoTrainingInfoProto	TypeProtoValueInfoProtodefsmappingsubbyte)z1.0      r"   )z1.1r!      r"   )z1.1.2r!      r"   )z1.2r!      r"   )z1.3r!      r"   )z1.4.1   	   r"   )z1.5.0r#   
   r"   )z1.6.0r$         )z1.7.0r%      r+   r"   )z1.8.0r%      r+   r"   )z1.8.1r%   r-   r+   r"   )z1.9.0r%      r+   r"   )z1.10.0r&      r+   r"   )z1.10.1r&   r/   r+   r"   )z1.10.2r&   r/   r+   r"   )z1.11.0r&      r!   r"   )z1.12.0r&      r!   r"   )z1.13.0r&      r!   r"   )z1.13.1r&   r2   r!   r"   )z1.14.0r(      r!   r"   )z1.14.1r(   r3   r!   r"   )z1.15.0r(      r'   r"   )z1.16.0r)      r#   r"   )z1.17.0r)      r#   r"   VersionTableTypeVERSION_TABLEVersionMapType)tablereturnc                   s2   i  ddddd fdd}| D ]}||  q  S )zOCreate a map from (opset-domain, opset-version) to ir-version from above table.strintr   None)release_version
ir_versionargsr;   c                   sH   ~ t dddg|D ]0}| kr| |< |d dkr| d|d f< qd S )Nai.onnxz
ai.onnx.mlzai.onnx.trainingr   zai.onnx.preview.trainingr"   )zip)r?   r@   rA   pairresult //tmp/pip-unpacked-wheel-xnis5xre/onnx/helper.pyprocessZ   s    z-create_op_set_id_version_map.<locals>.processrG   )r:   rI   rowrG   rE   rH   create_op_set_id_version_mapV   s
    
rK   FzSequence[OperatorSetIdProto]boolr=   )opsetidlistignore_unknownr;   c                   s:   d dddd fdd| r6t fdd| D S  S )	a=  Given list of opset ids, determine minimum IR version required.

    Args:
        opsetidlist: A sequence of OperatorSetIdProto.
        ignore_unknown: If True, ignore unknown domain and return default minimum
            version for that domain.

    Returns:
        The minimum IR version required (integer)
    r!   
str | Noner=   domainversionr;   c                   s0   | pd|f}|t krt | S r$ S tdd S )NrB   zUnsupported opset-version.)OP_SET_ID_VERSION_MAP
ValueError)rQ   rR   key)default_min_versionrN   rG   rH   find_miny   s    z)find_min_ir_version_for.<locals>.find_minc                 3  s   | ]} |j |jV  qd S N)rQ   rR   .0x)rW   rG   rH   	<genexpr>   s     z*find_min_ir_version_for.<locals>.<genexpr>)max)rM   rN   rG   )rV   rW   rN   rH   find_min_ir_version_forj   s
    r^   r<   zSequence[str]rO   r   r   )	op_typeinputsoutputsname
doc_stringrQ   overloadkwargsr;   c           	      K  sz   t  }| |_|j| |j| |r.||_|r8||_|dk	rF||_|dk	rT||_|rv|j	dd t
| D  |S )a  Construct a NodeProto.

    Args:
        op_type (string): The name of the operator to construct
        inputs (list of string): list of input names
        outputs (list of string): list of output names
        name (string, default None): optional unique identifier for NodeProto
        doc_string (string, default None): optional documentation string for NodeProto
        domain (string, default None): optional domain for NodeProto.
            If it's None, we will just use default domain (which is empty)
        overload (string, default None): optional field, used to
            resolve calls to model-local functions
        **kwargs (dict): the attributes of the node.  The acceptable values
            are documented in :func:`make_attribute`.

    Returns:
        NodeProto
    Nc                 s  s$   | ]\}}|d k	rt ||V  qd S rX   )make_attribute)rZ   rU   valuerG   rG   rH   r\      s   zmake_node.<locals>.<genexpr>)r   r_   inputextendoutputrb   rc   rQ   rd   	attributesorteditems)	r_   r`   ra   rb   rc   rQ   rd   re   noderG   rG   rH   	make_node   s"    
ro   r   rP   c                 C  s   t  }| |_||_|S zConstruct an OperatorSetIdProto.

    Args:
        domain (string): The domain of the operator set id
        version (integer): Version of operator set id
    Returns:
        OperatorSetIdProto
    r   rQ   rR   )rQ   rR   ZoperatorsetidrG   rG   rH   make_operatorsetid   s    rr   zSequence[NodeProto]zSequence[ValueInfoProto]zSequence[TensorProto] | NonezSequence[ValueInfoProto] | Nonez"Sequence[SparseTensorProto] | Noner   )	nodesrb   r`   ra   initializerrc   
value_infosparse_initializerr;   c           	      C  s   |dkrg }|dkrg }|dkr$g }t  }|j|  ||_|j| |j| |j| |j| |j| |r||_	|S )a  Construct a GraphProto

    Args:
        nodes: list of NodeProto
        name (string): graph name
        inputs: list of ValueInfoProto
        outputs: list of ValueInfoProto
        initializer: list of TensorProto
        doc_string (string): graph documentation
        value_info: list of ValueInfoProto
        sparse_initializer: list of SparseTensorProto
    Returns:
        GraphProto
    N)
r   rn   ri   rb   rh   rj   rt   rv   ru   rc   )	rs   rb   r`   ra   rt   rc   ru   rv   graphrG   rG   rH   
make_graph   s"    rx   c                 C  s   t  }| |_||_|S rp   rq   )rQ   rR   ZopsetidrG   rG   rH   make_opsetid   s    	ry   zSequence[str] | NonezSequence[AttributeProto] | Noner   )rQ   fnamer`   ra   rs   opset_imports
attributesattribute_protosrc   rd   ru   r;   c                 C  s   |d krg }|d krg }|
d kr$g }
t  }| |_||_|j| |j| |j| |j| |j| |j	| |r||_
|	d k	r|	|_|j|
 |S rX   )r   rQ   rb   rh   ri   rj   rn   opset_importrk   Zattribute_protorc   rd   ru   )rQ   rz   r`   ra   rs   r{   r|   r}   rc   rd   ru   frG   rG   rH   make_function  s*    r   r   )rw   re   r;   c                 K  s   t  }t|_|j|  d}|dd}|dk	r>|j| n|j }t	
 |_d}|dd}|dk	rv|j| | D ]\}}t||| q~|S )zConstruct a ModelProto

    Args:
        graph (GraphProto): *make_graph* returns
        **kwargs: any attribute to add to the returned instance
    Returns:
        ModelProto
    Nr{   	functions)r   r   r@   rw   CopyFrompopr~   ri   addr   Zonnx_opset_versionrR   r   rm   setattr)rw   re   modelr{   impr   kvrG   rG   rH   
make_model'  s     	

r   c                 K  s4   d}||kr(d}| |g }t|||< t| f|S )Nr@   r{   )getr^   r   )rw   re   Zir_version_fieldZopset_imports_fieldZimportsrG   rG   rH   make_model_gen_versionL  s    r   zRModelProto | GraphProto | FunctionProto | NodeProto | TensorProto | ValueInfoProtozdict[str, str]r>   )proto
dict_valuer;   c                 C  s8   | j d d = | D ]\}}| j  }||_||_qd S rX   )Zmetadata_propsrm   r   rU   rg   )r   r   r   r   entryrG   rG   rH   set_metadata_propsU  s
    
r   )r   r   r;   c                 C  s   t | | d S rX   )r   )r   r   rG   rG   rH   set_model_propsg  s    r   zSequence[np.complex64]zSequence[int])car;   c                   s    fddt t d D S )Nc                   s4   g | ],}|d  dkr" |d   j n |d   jqS )r+   r   )realimagrZ   ir   rG   rH   
<listcomp>l  s   z*split_complex_to_pairs.<locals>.<listcomp>r+   )rangelenr   rG   r   rH   split_complex_to_pairsk  s    
r   float)fvaltruncater;   c                 C  sH   t td| d}|r |d? S t| r,dS |d? d@ d }|| d? S )N<flittler0   i  r"   i  )r=   
from_bytesstructpackr   )r   r   ZivalZroundedrG   rG   rH   float32_to_bfloat16x  s    r         ?T)r   scalefnuzsaturater;   c                 C  s  |st d| | }ttdt|d}|d@ d? }|r|d@ dkrPdS t|rj|rf|dB S dS |d	@ d
? }|d@ }	|dk rd}nX|dk rF|d }
|
dkr|dd|
 > O }||	d|
 ? O }n|	dkr|dO }nd}dd|
 > }|	|@ r|d@ s<|	|d @ dks<|	|@ r|	|d> @ r|	|d @ dkr|d7 }n|dk r|d }
|
dkrx|dO }||	d? O }n||
d> O }||	d? O }|	d@ r|	d@ s|	d@ r|d@ dk r|d7 }n
|sdS n|r|dO }nd}t|S |d@ dkrd|B S t|r&|r|dB S d|B S |d	@ d
? }|d@ }	|dkr|dk rRnt|dk r|d }
|
dkr|dd|
 > O }||	d|
 ? O }n|	dkr|dO }dd|
 > }|	|@ r|d@ s|	|d @ dks|	|@ r|	|d> @ r|	|d @ dkr|d7 }n|dk r|d }
|
dkr:|dO }||	d? O }n.||
d> O }||	d? O }|d@ dkrh|dM }|	d@ r|	d@ s|	d@ r|d@ dk r|d7 }n|s|dO }n|r|dO }n|dO }t|S d S )!a  Convert a float32 value to a float8, e4m3 (as int).

    See :ref:`onnx-detail-float8` for technical details.

    Args:
        fval: float to convert
        scale: scale, divide *fval* by *scale* before casting it
        fn: no infinite values
        uz: no negative zero
        saturate: if True, any value out of range included inf becomes
            the maximum value, otherwise, it becomes NaN. The
            description of operator Cast fully describes the
            differences.

    Returns:
        converted float
    z4float32_to_float8e4m3 not implemented with fn=False.r   r                            t   r   x   w   r"   r+   r5   r4      r'   r!   i      i ~   u   y         N)NotImplementedErrorr=   r   r   r   npfloat32isinfr   r   r   r   r   r[   bretemexmaskrG   rG   rH   float32_to_float8e4m3  s    






















r   c                 C  s  | | }t tdt|d}|d@ d? }|r|r|d@ dkrJdS |d@ dkrf|rb|d	B S dS |d@ d
? }|d@ }	|dk rd}nR|dk rB|d }
|
dkr|dd|
 > O }||	d|
 ? O }n|	dkr|dO }nd}dd|
 > }|	|@ r|d@ s8|	|d @ dks8|	|@ r|	|d> @ r|	|d @ dkr|d7 }n|dk r|d }
||
d> O }||	d? O }|	d@ r|	d@ s|	d@ r|d	@ d	k r|d7 }n
|sd}n.|dkr|	dkrd}n|r|d	O }nd}t |S |s|s|d@ dkrd	|B S t|r(|r d|B S d|B S |d@ d
? }|d@ }	|dkr|dk rTnH|dk r
|d }
|
dkr|dd|
 > O }||	d|
 ? O }n|	dkr|dO }dd|
 > }|	|@ r|d@ s |	|d @ dks |	|@ r|	|d> @ r|	|d @ dkr|d7 }n|dk r|d }
||
d> O }||	d? O }|	d@ r|	d@ sR|	d@ r|d	@ dk rj|d7 }n|rz|dO }n|dO }n|r|dO }n|dO }t |S tddS ) a  Convert a float32 value to a float8, e5m2 (as int).

    Args:
        fval: float to convert
        scale: scale, divide *fval* by *scale* before casting it
        fn: no infinite values
        uz: no negative zero
        saturate: if True, any value out of range included inf becomes
            the maximum value, otherwise, it becomes NaN. The
            description of operator Cast fully describes the
            differences.

    Returns:
        converted float
    r   r   r   r   r   r   ir   r   r   r   m   r   p   o   r"   r6   r5      r+   r   i i       {   |   n   q   z%fn and uz must be both False or True.N)r=   r   r   r   r   r   r   r   r   rG   rG   rH   float32_to_float8e5m2  s    




















r   znp.ndarray | Sequencez
np.ndarray)arraysignedr;   c                   s   t | tjstj| tjd} |  }t| jd dk}|rPt|t	dg} fdd}t
|dd}||ddd |ddd }|tjS )ax  Convert an array of float32 value to a 4bit data-type and pack every two concecutive elements in a byte.
    See :ref:`onnx-detail-int4` for technical details.

    Args:
        array: array of float to convert and pack
        signed: Whether the 4 bit variant is signed or unsigned

    Returns:
        Packed array with size `ceil(farray.size/2)` (single dimension).
    Zdtyper+   r"   r   c                   s   t | | S rX   )r    Zfloat32x2_to_4bitx2)r[   yr   rG   rH   <lambda>      z&pack_float32_to_4bit.<locals>.<lambda>N)
isinstancer   ndarrayZasarrayr   Zravelprodshapeappendr   Z
frompyfuncastypeZuint8)r   r   Z
array_flatZis_odd_volumeZsingle_funcfuncZarrrG   r   rH   pack_float32_to_4bit  s    r   r   )rb   	data_typedimsvalsrawr;   c                 C  s`  t  }||_| |_|t jkr(|r(tdt|}d}|r|t jkrHd}n:|t jt jt j	t j
fkrfd}n|t jt jfkr|d}n|j}t|tjkrt|jdkr| }|D ]}||9 }qt||kr|t jt jfkrt||d kstd| dt| d|r||_nB|t jt jfkr,t|}n|t jkr\t||jtjd  }n|t jt jt jt j	t j
fkrt jtt jt t jd	d
 t j	t!t j
dd
 i| }	t"t#|	t||  }nl|t jt jfkr|t jk}
t$||
d  }n:|t j%krt|t&}n|t jkr8t|t'}t(|}t)||*| |j+*| |S )a  Make a TensorProto with specified arguments.  If raw is False, this
    function will choose the corresponding proto field to store the
    values based on data_type. If raw is True, use "raw_data" proto
    field to store the values, and values should be of type bytes in
    this case.

    Args:
        name (string): tensor name
        data_type (int): a value such as onnx.TensorProto.FLOAT
        dims (List[int]): shape
        vals: values
        raw (bool): if True, vals contains the serialized content of the tensor,
            otherwise, vals should be a list of values of the type defined by *data_type*

    Returns:
        TensorProto
    z*Can not use raw_data to store string type.r"   r+   g      ?z8Number of values does not match tensor's size. Expected z, but it is z. r   c                  W  s   t | ddiS )Nr   T)r   rA   rG   rG   rH   r     s   zmake_tensor.<locals>.<lambda>c                  W  s   t | dddS )NT)r   r   )r   r   rG   rG   rH   r     s     r   ),r   r   rb   STRING	TypeErrortensor_dtype_to_np_dtypeZBFLOAT16ZFLOAT8E4M3FNZFLOAT8E4M3FNUZZ
FLOAT8E5M2ZFLOAT8E5M2FNUZZUINT4ZINT4itemsizetyper   r   r   r   flattenrT   raw_dataZ	COMPLEX64Z
COMPLEX128r   ZFLOAT16r   r   viewZuint16tolistr   r   r   listmapr   ZBOOLr=   bytestensor_dtype_to_fieldgetattrri   r   )rb   r   r   r   r   Ztensornp_dtypeZexpected_sizedZfcastr   fieldrG   rG   rH   make_tensor  s    


      
r   r   )valuesindicesr   r;   c                 C  s.   t  }|j|  |j| |j| |S )zConstruct a SparseTensorProto

    Args:
        values (TensorProto): the values
        indices (TensorProto): the indices
        dims: the shape

    Returns:
        SparseTensorProto
    )r   r   r   r   r   ri   )r   r   r   sparserG   rG   rH   make_sparse_tensor  s
    r   zSequenceProto.DataTypezSequence[Any]r   )rb   	elem_typer   r;   c                 C  s   t  }| |_||_|t jkr |S |t jkr2|j}nP|t jkrD|j}n>|t jkrV|j	}n,|t j
krh|j}n|tjkrz|j}ntd|| |S )z/Make a Sequence with specified value arguments.z8The element type in the input sequence is not supported.)r   rb   r   	UNDEFINEDTENSORZtensor_valuesSPARSE_TENSORZsparse_tensor_valuesSEQUENCEZsequence_valuesMAPZ
map_valuesr   OPTIONALZoptional_valuesr   ri   )rb   r   r   sequencerk   rG   rG   rH   make_sequence/  s$    






r  z	list[Any]r   )rb   key_typekeysr   r;   c                 C  sr   t  }tjtjtjtjtjtjtjtj	g}| |_
||_|tjkrN|j| n||krb|j| |j| |S )zMake a Map with specified key-value pair arguments.

    Criteria for conversion:
    - Keys and Values must have the same number of elements
    - Every key in keys must be of the same type
    - Every value in values must be of the same type
    )r   r   ZINT8ZINT16ZINT32ZINT64ZUINT8ZUINT16ZUINT32ZUINT64rb   r  r   Zstring_keysri   r  r   r   )rb   r  r  r   Z	map_protoZvalid_key_int_typesrG   rG   rH   make_mapL  s$    


r	  zOptionalProto.DataTypez
Any | Noner   )rb   r   rg   r;   c                 C  s   t  }| |_||_|t jkr |S |t jkr2|j}nP|t jkrD|j}n>|t jkrV|j	}n,|t j
krh|j}n|t jkrz|j}ntd|| |S )z0Make an Optional with specified value arguments.z8The element type in the input optional is not supported.)r   rb   r   r   r   Ztensor_valuer  Zsparse_tensor_valuer  Zsequence_valuer  Z	map_valuer  Zoptional_valuer   r   )rb   r   rg   optionalrk   rG   rG   rH   make_optionalk  s$    






r  zstr | bytesr   )rg   r;   c                 C  s   t | tr| S | dS )z2Coerce a string (or bytes) value into UTF-8 bytes.utf-8)r   r   encode)rg   rG   rG   rH   	_to_bytes  s    r  z
int | Noner   )rU   rg   rc   	attr_typer;   c              
     s<  t  }| |_|r||_t|tjr8t||_t j|_	nt|tj
rZt||_t j|_	nt|ttfr~t||_t j|_	nvt|tr|j| t j|_	nTt|tr|j| t j|_	n2t|tr|j| t j|_	nt|tr|j| t j|_	nt|t j!j"rt#|}t$|dkrH|dkrHt%d|  d|dkrdd |D }tjt j&ftj
t j'fttft j(ftt j)ftt j*ftt j+ftt j,ffD ],\ }t- fdd|D r|} qҐq|dkrt%d	|t j&kr|j./| t j&|_	n|t j'kr(|j0/| t j'|_	n|t j(krT|j1/d
d |D  t j(|_	n|t j)krv|j2/| t j)|_	nl|t j*kr|j3/| t j*|_	nJ|t j+kr|j4/| t j+|_	n(|t j,kr|j5/| t j,|_	nt6 nt7d| d|dk	r8|j	|kr8t7dt8|j	 d|j	 dt8| d| d	|S )z0Makes an AttributeProto based on the value type.r   NzCould not infer attribute `z` type from empty iteratorc                 S  s   h | ]}t |qS rG   )r   rZ   r   rG   rG   rH   	<setcomp>  s     z!make_attribute.<locals>.<setcomp>c                 3  s   | ]}t | V  qd S rX   )
issubclassrZ   tZexp_trG   rH   r\     s     z!make_attribute.<locals>.<genexpr>zRCould not infer the attribute type from the elements of the passed Iterable value.c                 s  s   | ]}t |V  qd S rX   )r  r  rG   rG   rH   r\     s     'z%' is not an accepted attribute value.zInferred attribute type 'z'(z") mismatched with specified type '))9r   rb   rc   r   numbersIntegralr=   r   INTr   Realr   r   FLOATr<   r   r  sr   r   r  r   r   r   sparse_tensorr  r   gGRAPHr   tp
TYPE_PROTOcollectionsabcIterabler   r   rT   INTSFLOATSSTRINGSTENSORSSPARSE_TENSORSGRAPHSTYPE_PROTOSallintsri   floatsstringstensorssparse_tensorsgraphstype_protosAssertionErrorr   _attr_type_to_str)rU   rg   rc   r  attrtypesZexp_enumrG   r  rH   rf     s    









	








(rf   zAttributeProto.AttributeType)rb   r  rc   r;   c                 C  s    t  }| |_||_|r||_|S )zeMake an AttributeProto holding a reference to the parent function's attribute of given name and type.)r   rb   r   rc   )rb   r  rc   r7  rG   rG   rH   make_attribute_ref  s    r9  )r7  r;   c                 C  sV  | j rtd|  | jtjkr&| jS | jtjkr8| jS | jtjkrJ| j	S | jtj
kr\| jS | jtjkrn| jS | jtjkr| jS | jtjkr| jS | jtjkrt| jS | jtjkrt| jS | jtjkrt| jS | jtjkrt| jS | jtjkrt| jS | jtjkrt| jS | jtjkr2t| j S | jtj!krDd S td|  d S )Nz)Cannot get value of reference attribute: zUnsupported ONNX attribute: )"Zref_attr_namerT   r   r   r  r   r  r   r   r  r   r  r  r  r   r  r"  r!  r'  r   r/  r&  r.  r(  r0  r)  r1  r*  r2  r+  r3  r,  r4  r   )r7  rG   rG   rH   get_attribute_value  sB    






r:  )rn   	attr_namer;   c                   sT    fdd| j D }t|dkr.td  t|dk rHtd  t|d S )Nc                   s   g | ]}|j  kr|qS rG   rb   rY   r;  rG   rH   r     s     
 z'get_node_attr_value.<locals>.<listcomp>r"   z'Node has multiple attributes with name z Node has no attribute with name r   )rk   r   rT   r:  )rn   r;  ZmatchingrG   r=  rH   get_node_attr_value  s    r>  r   )rb   r;   c                 C  s   t  }| |_|S rX   )r   rb   )rb   value_info_protorG   rG   rH   make_empty_tensor_value_info$  s    r@  z!Sequence[str | int | None] | Nonezlist[str] | Noner   )r   r   shape_denotationr;   c           	      C  s   t  }|j}| |_|j}|dk	r|jg  |rHt|t|krHtdt|D ]^\}}|j	 }|dkrln4t
|tr~||_n"t
|tr||_ntd| d|rP|| |_qP|S )z:Makes a Tensor TypeProto based on the data type and shape.N>Invalid shape_denotation. Must be of the same length as shape.Invalid item in shape: z. Needs to be of int or str.)r   tensor_typer   r   dimri   r   rT   	enumerater   r   r=   	dim_valuer<   	dim_param
denotation)	r   r   rA  
type_prototensor_type_protoZtensor_shape_protor   r   rE  rG   rG   rH   make_tensor_type_proto*  s0    



rL   )rb   r   r   rc   rA  r;   c                 C  s2   t  }| |_|r||_t|||}|j| |S )z8Makes a ValueInfoProto based on the data type and shape.)r   rb   rc   rL  r   r   )rb   r   r   rc   rA  r?  rK  rG   rG   rH   make_tensor_value_infoW  s    rN  c           	      C  s   t  }|j}| |_|j}|dk	r|jg  |rHt|t|krHtdt|D ]^\}}|j	 }|dkrln4t
|tr~||_n"t
|tr||_ntd| d|rP|| |_qP|S )z@Makes a SparseTensor TypeProto based on the data type and shape.NrB  rC  z. Needs to be of int or text.)r   sparse_tensor_typer   r   rE  ri   r   rT   rF  r   r   r=   rG  r<   rH  rI  )	r   r   rA  rJ  sparse_tensor_type_protoZsparse_tensor_shape_protor   r   rE  rG   rG   rH   make_sparse_tensor_type_protoi  s0    



rQ  c                 C  s6   t  }| |_|r||_t|||}|jj|j |S )zEMakes a SparseTensor ValueInfoProto based on the data type and shape.)r   rb   rc   rQ  r   rO  r   )rb   r   r   rc   rA  r?  rP  rG   rG   rH   make_sparse_tensor_value_info  s      rR  )inner_type_protor;   c                 C  s   t  }|jj|  |S )zMakes a sequence TypeProto.)r   sequence_typer   r   rS  rJ  rG   rG   rH   make_sequence_type_proto  s    rV  c                 C  s   t  }|jj|  |S )zMakes an optional TypeProto.)r   Zoptional_typer   r   rU  rG   rG   rH   make_optional_type_proto  s    rW  )r  
value_typer;   c                 C  s    t  }| |j_|jj| |S )zMakes a map TypeProto.)r   Zmap_typer  rX  r   )r  rX  rJ  rG   rG   rH   make_map_type_proto  s    rY  )rb   rJ  rc   r;   c                 C  s&   t  }| |_|r||_|j| |S )z1Makes a ValueInfoProto with the given type_proto.)r   rb   rc   r   r   )rb   rJ  rc   r?  rG   rG   rH   make_value_info  s    rZ  )r  r;   c                 C  sb   t | tr| }n"t | tr*| jddd}nt| }t|dk rB|S |d d dt|d  d S )Nr  ignore)errors@   z	...<+len=>)r   r<   r   decoder   )r  Z	sanitizedrG   rG   rH   _sanitize_str  s    

r`  )rb   r   r   rc   elem_shape_denotationr;   c                 C  s>   t  }| |_|r||_t|||}t|}|jj|j |S )zJMakes a Sequence[Tensors] ValueInfoProto based on the data type and shape.)r   rb   rc   rL  rV  r   rT  r   )rb   r   r   rc   ra  r?  rK  Zsequence_type_protorG   rG   rH   make_tensor_sequence_value_info  s    rb  z"str | tuple[str, list[GraphProto]])r7  	subgraphsr;   c                 C  s  g }| | j | d ddddd}dddd	d
}td}dddddd}g }| drv| || j n@| dr| || j n"| dr| tt| j n | drt	| j
jdkr| d n&t| j
j}| dt| j
| d n| dr:| d| jj d | | j n|| dr^| d| j d nX| jr|| ||| j n:| jr| ||| j n| jr| tttt| j n| jr| d n| jr8| d t| jD ]<\}	}
|	t	| jd krd nd!}| d|
 d|  q| d" n~| jr| d t| jD ]>\}	}|	t	| jd krtd nd!}| d|j d|  qT| d" || j n
| d# |rd$||fS d$|S )%N=r   r<   )r   r;   c                 S  s   | dS )Nz.15grG   )r   rG   rG   rH   	str_float  s    z&printable_attribute.<locals>.str_floatr=   )r   r;   c                 S  s   t | S rX   )r<   )r   rG   rG   rH   str_int  s    z$printable_attribute.<locals>.str_int_TzCallable[[_T], str]zSequence[_T])str_elemxsr;   c                 S  s   dd t| | d S )N[, ])joinr   )rh  ri  rG   rG   rH   str_list
  s    z%printable_attribute.<locals>.str_listr   r   r  r  r   z<Tensor>z<Scalar Tensor r^  r  z<graph r!  z<Type Proto z[<Tensor>, ...]rj  r"   ,rM  rl  z	<Unknown> )r   rb   r   HasFieldr   r   reprr`  r  r   r  r   r   r   r   r  r!  r/  r.  r0  r<   r   r   r1  r4  rF  r3  ri   rm  )r7  rc  contentre  rf  rg  rn  r3  r   r   r!  commar  rG   rG   rH   printable_attribute  sb    
	






ru  zTensorShapeProto.Dimension)rE  r;   c                 C  s$   |  d}|d krdS tt| |S )Nrg   ?)
WhichOneofr<   r   )rE  whichrG   rG   rH   printable_dimD  s    
ry  )r  r;   c                 C  s   |  ddkrhtj| jj}| jdrdt| jjj	r\|t
ddtt| jjj	 7 }n|d7 }|S |  dd krzdS d|  d S )	Nrg   rD  r   rk  r[   , scalarrM  zUnknown type )rw  r   DataTypeNamerD  r   rq  r   r   rE  r<   rm  r   ry  r  r  rG   rG   rH   printable_typeK  s    $r~  )r   r;   c                 C  s,   d| j  }| jr(| dt| j d}|S )N%rj  rl  )rb   r   r~  )r   r  rG   rG   rH   printable_value_infoY  s    r  c                 C  sh   d| j  d}|tj| j7 }| jd k	r\t| jrT|tddt	t| j 7 }n|d7 }|d7 }|S )Nr  rj  rk  r[   rz  rl  )
rb   r   r{  r|  r   r   r   r<   rm  r   r}  rG   rG   rH   printable_tensor_proto`  s    

 r  )rn   prefixrc  r;   c                 C  sH  g }t | jr4|ddd | jD  |d g }g }| jD ]z}|rt||}t|d tsrtdt d|	|d  ||d  qBt|}t|t
std	t
 d|| qBdt|}	dd
d | jD }
| jr
|| j d|	 d|
 d n|| j d|
 d |r:|d| |fS |d| S )Nrk  c                 S  s   g | ]}d | qS r  rG   rZ   rb   rG   rG   rH   r   q  s     z"printable_node.<locals>.<listcomp>rd  r"   z1printed_attr_subgraphs[1] must be an instance of .r   zprinted must be an instance of c                 S  s   g | ]}d | qS r  rG   r  rG   rG   rH   r     s     rj  z](r  (rp  )r   rj   r   rm  rk   ru  r   r   r   ri   r<   rl   rh   r_   )rn   r  rc  rs  r3  Zprinted_attrsr7  Zprinted_attr_subgraphsZprintedZprinted_attributesZprinted_inputsrG   rG   rH   printable_nodel  s6    





 r  )rw   r  r;   c                   sz  g }|d }d| j g}dd | jD }t| jr|d g }g }| jD ],}|j |krh|t| qJ|t| qJ|r||d|  g }|D ]}	||d |	  q|d |r|d ||d|  g }|D ]}	||d |	  q|d t|t|k rd	d | jD   fd
d| jD }
|d ||d|  g }|
D ]}	||d |	  qd|d |d ||d|  g }| jD ]P}t||dd}t	|d t
stdt
 d||d  ||d  qdg}t| jr0|ddd | jD  ||d|  ||d  |D ]}|dt|  qVd|S )zDisplay a GraphProto as a string.

    Args:
        graph (GraphProto): the graph to display
        prefix (string): prefix of every line

    Returns:
        string
    z  rw   c                 S  s   h | ]
}|j qS rG   r<  r  rG   rG   rH   r    s     z"printable_graph.<locals>.<setcomp>r  rp  r  z,optional inputs with matching initializers (c                 S  s   h | ]
}|j qS rG   r<  r   rG   rG   rH   r    s     c                   s   g | ]}|j  krt|qS rG   )rb   r  r   Zgraph_inputsrG   rH   r     s   
z#printable_graph.<locals>.<listcomp>zinitializers ({T)rc  r"   z-contents_subgraphs[1] must be an instance of r  r   r;   rk  c                 S  s   g | ]}d |j  qS r  r<  )rZ   outrG   rG   rH   r     s     }
)rb   rt   r   rh   r   r  rm  rn   r  r   r   r   ri   rj   printable_graph)rw   r  rs  indentheaderZinitializersZin_strsZin_with_init_strsinplineZ	init_strsr3  rn   Zcontents_subgraphstailr  rG   r  rH   r    sl    












r  zgoogle.protobuf.message.Message)r   r;   c                 C  s   t | tjjjs&tdtjjj d| jjD ]l}|jdkrJ| 	|j q.|j
|jkr.|j|jkr~t| |jD ]}t| qnq.| |jr.tt| |j q.dS )z:Empties `doc_string` field on any nested protobuf messageszproto must be an instance of r  rc   N)r   googleZprotobufmessageMessager   Z
DESCRIPTORfieldsrb   Z
ClearFieldr   ZTYPE_MESSAGElabelZLABEL_REPEATEDr   strip_doc_stringrq  )r   Z
descriptorr[   rG   rG   rH   r    s    
r  AssignmentBindingTypezGraphProto | NonezAssignmentBindingType | Noner   )	algorithmalgorithm_bindingsinitializationinitialization_bindingsr;   c                 C  sr   t  }|j|  |D ]\}}|j }||_||_q|rF|j| |rn|D ]\}}|j }||_||_qN|S rX   )	r   r  r   Zupdate_bindingr   rU   rg   r  Zinitialization_binding)r  r  r  r  Ztraining_infor   r   ZbindingrG   rG   rH   make_training_info  s    

r  znp.dtype)tensor_dtyper;   c                 C  s   t j|  jS )zConvert a TensorProto's data_type to corresponding numpy dtype. It can be used while making tensor.

    Args:
        tensor_dtype: TensorProto's data_type

    Returns:
        numpy's data_type
    )r   TENSOR_TYPE_MAPr   r  rG   rG   rH   r     s    	r   c                 C  s   t j|  jS )zConvert a TensorProto's data_type to corresponding data_type for storage.

    Args:
        tensor_dtype: TensorProto's data_type

    Returns:
        data_type for storage
    )r   r  storage_dtyper  rG   rG   rH   $tensor_dtype_to_storage_tensor_dtype  s    	r  c                 C  s   t j|  jS )zGet the name of given TensorProto's data_type.

    Args:
        tensor_dtype: TensorProto's data_type

    Returns:
        the name of data_type
    )r   r  rb   r  rG   rG   rH   tensor_dtype_to_string   s    	r  c                 C  s   t jt j|  j S )zConvert a TensorProto's data_type to corresponding field name for storage. It can be used while making tensors.

    Args:
        tensor_dtype: TensorProto's data_type

    Returns:
        field name
    )r   Z_STORAGE_TENSOR_TYPE_TO_FIELDr  r  r  rG   rG   rH   r   ,  s    	
r   )r   r;   c                 C  sz   | t jkrttt j|  S t| tjr.tjS | t	j
t	jt	jt	jt	jt	jt	jhkrft	j| jd d  S td| ddS )zConvert a numpy's dtype to corresponding tensor type. It can be used while converting numpy arrays to tensors.

    Args:
        np_dtype: numpy's data_type

    Returns:
        TensorsProto's data_type
    r   zUnable to convert type z into TensorProto element type.N)r   Z_NP_TYPE_TO_TENSOR_TYPEr   r=   r   Z
issubdtypeZstr_r   r   custom_np_typesZbfloat16Zfloat8e4m3fnZfloat8e4m3fnuzZ
float8e5m2Zfloat8e5m2fnuzZint4Zuint4Zmapping_name_to_data_typedescrrT   )r   rG   rG   rH   np_dtype_to_tensor_dtype:  s(    	
	
r  zKeysView[int])r;   c                   C  s
   t j S )zcGet all tensor types from TensorProto.

    Returns:
        all tensor types from TensorProto
    )r   r  r  rG   rG   rG   rH   get_all_tensor_dtypes\  s    r  c                 C  s   i | ]\}}||qS rG   rG   )rZ   r   r   rG   rG   rH   
<dictcomp>e  s      r  )r  r;   c                 C  s$   | t j krt|  S t j d S )zConvert AttributeProto type to string.

    Args:
        attr_type: AttributeProto type.

    Returns:
        String representing the supplied attr_type.
    r   )r   AttributeTyper   _ATTRIBUTE_TYPE_TO_STRr  )r  rG   rG   rH   r6  h  s    	r6  )F)NNNN)NNNN)NNNNN)F)r   TFT)r   FFT)F)NN)N)N)rM  N)N)rM  N)rM  )rM  N)F)rM  F)rM  )o
__future__r   collections.abcr#  r  r   Zcmathr   typingr   r   r   r   r   r	   r
   r   r   r   Zgoogle.protobuf.messager  Znumpyr   Zonnx._custom_element_typesZ_custom_element_typesr  Zonnxr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r<   r=   ZVersionRowTyper7   r  r8   __annotations__r9   rK   rS   r^   ro   rr   rx   ry   r   r   r   r   r   r   r   r   r   r   r   r   r  r	  r  r  rf   r9  r:  r>  r@  rL  rN  rQ  rR  rV  rW  rY  rZ  r`  rb  ru  ry  r~  r  r  r  r  r  r  r   r  r  r   r  r  r  rm   r  r6  rG   rG   rG   rH   <module>   s
   0T&       1     +     &$%	     	    ~ x  _ $		 1   1 		 L  #O"	