B
    ӻd9                 @   s  d 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ZdZi i i i dZdd Zdd Zdd ZedgdG dd dZedgdddddefddZedgdddefddZdS )zWModel Analyzer.

Analyze model, including shape, params, time, memory, structure, etc.
    N)message)tfprof_options_pb2)tfprof_output_pb2)context)errors)ops)option_builder)tfprof_logger)_pywrap_tfprof)	tf_export)ZExpensiveOperationCheckerZAcceleratorUtilizationCheckerZ
JobCheckerZOperationCheckerc             C   s   | r| j dd S dS dS )z&Helper to serialize a graph to string.T)Z
add_shapes    N)Zas_graph_defSerializeToString)graph r   [/var/www/html/venv/lib/python3.7/site-packages/tensorflow/python/profiler/model_analyzer.py_graph_string-   s    r   c             C   s  t  }| dd|_| dd|_| dd|_| dd|_| dd|_| dd|_| d	d|_	| d
d|_
| dd|_| dd|_| dd|_| dd|_| dd|_x | dg D ]}|j| qW x | dg D ]}|j| qW x"| dg D ]}|j| qW x"| dg D ]}|j| q4W x"| dg D ]}|j| qXW | dd|_x"| dg D ]}|j| qW | dd|_| dd|_|S )zqBuild tfprof.OptionsProto.

  Args:
    options: A dictionary of options.

  Returns:
    tfprof.OptionsProto.
  	max_depth
   	min_bytesr   min_peak_bytesmin_residual_bytesmin_output_bytes
min_microsmin_accelerator_microsmin_cpu_micros
min_paramsmin_float_opsmin_occurrencesteporder_bynameaccount_type_regexesstart_name_regexestrim_name_regexesshow_name_regexeshide_name_regexesaccount_displayed_op_onlyFselectoutputstdoutdump_to_file )r   ZOptionsProtogetr   r   r   r   r   r   r   r   r   r   r   r   r    r"   appendr#   r$   r%   r&   r'   r(   r)   r+   )optionsoptspr   r   r   _build_options5   s>    	r2   c             C   sf   t  }| dkr|S xL|  D ]@\}}t j }x| D ]\}}|||< q:W |j| | qW |S )zBuild tfprof.AdvisorOptionsProto.

  Args:
    options: A dictionary of options. See ALL_ADVICE example.

  Returns:
    tfprof.AdvisorOptionsProto.
  N)r   ZAdvisorOptionsProtoitemsZCheckerOptionZcheckersZ	MergeFrom)r/   r0   checkerZchecker_optsZchecker_ops_pbkvr   r   r   _build_advisor_optionse   s    	
r7   zprofiler.Profiler)Zv1c               @   sb   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd ZdS )Profilera  TensorFlow multi-step profiler.


  ```python
  Typical use case:
    # Currently we are only allowed to create 1 profiler per process.
    profiler = Profiler(sess.graph)

    for i in range(total_steps):
      if i % 10000 == 0:
        run_meta = tf.compat.v1.RunMetadata()
        _ = sess.run(...,
                     options=tf.compat.v1.RunOptions(
                         trace_level=tf.RunOptions.FULL_TRACE),
                     run_metadata=run_meta)
        profiler.add_step(i, run_meta)

        # Profile the parameters of your model.
        profiler.profile_name_scope(options=(option_builder.ProfileOptionBuilder
            .trainable_variables_parameter()))

        # Or profile the timing of your model operations.
        opts = option_builder.ProfileOptionBuilder.time_and_memory()
        profiler.profile_operations(options=opts)

        # Or you can generate a timeline:
        opts = (option_builder.ProfileOptionBuilder(
                option_builder.ProfileOptionBuilder.time_and_memory())
                .with_step(i)
                .with_timeline_output(filename).build())
        profiler.profile_graph(options=opts)
      else:
        _ = sess.run(...)
    # Auto detect problems and generate advice.
    profiler.advise()
  ```
  Nc             C   sJ   |st  st }d| _|| _tj| j|d}t	t
| j|  dS )zConstructor.

    Args:
      graph: tf.Graph. If None and eager execution is not enabled, use default
        graph.
      op_log: optional. tensorflow::tfprof::OpLogProto proto. Used to define
        extra op types.
    g        )op_logN)r   executing_eagerlyr   get_default_graph	_coverage_graphr	   merge_default_with_oplog	print_mdlZNewProfilerr   r   )selfr   r9   r   r   r   __init__   s    	zProfiler.__init__c             C   s   t   d S )N)r?   ZDeleteProfiler)r@   r   r   r   __del__   s    zProfiler.__del__c             C   s4   t j| j|d}t|t| j| | | _dS )aR  Add statistics of a step.

    Args:
      step: int, An id used to group one or more different `run_meta` together.
        When profiling with the profile_xxx APIs, user can use the `step` id in
        the `options` to profile these `run_meta` together.
      run_meta: RunMetadata proto that contains statistics of a session run.
    )run_metaN)r	   r>   r=   r?   ZAddStepr   r   r<   )r@   r   rC   r9   r   r   r   add_step   s
    
zProfiler.add_stepc          
   C   sj   t |}t }y |tdd|  W n4 tj	k
rd } zt
jd|  W dd}~X Y nX |S )a}  Profile the statistics of the Python codes.

      By default, it shows the call stack from root. To avoid
      redundant output, you may use options to filter as below
        options['show_name_regexes'] = ['.*my_code.py.*']

    Args:
      options: A dict of options. See core/profiler/g3doc/options.md.

    Returns:
      a MultiGraphNodeProto that records the results.
    codezutf-8z!Cannot parse returned proto: %s.
N)r2   r   MultiGraphNodeProtoParseFromStringr?   Profileencoder   r   DecodeErrorsysstderrwrite)r@   r/   r0   tfprof_nodeer   r   r   profile_python   s    "zProfiler.profile_pythonc          
   C   sj   t |}t }y |tdd|  W n4 tj	k
rd } zt
jd|  W dd}~X Y nX |S )zProfile the statistics of the Operation types (e.g.

    MatMul, Conv2D).

    Args:
      options: A dict of options. See core/profiler/g3doc/options.md.

    Returns:
      a MultiGraphNodeProto that records the results.
    opzutf-8z!Cannot parse returned proto: %s.
N)r2   r   rF   rG   r?   rH   rI   r   r   rJ   rK   rL   rM   )r@   r/   r0   rN   rO   r   r   r   profile_operations   s    "zProfiler.profile_operationsc          
   C   sj   t |}t }y |tdd|  W n4 tj	k
rd } zt
jd|  W dd}~X Y nX |S )zProfile the statistics of graph nodes, organized by name scope.

    Args:
      options: A dict of options. See core/profiler/g3doc/options.md.

    Returns:
      a GraphNodeProto that records the results.
    scopezutf-8z!Cannot parse returned proto: %s.
N)r2   r   GraphNodeProtorG   r?   rH   rI   r   r   rJ   rK   rL   rM   )r@   r/   r0   rN   rO   r   r   r   profile_name_scope   s    	"zProfiler.profile_name_scopec          
   C   sj   t |}t }y |tdd|  W n4 tj	k
rd } zt
jd|  W dd}~X Y nX |S )zProfile the statistics of graph nodes, organized by dataflow graph.

    Args:
      options: A dict of options. See core/profiler/g3doc/options.md.

    Returns:
      a GraphNodeProto that records the results.
    r   zutf-8z!Cannot parse returned proto: %s.
N)r2   r   rT   rG   r?   rH   rI   r   r   rJ   rK   rL   rM   )r@   r/   r0   rN   rO   r   r   r   profile_graph  s    	"zProfiler.profile_graphc             C   s0   t  }t|}|tdd|  |S )zAutomatically detect problems and generate reports.

    Args:
      options: A dict of options. See ALL_ADVICE example above.

    Returns:
      An Advise proto that contains the reports from all checkers.
    advisezutf-8)r   AdviceProtor7   rG   r?   rH   rI   r   )r@   r/   Z	advise_pbr0   r   r   r   rW     s
    	zProfiler.advisec             C   s   t  S )zSerialize the ProfileProto to a binary string.

      Users can write it to file for offline analysis by tfprof commandline
      or graphical interface.

    Returns:
      ProfileProto binary string.
    )r?   r   )r@   r   r   r   serialize_to_string&  s    	zProfiler.serialize_to_stringc             C   s   t | dS )zWrites the profile to a file.N)r?   ZWriteProfile)r@   filenamer   r   r   _write_profile1  s    zProfiler._write_profile)NN)__name__
__module____qualname____doc__rA   rB   rD   rP   rR   rU   rV   rW   rY   r[   r   r   r   r   r8   y   s   &
r8   zprofiler.profilerS   c          
   C   sr  | st  st } |tkr&tj }tj	| |||dkd}t
|}|rP| nd}t| }|dksl|dkrt }t||| |d| }	y||	 W n4 tjk
r }
 ztjd|
  W dd}
~
X Y nX n|dks|d	kr\t }t||| |d| }	y||	 W n6 tjk
rX }
 ztjd|
  W dd}
~
X Y nX ntddd
| |S )a  Profile model.

    Tutorials and examples can be found in:
    https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/profiler/g3doc/python_api.md

  Args:
    graph: tf.Graph. If None and eager execution is not enabled, use default
      graph.
    run_meta: optional tensorflow.RunMetadata proto. It is necessary to
      support run time information profiling, such as time and memory.
    op_log: tensorflow.tfprof.OpLogProto proto. User can assign "types" to graph
      nodes with op_log. "types" allow user to flexibly group and account
      profiles using options['accounted_type_regexes'].
    cmd: string. Either 'op', 'scope', 'graph' or 'code'. 'op' view organizes
      profile using operation type. (e.g. MatMul) 'scope' view organizes profile
      using graph node name scope. 'graph' view organizes profile using graph
      node inputs/outputs. 'code' view organizes profile using Python call
      stack.
    options: A dict of options. See core/profiler/g3doc/options.md.

  Returns:
    If cmd is 'scope' or 'graph', returns GraphNodeProto proto.
    If cmd is 'op' or 'code', returns MultiGraphNodeProto proto.
    Side effect: stdout/file/timeline.json depending on options['output']
  rE   )	add_tracer   rQ   zutf-8z!Cannot parse returned proto: %s.
Nr   rS   zunknown cmd: %s
)r   r:   r   r;   _DEFAULT_PROFILE_OPTIONSr   ZProfileOptionBuilderZtrainable_variables_parameterr	   r>   r2   r   r   r   rF   r?   PrintModelAnalysisrI   rG   r   rJ   rK   rL   rM   rT   r   ZInvalidArgumentError)r   rC   r9   cmdr/   r0   run_meta_strZ	graph_strrN   retrO   r   r   r   profile6  s>    

$
$rf   zprofiler.advisec          
   C   s   | st  st } |tkr$t }tj| d|dd}|rB|	 nd}t
|}t }|tt| ||	 dd|	  |S )a:  Auto profile and advise.

    Builds profiles and automatically check anomalies of various
    aspects. For more details:
    https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler/README.md

  Args:
    graph: tf.Graph. If None and eager execution is not enabled, use default
      graph.
    run_meta: optional tensorflow.RunMetadata proto. It is necessary to
      support run time information profiling, such as time and memory.
    options: see ALL_ADVICE example above. Default checks everything.

  Returns:
    Returns AdviceProto proto
  NT)r`   r   rW   zutf-8)r   r:   r   r;   _DEFAULT_ADVISE_OPTIONS
ALL_ADVICEcopyr	   r>   r   r7   r   rX   rG   r?   rb   r   rI   )r   rC   r/   r9   rd   r0   re   r   r   r   rW     s    rW   )r_   rK   Zgoogle.protobufr   Ztensorflow.core.profilerr   r   Ztensorflow.python.eagerr   Ztensorflow.python.frameworkr   r   Ztensorflow.python.profilerr   r	   Ztensorflow.python.utilr
   r?   Z tensorflow.python.util.tf_exportr   ra   rg   rh   r   r2   r7   r8   rf   rW   r   r   r   r   <module>   s<   0 >
F
