B
    лd                 @   sv  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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-m.Z. dZ/e0dddgZ1dd Z2dd Z3d d! Z4d"d# Z5ddd$d%Z6d&d' Z7ded)d*Z8dfd+d,Z9d-d. Z:d/d0 Z;d1d2 Z<d3d4 Z=d5d6 Z>dgd8d9Z?d:d; Z@dhd=d>ZAd?d@ ZBdAdB ZCdCdD ZDdEdF ZEdGdH ZFdIdJ ZGdKdL ZHdMdN ZIdOdP ZJdQdR ZKdSdT ZLdUdV ZMdWdX ZNdYdZ ZOd[d\ ZPd]d^ ZQd_d` ZRdadb ZSeTdckrreUeS  dS )izCommand-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)example_pb2)	types_pb2)
config_pb2)session)local_cli_wrapper)def_function)function)
meta_graph)ops)tensor_spec)file_io)
tf_logging)load)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.ccZ	WriteFileZReadFileZPrintV2c             C   s>   t | }td x&t|D ]}tddt|  qW dS )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%rz, N)r   get_saved_model_tag_setsprintsortedjoin)saved_model_dirtag_setstag_set r   Y/var/www/html/venv/lib/python3.7/site-packages/tensorflow/python/tools/saved_model_cli.py_show_tag_sets>   s    
r    c             C   s8   t | |}td x t| D ]}td|  q W dS )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_mapr   r   keys)r   r   signature_def_mapsignature_def_keyr   r   r   _show_signature_def_map_keysL   s    
r%   c             C   s6   || j kr*td| dd| 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: z, )signature_def
ValueErrorr   r"   inputs)meta_graph_defr$   r   r   r   +_get_inputs_tensor_info_from_meta_graph_def_   s    
r*   c             C   s   | 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&   outputs)r)   r$   r   r   r   ,_get_outputs_tensor_info_from_meta_graph_defx   s    r,   c                s   t | |}t||}t||}d|   fdd}|d x2t| D ]"\}}	|d|  t|	|d  qJW |d x2t| D ]"\}
}|d|
  t||d  qW |d	|j| j  d
S )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.
  z  c                s   t  |   d S )N)r   )s)
indent_strr   r   in_print   s    z&_show_inputs_outputs.<locals>.in_printzBThe 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)	r   get_meta_graph_defr*   r,   r   items_print_tensor_infor&   method_name)r   r   r$   indentr)   inputs_tensor_infooutputs_tensor_infor/   	input_keyZinput_tensorZ
output_keyZoutput_tensorr   )r.   r   _show_inputs_outputs   s$    r9   c          	   C   sl  t | j}d}x|D ]}||dO }qW |s4dS t   t| }W dQ R X tddd t	t
||}t|dd d	}x|D ]\}}g }t|tjr|| nt|tjr||  nqtd
|  t|dd d	}xxt|dD ]j\}	}
d\}}|
jr|
j\}}n|
jr(|
j}|rNtd|	  td t|dd |rt|ddd qW qW dS )zPrints the callable concrete and polymorphic functions of the Saved Model.

  Args:
    saved_model_dir: Directory containing the SavedModel to inspect.
  FZobject_graph_defNz
Concrete Functions: )endc             S   s   | j S )N)name)xr   r   r   <lambda>       z)_show_defined_functions.<locals>.<lambda>)keyz
  Function Name: '%s'c             S   s   | j S )N)r<   )r=   r   r   r   r>      r?   r0   )NNz    Option #%dz      Callable with:   )r5   zNamed Argument)r   read_saved_modelmeta_graphsZHasFieldops_libGraphZ
as_defaultr   r   listr   Z_AugmentedGraphViewZlist_childrenr   
isinstancedefunZConcreteFunctionappendr   FunctionextendZ._list_all_concrete_functions_for_serialization	enumerateZstructured_input_signatureZ_arg_keywords_print_args)r   rC   Zhas_object_graph_defr)   Ztrackable_objectchildrenr<   childZconcrete_functionsindexZconcrete_functionargskwargsr   r   r   _show_defined_functions   sF    

rS   Argumentc       	         s  d|  dd }d fdd	}xbt | dD ]R\}}|dkrN|d	||f  t|trf|d
|  q,t|tjrt|d d d|jt|f   q,t|tj	rt|t
s|dt|j  |ddd x |D ]}td|| dd qW td q,t|t
r^|dt|j  |ddd x2| D ]&\}}tdt|||f dd q*W td q,|dt|j  |dt|  q,W dS )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.
  z  c             S   s   dt | t }|t|  | S )N')rG   str)valueZ	is_quotesr   r   r   _maybe_add_quotes   s    z&_print_args.<locals>._maybe_add_quotes
c                s   t  |  |d d S )N)r;   )r   )r-   r;   )r.   r   r   r/      s    z_print_args.<locals>.in_printr0   rA   z%s #%dz  %sz%s: %sz  DType: %sz
  Value: [r:   )r;   z%sz, z]z
  Value: {z'%s': %sz}z  Value: %sN)rY   )rL   rG   rV   r   Z
TensorSpecr   r<   reprr   Iterabledicttype__name__r2   )		argumentsZargument_typer5   rX   r/   rP   elementrW   r@   r   )r.   r   rM      s2    	
$


"
rM   c                s   d|   fdd}|ddd t j D | j   | jjrDd}n(dd	 | jjD }d
|}d| d }|d|  |d| j  dS )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
  z  c                s   t  |   d S )N)r   )r-   )r.   r   r   r/     s    z$_print_tensor_info.<locals>.in_printz    dtype: c             S   s   i | ]\}}||qS r   r   ).0r@   rW   r   r   r   
<dictcomp>  s   z&_print_tensor_info.<locals>.<dictcomp>unknown_rankc             S   s   g | ]}t |jqS r   )rV   size)ra   dimr   r   r   
<listcomp>  s    z&_print_tensor_info.<locals>.<listcomp>z, ()z    shape: z
    name: N)	r   ZDataTyper2   ZdtypeZtensor_shaperc   re   r   r<   )Ztensor_infor5   r/   shapeZdimsr   )r.   r   r3     s    
r3   c             C   s   t | }xlt|D ]`}tdd|  d|}t| |}x4t| D ]$}td| d  t| ||dd qLW qW t|  dS )	a   Prints tag-set, SignatureDef and Inputs/Outputs information in SavedModel.

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

  Args:
    saved_model_dir: Directory containing the SavedModel to inspect.
  zF
MetaGraphDef with tag-set: '%s' contains the following SignatureDefs:z, ,z
signature_def['z']:r0   )r5   N)	r   r   r   r   r   r!   r"   r9   rS   )r   r   r   r#   r$   r   r   r   	_show_all%  s    	


rk   c             C   s   t | |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   r1   )r   r   r   r   r   r1   <  s    r1   c             C   s   t | |}|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   r1   r&   )r   r   r
   r   r   r   r!   R  s    r!   c             C   s   t dd | dD }|S )Nc             S   s   g | ]}|r|qS r   r   )ra   opr   r   r   rf   g  s    z(_get_op_denylist_set.<locals>.<listcomp>rj   )setsplit)op_denylistZset_of_denylisted_opsr   r   r   _get_op_denylist_sete  s    rp   c             C   sF   t t| j}||@ }|r0td| jj | ntd| jj | dS )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)rm   meta_graph_libZops_used_by_graph_defZ	graph_defr   Zmeta_info_deftags)r)   ro   Zops_in_metagraphZdenylisted_opsr   r   r   scan_meta_graph_defk  s    
rs   Fc
          	      s  t | |}
t|
| x:| D ].}| kr td|dd   d f q W  fdd| D }t|
|t }fdd|D }d}|rt	
d	 tjtjjd
dd}tj|t |d}|rtd |t  t||d|  |	rt|}|j||d}xt|D ]\}}|| }td||f  |r$tj|sbt| tj||d }|stj |rt!d| t"#|| td||f  q$W W dQ R X dS )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.
  zK"%s" is not a valid input key. Please choose from %s, or use --show option."z", "c                s   i | ]\}}| | j qS r   )r<   )ra   r@   Ztensor)r6   r   r   rb     s   z2run_saved_model_with_feed_dict.<locals>.<dictcomp>c                s   g | ]} | j qS r   )r<   )ra   Z
tensor_key)r7   r   r   rf     s   z2run_saved_model_with_feed_dict.<locals>.<listcomp>NzUsing TFRT session.T)use_tfrt)Zexperimental)graphconfigzInitializing TPU System ...rj   )Z	feed_dictzResult for output key %s:
%sz.npyzXOutput file %s already exists. Add "--overwrite" to overwrite the existing output files.zOutput %s is saved to %s)$r   r1   r*   r"   r'   r   r2   r,   r   logginginfor   ZConfigProtoZExperimentalr   SessionrD   rE   r   runr   Zinitialize_systemr   r   rn   r   ZLocalCLIDebugWrapperSessionrL   ospathisdirmakedirsexistsRuntimeErrornpr   )r   r   r$   Zinput_tensor_key_feed_dictoutdirZoverwrite_flagworkerinit_tpuru   tf_debugr)   Zinput_key_nameZinputs_feed_dictZoutput_tensor_keys_sortedZoutput_tensor_names_sortedrw   sessr+   ioutputZoutput_tensor_keyZoutput_full_pathr   )r6   r7   r   run_saved_model_with_feed_dict  sV    *"




r   c             C   s   i }|  d}xxtt|D ]j}td|}|rN|d|df||d< qtd|}|rx|ddf||d< qtd| qW |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!([^=]+)=([^\[\]]+)\[([^\[\]]+)\]$      r0   z([^=]+)=([^\[\]]+)$Nzu--inputs "%s" format is incorrect. Please follow"<input_key>=<filename>", or"<input_key>=<filename>[<variable_name>]")rn   filterboolrematchgroupr   )
inputs_str
input_dictZ
inputs_raw	input_rawr   r   r   r   preprocess_inputs_arg_string  s    
 r   Tc             C   s   i }x~t t| dD ]j}d| kr.td|  |dd\}}|rtyt|||< W q   td| dY qX qt|||< qW |S )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>"r0   zExpression "z " is not a valid python literal.)r   r   rn   r   astliteral_evaleval)input_exprs_strsafer   r   r8   exprr   r   r   !preprocess_input_exprs_arg_string#  s    r   c             C   sR   t | }xD| D ]8\}}t|ts8td|t|f dd |D ||< qW |S )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.
  z?tf.Example input must be a list of dictionaries, but "%s" is %sc             S   s   g | ]}t |qS r   )_create_example_string)ra   exampler   r   r   rf   d  s    z8preprocess_input_examples_arg_string.<locals>.<listcomp>)r   r2   rG   rF   r'   r]   )input_examples_strr   r8   Zexample_listr   r   r   $preprocess_input_examples_arg_stringI  s    
r   c             C   s  t  }x|  D ]\}}t|ts:td||t|f t|d tr`|jj	| j
j| qt|d tr|jj	| jjdd |D  qt|d tr|jj	| jj| qt|d tr|jj	| jj| qtdt|d |d f qW | S )z7Create a serialized tf.example from feature dictionary.z0feature value must be a list, but %s: "%s" is %sr   c             S   s   g | ]}| d qS )utf8)encode)ra   fr   r   r   rf   u  s    z*_create_example_string.<locals>.<listcomp>z;Type %s for value %s is not supported for tf.train.Feature.)r   ZExampler2   rG   rF   r'   r]   floatfeaturesfeatureZ
float_listrW   rK   rV   Z
bytes_listbytesintZ
int64_listZSerializeToString)Zexample_dictr   Zfeature_nameZfeature_listr   r   r   r   i  s*    
r   c             C   s\  i }t | }t|}t|}x| D ]\}\}}	tjtj|dddd}
|	rt|
tj	rvt
d||	f  |
||< q|	|
kr|
|	 ||< qtd||	f q&t|
tjjjr|
j}t|dkrtd| |
|d	  ||< q&|
||< q&W x4| D ](\}}||krt
d
|  |||< qW x6| D ]*\}}||krJt
d|  |||< q*W |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)Zallow_picklez?Input file %s contains a single ndarray. Name key "%s" ignored.z7Input file %s does not contain variable with name "%s".r0   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   r2   r   r   r   FileIOrG   Zndarrayrx   warnr   libZnpyioZNpzFilefileslen)r   r   r   tensor_key_feed_dictr(   input_exprsinput_examplesZinput_tensor_keyfilenameZvariable_namedataZvariable_name_listZpy_expr_evaluatedr   r   r   r   !load_inputs_from_input_arg_string  sL    0


r   c             C   sX   | j rt| j nB| jdkr(t| j n,| jdkrBt| j| j nt| j| j| j dS )z_Function triggered by show command.

  Args:
    args: A namespace parsed from command line.
  N)allrk   dirr   r    r&   r%   r9   )rQ   r   r   r   show  s    

r   c             C   s^   | j s| js| jstdt| j | j| j}t| j| j| j|| j	| j
| j| j| j| jd
 dS )zFunction triggered by run command.

  Args:
    args: A namespace parsed from command line.

  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   ru   r   N)r(   r   r   AttributeErrorr   r   r   r   r&   r   	overwriter   r   ru   r   )rQ   r   r   r   r   r{      s     
r{   c             C   s   | j r*| jr*tt| j| j t| j nl| j rHtt| j| j t nNt| j}| jr|x:|j	D ]}t|t| j qbW nx|j	D ]}t|t qW dS )z_Function triggered by scan command.

  Args:
    args: A namespace parsed from command line.
  N)
r   ro   rs   r   r1   r   rp   _OP_DENYLISTrB   rC   )rQ   Zsaved_modelr)   r   r   r   scan  s    r   c             C   s   ddl m} | js|jj| j| j| jd}y0|jf | j	| j
dd| }|  W n0 tk
r } ztd|W dd}~X Y nX |j| jd n0|jddd	| j| j| jd
| j	| j
d| jd
 dS )zmFunction triggered by 'convert tensorrt' command.

  Args:
    args: A namespace parsed from command line.
  r   )trt_convert)max_workspace_size_bytesprecision_modeminimum_segment_sizerj   )input_saved_model_dirinput_saved_model_tagsz+{}. Try passing "--convert_tf1_model=True".N)output_saved_model_dirr0   T)Zmax_batch_sizer   r   r   Zis_dynamic_opr   r   r   )Z#tensorflow.python.compiler.tensorrtr   Zconvert_tf1_modelZDEFAULT_TRT_CONVERSION_PARAMS_replacer   r   r   ZTrtGraphConverterV2r   r   rn   _asdictconvert	Exceptionr   formatr   
output_dirZcreate_inference_graph)rQ   Ztrtparams	converterer   r   r   convert_with_tensorrt6  s6    

r   c             C   sj   | j ptj| jd}| js"g }n | j dkr6d}n| jd}tj	|t
| j| j| j|| jd dS )zgFunction triggered by freeze_model command.

  Args:
    args: A namespace parsed from command line.
  zvariables/variablesr   Nrj   )checkpoint_pathr)   r$   variables_to_feedoutput_prefix)r   r|   r}   r   r   r   lowerrn   r   freeze_modelr   r1   r   r$   r   )rQ   r   r   r   r   r   r   ]  s    
r   c             C   s   | j ptj| jd}| js"g }n | j dkr6d}n| jd}tj	|t
| j| j| j|| j| j| j| j| j dkd	 dS )zjFunction triggered by aot_compile_cpu command.

  Args:
    args: A namespace parsed from command line.
  zvariables/variablesr   Nrj   )r   false0)	r   r)   r$   r   r   target_triple
target_cpu	cpp_classmultithreading)r   r|   r}   r   r   r   r   rn   r   Zaot_compile_cpu_meta_graph_defr   r1   r   r$   r   r   r   r   r   )rQ   r   r   r   r   r   aot_compile_cpuv  s$    
r   c             C   sn   d}| j d|tjd}|jdtddd |jdd	d
d |jdtddd |jdtdddd |jtd dS )zAdd parser for `show`.a  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 available information in the SavedModel:
$saved_model_cli show --dir /tmp/saved_model --allr   )descriptionformatter_classz--dirTz.directory containing the SavedModel to inspect)r]   requiredhelpz--all
store_truez7if set, will output all information in given SavedModel)actionr   z	--tag_setNz8tag-set of graph in SavedModel to show, separated by ',')r]   defaultr   z--signature_defSIGNATURE_DEF_KEYz9key of SignatureDef to display input(s) and output(s) for)r]   r   metavarr   )func)
add_parserargparseRawTextHelpFormatteradd_argumentrV   set_defaultsr   )
subparsersZshow_msgZparser_showr   r   r   add_show_subparser  s4    
r   c             C   s  d}| j d|tjd}|jdtddd |jdtdd	d |jd
tdddd d}|jdtd|d d}|jdtd|d d}|jdtd|d |jdtddd |jdddd |jdddd |jdtdd d |jd!ddd"d# |jd$ddd%d# |jtd& dS )'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
r{   )r   r   z--dirTz.directory containing the SavedModel to execute)r]   r   r   z	--tag_setz8tag-set of graph in SavedModel to load, separated by ','z--signature_defr   zkey of SignatureDef to run)r]   r   r   r   zLoading inputs from files, in the format of '<input_key>=<filename>, or '<input_key>=<filename>[<variable_name>]', separated by ';'. The file format can only be from .npy, .npz or pickle.z--inputsr:   )r]   r   r   aG  Specifying inputs by python expressions, in the format of "<input_key>='<python expression>'", separated by ';'. numpy module is available as 'np'. Please note that the expression will be evaluated as-is, and is susceptible to code injection. When this is set, the value will override duplicate input keys from --inputs option.z--input_exprszSpecifying tf.Example inputs as list of dictionaries. For example: <input_key>=[{feature0:value_list,feature1:value_list}]. Use ";" to separate input keys. Will override duplicate input keys from --inputs and --input_exprs option.z--input_examplesz--outdirNz?if specified, output tensor(s) will be saved to given directoryz--overwriter   z=if set, output file will be overwritten if it already exists.)r   r   z
--tf_debugzif set, will use TensorFlow Debugger (tfdbg) to watch the intermediate Tensors and runtime GraphDefs while running the SavedModel.z--workerzdif specified, a Session will be run on the worker. Valid worker specification is a bns or gRPC path.z
--init_tpuz~if specified, tpu.initialize_system will be called on the Session. This option should be only used if the worker is a TPU job.)r   r   r   z
--use_tfrtz@if specified, TFRT session will be used, instead of TF1 session.)r   )r   r   r   r   rV   r   r{   )r   Zrun_msgZ
parser_runmsgr   r   r   add_run_subparser  sl    r   c             C   sX   d}| j d|tjd}|jdtddd |jdtd	d
 |jdtdd
 |jtd dS )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
r   )r   r   z--dirTz.directory containing the SavedModel to execute)r]   r   r   z	--tag_setz8tag-set of graph in SavedModel to scan, separated by ',')r]   r   z--op_denylistzlist of ops to detect and report, separated by ','. If not set, default is WriteFile,ReadFile,PrintV2. For empty list, pass in '')r   N)r   r   r   r   rV   r   r   )r   Zscan_msgZparser_scanr   r   r   add_scan_subparser  s&    
r   c             C   s   d}| j d|tjd}|jdtddd |jdtdd	d |jd
tddd |jdddd}|j ddtjd}|jdtddd |jdtddd |jdtddd |jdtddd |jt	d d S )!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 
r   )r   r   z--dirTz.directory containing the SavedModel to convert)r]   r   r   z--output_dirz-output directory for the converted SavedModelz	--tag_setz;tag-set of graph in SavedModel to convert, separated by ','zconversion methodszvalid conversion methodsz)the conversion to run with the SavedModel)titler   r   Ztensorrtz;Convert the SavedModel with Tensorflow-TensorRT integrationz--max_workspace_size_bytesi    zOthe maximum GPU temporary memory which the TRT engine can use at execution time)r]   r   r   z--precision_modeZFP32zone of FP32, FP16 and INT8z--minimum_segment_sizer   zTthe minimum number of nodes required for a subgraph to be replacedin a TensorRT nodez--convert_tf1_modelFz%support TRT conversion for TF1 models)r   N)
r   r   r   r   rV   add_subparsersr   r   r   r   )r   Zconvert_msgZparser_convertZconvert_subparsersZparser_convert_with_tensorrtr   r   r   add_convert_subparser5  sb    

r   c             C   sr   | j dtddd | j dtddd | j dtddd | j d	ttjd
d | j dtddd | j dtddd dS )z7Parse arguments shared by freeze model and aot_compile.z--dirTz.directory containing the SavedModel to convert)r]   r   r   z--output_prefixzQoutput directory + filename prefix for the resulting header(s) and object file(s)z	--tag_setz;tag-set of graph in SavedModel to convert, separated by ','z--signature_def_keyzEsignature_def key to use.  default: DEFAULT_SERVING_SIGNATURE_DEF_KEY)r]   r   r   z--checkpoint_pathNz@Custom checkpoint to use (default: use the SavedModel variables)z--variables_to_feedr:   a  The names of variables that will be fed into the network.  Options are: empty (default; all variables are frozen, none may be fed), 'all' (all variables may be fed), or a comma-delimited list of names of variables that may be fed.  In the last case, the non-fed variables will be frozen in the graph.**NOTE** Any variables passed to `variables_to_feed` *must be set by the user*.  These variables will NOT be frozen and their values will be uninitialized in the compiled object (this applies to all input arguments from the signature as well).)r   rV   r   Z!DEFAULT_SERVING_SIGNATURE_DEF_KEY)parser_compiler   r   r   _parse_common_freeze_and_aotr  s<    r   c             C   s@   d ddddddg}| jd|tjd	}t| |jtd
 dS )zAdd parser for `freeze_model`.rY   zUsage example:z4To freeze a SavedModel in preparation for tfcompile:z$saved_model_cli freeze_model \z   --dir /tmp/saved_model \z   --tag_set serve \z+   --output_prefix /tmp/saved_model_xla_aotr   )r   r   )r   N)r   r   r   r   r   r   r   )r   compile_msgr   r   r   r   add_freeze_model_subparser  s    
r   c             C   s   d ddddddddd	d
ddtdddddddddg}| jd|tjd}t| |jdtddd |jdtddd |jdtddd |jdtd d!d |j	t
d" d#S )$z!Add parser for `aot_compile_cpu`.rY   zUsage example:z4To compile a SavedModel signature via (CPU) XLA AOT:z"$saved_model_cli aot_compile_cpu \z   --dir /tmp/saved_model \z   --tag_set serve \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:zQXLA_FLAGS="--xla_cpu_enable_fast_math=false" $saved_model_cli 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)r   )r   r   z--target_triplezx86_64-pc-linuxzTarget triple for LLVM during AOT compilation.  Examples: x86_64-none-darwin, x86_64-apple-ios, arm64-none-ios, armv7-none-android.  More examples are available in tfcompile.bzl in the tensorflow codebase.)r]   r   r   z--target_cpuzTarget cpu name for LLVM during AOT compilation.  Examples: x86_64, skylake, haswell, westmere, <empty> (unknown).  For a complete list of options, run (for x86 targets): `llc -march=x86 -mcpu=help`z--cpp_classTa  The name of the generated C++ class, wrapping the generated function.  The syntax of this flag is [[<optional_namespace>::],...]<class_name>.  This mirrors the C++ syntax for referring to a class, where multiple namespaces may precede the class name, separated by double-colons.  The class will be generated in the given namespace(s), or if no namespaces are given, within the global namespace.)r]   r   r   z--multithreadingFalsezEnable multithreading in the compiled computation.  Note that if using this option, the resulting object files may have external dependencies on multithreading libraries like nsync.)r   N)r   r   _XLA_DEBUG_OPTIONS_URLr   r   r   r   r   rV   r   r   )r   r   r   r   r   r   add_aot_compile_cpu_subparser  s^    
r   c              C   sb   t jdd} | jddddd | jd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)r   z-vz	--versionversionz0.1.0)r   r   commandszvalid commandszadditional help)r   r   r   )
r   ArgumentParserr   r   r   r   r   r   r   r   )parserr   r   r   r   create_parser  s    r   c              C   s<   t t j t } |  }t|ds.| d || d S )Nr   ztoo few arguments)rx   set_verbosityINFOr   
parse_argshasattrerrorr   )r   rQ   r   r   r   main  s    

r  __main__)r   )rT   r   )r   )NFFF)T)V__doc__r   r   r|   r   sysZabslr   numpyr   Ztensorflow.core.exampler   Ztensorflow.core.frameworkr   Ztensorflow.core.protobufr   Ztensorflow.python.clientr   Z tensorflow.python.debug.wrappersr   Ztensorflow.python.eagerr   r	   rH   Ztensorflow.python.frameworkr
   rq   r   rD   r   Ztensorflow.python.lib.ior   Ztensorflow.python.platformr   rx   Ztensorflow.python.saved_modelr   r   r   r   Ztensorflow.python.toolsr   r   Ztensorflow.python.tpur   Ztensorflow.python.util.compatr   r   rm   r   r    r%   r*   r,   r9   rS   rM   r3   rk   r1   r!   rp   rs   r   r   r   r   r   r   r   r{   r   r   r   r   r   r   r   r   r   r   r   r   r  r^   exitr   r   r   r   <module>   s   
'0
+
   
h/
& g'.U=-F!	
