
    iW                        S SK r S SKrS SKrS SKrS SKrS SKrS SKJrJrJ	r	J
r
JrJr  S SKJr  S SKJr  S SKrS SKrS SKrS SKrS SKrS SKr S SKrS SK J!r"  SSK#J$r$  SSK#J%r%  SSK#J&r&  \\'   r(\\)\(4   r*\\
\)   \(4   r+S\RX                  S\\)   4S jr-S\RX                  S\\)   S\RX                  4S jr.S\RX                  S\RX                  4S jr/S\RX                  S\
\+   S\
\*   4S jr0Sr1S SSSSSSSSSSSS\1S4SS.S\	\)\RX                  4   S\'S\2S \2S!\
\\)      S"\2S#\
\)   S$\2S\
\\)      S%\)S&\2S\\RX                  \24   4S' jjjr3 " S( S)\"Rh                  5      r5S* r6g! \ aO    \R6                  SSSS/r\" \" S	S
R;                  \5       S3SS95        S SKr\R>                  " \5        S SKr GNlf = f)+    N)ListDictUnionOptionalTupleSequence)Text)printz-mpipinstallonnxruntimezInstalling onnxruntime by ` z`, please wait for a moment..bold magentastyle   )
model_info)model_checking)versionmodelreturnc                 n    U R                   R                   Vs/ s H  oR                  PM     nnU$ s  snf N)graphoutputname)r   optoutput_namess      V/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/onnxsim/onnx_simplifier.pyget_output_namesr    '   s/    (-(:(:;(:HH(:L; <s   2unused_outputc                 *   Un[        U 5      nU H  nXC;  d  M
  [        SU S35      e   [        R                  " U R                  R
                  5       H:  nUR                  U;   d  M  U R                  R
                  R                  U5        M<     U $ )Nz%The model doesn't have output named "")r    RuntimeErrorcopydeepcopyr   r   r   remove)r   r!   unused_output_namesr   unused_output_namegraph_outputs         r   remove_unused_outputr+   ,   s     (#E*L1189K8LAN  2
 ekk&8&89 33KK%%l3 : L    c                 >   U R                   R                   Vs/ s H  oR                  PM     nn[        R                  " U R                   R
                  5       H:  nUR                  U;   d  M  U R                   R
                  R                  U5        M<     U $ s  snf r   )r   initializerr   r%   r&   inputr'   )r   xinitializer_namesgraph_inputs       r   remove_initializer_from_inputr3   <   sv    ).)@)@A)@A)@A}}U[[%6%6700KK$$[1 8 L	 Bs   Binput_shapesc                 n  ^ Uc  g S[         R                  S[        [         R                     4S jmS[         R                  S[        [           4U4S jjnU" U 5      nS U;   a(  [        U5      S:X  a  US    XS   '   US 	 O[        S5      eU H"  nXC;  d  M
  [        SR                  U5      5      e   U$ )	Nr   r   c                     U R                   R                   Vs/ s H  oR                  PM     nnU R                   R                   Vs/ s H  o3R                  U;  d  M  UPM     sn$ s  snf s  snf r   )r   r.   r   r/   )r   r0   r1   ipts       r   
get_inputs1check_and_update_input_shapes.<locals>.get_inputsH   sY    -2[[-D-DE-DVV-DE${{00V0HHDU4U0VV FVs   A(A-A-c                 T   > T" U 5       Vs/ s H  oR                   PM     nnU$ s  snf r   )r   )r   r7   input_namesr8   s      r   get_input_names6check_and_update_input_shapes.<locals>.get_input_namesL   s+    +5e+<=+<Cxx+<= >s   %r   r   zhThe model has more than 1 inputs, please use the format "input_name:dim0,dim1,...,dimN" in --input-shapez'The model doesn't have input named "{}")onnx
ModelProtor   ValueInfoProtostrlenr$   format)r   r4   r<   r;   r0   r8   s        @r   check_and_update_input_shapesrD   D   s    W$// Wd43F3F.G Wt 49  "%(K|{q +7+=LQ(T"z| |:AA!DF F 
 r,   z1.5GBTF)r4   check_nperform_optimizationskip_fuse_bnskipped_optimizersdynamic_input_shape
custom_libinclude_subgraphtensor_size_thresholdmutable_initializerc          
      r   U
(       a  [        [        SSS95        Ub  [        [        SSS95        UnUnU(       d  SnOUc  / nU(       a  Ub  UR                  S5        [        U [        5      (       a  [
        R                  " U 5      n Uc  0 n[        X5      n[        X5      nUR                  5        H|  u  nnU R                  R                   H\  nUR                  U:X  d  M  [        UR                  R                  R                  R                   5       H  u  nnUU   Ul        M     M^     M~     Ub  [%        X5      n U(       d  U R&                  S:  a  [)        U 5      n S[        S	[*        4S
 jnU" U5      nUS:  a  [-        S5      e U R/                  5       n[0        R2                  " UUU(       + U(       + U5      n[5        U5      S:X  a  [-        S5      e[
        R6                  " U5      n[8        R:                  " UXXYU5      nUU4$ ! [,        [
        R<                  R>                  R@                  4 Gav    [        S5        [B        RD                  " 5        n[
        RF                  " [H        RJ                  " U 5      [L        RN                  RQ                  US5      SS9  [0        RR                  " [L        RN                  RQ                  US5      [L        RN                  RQ                  US5      UU(       + U(       + U5      n[8        R:                  " [L        RN                  RQ                  US5      [L        RN                  RQ                  US5      XX5      n[
        R                  " [L        RN                  RQ                  US5      5      nSSS5         UU4$ ! , (       d  f        WW4$ = ff = f)aT  
:param model: onnx ModelProto object or file path
:param check_n: The simplified model will be checked for `check_n` times by random inputs
:param perform_optimization: Whether to run onnx optimizer on the model
:param skip_fuse_bn: Skip fuse_bn_into_conv onnx optimizer
:param overwrite_input_shapes: If the model has dynamic input shape, user must pass a fixed input shape
        for generating random inputs and checking equality.
:param test_input_shapes: If the model has dynamic input shape, user must pass a fixed input shape
        for generating random inputs and checking equality.
:param skipped_optimizers: Skip some specific onnx optimizers
:param skip_constant_folding: Skip constant folding
:param skip_shape_inference: Skip shape inference (sometimes shape inference will crash)
:param input_data: Feed custom input data for checking if needed
:param dynamic_input_shape: Deprecated. Not needed anymore.
:param custom_lib: onnxruntime custom ops's shared library
:param include_subgraph: Simplify subgraph (e.g. true graph and false graph of "If" operator) instead of only the main graph
:param unused_output: name of unused outputs that will be eliminated from the model
:param input_shapes: Deprecated. Please use `overwrite_input_shapes` and/or `test_input_shapes` instead.
:return: A tuple (simplified model, success(True) or failed(False))
zWARNING: The argument `dynamic_input_shape=True` is not needed any more, onnxsim can now support dynamic input shapes natively, please refer to the latest documentation. An error will be raised in the future.bold redr   NzWARNING: The argument `input_shapes` is deprecated. Please use `overwrite_input_shapes` and/or `test_input_shapes` instead. An error will be raised in the future.fuse_bn_into_conv   sizer   c                 6   SSSSSS.nU R                  5       n [        R                  " SU 5      (       d  [        R                  " SS	U 5      n U R	                  5        Vs/ s H  o"R                  5       PM     snu  p4[        [        U5      X   -  5      $ s  snf )
Nr   i   i   i   @l        )BKBMBGBTBr   z
([KMGT]?B)z \1)upperrematchsubsplitstripintfloat)rR   unitsstringnumberunits        r   
parse_sizesimplify.<locals>.parse_size   s|    uEeLzz|xxd##66-6D59ZZ\B\6\B5=,-- Cs   Biz-tensor_size_threshold should be less than 2GBr   z Simplified model larger than 2GBza[bold magenta]Simplified model larger than 2GB. Trying to save as external data...[/bold magenta]z
model.onnxT)save_as_external_datazopt.onnx)*r
   r	   append
isinstancerA   r>   loadrD   itemsr   r/   r   	enumeratetypetensor_typeshapedim	dim_valuer+   
ir_versionr3   r_   
ValueErrorSerializeToStringCsimplifyrB   load_from_stringr   compareonnx_cpp2py_exportcheckerValidationErrortempfileTemporaryDirectorysaver%   r&   ospathjoinsimplify_path)r   rE   rF   rG   overwrite_input_shapestest_input_shapesrH   skip_constant_foldingskip_shape_inference
input_datarI   rJ   rK   r!   rL   rM   r4   r   input_shaper7   irp   re   model_bytesmodel_opt_bytes	model_optcheck_ok
tmpdirnames                               r   rv   rv   d   sR   P  c 	
  u 	
 ".(!		#*6!!"56%		% %!#:'5" 499;k;;$$Cxx4'(<(<(B(B(F(FGFAs$/NCM H % <
  $U:5#3#3q#8-e4. . . ''<=|+HII%H--/**%%$$!
 1$?@@))/:	!))u'8j
4 h/ //77GGH Hqr((*jIIe$Z6&*
 Z6Z4"))((%H &--Z4Z6JH
 		"'',,z:"FGI' +*( h) +*( h/Hs-   A=H AN6 D3N N6 
N2	*N62N6c                   ,    \ rS rSrS\S\\   4S jrSrg)PyModelExecutor   	model_str
inputs_strc                 4   [         R                  " 5       nUR                  U5        S n[        XB5      n[        [         R                  R
                  U5      nUR                  R                   Vs/ s H  owR                  PM     nn[        [        X5      5      n	[        R                  " 5       n
[        R                  " S5      U
l        SU
l        [        R                   " UR#                  5       U
S/S9nUR%                  5        Vs/ s H  owR                  PM     nn[        R&                  " 5       nSUl        UR)                  XUS9nU Vs/ s H0  n[         R                  R+                  U5      R#                  5       PM2     sn$ s  snf s  snf s  snf )Nc                 R    [         R                  " 5       nUR                  U 5        U$ r   )r>   TensorProtoParseFromString)tp_strtps     r   deserialize_tp+PyModelExecutor.Run.<locals>.deserialize_tp   s#    !!#Bv&Ir,   r      CPUExecutionProvider)sess_options	providers)run_options)r>   r?   r   mapnumpy_helperto_arrayr   r/   r   dictziprtSessionOptionsGraphOptimizationLevelgraph_optimization_levellog_severity_levelInferenceSessionrt   get_outputs
RunOptionsrun
from_array)selfr   r   r   r   	input_tps
input_arrsr0   r;   inputsr   sessr   r   output_arrss                  r   RunPyModelExecutor.Run   sQ   !i(	
 3	**33Y?
',{{'8'89'8!vv'89c+23((*020I0I!0L-*+'""##%%-.

 )-(8(8(:;(:1(:;mmo)*&hh|hMIT
ITAD((+==?
 	
 : <
s   1F
F7F N)__name__
__module____qualname____firstlineno__rA   r   r   __static_attributes__r   r,   r   r   r      s    
S 
d3i 
r,   r   c                     [         R                  " 5       n U R                  SSS9  U R                  SSS9  U R                  SSS[        S	S
9  U R                  SSSS9  U R                  SSSS9  U R                  SS[        SS9  U R                  SSSS9  U R                  SS[        SS9  U R                  SS[        SS9  U R                  SS[        SS9  U R                  SS[        SS9  U R                  S S!SS9  U R                  S"S#SS9  U R                  S$S%SS9  U R                  S&S'[        SS9  U R                  S(S%[        S)9  U R                  S*S+SS9  U R                  S,S-[        SS9  U R                  S.S/[        S0[
        SS1S29  U R                  S3S4SS9  U R                  S5S6SS9  U R                  S7S8S9S:[        R                  -   S;9  U R                  5       nUR                  (       a  [        [        S<S=S>95        UR                  (       a  [        [        S?S=S>95        UR                  b  UR                  b   eUR                  (       a$  [        [        S@S=S>95        UR                  Ul        UR                  (       a  [        [        SAS=S>95        UR                  b  UR                   b   eUR                  (       a$  [        [        SBS=S>95        UR                  Ul        UR                   c  / Ul        O [#        UR                   5      S	:X  a  S Ul        UR$                  (       a(  UR                   b  UR                   R'                  SC5        UR                   c  SDOSEnSF nU" UR(                  5      nU" UR                  5      nUR*                  (       a  [,        R.                  " 5       n[0        R2                  " 5       n[0        R4                  R6                  Ul        UR:                  Ul        [0        R>                  " UR@                  USG/SH9n[B        RD                  " UR:                  5      n	O [B        RD                  " UR@                  5      n	URF                  [
        :X  aB  U	RH                  RJ                   H(  n
U
RL                  SI;   d  M  [        [        SJSKS>95          O   URN                  (       d  [Q        U	RH                  RR                   Vs/ s H  oR:                  PM     sn5      n[Q        U	RH                  RT                   Vs/ s H  oR:                  PM     sn5      n[#        URW                  U5      5      S	:  a  [        [        SLSKS>95        S nURX                  bf  0 nURX                   HT  nUR[                  SM5      nSMR]                  US SN 5      USN   nnUR_                  U[`        RD                  " U5      05        MV     [        SO5        [c        U	URd                  USDUUUR                   URf                  URh                  USDURj                  UR                  URl                  URF                  URN                  5      u  nn URn                  (       d"  [B        Rp                  " UURr                  5        O[u        SP5      eU(       a#  [        SS5        [        R                  " U	U5        g [        ST5        [        SU5        [        R                  " U	U5        [        R                  " SV5        g s  snf s  snf ! [t         a    [v        Rx                  R{                  URr                  5      SQ-   n[v        Rx                  R}                  U5      (       a  [v        R~                  " U5        [B        Rp                  " [        R                  " U5      URr                  SESEUSR9   GN!f = f)WNinput_modelzInput ONNX model)helpoutput_modelzOutput ONNX modelrE   z8Check whether the output is correct with n random inputs?r   )r   nargsrm   defaultz--enable-fuse-bnzEThis option is deprecated. Fusing bn into conv is enabled by default.
store_true)r   actionz--skip-fuse-bnz Skip fusing batchnorm into conv.z--skip-optimizationzSkip all ONNX optimizers or some of them. To skip all optimizers, use `onnxsim a.onnx b.onnx --skip-optimization`. To skip some of optimizers, use something like `onnxsim a.onnx b.onnx --skip-optimization fuse_bn_into_conv fuse_pad_into_pool`.*)r   rm   r   z--skip-constant-foldingzSkip constant foldingz--input-shapezMThis argument has been renamed to --overwrite-input-shape, please refer to it+z--overwrite-input-shapeaC  Overwrite the input shape. The format is "input_name:dim0,dim1,...,dimN" or simply "dim0,dim1,...,dimN" when there is only one input, for example, "data:1,3,224,224" or "1,3,224,224". Note: you might want to use some visualization tools like netron to make sure what the input name and dimension ordering (NCHW or NHWC) is.z--test-input-shapea  The input shape to generated random inputs for test, useful when the input shape is dynamic. The format is "input_name:dim0,dim1,...,dimN" or simply "dim0,dim1,...,dimN" when there is only one input, for example, "data:1,3,224,224" or "1,3,224,224". Note: you might want to use some visualization tools like netron to make sure what the input name and dimension ordering (NCHW or NHWC) is.z--skip-optimizerz(Deprecated. Refer to --skip-optimizationz--skip-shape-inferencezSkip shape inferencez!--enable-onnxruntime-optimizationz:Enable ONNX Runtime's ORT_ENABLE_BASIC level optimization.z--dynamic-input-shapez Deprecated. Not needed any more.z--input-data-pathz|input data, The value should be "input_name1:xxx1.bin"  "input_name2:xxx2.bin ...", input data should be a binary data file.z--custom-lib)r   rm   z--include-subgraphzyExperimental feature. Simplify subgraph (e.g. true graph and false graph of "If" operator) instead of only the main graphz--unused-outputz=Name of unused outputs that will be eliminated from the modelz--no-large-tensora[  Some ops like Tile and ConstantOfShape can produce large tensor and make the model size much larger. Specifying this flag to skip folding these ops, with loss of some optimization chances. It can be followed with a threshold, for example, --no-large-tensor 1M or --no-large-tensor 100KB. A simple '--no-large-tensor' means '--no-large-tensor 1KB'.1KBrL   )r   rm   constr   r   destz--mutable-initializera  By ONNX specification, initializers can also serve as inputs. This allows users to overwrite their values during runtime, but some useful optimizations like fuse-conv-and-bn will not be applicable anymore. In almost all cases, having an initializer that is also an input is unintended (usually caused by a out-dated PyTorch). So onnxsim treats all initializers immutable to enabling all optimizations. If it is not wanted, you can specify '--mutable-initializer' to disable this behavior.z--save-as-external-datazSave parameters as external data. This will make the .onnx file much smaller, but the .onnx file will depend on the external data file (.data).z-vz	--versionr   zonnxsim )r   r   zWARNING: "--enable-fuse-bn" is not needed any more, because fuse bn is enabled by default. "--enable-fuse-bn" flag is ignored now and will raise an error in the future.rO   r   zWARNING: "--dynamic-input-shape" is not needed any more, onnxsim v0.4 now handles dynamic input shapes automatically. "--dynamic-input-shape" flag is ignored now and will raise an error in the future.zXWARNING: "--input-shape" is renamed to "--overwrite-input-shape". Please use it instead.z@WARNING: subgraph optimization is not supported in v0.4 for now.zWWARNING: "--skip-optimizer" is renamed to "--skip-optimization". Please use it instead.rP   FTc           
      J   0 nU b  U  H  nSU;  a-  [        [        [        UR                  S5      5      5      US '   M6  UR                  S5      nSR	                  US S 5      [        [        [        US   R                  S5      5      5      pTUR                  XE05        M     U$ )N:,)listr   r_   r]   r   update)
shapes_argshapesr0   piecesr   ro   s         r   parse_shapesmain.<locals>.parse_shapes  s    !a<#'C(>#?F4LWWS\F"%((s#%&*3sF2J4D4DS4I+J&K  MM4-0   r,   r   )r   )TileConstantOfShapezYour model contains "Tile" ops or/and "ConstantOfShape" ops. Folding these ops can make the simplified model much larger. If it is not expected, please specify "--no-large-tensor" (which will lose some optimization chances)r   a  Your model contains initializers that are also inputs. This is usually caused by an out-dated PyTorch. onnxsim treats all initializers immutable to enabling all optimizations. If it is not wanted, please specify "--mutable-initializer" to disable this behavior.r   r   zSimplifying...rg   z.data)rg   all_tensors_to_one_filelocationzFinish! Here is the difference:zCheck failed. Please be careful to use the simplified model, or try specifying "--skip-fuse-bn" or "--skip-optimization" (run "onnxsim -h" for details).z,Here is the difference after simplification:r   )FargparseArgumentParseradd_argumentr_   rA   !DEFAULT_TENSOR_SIZE_THRESHOLDHOLDr   
parse_argsenable_fuse_bnr
   r	   rI   r   overwrite_input_shaperK   skip_optimizerskip_optimizationrB   rG   rh   test_input_shapeenable_onnxruntime_optimizationr|   NamedTemporaryFiler   r   r   ORT_ENABLE_BASICr   r   optimized_model_filepathr   r   r>   rj   rL   r   nodeop_typerM   setr.   r/   intersectioninput_data_pathr]   r   r   nprv   rE   r   r   rJ   r!   rg   r~   r   rs   r   r   basenameexistsr'   r%   r&   r   print_simplifying_infosysexit)parserargsrF   r   r   r   tmp_filer   _r   r   r0   r1   r;   input_tensorsr   r   datar   r   external_data_paths                        r   mainr     s   $$&F
,>?
-@A
G   T  
 A,    C	   18OXde
\	   ! S	    U	   7	    '=l   +I  
 /  
  L	   ?c    I  
 L	    k1$    x  

 ! _  

 k)ZRYRaRaEabD { 	
  [ 	
   ,1K1K1WXXj 	
 &*%5%5"R 	
 ##/D4J4J4VWWi 	
 "&!4!4%!#	T##	$	) "&T33?%%&9:$($:$:$B5 %T%:%:;)$*D*DE++..0((*020I0I0Z0Z-08- 0 0,KaJbc		(--(		$**+!!%FFKK$$D||:: z,  % ##1H1H I1HA1H IJ5;;+<+<=+<a66+<=> --k:;a? \( M'%%AWWS\F&"+.r
$D  $!67 &
 

"""!!""  !Ix&
))IIi!2!23455 /0))%; g	
 	<=))%;G !J=V  
  WW--d.?.?@7J77>>,--II()		MM)$"&$('	

s%   *\#\(2\ \ B&__)7r   r%   r   r   rZ   r|   typingr   r   r   r   r   r   	rich.textr	   richr
   numpyr   r>   onnx.checkeronnx.helperonnx.shape_inferenceonnx.numpy_helperr   r   ImportError
executablecommandr   
subprocess
check_callonnxsim.onnxsim_cpp2py_exportonnxsim_cpp2py_exportru    r   r   r   r_   TensorShaperA   TensorShapesTensorShapesWithOptionalKeyr?   r    r+   r3   rD   r   boolrv   ModelExecutorr   r   r   r,   r   <module>r     s{     	 
 	  ? ?         *    3iC$%"8C=+#=> DOO S	 
??+3C=	__  T__  QlHm rz  |H  sI : %, !
 !%.2 % $"-1!B %!G$ %Gdoo%&GG G 	G !c+G G G G HSM*G G  !G& 4??D !'GT
aoo 
>Ks  ~~tUI}EG	$,SXXg->,??\]es
tu'"s   E* *AF?>F?