B
    һdޑ                 @   s:  d 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dlmZ dd ZG dd dZG dd dZG dd dZG dd dZG dd dZG dd dZG dd dZG dd dZG dd dejejd Z G d!d" d"Z!G d#d$ d$e Z"dS )%an  Framework of debug wrapper sessions.

A debug wrapper session is a wrapper around a TensorFlow Python Session.
The wrapper preserves the Session interface, most importantly the run() method,
while providing abilities to:
a) Intercept a run() call to a wrapped session and insert debug tensor watches
   according to externally-specified debug URLs.

b) Release control to an external (i.e., non-Session) object before and after
   the run() call, so that the external object can perform actions such as
   launching a UI to let users inspect the intermediate tensors and partition
   graphs from the run() call.

c) (To be implemented in a future CL) Enter an instruction loop to let an
   external object (e.g., remote client) launch run() and cont() calls
   remotely.

*** The lifetime of a debug wrapper session: ***

1) The wrapper session is created by calling the constructor with a
   wrapped (normal) session as the argument:
     wrapper = FooDebugWrapperSession(sess)
   wherein FooDebugWrapperSession is a concrete subclass implementing the
   abstract BaseDebugWrapperSession class below.

2) Near the end of the constructor call, the on_session_init() callback is
   invoked, with a OnSessionInitRequest object as the argument. The object
   carries the wrapped (normal) session object.

3) The callback handles the request and returns a OnSessionInitResponse
   object with an action field, directing the wrapper session what to do next.

If the action field in the OnSessionInitResponse is PROCEED, the constructor
returns. Control is released back to the caller of the constructor, which can
invoke run() method of wrapper session with the same syntax as a non-wrapped
session, e.g.,:
  wrapper.run(fetches, feed_dict=feeds, options=run_options)

Below, A1 - A2 is the lifetime of a wrapper run() call if the action is
PROCEED:

A1) Right at the start of each run() call, the on_run_start() callback is
    invoked, with an OnRunStartRequest object carrying information such as
    the fetches, the feed dict, the run options and run metadata used in
    this run call, along with a count of how many run calls has occurred
    on this wrapper session. The callback then returns an OnRunStartResponse
    object, of which the action field directs what the wrapper session
    actually will do of the run() call.

    If the action is DEBUG_RUN, a debugged (tensor-watched) run will ensue,
    with the debug URLs supplied in the debug_urls field of the response.
    These can be file:// or grpc:// URLs, for example.

    If the action is NON_DEBUG_RUN, a non-debug (normal) run will ensue.

A2) Right before the run() returns, the on_run_end() callback is invoked,
    with an OnRunEndRequest object as the argument, which carries information
    including the actual action performed in the wrapper run() call and the
    run_metadata from the run() call.

However, if the action field in OnSessionInitResponse is
REMOTE_INSTR_LOOP, the constructor will automatically invoke an instruction loop
that gives the control to a remote caller.

In the remote instruction loop, the following steps will happen:

B1) Callback on_instr_start() is invoked. The callback will return an
    OnInstrStartResponse object with an action field which can order one of
    the following actions:
        i) a run() call with fetches, feeds and debug_urls specified.
       ii) exit the instruction loop.

B2) The wrapper session carries out the action specified above.

B3) If still in the instruction loop, the wrapper session invokes the
    on_instr_end() callback. After the on_instr_end() callback returns, jump
    back to B1.

TODO(cais): Implemented the instruction loop in B1 - B3.

    N)
config_pb2)session)debug_utils)errors)ops)
tf_logging)monitored_session)nest)collections_abcc             C   s"   t | |std|t| f dS )zCheck if an object is of the expected type.

  Args:
    obj: The object being checked.
    expected_types: (`type` or an iterable of `type`s) The expected `type`(s)
      of obj.

  Raises:
      TypeError: If obj is not an instance of expected_type.
  zExpected type %s; got type %sN)
isinstance	TypeErrortype)objZexpected_types r   \/var/www/html/venv/lib/python3.7/site-packages/tensorflow/python/debug/wrappers/framework.py_check_typeq   s    
r   c               @   s   e Zd ZdZdd ZdS )OnSessionInitRequestz{Request to an on-session-init callback.

  This callback is invoked during the __init__ call to a debug-wrapper session.
  c             C   s   t |tjtjf || _dS )zEConstructor.

    Args:
      sess: A tensorflow Session object.
    N)r   r   BaseSessionr   MonitoredSession)selfsessr   r   r   __init__   s    zOnSessionInitRequest.__init__N)__name__
__module____qualname____doc__r   r   r   r   r   r      s   r   c               @   s   e Zd ZdZdZdZdS )OnSessionInitActionz=Enum-like values for possible action to take on session init.proceedZremote_instr_loopN)r   r   r   r   PROCEEDREMOTE_INSTR_LOOPr   r   r   r   r      s   r   c               @   s   e Zd ZdZdd ZdS )OnSessionInitResponsez*Response from an on-session-init callback.c             C   s   t |t || _dS )zkConstructor.

    Args:
      action: (`OnSessionInitAction`) Debugger action to take on session init.
    N)r   straction)r   r"   r   r   r   r      s    
zOnSessionInitResponse.__init__N)r   r   r   r   r   r   r   r   r   r       s   r    c               @   s   e Zd ZdZdddZdS )OnRunStartRequestzRequest to an on-run-start callback.

  This callback is invoked during a run() call of the debug-wrapper
  session, immediately after the run() call counter is incremented.
  Fc             C   s(   || _ || _|| _|| _|| _|| _dS )ae  Constructor of `OnRunStartRequest`.

    Args:
      fetches: Fetch targets of the run() call.
      feed_dict: The feed dictionary to the run() call.
      run_options: RunOptions input to the run() call.
      run_metadata: RunMetadata input to the run() call.
        The above four arguments are identical to the input arguments to the
        run() method of a non-wrapped TensorFlow session.
      run_call_count: 1-based count of how many run calls (including this one)
        has been invoked.
      is_callable_runner: (bool) whether a runner returned by
        Session.make_callable is being run.
    N)fetches	feed_dictrun_optionsrun_metadatarun_call_countis_callable_runner)r   r$   r%   r&   r'   r(   r)   r   r   r   r      s    zOnRunStartRequest.__init__N)F)r   r   r   r   r   r   r   r   r   r#      s   r#   c               @   s   e Zd ZdZdZdZdZdS )OnRunStartActionzFEnum-like values for possible action to take on start of a run() call.Z	debug_runZprofile_runZnon_debug_runN)r   r   r   r   	DEBUG_RUNPROFILE_RUNNON_DEBUG_RUNr   r   r   r   r*      s   r*   c               @   s   e Zd ZdZdddZdS )OnRunStartResponsezRequest from an on-run-start callback.

  The caller of the callback can use this response object to specify what
  action the debug-wrapper session actually takes on the run() call.
  DebugIdentityNFc             C   sB   t |t || _t |t || _|| _|| _|| _|| _|| _	dS )a  Constructor of `OnRunStartResponse`.

    Args:
      action: (`OnRunStartAction`) the action actually taken by the wrapped
        session for the run() call.
      debug_urls: (`list` of `str`) debug_urls used in watching the tensors
        during the run() call.
      debug_ops: (`str` or `list` of `str`) Debug op(s) to be used by the
        debugger.
      node_name_regex_allowlist: Regular-expression allowlist for node
        name.
      op_type_regex_allowlist: Regular-expression allowlist for op type.
      tensor_dtype_regex_allowlist: Regular-expression allowlist for tensor
        dtype.
      tolerate_debug_op_creation_failures: Whether debug op creation failures
        are to be tolerated.
    N)
r   r!   r"   list
debug_urls	debug_opsnode_name_regex_allowlistop_type_regex_allowlisttensor_dtype_regex_allowlist#tolerate_debug_op_creation_failures)r   r"   r1   r2   r3   r4   r5   r6   r   r   r   r      s    

zOnRunStartResponse.__init__)r/   NNNF)r   r   r   r   r   r   r   r   r   r.      s       r.   c               @   s   e Zd ZdZdddZdS )OnRunEndRequestzpRequest to an on-run-end callback.

  The callback is invoked immediately before the wrapped run() call ends.
  Nc             C   s:   t |t || _|dk	r$t |tj || _|| _|| _dS )a  Constructor for `OnRunEndRequest`.

    Args:
      performed_action: (`OnRunStartAction`) Actually-performed action by the
        debug-wrapper session.
      run_metadata: run_metadata output from the run() call (if any).
      client_graph_def: (GraphDef) GraphDef from the client side, i.e., from
        the python front end of TensorFlow. Can be obtained with
        session.graph.as_graph_def().
      tf_error: (errors.OpError subtypes) TensorFlow OpError that occurred
        during the run (if any).
    N)r   r!   performed_actionr   RunMetadatar'   client_graph_deftf_error)r   r8   r'   r:   r;   r   r   r   r     s    
zOnRunEndRequest.__init__)NNN)r   r   r   r   r   r   r   r   r   r7     s     r7   c               @   s   e Zd ZdZdd ZdS )OnRunEndResponsez%Response from an on-run-end callback.c             C   s   d S )Nr   )r   r   r   r   r   1  s    zOnRunEndResponse.__init__N)r   r   r   r   r   r   r   r   r   r<   .  s   r<   c               @   s2  e Zd ZdZdAddZedd Zedd	 Zed
d Zedd Z	dBddZ
dd Zdd Zdd Zdd ZdCddZdDddZdd Zdd ZdEd d!Zd"d# Zed$d% Zd&d' Zd(d) ZdFd+d,Zd-d. Zejd/d0 Zejd1d2 Zejd3d4 Zd5d6 Zd7d8 Z d9d: Z!d;d< Z"d=d> Z#d?d@ Z$dS )GBaseDebugWrapperSessionzBase class of debug-wrapper session classes.

  Concrete classes that inherit from this class need to implement the abstract
  methods such as on_session_init, on_run_start and on_run_end.
  NFc             C   s   t |tjtjf || _|r&t|nd| _|| _	d| _
| t| j}t |t |jtjkr`n$|jtjkrvtdntd|j d| _i | _dS )a  Constructor of `BaseDebugWrapperSession`.

    Args:
      sess: An (unwrapped) TensorFlow session instance. It should be a subtype
        of `BaseSession` or `tf.MonitoredSession`.
      thread_name_filter: Regular-expression filter (allowlist) for name(s) of
        thread(s) on which the wrapper session will be active. This regular
        expression is used in a start-anchored fashion on the thread name, i.e.,
        by applying the `match` method of the compiled pattern. The default
        `None` means that the wrapper session will be active on all threads.
        E.g., r"MainThread$", r"QueueRunnerThread.*".
      pass_through_operrors: If True, all captured OpErrors will be
        propagated.  By default this captures all OpErrors.

    Raises:
      ValueError: On invalid `OnSessionInitAction` value.
      NotImplementedError: If a non-DirectSession sess object is received.
    Nr   z?OnSessionInitAction REMOTE_INSTR_LOOP has not been implemented.z%Invalid OnSessionInitAction value: %s)r   r   r   r   r   _sessrecompile_thread_name_filter_pattern_pass_through_operrors_run_call_counton_session_initr   r    r"   r   r   r   NotImplementedError
ValueError _default_session_context_manager_cached_callables_from_options)r   r   thread_name_filterpass_through_operrorsresponser   r   r   r   >  s     
z BaseDebugWrapperSession.__init__c             C   s   | j jS )N)r>   graph)r   r   r   r   rL   v  s    zBaseDebugWrapperSession.graphc             C   s   | j jS )N)r>   	graph_def)r   r   r   r   rM   z  s    z!BaseDebugWrapperSession.graph_defc             C   s   | j jS )N)r>   sess_str)r   r   r   r   rN   ~  s    z BaseDebugWrapperSession.sess_strc             C   s   | j S )N)r>   )r   r   r   r   r     s    zBaseDebugWrapperSession.sessionc          
      s  |r|rt d|r&|s|r&t dn|r:|s2|r:t d|    fdd  |}|rdtd |  sp|r|r||| S |r| j|| S | jj||||dS | t	||||| j
t|d}	t|	t |	jtjkr| |	|||||||\}
}n|	jtjkr$| |	|||||||\}
}nh|	jtjkr~|rB|| }
n0|r^| j|}|| }
n| jj||||d}
t|	j}nt d	|	j | |}t|t |
S )
ab  Wrapper around Session.run() that inserts tensor watch options.

    Args:
      fetches: Same as the `fetches` arg to regular `Session.run()`.
      feed_dict: Same as the `feed_dict` arg to regular `Session.run()`.
      options: Same as the `options` arg to regular `Session.run()`.
      run_metadata: Same as the `run_metadata` arg to regular `Session.run()`.
      callable_runner: A `callable` returned by `Session.make_callable()`.
        If not `None`, `fetches` and `feed_dict` must both be `None`.
        Mutually exclusive with `callable_options`.
      callable_runner_args: An optional list of arguments to `callable_runner`
        or for `callable_options`.
      callable_options: An instance of `config_pb2.CallableOptions`, to be
        used with `Session._make_callable_from_options()`. Mutually exclusive
        with `callable_runner`.

    Returns:
      Simply forwards the output of the wrapped `Session.run()` call.

    Raises:
      ValueError: On invalid `OnRunStartAction` value. Or if `callable_runner`
        is not `None` and either or both of `fetches` and `feed_dict` is `None`.
    zcallable_runner and callable_options are mutually exclusive, but are both specified in this call to BaseDebugWrapperSession.run().zZcallable_runner and fetches/feed_dict are mutually exclusive, but are used simultaneously.z[callable_options and fetches/feed_dict are mutually exclusive, but are used simultaneously.c                sH   t | sdS t| tjr* t|  S x| D ]} |s0dS q0W dS )z3Check whether a possibly nested structure is empty.FT)r	   Z	is_nestedr   r
   Mappingr0   values)xitem)is_emptyr   r   rS     s    

z-BaseDebugWrapperSession.run.<locals>.is_emptyzpDue to empty fetches, tfdbg Session wrapper is letting a Session.run pass through without any debugging actions.)r%   optionsr'   )r)   z"Invalid OnRunStartAction value: %s)rF   increment_run_call_countr   info_is_disabled_threadr>   _make_callable_from_optionsrunon_run_startr#   rC   boolr   r.   r"   r*   r+   _run_with_debuggingr,   _run_with_profilingr-   r7   
on_run_endr<   )r   r$   r%   rT   r'   callable_runnercallable_runner_argscallable_optionsZempty_fetchesrun_start_respretvalsZrun_end_reqcallable_objectZrun_end_respr   )rS   r   rY     sp    








zBaseDebugWrapperSession.runc	          
   C   s@  d}	|r4t |}
|
| jkr@t }|| |j}	n|p>t }	|pJt }|	rt| j|	|j	|j
|j|j|j|jd d}yn|r|||	|d}nT|r|
| jkr| j|
 }n| j|}|| j|
< ||d|i}n| jj|||	|d}W n: tjk
r  } z| jr||}|}W dd}~X Y nX |t|j|| jj |dfS )z3Perform a session.run() or callable with debugging.N)r2   r3   r4   r5   r6   )rT   r'   r'   )r%   rT   r'   )r'   r:   r;   )idrH   r   CallableOptionsCopyFromr&   
RunOptionsr9   _decorate_run_options_for_debugr1   r2   r3   r4   r5   r6   r>   rX   rY   r   ZOpErrorrB   r7   r"   rL   as_graph_def)r   rb   r$   r%   rT   r'   r_   r`   ra   decorated_run_optionscallable_options_idnew_callable_optionsr;   rc   rd   Zop_errorr   r   r   r\      s^    





z+BaseDebugWrapperSession._run_with_debuggingc	             C   s   d}	|r4t |}
|
| jkr@t }|| |j}	n|p>t }	| |	 |pTt }|rl|||	|d}n4|r| j	
|}||d|i}n| j	j|||	|d}|t|j|| j	j dfS )z3Perform a session.run() or callable with profiling.N)rT   r'   r'   )r%   rT   r'   )r'   r:   )re   rH   r   rf   rg   r&   rh   !_decorate_run_options_for_profiler9   r>   rX   rY   r7   r"   rL   rj   )r   rb   r$   r%   rT   r'   r_   r`   ra   rk   rl   rm   rc   rd   r   r   r   r]   J  s6    


z+BaseDebugWrapperSession._run_with_profilingc             C   s"   t  jpd}| jo | j| S )N )	threadingcurrent_threadnamerA   match)r   Zthread_namer   r   r   rW   w  s    z+BaseDebugWrapperSession._is_disabled_threadc             C   s   |t j| j| jS )N)r   r   ZStepContextr>   rY   )r   Zstep_fnr   r   r   run_step_fn|  s    z#BaseDebugWrapperSession.run_step_fnc             C   s   t ddS )z>Sets up the feeds and fetches for partial runs in the session.z@partial_run_setup is not implemented for debug-wrapper sessions.N)rE   )r   r$   Zfeedsr   r   r   partial_run_setup  s    z)BaseDebugWrapperSession.partial_run_setupc             C   s   t dd S )Nz:partial_run is not implemented for debug-wrapper sessions.)rE   )r   handler$   r%   r   r   r   partial_run  s    z#BaseDebugWrapperSession.partial_runc             O   s   | j j||S )N)r>   list_devices)r   argskwargsr   r   r   rx     s    z$BaseDebugWrapperSession.list_devicesc             O   s   | j j||S )N)r>   reset)r   ry   rz   r   r   r   r{     s    zBaseDebugWrapperSession.resetc                s$   j j||dd  fdd}|S )NT)	feed_listaccept_optionsc                 s&   j d d |dd |dd  | dS )NrT   r'   )r%   rT   r'   r_   r`   )rY   get)Zrunner_argsrz   )runnerr   r   r   wrapped_runner  s    

z=BaseDebugWrapperSession.make_callable.<locals>.wrapped_runner)r>   make_callable)r   r$   r|   r}   r   r   )r   r   r   r     s    z%BaseDebugWrapperSession.make_callablec                s    fdd}|S )Nc                 s   j d |dd  | dS )Nr'   )r'   ra   r`   )rY   r~   )Zfeed_valuesrz   )ra   r   r   r   r     s    
zKBaseDebugWrapperSession._make_callable_from_options.<locals>.wrapped_runnerr   )r   ra   r   r   )ra   r   r   rX     s    z3BaseDebugWrapperSession._make_callable_from_optionsc             C   s   | j S )N)rC   )r   r   r   r   r(     s    z&BaseDebugWrapperSession.run_call_countc             C   s   |  j d7  _ d S )N   )rC   )r   r   r   r   rU     s    z0BaseDebugWrapperSession.increment_run_call_countc             C   s   dS )a  Indicates whether disk usage is reset after each Session.run.

    Subclasses that clean up the disk usage after every run should
    override this protected method.

    Returns:
      (`bool`) Whether the disk usage amount is reset to zero after
        each Session.run.
    Fr   )r   r   r   r   _is_disk_usage_reset_each_run  s    
z5BaseDebugWrapperSession._is_disk_usage_reset_each_runr/   c             C   s8   d|_ tj|| jj||||||| jdkp.|  d	 dS )a  Modify a RunOptions object for debug tensor watching.

    Specifies request for outputting partition graphs. Adds
    debug_tensor_watch_opts with proper debug URLs.

    Args:
      run_options: (RunOptions) the modified RunOptions object.
      debug_urls: (list of str) debug URLs to be entered in run_options.
        debug_tensor_watch_opts.
      debug_ops: (str or list of str) debug op(s) to be used by the debugger.
      node_name_regex_allowlist: Regular-expression allowlist for node
        name.
      op_type_regex_allowlist: Regular-expression allowlist for op type.
      tensor_dtype_regex_allowlist: Regular-expression allowlist for tensor
        dtype.
      tolerate_debug_op_creation_failures: Whether debug op creation failures
        are to be tolerated.
    Tr   )r1   r2   r3   r4   r5   r6   Zreset_disk_byte_usageN)Zoutput_partition_graphsr   Zwatch_graphr>   rL   rC   r   )r   r&   r1   r2   r3   r4   r5   r6   r   r   r   ri     s    
z7BaseDebugWrapperSession._decorate_run_options_for_debugc             C   s   t jj|_dS )zModify a RunOptions object for profiling TensorFlow graph execution.

    Args:
      run_options: (RunOptions) the modified RunOptions object.
    N)r   rh   Z
FULL_TRACEZtrace_level)r   r&   r   r   r   rn     s    z9BaseDebugWrapperSession._decorate_run_options_for_profilec             C   s   dS )ag  Callback invoked during construction of the debug-wrapper session.

    This is a blocking callback.
    The invocation happens right before the constructor ends.

    Args:
      request: (`OnSessionInitRequest`) callback request carrying information
        such as the session being wrapped.

    Returns:
      An instance of `OnSessionInitResponse`.
    Nr   )r   requestr   r   r   rD     s    z'BaseDebugWrapperSession.on_session_initc             C   s   dS )aZ  Callback invoked on run() calls to the debug-wrapper session.

    This is a blocking callback.
    The invocation happens after the wrapper's run() call is entered,
    after an increment of run call counter.

    Args:
      request: (`OnRunStartRequest`) callback request object carrying
        information about the run call such as the fetches, feed dict, run
        options, run metadata, and how many `run()` calls to this wrapper
        session have occurred.

    Returns:
      An instance of `OnRunStartResponse`, carrying information to
        debug URLs used to watch the tensors.
    Nr   )r   r   r   r   r   rZ     s    z$BaseDebugWrapperSession.on_run_startc             C   s   dS )a  Callback invoked on run() calls to the debug-wrapper session.

    This is a blocking callback.
    The invocation happens right before the wrapper exits its run() call.

    Args:
      request: (`OnRunEndRequest`) callback request object carrying information
        such as the actual action performed by the session wrapper for the
        run() call.

    Returns:
      An instance of `OnRunStartResponse`.
    Nr   )r   r   r   r   r   r^     s    z"BaseDebugWrapperSession.on_run_endc             C   s
   t | S )N)r   Zdefault_session)r   r   r   r   
as_default  s    z"BaseDebugWrapperSession.as_defaultc             C   s   | j d kr|  | _ | j  S )N)rG   r   	__enter__)r   r   r   r   r      s    

z!BaseDebugWrapperSession.__enter__c             C   s   | j ||| d S )N)rG   __exit__)r   Z	exec_typeZ
exec_valueZexec_tbr   r   r   r   %  s    z BaseDebugWrapperSession.__exit__c             C   s   t | jdr| j  d S )N__del__)hasattrr>   r   )r   r   r   r   r   )  s    zBaseDebugWrapperSession.__del__c             C   s   | j   d S )N)r>   close)r   r   r   r   r   -  s    zBaseDebugWrapperSession.closec             C   s(   t | jdr| j S td| j d S )Nshould_stopzxThe wrapped session %r does not have a method called 'should_stop'. Do you intend to wrap a tf.MonitoredSession instead?)r   r>   r   rF   )r   r   r   r   r   3  s
    
z#BaseDebugWrapperSession.should_stop)NF)NNNNNN)N)N)NF)r/   NNNF)%r   r   r   r   r   propertyrL   rM   rN   r   rY   r\   r]   rW   rt   ru   rw   rx   r{   r   rX   r(   rU   r   ri   rn   abcabstractmethodrD   rZ   r^   r   r   r   r   r   r   r   r   r   r   r=   7  sT    
7     
sJ-

 
    
!	r=   )	metaclassc               @   s"   e Zd ZdZdddZdd ZdS )	WatchOptionsz#Type for return values of watch_fn.NFc             C   s0   |r|| _ ndg| _ || _|| _|| _|| _dS )a(  Constructor of WatchOptions: Debug watch options.

    Used as return values of `watch_fn`s.

    Args:
      debug_ops: (`str` or `list of str`) Debug ops to be used.
      node_name_regex_allowlist: Regular-expression allowlist for node_name,
        e.g., `"(weight_[0-9]+|bias_.*)"`
      op_type_regex_allowlist: Regular-expression allowlist for the op type of
        nodes, e.g., `"(Variable|Add)"`.
        If both `node_name_regex_allowlist` and `op_type_regex_allowlist`
        are set, the two filtering operations will occur in a logical `AND`
        relation. In other words, a node will be included if and only if it
        hits both allowlists.
      tensor_dtype_regex_allowlist: Regular-expression allowlist for Tensor
        data type, e.g., `"^int.*"`.
        This allowlist operates in logical `AND` relations to the two allowlists
        above.
      tolerate_debug_op_creation_failures: (`bool`) whether debug op creation
        failures (e.g., due to dtype incompatibility) are to be tolerated by not
        throwing exceptions.
    r/   N)r2   r3   r4   r5   r6   )r   r2   r3   r4   r5   r6   r   r   r   r   ?  s    zWatchOptions.__init__c             C   s   d| j | j| j| j| jf S )NzWatchOptions(debug_ops=%r, node_name_regex_allowlist=%r, op_type_regex_allowlist=%r, tensor_dtype_regex_allowlist=%r, tolerate_debug_op_creation_failures=%r))r2   r3   r4   r5   r6   )r   r   r   r   __repr__e  s    zWatchOptions.__repr__)NNNNF)r   r   r   r   r   r   r   r   r   r   r   <  s       
!r   c               @   sH   e Zd ZdZdddZdd Zejdd	 Zd
d Z	dd Z
dd ZdS )!NonInteractiveDebugWrapperSessionzFBase class for non-interactive (i.e., non-CLI) debug wrapper sessions.NFc             C   s:   t j| |||d d| _|dk	r6t|s0td|| _dS )aA  Constructor of NonInteractiveDebugWrapperSession.

    Args:
      sess: The TensorFlow `Session` object being wrapped.
      watch_fn: (`Callable`) A Callable that maps the fetches and feeds of a
        debugged `Session.run()` call to `WatchOptions.`
        * Args:
          * `fetches`: the fetches to the `Session.run()` call.
          * `feeds`: the feeds to the `Session.run()` call.

        * Returns:
         (`tf_debug.WatchOptions`) An object containing debug options including
           the debug ops to use, the node names, op types and/or tensor data
           types to watch, etc. See the documentation of `tf_debug.WatchOptions`
           for more details.
      thread_name_filter: Regular-expression white list for threads on which the
        wrapper session will be active. See doc of `BaseDebugWrapperSession` for
        more details.
      pass_through_operrors: If true, all captured OpErrors will be
        propagated.  By default this captures all OpErrors.
    Raises:
       TypeError: If a non-None `watch_fn` is specified and it is not callable.
    )rI   rJ   Nzwatch_fn is not callable)r=   r   	_watch_fncallabler   )r   r   Zwatch_fnrI   rJ   r   r   r   r   q  s    z*NonInteractiveDebugWrapperSession.__init__c             C   s
   t tjS )z0See doc of BaseDebugWrapperSession.on_run_start.)r    r   r   )r   r   r   r   r   rD     s    z1NonInteractiveDebugWrapperSession.on_session_initc             C   s   dS )a  Abstract method to be implemented by concrete subclasses.

    This method prepares the run-specific debug URL(s).

    Args:
      fetches: Same as the `fetches` argument to `Session.run()`
      feed_dict: Same as the `feed_dict` argument to `Session.run()`

    Returns:
      debug_urls: (`str` or `list` of `str`) Debug URLs to be used in
        this `Session.run()` call.
    Nr   )r   r$   r%   r   r   r   prepare_run_debug_urls  s    z8NonInteractiveDebugWrapperSession.prepare_run_debug_urlsc          	   C   s6   |  |j|j\}}ttj||j|j|j|j	|j
dS )z0See doc of BaseDebugWrapperSession.on_run_start.)r2   r3   r4   r5   r6   )_prepare_run_watch_configr$   r%   r.   r*   r+   r2   r3   r4   r5   r6   )r   r   r1   Z
watch_optsr   r   r   rZ     s    z.NonInteractiveDebugWrapperSession.on_run_startc             C   sD   |  ||}| jdkrt }n| ||}t|tr<t| }||fS )a
  Get the debug_urls, and node/op allowlists for the current run() call.

    Args:
      fetches: Same as the `fetches` argument to `Session.run()`.
      feed_dict: Same as the `feed_dict argument` to `Session.run()`.

    Returns:
      debug_urls: (str or list of str) Debug URLs for the current run() call.
        Currently, the list consists of only one URL that is a file:// URL.
      watch_options: (WatchOptions) The return value of a watch_fn, containing
        options including debug_ops, and allowlists.
    N)r   r   r   r   tuple)r   r$   r%   r1   Zwatch_optionsr   r   r   r     s    

z;NonInteractiveDebugWrapperSession._prepare_run_watch_configc             C   s   t  S )z.See doc of BaseDebugWrapperSession.on_run_end.)r<   )r   r   r   r   r   r^     s    z,NonInteractiveDebugWrapperSession.on_run_end)NNF)r   r   r   r   r   rD   r   r   r   rZ   r   r^   r   r   r   r   r   n  s    
#r   )#r   r   r?   rp   Ztensorflow.core.protobufr   Ztensorflow.python.clientr   Ztensorflow.python.debug.libr   Ztensorflow.python.frameworkr   r   Ztensorflow.python.platformr   Ztensorflow.python.trainingr   Ztensorflow.python.utilr	   Ztensorflow.python.util.compatr
   r   r   r   r    r#   r*   r.   r7   r<   ZSessionInterfaceABCMetar=   r   r   r   r   r   r   <module>_   s8   0"	    	2