
    /;jinS                       d dl mZ d dlZd dlmZmZ d dlZd dlZd dl	mZ
 d dlZd dlmZ erd dlmZ 	 	 d?d@dZdAdZdBdZdAdZdBdZdCdDdZdEdZdFdGd"ZdHd&Z	 dIdJd*ZdKd.ZdFdLd0ZdMd4Z	 dIdNd6Z	 dOdPd=ZdQd>ZdS )R    )annotationsN)TYPE_CHECKINGAny)helper)SequenceTupx
np.ndarraysaturatebool
round_modestrreturnc                R   t          j        | t           j                  }|                    t           j                  }|dz	  dz  }|                    t           j                  }|dk    }t          j        |t           j                  }d||<   | }|dk    r|dz  dk                        t           j                  }	|dz  dk                        t           j                  }
|dz  dk                        t           j                  }|dk                        t           j                  }|	d	k    |
d	k    |d	k    z  |d	k    z  z  }t          j        |          }d	|||z  <   |r|d
k    |z  |z  }d||<   ||z  }n`|dk    rA|dz  dk    }||z  }|r|d
k    |z  }d||<   ||                    t           j                  z  }n|dk    rnt          d|           |                    t           j                  }||         ||<   |                    t          j                  S )ar  Convert float32 NumPy array to float8e8m0 representation. If the input
    is not a float32 array, it will be cast to one first.

    Args:
        x: Input array to convert.
        saturate: Whether to saturate at max/min float8e8m0 value.
        round_mode: "nearest", "up", or "down".

    Returns:
        np.ndarray: Array of ml_dtypes.float8_e8m0fnu values.
    dtype      nearesti  @ r   i    i       r   iO FdownzUnsupported rounding mode: )npasarrayfloat32viewuint32astypeuint16
zeros_likeuint8
ValueError	ml_dtypesfloat8_e8m0fnu)r	   r   r   x_f32f_bitsexponentspecial_maskoutputnormal_maskgrslsbround_up	incrementmax_maskhas_fractions                    K/root/voice-cloning/.venv/lib/python3.11/site-packages/onnx/numpy_helper.pyto_float8e8m0r4      s>     Jq
+++EZZ	""F "$H
	 H
 t#L]828444FF<  -KYx1$,,RX66x1$,,RX66x1$,,RX66!|##BH--FQ162cQh?@M(++	,-	([() 	$ D(H4{BH"#IhI	t		)Q.+- 	' D(H4H!&HXHOOBI...	v		 CzCCDDD rx((H";/F;;;y/000    datanpt.NDArray[np.uint8]dimsSequence[int]c                z   t          j        | j        dz  g| j                  }| t          j        d          z  }| t          j        d          z  }|t          j        d          z  }||ddd<   ||ddd<   |j        t          j        |          dz   k    r
|dd	         }|                    |d
           |S )a  Convert a packed uint4 array to unpacked uint4 array represented as uint8.

    Args:
        data: A numpy array.
        dims: The dimensions are used to reshape the unpacked buffer.

    Returns:
        A numpy array of int8/uint8 reshaped to dims.
       r            r   Nr   Frefcheck)r   emptysizer   r!   prodresize)r6   r8   result	array_low
array_highs        r3   _unpack_4bitrI   _   s     Xty1}oTZ888Frx~~%I&J28A;;JF14a4LF14a4L{bgdmma'''
MM$M'''Mr5   arrayc                @   |                                                      t          j                                                  }| j        }|dz  dk    }|r|                    |dz   gd           |dz  }|dddxx         dz  cc<   |ddd         |ddd         z  S )	z[Convert a numpy array to flatten, packed int4/uint4. Elements must be in the correct range.r;   r   Fr@   r<   Nr>   r   ravelr   r   r!   copyrC   rE   )rJ   
array_flatrC   	odd_sizeds       r3   _pack_4bitx2rQ   x   s     ##BH--2244J:DqAI 64!8*u555$Jqt!taddjA...r5   c                X   t          j        | j        dz  g| j                  }| dz  |ddd<   | dz	  dz  |ddd<   | dz	  dz  |ddd<   | dz	  dz  |ddd<   |j        t          j        |          k    r|dt          j        |                   }|                    |d	
           |S )a  Convert a packed uint2 array to unpacked uint2 array represented as uint8.

    Args:
        data: A numpy array.
        dims: The dimensions are used to reshape the unpacked buffer.

    Returns:
        A numpy array of int8/uint8 reshaped to dims.
    r>   r      r   Nr;   r      Fr@   )r   rB   rC   r   rD   rE   )r6   r8   rF   s      r3   _unpack_2bitrU      s     Xty1}oTZ888F$;F14a4LAI%F14a4LAI%F14a4LAI%F14a4L{RWT]]"""'$--(
MM$M'''Mr5   c                   |                                                      t          j                                                  }| j        }|dz  }|r|                    |d|z
  z   gd           |dz  }|dddxx         dz  cc<   |dddxx         dz  cc<   |dddxx         dz  cc<   |d	dd         |ddd         z  |ddd         z  |ddd         z  S )
z[Convert a numpy array to flatten, packed int2/uint2. Elements must be in the correct range.r>   Fr@   rS   r   Nr;   rT   r   rL   )rJ   rO   rC   pad_lens       r3   _pack_2bitx4rX      s    ##BH--2244J:DQhG B41w;/05AAA$Jqt!tqt!tqt!taddjA..ADqD1AAJqtRStDTTTr5    tensoronnx.TensorProtobase_dirc                   |                      d          rt          d          | j        t          j        j        k    rt          d          | j        }t          j        |          }t          j        t          j	        |                    }t          j
        |          }| j        }| j        t          j        j        k    rVt          | |          }d |D             }t          j        |                              |                              |          S t          j                            |           r t          j                            | |           |                      d          rX| j        }	t,          j        dk    r:t          j        |	|                                                                          }	|t          j        j        t          j        j        t          j        j        hv rCt          j        |	t          j                  }
t?          |
|                               |          S |t          j        j!        t          j        j"        hv rCt          j        |	t          j                  }
tG          |
|                               |          S t          j        |	|                              |          S |t          j        j$        t          j        j%        t          j        j&        t          j        j'        hv rt          j(        | j)        t          j*                                       t          j+                                      t          j,                                      |                               |          S |t          j        j-        t          j        j.        t          j        j/        t          j        j0        t          j        j1        t          j        j2        hv rt          j(        | j)        t          j*                                       t          j+                                      t          j                                       |                              |          S |t          j        j        t          j        j        t          j        j        hv rt          j(        | j)        t          j*                                       t          j+                                      t          j                  }
t?          |
|                               |          S |t          j        j!        t          j        j"        hv rt          j(        | j)        t          j*                                       t          j+                                      t          j                  }
tG          |
|                               |          S t          | |          }
|t          j        j3        t          j        j4        fv r=t          j(        |
|                               |                              |          S t          j        |
|                              |                              |          S )a6  Converts a tensor def object to a numpy array.

    This function uses ml_dtypes if the dtype is not a native numpy dtype.

    Args:
        tensor: a TensorProto object.
        base_dir: if external tensor exists, base_dir can help to find the path to it

    Returns:
        arr: the converted array.
    segmentz*Currently not supporting loading segments.z2The element type in the input tensor is UNDEFINED.c                8    g | ]}|                     d           S )utf-8)decode).0r-   s     r3   
<listcomp>zto_array.<locals>.<listcomp>   s$    666Aahhw666r5   raw_databigr   )5HasFieldr"   	data_typeonnxTensorProto	UNDEFINED	TypeErrorr   tensor_dtype_to_np_dtype$tensor_dtype_to_storage_tensor_dtypetensor_dtype_to_fieldr8   STRINGgetattrr   r   r   reshapeexternal_data_helperuses_external_dataload_external_data_for_tensorrd   sys	byteorder
frombufferbyteswaptobytesINT4UINT4
FLOAT4E2M1r!   rI   r   UINT2INT2rU   BFLOAT16FLOAT16INT16UINT16rJ   
int32_dataint32r   r   FLOAT8E4M3FNFLOAT8E4M3FNUZ
FLOAT8E5M2FLOAT8E5M2FNUZ
FLOAT8E8M0BOOL	COMPLEX64
COMPLEX128)rZ   r\   tensor_dtypenp_dtypestorage_np_dtypestorage_fieldr8   utf8_stringsssrd   r6   s              r3   to_arrayr      s)    y!! GEFFF4+555LMMM#L.|<<H63LAA  0>>M;D4+222v}5566666z"~~$$X..66t<<<  33F;; R!??QQQz"" E?=E!!}XX>>>GGIIQQSSH!"'
 
 

 =:::Dd++00:::"!
 
 
 =:::Dd++00:::}XX666>>tDDD! 	   HV&bh777T")__VBIWT]]T(^^	
 %'#'#   HV&bh777T")__VBHT(^^WT]]	
 #   HV&bh777<<RYGGNNrxXX 	 D$'',,X666  
 HV&bh777<<RYGGNNrxXX 	 D$'',,X6666=))D(2D4D4OPPPx$4555:::JJRRSWXXX:d"2333::8DDLLTRRRr5   bytesc                    | j         j        dk    s t          j        dk    r=| j         j        dk    r-|                     | j                             d                    } |                                 S )zConverts an array into bytes in little endian byte order.

    Args:
        array: a numpy array.

    Returns:
        bytes: Byte representation of passed array in little endian byte order.

    .. versionadded:: 1.20
    >re   =<)r   rv   ru   r   newbyteorderry   )rJ   s    r3   tobytes_little_endianr     sa     {##5;#8C#?#? U[55c::;;==??r5   name
str | Nonec          	        t          j                    }|j                            | j                   |r||_        | j        t          k    s$t          j	        | j        t          j
                  rt           j        j        |_        |                                 }|D ]}t          |t                    r.|j                            |                    d                     Et          |t&                    r|j                            |           ut)          dt          t+          |                              |S t-          j        | j                  }|t           j        j        t           j        j        t           j        j        hv rt7          |           } |t           j        j        t           j        j        hv rt=          |           } t?          |           |_         ||_        |S )zConverts an array into a TensorProto including

    Args:
        array: a numpy array.
        name: (optional) the name of the tensor.

    Returns:
        TensorProto: the converted tensor def.
    r`   zMUnrecognized object in the object array, expect a string, or array of bytes: )!rh   ri   r8   extendshaper   r   objectr   
issubdtypestr_ro   rg   flatten
isinstancer   string_dataappendencoder   NotImplementedErrortyper   np_dtype_to_tensor_dtyperz   r{   r|   rQ   r}   r~   rX   r   rd   )rJ   r   rZ   
flat_arrayer   s         r3   
from_arrayr   2  s    F
Ku{### {fek27 C C+2 ]]__
 		 		A!S!! "))!((7*;*;<<<<Au%% "))!,,,,)cQLL   +EK88E#   U##  
 U##+E22FOFMr5   sequenceonnx.SequenceProto	list[Any]c                ^   | j         }|t          j        j        k    rd | j        D             S |t          j        j        k    rd | j        D             S |t          j        j        k    rd | j        D             S |t          j        j	        k    rd | j
        D             S t          d          )zConverts a sequence def to a Python list.

    Args:
        sequence: a SequenceProto object.

    Returns:
        list: the converted list.
    c                ,    g | ]}t          |          S  r   rb   vs     r3   rc   zto_list.<locals>.<listcomp>x  s    <<<<<<r5   c                ,    g | ]}t          |          S r   r   r   s     r3   rc   zto_list.<locals>.<listcomp>z  s    CCCCCCr5   c                ,    g | ]}t          |          S r   )to_listr   s     r3   rc   zto_list.<locals>.<listcomp>|  s    ===q

===r5   c                ,    g | ]}t          |          S r   )to_dictr   s     r3   rc   zto_list.<locals>.<listcomp>~  s    888q

888r5   z8The element type in the input sequence is not supported.)	elem_typerh   SequenceProtoTENSORtensor_valuesSPARSE_TENSORsparse_tensor_valuesSEQUENCEsequence_valuesMAP
map_valuesrk   )r   r   s     r3   r   r   m  s     "ID&---<<X%;<<<<D&444CCX%BCCCCD&///==H$<====D&***88H$78888
N
O
OOr5   lstr   
int | Nonec                    t          j                    }|r||_        |r|}nt                     dk    rh d         }t	          |t
                    rt           j        j        }nJt	          |t                    rt           j        j        }n#t           j        j	        }nt           j        j	        }||_
        t                     dk    r*t           fd D                       st          d          |t           j        j	        k    r@ D ]<}|j                            t          t!          j        |                    g           =n|t           j        j        k    r. D ]*}|j                            t'          |          g           +nR|t           j        j        k    r. D ]*}|j                            t+          |          g           +nt          d          |S )a]  Converts a list into a sequence def.

    Args:
        lst: a Python list
        name: (optional) the name of the sequence.
        dtype: (optional) type of element in the input list, used for specifying
                          sequence values when converting an empty list.

    Returns:
        SequenceProto: the converted sequence def.
    r   c              3  ^   K   | ]'}t          |t          d                              V  (dS )r   N)r   r   )rb   elemr   s     r3   	<genexpr>zfrom_list.<locals>.<genexpr>  s7      !Q!QT*T4A<<"@"@!Q!Q!Q!Q!Q!Qr5   zqThe element type in the input list is not the same for all elements and therefore is not supported as a sequence.zZThe element type in the input list is not a tensor, sequence, or map and is not supported.)rh   r   r   lenr   dictr   listr   r   r   allrk   r   r   r   r   r   r   	from_listr   	from_dict)	r   r   r   r   r   
first_elemrZ   seqmappings	   `        r3   r   r     s    !##H  .			SAV
j$'' 	2*.II
D)) 	2*3II*1II &-	"HC1c!Q!Q!Q!QS!Q!Q!QQQM
 
 	

 D&--- 	L 	LF")):bj6H6H+I+I*JKKKK	L	d(1	1	1 	> 	>C$++Ys^^,<====	>	d(,	,	, 	= 	=G&&	'(:(:';<<<<	= 5
 
 	
 Or5   	map_protoonnx.MapProtodict[Any, Any]c                ^   g }| j         t          j        j        k    rt	          | j                  }nt	          | j                  }t          | j                  }t          |          t          |          k    rt          d| j        d          t          t          ||d                    S )zConverts a map def to a Python dictionary.

    Args:
        map_proto: a MapProto object.

    Returns:
        The converted dictionary.
    z2Length of keys and values for MapProto (map name: z) are not the same.F)strict)key_typerh   ri   ro   r   string_keyskeysr   valuesr   
IndexErrorr   r   zip)r   key_list
value_lists      r3   r   r     s     HT-444	-..	'')**J
8}}J''@N!
 
 	

 Hj777888r5   dict_c                  	 t          j                    }|r||_        t          |           }t	          j        |d                   t          j                  }t           j        j	        t           j        j
        t           j        j        t           j        j        t           j        j        t           j        j        t           j        j        t           j        j        h}t#          fd|D                       st%          d          t          |                                           }t	          j        |d                   	t#          	fd|D                       st%          d          t)          |          }||_        |t           j        j        k    r|j                            |           n||v r|j                            |           |j                            |           |S )zConverts a Python dictionary into a map def.

    Args:
        dict_: Python dictionary
        name: (optional) the name of the map.

    Returns:
        MapProto: the converted map def.
    r   c              3  H   K   | ]}t          j        |          k    V  d S Nr   result_type)rb   keyraw_key_types     r3   r   zfrom_dict.<locals>.<genexpr>  s2      DDs##|3DDDDDDr5   zfThe key type in the input dictionary is not the same for all keys and therefore is not valid as a map.c              3  H   K   | ]}t          j        |          k    V  d S r   r   )rb   valraw_value_types     r3   r   zfrom_dict.<locals>.<genexpr>  s2      GGr~c""n4GGGGGGr5   zjThe value type in the input dictionary is not the same for all values and therefore is not valid as a map.)rh   MapProtor   r   r   r   r   r   ri   INT8r   INT32INT64UINT8r   UINT32UINT64r   rk   r   r   r   ro   r   r   r   CopyFrom)
r   r   r   r   r   valid_key_int_typesr   	value_seqr   r   s
           @@r3   r   r     s    I 	;;D>$q'**L.|<<H 		 DDDDtDDDDD 
@
 
 	

 %,,..!!F^F1I..NGGGGGGGGG 
B
 
 	

 &!!I!I4#***$$T****	(	(	(d###i(((r5   optionalonnx.OptionalProto
Any | Nonec                   | j         }|t          j        j        k    rdS |t          j        j        k    rt          | j                  S |t          j        j        k    rt          | j                  S |t          j        j	        k    rt          | j                  S |t          j        j        k    rt          | j                  S |t          j        j        k    rt!          | j                  S t%          d          )zConverts an optional def to a Python optional.

    Args:
        optional: an OptionalProto object.

    Returns:
        opt: the converted optional.
    Nz8The element type in the input optional is not supported.)r   rh   OptionalProtorj   r   r   tensor_valuer   sparse_tensor_valuer   r   sequence_valuer   r   	map_valueOPTIONALto_optionaloptional_valuerk   )r   r   s     r3   r  r  	  s     "ID&000tD&----...D&4444555D&///x.///D&***x)***D&///82333
N
O
OOr5   optc                :   t          j                    }|r||_        |:|t           j        j                                        vrt          | d          |}nst          | t                    rt           j        j        }nLt          | t                    rt           j        j
        }n%| t           j        j        }nt           j        j        }||_        | |t           j        j        k    r(|j                            t!          |                      n|t           j        j
        k    r(|j                            t%          |                      nL|t           j        j        k    r(|j                            t)          |                      nt          d          |S )a  Converts an optional value into a Optional def.

    Args:
        opt: a Python optional
        name: (optional) the name of the optional.
        dtype: (optional) type of element in the input, used for specifying
                          optional values when converting empty none. dtype must
                          be a valid OptionalProto.DataType value

    Returns:
        optional: the converted optional def.
    Nz( must be a valid OptionalProto.DataType.zUThe element type in the input is not a tensor, sequence, or map and is not supported.)rh   r   r   DataTyper   rk   r   r   r   r   r   rj   r   r   r   r   r   r   r   r   r   )r  r   r   r   r   s        r3   from_optionalr  "  s{     !##H *3::<<<<uNNNOOO			C		 .&*			C		 .&/			&0		&-	"H
*111!**:c??;;;;$,555#,,Ys^^<<<<$,000''	#77779   Or5   r   input_shape
tuple[int]np.dtypeseedintc           	        t           j                            |           |t           j        t           j        t           j        t           j        t           j        t           j        t           j	        t           j
        fv rt          t          j        |          j        t          j        t           j	                  j                  }t          t          j        |          j        t          j        t           j	                  j                  }t           j                            |||                               |          S t!          | d          )a'  Create random integer array for backend/test/case/node.

    Args:
        input_shape: The shape for the returned integer array.
        dtype: The NumPy data type for the returned integer array.
        seed: The seed for np.random.

    Returns:
        np.ndarray: Random integer array.
    )rC   z' is not supported by create_random_int.)r   randomr
  r!   r   r   uint64int8int16r   int64miniinfomaxrandintr   rk   )r  r   r
  endstarts        r3   create_random_intr  U  s     INN4

	
	
	



	 	 	 "(5//%rx'9'9'=>>BHUOO'"(););)?@@y  + >>EEeLLL
uEEE
F
FFr5   c                   t          j        |t           j                  s0|t          j        t          j        t          j        t          j        fv r)t          j        |          }t          j	        |           } nt          j
        |          }t          j        | |j        |j                                      |          S )zSaturate cast for numeric types.

    This function ensures that values outside the representable range
    of the target dtype are clamped to the maximum or minimum representable
    value of that dtype.
    )r   r   integerr#   int4uint4int2uint2r  roundfinfoclipr  r  r   )r	   r   infos      r3   saturate_castr#  t  s     
}UBJ'' 	&5	5 , , u%%HQKKu%%71dh))00777r5   )Tr   )r	   r
   r   r   r   r   r   r
   )r6   r7   r8   r9   r   r7   )rJ   r
   r   r7   )rY   )rZ   r[   r\   r   r   r
   )rJ   r
   r   r   r   )r   r   rJ   r
   r   r[   )r   r   r   r   )NN)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   r	  r   r
   ) 
__future__r   ru   typingr   r   r#   numpyr   numpy.typingnptonnx.external_data_helperrh   r   collections.abcr   r4   rI   rQ   rU   rX   r   r   r   r   r   r   r   r  r  r  r#  r   r5   r3   <module>r+     sJ   # " " " " " 



 % % % % % % % %                             )((((((
 H1 H1 H1 H1 H1V   2
/ 
/ 
/ 
/   0U U U UoS oS oS oS oSd   (8 8 8 8 8vP P P P, BF6 6 6 6 6r9 9 9 922 2 2 2 2jP P P P4 CG0 0 0 0 0h ;<G G G G G>8 8 8 8 8 8r5   