B
    ӻda                 @   s   d 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m	Z	 ddl
mZ ddlmZ dd	lmZ d
ZdZdd Zdd ZdddZdddZedgddddZdS )zqLogging tensorflow::tfprof::OpLogProto.

OpLogProto is used to add extra model information for offline analysis.
    N)tfprof_log_pb2)context)ops)tensor_shape)gfile)flops_registry)	tf_exportZ_trainable_variablesZflopsc       
      C   s,  x$|j jD ]}x|jD ]}|js*qy| |j}W n$ tk
r^ } zwW dd}~X Y nX t|jt|jkrvqxt	|jD ]\}}|j| 
  rq|jjj}tdd |D }	y$|j| |j| 
 |	 W q tk
r } ztjd|j|f  W dd}~X Y qX qW qW qW | S )zBFill Tensor shapes in 'graph' with run time shape from 'run_meta'.Nc             S   s   g | ]
}|j qS  )size).0dr	   r	   Z/var/www/html/venv/lib/python3.7/site-packages/tensorflow/python/profiler/tfprof_logger.py
<listcomp>5   s    z-_fill_missing_graph_shape.<locals>.<listcomp>z!Node %s incompatible shapes: %s.
)Z
step_statsZ	dev_statsZ
node_statsoutputZget_operation_by_nameZ	node_nameKeyErrorlenoutputs	enumerate	get_shapeZis_fully_definedZtensor_descriptionshapedimr   ZTensorShape	set_shapeZ
merge_with
ValueErrorsysstderrwrite)
graphrun_metaZdev_statZ	node_statopeiZnode_stat_outZnode_stat_dimsZnode_stat_shaper	   r	   r   _fill_missing_graph_shape"   s.    
,r!   c             C   s(   | | d}|dkr$t|}||| < |S )zMaps string to id.N)getr   )sZ	str_to_idnumr	   r	   r   _str_id?   s
    r%   Tc          	   C   s  |rt | |} d}i }i }t||d< x|  D  ]}yt| |jt}W n  tk
rl   |d7 }d}Y nX t	 }	|j
|	_
d}
|r|jrt|j|	_d}
|r$|jr xt|jD ]j\}}}}|	jj }|rt||nd|_|r|nd|_|rt||nd|_|rt||nd|_d|_qW d}
|
r2|	||	j
< q2W |rxd| tjjD ]R}|jj
|krt	 }	|jj
|	_
|	jt |	||	j
< n||jj
 jt qLW |dkr|stj d|  ||fS )	a  Extract trainable model parameters and FLOPs for ops from a Graph.

  Args:
    graph: tf.Graph.
    run_meta: RunMetadata proto used to complete shape information.
    add_trace: Whether to add op trace information.
    add_trainable_var: Whether to assign tf.compat.v1.trainable_variables() op
      type '_trainable_variables'.
  Returns:
    logged_ops: dict mapping from op_name to OpLogEntry.
    string_to_id: dict mapping from string to id.
  r   none   NFTz0%d ops no flops stats due to incomplete shapes.
)!r!   r   Zget_operationsr   Zget_stats_for_node_defZnode_defREGISTERED_FLOP_STATSr   r   Z
OpLogEntrynamevalueint	float_ops	tracebackcode_deftracesaddr%   Zfile_idlinenoZfunction_idZline_idZfunc_start_lineZget_collectionZ	GraphKeysTRAINABLE_VARIABLESr   typesappendr   r   r   )r   r   	add_traceadd_trainable_varZop_missing_shape
logged_opsstring_to_idr   statsentry	add_entryfilenamer2   funcnamelinetracevr	   r	   r   _get_logged_opsH   sV    




rB   c             C   s&  | st  st } t }| s$|S t| |||d\}}|sN|j|	  ni }x|jD ]}	|	||	j
< qZW x| D ]v\}
}	|
|kr||
 j|	j |	jdkr||
 jdkr|	j||
 _|	jjr||
 jjs||
 j|	j qv|	||
< qvW |j|	  x | D ]\}}||j|< q
W |S )a  Merge the tfprof default extra info with caller's op_log.

  Args:
    graph: tf.Graph. If None and eager execution is not enabled, use
        default graph.
    op_log: OpLogProto proto.
    run_meta: RunMetadata proto used to complete shape information.
    add_trace: Whether to add op trace information.
    add_trainable_var: Whether to assign tf.compat.v1.trainable_variables() op
      type '_trainable_variables'.
  Returns:
    tmp_op_log: Merged OpLogProto proto.
  )r6   r7   r   )r   executing_eagerlyr   get_default_graphr   Z
OpLogProtorB   Zlog_entriesextendvaluesr*   itemsr4   r-   r/   r0   Z	MergeFromZid_to_string)r   op_logr   r6   r7   Z
tmp_op_logr8   r9   Zall_opsr;   Zop_namer#   r    r	   r	   r   merge_default_with_oplog   s0    rI   zprofiler.write_op_log)Zv1c          	   C   sV   | st  st } t| |||}ttj	|dd}|
|  W dQ R X dS )a  Log provided 'op_log', and add additional model information below.

    The API also assigns ops in tf.compat.v1.trainable_variables() an op type
    called '_trainable_variables'.
    The API also logs 'flops' statistics for ops with op.RegisterStatistics()
    defined. flops calculation depends on Tensor shapes defined in 'graph',
    which might not be complete. 'run_meta', if provided, completes the shape
    information with best effort.

  Args:
    graph: tf.Graph. If None and eager execution is not enabled, use
        default graph.
    log_dir: directory to write the log file.
    op_log: (Optional) OpLogProto proto to be written. If not provided, an new
        one is created.
    run_meta: (Optional) RunMetadata proto that helps flops computation using
        run time shape information.
    add_trace: Whether to add python code trace information.
        Used to support "code" view.
  Z
tfprof_logwN)r   rC   r   rD   rI   r   ZOpenospathjoinr   ZSerializeToString)r   Zlog_dirrH   r   r6   logr	   r	   r   write_op_log   s
    rO   )NTT)NNTT)NNT)__doc__rK   r   Ztensorflow.core.profilerr   Ztensorflow.python.eagerr   Ztensorflow.python.frameworkr   r   Ztensorflow.python.platformr   Z#tensorflow.python.profiler.internalr   Z tensorflow.python.util.tf_exportr   r3   r)   r!   r%   rB   rI   rO   r	   r	   r	   r   <module>   s&   	 
D 
.
