
    BVh                        d Z ddlZddlZddlZddlZddlZddlmZ ddlmZ ddl	m
Z
 ddl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dl&m*Z* ddl&m+Z+ ddl,m-Z- ddl,m.Z. ddl/m0Z0 ddl1m2Z2 dZ3 e4g d      Z5 ejl                  ddd      Z7 ejp                  d d!d"      Z9 ejl                  d#dd$      Z: ejl                  d%dd&      Z; ejp                  d'd!d(      Z< ejl                  d)d*d+      Z= ejl                  d,d*d-      Z> ejl                  d.d*d/      Z? ejl                  d0dd1      Z@ ejp                  d2d!d3      ZA ejp                  d4d!d5      ZB ejl                  d6dd7      ZC ejp                  d8d!d9      ZD ejp                  d:d!d;      ZE ejl                  d<dd=      ZF ejl                  d>dd?      ZG ej                  d@dAdB      ZI ej                  dCdDg dEdFG      ZK ej                  dHdIdJ      ZL ejp                  dKd!dL      ZM ejl                  dMddN      ZN ejl                  dOe+j                  dP      ZP ejl                  dQddR      ZQ ejl                  dSd*dT      ZR ej                         dUk(  r ejl                  dVd*dW      ZTn ejl                  dVdXdY      ZT ejl                  dZd*d[      ZU ejl                  d\dd]      ZV ejl                  d^d_d`      ZWdgg dadgg dbg dcd\gddZXde ZYdf ZZdg Z[dh Z\di Z]dj Z^dk Z_dl Z`ddmZadn ZbddoZcddpZddq Zedr Zfds Zgdt Zhdu Zi	 	 	 	 ddvZjdw ZkddxZldy Zmdz Znd{ Zod| Zpd} Zqd~ Zrd Zsd Ztd Zud Zvd Zwd Zxd Zyd Zzd Z{d Z|d Z}e~dk(  r e}        yy)zCommand-line interface to inspect and execute a graph in a SavedModel.

For detailed usages and examples, please refer to:
https://www.tensorflow.org/guide/saved_model#cli_to_inspect_and_execute_savedmodel

    N)app)flags)argparse_flags)example_pb2)	types_pb2)
config_pb2)session)local_cli_wrapper)def_function)function)
meta_graph)ops)tensor_spec)file_io)
tf_logging)load)load_options)loader)save)signature_constants)saved_model_aot_compile)saved_model_utils)tpu)collections_abczchttps://github.com/tensorflow/tensorflow/blob/master/tensorflow/compiler/xla/debug_options_flags.cc)	WriteFileReadFilePrintV2dirz$Directory containing the SavedModel.)namedefaulthelpallFzBIf set, outputs all available information in the given SavedModel.tag_setzKComma-separated set of tags that identify variant graphs in the SavedModel.signature_defz^Specifies a SignatureDef (by key) within the SavedModel to display input(s) and output(s) for.list_opszDIf set, will output ops used by a MetaGraphDef specified by tag_set.inputs zSpecifies input data files to pass to numpy.load(). Format should be '<input_key>=<filename>' or '<input_key>=<filename>[<variable_name>]', separated by ';'. File formats are limited to .npy, .npz, or pickle.input_exprsaE  Specifies Python literal expressions or numpy functions. Format should be "<input_key>='<python_expression>'", separated by ';'. Numpy can be accessed with 'np'. Note that expressions are passed to literal_eval(), making this flag susceptible to code injection. Overrides duplicate input keys provided with the --inputs flag.input_exampleszSpecifies tf.train.Example objects as inputs. Format should be '<input_key>=[{{feature0:value_list,feature1:value_list}}]', where input keys are separated by ';'. Overrides duplicate input keys provided with the --inputs and --input_exprs flags.outdirz7If specified, writes CLI output to the given directory.	overwritez4If set, overwrites output file if it already exists.tf_debugz~If set, uses the Tensorflow Debugger (tfdbg) to watch intermediate Tensors and runtime GraphDefs while running the SavedModel.workerzFIf specified, runs the session on the given worker (bns or gRPC path).init_tpuznIf set, calls tpu.initialize_system() on the session. Should only be set if the specified worker is a TPU job.use_tfrtz6If set, runs a TFRT session, instead of a TF1 session.op_denylistzIf specified, detects and reports the given ops. List of ops should be comma-separated. If not specified, the default list of ops is [WriteFile, ReadFile, PrintV2]. To specify an empty list, pass in the empty string.
output_dirz$Output directory for the SavedModel.max_workspace_size_bytesi    zUThe maximum temporary GPU memory which the TensorRT engine can use at execution time.precision_modeFP32)r4   FP16INT8z4TensorRT data precision. One of FP32, FP16, or INT8.)r   r    enum_valuesr!   minimum_segment_size   zVThe minimum number of nodes required for a subgraph to be replaced in a TensorRT node.convert_tf1_modelz+Support TensorRT conversion for TF1 models.output_prefixzROutput directory + filename prefix for the resulting header(s) and object file(s).signature_def_keyz#SavedModel SignatureDef key to use.checkpoint_pathz?Custom checkpoint to use. Uses SavedModel variables by default.variables_to_feedaj  Names of the variables that will be fed into the SavedModel graph. Pass in '' to feed no variables, 'all' to feed all variables, or a comma-separated list of variable names. Variables not fed will be frozen. *NOTE* Variables passed here must be set *by the user*. These variables will NOT be frozen, and their values will be uninitialized in the compiled object.s390xtarget_triplezTriple identifying a target variation, containing information suchas processor architecture, vendor, operating system, and environment. Defaults to ''.zx86_64-pc-linuxzTriple identifying a target variation, containing information such as processor architecture, vendor, operating system, and environment. Defaults to 'x86_64-pc-linux'.
target_cpuz{Target CPU name for LLVM during AOT compilation. Examples include 'x86_64', 'skylake', 'haswell', 'westmere', '' (unknown).	cpp_classa  The name of the generated C++ class, wrapping the generated function. Format should be [[<optional_namespace>::],...]<class_name>, i.e. the same syntax as C++ for specifying a class. This class will be generated in the given namespace(s), or, if none are specified, the global namespace.multithreadingFalsezEnable multithreading in the compiled computation. Note that with this flag enabled, the resulting object files may have external dependencies on multithreading libraries, such as 'Abseil'.)r   r#   r$   )r   r1   r#   )r   r;   r#   )showrunscanconvertfreeze_modelaot_compile_cpuc           	          t        j                  |       }t        d       t        |      D ](  }t        ddj	                  t        |            z         * y)zPrints the tag-sets stored in SavedModel directory.

  Prints all the tag-sets for MetaGraphs stored in SavedModel directory.

  Args:
    saved_model_dir: Directory containing the SavedModel to inspect.
  z5The given SavedModel contains the following tag-sets:z%r, N)r   get_saved_model_tag_setsprintsortedjoin)saved_model_dirtag_setsr#   s      W/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/tools/saved_model_cli.py_show_tag_setsrT      sK     77H(?@! -g	$6'?+
+,-    c                 R    t        t        j                  | j                              S )zReturns a set of the ops in the MetaGraph.

  Returns the set of all the ops used in the MetaGraphDef indicated by the
  tag_set stored in SavedModel directory.

  Args:
    meta_graph_def: MetaGraphDef to list the ops of.

  Returns:
    A set of ops.
  )setmeta_graph_libops_used_by_graph_def	graph_defmeta_graph_defs    rS   _get_ops_in_metagraphr]      s      
^11.2J2JK	LLrU   c                 `    t        |       }t        d| j                  j                  z  |       y )Nz9The MetaGraph with tag set %s contains the following ops:)r]   rN   meta_info_deftags)r\   all_ops_sets     rS   _show_ops_in_metagraph_mgdrb   
  s.    %n5+A$$))*rU   c                 F    t        j                  | |      }t        |       y)av  Prints the ops in the MetaGraph.

  Prints all the ops used in the MetaGraphDef indicated by the tag_set stored in
  SavedModel directory.

  Args:
    saved_model_dir: Directory containing the SavedModel to inspect.
    tag_set: Group of tag(s) of the MetaGraphDef in string format, separated by
      ','. For tag-set contains multiple tags, all tags must be passed in.
  N)r   get_meta_graph_defrb   )rQ   r#   r\   s      rS   _show_ops_in_metagraphre     s"     %778?A.^,rU   c                     t        | |      }t        d       t        |j                               D ]  }t        d|z          y)a  Prints the keys for each SignatureDef in the SignatureDef map.

  Prints the list of SignatureDef keys from the SignatureDef map specified by
  the given tag-set and SavedModel directory.

  Args:
    saved_model_dir: Directory containing the SavedModel to inspect.
    tag_set: Group of tag(s) of the MetaGraphDef to get SignatureDef map from,
        in string format, separated by ','. For tag-set contains multiple tags,
        all tags must be passed in.
  zQThe given SavedModel MetaGraphDef contains SignatureDefs with the following keys:zSignatureDef key: "%s"N)get_signature_def_maprN   rO   keys)rQ   r#   signature_def_mapr<   s       rS   _show_signature_def_map_keysrj   #  sL     ,OWE 	 !"3"8"8":; :	
$'8
89:rU   c           	          || j                   vr8t        d| ddj                  | j                   j                                      | j                   |   j                  S )a  Gets TensorInfo for all inputs of the SignatureDef.

  Returns a dictionary that maps each input key to its TensorInfo for the given
  signature_def_key in the meta_graph_def

  Args:
    meta_graph_def: MetaGraphDef protocol buffer with the SignatureDef map to
        look up SignatureDef key.
    signature_def_key: A SignatureDef key string.

  Returns:
    A dictionary that maps input tensor keys to TensorInfos.

  Raises:
    ValueError if `signature_def_key` is not found in the MetaGraphDef.
  zCould not find signature "z". Please choose from: rL   )r$   
ValueErrorrP   rh   r&   r\   r<   s     rS   +_get_inputs_tensor_info_from_meta_graph_defrn   6  sh    $ n:::

$%6$77N99^116689
:	<= = 
	%	%&7	8	?	??rU   c                 4    | j                   |   j                  S )a  Gets TensorInfos for all outputs of the SignatureDef.

  Returns a dictionary that maps each output key to its TensorInfo for the given
  signature_def_key in the meta_graph_def.

  Args:
    meta_graph_def: MetaGraphDef protocol buffer with the SignatureDefmap to
    look up signature_def_key.
    signature_def_key: A SignatureDef key string.

  Returns:
    A dictionary that maps output tensor keys to TensorInfos.
  )r$   outputsrm   s     rS   ,_get_outputs_tensor_info_from_meta_graph_defrq   O  s     
	%	%&7	8	@	@@rU   c                   
 t        | |      }t        | |      }d|z  

fd} |d       t        |j                               D ]  \  }} |d|z         t	        ||dz          !  |d       t        |j                               D ]  \  }}	 |d|z         t	        |	|dz          !  |d| j
                  |   j                  z         y	)
aR  Prints input and output TensorInfos.

  Prints the details of input and output TensorInfos for the SignatureDef mapped
  by the given signature_def_key.

  Args:
    meta_graph_def: MetaGraphDef to inspect.
    signature_def_key: A SignatureDef key string.
    indent: How far (in increments of 2 spaces) to indent each line of output.
    c                 "    t        | z          y NrN   s
indent_strs    rS   in_printz*_show_inputs_outputs_mgd.<locals>.in_prints      	*q.rU   zBThe given SavedModel SignatureDef contains the following input(s):z  inputs['%s'] tensor_info:   zCThe given SavedModel SignatureDef contains the following output(s):z  outputs['%s'] tensor_info:zMethod name is: %sN)rn   rq   rO   items_print_tensor_infor$   method_name)r\   r<   indentinputs_tensor_infooutputs_tensor_inforz   	input_keyinput_tensor
output_keyoutput_tensorry   s             @rS   _show_inputs_outputs_mgdr   a  s     C' E') f}* OP!'(:(@(@(B!C /i,y89|VAX./   #)*=*C*C*E#F 0j--
:;}fQh/0 ''(9:FFG HrU   c                 J    t        j                  | |      }t        |||       y)a  Prints input and output TensorInfos.

  Prints the details of input and output TensorInfos for the SignatureDef mapped
  by the given signature_def_key.

  Args:
    saved_model_dir: Directory containing the SavedModel to inspect.
    tag_set: Group of tag(s) of the MetaGraphDef, in string format, separated by
      ','. For tag-set contains multiple tags, all tags must be passed in.
    signature_def_key: A SignatureDef key string.
    indent: How far (in increments of 2 spaces) to indent each line of output.
  N)r   rd   r   )rQ   r#   r<   r   r\   s        rS   _show_inputs_outputsr     s(     %77w. >+<fErU   c                 8   d}|D ]  }||j                  d      z  } |syt        dd       	 t        j                         j	                         5  t        j
                  | t        j                  d      	      }ddd       t        t        j                        j                  |            }t        |d       }|D ]  \  }}	g }
t        |	t         j"                        r|
j%                  |	       n;t        |	t&        j(                        r |
j+                  |	j-                                npt        d|z         t        |
d       }
t/        |
d      D ]w  \  }}d\  }}|j0                  r|j0                  \  }}n|j2                  r|j2                  }|r&t        d|z         t        d       t5        |d       |sjt5        |dd       y  y# 1 sw Y   ]xY w# t        $ r+}d
t        |      v rd}nd}t        d| d       Y d}~yd}~ww xY w)zPrints the callable concrete and polymorphic functions of the Saved Model.

  Args:
    saved_model_dir: Directory containing the SavedModel to inspect.
    meta_graphs: Already-extracted MetaGraphDef of the SavedModel.
  Fobject_graph_defNz
Concrete Functions:r'   endT)experimental_skip_checkpoint)optionszOp type not registeredz-the existence of custom ops in the SavedModelzunknown reasonsz! N/A (could not be listed due to )c                     | j                   S ru   r   xs    rS   <lambda>z)_show_defined_functions.<locals>.<lambda>  s
    AFF rU   keyz
  Function Name: '%s'c                     | j                   S ru   r   r   s    rS   r   z)_show_defined_functions.<locals>.<lambda>  s
    !&& rU   r|   )NNz    Option #%dz      Callable with:   r   zNamed Argument)HasFieldrN   ops_libGraph
as_defaultr   r   LoadOptions	Exceptionstrlistr   _AugmentedGraphViewlist_childrenrO   
isinstancedefunConcreteFunctionappendr   Functionextend._list_all_concrete_functions_for_serialization	enumeratestructured_input_signature_arg_keywords_print_args)rQ   meta_graphshas_object_graph_defr\   trackable_objecteerrorchildrenr   childconcrete_functionsindexconcrete_functionargskwargss                  rS   _show_defined_functionsr     s    # HnN334FGGH	
R(		#	#	% O
**MOO 
/0}%&(( H"23( 8kdE%//0&	E<00	1

>
>
@B 	
%
,- 28HI$-.@!$D 8  ldF		5	5(CCf** !..	&'$%D#	F,Q788!O O 
 3q6)=ee	-eWA
67
s/   "G% ,G=G% G"G% %	H.!HHc           
        	 d|z  	d }d	fd	}t        | d      D ]  \  }}|dk(  r |d||fz         t        |t              r |d|z         5t        |t        j                        r-t        |dz   dz  |j                  dt        |      z          |t        |t        j                        rat        |t              sQ |d	t        |      j                  z          |d
d       |D ]  }t        d ||      z  d        t        d       t        |t              ro |d	t        |      j                  z          |dd       |j                         D ]'  \  }}t        dt        |      d ||      d       ) t        d       v |d	t        |      j                  z          |dt        |      z          y)zFormats and prints the argument of the concrete functions defined in the model.

  Args:
    arguments: Arguments to format print.
    argument_type: Type of arguments.
    indent: How far (in increments of 2 spaces) to indent each line of
     output.
  rs   c                 J    dt        | t              z  }|t        |       z   |z   S )N')r   r   )value	is_quotess     rS   _maybe_add_quotesz&_print_args.<locals>._maybe_add_quotes  s'    z%--Is5z!I--rU   c                 &    t        | z   |       y )Nr   rv   )rx   r   ry   s     rS   rz   z_print_args.<locals>.in_print  s    	*q.c"rU   r|   r   z%s #%dz  %sz: z  DType: %sz
  Value: [r'   r   z%srL   z]z
  Value: {r   z': z}z  Value: %sN)
)r   r   r   r   
TensorSpecrN   r   reprr   Iterabledicttype__name__r}   )
	argumentsargument_typer   r   rz   r   elementr   r   ry   s
            @rS   r   r     s    f}*.# ")Q/ -neW{x=%001'3v 	G[33	4VaZ4gllDM"JJK
Wo66
7$'}tG}5556|$ 9%d&u--489Gn	GT	"}tG}5556|$!--/ M,3c#h(9%(@AtLMGn}tG}5556}s7|+,--rU   c           	         d|z  fd} |dt         j                  j                         D ci c]  \  }}||
 c}}| j                     z          | j                  j
                  rd}nO| j                  j                  D cg c]  }t        |j                         }}dj                  |      }d|z   dz   } |d|z           |d	| j                  z          y
c c}}w c c}w )zPrints details of the given tensor_info.

  Args:
    tensor_info: TensorInfo object to be printed.
    indent: How far (in increments of 2 spaces) to indent each line output
  rs   c                 "    t        | z          y ru   rv   rw   s    rS   rz   z$_print_tensor_info.<locals>.in_print  r{   rU   z    dtype: unknown_rankrL   (r   z    shape: z
    name: N)r   DataTyper}   dtypetensor_shaper   dimr   sizerP   r   )	tensor_infor   rz   r   r   shaper   dimsry   s	           @rS   r~   r~     s     f}* = ) 2 2 8 8 :<e 3J <<G<M<MOO P **E%0%=%=%A%ABcCMBDBIIdOE%K#E
=5 !
<+***+< Cs   CC#c                    t        j                  |       }t        |j                  d       D ]  }|j                  j
                  }t        ddj                  |      z         dj                  |      }|j                  }t        |j                               D ]!  }t        d|z   dz          t        ||d	       # t        |        t        | |j                         y
)zPrints tag-set, ops, SignatureDef, and Inputs/Outputs of SavedModel.

  Prints all tag-set, ops, SignatureDef and Inputs/Outputs information stored in
  SavedModel directory.

  Args:
    saved_model_dir: Directory containing the SavedModel to inspect.
  c                 @    t        | j                  j                        S ru   )r   r_   r`   r[   s    rS   r   z_show_all.<locals>.<lambda>"  s    n&B&B&G&G!H rU   r   zF
MetaGraphDef with tag-set: '%s' contains the following SignatureDefs:rL   ,z
signature_def['z']:r|   r   N)r   read_saved_modelrO   r   r_   r`   rN   rP   r$   rh   r   rb   r   )rQ   saved_modelr\   r#   ri   r<   s         rS   	_show_allr     s     "22?C+
H /n **//G	 248IIg4FG H hhwG&44#$5$:$:$<= L #44v=>~/@KL ~./ /;+B+BCrU   c                 .    t        j                  | |      S )a\  DEPRECATED: Use saved_model_utils.get_meta_graph_def instead.

  Gets MetaGraphDef from SavedModel. Returns the MetaGraphDef for the given
  tag-set and SavedModel directory.

  Args:
    saved_model_dir: Directory containing the SavedModel to inspect or execute.
    tag_set: 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.

  Raises:
    RuntimeError: An error when the given tag-set does not exist in the
        SavedModel.

  Returns:
    A MetaGraphDef corresponding to the tag-set.
  )r   rd   )rQ   r#   s     rS   rd   rd   1  s    & 
	-	-ow	GGrU   c                 F    t        j                  | |      }|j                  S )a  Gets SignatureDef map from a MetaGraphDef in a SavedModel.

  Returns the SignatureDef map for the given tag-set in the SavedModel
  directory.

  Args:
    saved_model_dir: Directory containing the SavedModel to inspect or execute.
    tag_set: Group of tag(s) of the MetaGraphDef with the SignatureDef map, in
        string format, separated by ','. For tag-set contains multiple tags, all
        tags must be passed in.

  Returns:
    A SignatureDef map that maps from string keys to SignatureDefs.
  )r   rd   r$   )rQ   r#   r   s      rS   rg   rg   G  s"     !33OWM*		!	!!rU   c                 f    t        | j                  d      D cg c]  }|s|	 c}      }|S c c}w )Nr   )rW   split)r0   opset_of_denylisted_opss      rS   _get_op_denylist_setr   Z  s1    K,=,=c,BIbbrIJ	 Js   ..c                     t        t        j                  | j                              }||z  }|r$t	        d| j
                  j                  z  |       yt	        d| j
                  j                  z  |       y)zScans meta_graph_def and reports if there are ops on denylist.

  Print ops if they are on denylist, or print success if no denylisted ops
  found.

  Args:
    meta_graph_def: MetaGraphDef protocol buffer.
    op_denylist: set of ops to scan for.
  z@MetaGraph with tag set %s contains the following denylisted ops:zFMetaGraph with tag set %s does not contain the default denylisted ops:N)rW   rX   rY   rZ   rN   r_   r`   )r\   r0   ops_in_metagraphdenylisted_opss       rS   scan_meta_graph_defr   `  sx     **>+C+CDF!11.	J$$))	*+9; 
P

&
&
+
+	,-8:rU   c
                    t        j                  | |      }
t        |
|      }|j                         D ];  }||vst	        d|dddj                  |j                               z   dz   d       |j                         D ci c]  \  }}||   j                  | }}}t        |
|      }t        |j                               }|D cg c]  }||   j                   }}d}|rIt        j                  d       t        j                  t        j                  j                  d      	      }t        j                   |t#        j$                         |
      5 }|r.t'        d       |j)                  t+        j,                                t/        j0                  ||j3                  d      |        |	rt5        j6                  |      }|j)                  ||      }t9        |      D ]  \  }}||   }t'        d|d|       |st:        j<                  j?                  |      st;        j@                  |       t:        j<                  j                  ||dz         }|s-t:        j<                  jC                  |      rtE        d|z        tG        jH                  ||       t'        d|d|        	 ddd       yc c}}w c c}w # 1 sw Y   yxY w)a  Runs SavedModel and fetch all outputs.

  Runs the input dictionary through the MetaGraphDef within a SavedModel
  specified by the given tag_set and SignatureDef. Also save the outputs to file
  if outdir is not None.

  Args:
    saved_model_dir: Directory containing the SavedModel to execute.
    tag_set: Group of tag(s) of the MetaGraphDef with the SignatureDef map, in
        string format, separated by ','. For tag-set contains multiple tags, all
        tags must be passed in.
    signature_def_key: A SignatureDef key string.
    input_tensor_key_feed_dict: A dictionary maps input keys to numpy ndarrays.
    outdir: A directory to save the outputs to. If the directory doesn't exist,
        it will be created.
    overwrite_flag: A boolean flag to allow overwrite output file if file with
        the same name exists.
    worker: If provided, the session will be run on the worker.  Valid worker
        specification is a bns or gRPC path.
    init_tpu: If true, the TPU system will be initialized after the session
        is created.
    use_tfrt: If true, TFRT session will be used.
    tf_debug: A boolean flag to use TensorFlow Debugger (TFDBG) to observe the
        intermediate Tensor values and runtime GraphDefs while running the
        SavedModel.

  Raises:
    ValueError: When any of the input tensor keys is not valid.
    RuntimeError: An error when output file already exists and overwrite is not
    enabled.
  "z/" is not a valid input key. Please choose from z", "z, or use --show option.NzUsing TFRT session.T)r/   )experimental)graphconfigzInitializing TPU System ...r   )	feed_dictzResult for output key z:
z.npyzXOutput file %s already exists. Add "--overwrite" to overwrite the existing output files.zOutput z is saved to )%r   rd   rn   rh   rl   rP   r}   r   rq   rO   logginginfor   ConfigProtoExperimentalr	   Sessionr   r   rN   rF   r   initialize_systemr   r   r   r
   LocalCLIDebugWrapperSessionr   ospathisdirmakedirsexistsRuntimeErrornpr   )rQ   r#   r<   input_tensor_key_feed_dictr*   overwrite_flagr-   r.   r/   r,   r\   r   input_key_namer   tensorinputs_feed_dictr   output_tensor_keys_sorted
tensor_keyoutput_tensor_names_sortedr   sessrp   ioutputoutput_tensor_keyoutput_full_paths                              rS   run_saved_model_with_feed_dictr  x  s   T %778?A.
 C') 3779 Pn// 3-?-D-D-F!GG#MOP PP 499;
#v ""F* 
 E') %%8%=%=%?@ 2 
 *%**   
 &LL&'##++88$8GIFvW]]_VD !?)* hhs$$&'
KKgmmC(/:::4@dhh1=MhNGw' ?	63A6/@&IJ 
ww}}V$
++f
77<<0AF0JK "''..1A"B,.>?@ @ 	 &),=,<> 	?%?!? !?' !? !?s    J=
KB*KB/KKc                    i }| j                  d      }t        t        |      D ]  }t        j                  d|      }|r5|j                  d      |j                  d      f||j                  d      <   Pt        j                  d|      }|r&|j                  d      df||j                  d      <   t        d|z         |S )	ai  Parses input arg into dictionary that maps input to file/variable tuple.

  Parses input string in the format of, for example,
  "input1=filename1[variable_name1],input2=filename2" into a
  dictionary looks like
  {'input_key1': (filename1, variable_name1),
   'input_key2': (file2, None)}
  , which maps input keys to a tuple of file name and variable name(None if
  empty).

  Args:
    inputs_str: A string that specified where to load inputs. Inputs are
    separated by semicolons.
        * For each input key:
            '<input_key>=<filename>' or
            '<input_key>=<filename>[<variable_name>]'
        * The optional 'variable_name' key will be set to None if not specified.

  Returns:
    A dictionary that maps input keys to a tuple of file name and variable name.

  Raises:
    RuntimeError: An error when the given input string is in a bad format.
  ;z!([^=]+)=([^\[\]]+)\[([^\[\]]+)\]$   r9   r|   z([^=]+)=([^\[\]]+)$Nzu--inputs "%s" format is incorrect. Please follow"<input_key>=<filename>", or"<input_key>=<filename>[<variable_name>]")r   filterboolrematchgroupr   )
inputs_str
input_dict
inputs_raw	input_rawr  s        rS   preprocess_inputs_arg_stringr    s    2 *$*$
+ EiHH99EE#(;;q>5;;q>#AjQ  hh-y9e	%*[[^T%9
5;;q>"8:CDE 	EE" 
rU   c                 6   i }t        t        | j                  d            D ]S  }d| vrt        d| z        |j                  dd      \  }}|r	 t	        j
                  |      ||<   Ft        |      ||<   U |S # t        $ r}t        d| d      |d}~ww xY w)a  Parses input arg into dictionary that maps input key to python expression.

  Parses input string in the format of 'input_key=<python expression>' into a
  dictionary that maps each input_key to its python expression.

  Args:
    input_exprs_str: A string that specifies python expression for input keys.
      Each input is separated by semicolon. For each input key:
        'input_key=<python expression>'
    safe: Whether to evaluate the python expression as literals or allow
      arbitrary calls (e.g. numpy usage).

  Returns:
    A dictionary that maps input keys to their values.

  Raises:
    RuntimeError: An error when the given input string is in a bad format.
  r  =zV--input_exprs "%s" format is incorrect. Please follow"<input_key>=<python expression>"r|   zExpression "z " is not a valid python literal.N)r  r  r   r   astliteral_evalr   eval)input_exprs_strsafer  r  r   exprexcs          rS   !preprocess_input_exprs_arg_stringr#    s    & *$ 5 5c :; )i
/! =?NO P Pooc1-OItL # 0 0 6
9 #4jj) 
  L4& @ACHK	LLs   A::	BBBc           	          t        |       }|j                         D ]K  \  }}t        |t              st	        d|dt        |            |D cg c]  }t        |       c}||<   M |S c c}w )a  Parses input into dict that maps input keys to lists of tf.Example.

  Parses input string in the format of 'input_key1=[{feature_name:
  feature_list}];input_key2=[{feature_name:feature_list}];' into a dictionary
  that maps each input_key to its list of serialized tf.Example.

  Args:
    input_examples_str: A string that specifies a list of dictionaries of
    feature_names and their feature_lists for each input.
    Each input is separated by semicolon. For each input key:
      'input=[{feature_name1: feature_list1, feature_name2:feature_list2}]'
      items in feature_list can be the type of float, int, long or str.

  Returns:
    A dictionary that maps input keys to lists of serialized tf.Example.

  Raises:
    ValueError: An error when the given tf.Example is not a list.
  z6tf.Example input must be a list of dictionaries, but "" is )r#  r}   r   r   rl   r   _create_example_string)input_examples_strr  r   example_listexamples        rS   $preprocess_input_examples_arg_stringr*  >  s    ( 11CD*!+!1!1!3 ilD)l+-. . 8D,3w'Jy 
s   A,c                    t        j                         }| j                         D ]  \  }}t        |t              st        d|d|dt        |            t        |d   t              r=|j                  j                  |   j                  j                  j                  |       t        |d   t              rZ|j                  j                  |   j                  j                  j                  |D cg c]  }|j                  d       c}       t        |d   t               r>|j                  j                  |   j                  j                  j                  |       Bt        |d   t"              r>|j                  j                  |   j$                  j                  j                  |       t        dt        |d         d|d   d       |j'                         S c c}w )	z7Create a serialized tf.example from feature dictionary.z"feature value must be a list, but z: "r%  r   utf8zType z for value z' is not supported for tf.train.Feature.)r   Exampler}   r   r   rl   r   floatfeaturesfeature
float_listr   r   r   
bytes_listencodebytesint
int64_listSerializeToString)example_dictr)  feature_namefeature_listfs        rS   r&  r&  ^  s   !'$0$6$6$8 4 lLlD)$lD4FH I I,q/5)|,77==DD
	LOS	)|,77==DD%1
2188F
24	LOU	+|,77==DD
	LOS	)|,77==DD
 Q ,q/34 4#4( 
	"	"	$$ 3s   6G*
c                 F   i }t        |       }t        |      }t        |      }|j                         D ]  \  }\  }}	t	        j
                  t        j                  |d      d      }
|	r[t        |
t        j                        r"t        j                  d|d|	d       |
||<   s|	|
v r	|
|	   ||<   t        d|d|	d	      t        |
t        j                  j                  j                        r4|
j                   }t#        |      d
k7  rt        d|z        |
|d      ||<   |
||<    |j                         D ]&  \  }}||v rt        j                  d|z         |||<   ( |j                         D ]&  \  }}||v rt        j                  d|z         |||<   ( |S )a	  Parses input arg strings and create inputs feed_dict.

  Parses '--inputs' string for inputs to be loaded from file, and parses
  '--input_exprs' string for inputs to be evaluated from python expression.
  '--input_examples' string for inputs to be created from tf.example feature
  dictionary list.

  Args:
    inputs_str: A string that specified where to load inputs. Each input is
        separated by semicolon.
        * For each input key:
            '<input_key>=<filename>' or
            '<input_key>=<filename>[<variable_name>]'
        * The optional 'variable_name' key will be set to None if not specified.
        * File specified by 'filename' will be loaded using numpy.load. Inputs
            can be loaded from only .npy, .npz or pickle files.
        * The "[variable_name]" key is optional depending on the input file type
            as descripted in more details below.
        When loading from a npy file, which always contains a numpy ndarray, the
        content will be directly assigned to the specified input tensor. If a
        variable_name is specified, it will be ignored and a warning will be
        issued.
        When loading from a npz zip file, user can specify which variable within
        the zip file to load for the input tensor inside the square brackets. If
        nothing is specified, this function will check that only one file is
        included in the zip and load it for the specified input tensor.
        When loading from a pickle file, if no variable_name is specified in the
        square brackets, whatever that is inside the pickle file will be passed
        to the specified input tensor, else SavedModel CLI will assume a
        dictionary is stored in the pickle file and the value corresponding to
        the variable_name will be used.
    input_exprs_str: A string that specifies python expressions for inputs.
        * In the format of: '<input_key>=<python expression>'.
        * numpy module is available as np.
    input_examples_str: A string that specifies tf.Example with dictionary.
        * In the format of: '<input_key>=<[{feature:value list}]>'

  Returns:
    A dictionary that maps input tensor keys to numpy ndarrays.

  Raises:
    RuntimeError: An error when a key is specified, but the input file contains
        multiple numpy ndarrays, none of which matches the given key.
    RuntimeError: An error when no key is specified, but the input file contains
        more than one numpy ndarrays.
  rb)modeT)allow_picklezInput file z& contains a single ndarray. Name key "z
" ignored.z& does not contain variable with name "z".r|   zYInput file %s contains more than one ndarrays. Please specify the name of ndarray to use.r   zrinput_key %s has been specified with both --inputs and --input_exprs options. Value in --input_exprs will be used.z\input_key %s has been specified in multiple options. Value in --input_examples will be used.)r  r#  r*  r}   r   r   r   FileIOr   ndarrayr   warnr   libnpyioNpzFilefileslen)r  r  r'  tensor_key_feed_dictr&   r(   r)   input_tensor_keyfilenamevariable_namedatavariable_name_listpy_expr_evaluatedr)  s                 rS   !load_inputs_from_input_arg_stringrO  x  s   ` '
3&1/B+78JK.5;\\^ 611=777>>(6TJD 	D"**	%(	) 26-.D 373F
/
0() ) 
D"&&,,..	/!ZZ!"a',.678 8 266H6K1L-.15-.;6@ .9->->-@ ?))//ll;=MNO .?)*? $2#7#7#9 5//ll+-=>? .5)*5 
rU   c                  2   t         j                  rt        t        j                         yt        j                  5t
        j                  rt        d       t        t        j                         yt
        j                  r(t        t        j                  t        j                         t        j                  )t        t        j                  t        j                         yt        t        j                  t        j                  t        j                         y)z#Function triggered by show command.Nz7--list_ops must be paired with a tag-set or with --all.)
_SMCLI_ALLr   r   
_SMCLI_DIR_SMCLI_TAG_SET_SMCLI_LIST_OPSrN   rT   re   _SMCLI_SIGNATURE_DEFrj   r    rU   rS   rE   rE     s     j #			GHZ%%&			z//1E1EF		#	#	+$Z%5%5~7K7KLn224H4N4N	PrU   c                     t         j                  s+t        j                  st        j                  st	        d      t        t         j                  t        j                  t        j                        } t        t        j                  t        j                  t        j                  | t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  
       y)zFunction triggered by run command.

  Raises:
    AttributeError: An error when neither --inputs nor --input_exprs is passed
    to run command.
  zLAt least one of --inputs, --input_exprs or --input_examples must be required)r-   r.   r/   r,   N)_SMCLI_INPUTSr   _SMCLI_INPUT_EXPRS_SMCLI_INPUT_EXAMPLESAttributeErrorrO  r  rR  rS  rU  _SMCLI_OUTDIR_SMCLI_OVERWRITE_SMCLI_WORKER_SMCLI_INIT_TPU_SMCLI_USE_TFRT_SMCLI_TF_DEBUG)rH  s    rS   rF   rF     s     

 &&#))
	  ;!!# !    $$$$$$
&rU   c                     t         j                  rdt        j                  rTt        t	        j
                  t        j                  t         j                        t        t        j                               yt         j                  rAt        t	        j
                  t        j                  t         j                        t               yt	        j                  t        j                        } t        j                  r5| j                  D ]%  }t        |t        t        j                               ' y| j                  D ]  }t        |t                y)z#Function triggered by scan command.N)rS  r   _SMCLI_OP_DENYLISTr   r   rd   rR  r   _OP_DENYLISTr   r   )r   r\   s     rS   rG   rG     s    066,,n22	4/5568 ,,n22	4
 $44Z5E5EFK'33 L.N01C1I1IJ	LL (33 :.NL9:rU   c                     ddl m}  t        j                  s| j                  j                  t        j                  t        j                  t        j                        }	  | j                  dt        j                  t        j                  j                  d      d|j                         }|j                          |j%                  t&        j                         y| j)                  ddd	t        j                  t        j                  t        j                  d
t        j                  t        j                  j                  d      t&        j                  
       y# t        $ r }t!        dj#                  |            |d}~ww xY w)z1Function triggered by 'convert tensorrt' command.r   )trt_convert)r2   r3   r8   r   )input_saved_model_dirinput_saved_model_tagsz+{}. Try passing "--convert_tf1_model=True".N)output_saved_model_dirr|   T)max_batch_sizer2   r3   r8   is_dynamic_oprg  rh  ri  rV  )#tensorflow.python.compiler.tensorrtrf  _SMCLI_CONVERT_TF1_MODELr   DEFAULT_TRT_CONVERSION_PARAMS_replace_SMCLI_MAX_WORKSPACE_SIZE_BYTES_SMCLI_PRECISION_MODE_SMCLI_MINIMUM_SEGMENT_SIZETrtGraphConverterV2rR  rS  r   _asdictrH   r   r   formatr   _SMCLI_OUTPUT_DIRcreate_inference_graph)trtparams	converterr"  s       rS   convert_with_tensorrtr{  0  sL    E	!	'	'..77!@!F!F,228>> 8 @FN)#))  * 0 0!/!5!5!;!;C!@ NNi  NN*;*A*ANB!@!F!F,228>>(..-3399#>066  
8  N
7
>
>s
CEJMNNs    AE 	F'FFc                     t         j                  xs. t        j                  j	                  t
        j                  d      } t        j                  sg }nCt        j                  j                         dk(  rd}nt        j                  j                  d      }t        j                  | t        j                  t
        j                  t        j                        t        j                  |t        j                         y)z+Function triggered by freeze_model command.variables/variablesr"   Nr   )r=   r\   r<   r>   r;   )_SMCLI_CHECKPOINT_PATHr   r   r   rP   rR  _SMCLI_VARIABLES_TO_FEEDlowerr   r   rI   r   rd   rS  _SMCLI_SIGNATURE_DEF_KEY_SMCLI_OUTPUT_PREFIXr=   r>   s     rS   rI   rI   S  s     "" ?	j&&(=	>  
"	'	'%%++-6066<<SA&&%&99


N002066)(..0rU   c                     t         j                  xs. t        j                  j	                  t
        j                  d      } t        j                  sg }nCt        j                  j                         dk(  rd}nt        j                  j                  d      }t        j                  | t        j                  t
        j                  t        j                        t        j                  |t        j                  t         j                  t"        j                  t$        j                  t&        j                  j                         dv	       y)z.Function triggered by aot_compile_cpu command.r}  r"   Nr   )r;  false0)	r=   r\   r<   r>   r;   r@   rA   rB   rC   )r~  r   r   r   rP   rR  r  r  r   r   aot_compile_cpu_meta_graph_defr   rd   rS  r  r  _SMCLI_TARGET_TRIPLE_SMCLI_TARGET_CPU_SMCLI_CPP_CLASS_SMCLI_MULTITHREADINGr  s     rS   rJ   rJ   h  s     "" ?	j&&(=	>  
"	'	'%%++-6066<<SA88%&99


N002066)(..(.."(( &&

%
%
+
+
-5H
HKrU   c                 x    d}| j                  d|t        j                        }|j                  t               y)zAdd parser for `show`.aB  Usage examples:
To show all tag-sets in a SavedModel:
$saved_model_cli show --dir /tmp/saved_model

To show all available SignatureDef keys in a MetaGraphDef specified by its tag-set:
$saved_model_cli show --dir /tmp/saved_model --tag_set serve

For a MetaGraphDef with multiple tags in the tag-set, all tags must be passed in, separated by ';':
$saved_model_cli show --dir /tmp/saved_model --tag_set serve,gpu

To show all inputs and outputs TensorInfo for a specific SignatureDef specified by the SignatureDef key in a MetaGraph.
$saved_model_cli show --dir /tmp/saved_model --tag_set serve --signature_def serving_default

To show all ops in a MetaGraph.
$saved_model_cli show --dir /tmp/saved_model --tag_set serve --list_ops

To show all available information in the SavedModel:
$saved_model_cli show --dir /tmp/saved_model --allrE   descriptionformatter_classfuncN)
add_parserargparseRawTextHelpFormatterset_defaultsrE   )
subparsersshow_msgparser_shows      rS   add_show_subparserr    sE    ; ( %%33 & 5+ %rU   c                 x    d}| j                  d|t        j                        }|j                  t               y)zAdd parser for `run`.a  Usage example:
To run input tensors from files through a MetaGraphDef and save the output tensors to files:
$saved_model_cli show --dir /tmp/saved_model --tag_set serve \
   --signature_def serving_default \
   --inputs input1_key=/tmp/124.npz[x],input2_key=/tmp/123.npy \
   --input_exprs 'input3_key=np.ones(2)' \
   --input_examples 'input4_key=[{"id":[26],"weights":[0.5, 0.5]}]' \
   --outdir=/out

For more information about input file format, please see:
https://www.tensorflow.org/guide/saved_model_cli
rF   r  r  N)r  r  r  r  rF   )r  run_msg
parser_runs      rS   add_run_subparserr    s@    B' $$(2O2O % Q*s#rU   c                 x    d}| j                  d|t        j                        }|j                  t               y)zAdd parser for `scan`.a  Usage example:
To scan for default denylisted ops in SavedModel:
$saved_model_cli scan --dir /tmp/saved_model
To scan for a specific set of ops in SavedModel:
$saved_model_cli scan --dir /tmp/saved_model --op_denylist OpName,OpName,OpName
To scan a specific MetaGraph, pass in --tag_set
rG   r  r  N)r  r  r  r  rG   )r  scan_msgparser_scans      rS   add_scan_subparserr    sC    B( %%33 & 5+ %rU   c                     d}| j                  d|t        j                        }|j                  ddd      }|j                  dd	t        j                        }|j	                  t
        
       y)zAdd parser for `convert`.zUsage example:
To convert the SavedModel to one that have TensorRT ops:
$saved_model_cli convert \
   --dir /tmp/saved_model \
   --tag_set serve \
   --output_dir /tmp/saved_model_trt \
   tensorrt 
rH   r  zconversion methodszvalid conversion methodsz)the conversion to run with the SavedModeltitler  r!   tensorrtz;Convert the SavedModel with Tensorflow-TensorRT integrationr  N)r  r  r  add_subparsersr  r{  )r  convert_msgparser_convertconvert_subparsersparser_convert_with_tensorrts        rS   add_convert_subparserr    s    "+ ((33 ) 5. &44 ,6 5 8 "4!>!>O33 "? "5 ++1F+GrU   c                     dj                  g d      }| j                  d|t        j                        }|j	                  t
               y)zAdd parser for `freeze_model`.r   )Usage example:z4To freeze a SavedModel in preparation for tfcompile:z$saved_model_cli freeze_model \   --dir /tmp/saved_model \   --tag_set serve \z+   --output_prefix /tmp/saved_model_xla_aotrI   r  r  N)rP   r  r  r  r  rI   r  compile_msgparser_compiles      rS   add_freeze_model_subparserr    sN    			+ ((33 ) 5. <0rU   c                     dj                  ddddddddd	d
ddj                  t              ddddddddddg      }| j                  d|t        j
                        }|j                  t               y)z!Add parser for `aot_compile_cpu`.r   r  z4To compile a SavedModel signature via (CPU) XLA AOT:z"$saved_model_cli aot_compile_cpu \r  r  z(   --output_dir /tmp/saved_model_xla_aotr'   zFNote: Additional XLA compilation options are available by setting the zEXLA_FLAGS environment variable.  See the XLA debug options flags for zall the options: z  {}z5For example, to disable XLA fast math when compiling:z>XLA_FLAGS="--xla_cpu_enable_fast_math=false" $saved_model_cli zaot_compile_cpu ...zSome possibly useful flags:z"  --xla_cpu_enable_fast_math=falsez6  --xla_force_host_platform_device_count=<num threads>z:    (useful in conjunction with disabling multi threading)rJ   r  r  N)rP   ru  _XLA_DEBUG_OPTIONS_URLr  r  r  r  rJ   r  s      rS   add_aot_compile_cpu_subparserr    s    		=,%1	2ON}}+,	>	G	$+?C)	+0 ((33 ) 5.
 ?3rU   c                  
   t        j                  dd      } | j                  dddd       | j                  d	d
d      }t	        |       t        |       t        |       t        |       t        |       t        |       | S )zzCreates a parser that parse the command line arguments.

  Returns:
    A namespace parsed from command line arguments.
  z6saved_model_cli: Command-line interface for SavedModelresolve)r  conflict_handlerz-vz	--versionversionz0.1.0)actionr  commandszvalid commandszadditional helpr  )
r   ArgumentParseradd_argumentr  r  r  r  r  r  r  )parserr  s     rS   create_parserr    s     ((J "& 	dK	7K$$$4;L % N* Z  J Z  
#  
+ Z(	-rU   c                  z    t        j                  t         j                         d } t        j                  |        y )Nc                     t               }t        |       dk  r|j                  d       t        j                  t
        | d             |j                         }|j                          y )Nr  zToo few arguments.r|   )r  rG  r   r   mark_flags_as_requiredcommand_required_flags
parse_argsr  )argvr  r   s      rS   
smcli_mainzmain.<locals>.smcli_main4  sP    _F
4y1}ll'(	  !7Q!@ADIIKrU   )r   set_verbosityINFOr   rF   )r  s    rS   mainr  1  s'    	% ''*rU   __main__)r   )Argumentr   )NFFF)T)__doc__r  platformr  r   r  abslr   r   
absl.flagsr   numpyr   tensorflow.core.exampler   tensorflow.core.frameworkr   tensorflow.core.protobufr   tensorflow.python.clientr	    tensorflow.python.debug.wrappersr
   tensorflow.python.eagerr   r   r   tensorflow.python.frameworkr   rX   r   r   r   tensorflow.python.lib.ior   tensorflow.python.platformr   r   tensorflow.python.saved_modelr   r   r   r   r   tensorflow.python.toolsr   r   tensorflow.python.tpur   tensorflow.python.util.compatr   r  rW   rd  DEFINE_stringrR  DEFINE_boolrQ  rS  rU  rT  rX  rY  rZ  r\  r]  ra  r^  r_  r`  rc  rv  DEFINE_integerrp  DEFINE_enumrq  rr  rm  r  !DEFAULT_SERVING_SIGNATURE_DEF_KEYr  r~  r  machiner  r  r  r  r  rT   r]   rb   re   rj   rn   rq   r   r   r   r   r~   r   rd   rg   r   r   r  r  r#  r*  r&  rO  rE   rF   rG   r{  rI   rJ   r  r  r  r  r  r  r  r  r   rV  rU   rS   <module>r     s(     
 	 	   %  / / / , > 0 5 D 6 3 , < . 6 0 . = ; 5 % 95  78 !U  	#IK
 U		MO
 %$$	D

 +u**	$
"# 
 $%##	U	OQ $##	2
NO )U((	
<=  ,++	2
-.  $##	4	BD %5$$	e	?A  $%##	U
BC
 $##	4

 $%##	U
MN
 $%##	U	AC )U((	
  (E''	t	/1  #7%"6"6	#W
# 
 *))	67O	?A  3e22	
 
 -5,,	e	68  +u**	$
 
 /5..	AA	.0 
 -,,	D	JL  /5..	b
  8 ,,,	 -,,9	 (E''	r
JK 
 '5&&	d
PQ  ,++	7
DE  G.G/7#} -M- :&@2A$!HHF&78t(-V,2D6H,"&:< +/,1,1,1n?b,^#L@%4dNP4&@:. 8F0*K4&:$(& H01$4DD z& rU   