o
    2ha                     @   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_export_trainable_variablesflopsc           
      C   s  |j jD ]}|jD ]~}|jsq	z| |j}W n ty) } zW Y d}~q	d}~ww t|jt|jkr5q	t	|jD ]L\}}|j| 
  rHq:|jjj}tdd |D }	z|j| |j| 
 |	 W q: ty } ztjd|j|f  W Y d}~q:d}~ww q	q| S )zBFill Tensor shapes in 'graph' with run time shape from 'run_meta'.Nc                 S   s   g | ]}|j qS  )size).0dr   r   c/var/www/html/chatgem/venv/lib/python3.10/site-packages/tensorflow/python/profiler/tfprof_logger.py
<listcomp>5   s    z-_fill_missing_graph_shape.<locals>.<listcomp>z!Node %s incompatible shapes: %s.
)
step_stats	dev_stats
node_statsoutputget_operation_by_name	node_nameKeyErrorlenoutputs	enumerate	get_shapeis_fully_definedtensor_descriptionshapedimr   TensorShape	set_shape
merge_with
ValueErrorsysstderrwrite)
graphrun_metadev_stat	node_statopeinode_stat_outnode_stat_dimsnode_stat_shaper   r   r   _fill_missing_graph_shape"   s@   


r1   c                 C   s(   | | d}|du rt|}||| < |S )zMaps string to id.N)getr   )s	str_to_idnumr   r   r   _str_id?   s
   r6   Tc              	   C   s  |rt | |} d}i }i }t||d< |  D ]y}z
t| |jt}W n ty2   |d7 }d}Y nw t	 }	|j
|	_
d}
|rJ|jrJt|j|	_d}
|r|jr|jD ]4\}}}}|	jj }|ret||nd|_|rl|nd|_|rvt||nd|_|rt||nd|_d|_qRd}
|
r|	||	j
< q|r| tjjD ]'}|jj
|vrt	 }	|jj
|	_
|	jt |	||	j
< q||jj
 jt q|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.
)!r1   r   get_operationsr   get_stats_for_node_defnode_defREGISTERED_FLOP_STATSr#   r   
OpLogEntrynamevalueint	float_ops	tracebackcode_deftracesaddr6   file_idlinenofunction_idline_idfunc_start_lineget_collection	GraphKeysTRAINABLE_VARIABLESr+   typesappendr$   r%   r&   )r'   r(   	add_traceadd_trainable_varop_missing_shape
logged_opsstring_to_idr+   statsentry	add_entryfilenamerH   funcnamelinetracevr   r   r   _get_logged_opsH   s^   



r^   c                 C   s  | s
t  s
t } t }| s|S t| |||d\}}|s'|j|	  nUi }|jD ]}	|	||	j
< q,| D ];\}
}	|
|v ro||
 j|	j |	jdkr[||
 jdkr[|	j||
 _|	jjrn||
 jjsn||
 j|	j q8|	||
< q8|j|	  | D ]	\}}||j|< q|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.
  )rQ   rR   r   )r   executing_eagerlyr   get_default_graphr   
OpLogProtor^   log_entriesextendvaluesr?   itemsrO   rB   rD   rE   	MergeFromid_to_string)r'   op_logr(   rQ   rR   
tmp_op_logrT   rU   all_opsrW   op_namer3   r-   r   r   r   merge_default_with_oplog   s4   


rl   zprofiler.write_op_log)v1c                 C   sl   | s
t  s
t } t| |||}ttj	|dd}|
|  W d   dS 1 s/w   Y  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.
  
tfprof_logwN)r   r_   r   r`   rl   r   Openospathjoinr&   SerializeToString)r'   log_dirrh   r(   rQ   logr   r   r   write_op_log   s   "rw   )NTT)NNTT)NNT)__doc__rq   r$   tensorflow.core.profilerr   tensorflow.python.eagerr   tensorflow.python.frameworkr   r   tensorflow.python.platformr   #tensorflow.python.profiler.internalr    tensorflow.python.util.tf_exportr   rN   r=   r1   r6   r^   rl   rw   r   r   r   r   <module>   s,   	
E

/