
    bIg9                        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y)    )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_arrayc                   | j                   dk7  rt        d| j                   d      | j                  D ]3  }|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)node	thresholdvalue_constant_of_shapeattr   new_namer'   sizeinitr   
node_shapenew_nodes               Y/var/www/html/answerous/venv/lib/python3.12/site-packages/onnx/tools/replace_constants.py_replace_constantr9      s_    ||z!;DLL;K1MNN~~ 
88~%%"ii]".  88wEEE**W-H::D774=Dy vbhhtDzBRD,U__=E"
	J !!
 +B*C5!QR	H ))!5chh\B
 	
9
> 6M    c           	        t        | t              rt        | j                        }n>t        | t              rt        | j                        }nt        dt        |        d      t               |D ]2  }t        |j                        z  t        |j                        z  4 fd}t        dg  |d      gd      }t        dg  |d      gd	      }i }t        |      D ]|  \  }}|j                  d
k7  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||<    t'        |j)                         d      D ]  \  }}||||d	z     |j+                  d|       |j+                  d	|       t        | t              rEt-        || j.                  | j                  | j                  | j0                  | j2                        }|S t        | t              rEt5        | j6                  | j.                  | j                  | j                  || j8                        }|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j                  |        | S d}	 |  d| }|vrj                  |       |S |dz  }$)N   _   )addRuntimeError)prefixir   existing_namess      r8   
_find_namez9_replace_constant_of_shape_with_range.<locals>._find_name[   s^    'v&MXQqc?D>)""4(FA r:   r   zeror   )	value_intoner@   r!   
ReduceProd_NRange_RANGECast_RANGEf)to_NfDiv_FLATReshapeT)reverseinitializersparse_initializeropset_imports)
isinstancer   r+   r/   r   r#   typesetinputr.   r   	enumerater"   lenr$   r&   r-   r
   FLOATsorteditemsinsertr   r   rW   rX   r   domainopset_import)onxnodesr/   rF   cst0cst1updateinodeshapenarP   accldreshupgraphnew_onxrE   s                      @r8   %_replace_constant_of_shape_with_rangerw   G   s:    #z"SXX	C	'SXX3DI;a@AAUN +#djj/)#dkk**+N Zj&8%9QGDZj&7%8AFDF ' 0t<<,,

1lUGjE7".F-GH[[^QXXa[$++a.95'()*

 t~~!#"$$..B""Bv}zUG7:K/L.MRTUv}zUG3-/H.IbQBIIaL"))A,/*we_2M1N
 QXXa[%$8$++FAr2q$/u+0. FLLND9 &	r#%eeai &	LLD	LLD#z"HHIIJJ"55
 #}%JJHHIIJJ**
 
/S	{!<
==r:   c                   t        | t              rt        | j                        }n>t        | t              rt        | j                        }nt        dt        |        d      t               }|D ]2  }|t        |j                        z  }|t        |j                        z  }4 i }t        |      D ]  \  }}|j                  dk7  r|j                  d   j                  }t        |j                  |j                   dg|g      }t#        d|j                  |j                        }	t%        |j                  d   j                  |      }
|	j                  j'                  |
       |	||<    |j)                         D ]
  \  }}|||<    t        | t              rEt+        || j                  | j                  | j                  | j,                  | j.                        }|S t        | t              rEt1        | j2                  | j                  | j                  | j                  || j4                        }|S t        dt        |        d      )	z7Replaces all fill value of all nodes *ConstantOfShape*.r<   r   r!   r   r@   r    rV   rY   )r[   r   r+   r/   r   r#   r\   r]   r^   r.   r_   r"   r$   r&   r   r   r-   r   r   appendrc   r   rW   rX   r   re   rf   )rg   r1   rh   rE   r/   rk   rl   tensor
new_tensorr7   r2   rt   ru   rv   s                 r8    _replace_constant_of_shape_valuer|      s    #z"SXX	C	'SXX3DI;a@AAUN +#djj/)#dkk**+ F ' 
!t<<,,"$$ KK))A31H0I

 .

DKKHT^^A.33:F!!#& u
! \\^ 	re #z"HHIIJJ"55
 #}%JJHHIIJJ**
 
/S	{!<
==r:   c                D   t        | t              rd}g }| j                  D ]Q  }|j                  dk(  r/t	        |||      }t        |      dk(  rd}|j                  |       A|j                  |       S |rct        | j                  | j                  | j                  | j                  || j                        }	|rt        |	      S |dk7  rt        |	|      S |	S |rt        |       S |dk7  rt        | |      S | S t        | t               rt#        | j$                  |xs | j&                  |||      }
| j(                  D cg c]   }t#        |||xs | j&                  ||      " }}t+        |
|| j,                  | j.                  |xs | j&                  | j0                  | j                  | j2                  	      }t        | j4                        d
kD  r:| j4                  D ci c]  }|j6                  |j8                   }}t;        ||       |j                  dd= | j                  D ]  }|j                  j=                         }|j                  dk(  r*|j>                  dk  r|rtA        d|j>                   d      |j                  dk(  r(|j>                  dk  rtA        d|j>                   d      |j                  |_	        |j>                  |_         |S t        | tB              stE        dtG        |        d      d
}g }tI               }g }g }| jJ                  D ]Z  }tM        |jN                        }tQ        jR                  |      }||k  r|j                  |       E|dz  }|j                   d}|j                  tU        tQ        jV                  tY        |      tP        jZ                        |             t]        |j^                        }ta        d|g|j                  gtU        tQ        jV                  dg|                  }|j                  |       |j=                  |j                         | |dk  s'|j                  tc        |td        jf                  t        |      g             ] g }| jh                  D ]|  }tM        |jN                        }tQ        jR                  |      }||k  r|j                  |       Dtk        d|jl                  j                  d|jn                  j                  d       | j                  D ]c  }|j                  dk(  r2t	        |||      }t        |      dk(  r|dz  }|j                  |       Ed}g }|jp                  D ]  }|jF                  tr        jt                  k(  rktw        |d      r_|jx                  St#        |jx                  ||||      } t{        |       t{        |jx                        k7  rd}t}        |j                  |       }|j                  |        |r^ta        |j                  |j                  |j                        }!|!jp                  j                  |       |j                  |!       |dz  }S|j                  |       f |d
kD  rot        || j                  | j                  D "cg c]  }"|"j                  |vs|" c}"|z   | j                  ||      }#|rt        |#      S |dk7  rt        |#|      S |#S |rt        |       S |dk7  rt        | |      S | S c c}w c c}w c c}"w )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   r>   TrY   r@   )
ir_versionr0   	use_ranger1   )r0   r~   r   r1   )	functionsproducer_nameproducer_versionr~   
doc_stringre   model_versionr   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       zKThis feature is not yet implemented for a sparse initializer (indices.name=z, values.name=r   grV   )@r[   r   r/   r"   r9   r`   extendry   r   re   r   r^   r.   rf   rw   r|   r   (replace_initializer_by_constant_of_shaperu   r~   r   r   r   r   r   r   metadata_propskeyr   r   rA   versionrB   r   r#   r\   r]   rW   tupler'   r(   r)   r   r*   r+   r,   r   r-   r   r   r
   INT64rX   r%   indicesvaluesr$   r   GRAPHhasattrr   idr   r   )$rg   r0   r~   r   r1   modified	new_nodesr/   	cst_nodesrv   	new_graphfnew_functionsmodelpr   oimpop_setn_modificationsremovedadditional_inputs	new_initsr5   r'   r4   r3   r   new_sparse_initssp_initshape_nodesattsr2   r   r7   rD   ru   s$                                       r8   r   r      s   > #}%%'	HH 	#D||z)-dI?VW	y>Q&#H  +T"	# #

		

!..G <WEE&!+74  N8=="a'3C9PQQ
#z"<II!3S^^$;
	 ]]	
  5#%7#(?	
 	
 #++ 11!3S^^~~::++	
 s!!"Q&.1.@.@AaeeQWWnAFAE6*q!$$ 	*D''++-F{{b T\\B%69"DT\\NRST  {{b T\\A%5",,0LL><  !KKFM!\\FN	* c:&GS	{RSTUUOIeG#%I TYYwwt}9T"1ii[(rxxT
"((;(K	
 )8JYYKRXXse59:	
 	DII!jAo$$&x1B1BSYKP+2 13)) 

W\\"wwt}9##G,!$__114 5">>..15
 	


   #<<:%+D)=TUK;1$1$[)>> 	CN000C%EE%<EE')',C a5BsuuI%#H(15CKK!	"  tzz4;;GH%%d+X&q OT"A #D HH		;1QVV7%:Q;>OOJJ!/
 8??"a'3E;RSS4S99!#/5LMMJW	
* BP <s   %\!\#\7\)r/   r   r0   intr1   floatreturnzlist[NodeProto])rg   GraphProto | FunctionProtor   r   )rg   r   r1   r   r   r   )   NFr   )
rg   z'FunctionProto | GraphProto | ModelProtor0   r   r~   z
int | Noner   boolr1   r   )
__future__r   numpyr(   onnxr   r   r   r   r   r	   r
   onnx.helperr   r   r   r   r   r   r   r   r   onnx.numpy_helperr   r9   rw   r|   r    r:   r8   <module>r      s    #   
 
 
 )%
% #%>C%%PU>	#U>U>p4>	#4>>C4>4>r !%(S	0SS S 	S
 #Sr:   