
    wiz9                        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mZmZmZmZmZmZmZmZmZ d dlmZ ddZddZddZ	 	 	 	 dd dZdS )!    )annotationsN)AttributeProtoFunctionProto
GraphProto
ModelProto	NodeProtoSparseTensorProtoTensorProto)	make_attributemake_function
make_graph
make_model	make_nodemake_tensormake_tensor_value_infoset_model_propstensor_dtype_to_np_dtype)
from_arraynoder   	thresholdintvalue_constant_of_shapefloatreturnlist[NodeProto]c                   | j         dk    rt          d| j         d          | j        D ]"}|j        dk    rt	          d| j        d          |j        dk    r|j        }|j         d}|j        }t          j        |          }||k    r| gc S t          t          j
        t          |          t          j        	          |
          }t          |j                  }	t          dg |g|          }
t          d|g| j        t          t          j
        |g|		                              }|
|gc S t	          d|j                  | gS )zReplaces a Constant node with a large tensor (with more than threshold elements) by a sequence of nodes that produces a dummy constant of same shape as original tensor.Constantz!Node type must be 'Constant' not .sparse_valuezEThis feature is not yet implemented for a sparse constant (node name=).value__SHAPEdtypenamer!   ConstantOfShapez'Replacement of constant with attribute )op_type	TypeError	attributer&   NotImplementedErrortdimsnpprodr   arraylistint64r   	data_typer   output)r   r   r   attr!   new_namer.   sizeinitr$   
node_shapenew_nodes               l/root/.openclaw/workspace/chatterbox_venv_py311/lib/python3.11/site-packages/onnx/tools/replace_constants.py_replace_constantr=      s    |z!!MDLMMMNNN~ 
 
8~%%%."i. . .   8wEE*---H:D74==Dy  vbhtDzzBBBRRRD,U_==E"
	  J !!
 +B*C5!Q!Q!QRR	  H ))))!BchBB
 
 	
 6M    onxGraphProto | FunctionProtoc           	        t          | t                    rt          | j                  }nJt          | t                    rt          | j                  }n t          dt          |            d          t                      |D ]0}t          |j                  z  t          |j	                  z  1fd}t          dg  |d          gd          }t          dg  |d          gd	          }i }t          |          D ]x\  }}|j        d
k    r|j        d         }t          d|g || d          g          }	t          d|j	        d         |	j	        d         |j	        d         g || d          g          }
t          |j                  d	k    r|j        d         j        j        }nt"          j        }t          d|
j	        d         g || d          g|          }t          d|	j	        d         g || d          g|          }t          d|j	        d         |j	        d         g || d          g          }t          d|j	        d         |g|j	                  }|	|
||||g||<   zt'          |                                d          D ]\  }}||||d	z   <   |                    d|           |                    d	|           t          | t                    r.t-          || j        | j        | j	        | j        | j                  S t          | t                    r.t5          | j        | j        | j        | j	        || j                  S t          dt          |            d          )zReplaces all *ConstantOfShape* by node *Range* to avoid constant tensors.

    The function is not recursive. The recursivity is done by
    *replace_initializer_by_constant_of_shape*.
    Not implemented for type r   c                    | vr                     |            | S d}	 |  d| }|vr                     |           |S |dz  }()N   T_   )addRuntimeError)prefixir&   existing_namess      r<   
_find_namez9_replace_constant_of_shape_with_range.<locals>._find_name[   sr    ''v&&&M	??q??D>))""4(((FA	r>   r   zeror   )	value_intonerF   r(   
ReduceProd_NRange_RANGECast_RANGEf)to_NfDiv_FLATReshapeT)reverseinitializersparse_initializeropset_imports)
isinstancer   r2   r   r   r*   typesetinputr5   r   	enumerater)   lenr+   r-   r4   r
   FLOATsorteditemsinsertr   r&   r]   r^   r   domainopset_import)r?   nodesr   rL   cst0cst1updateinodeshapenarV   accldreshuprK   s                    @r<   %_replace_constant_of_shape_with_rangerz   G   s    #z"" BSX	C	'	' BSX@DII@@@AAAUUN + +#dj//)#dk***N N N N N Zjj&8&8%9QGGGDZjj&7&7%8AFFFDF '' 0 0t<,,,
1lUGjjE.F.F-GHH[^QXa[$+a.9Z5((())*
 

 t~!##"$.BB"Bv}zzU:K:K:K/L/L.MRTUUUv}zzU---/H/H.IbQQQBIaL")A,/**___2M2M1N
 
 QXa[%$8$+FFAr2q$/uFLLNND999 & &	r#%eeai  	LLD	LLD#z"" 
HIJ"5
 
 
 	
 #}%% 
JHIJ*
 
 
 	
 <S		<<<
=
==r>   c                R   t          | t                    rt          | j                  }nJt          | t                    rt          | j                  }n t          dt          |            d          t                      }|D ]0}|t          |j                  z  }|t          |j	                  z  }1i }t          |          D ]\  }}|j        dk    r|j        d         j        }t          |j        |j        dg|g          }t#          d|j        |j	                  }	t%          |j        d         j        |          }
|	j                            |
           |	||<   |                                D ]
\  }}|||<   t          | t                    r.t+          || j        | j        | j	        | j        | j                  S t          | t                    r.t1          | j        | j        | j        | j	        || j                  S t          dt          |            d          )	z7Replaces all fill value of all nodes *ConstantOfShape*.rB   r   r(   r   rF   r'   r\   r_   )ra   r   r2   r   r   r*   rb   rc   rd   r5   re   r)   r+   r-   r   r&   r4   r   r   appendri   r   r]   r^   r   rk   rl   )r?   r   rm   rK   r   rp   rq   tensor
new_tensorr;   r6   ry   s               r<    _replace_constant_of_shape_valuer      s7    #z"" BSX	C	'	' BSX@DII@@@AAAUUN + +#dj//)#dk***F '' 
! 
!t<,,,"$ K)A31H0I
 

 .
DKHHT^A.3:FFF!!#&&& u\\^^  	re#z"" 
HIJ"5
 
 
 	
 #}%% 
JHIJ*
 
 
 	
 <S		<<<
=
==r>      F      ?'FunctionProto | GraphProto | ModelProto
ir_version
int | None	use_rangeboolc                "     t           t                    rd}g } j        D ]^}|j        dk    r<t	          |          }t          |          dk    rd}|                    |           I|                    |           _|rWt           j	         j
         j         j        | j                  }	rt          |	          S dk    rt          |	          S |	S rt                     S dk    rt                     S  S t           t                     rLt#           j        p j                  }
 fd j        D             }t+          |
| j         j        p j         j         j	         j        	          }t           j                  d
k    r!d  j        D             }t7          ||           |j        dd=  j        D ]}|j                                        }|j	        dk    r%|j        dk     rrt=          d|j         d          |j	        dk    r#|j        dk     rt=          d|j         d          |j	        |_	        |j        |_        |S t           t>                    s tA          dtC                      d          d
}g }tE                       g }g } j#        D ]h}tI          |j%                  }tM          j'        |          }|k    r|                    |           G|dz  }|j
         d}|                    tQ          tM          j)        tU          |          tL          j+                  |                     tY          |j-                  }t]          d|g|j
        gtQ          tM          j)        dg|                              }|                    |                                |j
                   Bdk    r<|                    t_          |t`          j1        t          |          g                     jg } j2        D ]o}tI          |j%                  }tM          j'        |          }|k    r|                    |           Ftg          d|j4        j
        d|j5        j
        d           j        D ]^}|j        dk    r?t	          |          }t          |          dk    r|dz  }|                    |           Md}g }|j6        D ]}|j!        tn          j8        k    rlts          |d          r\|j:        Ut#          |j:                  }tw          |          tw          |j:                  k    rd}ty          |j
        |          }|                    |           |rVt]          |j        |j        |j                  }|j6                            |           |                    |           |dz  }I|                    |           `|d
k    r\t{          | j
         fd  j        D             |z    j        ||!          }rt          |          S dk    rt          |          S |S rt                     S dk    rt                     S  S )"a  Replace initializers or constant node by nodes *ConstantOfShape* to reduce the size.

    This reduce the cost to write a unit test about a specific graph structure.

    Args:
        onx: ModelProto
        threshold: every initializer under this threshold is not
            impacted
        ir_version: initializer must be specified as input for
            `ir_version <= 3`, this must be specified if onx is
            :class:`FunctionProto` or :class:`GraphProto`
        use_range: if uses operator *Range* instead of *ConstantOfShape*
            to avoid constant tensors
        value_constant_of_shape: value to use as a value for all nodes
            *ConstantOfShape*, a high value may produce nan or inf
            predictions

    Returns:
        onx, modified ModelProto

    The function is designed so that the function can be reapplied on a modified model
    and either replace *ConstantOfShape* with *Range* operators, either replace the fill value
    for every *ConstantOfShape*.
    Fr   rD   Tr_   rF   )r   r   r   r   c           	     F    g | ]}t          |pj                   S )r   r   r   r   )(replace_initializer_by_constant_of_shaper   ).0fr   r?   r   r   r   s     r<   
<listcomp>z<replace_initializer_by_constant_of_shape.<locals>.<listcomp>  sP     	
 	
 	
  5#%7#(?  	
 	
 	
r>   )	functionsproducer_nameproducer_versionr   
doc_stringrk   model_versionr   c                (    i | ]}|j         |j        S  )keyr!   )r   ps     r<   
<dictcomp>z<replace_initializer_by_constant_of_shape.<locals>.<dictcomp>/  s    AAAaeQWAAAr>   N    z.Range was introduced in opset 11 but opset is r   	   z7ConstantOfShape was introduced in opset 9 but opset is z-onx should be a GraphProto at this stage not r"   r#   r%   r(   r   r'      zKThis feature is not yet implemented for a sparse initializer (indices.name=z, values.name=r    gr   c                &    g | ]}|j         v|S r   r%   )r   rJ   removeds     r<   r   z<replace_initializer_by_constant_of_shape.<locals>.<listcomp>  s%    ;;;1QV7%:%:Q%:%:%:r>   r\   )>ra   r   r   r)   r=   rf   extendr|   r   rk   r&   rd   r5   rl   rz   r   r   r   graphr   r   r   r   r   r   r   metadata_propsr   rG   versionrH   r   r*   rb   rc   r]   tupler.   r/   r0   r   r1   r2   r3   r   r4   r   r   r
   INT64r^   r,   indicesvaluesr+   r   GRAPHhasattrr   idr   r   )!r?   r   r   r   r   modified	new_nodesr   	cst_nodesnew_onx	new_graphnew_functionsmodelr   oimpop_setn_modificationsadditional_inputs	new_initsr9   r.   r8   r7   r$   new_sparse_initssp_initshape_nodesattsr6   r   r;   r   r   s!   `````                           @r<   r   r      s   > #}%% %'	H 	# 	#D|z))-dI?VWW	y>>Q&&#H  +++T"""" 	#
	
!.  G  F<WEEE&!++74   N 	>8==="a''3C9PQQQ
#z"" .<I!3S^$;
 
 
		
 	
 	
 	
 	
 	
 	
 	
 ]	
 	
 	
 #+ 1!3S^~:+	
 	
 	
 s!""Q&&AAc.@AAAFE6***qqq!$ 	* 	*D'++--F{b  T\B%6%69%6"TT\TTT   {b  T\A%5%5"<,0L< < <   !KFM!\FNNc:&& VTS		TTTUUUOIeeG#%I  TYwt}}9T"""1i(((rxT

"(;;;(KKK	
 	
 	
 )88JYKRXse5999::	
 
 
 	DI!jAoo$$&x1BSYYKPP   13) 

 

W\""wt}}9##G,,,!5$_15 5">.5 5 5
 
 	
   #  #<:%%+D)=TUUK;1$$1$[)))> 	 	CN000C%% 1E%<E')',C   a55BsuII%%#H(155CKK 	# tz4;GGH%%d+++X&&&q OOT""""H;;;;	;;;>OOJ!/
 
 
  	@8???"a''3E;RSSS :4S999!##/5LMMMJr>   )r   r   r   r   r   r   r   r   )r?   r@   r   r@   )r?   r@   r   r   r   r@   )r   NFr   )
r?   r   r   r   r   r   r   r   r   r   )
__future__r   numpyr/   onnxr   r   r   r   r   r	   r
   onnx.helperr   r   r   r   r   r   r   r   r   onnx.numpy_helperr   r=   rz   r   r   r   r>   r<   <module>r      s|   # " " " " "                     
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 ) ( ( ( ( (% % % %PS> S> S> S>l2> 2> 2> 2>n !%(S S S S S S Sr>   