B
    һd              	   @   s~  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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ZdZdZdZdZdZdZdd ZG 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(d) Z*e+d*d+d,d-d.d/d0gZ,d1d2 Z-d3d4 Z.d5d6 Z/G d7d8 d8Z0G d9d: d:e1Z2G d;d< d<Z3dS )=zGClasses and functions to handle debug-dump data of TensorFlow Debugger.    N)	graph_pb2)	types_pb2)	event_pb2)debug_graphs)tensor_util)gfile)
tf_logging)compatZ_tfdbg_Zcore_metadata_Zgraph_device_hashZfetches_info_Zfeed_keys_info_c             C   s$   t  dkrt| S t| S d S )NWindows)platformsystemglobr   ZGlob)Zglob_pattern r   X/var/www/html/venv/lib/python3.7/site-packages/tensorflow/python/debug/lib/debug_data.py_glob/   s    
r   c               @   s.   e Zd ZdZd
ddZdd Zedd Zd	S )InconvertibleTensorProtoz@Represents a TensorProto that cannot be converted to np.ndarray.Tc             C   s   || _ || _dS )zConstructor.

    Args:
      tensor_proto: the `TensorProto` object that cannot be represented as a
        `np.ndarray` object.
      initialized: (`bool`) whether the Tensor is initialized.
    N)_tensor_proto_initialized)selftensor_protoinitializedr   r   r   __init__9   s    z!InconvertibleTensorProto.__init__c             C   s    | j r
dnd}|t| j7 }|S )N zUninitialized tensor:
)r   strr   )r   outputr   r   r   __str__D   s    z InconvertibleTensorProto.__str__c             C   s   | j S )N)r   )r   r   r   r   r   I   s    z$InconvertibleTensorProto.initializedN)T)__name__
__module____qualname____doc__r   r   propertyr   r   r   r   r   r   6   s   
r   c          	   C   s6   t  }t| d}||  t|S Q R X dS )a  Load a tensor from an event file.

  Assumes that the event file contains a `Event` protobuf and the `Event`
  protobuf contains a `Tensor` value.

  Args:
    event_file_path: (`str`) path to the event file.

  Returns:
    The tensor value loaded from the event file, as a `numpy.ndarray`. For
    uninitialized Tensors, returns `None`. For Tensors of data types that
    cannot be converted to `numpy.ndarray` (e.g., `tf.resource`), return
    `None`.
  rbN)r   Eventr   OpenParseFromStringreadload_tensor_from_event)event_file_patheventfr   r   r   load_tensor_from_event_fileN   s    r,   c             C   s   | j jd j}t|j}d}x|D ]}||9 }q$W |jsD|jsD|s|jt	j
krZt|}qyt|}W q tk
r   t|}Y qX n
t|d}|S )a  Load a tensor from an Event proto.

  Args:
    event: The Event proto, assumed to hold a tensor value in its
        summary.value[0] field.

  Returns:
    The tensor value loaded from the event file, as a `numpy.ndarray`, if
    representation of the tensor value by a `numpy.ndarray` is possible.
    For uninitialized Tensors, returns `None`. For Tensors of data types that
    cannot be represented as `numpy.ndarray` (e.g., `tf.resource`), return
    the `TensorProto` protobuf object without converting it to a
    `numpy.ndarray`.
  r      F)summaryvaluetensorr   ZTensorShapeProtoToListZtensor_shapeZtensor_contentZ
string_valdtyper   ZDT_RESOURCEr   ZMakeNdarrayKeyError)r*   r   shapeZnum_elementsZ	shape_dimZtensor_valuer   r   r   r(   d   s    


r(   c          	   C   s<   t  }t| d}||  W d Q R X tj|j	S )Nr#   )
r   r$   r   r%   r&   r'   r   ZGraphDefZ
FromString	graph_def)r)   r*   r+   r   r   r   _load_graph_def_from_event_file   s    r5   c          	   C   s6   t  }t| d}||  W d Q R X |jjS )Nr#   )r   r$   r   r%   r&   r'   log_messagemessage)r)   r*   r+   r   r   r   !_load_log_message_from_event_file   s    r8   c             C   s   |  tt S )N)
startswithMETADATA_FILE_PREFIXGRAPH_FILE_TAG)	file_namer   r   r   _is_graph_file   s    r=   c             C   s   | t t kS )N)r:   FETCHES_INFO_FILE_TAG)r<   r   r   r   _is_run_fetches_info_file   s    r?   c             C   s   | t t kS )N)r:   FEED_KEYS_INFO_FILE_TAG)r<   r   r   r   _is_run_feed_keys_info_file   s    rA   c             C   s   d| |f S )zGet tensor name given node name and output slot index.

  Args:
    node_name: Name of the node that outputs the tensor, as a string.
    output_slot: Output slot index of the tensor, as an integer.

  Returns:
    Name of the tensor, as a string.
  z%s:%dr   )	node_nameoutput_slotr   r   r   _get_tensor_name   s    rD   c             C   s   dt | ||f S )a  Get the string representation of a debug watch on a tensor.

  Args:
    node_name: Name of the node by which the watched tensor is produced, as a
        string.
    output_slot: Output slot index of the tensor, as an integer.
    debug_op: Name of the debug op that is used to watch the tensor, as a
        string.

  Returns:
    A string representing the debug watch on the tensor (i.e., the "watch
        key").
  z%s:%s)rD   )rB   rC   debug_opr   r   r   _get_tensor_watch_key   s    rF   c             C   sj   | }t |trdS t|jtjsBt|jtjsBt|jtjrbtt	|p`tt
|S dS dS )a  A predicate for whether a tensor consists of any bad numerical values.

  This predicate is common enough to merit definition in this module.
  Bad numerical values include `nan`s and `inf`s.
  The signature of this function follows the requirement of the method
  `DebugDumpDir.find()`.

  Args:
    datum: (`DebugTensorDatum`) Datum metadata.
    tensor: (`numpy.ndarray` or None) Value of the tensor. None represents
      an uninitialized tensor.

  Returns:
    (`bool`) True if and only if tensor consists of any nan or inf values.
  FN)
isinstancer   npZ
issubdtyper1   ZfloatingZcomplexfloatingintegeranyisnanisinf)datumr0   _r   r   r   has_inf_or_nan   s    
 rO   ZCoreMetadataglobal_stepsession_run_indexexecutor_step_indexinput_namesoutput_namestarget_nodesc             C   s8   t | jj}t|d |d |d |d |d |d S )NrP   rQ   rR   rS   rT   rU   )jsonloadsr6   r7   _CoreMetadata)r*   Zjson_metadatar   r   r   &extract_core_metadata_from_event_proto   s    rY   c             C   s0   t | d}dd |D }tt d| S )z#Convert device name to device path./c             S   s   g | ]}| d dqS ):rN   )replace).0itemr   r   r   
<listcomp>   s    z.device_name_to_device_path.<locals>.<listcomp>,)r	   Zas_textsplitr:   
DEVICE_TAGjoin)device_nameZdevice_name_itemsr   r   r   device_name_to_device_path   s    re   c             C   s:   t j| tttt d d}ddd |D S )zParse device name from device path.

  Args:
    device_dir: (str) a directory name for the device.

  Returns:
    (str) parsed device name.
  Nr`   rZ   c             S   s"   g | ]}| d d dddqS )r
   zdevice:rN   r[   r-   )r\   )r]   	path_itemr   r   r   r_     s   z.device_path_to_device_name.<locals>.<listcomp>)ospathbasenamelenr:   rb   ra   rc   )
device_dirZ
path_itemsr   r   r   device_path_to_device_name   s
    	
rl   c               @   s   e Zd ZdZdd Zdd Zdd Zdd	 Zed
d Z	edd Z
edd Zedd Zedd Zedd Zedd Zedd Zedd Zedd ZdS )DebugTensorDatuma  A single tensor dumped by TensorFlow Debugger (tfdbg).

  Contains metadata about the dumped tensor, including `timestamp`,
  `node_name`, `output_slot`, `debug_op`, and path to the dump file
  (`file_path`).

  This type does not hold the generally space-expensive tensor value (numpy
  array). Instead, it points to the file from which the tensor value can be
  loaded (with the `get_tensor` method) if needed.
  c             C   s  t j|t j}t|d | _|d }|ddk rDtd| |dd | _	d| j	kr|t
| j	d| j	d | _nt
| j	| _|dd | _t
|dd	 | _d|ddd	 }d
|dd |g | _t j||| _t| jr
t| jjnd| _dS )a  `DebugTensorDatum` constructor.

    Args:
      dump_root: (`str`) Debug dump root directory. This path should not include
        the path component that represents the device name (see also below).
      debug_dump_rel_path: (`str`) Path to a debug dump file, relative to the
        `dump_root`. The first item of this relative path is assumed to be
        a path representing the name of the device that the Tensor belongs to.
        See `device_path_to_device_name` for more details on the device path.
        For example, suppose the debug dump root
        directory is `/tmp/tfdbg_1` and the dump file is at
        `/tmp/tfdbg_1/<device_path>/>ns_1/node_a_0_DebugIdentity_123456789`,
        then the value of the debug_dump_rel_path should be
        `<device_path>/ns_1/node_a_0_DebugIdentity_1234456789`.

    Raises:
      ValueError: If the base file name of the dump file does not conform to
        the dump file naming pattern:
        `node_name`_`output_slot`_`debug_op`_`timestamp`
    r   rN      z9Dump file path does not conform to the naming pattern: %s-NrZ   r-   )rg   rh   normpathra   seprl   _device_namecount
ValueError_extended_timestampintfind
_timestamp	_debug_op_output_slotrc   
_node_name
_file_pathr   ZExistsZStatlength_dump_size_bytes)r   	dump_rootdebug_dump_rel_pathZpath_componentsbaseZnode_base_namer   r   r   r     s"    

zDebugTensorDatum.__init__c             C   s   d| j | j| j| j| jf S )Nz'{DebugTensorDatum (%s) %s:%d @ %s @ %d})rd   rB   rC   rE   	timestamp)r   r   r   r   r   H  s
    zDebugTensorDatum.__str__c             C   s   |   S )N)r   )r   r   r   r   __repr__O  s    zDebugTensorDatum.__repr__c             C   s
   t | jS )zqGet tensor from the dump (`Event`) file.

    Returns:
      The tensor loaded from the dump (`Event`) file.
    )r,   	file_path)r   r   r   r   
get_tensorR  s    zDebugTensorDatum.get_tensorc             C   s   | j S )zoTimestamp of when this tensor value was dumped.

    Returns:
      (`int`) The timestamp in microseconds.
    )r{   )r   r   r   r   r   \  s    zDebugTensorDatum.timestampc             C   s   | j S )aS  Extended timestamp, possibly with an index suffix.

    The index suffix, e.g., "-1", is for disambiguating multiple dumps of the
    same tensor with the same timestamp, which can occur if the dumping events
    are spaced by shorter than the temporal resolution of the timestamps.

    Returns:
      (`str`) The extended timestamp.
    )rx   )r   r   r   r   extended_timestampf  s    z#DebugTensorDatum.extended_timestampc             C   s   | j S )z]Name of the debug op.

    Returns:
      (`str`) debug op name (e.g., `DebugIdentity`).
    )r|   )r   r   r   r   rE   t  s    zDebugTensorDatum.debug_opc             C   s   | j S )z\Name of the device that the tensor belongs to.

    Returns:
      (`str`) device name.
    )ru   )r   r   r   r   rd   ~  s    zDebugTensorDatum.device_namec             C   s   | j S )zName of the node from which the tensor value was dumped.

    Returns:
      (`str`) name of the node watched by the debug op.
    )r~   )r   r   r   r   rB     s    zDebugTensorDatum.node_namec             C   s   | j S )zOutput slot index from which the tensor value was dumped.

    Returns:
      (`int`) output slot index watched by the debug op.
    )r}   )r   r   r   r   rC     s    zDebugTensorDatum.output_slotc             C   s   t | j| jS )zName of the tensor watched by the debug op.

    Returns:
      (`str`) `Tensor` name, in the form of `node_name`:`output_slot`
    )rD   rB   rC   )r   r   r   r   tensor_name  s    zDebugTensorDatum.tensor_namec             C   s   t | j| j| jS )zWatch key identities a debug watch on a tensor.

    Returns:
      (`str`) A watch key, in the form of `tensor_name`:`debug_op`.
    )rF   rB   rC   rE   )r   r   r   r   	watch_key  s    
zDebugTensorDatum.watch_keyc             C   s   | j S )z=Path to the file which stores the value of the dumped tensor.)r   )r   r   r   r   r     s    zDebugTensorDatum.file_pathc             C   s   | j S )zSize of the dump file.

    Unit: byte.

    Returns:
      If the dump file exists, size of the dump file, in bytes.
      If the dump file does not exist, None.
    )r   )r   r   r   r   dump_size_bytes  s    z DebugTensorDatum.dump_size_bytesN)r   r   r    r!   r   r   r   r   r"   r   r   rE   rd   rB   rC   r   r   r   r   r   r   r   r   rm     s   
0






rm   c               @   s   e Zd ZdS )'WatchKeyDoesNotExistInDebugDumpDirErrorN)r   r   r    r   r   r   r   r     s   r   c               @   s  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edd Zedd Zedd Zedd Zed d! Zd"d# Zd$d% Zd&d' Zd(d) Zdad+d,Zd-d. Zd/d0 Zd1d2 Zed3d4 Zed5d6 Zd7d8 Zdbd9d:Zdcd;d<Z ddd>d?Z!ded@dAZ"dBdC Z#dfdDdEZ$dgdFdGZ%dHdI Z&dhdJdKZ'dLdM Z(didNdOZ)djdPdQZ*dkdRdSZ+dldTdUZ,dmdVdWZ-dndXdYZ.dodZd[Z/dpd\d]Z0d^d_ Z1dS )qDebugDumpDirzData set from a debug-dump directory on filesystem.

  An instance of `DebugDumpDir` contains all `DebugTensorDatum` instances
  in a tfdbg dump root directory.
  NTc             C   sP   t |std| g | _|| _|   |   |   | || d| _	dS )a  `DebugDumpDir` constructor.

    Args:
      dump_root: (`str`) path to the dump root directory.
      partition_graphs: A repeated field of GraphDefs representing the
          partition graphs executed by the TensorFlow runtime.
      validate: (`bool`) whether the dump files are to be validated against the
          partition graphs.

    Raises:
      IOError: If dump_root does not exist as a directory.
      ValueError: If more than one core metadata file is found under the dump
        root directory.
    z%Dump root directory %s does not existN)
r   ZIsDirectoryIOError_core_metadata
_dump_root_load_core_metadata_load_fetches_info_load_feeds_info_load_all_device_dumps_python_graph)r   r   partition_graphsvalidater   r   r   r     s    
zDebugDumpDir.__init__c             C   s   t tj| jtt d }g | _i | _i | _	i | _
i | _i | _i | _i | _i | _x,|D ]$}t|}| j| | || qXW | || |   x| jD ]}| | qW dS )z#Load the dump data for all devices.*N)r   rg   rh   rc   r   r:   rb   _device_names_t0s_dump_tensor_data_dump_graph_file_paths_debug_watches_watch_key_to_devices_watch_key_to_datum_watch_key_to_rel_time_watch_key_to_dump_size_bytesrl   append_load_device_dumps_load_partition_graphs_calculate_t0_create_tensor_watch_maps)r   r   r   Zdevice_dirsrk   rd   r   r   r   r     s&    
z#DebugDumpDir._load_all_device_dumpsc             C   s   g | j |< tdd | j|< x~t|D ]p\}}}xd|D ]\}t|r\tj	||| j
|< q:| ||}| j | | | j| |j |j |j q:W q*W t| j | dd d| j |< | j | r| j | d j| j|< n
d| j|< dS )ae  Load `DebugTensorDatum` instances from the dump root of a given device.

    Populates a map {device_name: a list of `DebugTensorDatum`}, where the list
    is sorted by ascending timestamp.

    This sorting order reflects the order in which the TensorFlow executor
    processed the nodes of the graph. It is (one of many possible) topological
    sort of the nodes. This is useful for displaying tensors in the debugger
    frontend as well as for the use case in which the user wants to find a
    "culprit tensor", i.e., the first tensor in the graph that exhibits certain
    problematic properties, i.e., all zero values, or bad numerical values such
    as nan and inf.

    In addition, creates a map from node name to debug watches. In this Map,
    the key is the watched node name; the value is a dictionary.
    Of this dictionary, the key is the watched_output_slot.

    This method attempts to load the debug watches from the tensor dump files
    first, before loading the full set of debug watches from the partition
    graphs as done later. This is necessary because sometimes the partition
    graphs may not be available, e.g., when the run errors out.

    Args:
      device_name: (`str`) name of the device.
      device_root: (`str`) dump root directory of the given device.

    Raises:
      ValueError: If GraphDef for the device is not available.
    c               S   s
   t tS )N)collectionsdefaultdictsetr   r   r   r   <lambda>(      z1DebugDumpDir._load_device_dumps.<locals>.<lambda>c             S   s   | j S )N)r   )xr   r   r   r   6  r   )keyr   N)r   r   r   r   r   ZWalkr=   rg   rh   rc   r   _dump_file_name_to_datumr   rB   rC   addrE   sortedr   r   )r   rd   Zdevice_rootrootrN   filesr+   rM   r   r   r   r     s"    


zDebugDumpDir._load_device_dumpsc             C   s*   dd | j  D }|r t|nd| _dS )z1Calculate the first timestamp across all devices.c             S   s   g | ]}|d k	r|qS )Nr   )r]   t0r   r   r   r_   ?  s    z.DebugDumpDir._calculate_t0.<locals>.<listcomp>N)r   valuesmin_t0)r   Zt0sr   r   r   r   =  s    zDebugDumpDir._calculate_t0c          
   C   sl   t tj| jtt d }xJ|D ]B}t|d,}t	
 }||  | jt| W d Q R X q"W d S )Nr   r#   )r   rg   rh   rc   r   r:   CORE_METADATA_TAGr   r%   r   r$   r&   r'   r   r   rY   )r   Zcore_metadata_filesZcore_metadata_filer+   r*   r   r   r   r   B  s    
z DebugDumpDir._load_core_metadatac             C   sD   t tj| jtt d }g | _x|D ]}| jt	| q(W d S )Nr   )
r   rg   rh   rc   r   r:   r>   _run_fetches_infor   r8   )r   Zfetches_info_filesZfetches_info_filer   r   r   r   L  s    
zDebugDumpDir._load_fetches_infoc             C   sD   t tj| jtt d }g | _x|D ]}| jt	| q(W d S )Nr   )
r   rg   rh   rc   r   r:   r@   _run_feed_keys_infor   r8   )r   Zfeeds_info_filesZfeeds_info_filer   r   r   r   T  s    
zDebugDumpDir._load_feeds_infoc             C   s&   t jt j|| j|}t| j|S )a)  Obtain a DebugTensorDatum from the directory and file name.

    Args:
      dir_name: (`str`) Name of the directory in which the dump file resides.
      file_name: (`str`) Base name of the dump file.

    Returns:
      (`DebugTensorDatum`) The `DebugTensorDatum` loaded from the dump file.
    )rg   rh   rc   relpathr   rm   )r   dir_namer<   r   r   r   r   r   \  s    z%DebugDumpDir._dump_file_name_to_datumc             C   s  i | j |< i | j|< i | j|< x| j| D ]}|j| jkrJ|h| j|j< n| j|j | |j| j | kr|g| j | |j< |j| j g| j| |j< |j	g| j| |j< q*| j | |j 
| | j| |j 
|j| j  | j| |j 
|j	 q*W dS )a;  Create maps from tensor watch keys to datum and to timestamps.

    Create a map from watch key (tensor name + debug op) to `DebugTensorDatum`
    item. Also make a map from watch key to relative timestamp.
    "relative" means (absolute timestamp - t0).

    Args:
      device_name: (str) name of the device.
    N)r   r   r   r   r   r   r   r   r   r   r   )r   rd   rM   r   r   r   r   l  s     


z&DebugDumpDir._create_tensor_watch_mapsc             C   sB   || _ i | _| j r>x*| j  D ]}ttt|j| j|j< qW dS )aJ  Provide Python `Graph` object to the wrapper.

    Unlike the partition graphs, which are protobuf `GraphDef` objects, `Graph`
    is a Python object and carries additional information such as the traceback
    of the construction of the nodes in the graph.

    Args:
      python_graph: (ops.Graph) The Python Graph object.
    N)r   _node_tracebackZget_operationstuplemap	tracebackname)r   python_graphopr   r   r   set_python_graph  s
    zDebugDumpDir.set_python_graphc             C   s   | j S )zGet the Python graph.

    Returns:
      If the Python graph has been set, returns a `tf.Graph` object. Otherwise,
      returns None.
    )r   )r   r   r   r   r     s    	zDebugDumpDir.python_graphc             C   s   | j }t|dkr|d S |S )a^  Metadata about the `Session.run()` call from the core runtime.

    Of the three counters available in the return value, `global_step` is
    supplied by the caller of the debugged `Session.run()`, while
    `session_run_index` and `executor_step_index` are determined by the state
    of the core runtime, automatically. For the same fetch list, feed keys and
    debug tensor watch options, the same executor will be used and
    `executor_step_index` should increase by one at a time. However, runs with
    different fetch lists, feed keys and debug_tensor watch options that all
    share the same `Session` object can lead to gaps in `session_run_index`.

    Returns:
      If core metadata are loaded, a `namedtuple` with the fields:
        `global_step`: A global step count supplied by the caller of
          `Session.run()`. It is optional to the caller. If the caller did not
          supply this parameter, its value will be -1.
        `session_run_index`: A sorted index for Run() calls to the underlying
          TensorFlow `Session` object.
        `executor_step_index`: A counter for invocations of a given runtime
          executor. The same executor is re-used for the same fetched tensors,
          target nodes, input feed keys and debug tensor watch options.
        `input_names`: Names of the input (feed) Tensors.
        `output_names`: Names of the output (fetched) Tensors.
        `target_nodes`: Names of the target nodes.
      If the core metadata have not been loaded, `None`.
      If more than one core metadata files exist, return a list of the
        `nametuple` described above.
    r-   r   )r   rj   )r   r   r   r   r   core_metadata  s    zDebugDumpDir.core_metadatac             C   s\   t |  dkr"| j|  d  S | j }g }x|D ]}|| q6W t|dd dS dS )zRetrieve dumped tensor data.r-   r   c             S   s   | j S )N)r   )r   r   r   r   r     r   z1DebugDumpDir.dumped_tensor_data.<locals>.<lambda>)r   N)rj   devicesr   r   extendr   )r   Zall_devices_datadataZdevice_datar   r   r   dumped_tensor_data  s    

zDebugDumpDir.dumped_tensor_datac             C   s   | j S )zAbsolute timestamp of the first dumped tensor across all devices.

    Returns:
      (`int`) absolute timestamp of the first dumped tensor, in microseconds.
    )r   )r   r   r   r   r     s    zDebugDumpDir.t0c                s   t  fdd jD S )zTotal number of dumped tensors in the dump root directory.

    Returns:
      (`int`) The total number of dumped tensors in the dump root directory.
    c             3   s   | ]}t  j| V  qd S )N)rj   r   )r]   rd   )r   r   r   	<genexpr>  s   z$DebugDumpDir.size.<locals>.<genexpr>)sumr   )r   r   )r   r   size  s    zDebugDumpDir.sizec             C   s   i | _ i | _g }xX| jD ]N}d}|| jkr:t| j| }ntd|  | ||}|r|||f qW xP|D ]H\}}t	j
||d}|| j |j< | | |rp|j| jkrp| |j qpW dS )a&  Load and process partition graphs.

    Load the graphs; parse the input and control input structure; obtain the
    device and op type of each node; remove the Copy and debug ops inserted
    by the debugger. The gathered information can be used to validate the
    tensor dumps.

    Args:
      client_partition_graphs: A repeated field of GraphDefs representing the
        partition graphs executed by the TensorFlow runtime, from the Python
        client. These partition graphs are used only if partition graphs
        cannot be loaded from the dump directory on the file system.
      validate: (`bool`) Whether the dump files are to be validated against the
        partition graphs.

    Raises:
      ValueError: If the partition GraphDef of one or more devices fail to be
        loaded.
    NzFailed to load partition graphs for device %s from disk. As a fallback, the client graphs will be used. This may cause mismatches in device names.)rd   )_debug_graphs_node_devicesr   r   r5   loggingwarn_find_partition_graphr   r   Z
DebugGraphrd   _collect_node_devicesr   _validate_dump_with_graphs)r   Zclient_partition_graphsr   Z!partition_graphs_and_device_namesrd   Zpartition_graphZmaybe_device_namedebug_graphr   r   r   r     s.    

z#DebugDumpDir._load_partition_graphsc             C   s@   |d krd S x*|D ]"}x|j D ]}|j|kr|S qW qW d S d S )N)nodedevice)r   r   rd   r4   Znode_defr   r   r   r     s    

z"DebugDumpDir._find_partition_graphc             C   sL   xF|j D ]<}|| jkr4| j| |j | | j|< q|j | | j|< qW d S )N)Znode_devicesr   union)r   r   rB   r   r   r   r   &  s
    

z"DebugDumpDir._collect_node_devicesc             C   s  | j std| | j | }x0| j| D ]"}|j|jkr(td|j|f q(W i }x|jD ]}g ||< |j| }xr|D ]j}t|}t|}	|| j	| krv|	| j	| | krv|j
|dkrv||	f|| krv|| ||	f qvW qZW xt| j| D ]\}
}|j}|j}| j||| |j|
d dsFtd||jt|| f |j| }xP|D ]H}|| }||f|krV| |dkr|dd= n||||f= qVW qW dS )	a
  Validate the dumped tensor data against the partition graphs.

    Only the watched nodes are validated by this method, because tfdbg allows
    clients to watch only a subset of the nodes.

    Args:
      device_name: (`str`) device name.

    Raises:
      LookupError: If the partition graphs have not been loaded yet.
      ValueError: If dumps contain node names not found in partition graph.
        Or if the temporal order of the dump's timestamps violate the
        input relations on the partition graphs.
    z(No partition graphs loaded for device %sz=Node name '%s' is not found in partition graphs of device %s.)ZEnterZNextIterationr-   )start_izdCausality violated in timing relations of debug dumps: %s (%d): these input(s) are not satisfied: %sMergeN)r   LookupErrorr   rB   node_inputsrw   r   get_node_nameZget_output_slotr   node_op_typesgetr   	enumeraterC   _satisfied_at_timestampr   reprnode_recipientsnode_op_typeindex)r   rd   r   rM   Zpending_inputsr   inputsinpZinp_nodeZinp_output_slotiZslotZ
recipientsZ	recipientZrecipient_pending_inputsr   r   r   r   .  sH    








z'DebugDumpDir._validate_dump_with_graphsr   c             C   sj   |sdS xZ| j | |d D ]D}|j|kr,P |j|kr|j|jf|kr||j|jf |sdS qW | S )aG  Determine whether pending inputs are satisfied at given timestamp.

    Note: This method mutates the input argument "pending".

    Args:
      device_name: (str) device name.
      pending: A list of 2-tuple (node_name, output_slot): the dependencies to
        check.
      timestamp: (int) the timestamp in question.
      start_i: (int) the index in self._dump_tensor_data to start searching for
        the timestamp.

    Returns:
      (bool) Whether all the dependencies in pending are satisfied at the
        timestamp. If pending is empty to begin with, return True.
    TN)r   r   rB   rC   remove)r   rd   pendingr   r   rM   r   r   r   r   t  s    

z$DebugDumpDir._satisfied_at_timestampc             C   s
   t | jS )z/Test whether partition graphs have been loaded.)boolr   )r   r   r   r   loaded_partition_graphs  s    z$DebugDumpDir.loaded_partition_graphsc                s"    j std fdd j D S )zGet the partition graphs.

    Returns:
      Partition graphs as a list of GraphDef.

    Raises:
      LookupError: If no partition graphs have been loaded.
    z%No partition graphs have been loaded.c                s   g | ]} j | jqS r   )r   Zdebug_graph_def)r]   r   )r   r   r   r_     s   z1DebugDumpDir.partition_graphs.<locals>.<listcomp>)r   r   )r   r   )r   r   r     s    	
zDebugDumpDir.partition_graphsc             C   s(   i }x| j D ]}| j | j||< qW |S )a  Reconstruct partition graphs with the debugger-inserted ops stripped.

    The reconstructed partition graphs are identical to the original (i.e.,
    non-debugger-decorated) partition graphs except in the following respects:
      1) The exact names of the runtime-inserted internal nodes may differ.
         These include _Send, _Recv, _HostSend, _HostRecv, _Retval ops.
      2) As a consequence of 1, the nodes that receive input directly from such
         send- and recv-type ops will have different input names.
      3) The parallel_iteration attribute of while-loop Enter ops are set to 1.

    Returns:
      A dict mapping device names (`str`s) to reconstructed
      `tf.compat.v1.GraphDef`s.
    )r   Znon_debug_graph_def)r   Znon_debug_graphsr   r   r   r   (reconstructed_non_debug_partition_graphs  s    z5DebugDumpDir.reconstructed_non_debug_partition_graphsc             C   s   | j }t|dkr|d S |S )ax  Get a str representation of the fetches used in the Session.run() call.

    Returns:
      If the information is available from one `Session.run` call, a `str`
        obtained from `repr(fetches)`.
      If the information is available from multiple `Session.run` calls, a
        `list` of `str` from `repr(fetches)`.
      If the information is not available, `None`.
    r-   r   )r   rj   )r   r   r   r   r   run_fetches_info  s    zDebugDumpDir.run_fetches_infoc             C   s   | j }t|dkr|d S |S )a  Get a str representation of the feed_dict used in the Session.run() call.

    Returns:
      If the information is available from one `Session.run` call, a `str`
        obtained from `repr(feed_dict)`.
      If the information is available from multiple `Session.run` calls, a
        `list` of `str` obtained from `repr(feed_dict)`.
      If the information is not available, `None`.
    r-   r   )r   rj   )r   r   r   r   r   run_feed_keys_info  s    zDebugDumpDir.run_feed_keys_infoc             C   sr   |dkrj|| j krRt| j | dkr6t| j | d S tdt| j | |f qntdt| j|f n|S dS )aE  Infer the device name given node name.

    If device_name is provided (i.e., not None), it'll be simply returned right
    away.

    Args:
      device_name: (str or None) name of the device. If None, will try to infer
        the device name by looking at the available nodes.
      node_name: (str) name of the node.

    Returns:
      (str) Inferred name of the device, if available.

    Raises:
      ValueError: If the node name does not exist on any of the available
        devices or if there are multiple devices that contain the node with
        the given name.
    Nr-   r   zWThere are multiple (%d) devices with nodes named '%s' but device_name is not specified.z/None of the %d device(s) has a node named '%s'.)r   rj   listrw   r   )r   rd   rB   r   r   r   _infer_device_name  s    
zDebugDumpDir._infer_device_namec             C   sn   | j std|dkrDg }x$| j D ]}|| j | j  q"W |S || j krZtd| | j | j S dS )ao  Get a list of all nodes from the partition graphs.

    Args:
      device_name: (`str`) name of device. If None, all nodes from all available
        devices will be included.

    Returns:
      All nodes' names, as a list of str.

    Raises:
      LookupError: If no partition graphs have been loaded.
      ValueError: If specified node name does not exist.
    z%No partition graphs have been loaded.NzInvalid device name: %s)r   r   r   r   keysrw   )r   rd   nodesr   r   r   r     s    
zDebugDumpDir.nodesc             C   s*   | j std| ||}| j | j| S )aj  Get the attributes of a node.

    Args:
      node_name: Name of the node in question.
      device_name: (`str`) name of the device. If there is only one device or if
        node_name exists on only one device, this argument is optional.

    Returns:
      Attributes of the node.

    Raises:
      LookupError: If no partition graphs have been loaded.
    z%No partition graphs have been loaded.)r   r   r   node_attributes)r   rB   rd   r   r   r   r     s    zDebugDumpDir.node_attributesFc             C   sB   | j std| ||}|r.| j | j| S | j | j| S dS )aD  Get the inputs of given node according to partition graphs.

    Args:
      node_name: Name of the node.
      is_control: (`bool`) Whether control inputs, rather than non-control
        inputs, are to be returned.
      device_name: (`str`) name of the device. If there is only one device or if
        node_name exists on only one device, this argument is optional.

    Returns:
      (`list` of `str`) inputs to the node, as a list of node names.

    Raises:
      LookupError: If node inputs and control inputs have not been loaded
         from partition graphs yet.
    z5Node inputs are not loaded from partition graphs yet.N)r   r   r   node_ctrl_inputsr   )r   rB   
is_controlrd   r   r   r   r   '  s    zDebugDumpDir.node_inputsc             C   sz   | j std| ||}| j | jg}|r>|| j | j |rT|| j | j tj|| 	|d}|
| | S )a  Get the transitive inputs of given node according to partition graphs.

    Args:
      node_name: Name of the node.
      include_control: Include control inputs (True by default).
      include_reversed_ref: Whether a ref input, say from A to B, is to be also
        considered as an input from B to A. The rationale is that ref inputs
        generally let the recipient (e.g., B in this case) mutate the value of
        the source (e.g., A in this case). So the reverse direction of the ref
        edge reflects the direction of information flow.
      device_name: (`str`) name of the device. If there is only one device or if
        node_name exists on only one device, this argument is optional.

    Returns:
      (`list` of `str`) all transitive inputs to the node, as a list of node
        names.

    Raises:
      LookupError: If node inputs and control inputs have not been loaded
         from partition graphs yet.
    z5Node inputs are not loaded from partition graphs yet.)skip_node_names)r   r   r   r   r   r   node_reversed_ref_inputsr   DFSGraphTracer_get_merge_node_namestracer   )r   rB   include_controlinclude_reversed_refrd   input_liststracerr   r   r   transitive_inputsB  s    
zDebugDumpDir.transitive_inputsc                s^   || j krtd| t| ds&i | _|| jkrT| j|   fdd jD | j|< | j| S )z3Lazily get a list of Merge nodes on a given device.zInvalid device name: %s_merge_node_namesc                s   g | ]} j | d kr|qS )r   )r   )r]   r   )r   r   r   r_   x  s    z6DebugDumpDir._get_merge_node_names.<locals>.<listcomp>)r   rw   hasattrr   r   r   )r   rd   r   )r   r   r   n  s    



z"DebugDumpDir._get_merge_node_namesc             C   s  |  ||}|  ||}||kr4td||||f | j| jg}| j| }	|r\||	j |rl||	j tj|| 	||d}
y|

| W nz tjk
r
   |g|
  }dg|
  }g }|d }x8tt|t|D ]"\}}||kr|| |d8 }qW |S X dS )a  Find a path between a source node and a destination node.

    Limitation: the source and destination are required to be on the same
    device, i.e., this method does not yet take into account Send/Recv nodes
    across devices.

    TODO(cais): Make this method work across device edges by tracing Send/Recv
      nodes.

    Args:
      src_node_name: (`str`) name of the source node or name of an output tensor
        of the node.
      dst_node_name: (`str`) name of the destination node or name of an output
        tensor of the node.
      include_control: (`bool`) whrther control edges are considered in the
        graph tracing.
      include_reversed_ref: Whether a ref input, say from A to B, is to be also
        considered as an input from B to A. The rationale is that ref inputs
        generally let the recipient (e.g., B in this case) mutate the value of
        the source (e.g., A in this case). So the reverse direction of the ref
        edge reflects the direction of information flow.
      device_name: (`str`) name of the device. If there is only one device or if
        node_name exists on only one device, this argument is optional.

    Returns:
      A path from the src_node_name to dst_node_name, as a `list` of `str`, if
      it exists. The list includes src_node_name as the first item and
      dst_node_name as the last.
      If such a path does not exist, `None`.

    Raises:
      ValueError: If the source and destination nodes are not on the same
        device.
    zFSource (%s) and destination (%s) are not on the same device: %s vs. %s)r   Zdestination_node_namer   rn   r-   N)r   rw   r   r   r   r   r   r   r   r   r   ZGraphTracingReachedDestinationr   
depth_listzipreversed)r   Zsrc_node_nameZdst_node_namer   r   rd   Zsrc_device_nameZdst_device_namer   r   r   r   r  rh   Z
curr_depthr   depthr   r   r   find_some_path|  s:    (


zDebugDumpDir.find_some_pathc             C   s@   | j std| ||}| j | }|r2|j| S |j| S dS )a^  Get recipient of the given node's output according to partition graphs.

    Args:
      node_name: (`str`) name of the node.
      is_control: (`bool`) whether control outputs, rather than non-control
        outputs, are to be returned.
      device_name: (`str`) name of the device. If there is only one device or if
        node_name exists on only one device, this argument is optional.

    Returns:
      (`list` of `str`) all inputs to the node, as a list of node names.

    Raises:
      LookupError: If node inputs and control inputs have not been loaded
         from partition graphs yet.
    z9Node recipients are not loaded from partition graphs yet.N)r   r   r   Znode_ctrl_recipientsr   )r   rB   r   rd   r   r   r   r   r     s    

zDebugDumpDir.node_recipientsc             C   s   | j S )z^Get the list of device names.

    Returns:
      (`list` of `str`) names of the devices.
    )r   )r   r   r   r   r     s    zDebugDumpDir.devicesc             C   sV   | j std|dk	r,|| j kr,td| x$| j  D ]\}}||jkr8dS q8W dS )a  Test if a node exists in the partition graphs.

    Args:
      node_name: (`str`) name of the node to be checked.
      device_name: optional device name. If None, will search for the node
        on all available devices. Otherwise, search for the node only on
        the given device.

    Returns:
      A boolean indicating whether the node exists.

    Raises:
      LookupError: If no partition graphs have been loaded yet.
      ValueError: If device_name is specified but cannot be found.
    z5Nodes have not been loaded from partition graphs yet.Nz/The specified device_name '%s' cannot be found.TF)r   r   rw   itemsr   )r   rB   rd   rN   r   r   r   r   node_exists  s    

zDebugDumpDir.node_existsc             C   sJ   | j std|| jkr$td| t| j| }t|dkrF|d S |S )a  Get the names of the devices that has nodes of the specified name.

    Args:
      node_name: (`str`) name of the node.

    Returns:
      (`str` or `list` of `str`) name of the device(s) on which the node of the
        given name is found. Returns a `str` if there is only one such device,
        otherwise return a `list` of `str`.

    Raises:
      LookupError: If node inputs and control inputs have not been loaded
         from partition graphs yet.
      ValueError: If the node does not exist in partition graphs.
    z6Node devices are not loaded from partition graphs yet.z-Node '%s' does not exist in partition graphs.r-   r   )r   r   r   rw   r   rj   )r   rB   r   r   r   r   node_device  s    
zDebugDumpDir.node_devicec             C   s*   | j std| ||}| j | j| S )a  Get the op type of given node.

    Args:
      node_name: (`str`) name of the node.
      device_name: (`str`) name of the device. If there is only one device or if
        node_name exists on only one device, this argument is optional.

    Returns:
      (`str`) op type of the node.

    Raises:
      LookupError: If node op types have not been loaded
         from partition graphs yet.
    z7Node op types are not loaded from partition graphs yet.)r   r   r   r   )r   rB   rd   r   r   r   r   '  s
    zDebugDumpDir.node_op_typec             C   s   y|  ||}W n tk
r$   g S X || j| kr8g S g }xH| j| | D ]6}| j| | | }x|D ]}|t||| qhW qLW |S )a-  Get all tensor watch keys of given node according to partition graphs.

    Args:
      node_name: (`str`) name of the node.
      device_name: (`str`) name of the device. If there is only one device or if
        node_name exists on only one device, this argument is optional.

    Returns:
      (`list` of `str`) all debug tensor watch keys. Returns an empty list if
        the node name does not correspond to any debug watch keys.

    Raises:
      `LookupError`: If debug watch information has not been loaded from
        partition graphs yet.
    )r   rw   r   r   rF   )r   rB   rd   Z
watch_keysZwatched_slotZ	debug_opsrE   r   r   r   debug_watch_keys=  s    
zDebugDumpDir.debug_watch_keysc                sz   |dkrR fddj D }|s&g S t|dkr<|d }qhtd t|f n|jkrhtd| j |  g S )ad  Get all `DebugTensorDatum` instances corresponding to a debug watch key.

    Args:
      debug_watch_key: (`str`) debug watch key.
      device_name: (`str`) name of the device. If there is only one device or if
        the specified debug_watch_key exists on only one device, this argument
        is optional.

    Returns:
      A list of `DebugTensorDatum` instances that correspond to the debug watch
      key. If the watch key does not exist, returns an empty list.

    Raises:
      ValueError: If there are multiple devices that have the debug_watch_key,
        but device_name is not specified.
    Nc                s   g | ]} j | kr|qS r   )r   )r]   r   )debug_watch_keyr   r   r   r_   r  s    z2DebugDumpDir.watch_key_to_data.<locals>.<listcomp>r-   r   z[The debug watch key '%s' exists on multiple (%d) devices, but device name is not specified.z=There is no device named '%s' consisting of debug watch keys.)r   rj   rw   Z_debug_key_to_datumr   )r   r  rd   Zmatching_device_namesr   )r  r   r   watch_key_to_data_  s    

zDebugDumpDir.watch_key_to_datac             C   s   |rt |}g }xx|dkr"| jn
| j| fD ]Z}xT| j| D ]F}|rT||jrTq>||| r>|| |dkr>t||kr>|S q>W q.W |S )a$  Find dumped tensor data by a certain predicate.

    Args:
      predicate: A callable that takes two input arguments:

        ```python
        def predicate(debug_tensor_datum, tensor):
          # returns a bool
        ```

        where `debug_tensor_datum` is an instance of `DebugTensorDatum`, which
        carries the metadata, such as the `Tensor`'s node name, output slot
        timestamp, debug op name, etc.; and `tensor` is the dumped tensor value
        as a `numpy.ndarray`.
      first_n: (`int`) return only the first n `DebugTensotDatum` instances (in
        time order) for which the predicate returns True. To return all the
        `DebugTensotDatum` instances, let first_n be <= 0.
      device_name: optional device name.
      exclude_node_names: Optional regular expression to exclude nodes with
        names matching the regular expression.

    Returns:
      A list of all `DebugTensorDatum` objects in this `DebugDumpDir` object
       for which predicate returns True, sorted in ascending order of the
       timestamp.
    Nr   )recompiler   matchrB   r   r   rj   )r   	predicateZfirst_nrd   Zexclude_node_namesZmatched_datar   rM   r   r   r   rz     s    

zDebugDumpDir.findc             C   sN   |  ||}t|||}|| j| kr6td||f dd | j| | D S )a  Get the file paths from a debug-dumped tensor.

    Args:
      node_name: (`str`) name of the node that the tensor is produced by.
      output_slot: (`int`) output slot index of tensor.
      debug_op: (`str`) name of the debug op.
      device_name: (`str`) name of the device. If there is only one device or if
        the specified debug_watch_key exists on only one device, this argument
        is optional.

    Returns:
      List of file path(s) loaded. This is a list because each debugged tensor
        may be dumped multiple times.

    Raises:
      WatchKeyDoesNotExistInDebugDumpDirError: If the tensor does not exist in
        the debug-dump data.
    z<Watch key "%s" does not exist in the debug dump of device %sc             S   s   g | ]
}|j qS r   )r   )r]   rM   r   r   r   r_     s    z6DebugDumpDir.get_tensor_file_paths.<locals>.<listcomp>)r   rF   r   r   )r   rB   rC   rE   rd   r   r   r   r   get_tensor_file_paths  s    z"DebugDumpDir.get_tensor_file_pathsc          	   C   s^   t |||}y$| ||}dd | j| | D S  ttfk
rX   td||f Y nX dS )a  Get the tensor value from for a debug-dumped tensor.

    The tensor may be dumped multiple times in the dump root directory, so a
    list of tensors (`numpy.ndarray`) is returned.

    Args:
      node_name: (`str`) name of the node that the tensor is produced by.
      output_slot: (`int`) output slot index of tensor.
      debug_op: (`str`) name of the debug op.
      device_name: (`str`) name of the device. If there is only one device or if
        the specified debug_watch_key exists on only one device, this argument
        is optional.

    Returns:
      List of tensors (`numpy.ndarray`) loaded from the debug-dump file(s).

    Raises:
      WatchKeyDoesNotExistInDebugDumpDirError: If the tensor does not exist in
        the debug-dump data.
    c             S   s   g | ]}|  qS r   )r   )r]   rM   r   r   r   r_     s    z,DebugDumpDir.get_tensors.<locals>.<listcomp>z<Watch key "%s" does not exist in the debug dump of device %sN)rF   r   r   rw   r2   r   )r   rB   rC   rE   rd   r   r   r   r   get_tensors  s    zDebugDumpDir.get_tensorsc             C   s@   |  ||}t|||}|| j| kr2td| | j| | S )a  Get the relative timestamp from for a debug-dumped tensor.

    Relative timestamp means (absolute timestamp - `t0`), where `t0` is the
    absolute timestamp of the first dumped tensor in the dump root. The tensor
    may be dumped multiple times in the dump root directory, so a list of
    relative timestamps (`numpy.ndarray`) is returned.

    Args:
      node_name: (`str`) name of the node that the tensor is produced by.
      output_slot: (`int`) output slot index of tensor.
      debug_op: (`str`) name of the debug op.
      device_name: (`str`) name of the device. If there is only one device or if
        the specified debug_watch_key exists on only one device, this argument
        is optional.

    Returns:
      (`list` of `int`) list of relative timestamps.

    Raises:
      WatchKeyDoesNotExistInDebugDumpDirError: If the tensor watch key does not
        exist in the debug dump data.
    z/Watch key "%s" does not exist in the debug dump)r   rF   r   r   r   )r   rB   rC   rE   rd   r   r   r   r   get_rel_timestamps  s    
zDebugDumpDir.get_rel_timestampsc             C   sD   |  ||}t|||}|| j| kr6td||f | j| | S )a  Get the sizes of the dump files for a debug-dumped tensor.

    Unit of the file size: byte.

    Args:
      node_name: (`str`) name of the node that the tensor is produced by.
      output_slot: (`int`) output slot index of tensor.
      debug_op: (`str`) name of the debug op.
      device_name: (`str`) name of the device. If there is only one device or if
        the specified debug_watch_key exists on only one device, this argument
        is optional.

    Returns:
      (`list` of `int`): list of dump file sizes in bytes.

    Raises:
      WatchKeyDoesNotExistInDebugDumpDirError: If the tensor watch key does not
        exist in the debug dump data.
    z<Watch key "%s" does not exist in the debug dump of device %s)r   rF   r   r   r   )r   rB   rC   rE   rd   r   r   r   r   get_dump_sizes_bytes  s    z!DebugDumpDir.get_dump_sizes_bytesc             C   s<   | j dkrtdt|}|| jkr2td| | j| S )a  Try to retrieve the Python traceback of node's construction.

    Args:
      element_name: (`str`) Name of a graph element (node or tensor).

    Returns:
      (list) The traceback list object as returned by the `extract_trace`
        method of Python's traceback module.

    Raises:
      LookupError: If Python graph is not available for traceback lookup.
      KeyError: If the node cannot be found in the Python graph loaded.
    Nz2Python graph is not available for traceback lookupz%Cannot find node "%s" in Python graph)r   r   r   r   r   r2   )r   Zelement_namerB   r   r   r   node_traceback>  s    


zDebugDumpDir.node_traceback)NT)r   )N)N)FN)TFN)TFN)FN)N)N)N)N)r   NN)N)N)N)N)2r   r   r    r!   r   r   r   r   r   r   r   r   r   r   r"   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r   r  r	  r   r
  r  rz   r  r  r  r  r  r   r   r   r   r     sh   
6
!"	
2
F
"


  
(  
I



"
'  
1

$
%
r   )4r!   r   r   rV   rg   r   r  numpyrH   Ztensorflow.core.frameworkr   r   Ztensorflow.core.utilr   Ztensorflow.python.debug.libr   Ztensorflow.python.frameworkr   Ztensorflow.python.platformr   r   r   Ztensorflow.python.utilr	   r:   r   r;   rb   ZHASH_TAGr>   r@   r   r   r,   r(   r5   r8   r=   r?   rA   rD   rF   rO   
namedtuplerX   rY   re   rl   rm   rw   r   r   r   r   r   r   <module>   sX   & 

 :