
    1VhGa                     N    d Z ddlZddlmZ dZdZdZd Zd Zd	 Z	 G d
 d      Z
y)zCA wrapper around DebugDataReader used for retrieving tfdbg v2 data.    N)errors__default_debugger_run__i     c                      t        j                          fd}t        j                  |d      }|j                          |fS )a  Run a target task repeatedly in the background.

    In the context of this module, `target` is the `update()` method of the
    underlying reader for tfdbg2-format data.
    This method is mocked by unit tests for deterministic behaviors during
    testing.

    Args:
      target: The target task to run in the background, a callable with no args.
      interval_sec: Time interval between repeats, in seconds.

    Returns:
      - A `threading.Event` object that can be used to interrupt an ongoing
          waiting interval between successive runs of `target`. To interrupt the
          interval, call the `set()` method of the object.
      - The `threading.Thread` object on which `target` is run repeatedly.
    c                  X    	           j                          j                          )N)waitclear)eventinterval_sectargets   f/home/dcms/DCMS/lib/python3.12/site-packages/tensorboard/plugins/debugger_v2/debug_data_multiplexer.py_run_repeatedlyz5run_repeatedly_in_background.<locals>._run_repeatedly<   s%    HJJ|$KKM     T)r   daemon)	threadingEventThreadstart)r   r   r   threadr   s   ``  @r   run_repeatedly_in_backgroundr   (   s=    $ OOE _TBF
LLN&=r   c           
          ddl m} t        | |j                        r\d| j                  | j
                  | j                  | j                  | j                  | j                  | j                  | j                  d	S t        dt        |       z        )Nr   debug_events_monitorsInfNanAlert)	
alert_typeop_typeoutput_slotsizenum_neg_infnum_pos_infnum_nanexecution_indexgraph_execution_trace_indexzUnrecognized alert subtype: %s)tensorflow.python.debug.libr   
isinstancer   r   r   r   r    r!   r"   r#   r$   	TypeErrortype)alertr   s     r   _alert_to_jsonr*   H   s     B%.::;'}} ,, JJ ,, ,,}}$44+0+L+L
 	
 84;FGGr   c                 `    d}d| v r#| j                  d      \  }}t        |      }||fS | }||fS )z@Helper function that extracts op name and slot from tensor name.r   :)splitint)tensor_namer   op_names      r   parse_tensor_namer1   _   sM    K
k*005+& K Kr   c                       e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
dd
Zd Zd ZddZddZd Zd Zd Zd Zd Zd Zd Zy	)DebuggerV2EventMultiplexera  A class used for accessing tfdbg v2 DebugEvent data on local filesystem.

    This class is a short-term hack, mirroring the EventMultiplexer for the main
    TensorBoard plugins (e.g., scalar, histogram and graphs.) As such, it only
    implements the methods relevant to the Debugger V2 pluggin.

    TODO(cais): Integrate it with EventMultiplexer and use the integrated class
    from MultiplexerDataProvider for a single path of accessing debugger and
    non-debugger data.
    c                     || _         d| _        t        j                         | _        d| _        | j                          y)zConstructor for the `DebugEventMultiplexer`.

        Args:
          logdir: Path to the directory to load the tfdbg v2 data from.
        N)_logdir_readerr   Lock_reader_lock_reload_needed_event_tryCreateReader)selflogdirs     r   __init__z#DebuggerV2EventMultiplexer.__init__v   s7     %NN,$(! 	r   c                    | j                   ry| j                  5  | j                   s	 ddlm} ddlm} 	 |j                  | j                        | _         |j                  | j                   t              g| _        t        | j                   j                  t              \  | _        }ddd       y# t
        $ r Y ddd       yw xY w# t        $ r Y ddd       yt        $ r Y ddd       yw xY w# 1 sw Y   yxY w)a*  Try creating reader for tfdbg2 data in the logdir.

        If the reader has already been created, a new one will not be created and
        this function is a no-op.

        If a reader has not been created, create it and start periodic calls to
        `update()` on a separate thread.
        Nr   )debug_events_readerr   )limit)r6   r8   r%   r?   r   ImportErrorDebugDataReaderr5   AttributeError
ValueErrorInfNanMonitorDEFAULT_PER_TYPE_ALERT_LIMIT	_monitorsr   updateDEFAULT_RELOAD_INTERVAL_SECr9   )r;   r?   r   _s       r   r:   z+DebuggerV2EventMultiplexer._tryCreateReader   s    << %	<< P#6#F#F$DL *77,H 8 "
 0LLL'')D0,)1G%	 %	 #  %	 %	 & 
 1%	 %	2 "  9%	 %	23%	 %	sX   C1B1 CAC11	C:C1CC1	C.C1C.#C1-C..C11C:c                 R    | j                   r| j                   j                          yy)a(  If a reader exists and has started period updating, unblock the update.

        The updates are performed periodically with a sleep interval between
        successive calls to the reader's update() method. Calling this method
        interrupts the sleep immediately if one is ongoing.
        N)r9   setr;   s    r   _reloadReaderz(DebuggerV2EventMultiplexer._reloadReader   s$     $$%%))+ %r   c                     | j                   t        d      |t        k7  rt        dt        d|      | j                   j                         S )aW  Return the timestamp of the first DebugEvent of the given run.

        This may perform I/O if no events have been loaded yet for the run.

        Args:
          run: A string name of the run for which the timestamp is retrieved.
            This currently must be hardcoded as `DEFAULT_DEBUGGER_RUN_NAME`,
            as each logdir contains at most one DebugEvent file set (i.e., a
            run of a tfdbg2-instrumented TensorFlow program.)

        Returns:
            The wall_time of the first event of the run, which will be in seconds
            since the epoch as a `float`.
        zNo tfdbg2 runs exists.zExpected run name to be z
, but got )r6   rD   DEFAULT_DEBUGGER_RUN_NAMEstarting_wall_time)r;   runs     r   FirstEventTimestampz.DebuggerV2EventMultiplexer.FirstEventTimestamp   sO     <<566++,c3  ||..00r   c                     t        d      )NzLDebugDataMultiplexer.PluginRunToTagToContent() has not been implemented yet.)NotImplementedError)r;   plugin_names     r   PluginRunToTagToContentz2DebuggerV2EventMultiplexer.PluginRunToTagToContent   s    !
 	
r   c                 r    | j                          | j                  r| j                          t        dg iiS i S )a  Return all the tfdbg2 run names in the logdir watched by this instance.

        The `Run()` method of this class is specialized for the tfdbg2-format
        DebugEvent files.

        As a side effect, this method unblocks the underlying reader's period
        reloading if a reader exists. This lets the reader update at a higher
        frequency than the default one with 30-second sleeping period between
        reloading when data is being queried actively from this instance.
        Note that this `Runs()` method is used by all other public data-access
        methods of this class (e.g., `ExecutionData()`, `GraphExecutionData()`).
        Hence calls to those methods will lead to accelerated data reloading of
        the reader.

        Returns:
          If tfdbg2-format data exists in the `logdir` of this object, returns:
              ```
              {runName: { "debugger-v2": [tag1, tag2, tag3] } }
              ```
              where `runName` is the hard-coded string `DEFAULT_DEBUGGER_RUN_NAME`
              string. This is related to the fact that tfdbg2 currently contains
              at most one DebugEvent file set per directory.
          If no tfdbg2-format data exists in the `logdir`, an empty `dict`.
        zdebugger-v2)r:   r6   rN   rP   rM   s    r   RunszDebuggerV2EventMultiplexer.Runs   sE    8 	<<  ) "2,  Ir   c                     |dk  rt        j                  d|z        ||kD  rt        j                  d||fz        |dk\  r||k  rt        j                  d||fz        |dk  r|}|S )Nr   zInvalid begin index (%d)z!end index (%d) out of bounds (%d)z9end index (%d) is unexpectedly less than begin index (%d))r   InvalidArgumentError)r;   beginendtotal_counts       r   _checkBeginEndIndicesz0DebuggerV2EventMultiplexer._checkBeginEndIndices
  s    19--*U2  --3sK6HH  !8e--K,  7C
r   Nc                    ddl m} | j                         }||vryg }t               }t               }	| j                  D ]T  }
|
j                         }|s|j                  |       t        |
|j                        rd}nd}t        |      ||<   ||	|<   V t        |      }|!||vrt        j                  d|z        |	|   }| j                  ||t        |            }|||||t        ||| D cg c]  }t        |       c}dS c c}w )a  Get alerts from the debugged TensorFlow program.

        Args:
          run: The tfdbg2 run to get Alerts from.
          begin: Beginning alert index.
          end: Ending alert index.
          alert_type_filter: Optional filter string for alert type, used to
            restrict retrieved alerts data to a single type. If used,
            `begin` and `end` refer to the beginning and ending indices within
            the filtered alert type.
        r   r   Nr   __MiscellaneousAlert__z8Filtering of alerts failed: alert type %s does not exist)r\   r]   r   
num_alertsalerts_breakdownper_type_alert_limitalerts)r%   r   rY   dictrG   re   extendr&   rE   lenr   r[   r_   rF   r*   )r;   rR   r\   r]   alert_type_filterr   runsre   rc   alerts_by_typemonitormonitor_alertsr   rb   r)   s                  r   Alertsz!DebuggerV2EventMultiplexer.Alerts  s2    	Fyy{d?6~~ 	8G$^^-N!MM.) '#8#F#FG*
5
+.~+>Z()7N:&	8 [
( (8811N'(  $$56F((S[A+$ 0$@:@s:KL~e,L
 	
 Ms   0Dc                    | j                         }||vry| j                  j                  d      }| j                  ||t	        |            }||t	        |      ||| D cg c]  }|j                          c}dS c c}w )a>  Get ExecutionDigests.

        Args:
          run: The tfdbg2 run to get `ExecutionDigest`s from.
          begin: Beginning execution index.
          end: Ending execution index.

        Returns:
          A JSON-serializable object containing the `ExecutionDigest`s and
          related meta-information
        NTdigest)r\   r]   num_digestsexecution_digestsrY   r6   
executionsr_   rh   to_json)r;   rR   r\   r]   rj   rs   rq   s          r   ExecutionDigestsz+DebuggerV2EventMultiplexer.ExecutionDigestsQ  s     yy{d? !LL3343@((S9J5KL01/@s/K"%+ "	
 	
"s   !A=
c                 0   | j                         }||vry| j                  j                  d      }| j                  ||t	        |            }||| }| j                  j                  d||      }|||D cg c]  }|j                          c}dS c c}w )a`  Get Execution data objects (Detailed, non-digest form).

        Args:
          run: The tfdbg2 run to get `ExecutionDigest`s from.
          begin: Beginning execution index.
          end: Ending execution index.

        Returns:
          A JSON-serializable object containing the `ExecutionDigest`s and
          related meta-information
        NTrp   Frq   r\   r]   )r\   r]   ru   rt   )r;   rR   r\   r]   rj   rs   ru   	executions           r   ExecutionDataz(DebuggerV2EventMultiplexer.ExecutionDatam  s     yy{d? LL3343@((S9J5KL-eC8\\,,EC,P
@JK99,,.K
 	
 Ls   7Bc                    | j                         }||vry|t        d      | j                  j                  d      }| j	                  ||t        |            }||t        |      ||| D cg c]  }|j                          c}dS c c}w )a`  Get `GraphExecutionTraceDigest`s.

        Args:
          run: The tfdbg2 run to get `GraphExecutionTraceDigest`s from.
          begin: Beginning graph-execution index.
          end: Ending graph-execution index.

        Returns:
          A JSON-serializable object containing the `ExecutionDigest`s and
          related meta-information
        NzFtrace_id support for GraphExecutionTraceDigest is not implemented yet.Trp   )r\   r]   rr   graph_execution_digestsrY   rU   r6   graph_execution_tracesr_   rh   rv   )r;   rR   r\   r]   trace_idrj   graph_exec_digestsrq   s           r   GraphExecutionDigestsz0DebuggerV2EventMultiplexer.GraphExecutionDigests  s     yy{d? %'  "\\@@@M((S9K5LM12/A%/L(%+ (	
 	
(s   .B

c                 @   | j                         }||vry|t        d      | j                  j                  d      }| j	                  ||t        |            }| j                  j                  d||      }|||D cg c]  }|j                          c}dS c c}w )aT  Get `GraphExecutionTrace`s.

        Args:
          run: The tfdbg2 run to get `GraphExecutionTrace`s from.
          begin: Beginning graph-execution index.
          end: Ending graph-execution index.

        Returns:
          A JSON-serializable object containing the `ExecutionDigest`s and
          related meta-information
        NzDtrace_id support for GraphExecutionTraceData is not implemented yet.Trp   Fry   )r\   r]   graph_executionsr~   )	r;   rR   r\   r]   r   rj   digestsr   
graph_execs	            r   GraphExecutionDataz-DebuggerV2EventMultiplexer.GraphExecutionData  s     yy{d? %'  ,,55T5B((S\B<<>>3 ? 
 7G!)3
""$!
 	
!s   ?Bc                     | j                         }||vry	 | j                  j                  |      }|j                         S # t        $ r t	        j
                  d|z        w xY w)a  Get the information regarding a TensorFlow graph.

        Args:
          run: Name of the run.
          graph_id: Debugger-generated ID of the graph in question.
            This information is available in the return values
            of `GraphOpInfo`, `GraphExecution`, etc.

        Returns:
          A JSON-serializable object containing the information regarding
            the TensorFlow graph.

        Raises:
          NotFoundError if the graph_id is not known to the debugger.
        NThere is no graph with ID "%s")rY   r6   graph_by_idKeyErrorr   NotFoundErrorrv   )r;   rR   graph_idrj   graphs        r   	GraphInfoz$DebuggerV2EventMultiplexer.GraphInfo  sl      yy{d?	LL,,X6E
 }}	  	&&08; 	s   A "A$c                 z   | j                         }||vry	 | j                  j                  |      }	 |j                  |      }| j                  ||      }|d   D ]/  }	 |j                  |d         }	|	s| j                  |	|      |d<   1 |d	   D ]6  }
|
D ]/  }	 |j                  |d         }|s| j                  ||      |d<   1 8 |S # t        $ r t	        j
                  d|z        w xY w# t        $ r t	        j
                  d|d|d      w xY w# t        $ r d}	Y w xY w# t        $ r d}Y w xY w)
ab  Get the information regarding a graph op's creation.

        Args:
          run: Name of the run.
          graph_id: Debugger-generated ID of the graph that contains
            the op in question. This ID is available from other methods
            of this class, e.g., the return value of `GraphExecutionDigests()`.
          op_name: Name of the op.

        Returns:
          A JSON-serializable object containing the information regarding
            the op's creation and its immediate inputs and consumers.

        Raises:
          NotFoundError if the graph_id or op_name does not exist.
        Nr   zThere is no op named "z" in graph with ID ""inputsr0   data	consumers)rY   r6   r   r   r   r   get_op_creation_digest_opCreationDigestToDataObject)r;   rR   r   r0   rj   r   op_creation_digestdata_object
input_specinput_op_digestslot_consumer_specsconsumer_specrq   s                r   GraphOpInfoz&DebuggerV2EventMultiplexer.GraphOpInfo  s   " yy{d?	LL,,X6E
	!&!=!=g!F 88
 &h/ 
	J'"'">">y)#
 %)%G%G#U&
6"
	 $/{#; 	!4 
""99%i0F
 ,0,N,N-M&)
	 O  	&&08; 	  	&&H& 	  '"&'   "!F"s:   C C2 DD,"C/2&DD)(D),D:9D:c                    |y |j                         }|d= | j                  |j                        |d<   |j                  |d<   |d= g |d<   |j                  xs g D ]'  }t        |      \  }}|d   j                  ||d       ) g |d<   t        |d         D ]  }|d   j                  g         |j                  |d         D ]   \  }}	}
|d   |   j                  |	|
d	       " |S )
Nr   	graph_idsnum_outputsinput_namesr   )r0   r   r   r0   )r0   
input_slot)	rv   _getGraphStackIdsr   r   r   r1   appendrangeget_op_consumers)r;   r   r   json_objectinput_tensor_nameinput_op_namer   rJ   src_slotconsumer_op_namedst_slots              r   r   z8DebuggerV2EventMultiplexer._opCreationDigestToDataObject$  s5   %(002
##'#9#9''$
K  &8%C%CM"& "H!3!?!?!E2 	):;L)M&M;!(()+F	
 $&K {=12 	0A$++B/	0494J4J	"5
 	0H& $X.55,HE	 r   c                     |g}| j                   j                  |      }|j                  rN|j                  d|j                         | j                   j                  |j                        }|j                  rN|S )aL  Retrieve the IDs of all outer graphs of a graph.

        Args:
          graph_id: Id of the graph being queried with respect to its outer
            graphs context.

        Returns:
          A list of graph_ids, ordered from outermost to innermost, including
            the input `graph_id` argument as the last item.
        r   )r6   r   outer_graph_idinsert)r;   r   r   r   s       r   r   z,DebuggerV2EventMultiplexer._getGraphStackIdsA  sk     J	((2""Q 4 45LL,,U-A-ABE "" r   c                 `    | j                         }||vry | j                  j                         S r   )rY   r6   source_file_list)r;   rR   rj   s      r   SourceFileListz)DebuggerV2EventMultiplexer.SourceFileListS  s*    yy{d?||,,..r   c                     | j                         }||vry 	 | j                  j                         |   \  }}||| j                  j                  ||      dS # t        $ r t	        j
                  d|z        w xY w)Nz(There is no source-code file at index %d)	host_name	file_pathlines)rY   r6   r   
IndexErrorr   r   source_lines)r;   rR   indexrj   r   r   s         r   SourceLinesz&DebuggerV2EventMultiplexer.SourceLinesY  s    yy{d?	#'<<#@#@#B5#I Iy #"\\..y)D
 	
	  	&&:UB 	s    A "A9c                     | j                         }||vry g }|D ]Z  }|| j                  j                  vrt        j                  d|z        |j                  | j                  j                  |          \ d|iS )Nz"Cannot find stack frame with ID %sstack_frames)rY   r6   _stack_frame_by_idr   r   r   )r;   rR   stack_frame_idsrj   r   stack_frame_ids         r   StackFramesz&DebuggerV2EventMultiplexer.StackFramesi  s    yy{d?- 	QNT\\%D%DD**8>I   ? ? OP	Q --r   r   )__name__
__module____qualname____doc__r=   r:   rN   rS   rW   rY   r_   rn   rw   r{   r   r   r   r   r   r   r   r   r    r   r   r3   r3   j   sl    	 0d,10
)V$3
j
8
2
B!
F6=~:$/
 .r   r3   )r   r   tensorboardr   rP   rF   rI   r   r*   r1   r3   r   r   r   <module>r      sH    J   7   $  ! @H. N. N.r   