
    BVhH              #       `   d Z ddlZddlZddlZddlmZmZmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddlm!Z" dejF                  de$fdZ%dddddejL                  jN                  fdeejP                     deejL                     dee)   de)dee)   dee)   de)de$de)d e)d!e)d"eejT                     d#ee)   d$eee)      d%e+dejP                  f d&Z,d'e)d(e$dejP                  fd)Z-d'e)d(e$dejT                  fd*Z.d+ Z/ddddej`                  ejL                  jN                  fd'ee)   d,e)d(e$dee)   de)dee)   dee)   de)de$de)d e)d!e)d-ede$e)f   d#ee)   d$e)d%e+dejP                  f"d.Z1d/ Z2d0 Z3e4d1k(  r e3        yy)2ay  Converts checkpoint variables into Const ops in a standalone GraphDef file.

This script is designed to take a GraphDef proto, a SaverDef proto, and a set of
variable values stored in a checkpoint file, and output a GraphDef with all of
the variable ops converted into const ops containing the values of the
variables.

It's useful to do this when we need to load a single file in C++, especially in
environments like mobile or embedded where we may not have access to the
RestoreTensor ops and file loading calls that they rely on.

An example of command-line usage is:
bazel build tensorflow/python/tools:freeze_graph && \
bazel-bin/tensorflow/python/tools/freeze_graph \
--input_graph=some_graph_def.pb \
--input_checkpoint=model.ckpt-8361242 \
--output_graph=/tmp/frozen_graph.pb --output_node_names=softmax

You can also look at freeze_graph_test.py for an example of how to use it.

    N)ListOptionalUnion)app)text_format)	graph_pb2)meta_graph_pb2)	saver_pb2)checkpoint_management)session)convert_to_constants)importer)gfile)loader)tag_constants)saved_model_utils)py_checkpoint_reader)saversessreturnc                     | j                   j                         D ]:  }|j                  j                  d      s|j                  j	                  d      s: y y)zjDetermines if the graph has any variables.

  Args:
    sess: TensorFlow Session.

  Returns:
    Bool.
  Variable
VariableOpFT)graphget_operationstype
startswithendswith)r   ops     T/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/tools/freeze_graph.py_has_no_variablesr!   ;   sK     JJ%%' b	ww*%)9)9,)G 
     input_graph_definput_saver_definput_checkpointoutput_node_namesrestore_op_namefilename_tensor_nameoutput_graphclear_devicesinitializer_nodesvariable_names_whitelistvariable_names_denylistinput_meta_graph_definput_saved_model_dirsaved_model_tagscheckpoint_versionc           
          ~~|s&t        j                  |      st        d|z   dz         |st        d      |r?|r#|j                  j                  D ]	  }d|_         n| r| j                  D ]	  }d|_         | rt        j                  | d      }t        j                         5 }|r+t        j                  ||      }|j                  ||       n|r^t        j                  |d      }|j                  ||       |r|j                  |j                  d	d      j!                  d
             n_|r|g }t#        j$                  |||       n@i }t'        j(                  |      }|j+                         }|j,                  j/                         D cg c]U  }|j1                         D ]@  }t3        j4                  d|j6                        r|j6                  j!                  d      d   B W }}}d}|D ]<  	 |j,                  j9                  dz         }t;        fd|D              rd}||<   > 	 t        j                  ||      }|j                  ||       |r0|j                  |j                  d	d      j!                  d
             |	r!|	j                  d	d      j!                  d
      nd}	|
r!|
j                  d	d      j!                  d
      nd}
|rDtC        jD                  ||j                  |j                  d	d      j!                  d
      |	|
      }n9tC        jD                  || |j                  d	d      j!                  d
      |	|
      }ddd       |rBtG        jH                  |d      5 }|jK                  jM                  d             ddd       |S S c c}}w # t<        $ r Y w xY w# t>        $ r*}|rt        d      tA        |      rt        d      |d}~ww xY w# 1 sw Y   xY w# 1 sw Y   S xY w)a  Converts all variables in a graph and checkpoint into constants.

  Args:
    input_graph_def: A `GraphDef`.
    input_saver_def: A `SaverDef` (optional).
    input_checkpoint: The prefix of a V1 or V2 checkpoint, with V2 taking
      priority.  Typically the result of `Saver.save()` or that of
      `tf.train.latest_checkpoint()`, regardless of sharded/non-sharded or
      V1/V2.
    output_node_names: The name(s) of the output nodes, comma separated.
    restore_op_name: Unused.
    filename_tensor_name: Unused.
    output_graph: String where to write the frozen `GraphDef`.
    clear_devices: A Bool whether to remove device specifications.
    initializer_nodes: Comma separated string of initializer nodes to run before
      freezing.
    variable_names_whitelist: The set of variable names to convert (optional, by
      default, all variables are converted).
    variable_names_denylist: The set of variable names to omit converting to
      constants (optional).
    input_meta_graph_def: A `MetaGraphDef` (optional),
    input_saved_model_dir: Path to the dir with TensorFlow 'SavedModel' file and
      variables (optional).
    saved_model_tags: Group of comma separated tag(s) of the MetaGraphDef to
      load, in string format (optional).
    checkpoint_version: Tensorflow variable file format (saver_pb2.SaverDef.V1
      or saver_pb2.SaverDef.V2)

  Returns:
    Location of the output_graph_def.
  zInput checkpoint 'z' doesn't exist!z=You need to supply the name of a node to --output_node_names.r#   )name)	saver_defwrite_versionT)r+    ,Nz
/part_\d+/:r   Fz:0c              3   &   K   | ]  }|v  
 y wN ).0r4   keys     r    	<genexpr>z/freeze_graph_with_def_protos.<locals>.<genexpr>   s     FFs   )var_listr6   zModels containing partition variables cannot be converted from checkpoint files. Please pass in a SavedModel using the flag --input_saved_model_dir.zuNo variables were found in this model. It is likely the model was frozen previously. You cannot freeze a graph twice.)r-   variable_names_blacklistwb)deterministic)'r   checkpoint_exists
ValueError	graph_defnodedevicer   import_graph_defr   Session	saver_libSaverrestoreimport_meta_graphrunreplacesplitr   loadr   NewCheckpointReaderget_variable_to_shape_mapr   r   valuesresearchr4   get_tensor_by_nameanyKeyError	TypeErrorr!   r   convert_variables_to_constantsr   GFilewriteSerializeToString)r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   rG   _r   r   restorerr@   readervar_to_shape_mapr   tensorall_partition_variable_nameshas_partition_vareoutput_graph_deffr>   s                                 @r    freeze_graph_with_def_protosrj   J   sE   ` + 
'<'N'N( //2DD  

G  &0055 $	!&& $ !!/;A `Doo#3Ee mmD*+	,,
dh t-.	"**3399#>?			!kk$(*?@h#778HIf99; JJ--/&		& YY}fkk2 ++

C
 
#&
#&" &  ! 	#	::00t<&F)EFF $
 	-?
, mmD*+	"**3399#>? $ 	!((b177<  # 	 ''R066s;  -LL


(
(

#
#C
,
2
23
7#;#: .LL



#
#C
,
2
23
7#;#:u`F 	\4	( FAgg00t0DEF 
	_&  	 	   2  t$H 
 '#_` `HF 
su   'C1O7AN+2
O7=4N11O79ODO7="P+O71	N>:O7=N>>O7	O4
%O//O44O77P Pinput_graphinput_binaryc                 j   t        j                  |       st        d| z   dz         t        j                         }|rdnd}t        j
                  | |      5 }|r |j                  |j                                n$t        j                  |j                         |       ddd       |S # 1 sw Y   |S xY w)z2Parses input tensorflow graph into GraphDef proto.zInput graph file '' does not exist!rbrN)
r   ExistsIOErrorr   GraphDefr]   ParseFromStringreadr   Merge)rk   rl   r$   moderi   s        r    _parse_input_graph_protorx      s     
k	"
&47JJ
KK&&(/3${{;% 3%%affh//2	3
 
3
 
s   AB((B2c                    t        j                  |       st        d| z   dz         t        j                         }|rdnd}t        j
                  | |      5 }|r |j                  |j                                n$t        j                  |j                         |       ddd       t        d| z          |S # 1 sw Y   xY w)z6Parses input tensorflow graph into MetaGraphDef proto.zInput meta graph file 'rn   ro   rp   NzLoaded meta graph file ')r   rq   rr   r	   MetaGraphDefr]   rt   ru   r   rv   print)rk   rl   r/   rw   ri   s        r    _parse_input_meta_graph_protor|     s     
k	"
+k9<OO
PP'4463${{;% 8**16684"67	8
 "[01	8 8s   AB66B?c                 j   t        j                  |       st        d| z   dz         |rdnd}t        j                  | |      5 }t	        j
                         }|r |j                  |j                                n$t        j                  |j                         |       ddd       |S # 1 sw Y   S xY w)z2Parses input tensorflow Saver into SaverDef proto.zInput saver file 'rn   ro   rp   N)
r   rq   rr   r]   r
   SaverDefrt   ru   r   rv   )input_saverrl   rw   ri   r5   s        r    _parse_input_saver_protor      s    	k	"
&47JJ
KK3${{;% -""$I)),- 
- 
s   AB((B2r   input_meta_graphc                 F   d}|r!t        j                  ||      j                  }n| rt        | |      }d}|rt	        ||      }d}|rt        ||      }t        |||||||||	|
||||j                  dd      j                  d      D cg c]  }|s|	 c}|      S c c}w )a  Converts all variables in a graph and checkpoint into constants.

  Args:
    input_graph: A `GraphDef` file to load.
    input_saver: A TensorFlow Saver file.
    input_binary: A Bool. True means input_graph is .pb, False indicates .pbtxt.
    input_checkpoint: The prefix of a V1 or V2 checkpoint, with V2 taking
      priority.  Typically the result of `Saver.save()` or that of
      `tf.train.latest_checkpoint()`, regardless of sharded/non-sharded or
      V1/V2.
    output_node_names: The name(s) of the output nodes, comma separated.
    restore_op_name: Unused.
    filename_tensor_name: Unused.
    output_graph: String where to write the frozen `GraphDef`.
    clear_devices: A Bool whether to remove device specifications.
    initializer_nodes: Comma separated list of initializer nodes to run before
      freezing.
    variable_names_whitelist: The set of variable names to convert (optional, by
      default, all variables are converted),
    variable_names_denylist: The set of variable names to omit converting to
      constants (optional).
    input_meta_graph: A `MetaGraphDef` file to load (optional).
    input_saved_model_dir: Path to the dir with TensorFlow 'SavedModel' file and
      variables (optional).
    saved_model_tags: Group of comma separated tag(s) of the MetaGraphDef to
      load, in string format.
    checkpoint_version: Tensorflow variable file format (saver_pb2.SaverDef.V1
      or saver_pb2.SaverDef.V2).

  Returns:
    String that is the location of frozen GraphDef.
  Nr7   r#   r8   )r2   )	r   get_meta_graph_defrF   rx   r|   r   rj   rP   rQ   )rk   r   rl   r&   r'   r(   r)   r*   r+   r,   r-   r.   r   r0   r1   r2   r$   r/   r%   tags                       r    freeze_graphr   .  s    d /'::/i  .{LIO8, /.{LIO	%&..sB7==cBJscsJ+
  Ks   	B"B"c                 <   |j                   dk(  rt        j                  j                  }nB|j                   dk(  rt        j                  j                  }nt        d|j                   z        t        |j                  |j                  |j                  |j                  |j                  |j                  |j                  |j                  |j                  |j                   |j"                  |j$                  |j&                  |j(                  |j*                  |       y )N      z3Invalid checkpoint version (must be '1' or '2'): %d)r2   r
   r~   V1V2rE   r   rk   r   rl   r&   r'   r(   r)   r*   r+   r,   r-   r.   r   r0   r1   )unused_argsflagsr2   s      r    mainr     s    
""++..1$"++..
=

"
"	#    $$##!!!r"   c                     t        j                         } | j                  ddd        | j                  dt        dd       | j                  dt        dd	       | j                  d
t        dd       | j                  dt
        dd       | j                  dt        dd       | j                  dddddd       | j                  dt        dd       | j                  dt        dd       | j                  dt        dd       | j                  dddddd        | j                  d!t        dd"       | j                  d#t        dd$       | j                  d%t        dd&       | j                  d't        dd(       | j                  d)t        dd*       | j                  d+t        d,d-       | j                         \  }fd.}t        j                  |t        j                  d/   g|z   0       y1)2zMain function of freeze_graph.r   boolc                 (    | j                         dk(  S )Ntrue)lower)vs    r    <lambda>zrun_main.<locals>.<lambda>  s    AGGI,? r"   z--input_graphr#   z#TensorFlow 'GraphDef' file to load.)r   defaulthelpz--input_saverzTensorFlow saver file to load.z--input_checkpointz"TensorFlow variables file to load.z--checkpoint_versionr   zTensorflow variable file formatz--output_graphzOutput 'GraphDef' file name.z--input_binary?TFz-Whether the input files are in binary format.)nargsconstr   r   r   z--output_node_namesz.The name of the output nodes, comma separated.z--restore_op_namezsave/restore_allzg      The name of the master restore operator. Deprecated, unused by updated       loading code.
      z--filename_tensor_namezsave/Const:0zl      The name of the tensor holding the save path. Deprecated, unused by       updated loading code.
      z--clear_devicesz(Whether to remove device specifications.z--initializer_nodeszAComma separated list of initializer nodes to run before freezing.z--variable_names_whitelistz      Comma separated list of variables to convert to constants. If specified,       only those variables will be converted to constants.      z--variable_names_denylistzN      Comma separated list of variables to skip converting to constants.      z--input_meta_graphz'TensorFlow 'MetaGraphDef' file to load.z--input_saved_model_dirz@Path to the dir with TensorFlow 'SavedModel' file and variables.z--saved_model_tagsservez      Group of tag(s) of the MetaGraphDef to load, in string format,      separated by ','. For tag-set contains multiple tags, all tags       must be passed in.      c                     t        |       S r;   )r   )r   r   s    r    r   zrun_main.<locals>.<lambda>  s    [% 8 r"   r   )r   argvN)argparseArgumentParserregisteradd_argumentstrintparse_known_argsr   rO   sysr   )parserunparsedmy_mainr   s      @r    run_mainr     s|   ""$&//&&"?@0	   	+	   	/	   	,	   	)	   	:   	;	   	 
	   	
	   	5   	N	   	"
	   	!
	   	4	   	M	   	
	  	 ++-/%8'''wchhqk]X56r"   __main__)5__doc__r   rV   r   typingr   r   r   abslr   google.protobufr   tensorflow.core.frameworkr   tensorflow.core.protobufr	   r
   tensorflow.python.checkpointr   tensorflow.python.clientr   tensorflow.python.frameworkr   r   tensorflow.python.platformr   tensorflow.python.saved_modelr   r   tensorflow.python.toolsr   tensorflow.python.trainingr   r   rK   rJ   r   r!   r~   r   rs   r   rz   r   rj   rx   r|   r   SERVINGr   r   r   __name__r<   r"   r    <module>r      s  *  	 
 ( (  ' / 3 . > , < 0 , 0 7 5 ; 9GOO  2 %'#%BF+/,0'0033ri001ri001r smr 	r
 c]r #3-r r r r "r !r #>#>#>?r $C=r tCy)r r  !rj$( $(  "2 %'#%/3+/)11'0033!Q#QQ Q sm	Q
 Q c]Q #3-Q Q Q Q "Q !Q D$O,Q $C=Q Q  !Q" #Qh<z7z z
* r"   