
    6bi5                       S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSK	r
SSKJs  Jr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJ r   SSK!J"r"  SSK#J$r%  SSK&J'r'  SSK(J)r)  SSK*J+r+   SSK,r,SSSSSSS\"R\                  4S jr/SSSSSS\"R\                  4S jr0S r1SLS jr2\)" S5       " S S5      5       r3\)" S5       " S S5      5       r4\)" S 5       " S! S"\45      5       r5\)" S#5       " S$ S%\45      5       r6\)" S&5       " S' S(\45      5       r7\)" S)5       " S* S+\45      5       r8\)" S,5       " S- S.\45      5       r9\)" S// S09 " S1 S2\45      5       r:\)" S3/ S09\'Rv                  " S35       " S4 S5\:5      5       5       r<\)" S65       " S7 S8\45      5       r=\)" S95       " S: S;\45      5       r>\)" S<5       " S= S>\45      5       r?SMS? jr@\)" S@/ S09 " SA SB\4\R                  5      5       rB\)" SC5       " SD SE\45      5       rC\)" SF5       " SG SH\45      5       rD\)" SI5       " SJ SK\45      5       rEg! \- a    Sr, GNf = f)NzDCallbacks: utilities called at certain points during model training.    N)backend)distributed_file_utils)worker_training_state)	optimizer)learning_rate_schedule)generic_utils)io_utils)tf_utils)version_utils)Sequence)Progbar)ModeKeys)
tf_logging)deprecation)keras_export)doc_controlsF   stepsc
                    [        U [        5      (       a  U $ U (       d  / n U	[        R                  :X  aU  [	        5       Ul        [        5       /U =(       d    / -   UR
                  /-   n U(       a  U R                  [        U5      5        [        U 5      n
UR                  5       nU
R                  U5        [        U
UUUUUUUU	S9	  SU
R                  l        U
$ )a  Configures callbacks for use in various training loops.

Args:
    callbacks: List of Callbacks.
    model: Model being trained.
    do_validation: Whether or not validation loop will be run.
    batch_size: Number of samples per batch.
    epochs: Number of epoch to train.
    steps_per_epoch: Number of batches to run per training epoch.
    samples: Number of training samples.
    verbose: int, 0 or 1. TF-Keras logging verbosity to pass to
      ProgbarLogger.
    count_mode: One of 'steps' or 'samples'. Per-batch or per-sample count.
    mode: String. One of ModeKeys.TRAIN, ModeKeys.TEST, or ModeKeys.PREDICT.
      Which loop mode to configure callbacks for.

Returns:
    Instance of CallbackList used to control all Callbacks.
)do_validation
batch_sizeepochssteps_per_epochsamplesverbosemodeF)
isinstanceCallbackListr   TRAINHistoryhistory
BaseLoggerappendProgbarLogger_get_callback_model	set_modelset_callback_parametersmodelstop_training)	callbacksr(   r   r   r   r   r   r   
count_moder   callback_listcallback_models               P/home/james-whalen/.local/lib/python3.13/site-packages/tf_keras/src/callbacks.pyconfigure_callbacksr/   9   s    @ )\**	 x~~	\Nio26%--H	]:67 +M ..0NN+#'
 ).M%    c	                    Sn	U  H=  n
[        U
[        [        45      (       d  M   U	(       d  UR                  n	U	SS U
l        M?     / nU[
        R                  :w  aH  U	(       d  UR                  n	[        R                  " U	5      nU(       a  X Vs/ s H  nSU-   PM
     sn-  nUUUUUUUS.nU R                  U5        gs  snf )a<  Sets callback parameters.

Args:
    callback_list: CallbackList instance.
    model: Model being trained.
    do_validation: Whether or not validation loop will be run.
    batch_size: Number of samples per batch.
    epochs: Number of epoch to train.
    steps_per_epoch: Number of batches to run per training epoch.
    samples: Number of training samples.
    verbose: int, 0 or 1. TF-Keras logging verbosity to pass to
      ProgbarLogger.
    mode: String. One of ModeKeys.TRAIN, ModeKeys.TEST, or ModeKeys.PREDICT.
      Which loop mode to configure callbacks for.
Nr   val_)r   r   r   r   r   r   metrics)	r   r"   r$   metrics_namesstateful_metricsr   PREDICTcopy
set_params)r,   r(   r   r   r   r   r   r   r   metric_namescbkcallback_metricsncallback_paramss                 r.   r'   r'   {   s    4 LcJ677$22#/#3C 	   x ..L99\2\ B\!\ BB  &#O _- !Cs   C c                     [        U S5      =(       dj    [        U S5      =(       dW    [        U [        [        R                  R
                  R                  R                  [        R                  R                  45      $ )z5Checks if data is a generator, Sequence, or Iterator.__next__next)hasattrr   r   tfcompatv1dataIterator)rE   s    r.   _is_generator_likerG      sY     	j! 	
4 	
8RYY\\..779I9IJ
r0   c                     U R                   nU[        R                  [        R                  1;   a#  U(       a  [	        XR5       H  u  pgXqXF-   '   M     U$ X!S'   U$ )4Computes logs for sending to `on_batch_end` methods.outputs)r4   r   r   TESTzip)r(   logsrJ   r   prefixr9   labeloutputs           r.   	make_logsrQ      sT    &&L..< 7ME#)  8 K "YKr0   zkeras.callbacks.CallbackListc                   *   \ rS rSrSr    S$S jrS rS%S jrS rS r	S	 r
S&S
 jrS rS rS rS rS rS&S jrS&S jrS&S jrS&S jrS&S jrS&S jrS&S jrS&S jrS&S jrS&S jrS&S jrS&S jrS&S jrS&S jrS&S jrS&S jr S  r!S! r"S'S" jr#S#r$g)(r      z*Container abstracting a list of callbacks.Nc                    U(       a  [         R                  R                  U5      O/ U l        U R	                  X#5        U(       a  U R                  U5        U(       a  U R                  U5        [        S U R                   5       5      U l        [        S U R                   5       5      U l	        [        S U R                   5       5      U l        [        S U R                   5       5      U l        [        S U R                   5       5      U l        U R                  5         [        S U R                   5       5      U l        SU l        0 U l        SU l        / U l        g)	a  Container for `Callback` instances.

This object wraps a list of `Callback` instances, making it possible
to call them all at once via a single endpoint
(e.g. `callback_list.on_epoch_end(...)`).

Args:
  callbacks: List of `Callback` instances.
  add_history: Whether a `History` callback should be added, if one does
    not already exist in the `callbacks` list.
  add_progbar: Whether a `ProgbarLogger` callback should be added, if
    one does not already exist in the `callbacks` list.
  model: The `Model` these callbacks are used with.
  **params: If provided, parameters will be passed to each `Callback`
    via `Callback.set_params`.
c              3   <   #    U  H  n[        US S5      v   M     g7f_supports_tf_logsFN)getattr.0cbs     r.   	<genexpr>(CallbackList.__init__.<locals>.<genexpr>   s       %
>LGB+U33ns   c              3      #    U  HS  nUR                  5       (       d,  UR                  5       (       d  UR                  5       (       d  MD  [        US S5      v   MU     g7frV   )_implements_train_batch_hooks_implements_test_batch_hooks_implements_predict_batch_hooksrX   rY   s     r.   r\   r]      sP      0
$//11..00113	 4GB+U33$s   AA	Ac              3   @   #    U  H  oR                  5       v   M     g 7fN)r_   rY   s     r.   r\   r]      s      2
9G2,,..   c              3   @   #    U  H  oR                  5       v   M     g 7frc   )r`   rY   s     r.   r\   r]      s      1
8F"++--rd   c              3   @   #    U  H  oR                  5       v   M     g 7frc   )ra   rY   s     r.   r\   r]      s      4
;IR..00>rd   c              3   b   #    U  H%  oR                   R                  [        5       ;  v   M'     g 7frc   )	__class____name__globals)rZ   r:   s     r.   r\   r]     s"      !
?MMM""')3~s   -/   N)rB   nestflattenr*   _add_default_callbacksr&   r8   allrW   _batch_hooks_support_tf_logsany_should_call_train_batch_hooks_should_call_test_batch_hooks _should_call_predict_batch_hooks$_disallow_batch_hooks_in_ps_strategy_check_timing_num_batches_for_timing_check_hook_times_batch_start_time_batch_times)selfr*   add_historyadd_progbarr(   paramss         r.   __init__CallbackList.__init__   s9   0 8A3b##K=NN5!OOF# "% %
>Bnn%
 "
 -0 0
nn0
 -
) /2 2
9=2
 /
+ .1 1
8<1
 .
* 14 4
;?>>4
 1
- 	113
 ! !
?C~~!
 
 ./*!%r0   c                    SU l         SU l        U R                   H=  n[        U[        5      (       a  X0l         M   [        U[
        5      (       d  M7  X0l        M?     U R                  c;  U(       a4  [        5       U l        U R                  R                  U R                  5        U R                   c<  U(       a4  [	        SS9U l         U R                  R                  U R                   5        ggg)z)Adds `Callback`s that are always present.Nr   )r+   )_progbar_historyr*   r   r$   r    r#   )r{   r|   r}   r[   s       r.   rn   #CallbackList._add_default_callbacks  s    ..B"m,, "B(( "	 ! == [#IDMNN!!$--0== [)W=DMNN!!$--0 &1 r0   c                     Uc  0 $ U R                   (       a  U$ U(       a  U R                  (       a  U$ [        R                  " U5      $ )z?Turns tensors into numpy arrays or Python scalars if necessary.)rW   rp   r
   sync_to_numpy_or_python_type)r{   rM   is_batch_hooks      r.   _process_logsCallbackList._process_logs#  s;    <I!!KT>>K44T::r0   c                 :    U R                   R                  U5        g rc   )r*   r#   )r{   callbacks     r.   r#   CallbackList.append-  s    h'r0   c                 X    Xl         U R                   H  nUR                  U5        M     g rc   )r~   r*   r8   )r{   r~   r   s      r.   r8   CallbackList.set_params0  s#    H' 'r0   c                     Xl         U R                  (       a  U R                  Ul        U R                   H  nUR	                  U5        M     g rc   )r(   r   r!   r*   r&   )r{   r(   r   s      r.   r&   CallbackList.set_model5  s5    
== MMEMHu% 'r0   c                     U R                   (       d  gUS:X  a  U R                  XU5        gUS:X  a  U R                  XU5        g[        SU S35      e)z4Helper function for all batch_{begin | end} methods.NbeginendzUnrecognized hook: z&. Expected values are ["begin", "end"])r*   _call_batch_begin_hook_call_batch_end_hook
ValueError)r{   r   hookbatchrM   s        r.   _call_batch_hookCallbackList._call_batch_hook<  sX    ~~7?''T:U]%%d48%dV ,7 7 r0   c                     SU S3nU R                  XBU5        U R                  (       a  [        R                  " 5       U l        gg)z/Helper function for `on_*_batch_begin` methods.on__batch_beginN)_call_batch_hook_helperrv   timery   )r{   r   r   rM   	hook_names        r.   r   #CallbackList._call_batch_begin_hookK  s<    $|,	$$Yt<%)YY[D" r0   c                 >   SU S3nU R                   (       aC  US:  a=  [        R                  " 5       U R                  -
  nU R                  R	                  U5        U R                  XBU5        [        U R                  5      U R                  :  Ga  UnSU S3n[        U R                  5      [        U R                  5      -  n[        U R                  U   5      [        U R                  U   5      -  n	[        U R                  U   5      [        U R                  U   5      -  n
SU-  nSnX:  a%  [        R                  " UR                  UUU
S95        X:  a%  [        R                  " UR                  UUU	S95        SU l         S	U l        / U l        0 U l	        g	g	)
z-Helper function for `on_*_batch_end` methods.r   
_batch_endr   r         ?zCallback method `{hook}` is slow compared to the batch time (batch time: {batch_time:.4f}s vs `{hook}` time: {hook_time:.4f}s). Check your callbacks.)r   
batch_time	hook_timeFN)rv   r   ry   rz   r#   r   lenrw   sumrx   loggingwarningformat)r{   r   r   rM   r   r   end_hook_namebegin_hook_nameavg_batch_timeavg_end_hook_timeavg_begin_hook_timethreshold_timewarning_msgs                r.   r   !CallbackList._call_batch_end_hookS  s   $z*	%1*t'='==J$$Z0$$Yt<t  !T%G%GG%M #D66O !2!23c$:K:K6LLN #D$4$4]$C Ds  /H ! #&d&6&6&G"H3  1L # !>1NJ 
 #3&&,#1"5 '  !1&&*#1"3 '  "'D%)D" "D!DI Hr0   c                    U R                   (       a  [        R                  " 5       nU R                  USS9nU R                   H  n[	        XQ5      nU" X#5        M     U R                   (       aS  XR
                  ;  a  / U R
                  U'   U R
                  U   R                  [        R                  " 5       W-
  5        gg)z+Helper function for `on_*_batch_*` methods.T)r   N)rv   r   r   r*   rX   rx   r#   )r{   r   r   rM   
start_timer   r   s          r.   r   $CallbackList._call_batch_hook_helper  s    J!!$d!;H8/D '  0 00.0  +Y'..tyy{Z/GH r0   c                     U[         R                  :X  a  U R                  5         gU[         R                  :X  a  U R	                  5         gU R                  5         g)z:Helper function for on_{train|test|predict}_begin methods.N)r   r   on_train_beginrK   on_test_beginon_predict_beginr{   r   s     r.   _call_begin_hookCallbackList._call_begin_hook  s>    8>>!!X]]" !!#r0   c                     U[         R                  :X  a  U R                  5         gU[         R                  :X  a  U R	                  5         gU R                  5         g)z8Helper function for on_{train|test|predict}_end methods.N)r   r   on_train_endrK   on_test_endon_predict_endr   s     r.   _call_end_hookCallbackList._call_end_hook  s>    8>>!X]]"!r0   c                 f    U R                   (       a   U R                  [        R                  SXS9  g g )Nr   rM   rr   r   r   r   r{   r   rM   s      r.   on_batch_beginCallbackList.on_batch_begin  s)    ..!!(..'5!L /r0   c                 f    U R                   (       a   U R                  [        R                  SXS9  g g )Nr   r   r   r   s      r.   on_batch_endCallbackList.on_batch_end  s)    ..!!(..%!J /r0   c                 n    U R                  U5      nU R                   H  nUR                  X5        M     g)a  Calls the `on_epoch_begin` methods of its callbacks.

This function should only be called during TRAIN mode.

Args:
    epoch: Integer, index of epoch.
    logs: Dict. Currently no data is passed to this argument for this
       method but that may change in the future.
N)r   r*   on_epoch_beginr{   epochrM   r   s       r.   r   CallbackList.on_epoch_begin  s0     !!$'H##E0 'r0   c                 n    U R                  U5      nU R                   H  nUR                  X5        M     g)aD  Calls the `on_epoch_end` methods of its callbacks.

This function should only be called during TRAIN mode.

Args:
    epoch: Integer, index of epoch.
    logs: Dict, metric results for this training epoch, and for the
      validation epoch if validation is performed. Validation result
      keys are prefixed with `val_`.
N)r   r*   on_epoch_endr   s       r.   r   CallbackList.on_epoch_end  s0     !!$'H!!%. 'r0   c                 f    U R                   (       a   U R                  [        R                  SXS9  gg)a4  Calls the `on_train_batch_begin` methods of its callbacks.

Args:
    batch: Integer, index of batch within the current epoch.
    logs: Dict, contains the return value of `model.train_step`.
      Typically, the values of the `Model`'s metrics are returned.
      Example: `{'loss': 0.2, 'accuracy': 0.7}`.
r   r   Nr   r   s      r.   on_train_batch_begin!CallbackList.on_train_batch_begin  s+     ..!!(..'5!L /r0   c                 f    U R                   (       a   U R                  [        R                  SXS9  gg)zCalls the `on_train_batch_end` methods of its callbacks.

Args:
    batch: Integer, index of batch within the current epoch.
    logs: Dict. Aggregated metric results up until this batch.
r   r   Nr   r   s      r.   on_train_batch_endCallbackList.on_train_batch_end  s+     ..!!(..%!J /r0   c                 f    U R                   (       a   U R                  [        R                  SXS9  gg)a2  Calls the `on_test_batch_begin` methods of its callbacks.

Args:
    batch: Integer, index of batch within the current epoch.
    logs: Dict, contains the return value of `model.test_step`.
      Typically, the values of the `Model`'s metrics are returned.
      Example: `{'loss': 0.2, 'accuracy': 0.7}`.
r   r   Nrs   r   r   rK   r   s      r.   on_test_batch_begin CallbackList.on_test_batch_begin  s+     --!!(--%!K .r0   c                 f    U R                   (       a   U R                  [        R                  SXS9  gg)zCalls the `on_test_batch_end` methods of its callbacks.

Args:
    batch: Integer, index of batch within the current epoch.
    logs: Dict. Aggregated metric results up until this batch.
r   r   Nr   r   s      r.   on_test_batch_endCallbackList.on_test_batch_end  s+     --!!(--!I .r0   c                 f    U R                   (       a   U R                  [        R                  SXS9  gg)a!  Calls the `on_predict_batch_begin` methods of its callbacks.

Args:
    batch: Integer, index of batch within the current epoch.
    logs: Dict, contains the return value of `model.predict_step`,
      it typically returns a dict with a key 'outputs' containing
      the model's outputs.
r   r   Nrt   r   r   r6   r   s      r.   on_predict_batch_begin#CallbackList.on_predict_batch_begin  s-     00!!("2"2GU!N 1r0   c                 f    U R                   (       a   U R                  [        R                  SXS9  gg)zCalls the `on_predict_batch_end` methods of its callbacks.

Args:
    batch: Integer, index of batch within the current epoch.
    logs: Dict. Aggregated metric results up until this batch.
r   r   Nr   r   s      r.   on_predict_batch_end!CallbackList.on_predict_batch_end  s-     00!!("2"2E5!L 1r0   c                 n    U R                  U5      nU R                   H  nUR                  U5        M     g)zCalls the `on_train_begin` methods of its callbacks.

Args:
    logs: Dict. Currently, no data is passed via this argument
      for this method, but that may change in the future.
N)r   r*   r   r{   rM   r   s      r.   r   CallbackList.on_train_begin  0     !!$'H##D) 'r0   c                 n    U R                  U5      nU R                   H  nUR                  U5        M     g)zCalls the `on_train_end` methods of its callbacks.

Args:
    logs: Dict. Currently, no data is passed via this argument
      for this method, but that may change in the future.
N)r   r*   r   r   s      r.   r   CallbackList.on_train_end  s0     !!$'H!!$' 'r0   c                 n    U R                  U5      nU R                   H  nUR                  U5        M     g)zCalls the `on_test_begin` methods of its callbacks.

Args:
    logs: Dict. Currently no data is passed to this argument for this
      method but that may change in the future.
N)r   r*   r   r   s      r.   r   CallbackList.on_test_begin!  s0     !!$'H""4( 'r0   c                 n    U R                  U5      nU R                   H  nUR                  U5        M     g)zCalls the `on_test_end` methods of its callbacks.

Args:
    logs: Dict. Currently, no data is passed via this argument
      for this method, but that may change in the future.
N)r   r*   r   r   s      r.   r   CallbackList.on_test_end,  s0     !!$'H  & 'r0   c                 n    U R                  U5      nU R                   H  nUR                  U5        M     g)zCalls the 'on_predict_begin` methods of its callbacks.

Args:
    logs: Dict. Currently no data is passed to this argument for this
      method but that may change in the future.
N)r   r*   r   r   s      r.   r   CallbackList.on_predict_begin7  s0     !!$'H%%d+ 'r0   c                 n    U R                  U5      nU R                   H  nUR                  U5        M     g)zCalls the `on_predict_end` methods of its callbacks.

Args:
    logs: Dict. Currently, no data is passed via this argument
      for this method, but that may change in the future.
N)r   r*   r   r   s      r.   r   CallbackList.on_predict_endB  r   r0   c                 ,    [        U R                  5      $ rc   )iterr*   r{   s    r.   __iter__CallbackList.__iter__M  s    DNN##r0   c                    [         R                  R                  5       nUR                  (       a  / nU R                   Hi  n[        USS5      (       a  M  UR                  5       (       d,  UR                  5       (       d  UR                  5       (       d  MX  UR                  U5        Mk     U(       a  [        SU 35      egg)z>Error out if batch-level callbacks are passed with PSStrategy.rW   FzgBatch-level `Callback`s are not supported with `ParameterServerStrategy`. Found unsupported callbacks: N)rB   
distributeget_strategy_should_use_with_coordinatorr*   rX   r_   r`   ra   r#   r   )r{   strategyunsupported_callbacksr[   s       r.   ru   1CallbackList._disallow_batch_hooks_in_ps_strategyP  s     ==--/00$&!nn22E::4466668899;;)004 % % ""7!8:  % 1r0   c                 >    U R                   (       d  U$ [        XX4US9$ )rI   )rN   )r*   rQ   )r{   r(   rM   rJ   r   rN   s         r.   rQ   CallbackList.make_logsg  s    ~~KgFCCr0   )rp   ry   rz   rv   r   rx   rw   r   rt   rs   rr   rW   r*   r(   r~   )NFFN)Frc    )%ri   
__module____qualname____firstlineno____doc__r   rn   r   r#   r8   r&   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ru   rQ   __static_attributes__ r0   r.   r   r      s    4 BH1&;((
&1."`I$"MK1/
MK
LJ
OM	*	(	)	'	,	*$.Dr0   r   zkeras.callbacks.Callbackc                      \ rS rSrSrS rS rS r\R                  \
R                  SS j5       5       r\R                  \
R                  SS j5       5       r\R                  SS	 j5       r\R                  SS
 j5       r\R                  \
R                  SS j5       5       r\R                  \
R                  SS j5       5       r\R                  \
R                  SS j5       5       r\R                  \
R                  SS j5       5       r\R                  \
R                  SS j5       5       r\R                  \
R                  SS j5       5       r\R                  SS j5       r\R                  SS j5       r\R                  SS j5       r\R                  SS j5       r\R                  SS j5       r\R                  SS j5       rS rS rS rSrg)Callbackio  a  Abstract base class used to build new callbacks.

Callbacks can be passed to keras methods such as `fit`, `evaluate`, and
`predict` in order to hook into the various stages of the model training and
inference lifecycle.

To create a custom callback, subclass `keras.callbacks.Callback` and
override the method associated with the stage of interest. See
https://www.tensorflow.org/guide/tf_keras/custom_callback for more
information.

Example:

>>> training_finished = False
>>> class MyCallback(tf.keras.callbacks.Callback):
...   def on_train_end(self, logs=None):
...     global training_finished
...     training_finished = True
>>> model = tf.keras.Sequential([
...     tf.keras.layers.Dense(1, input_shape=(1,))])
>>> model.compile(loss='mean_squared_error')
>>> model.fit(tf.constant([[1.0]]), tf.constant([[1.0]]),
...           callbacks=[MyCallback()])
>>> assert training_finished == True

If you want to use `Callback` objects in a custom training loop:

1. You should pack all your callbacks into a single `callbacks.CallbackList`
   so they can all be called together.
2. You will need to manually call all the `on_*` methods at the appropriate
   locations in your loop. Like this:

Example:
```python
   callbacks =  tf.keras.callbacks.CallbackList([...])
   callbacks.append(...)
   callbacks.on_train_begin(...)
   for epoch in range(EPOCHS):
     callbacks.on_epoch_begin(epoch)
     for i, data in dataset.enumerate():
       callbacks.on_train_batch_begin(i)
       batch_logs = model.train_step(data)
       callbacks.on_train_batch_end(i, batch_logs)
     epoch_logs = ...
     callbacks.on_epoch_end(epoch, epoch_logs)
   final_logs=...
   callbacks.on_train_end(final_logs)
```

Attributes:
    params: Dict. Training parameters
        (eg. verbosity, batch size, number of epochs...).
    model: Instance of `keras.models.Model`.
        Reference of the model being trained.

The `logs` dictionary that callback methods
take as argument will contain keys for quantities relevant to
the current batch or epoch (see method-specific docstrings).
c                 <    S U l         S U l        S U l        SU l        g )NF)validation_datar(   _chief_worker_onlyrW   r   s    r.   r   Callback.__init__  s#    #
 #'!&r0   c                     Xl         g rc   )r~   r{   r~   s     r.   r8   Callback.set_params  s    r0   c                     Xl         g rc   )r(   r{   r(   s     r.   r&   Callback.set_model  s    
r0   Nc                     g)z;A backwards compatibility alias for `on_train_batch_begin`.Nr  r   s      r.   r   Callback.on_batch_begin      r0   c                     g)z9A backwards compatibility alias for `on_train_batch_end`.Nr  r   s      r.   r   Callback.on_batch_end  r  r0   c                     g)a-  Called at the start of an epoch.

Subclasses should override for any actions to run. This function should
only be called during TRAIN mode.

Args:
    epoch: Integer, index of epoch.
    logs: Dict. Currently no data is passed to this argument for this
      method but that may change in the future.
Nr  r{   r   rM   s      r.   r   Callback.on_epoch_begin  r  r0   c                     g)a  Called at the end of an epoch.

Subclasses should override for any actions to run. This function should
only be called during TRAIN mode.

Args:
    epoch: Integer, index of epoch.
    logs: Dict, metric results for this training epoch, and for the
      validation epoch if validation is performed. Validation result
      keys are prefixed with `val_`. For training epoch, the values of
      the `Model`'s metrics are returned. Example:
      `{'loss': 0.2, 'accuracy': 0.7}`.
Nr  r  s      r.   r   Callback.on_epoch_end  r  r0   c                 "    U R                  XS9  g)a  Called at the beginning of a training batch in `fit` methods.

Subclasses should override for any actions to run.

Note that if the `steps_per_execution` argument to `compile` in
`tf.keras.Model` is set to `N`, this method will only be called every
`N` batches.

Args:
    batch: Integer, index of batch within the current epoch.
    logs: Dict. Currently no data is passed to this argument for this
      method but that may change in the future.
r   N)r   r   s      r.   r   Callback.on_train_batch_begin  s    " 	E-r0   c                 "    U R                  XS9  g)a  Called at the end of a training batch in `fit` methods.

Subclasses should override for any actions to run.

Note that if the `steps_per_execution` argument to `compile` in
`tf.keras.Model` is set to `N`, this method will only be called every
`N` batches.

Args:
    batch: Integer, index of batch within the current epoch.
    logs: Dict. Aggregated metric results up until this batch.
r   N)r   r   s      r.   r   Callback.on_train_batch_end  s      	%+r0   c                     g)a&  Called at the beginning of a batch in `evaluate` methods.

Also called at the beginning of a validation batch in the `fit`
methods, if validation data is provided.

Subclasses should override for any actions to run.

Note that if the `steps_per_execution` argument to `compile` in
`tf.keras.Model` is set to `N`, this method will only be called every
`N` batches.

Args:
    batch: Integer, index of batch within the current epoch.
    logs: Dict. Currently no data is passed to this argument for this
      method but that may change in the future.
Nr  r   s      r.   r   Callback.on_test_batch_begin  r  r0   c                     g)a  Called at the end of a batch in `evaluate` methods.

Also called at the end of a validation batch in the `fit`
methods, if validation data is provided.

Subclasses should override for any actions to run.

Note that if the `steps_per_execution` argument to `compile` in
`tf.keras.Model` is set to `N`, this method will only be called every
`N` batches.

Args:
    batch: Integer, index of batch within the current epoch.
    logs: Dict. Aggregated metric results up until this batch.
Nr  r   s      r.   r   Callback.on_test_batch_end  r  r0   c                     g)a  Called at the beginning of a batch in `predict` methods.

Subclasses should override for any actions to run.

Note that if the `steps_per_execution` argument to `compile` in
`tf.keras.Model` is set to `N`, this method will only be called every
`N` batches.

Args:
    batch: Integer, index of batch within the current epoch.
    logs: Dict. Currently no data is passed to this argument for this
      method but that may change in the future.
Nr  r   s      r.   r   Callback.on_predict_batch_begin/  r  r0   c                     g)a~  Called at the end of a batch in `predict` methods.

Subclasses should override for any actions to run.

Note that if the `steps_per_execution` argument to `compile` in
`tf.keras.Model` is set to `N`, this method will only be called every
`N` batches.

Args:
    batch: Integer, index of batch within the current epoch.
    logs: Dict. Aggregated metric results up until this batch.
Nr  r   s      r.   r   Callback.on_predict_batch_end@  r  r0   c                     g)zCalled at the beginning of training.

Subclasses should override for any actions to run.

Args:
    logs: Dict. Currently no data is passed to this argument for this
      method but that may change in the future.
Nr  r{   rM   s     r.   r   Callback.on_train_beginP  r  r0   c                     g)zCalled at the end of training.

Subclasses should override for any actions to run.

Args:
    logs: Dict. Currently the output of the last call to
      `on_epoch_end()` is passed to this argument for this method but
      that may change in the future.
Nr  r0  s     r.   r   Callback.on_train_end[  r  r0   c                     g)zCalled at the beginning of evaluation or validation.

Subclasses should override for any actions to run.

Args:
    logs: Dict. Currently no data is passed to this argument for this
      method but that may change in the future.
Nr  r0  s     r.   r   Callback.on_test_beging  r  r0   c                     g)a  Called at the end of evaluation or validation.

Subclasses should override for any actions to run.

Args:
    logs: Dict. Currently the output of the last call to
      `on_test_batch_end()` is passed to this argument for this method
      but that may change in the future.
Nr  r0  s     r.   r   Callback.on_test_endr  r  r0   c                     g)zCalled at the beginning of prediction.

Subclasses should override for any actions to run.

Args:
    logs: Dict. Currently no data is passed to this argument for this
      method but that may change in the future.
Nr  r0  s     r.   r   Callback.on_predict_begin~  r  r0   c                     g)zCalled at the end of prediction.

Subclasses should override for any actions to run.

Args:
    logs: Dict. Currently no data is passed to this argument for this
      method but that may change in the future.
Nr  r0  s     r.   r   Callback.on_predict_end  r  r0   c                 T   [         R                  " U R                  5      (       + =(       d}    [         R                  " U R                  5      (       + =(       dQ    [         R                  " U R                  5      (       + =(       d%    [         R                  " U R
                  5      (       + $ )zBDetermines if this Callback should be called for each train batch.)r   
is_defaultr   r   r   r   r   s    r.   r_   &Callback._implements_train_batch_hooks  sy     (()<)<== E ++D,=,=>>E ++D,E,EFFE !++D,C,CDD		
r0   c                     [         R                  " U R                  5      (       + =(       d%    [         R                  " U R                  5      (       + $ )zADetermines if this Callback should be called for each test batch.)r   r=  r   r   r   s    r.   r`   %Callback._implements_test_batch_hooks  sA     ++$$
 
 B))$*@*@AA	Br0   c                     [         R                  " U R                  5      (       + =(       d%    [         R                  " U R                  5      (       + $ )zDDetermines if this Callback should be called for each predict
batch.)r   r=  r   r   r   s    r.   ra   (Callback._implements_predict_batch_hooks  sC     !++''
 
 E))$*C*CDD	Er0   )r  rW   r(   r~   r  rc   ) ri   r  r  r	  r
  r   r8   r&   r   for_subclass_implementersr   defaultr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r_   r`   ra   r  r  r0   r.   r  r  o  s<   :x' ++J  ,J ++H  ,H ++
 ,
 ++ , ++.  ,." ++,  ,,  ++  ,$ ++  ," ++  , ++  , ++ , ++	 ,	 ++ , ++	 ,	 ++ , ++ ,
BEr0   r  zkeras.callbacks.BaseLoggerc                   N   ^  \ rS rSrSrSU 4S jjrSS jrSS jrSS jrSr	U =r
$ )	r"   i  ah  Callback that accumulates epoch averages of metrics.

This callback is automatically applied to every TF-Keras model.

Args:
    stateful_metrics: Iterable of string names of metrics that
        should *not* be averaged over an epoch.
        Metrics in this list will be logged as-is in `on_epoch_end`.
        All others will be averaged in `on_epoch_end`.
c                 T   > [         TU ]  5         [        U=(       d    / 5      U l        g rc   )superr   setr5   )r{   r5   rh   s     r.   r   BaseLogger.__init__  s!     #$4$: ;r0   c                      SU l         0 U l        g Nr   )seentotalsr  s      r.   r   BaseLogger.on_epoch_begin  s    	r0   c                 v   U=(       d    0 nUR                  SS5      nUR                  SS5      nU =R                  X4-  -  sl        UR                  5        H_  u  pVXPR                  ;   a  X`R                  U'   M$  XPR                  ;   a  U R                  U==   Xc-  -  ss'   MN  Xc-  U R                  U'   Ma     g )Nsizer   	num_stepsr   )getrL  itemsr5   rM  )r{   r   rM   r   rQ  kvs          r.   r   BaseLogger.on_batch_end  s    zrXXfa(
 HH[!,			Z++	JJLDA)))!"A#KKNan4N%&^DKKN !r0   c                     Ubh  U R                   S    HT  nX0R                  ;   d  M  X0R                  ;   a  U R                  U   X#'   M6  U R                  U   U R                  -  X#'   MV     g g )Nr3   )r~   rM  r5   rL  )r{   r   rM   rT  s       r.   r   BaseLogger.on_epoch_end  s]    [[+#111"&++a."&++a.499"< , r0   )rL  r5   rM  rc   )ri   r  r  r	  r
  r   r   r   r   r  __classcell__rh   s   @r.   r"   r"     s!    	<4$= =r0   r"   zkeras.callbacks.TerminateOnNaNc                   6   ^  \ rS rSrSrU 4S jrSS jrSrU =r$ )TerminateOnNaNi  zACallback that terminates training when a NaN loss is encountered.c                 0   > [         TU ]  5         SU l        g NT)rG  r   rW   r{   rh   s    r.   r   TerminateOnNaN.__init__  s    !%r0   c                 4   U=(       d    0 nUR                  S5      nUby  [        R                  " U5      n[        R                  " U5      (       d  [        R
                  " U5      (       a,  [        R                  " SU S35        SU R                  l	        g g g )NlosszBatch z$: Invalid loss, terminating trainingT)
rR  r
   r   npisnanisinfr	   	print_msgr(   r)   )r{   r   rM   rb  s       r.   r   TerminateOnNaN.on_batch_end  s{    zrxx88>Dxx~~$""UG#GH ,0

(	 "0 r0   )rW   rc   )	ri   r  r  r	  r
  r   r   r  rY  rZ  s   @r.   r\  r\    s    K&	0 	0r0   r\  zkeras.callbacks.ProgbarLoggerc                      ^  \ rS rSrSrSS\4U 4S jjjrS rSS jrSS jr	SS jr
SS	 jrSS
 jrSS jrSS jrSS jrSS jrSS jrS rS rS rS rS rSS jrS rSrU =r$ )r$   i  a  Callback that prints metrics to stdout.

Args:
    count_mode: One of `"steps"` or `"samples"`.
        Whether the progress bar should
        count samples seen or steps (batches) seen.
    stateful_metrics: Iterable of string names of metrics that
        should *not* be averaged over an epoch.
        Metrics in this list will be logged as-is.
        All others will be averaged over time (e.g. loss, etc).
        If not provided, defaults to the `Model`'s metrics.

Raises:
    ValueError: In case of invalid `count_mode`.
r+   c                 T  > [         TU ]  5         SU l        US:X  a  SU l        OUS:X  a  SU l        O[	        SU S35      eU(       a  [        U5      O	[        5       U l        SU l        S U l        S U l	        SU l
        SU l        S	u  U l        U l        U l        SU l        SU l        g )
NTr   Fr   zUnknown `count_mode`: z*. Expected values are ["samples", "steps"]r   r   )NNN)rG  r   rW   	use_stepsr   rH  r5   rL  progbartargetr   r   _train_step
_test_step_predict_step_call_batch_hooks_called_in_fit)r{   r+   r5   rh   s      r.   r   ProgbarLogger.__init__  s    !%""DN7"!DN( 5; ;  &6C !35 	 	@P=$/4+=!%#r0   c                    US   U l         US   U l        U R                  (       a  SU;   a  US   U l        O)U R                  (       d  SU;   a  US   U l        OS U l        U R                   S:H  U l        U R                  cS   U R
                  R                  U l        U R
                  R                  U l	        U R
                  R                  U l        g g ! [         a
    SU l         g f = f)Nr   r   r   r   r   T)r   r   rj  rl  rp  r(   _train_counterrm  _test_counterrn  _predict_counterro  AttributeErrorr  s     r.   r8   ProgbarLogger.set_params  s    i(X&>>g/ /DKI$7 +DK  K "&!2;;.#'::#<#< "&**":":%)ZZ%@%@"	 
 " .)-&.s   AC C)(C)c                     SU l         g r^  )rq  r0  s     r.   r   ProgbarLogger.on_train_begin4  s
    "r0   c                 h    U R                   (       d!  U R                  5         U R                  5         g g rc   )rq  _reset_progbar_maybe_init_progbarr0  s     r.   r   ProgbarLogger.on_test_begin8  s(    ""!$$& #r0   c                 D    U R                  5         U R                  5         g rc   )r|  r}  r0  s     r.   r   ProgbarLogger.on_predict_begin=  s      "r0   c                     U R                  5         U R                  5         U R                  (       a;  U R                  S:  a*  [        R
                  " SUS-    SU R                   35        g g g )Nr   Epoch /)r|  r}  r   r   r	   rf  r  s      r.   r   ProgbarLogger.on_epoch_beginA  sU      "<<DKK!O	{!DKK=AB ,<r0   c                 &    U R                  X5        g rc   _batch_update_progbarr   s      r.   r    ProgbarLogger.on_train_batch_endG  s    ""5/r0   c                 J    U R                   (       d  U R                  X5        g g rc   )rq  r  r   s      r.   r   ProgbarLogger.on_test_batch_endJ  s    ""&&u3 #r0   c                 (    U R                  US 5        g rc   r  r   s      r.   r   "ProgbarLogger.on_predict_batch_endN  s    ""5$/r0   c                 :    U R                  X R                  5        g rc   )_finalize_progbarrm  r  s      r.   r   ProgbarLogger.on_epoch_endR  s    t%5%56r0   c                 ^    U R                   (       d  U R                  XR                  5        g g rc   )rq  r  rn  r0  s     r.   r   ProgbarLogger.on_test_endU  s"    """"49 #r0   c                 :    U R                  XR                  5        g rc   )r  ro  r0  s     r.   r   ProgbarLogger.on_predict_endY  s    t%7%78r0   c                      SU l         S U l        g rK  )rL  rk  r   s    r.   r|  ProgbarLogger._reset_progbar\  s    	r0   c                    [        U R                  5      U l        U R                  (       aD  U R                  R                  [        S U R                  R                   5       5      5      U l        U R
                  cB  [        U R                  U R                  U R                  U R                  (       a  SOSS9U l        U R
                  R                  U R                  5        g)zDInstantiate a `Progbar` if not yet, and update the stateful
metrics.c              3   8   #    U  H  oR                   v   M     g 7frc   )name)rZ   ms     r.   r\   4ProgbarLogger._maybe_init_progbar.<locals>.<genexpr>m  s     7$6qFF$6s   Nstepsample)rl  r   r5   	unit_name)rH  r5   r(   unionr3   rk  r   rl  r   rj  _update_stateful_metricsr   s    r.   r}  !ProgbarLogger._maybe_init_progbar`  s     !$D$9$9 ::: %)$9$9$?$?7DJJ$6$677%D! <<"{{!%!6!6$(NN&	DL 	--d.C.CDr0   c                     U R                   $ rc   rp  r   s    r.   r_   +ProgbarLogger._implements_train_batch_hooksz      %%%r0   c                     U R                   $ rc   r  r   s    r.   r`   *ProgbarLogger._implements_test_batch_hooks}  r  r0   c                     U R                   $ rc   r  r   s    r.   ra   -ProgbarLogger._implements_predict_batch_hooks  r  r0   c                    U=(       d    0 nU R                  5         U R                  (       a  US-   U l        Oe[        R                  " U5      nUR	                  SS5      nUR	                  SS5      nUR	                  SS5        XC-  nU =R                  U-  sl        U R
                  S:X  aS  [        R                  " U5      nU R                  R                  U R                  [        UR                  5       5      SS9  gg)	zUpdates the progbar.r   rP  r   rQ  r   NFfinalize)r}  rj  rL  r7   popr   r
   r   rk  updatelistrS  )r{   r   rM   r   rQ  add_seens         r.   r  #ProgbarLogger._batch_update_progbar  s    zr  ">>	DI 99T?D&!,Ja0IHHWd# -HII!I<<188>DLL		4

+=N r0   c                    [         R                  " U=(       d    0 5      nU R                  cm  Ub5  UR                  5       nU R                  (       d  X!R                  SS5      -  nU=(       d    U R                  U l        U R                  U R                  l        U R                  R                  U R                  [        UR                  5       5      SS9  g )NrP  r   Tr  )r
   r   rl  numpyrj  rR  rL  rk  r  r  rS  )r{   rM   counters      r.   r  ProgbarLogger._finalize_progbar  s    44TZR@;;"!--/~~xx22G!.TYYDK"&++DLLDKKdjjl);dKr0   )rp  rq  ro  rW   rn  rm  r   rk  rL  r5   rl  rj  r   )r   Nrc   )ri   r  r  r	  r
  strr   r8   r   r   r   r   r   r   r   r   r   r   r|  r}  r_   r`   ra   r  r  r  rY  rZ  s   @r.   r$   r$     s}     $3 $ $8.*#'
#C0407:9E4&&&O(	L 	Lr0   r$   zkeras.callbacks.Historyc                   @   ^  \ rS rSrSrU 4S jrSS jrSS jrSrU =r	$ )r    i  aT  Callback that records events into a `History` object.

This callback is automatically applied to
every TF-Keras model. The `History` object
gets returned by the `fit` method of models.

Example:

>>> model = tf.keras.models.Sequential([tf.keras.layers.Dense(10)])
>>> model.compile(tf.keras.optimizers.SGD(), loss='mse')
>>> history = model.fit(np.arange(100).reshape(5, 20), np.zeros(5),
...                     epochs=10, verbose=1)
>>> print(history.params)
{'verbose': 1, 'epochs': 10, 'steps': 1}
>>> # check the keys of history object
>>> print(history.history.keys())
dict_keys(['loss'])

c                 0   > [         TU ]  5         0 U l        g rc   )rG  r   r!   r_  s    r.   r   History.__init__  s    r0   c                     / U l         g rc   r   r0  s     r.   r   History.on_train_begin  s	    
r0   c                     U=(       d    0 nU R                   R                  U5        UR                  5        H0  u  p4U R                  R	                  U/ 5      R                  U5        M2     X R
                  l        g rc   )r   r#   rS  r!   
setdefaultr(   )r{   r   rM   rT  rU  s        r.   r   History.on_epoch_end  sZ    zr

% JJLDALL##Ar*11!4 !
 "

r0   )r   r!   rc   )
ri   r  r  r	  r
  r   r   r   r  rY  rZ  s   @r.   r    r      s    (" "r0   r    zkeras.callbacks.ModelCheckpointc                      ^  \ rS rSrSr        SS\S\S\S\S\4
U 4S jjjrSS	 jr	S
 r
SS jrSS jrSS jrS rS rS rS rS rS rS rSrU =r$ )ModelCheckpointi  a#  Callback to save the TF-Keras model or model weights at some frequency.

`ModelCheckpoint` callback is used in conjunction with training using
`model.fit()` to save a model or weights (in a checkpoint file) at some
interval, so the model or weights can be loaded later to continue the
training from the state saved.

A few options this callback provides include:

- Whether to only keep the model that has achieved the "best performance" so
  far, or whether to save the model at the end of every epoch regardless of
  performance.
- Definition of 'best'; which quantity to monitor and whether it should be
  maximized or minimized.
- The frequency it should save at. Currently, the callback supports saving
  at the end of every epoch, or after a fixed number of training batches.
- Whether only weights are saved, or the whole model is saved.

Note: If you get `WARNING:tensorflow:Can save best model only with <name>
available, skipping` see the description of the `monitor` argument for
details on how to get this right.

Example:

```python
model.compile(loss=..., optimizer=...,
              metrics=['accuracy'])

EPOCHS = 10
checkpoint_filepath = '/tmp/checkpoint'
model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
    filepath=checkpoint_filepath,
    save_weights_only=True,
    monitor='val_accuracy',
    mode='max',
    save_best_only=True)

# Model weights are saved at the end of every epoch, if it's the best seen
# so far.
model.fit(epochs=EPOCHS, callbacks=[model_checkpoint_callback])

# The model weights (that are considered the best) are loaded into the
# model.
model.load_weights(checkpoint_filepath)
```

Args:
    filepath: string or `PathLike`, path to save the model file. e.g.
      filepath = os.path.join(working_dir, 'ckpt', file_name). `filepath`
      can contain named formatting options, which will be filled the value
      of `epoch` and keys in `logs` (passed in `on_epoch_end`). For example:
      if `filepath` is `weights.{epoch:02d}-{val_loss:.2f}.hdf5`, then the
      model checkpoints will be saved with the epoch number and the
      validation loss in the filename. The directory of the filepath should
      not be reused by any other callbacks to avoid conflicts.
    monitor: The metric name to monitor. Typically the metrics are set by
      the `Model.compile` method. Note:

      * Prefix the name with `"val_`" to monitor validation metrics.
      * Use `"loss"` or "`val_loss`" to monitor the model's total loss.
      * If you specify metrics as strings, like `"accuracy"`, pass the same
        string (with or without the `"val_"` prefix).
      * If you pass `metrics.Metric` objects, `monitor` should be set to
        `metric.name`
      * If you're not sure about the metric names you can check the contents
        of the `history.history` dictionary returned by
        `history = model.fit()`
      * Multi-output models set additional prefixes on the metric names.

    verbose: Verbosity mode, 0 or 1. Mode 0 is silent, and mode 1
      displays messages when the callback takes an action.
    save_best_only: if `save_best_only=True`, it only saves when the model
      is considered the "best" and the latest best model according to the
      quantity monitored will not be overwritten. If `filepath` doesn't
      contain formatting options like `{epoch}` then `filepath` will be
      overwritten by each new better model.
    mode: one of {'auto', 'min', 'max'}. If `save_best_only=True`, the
      decision to overwrite the current save file is made based on either
      the maximization or the minimization of the monitored quantity.
      For `val_acc`, this should be `max`, for `val_loss` this should be
      `min`, etc. In `auto` mode, the mode is set to `max` if the quantities
      monitored are 'acc' or start with 'fmeasure' and are set to `min` for
      the rest of the quantities.
    save_weights_only: if True, then only the model's weights will be saved
      (`model.save_weights(filepath)`), else the full model is saved
      (`model.save(filepath)`).
    save_freq: `'epoch'` or integer. When using `'epoch'`, the callback
      saves the model after each epoch. When using integer, the callback
      saves the model at end of this many batches. If the `Model` is
      compiled with `steps_per_execution=N`, then the saving criteria will
      be checked every Nth batch. Note that if the saving isn't aligned to
      epochs, the monitored metric may potentially be less reliable (it
      could reflect as little as 1 batch, since the metrics get reset every
      epoch). Defaults to `'epoch'`.
    options: Optional `tf.train.CheckpointOptions` object if
      `save_weights_only` is true or optional `tf.saved_model.SaveOptions`
      object if `save_weights_only` is false.
    initial_value_threshold: Floating point initial "best" value of the
      metric to be monitored. Only applies if `save_best_value=True`. Only
      overwrites the model weights already saved if the performance of
      current model is better than this value.
    **kwargs: Additional arguments for backwards compatibility. Possible key
      is `period`.
monitorr   save_best_onlysave_weights_onlyr   c
                   > [         TU ]  5         SU l        X l        X0l        [
        R                  " U5      U l        X@l        XPl	        Xpl
        SU l        SU l        SU l        Xl        U(       ah  Ub)  [        U[         R"                  R$                  5      (       a-  U=(       d    [         R"                  R%                  5       U l        O[)        SU S35      eU(       a$  UR+                  S5      (       a  Ub  [-        S5      eUb)  [        U[         R.                  R0                  5      (       a-  U=(       d    [         R.                  R1                  5       U l        O[)        SU S35      eS	U
;   a!  U
S	   U l        [4        R6                  " S
5        OSU l        SU
;   a!  U
S   U l        [4        R6                  " S5        OSU l        US;  a  [4        R6                  " SU5        SnUS:X  a8  [:        R<                  U l        U R                  c  [:        R@                  U l        OUS:X  a9  [:        RB                  U l        U R                  c  [:        R@                  * U l        OSU R                  ;   d   U R                  RE                  S5      (       a9  [:        RB                  U l        U R                  c  [:        R@                  * U l        O7[:        R<                  U l        U R                  c  [:        R@                  U l        U R                  S:w  a8  [        U R                  [F        5      (       d  [-        SU R                   S35      eSU l$        g )NTr   zfIf save_weights_only is True, then `options` must be either None or a tf.train.CheckpointOptions. Got ..keraszThe native TF-Keras format does not support the `options` argument. Please remove the `options` argument, or use the SavedModel format by removing the `.keras` extension from the model filepath.zgIf save_weights_only is False, then `options` must be either None or a tf.saved_model.SaveOptions. Got load_weights_on_restartz`load_weights_on_restart` argument is deprecated. Please use `model.load_weights()` for loading weights before the start of `model.fit()`.Fperiodzk`period` argument is deprecated. Please use `save_freq` to specify the frequency in number of batches seen.r   autominmaxz:ModelCheckpoint mode %s is unknown, fallback to auto mode.r  r  r  accfmeasurer   zUnrecognized save_freq: z+. Expected save_freq are "epoch" or integer)%rG  r   rW   r  r   r	   path_to_stringfilepathr  r  	save_freqepochs_since_last_save_batches_seen_since_last_saving_last_batch_seenbestr   rB   trainCheckpointOptions_options	TypeErrorendswithr   saved_modelSaveOptionsr  r   r   r  rc  less
monitor_opInfgreater
startswithintr  )r{   r  r  r   r  r  r   r  optionsinitial_value_thresholdkwargsrh   s              r.   r   ModelCheckpoint.__init__6  s    	!% //9,!2"&'#/0, "+	*33# # !( G288+E+E+G")1&  H--h77G<O *  *33# # !( G2>>+E+E+G")1&  %.+12K+LD(OO5 ,1D( v *DKOOF
 DK--OOL D5= ggDOyy FF	U] jjDOyy VVG	$(?(?
(K(K"$**99$!#DI"$''99$ "DI>>W$Z-L-L*4>>*: ;< <  #(r0   c                    U R                   (       aS  U R                  U R                  5      nUb4  U R                  U5      (       a   U R                  R                  U5        g g g g ! [        [        4 a  n[        SU SU 35      eS nAff = f)NzError loading file from z
. Reason: )r  1_get_most_recently_modified_file_matching_patternr  _checkpoint_existsr(   load_weightsIOErrorr   )r{   rM   filepath_to_loades       r.   r   ModelCheckpoint.on_train_begin  s    ''FFMM 
  +0G0G 1 1	 JJ++,<=1+ (  , $23C2D E##$#' s   A& &B6BBc                      U R                   S:g  $ Nr   r  r   s    r.   r_   -ModelCheckpoint._implements_train_batch_hooks  s    ~~((r0   c                 f    U R                  U5      (       a  U R                  U R                  XS9  g g )Nr   r   rM   )_should_save_on_batch_save_model_current_epochr   s      r.   r   "ModelCheckpoint.on_train_batch_end  s1    %%e,,4#6#6eO -r0   c                     Xl         g rc   )r  r  s      r.   r   ModelCheckpoint.on_epoch_begin  s    #r0   c                 r    U =R                   S-  sl         U R                  S:X  a  U R                  US US9  g g )Nr   r   r  )r  r  r  r  s      r.   r   ModelCheckpoint.on_epoch_end  s9    ##q(#>>W$54@ %r0   c                     U R                   S:X  a  gXR                  ::  a  US-   nOXR                  -
  nU =R                  U-  sl        Xl        U R                  U R                   :  a  SU l        gg)z?Handles batch-level saving logic, supports steps_per_execution.r   Fr   r   T)r  r  r  )r{   r   add_batchess      r.   r  %ModelCheckpoint._should_save_on_batch  sk    >>W$)))!)K"7"77K,,;, %//4>>A34D0r0   c                    U=(       d    0 n[        U R                  [        5      (       d  U R                  U R                  :  Ga5  [
        R                  " U5      nSU l        U R                  XU5      n[        R                  R                  U5      nU(       am  UR                  S5      (       dW  [        R                  R                  R                  U5      (       d)  [        R                  R                  R!                  U5         U R"                  (       Ga  UR%                  U R&                  5      nUc#  [(        R*                  " SU R&                  5        GOU R-                  X`R.                  5      (       af  U R0                  S:  a>  [2        R4                  " SUS-    SU R&                   SU R.                  S	 S
US	 SU 3
5        X`l        U R7                  U5        OU R0                  S:  a7  [2        R4                  " SUS-    SU R&                   SU R.                  S	 35        O@U R0                  S:  a  [2        R4                  " SUS-    SU 35        U R7                  U5        U R9                  5         gg! [:         a    [=        SU 35      e[<         a?  nS[?        UR@                  S   5      RC                  5       ;   a  [=        SU 35      eUeSnAff = f)zSaves the model.

Args:
    epoch: the epoch this iteration is in.
    batch: the batch this iteration is in. `None` if the `save_freq`
      is set to `epoch`.
    logs: the `logs` dict passed in to `on_batch_end` or `on_epoch_end`.
r   zgs://Nz5Can save best model only with %s available, skipping.
Epoch r   z: z improved from z.5fz to z, saving model to z did not improve from z: saving model to zePlease specify a non-directory filepath for ModelCheckpoint. Filepath used is an existing directory: zis a directoryzfPlease specify a non-directory filepath for ModelCheckpoint. Filepath used is an existing directory: f)"r   r  r  r  r  r
   r   _get_file_pathospathdirnamer  rB   iogfileexistsmakedirsr  rR  r  r   r   r  r  r   r	   rf  _save_handler_maybe_remove_fileIsADirectoryErrorr  r  argslower)r{   r   r   rM   r  r  currentr  s           r.   r  ModelCheckpoint._save_model  s    zr t~~s++**dkk9 88>D*+D'**5>Hggooh/G**733**733$$W-7&&&"hht||4G( LL  ??7II>>#||a/ ( 2 2&.uqykDLL> J,,0IIc?$wsm L77?j%B!" )0I !..x8#||a/ ( 2 2&.uqyk'+||n 5,,0IIc?%<!" ||a' **&uqyk1CH:N
 &&x0'')k :l % ""*- 
  
 $s166!9~';';'==!''/j2  
s   	E1I< <!K:KKc                    U R                   (       aW  UR                  S5      (       a  U R                  R                  USS9  g U R                  R                  USU R                  S9  g UR                  S5      (       a  U R                  R                  USS9  g U R                  R                  USU R                  S9  g )Nz.weights.h5T)	overwrite)r  r  r  )r  r  r(   save_weightsr  save)r{   r  s     r.   r  ModelCheckpoint._save_handler6  s    !!  //

''" ( 
 

''" MM (    **

D9

" MM   r0   c                 v    Ub  SU;   a"  U R                   R                  " SSUS-   0UD6nO&U R                   R                  " SUS-   US-   S.UD6n [        R                  " X@R
                  R                  5      U l        U R                  $ ! [         a   n[        SU R                    SU 35      eSnAff = f)	z%Returns the file path for checkpoint.Nr   r   r   r   r   z*Failed to format this callback filepath: "z". Reason: r  )r  r   KeyErrorr   write_filepathr(   distribute_strategy_write_filepath)r{   r   r   rM   	file_pathr  s         r.   r  ModelCheckpoint._get_file_pathM  s    	
 }4 MM00IuqyIDI	 MM00 !)5198<	  6DDzz55 
 ###  	<T]]O L# 	s   *B %B 
B8B33B8c                 n    [         R                  " U R                  U R                  R                  5        g rc   )r   remove_temp_dir_with_filepathr  r(   r  r   s    r.   r  "ModelCheckpoint._maybe_remove_filee  s'     	<<  $**"@"@	
r0   c                 @   UR                  S5      (       a)  [        R                  R                  R	                  U5      $ [        R                  R                  R	                  U5      n[        R                  R                  R	                  US-   5      nU=(       d    U$ )z;Returns whether the checkpoint `filepath` refers to exists.z.h5z.index)r  rB   r  r  r	  )r{   r  tf_saved_model_exists!tf_weights_only_checkpoint_existss       r.   r  "ModelCheckpoint._checkpoint_existsm  st    U##55;;%%h// " 2 28 <,.EEKK,>,>x-
) %I(IIr0   c                 *   [         R                  R                  U5      n[         R                  R                  U5      nS[        R
                  " SSU5      -   S-   n[        R                  R                  U5      nUb;  [        R                  " U[         R                  R                  U5      5      (       a  U$ SnSnSnSn	[        R                  R                  R                  U5      (       a  [         R                  " U5       H  n
[        R                  " XJ5      (       d  M   [         R                  R                  X*5      n[         R                  R                  U5      nU	b  X:  a  Un	X:  a  UnUnSnMu  X:X  d  M|  US-  nM     US:X  a  U$ U	$ )a  Returns the most recently modified filepath matching pattern.

Pattern may contain python formatting placeholder. If
`tf.train.latest_checkpoint()` does not return None, use that;
otherwise, check for most recently modified one that matches the
pattern.

In the rare case where there are more than one pattern-matching file
having the same modified time that is most recent among all, return the
filepath that is largest (by `>` operator, lexicographically using the
numeric equivalents). This provides a tie-breaker when multiple files
are most recent. Note that a larger `filepath` can sometimes indicate a
later time of modification (for instance, when epoch/batch is used as
formatting option), but not necessarily (when accuracy or loss is used).
The tie-breaker is put in the logic as best effort to return the most
recent, and to avoid undeterministic result.

Modified time of a file is obtained with `os.path.getmtime()`.

This utility function is best demonstrated via an example:

```python
file_pattern = 'f.batch{batch:02d}epoch{epoch:02d}.h5'
test_dir = self.get_temp_dir()
path_pattern = os.path.join(test_dir, file_pattern)
file_paths = [
    os.path.join(test_dir, file_name) for file_name in
    ['f.batch03epoch02.h5',
     'f.batch02epoch02.h5', 'f.batch01epoch01.h5']
]
for file_path in file_paths:
  # Write something to each of the files
self.assertEqual(
    _get_most_recently_modified_file_matching_pattern(path_pattern),
    file_paths[-1])
```

Args:
    pattern: The file pattern that may optionally contain python
        placeholder such as `{epoch:02d}`.

Returns:
    The most recently modified file's full filepath matching `pattern`.
    If `pattern` does not contain any placeholder, this returns the
    filepath that exactly matches `pattern`. Returns `None` if no match
    is found.
^z{.*}z.*$Nr   r   )r  r  r  basenameresubrB   r  latest_checkpointmatchr  r  r	  listdirjoingetmtime)r{   patterndir_name	base_namebase_name_regexlatest_tf_checkpointlatest_mod_timefile_path_with_latest_mod_timen_file_with_latest_mod_time file_path_with_largest_file_name	file_namer  mod_times                r.   r  AModelCheckpoint._get_most_recently_modified_file_matching_patternw  s_   ` 77??7+GG$$W-	wy AACG  "xx99(C+RWW--.BC1
 1
 (')-&&'#+/(55;;h''ZZ1	88O77 "X AI!ww//	:H8@$G;D81*29B6 783!4 4q83+ 2. '!+11 43r0   )r  r  r  r  r  rW   r  r  r  r  r  r  r  r  r  r  r  r   )val_lossr   FFr  r   NNrc   )ri   r  r  r	  r
  r  r  boolr   r   r_   r   r   r   r  r  r  r  r  r  r  r  rY  rZ  s   @r.   r  r    s    gX "$"' $r( r( 	r(
 r(  r( r( r(h*)P$A"Sj.$0
J_4 _4r0   r  z keras.callbacks.BackupAndRestore)rD   c                      ^  \ rS rSrSr   SU 4S jjrSS jrSS jrSS jrS r	SS jr
SS	 jrSS
 jrSS jrSrU =r$ )BackupAndRestorei  a  Callback to back up and restore the training state.

`BackupAndRestore` callback is intended to recover training from an
interruption that has happened in the middle of a `Model.fit` execution, by
backing up the training states in a temporary checkpoint file (with the help
of a `tf.train.CheckpointManager`), at the end of each epoch. Each backup
overwrites the previously written checkpoint file, so at any given time
there is at most one such checkpoint file for backup/restoring purpose.

If training restarts before completion, the training state (which includes
the `Model` weights and epoch number) is restored to the most recently saved
state at the beginning of a new `Model.fit` run. At the completion of a
`Model.fit` run, the temporary checkpoint file is deleted.

Note that the user is responsible to bring jobs back after the interruption.
This callback is important for the backup and restore mechanism for fault
tolerance purpose, and the model to be restored from a previous checkpoint
is expected to be the same as the one used to back up. If user changes
arguments passed to compile or fit, the checkpoint saved for fault tolerance
can become invalid.

Note:

1. This callback is not compatible with eager execution disabled.
2. A checkpoint is saved at the end of each epoch. After restoring,
`Model.fit` redoes any partial work during the unfinished epoch in which the
training got restarted (so the work done before the interruption doesn't
affect the final model state).
3. This works for both single worker and multi-worker modes. When
`Model.fit` is used with `tf.distribute`, it supports
`tf.distribute.MirroredStrategy`,
`tf.distribute.MultiWorkerMirroredStrategy`, `tf.distribute.TPUStrategy`,
and `tf.distribute.experimental.ParameterServerStrategy`.

Example:

>>> class InterruptingCallback(tf.keras.callbacks.Callback):
...   def on_epoch_begin(self, epoch, logs=None):
...     if epoch == 4:
...       raise RuntimeError('Interrupting!')
>>> callback = tf.keras.callbacks.BackupAndRestore(backup_dir="/tmp/backup")
>>> model = tf.keras.models.Sequential([tf.keras.layers.Dense(10)])
>>> model.compile(tf.keras.optimizers.SGD(), loss='mse')
>>> try:
...   model.fit(np.arange(100).reshape(5, 20), np.zeros(5), epochs=10,
...             batch_size=1, callbacks=[callback, InterruptingCallback()],
...             verbose=0)
... except:
...   pass
>>> history = model.fit(np.arange(100).reshape(5, 20), np.zeros(5),
...                     epochs=10, batch_size=1, callbacks=[callback],
...                     verbose=0)
>>> # Only 6 more epochs are run, since first training got interrupted at
>>> # zero-indexed epoch 4, second training will continue from 4 to 9.
>>> len(history.history['loss'])
6

Besides the option to save at the end of every epoch or every N steps, if
you are doing distributed training with
`tf.distribute.MultiWorkerMirroredStrategy` on Google Cloud Platform or
Google Borg, you can also use the `save_before_preemption` argument
to enable saving a checkpoint right before a worker gets preempted
by other jobs and training gets interrupted. See
`tf.distribute.experimental.PreemptionCheckpointHandler` for more details.

Args:
    backup_dir: String, path to store the checkpoint.
      e.g. `backup_dir = os.path.join(working_dir, 'backup')`.
      This is the directory in which the system stores temporary files to
      recover the model from jobs terminated unexpectedly. The directory
      cannot be reused elsewhere to store other files, e.g. by the
      `BackupAndRestore` callback of another training run,
      or by another callback
      (e.g. `ModelCheckpoint`) of the same training.
    save_freq: `'epoch'`, integer, or `False`. When set to `'epoch'`
      the callback saves the checkpoint at the end of each epoch.
      When set to an integer, the callback saves the checkpoint every
      `save_freq` batches. Set `save_freq` to `False` if only using
      preemption checkpointing (with `save_before_preemption=True`).
    delete_checkpoint: Boolean, default to True. This `BackupAndRestore`
      callback works by saving a checkpoint to back up the training state.
      If `delete_checkpoint=True`, the checkpoint will be deleted after
      training is finished. Use `False` if you'd like to keep the checkpoint
      for future usage.
    save_before_preemption: A boolean value instructing whether to turn on
      the automatic checkpoint saving for preemption/maintenance events.
      This only supports
      `tf.distribute.MultiWorkerMirroredStrategy` on Google Cloud Platform
      or Google Borg for now.
c                   > [         TU ]  5         Xl        SU l        [        R
                  R                  [        R
                  R                  [        R
                  R                  R                  [        R
                  R                  [        R
                  R                  R                  4U l        X l        X0l        X@l        SU l        SU l        [        R"                  " 5       (       d0  [        R$                  " 5       (       a  ['        S5      e['        S5      eU(       d  U(       d  ['        S5      eSU l        g )NTr   z\This Callback's method contains Python state and should be called outside of `tf.function`s.zBackupAndRestore only supports eager mode. In graph mode, consider using ModelCheckpoint to manually save and restore weights with `model.load_weights()` and by providing `initial_epoch` in `model.fit()` for fault tolerance.z;Either `save_freq` or `save_before_preemption` must be set.F)rG  r   
backup_dirrW   rB   r   MirroredStrategyMultiWorkerMirroredStrategyexperimentalTPUStrategyParameterServerStrategy_supported_strategiesr  delete_checkpointsave_before_preemption_batches_countr  executing_eagerlyinside_functionr   r  )r{   rB  r  rI  rJ  rh   s        r.   r   BackupAndRestore.__init__6  s     	$!%MM**MM55MM&&22MM%%MM&&>>&
" #!2&<###%%!!## B 
 !!  $:P  #(r0   c                    U R                   R                  (       aZ  [        U R                   R                  U R                  5      (       d+  [        [        U R                   R                  5       S35      e[        R                  " U R                   U R                  U R                  U R                  5      U R                   l        U R                   R                  U l        U R                  R                  5         g )Nz is not supported yet. Currently BackupAndRestore callback only supports empty strategy, MirroredStrategy, MultiWorkerMirroredStrategy and TPUStrategy.)r(   _distribution_strategyr   r  rH  NotImplementedErrortyper   WorkerTrainingStaterB  r  rJ  _training_staterestorer0  s     r.   r   BackupAndRestore.on_train_begind  s     ::,,ZJJ**D,F,F6
 6
 &

6678 9Q Q  &;%N%NJJOONN''	&


"  $zz99$$&r0   c                     [        U R                  R                  [        R                  R
                  5      (       a  g U R                  R                  R                  U5        g rc   )	r   r(   r  rB   r   rG  rT  _ckpt_saved_batchassignr   s      r.   r   %BackupAndRestore.on_train_batch_beginz  sH    JJ**MM11
 
 ..55e<r0   c                    [        U R                  R                  [        R                  R
                  5      (       a  g U R                  R                  5         U R                  (       ac  U R                  S:w  aR  U =R                  S-  sl	        U R                  U R                  :  a"  SU l	        U R                  U R                  US9  g g g g )Nr   r   r   r  )r   r(   r  rB   r   rG  rT  backup_if_preemptedr  rK  _backupr  r   s      r.   r   #BackupAndRestore.on_train_batch_end  s    JJ**MM11
 
 002>>dnn71$""dnn4&'#4#6#6eD 5 8>r0   c                      U R                   S:g  $ r  r  r   s    r.   r_   .BackupAndRestore._implements_train_batch_hooks  s    ~~((r0   c                 v    U R                   (       a  U R                  R                  5         U ?U R                  ?g rc   )rI  rT  delete_backupr(   r0  s     r.   r   BackupAndRestore.on_train_end  s/    !!   ..0 JJ&r0   c                 Z    U R                   R                  R                  U5        Xl        g rc   )rT  _ckpt_saved_epochrY  r  r  s      r.   r   BackupAndRestore.on_epoch_begin  s"    ..55e<#r0   c                 D    U R                   S:X  a  U R                  US9  g g )Nr   r  )r  r]  r  s      r.   r   BackupAndRestore.on_epoch_end  s!    >>W$LLuL% %r0   c                 6    U R                   R                  XS9  g )Nr  )rT  back_up)r{   r   r   s      r.   r]  BackupAndRestore._backup  s    $$5$>r0   )
rK  r  r  rH  rW   rT  rB  rI  rJ  r  )r   TFrc   r   )ri   r  r  r	  r
  r   r   r   r   r_   r   r   r   r]  r  rY  rZ  s   @r.   r@  r@    sI    Y| $,(\',=E)'$&
? ?r0   r@  z-keras.callbacks.experimental.BackupAndRestorec                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )BackupAndRestoreExperimentali  zDeprecated. Please use `tf.keras.callbacks.BackupAndRestore` instead.

Caution: `tf.keras.callbacks.experimental.BackupAndRestore` endpoint is
  deprecated and will be removed in a future release. Please use
  `tf.keras.callbacks.BackupAndRestore`.
c                 R   > [         R                  " S5        [        TU ]  " U0 UD6  g )Nz`tf.keras.callbacks.experimental.BackupAndRestore` endpoint is deprecated and will be removed in a future release. Please use `tf.keras.callbacks.BackupAndRestore`.)r   r   rG  r   )r{   r  r  rh   s      r.   r   %BackupAndRestoreExperimental.__init__  s(    5	

 	$)&)r0   r  ri   r  r  r	  r
  r   r  rY  rZ  s   @r.   rn  rn    s    
* *r0   rn  zkeras.callbacks.EarlyStoppingc                   j   ^  \ rS rSrSr        S
U 4S jjrSS jrSS jrSS jrS r	S r
S	rU =r$ )EarlyStoppingi  a
  Stop training when a monitored metric has stopped improving.

Assuming the goal of a training is to minimize the loss. With this, the
metric to be monitored would be `'loss'`, and mode would be `'min'`. A
`model.fit()` training loop will check at end of every epoch whether
the loss is no longer decreasing, considering the `min_delta` and
`patience` if applicable. Once it's found no longer decreasing,
`model.stop_training` is marked True and the training terminates.

The quantity to be monitored needs to be available in `logs` dict.
To make it so, pass the loss or metrics at `model.compile()`.

Args:
  monitor: Quantity to be monitored.
  min_delta: Minimum change in the monitored quantity
      to qualify as an improvement, i.e. an absolute
      change of less than min_delta, will count as no
      improvement.
  patience: Number of epochs with no improvement
      after which training will be stopped.
  verbose: Verbosity mode, 0 or 1. Mode 0 is silent, and mode 1
      displays messages when the callback takes an action.
  mode: One of `{"auto", "min", "max"}`. In `min` mode,
      training will stop when the quantity
      monitored has stopped decreasing; in `"max"`
      mode it will stop when the quantity
      monitored has stopped increasing; in `"auto"`
      mode, the direction is automatically inferred
      from the name of the monitored quantity.
  baseline: Baseline value for the monitored quantity.
      Training will stop if the model doesn't show improvement over the
      baseline.
  restore_best_weights: Whether to restore model weights from
      the epoch with the best value of the monitored quantity.
      If False, the model weights obtained at the last step of
      training are used. An epoch will be restored regardless
      of the performance relative to the `baseline`. If no epoch
      improves on `baseline`, training will run for `patience`
      epochs and restore weights from the best epoch in that set.
  start_from_epoch: Number of epochs to wait before starting
      to monitor improvement. This allows for a warm-up period in which
      no improvement is expected and thus training will not be stopped.


Example:

>>> callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=3)
>>> # This callback will stop the training when there is no improvement in
>>> # the loss for three consecutive epochs.
>>> model = tf.keras.models.Sequential([tf.keras.layers.Dense(10)])
>>> model.compile(tf.keras.optimizers.SGD(), loss='mse')
>>> history = model.fit(np.arange(100).reshape(5, 20), np.zeros(5),
...                     epochs=10, batch_size=1, callbacks=[callback],
...                     verbose=0)
>>> len(history.history['loss'])  # Only 4 epochs are run.
4
c	                 
  > [         T	U ]  5         Xl        X0l        X@l        X`l        [        U5      U l        SU l        SU l	        Xpl
        S U l        Xl        US;  a  [        R                  " SU5        SnUS:X  a  [        R                   U l        OUS:X  a  [        R$                  U l        OU R                  R'                  S5      (       d@  U R                  R'                  S5      (       d   U R                  R'                  S	5      (       a  [        R$                  U l        O[        R                   U l        U R"                  [        R$                  :X  a  U =R                  S
-  sl        g U =R                  S-  sl        g )Nr   r  z8EarlyStopping mode %s is unknown, fallback to auto mode.r  r  r  r  accuracyaucr   r  )rG  r   r  patiencer   baselineabs	min_deltawaitstopped_epochrestore_best_weightsbest_weightsstart_from_epochr   r   rc  r  r  r  r  )
r{   r  rz  rw  r   r   rx  r}  r  rh   s
            r.   r   EarlyStopping.__init__  s    	  Y	$8!  0--OOJ D5= ggDOU] jjDO %%e,,<<((44<<((//"$**"$''??bjj(NNaNNNb Nr0   c                     SU l         SU l        U R                  [        R                  :X  a  [        R
                  O[        R
                  * U l        S U l        SU l        g rK  )	r{  r|  r  rc  r  r  r  r~  
best_epochr0  s     r.   r   EarlyStopping.on_train_begin-  sB    	"oo8BFFrvvg	 r0   c                 |   U R                  U5      nUb  XR                  :  a  g U R                  (       a,  U R                  c  U R                  R                  5       U l        U =R                  S-  sl        U R                  X0R                  5      (       aq  X0l        Xl	        U R                  (       a  U R                  R                  5       U l        U R                  b   U R                  X0R                  5      (       a  SU l        g U R                  U R                  :  a  US:  a  Xl        SU R                  l        U R                  (       ak  U R                  b]  U R                  S:  a'  [        R                   " SU R                  S-    S35        U R                  R#                  U R                  5        g g g g g )Nr   r   Tz8Restoring model weights from the end of the best epoch: r  )get_monitor_valuer  r}  r~  r(   get_weightsr{  _is_improvementr  r  rx  rw  r|  r)   r   r	   rf  set_weights)r{   r   rM   r  s       r.   r   EarlyStopping.on_epoch_end5  sg   ((.?e&;&;;$$):):)B $

 6 6 8D		Q	33I#O(($(JJ$:$:$<! }}$(<(<) ) 	 99%%!)!&'+DJJ$((T->->-J<<!#&&6??Q./q2
 

&&t'8'89 .K( +4%r0   c                     U R                   S:  a9  U R                  S:  a(  [        R                  " SU R                   S-    S35        g g g )Nr   r  r   z: early stopping)r|  r   r	   rf  r0  s     r.   r   EarlyStopping.on_train_endY  sJ    !dllQ&6++a/00@A '7!r0   c           
          U=(       d    0 nUR                  U R                  5      nUcH  [        R                  " SU R                  SR	                  [        UR                  5       5      5      5        U$ )Nz[Early stopping conditioned on metric `%s` which is not available. Available metrics are: %s,)rR  r  r   r   r/  r  keys)r{   rM   monitor_values      r.   r  EarlyStopping.get_monitor_value_  s[    zr. OODdiik*+	 r0   c                 >    U R                  XR                  -
  U5      $ rc   )r  rz  )r{   r  reference_values      r.   r  EarlyStopping._is_improvementk  s    }~~=OOr0   )rx  r  r  r~  rz  r  r  rw  r}  r  r|  r   r{  )r=  r   r   r   r  NFr   rc   )ri   r  r  r	  r
  r   r   r   r   r  r  r  rY  rZ  s   @r.   rs  rs    sJ    8x "0!d":H
P Pr0   rs  zkeras.callbacks.RemoteMonitorc                   D   ^  \ rS rSrSr     SU 4S jjrSS jrSrU =r$ )RemoteMonitorio  a8  Callback used to stream events to a server.

Requires the `requests` library.
Events are sent to `root + '/publish/epoch/end/'` by default. Calls are
HTTP POST, with a `data` argument which is a
JSON-encoded dictionary of event data.
If `send_as_json=True`, the content type of the request will be
`"application/json"`.
Otherwise the serialized JSON will be sent within a form.

Args:
  root: String; root url of the target server.
  path: String; path relative to `root` to which the events will be sent.
  field: String; JSON field under which the data will be stored.
      The field is used only if the payload is sent within a form
      (i.e. send_as_json is set to False).
  headers: Dictionary; optional custom HTTP headers.
  send_as_json: Boolean; whether the request should be
      sent as `"application/json"`.
c                 ^   > [         TU ]  5         Xl        X l        X0l        X@l        XPl        g rc   )rG  r   rootr  fieldheaderssend_as_json)r{   r  r  r  r  r  rh   s         r.   r   RemoteMonitor.__init__  s*     			
(r0   c                    [         c  [        S5      eU=(       d    0 n0 nXS'   UR                  5        HL  u  pE[        U[        R
                  [        R                  45      (       a  UR                  5       X4'   MH  XSU'   MN      U R                  (       a7  [         R                  " U R                  U R                  -   X0R                  S9  g [         R                  " U R                  U R                  -   U R                  [        R                  " U5      0U R                  S9  g ! [         R                   R"                   a/    [$        R&                  " S[)        U R                  5      -   5         g f = f)Nz.RemoteMonitor requires the `requests` library.r   )jsonr  )r  z6Warning: could not reach RemoteMonitor root server at )requestsImportErrorrS  r   rc  ndarraygenericitemr  postr  r  r  r  r  dumps
exceptionsRequestExceptionr   r   r  )r{   r   rM   sendrT  rU  s         r.   r   RemoteMonitor.on_epoch_end  s   NOOzrWJJLDA !bjj"**566&&(Q !	  II		)ll II		)ZZD!12 LL
 ""33 	OOHdii.!	s   AD% AD% %A
E21E2)r  r  r  r  r  )zhttp://localhost:9000z/publish/epoch/end/rE   NFrc   )	ri   r  r  r	  r
  r   r   r  rY  rZ  s   @r.   r  r  o  s(    . %")  r0   r  z%keras.callbacks.LearningRateSchedulerc                   D   ^  \ rS rSrSrSU 4S jjrSS jrSS jrSrU =r	$ )	LearningRateScheduleri  a  Learning rate scheduler.

At the beginning of every epoch, this callback gets the updated learning
rate value from `schedule` function provided at `__init__`, with the current
epoch and current learning rate, and applies the updated learning rate on
the optimizer.

Args:
  schedule: a function that takes an epoch index (integer, indexed from 0)
      and current learning rate (float) as inputs and returns a new
      learning rate as output (float).
  verbose: int. 0: quiet, 1: update messages.

Example:

>>> # This function keeps the initial learning rate for the first ten epochs
>>> # and decreases it exponentially after that.
>>> def scheduler(epoch, lr):
...   if epoch < 10:
...     return lr
...   else:
...     return lr * tf.math.exp(-0.1)
>>>
>>> model = tf.keras.models.Sequential([tf.keras.layers.Dense(10)])
>>> model.compile(tf.keras.optimizers.SGD(), loss='mse')
>>> round(model.optimizer.lr.numpy(), 5)
0.01

>>> callback = tf.keras.callbacks.LearningRateScheduler(scheduler)
>>> history = model.fit(np.arange(100).reshape(5, 20), np.zeros(5),
...                     epochs=15, callbacks=[callback], verbose=0)
>>> round(model.optimizer.lr.numpy(), 5)
0.00607

c                 :   > [         TU ]  5         Xl        X l        g rc   )rG  r   scheduler   )r{   r  r   rh   s      r.   r   LearningRateScheduler.__init__  s     r0   c                    [        U R                  R                  S5      (       d  [        S5      e [	        [
        R                  " U R                  R                  R                  5      5      nU R                  X5      n[        U[        R                  [        [        R                  [        R                  45      (       d  [        SU 35      e[        U[        R                  5      (       a3  UR                   R"                  (       d  [        SUR                    35      e[
        R$                  " U R                  R                  R                  [
        R                  " U5      5        U R&                  S:  a!  [(        R*                  " SUS-    SU S	35        g g ! [         a    U R                  U5      n GN<f = f)
Nlrz%Optimizer must have a "lr" attribute.z<The output of the "schedule" function should be float. Got: z/The dtype of `lr` Tensor should be float. Got: r   r  r   z1: LearningRateScheduler setting learning rate to r  )rA   r(   r   r   floatr   	get_valuer  r  r  r   rB   Tensorrc  float32float64dtypeis_floating	set_valuer   r	   rf  )r{   r   rM   r  s       r.   r   $LearningRateScheduler.on_epoch_begin  s^   tzz++T22DEE	&w(()=)=)@)@ABBu)B "ryy%RZZHII))+.  b"))$$RXX-A-AA"((L  	$**..1173D3DR3HI<<!519+ &$a!   	&u%B	&s   AF F=<F=c                     U=(       d    0 n[         R                  " U R                  R                  R                  5      US'   g )Nr  )r   r  r(   r   r  r  s      r.   r   "LearningRateScheduler.on_epoch_end  s/    zr&&tzz';';'>'>?T
r0   )r  r   rl  rc   )
ri   r  r  r	  r
  r   r   r   r  rY  rZ  s   @r.   r  r    s    "H
0@ @r0   r  c                    [         R                  R                  R                  5       nSUR                  l        SUR                  l         UR                  5       n[         R                  R                  R                  U SX/5       u  pg[         R                  " S5         [         R                  " U[         R                   S9nSSS5        [         R                  R#                  UWX#S9sSSS5        $ ! [         a!  n[        R                  " SU5         SnAgSnAff = f! , (       d  f       Nd= f! , (       d  f       g= f)	aP  Writes a TF-Keras model as JSON to as a Summary.

Writing the TF-Keras model configuration allows the TensorBoard graph plugin
to render a conceptual graph, as opposed to graph of ops. In case the model
fails to serialize as JSON, it ignores and returns False.

Args:
  name: A name for this summary. The summary tag used for TensorBoard will
    be this name prefixed by any active name scopes.
  data: A TF-Keras Model to write.
  step: Explicit `int64`-castable monotonic step value for this summary. If
    omitted, this defaults to `tf.summary.experimental.get_step()`, which
    must not be None.

Returns:
  True on success, or False if no summary was written because no default
  summary writer was available.

Raises:
  ValueError: if a default writer exists, but no step was provided and
    `tf.summary.experimental.get_step()` is None.
graph_keras_model   1z1Model failed to serialize as JSON. Ignoring... %sNFzcpu:0)r  )tagtensorr  metadata)rB   rC   rD   SummaryMetadataplugin_dataplugin_namecontentto_json	Exceptionr   r   summaryrE  summary_scopedeviceconstantstringwrite)	r  rE   r  summary_metadatajson_stringexcr  _r  s	            r.   keras_model_summaryr    s    . yy||335 0C  ,+/  (lln 
	 	 	.	.!D<
	#YYw[[BII>F  zzF   

 
  ?	
   
 
s<   C5 D4!$D#&D45
D ?DD #
D1	-D44
Ezkeras.callbacks.TensorBoardc                   >  ^  \ rS rSrSr         S%U 4S jjrS rS r\S 5       r	\S 5       r
S rS	 rS
 rS rS rS rS rS rS rS&S jrS&S jrS&S jrS&S jrS rS&S jrS&S jrS&S jrS&S jrS rS&S jrS rS r S r!S r"S  r#S! r$S" r%S'S# jr&S$r'U =r($ )(TensorBoardi/	  a1  Enable visualizations for TensorBoard.

TensorBoard is a visualization tool provided with TensorFlow.

This callback logs events for TensorBoard, including:

* Metrics summary plots
* Training graph visualization
* Weight histograms
* Sampled profiling

When used in `Model.evaluate` or regular validation
([on_test_end](https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks/Callback#on_test_end)),
in addition to epoch summaries, there will be a summary that records
evaluation metrics vs `Model.optimizer.iterations` written. The metric names
will be prepended with `evaluation`, with `Model.optimizer.iterations` being
the step in the visualized TensorBoard.

If you have installed TensorFlow with pip, you should be able
to launch TensorBoard from the command line:

```
tensorboard --logdir=path_to_your_logs
```

You can find more information about TensorBoard
[here](https://www.tensorflow.org/get_started/summaries_and_tensorboard).

Args:
    log_dir: the path of the directory where to save the log files to be
      parsed by TensorBoard. e.g. log_dir = os.path.join(working_dir,
      'logs') This directory should not be reused by any other callbacks.
    histogram_freq: frequency (in epochs) at which to compute
      weight histograms for the layers of the model. If set to 0, histograms
      won't be computed. Validation data (or split) must be specified for
      histogram visualizations.
    write_graph: whether to visualize the graph in TensorBoard. The log file
      can become quite large when write_graph is set to True.
    write_images: whether to write model weights to visualize as image in
      TensorBoard.
    write_steps_per_second: whether to log the training steps per second
      into TensorBoard. This supports both epoch and batch frequency
      logging.
    update_freq: `'batch'` or `'epoch'` or integer. When using `'epoch'`,
      writes the losses and metrics to TensorBoard after every epoch.
      If using an integer, let's say `1000`, all metrics and losses
      (including custom ones added by `Model.compile`) will be logged to
      TensorBoard every 1000 batches. `'batch'` is a synonym for `1`,
      meaning that they will be written every batch.
      Note however that writing too frequently to TensorBoard can slow down
      your training, especially when used with `tf.distribute.Strategy` as
      it will incur additional synchronization overhead.
      Use with `ParameterServerStrategy` is not supported.
      Batch-level summary writing is also available via `train_step`
      override. Please see
      [TensorBoard Scalars tutorial](https://www.tensorflow.org/tensorboard/scalars_and_keras#batch-level_logging)  # noqa: E501
      for more details.
    profile_batch: Profile the batch(es) to sample compute characteristics.
      profile_batch must be a non-negative integer or a tuple of integers.
      A pair of positive integers signify a range of batches to profile.
      By default, profiling is disabled.
    embeddings_freq: frequency (in epochs) at which embedding layers will be
      visualized. If set to 0, embeddings won't be visualized.
    embeddings_metadata: Dictionary which maps embedding layer names to the
      filename of a file in which to save metadata for the embedding layer.
      In case the same metadata file is to be
      used for all embedding layers, a single filename can be passed.

Examples:

Basic usage:

```python
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir="./logs")
model.fit(x_train, y_train, epochs=2, callbacks=[tensorboard_callback])
# Then run the tensorboard command to view the visualizations.
```

Custom batch-level summaries in a subclassed Model:

```python
class MyModel(tf.keras.Model):

  def build(self, _):
    self.dense = tf.keras.layers.Dense(10)

  def call(self, x):
    outputs = self.dense(x)
    tf.summary.histogram('outputs', outputs)
    return outputs

model = MyModel()
model.compile('sgd', 'mse')

# Make sure to set `update_freq=N` to log a batch-level summary every N
# batches.  In addition to any `tf.summary` contained in `Model.call`,
# metrics added in `Model.compile` will be logged every N batches.
tb_callback = tf.keras.callbacks.TensorBoard('./logs', update_freq=1)
model.fit(x_train, y_train, callbacks=[tb_callback])
```

Custom batch-level summaries in a Functional API Model:

```python
def my_summary(x):
  tf.summary.histogram('x', x)
  return x

inputs = tf.keras.Input(10)
x = tf.keras.layers.Dense(10)(inputs)
outputs = tf.keras.layers.Lambda(my_summary)(x)
model = tf.keras.Model(inputs, outputs)
model.compile('sgd', 'mse')

# Make sure to set `update_freq=N` to log a batch-level summary every N
# batches. In addition to any `tf.summary` contained in `Model.call`,
# metrics added in `Model.compile` will be logged every N batches.
tb_callback = tf.keras.callbacks.TensorBoard('./logs', update_freq=1)
model.fit(x_train, y_train, callbacks=[tb_callback])
```

Profiling:

```python
# Profile a single batch, e.g. the 5th batch.
tensorboard_callback = tf.keras.callbacks.TensorBoard(
    log_dir='./logs', profile_batch=5)
model.fit(x_train, y_train, epochs=2, callbacks=[tensorboard_callback])

# Profile a range of batches, e.g. from 10 to 20.
tensorboard_callback = tf.keras.callbacks.TensorBoard(
    log_dir='./logs', profile_batch=(10,20))
model.fit(x_train, y_train, epochs=2, callbacks=[tensorboard_callback])
```
c
                 d  > [         TU ]  5         SU l        U R                  U
5        [        R
                  " U5      U l        X l        X0l        X@l	        XPl
        US:X  a  SOUU l        Xl        Xl        U R                  U5        SU l        SU l        SU l        SU l        0 U l        / U l        g )NTr   r   r   )rG  r   rW   _validate_kwargsr	   r  log_dirhistogram_freqwrite_graphwrite_imageswrite_steps_per_secondupdate_freqembeddings_freqembeddings_metadata_init_profile_batch_global_train_batch_previous_epoch_iterations_train_accumulated_timery   _writers_prev_summary_state)r{   r  r  r  r  r  r  profile_batchr  r  r  rh   s              r.   r   TensorBoard.__init__	  s     	!%f%..w7,&(&<# +w 61K.#6   /#$ *+''($!"  $& r0   c                    UR                  SS5      (       a  [        R                  " S5        UR                  SS5      (       a  [        R                  " S5        UR                  SS5      (       a  [        R                  " S5        UR                  SS5      (       a  [        R                  " S	5        1 S
kn[        UR	                  5       5      U-
  nU(       a  [        SU SU 35      eg)z&Handle arguments were supported in V1.write_gradsFzO`write_grads` will be ignored in TensorFlow 2.0 for the `TensorBoard` Callback.r   ze`batch_size` is no longer needed in the `TensorBoard` Callback and will be ignored in TensorFlow 2.0.embeddings_layer_nameszp`embeddings_layer_names` is not supported in TensorFlow 2.0. Instead, all `Embedding` layers will be visualized.embeddings_datazl`embeddings_data` is not supported in TensorFlow 2.0. Instead, all `Embedding` variables will be visualized.>   r   r  r  r  z2Unrecognized arguments in `TensorBoard` Callback: z. Supported kwargs are: N)rR  r   r   rH  r  r   )r{   r  supported_kwargsunrecognized_kwargss       r.   r  TensorBoard._validate_kwargs	  s    ::mU++OO2 ::lE**OO%
 ::.66OO&
 ::'//OO
 "&++-03CC D&' ())9(:<  r0   c                    Xl         U R                  5       U l        [        R                  R                  U R                  S5      U l        U R                   R                  U l        [        R                  R                  U R                  S5      U l	        U R                   R                  U l        0 U l        SU l        U R                  (       a  U R                  5         SU l        U R                   (       a  U R#                  5         gg)z2Sets TF-Keras model and writes graph if specified.r  
validationFTN)r(   _get_log_write_dir_log_write_dirr  r  r/  
_train_dirrt  rm  _val_dirru  	_val_stepr  _should_write_train_graphr  _write_keras_model_summaryr  _configure_embeddingsr  s     r.   r&   TensorBoard.set_model

  s    
"557'',,t':':GD::44T%8%8,G11).&++--1D*&&(  r0   c                     SU R                   ;  a6  [        R                  R                  U R                  5      U R                   S'   U R                   S   $ )Nr  )r  rB   r  create_file_writerr  r   s    r.   _train_writerTensorBoard._train_writer
  sC    $--'%'ZZ%B%B&DMM'" }}W%%r0   c                     SU R                   ;  a6  [        R                  R                  U R                  5      U R                   S'   U R                   S   $ )Nval)r  rB   r  r  r  r   s    r.   _val_writerTensorBoard._val_writer&
  s>    %#%::#@#@#ODMM% }}U##r0   c                 l    [         R                  " U R                  U R                  R                  5      $ )zBFor multi-worker, only chief should write, others write to '/tmp'.)r   write_dirpathr  r(   r  r   s    r.   r  TensorBoard._get_log_write_dir,
  s(    %33LL$**88
 	
r0   c                 n    [         R                  " U R                  U R                  R                  5        g)z/Deletes tmp write directories for multi-worker.N)r   remove_temp_dirpathr  r(   r  r   s    r.   _delete_tmp_write_dir!TensorBoard._delete_tmp_write_dir2
  s#    22LL$**88	
r0   c                    U R                   R                  5          [        R                  R	                  S5         U R
                  R                  n[        US5      (       a3  [        R                  R                  UR                  R                  5        SSS5        SSS5        g! , (       d  f       N= f! , (       d  f       g= f)z:Writes TF-Keras model train_function graph to TensorBoard.Tfunction_specN)
r  
as_defaultrB   r  	record_ifr(   train_tf_functionrA   graph_concrete_variable_creation_fn)r{   train_fns     r.   _write_keras_model_train_graph*TensorBoard._write_keras_model_train_graph8
  s    **,%%d+::77 8_55JJ$$ ??EE , -,++ -,s#    B8AB'B8'
B5	1B88
Cc                    U R                   R                  5          [        R                  R	                  S5         U R
                  R                  =(       d#    U R
                  R                  R                  S:H  nU(       a  [        SU R
                  SS9  SSS5        SSS5        g! , (       d  f       N= f! , (       d  f       g= f)z5Writes TF-Keras graph network summary to TensorBoard.T
Sequentialkerasr   r  N)
r  r	  rB   r  r
  r(   _is_graph_networkrh   ri   r  )r{   summary_writables     r.   r  &TensorBoard._write_keras_model_summaryD
  s    **,%%d+JJ00 Ezz++44D ! $'!D , -,++ -,s#    B:AB)B:)
B7	3B::
Cc                    SSK Jn  SSKJn  SSKJn  UR                  5       nU R                  R                   H  n[        XQR                  5      (       d  M  UR                  R                  5       nSnXvl        U R                  c  MP  [        U R                  [        5      (       a  U R                  Ul        M  UR"                  U R                  R%                  5       ;   d  M  U R                  R'                  UR"                  5      Ul        M     U R                  (       aE  [        U R                  [        5      (       d&  [)        SU R                  R%                  5        35      eUR+                  U5      n[,        R.                  R1                  U R2                  S5      n	[4        R6                  R8                  R;                  U	S	5       n
U
R=                  U5        SSS5        g! , (       d  f       g= f)
z'Configure the Projector for embeddings.r   )core)projector_config_pb2)text_formatz:layer_with_weights-0/embeddings/.ATTRIBUTES/VARIABLE_VALUENzmUnrecognized `Embedding` layer names passed to `keras.callbacks.TensorBoard` `embeddings_metadata` argument: zprojector_config.pbtxtw)tf_keras.src.layersr  tf_keras.protobufr  google.protobufr  ProjectorConfigr(   layersr   	Embedding
embeddingsaddtensor_namer  r  metadata_pathr  r  r  r   MessageToStringr  r  r/  r  rB   r  r  GFiler  )r{   r  r  r  configlayer	embeddingr  config_pbtxtr  fs              r.   r  !TensorBoard._configure_embeddingsO
  s~    	-: 	0%557ZZ&&E%00"--113	 Q  )-%++7!$":":C@@262J2J	/ ::)A)A)F)F)HH $ 8 8 < <UZZ H &3 '& ##J$$c-
 -
 !55::<=?  #226:ww||D//1IJUU[[tS)QGGL! *))s   G))
G7c                 6  ^ ^ T R                   S:X  a  gU U4S jnUR                  TR                  5       5      [        R                  R                  U5      4nT R                  R                  U5        US   R                  5         US   R                  5         g)z9Sets the default writer for custom batch-level summaries.r   Nc                  L   > [         R                  " TT R                  -  S5      $ rK  )rB   equalr  )r{   r  s   r.   <lambda>*TensorBoard._push_writer.<locals>.<lambda>
  s    0@0@)@! Dr0   r   r   )	r  r	  valuerB   r  r
  r  r#   	__enter__)r{   writerr  should_recordsummary_contexts   ` `  r.   _push_writerTensorBoard._push_writerz
  s    w&D djjl+JJ  /
 	  ''8$$&$$&r0   c                     U R                   S:X  a  gU R                  R                  5       nUS   R                  " [        R
                  " 5       6   US   R                  " [        R
                  " 5       6   g)zPops the current writer.r   Nr   r   )r  r  r  __exit__sysexc_info)r{   previous_contexts     r.   _pop_writerTensorBoard._pop_writer
  s\    w&  33779$$clln5$$clln5r0   c                 f    U R                   R                  5        H  nUR                  5         M     g rc   )r  valuesclose)r{   r6  s     r.   _close_writersTensorBoard._close_writers
  s"    mm**,FLLN -r0   c                    SU 3n[        U[        5      (       a>  [        U5      R                  S5      n[        R                  R                  [        U5      n[        U[        5      (       a  Xl        Xl        OE[        U[        [        45      (       a  [        U5      S:X  a  Uu  U l        U l        O[        U5      eU R                  S:  d  U R                  U R                  :  a  [        U5      eSU l        U R                  S:  a  U R                  SS9  U R                  SS9  SU l        U R                  S:H  =(       a    U R                  S:H  (       + U l        g	)
a/  Validate profile_batch value and set the range of batches to profile.

Sets values of _start_batch and _stop_batch attributes,
specifying the start and stop batch to profile.
Setting `profile_batch=0` disables profiling.

Args:
  profile_batch: The range of batches to profile. Should be a
    non-negative integer or a comma separated string of pair of positive
    integers. A pair of positive integers signify a range of batches to
    profile.

Raises:
  ValueError: If profile_batch is not an integer or a comma separated
    pair of positive integers.

zprofile_batch must be a non-negative integer or 2-tuple of positive integers. A pair of positive integers signifies a range of batches to profile. Found: r     r   Fr  logdirr  N)r   r  splitrB   rl   map_structurer  _start_batch_stop_batchtupler  r   r   _profiler_started_start_profiler_stop_profiler_is_tracing_should_trace)r{   r  profile_batch_error_messages      r.   r  TensorBoard._init_profile_batch
  s=   &" #0	2 	$ mS)).44S9MGG11#}EMmS)) -,}udm44]9Kq9P2?/Dt/899q D$4$4t7H7H$H899
 "'q    +U+  "<t'7'71'<
r0   c                 l    SU l         SU l        U R                  U R                  U R                  5        g rK  )r  r  r9  r  rm  r0  s     r.   r   TensorBoard.on_train_begin
  s.    #$ *+'$,,d.>.>?r0   c                     U R                  5         U R                  (       a  U R                  5         U R                  5         U R	                  5         g rc   )r@  rT  _stop_tracerE  r  r0  s     r.   r   TensorBoard.on_train_end
  s;    ""$r0   c                 P    U R                  U R                  U R                  5        g rc   )r9  r  r  r0  s     r.   r   TensorBoard.on_test_begin
  s    $**DNN;r0   c           	      R   U R                   R                  (       a  [        U R                   R                  S5      (       a  [        R                  R                  S5         U R                  R                  5          UR                  5        HV  u  p#[        R                  R                  SU-   S-   UU R                   R                  R                  R                  5       S9  MX     S S S 5        S S S 5        U R                  5         g ! , (       d  f       N'= f! , (       d  f       N0= f)N
iterationsTevaluation__vs_iterationsr  )r(   r   rA   rB   r  r
  r  r	  rS  scalarr`  
read_valuer@  )r{   rM   r  r4  s       r.   r   TensorBoard.on_test_end
  s    ::GDJJ,@,@,$O$O%%d+T-=-=-H-H-J#'::<KDJJ%%%,/??!ZZ11<<GGI &  $0 .K+ 	 .K-J++s%    D;A+D&D
D	D
D&c                 @    U R                   =(       d    U R                  $ rc   )rU  r  r   s    r.   r_   )TensorBoard._implements_train_batch_hooks
  s     !!@T%@%@@r0   c                     U =R                   S-  sl         U R                  (       a  [        R                  " 5       U l        U R                  (       d  g U R                   U R
                  :X  a  U R                  5         g g )Nr   )r  r  r   ry   rU  rN  _start_tracer   s      r.   r    TensorBoard.on_train_batch_begin
  s[      A% &&%)YY[D"!!##t'8'88 9r0   c                 b   U R                   (       a  U R                  5         SU l         U R                  (       aN  [        R                  " 5       U R                  -
  n[
        R                  R                  SSU-  U R                  S9  [        U[        5      (       aD  UR                  5        H0  u  pE[
        R                  R                  SU-   XPR                  S9  M2     U R                  (       d  g U R                  (       a,  U R                  U R                  :  a  U R!                  5         g g g )NFbatch_steps_per_secondr   r  batch_)r  r  r  r   ry   rB   r  rc  rm  r   dictrS  rU  rT  r  rO  r[  )r{   r   rM   batch_run_timer  r4  s         r.   r   TensorBoard.on_train_batch_end
  s    ))//1-2D*&&!YY[4+A+AANJJ(n$%%   dD!!#zz|

!!(T/5?O?O!P  , !! 8 8D<L<L L !Mr0   c                     U R                   (       aN  U R                  R                  R                  R	                  5       U l        [        R                  " 5       U l        g g rc   )r  r(   r   r`  r  r  r   _epoch_start_timer  s      r.   r   TensorBoard.on_epoch_begin  sD    &&

$$//557 + &*YY[D"	 'r0   c                     U R                  X5        U R                  (       a#  XR                  -  S:X  a  U R                  U5        U R                  (       a%  XR                  -  S:X  a  U R	                  U5        ggg)z2Runs metrics and histogram summaries at epoch end.r   N)_log_epoch_metricsr  _log_weightsr  _log_embeddingsr  s      r.   r   TensorBoard.on_epoch_end!  sg    ,5+>+>#>!#Ce$E,@,@$@A$E  ' %Fr0   c                     [         R                  R                  SSS9  U R                  U R                  S9  SU l        g )NTF)r  profilerrI  )rB   r  trace_onrR  r  rT  r   s    r.   ri  TensorBoard._start_trace+  s6    


$7DLL1r0   c                 l   Uc  U R                   nU R                  R                  5          [        R                  R                  S5         [        R                  R                  SU-  US9  SSS5        SSS5        U R                  5         SU l        g! , (       d  f       N.= f! , (       d  f       N7= f)z$Logs the trace graph to TensorBoard.NTzbatch_%d)r  r  F)	rO  r  r	  rB   r  r
  trace_exportrS  rT  )r{   r   s     r.   r[  TensorBoard._stop_trace0  s    =$$E**,%%d+

''Z%-?e'L , - 	 	 ,+ -,s#    B%
"B,B%
B"	B%%
B3c                    [        U R                  R                  [        R                  5      (       a"  [	        U R                  R                  SS 5      nO![	        U R                  R                  SS 5      n[        U[
        R                  5      (       a)  U" U R                  R                  R                  5      US'   U$ )N_learning_rater  learning_rate)r   r(   r   	OptimizerrX   r   LearningRateScheduler`  )r{   rM   lr_schedules      r.   _collect_learning_rate"TensorBoard._collect_learning_rate;  s    djj**I,?,?@@!$**"6"68H$OK!$**"6"6dCKk#9#N#NOO$/

0D0D0O0O$PD!r0   c                     U R                   R                  R                  R                  5       n[        R                  " 5       U R
                  -
  nXR                  -
  U-  nU$ rc   )r(   r   r`  r  r   rr  r  )r{   current_iterationtime_since_epoch_beginsteps_per_seconds       r.   _compute_steps_per_second%TensorBoard._compute_steps_per_secondD  sW     JJ00;;AAC!%t/E/E!E ? ??"#  r0   c           	      h   U(       d  g[        5       n[        5       nUR                  5        H%  u  pVUR                  S5      (       a  XdU'   M!  XcU'   M'     U R                  U5      nU R                  (       a  U R                  5       US'   [        R                  R                  S5         U(       a]  U R                  R                  5          UR                  5        H&  u  px[        R                  R                  SU-   XS9  M(     SSS5        U(       ab  U R                  R                  5          UR                  5        H+  u  pxUSS n[        R                  R                  SU-   XS9  M-     SSS5        SSS5        g! , (       d  f       N= f! , (       d  f       N(= f! , (       d  f       g= f)zWrites epoch metrics out as scalar summaries.

Args:
    epoch: Int. The global step to use for TensorBoard.
    logs: Dict. Keys are scalar summary names, values are scalars.
Nr2   r  Tepoch_r     )rn  rS  r  r  r  r  rB   r  r
  r  r	  rc  r  )	r{   r   rM   
train_logsval_logsrT  rU  r  r4  s	            r.   ru  TensorBoard._log_epoch_metricsL  sH    V
6JJLDA||F## !1	 ! 00<
&&-1-K-K-MJ)*ZZ!!$'''224'1'7'7'9

))(T/5)M (: 5 %%002'/~~'7#ABx

))(T/5)M (8 3 ('44 32 ('s=   *"F#;F)F#0A F0F#
F	F#
F 	F##
F1c           
      D   U R                   R                  5          [        R                  R	                  S5         U R
                  R                   H  nUR                   Hl  nUR                  R                  SS5      nUS-   n[        R                  R                  XSUS9  U R                  (       d  MU  US-   nU R                  X6U5        Mn     M     U R                   R                  5         SSS5        SSS5        g! , (       d  f       N= f! , (       d  f       g= f)z-Logs the weights of the Model to TensorBoard.T:r  z
/histogramr  z/imageN)r  r	  rB   r  r
  r(   r!  weightsr  replace	histogramr  _log_weight_as_imageflush)r{   r   r*  weightweight_namehistogram_weight_nameimage_weight_names          r.   rv  TensorBoard._log_weightsm  s    **,%%d+!ZZ..E"'--&,kk&9&9#s&C0;l0J-

,,1 -   ,,, 1<h0F- 55 &5 #0 / ""((*! , -,++ -,s)    DA7D 69D /D 
D	
D
Dc                    [         R                  " U5      n[        R                  " U5      n[	        U5      S:X  a  [         R
                  " USUS   SS/5      nO[	        U5      S:X  aZ  US   US   :  a,  [         R                  " U5      n[        R                  " U5      n[         R
                  " USUS   US   S/5      nOx[	        U5      S:X  ai  [        R                  " 5       S:X  a-  [         R                  " U/ SQS9n[        R                  " U5      n[         R
                  " XES   US   US   S/5      n[        R                  " U5      n[	        U5      S:X  a)  US	   S
;   a  [         R                  R                  X$US9  ggg)z%Logs a weight as a TensorBoard image.r   r   rH     channels_last)rH  r   r   )permr  r  )r   r  r  r  N)
rB   squeezer   	int_shaper   reshape	transposeimage_data_formatr  image)r{   r  r  r   w_imgshapes         r.   r   TensorBoard._log_weight_as_image  sG   

6"!!%(u:?JJuq%(Aq&9:EZ1_Qx%("U+))%0JJuq%(E!Ha&@AEZ1_((*o= U;))%0JJuQxq58Q&GHE!!%(u:?uRyI5JJ[e<  6?r0   c                     [         R                  R                  U R                  SSU 35      nU R                  R                  U5        g )Nr  zkeras_embedding.ckpt-)r  r  r/  r  r(   r  )r{   r   embeddings_ckpts      r.   rw  TensorBoard._log_embeddings  s>    '',,#E7+

 	

0r0   c                    U R                   (       a  g [        R                  R                  R	                  US9  SU l         g! [        R
                  R                   a+  n[        R                  " SUR                  5         SnAgSnAff = f)zlStarts the profiler if currently inactive.

Args:
  logdir: Directory where profiler results will be saved.
NrI  TzFailed to start profiler: %s)
rQ  rB   rz  rE  starterrorsAlreadyExistsErrorr   errormessage)r{   rJ  r  s      r.   rR  TensorBoard._start_profiler  sk     !!	EKK$$**&*9%)D"yy++ 	EMM8!))DD	Es   .A B!!BBc                 6   U R                   (       d  g [        R                  R                  R	                  US9  SU l         g! [        R
                  R                   a+  n[        R                  " SUR                  5         SnANLSnAff = f! SU l         f = f)zlStops the profiler if currently active.

Args:
  save: Whether to save the profiler results to TensorBoard.
NrK  zFailed to stop profiler: %sF)
rQ  rB   rz  rE  stopr  UnavailableErrorr   r  r  )r{   r  r  s      r.   rS  TensorBoard._stop_profiler  sy     %%	+KK$$))t)4
 &+D"	 yy)) 	DMM7CC	D &+D"s)   'A B!!BB BB 	B)ry   rr  r  rT  r  r  r  rQ  rU  r  rN  rO  rW   r  r  rm  r  r  r  r  r  r  r  r(   r  r  r  r  )	rM   r   TFFr   r   r   Nrc   )T))ri   r  r  r	  r
  r   r  r&   propertyr  r  r  r  r  r  r  r9  r@  rE  r  r   r   r   r   r_   r   r   r   r   ri  r[  r  r  ru  rv  r  rw  rR  rS  r  rY  rZ  s   @r.   r  r  /	  s    FT $ $&L(T)( & & $ $



	E)"V'	6:
x@
%<	A
 41( 
	! NB+*=01E+ +r0   r  z!keras.callbacks.ReduceLROnPlateauc                   `   ^  \ rS rSrSr        S	U 4S jjrS rS
S jrS
S jrS r	Sr
U =r$ )ReduceLROnPlateaui  ad  Reduce learning rate when a metric has stopped improving.

Models often benefit from reducing the learning rate by a factor
of 2-10 once learning stagnates. This callback monitors a
quantity and if no improvement is seen for a 'patience' number
of epochs, the learning rate is reduced.

Example:

```python
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2,
                              patience=5, min_lr=0.001)
model.fit(X_train, Y_train, callbacks=[reduce_lr])
```

Args:
    monitor: quantity to be monitored.
    factor: factor by which the learning rate will be reduced.
      `new_lr = lr * factor`.
    patience: number of epochs with no improvement after which learning rate
      will be reduced.
    verbose: int. 0: quiet, 1: update messages.
    mode: one of `{'auto', 'min', 'max'}`. In `'min'` mode,
      the learning rate will be reduced when the
      quantity monitored has stopped decreasing; in `'max'` mode it will be
      reduced when the quantity monitored has stopped increasing; in
      `'auto'` mode, the direction is automatically inferred from the name
      of the monitored quantity.
    min_delta: threshold for measuring the new optimum, to only focus on
      significant changes.
    cooldown: number of epochs to wait before resuming normal operation
      after lr has been reduced.
    min_lr: lower bound on the learning rate.
c	                 \  > [         T
U ]  5         Xl        US:  a  [        SU 35      eSU	;   a'  U	R	                  S5      n[
        R                  " S5        X l        Xl        X`l	        X0l
        X@l        Xpl        SU l        SU l        SU l        XPl        S U l        U R%                  5         g )Nr   z8ReduceLROnPlateau does not support a factor >= 1.0. Got epsilonzN`epsilon` argument is deprecated and will be removed, use `min_delta` instead.r   )rG  r   r  r   r  r   r   factormin_lrrz  rw  r   cooldowncooldown_counterr{  r  r   r  _reset)r{   r  r  rw  r   r   rz  r  r  r  rh   s             r.   r   ReduceLROnPlateau.__init__  s     	S=((.x1  

9-IOO< "   !			r0   c                 v  ^  T R                   S;  a(  [        R                  " ST R                   5        ST l         T R                   S:X  d   T R                   S:X  a1  ST R                  ;  a!  U 4S jT l        [
        R                  T l        O!U 4S jT l        [
        R                  * T l        ST l        ST l	        g	)
z)Resets wait counter and cooldown counter.r  zBLearning rate reduction mode %s is unknown, fallback to auto mode.r  r  r  c                 J   > [         R                  " XTR                  -
  5      $ rc   )rc  r  rz  abr{   s     r.   r2  *ReduceLROnPlateau._reset.<locals>.<lambda>  s    2771$..6H+Ir0   c                 J   > [         R                  " XTR                  -   5      $ rc   )rc  r  rz  r  s     r.   r2  r    s    2::aT^^9K+Lr0   r   N)
r   r   r   r  r  rc  r  r  r  r{  r   s   `r.   r  ReduceLROnPlateau._reset  s    9922OO)		
 DI99IIE$=IDODILDODI !	r0   c                 $    U R                  5         g rc   )r  r0  s     r.   r    ReduceLROnPlateau.on_train_begin"  s    r0   c           
         U=(       d    0 n[         R                  " U R                  R                  R                  5      US'   UR                  U R                  5      nUcI  [        R                  " SU R                  SR                  [        UR                  5       5      5      5        g U R                  5       (       a  U =R                  S-  sl        SU l        U R                  X0R                   5      (       a  X0l        SU l        g U R                  5       (       Gd*  U =R                  S-  sl        U R                  U R"                  :  a  [         R                  " U R                  R                  R                  5      nU[$        R&                  " U R(                  5      :  a  X@R*                  -  n[-        XPR(                  5      n[         R.                  " U R                  R                  R                  U5        U R0                  S:  a   [2        R4                  " SUS-    SU S35        U R6                  U l        SU l        g g g g )	Nr  zgLearning rate reduction is conditioned on metric `%s` which is not available. Available metrics are: %sr  r   r   r  z.: ReduceLROnPlateau reducing learning rate to r  )r   r  r(   r   r  rR  r  r   r   r/  r  r  in_cooldownr  r{  r  r  rw  rc  r  r  r  r  r  r   r	   rf  r  )r{   r   rM   r  old_lrnew_lrs         r.   r   ReduceLROnPlateau.on_epoch_end%  s   zr&&tzz';';'>'>?T
((4<<(?OODdiik*+	 !!%%*%	w		22#		%%''		Q	99-$..tzz/C/C/F/FGF

4;; 77!'++!5!$V[[!9))$***>*>*A*A6J<<!+$.."*5!8* 544:81!>
 15-$%	 8 . (r0   c                      U R                   S:  $ rK  )r  r   s    r.   r  ReduceLROnPlateau.in_cooldownJ  s    $$q((r0   )r  r  r  r  rz  r  r   r  r  rw  r   r{  )r=  g?
   r   r  g-C6?r   r   rc   )ri   r  r  r	  r
  r   r  r   r   r  r  rY  rZ  s   @r.   r  r    sC    !J %N(#&J) )r0   r  zkeras.callbacks.CSVLoggerc                   N   ^  \ rS rSrSrSU 4S jjrS	S jrS	S jrS	S jrSr	U =r
$ )
	CSVLoggeriN  a  Callback that streams epoch results to a CSV file.

Supports all values that can be represented as a string,
including 1D iterables such as `np.ndarray`.

Example:

```python
csv_logger = CSVLogger('training.log')
model.fit(X_train, Y_train, callbacks=[csv_logger])
```

Args:
    filename: Filename of the CSV file, e.g. `'run/log.csv'`.
    separator: String used to separate elements in the CSV file.
    append: Boolean. True: append if file exists (useful for continuing
        training). False: overwrite existing file.
c                    > X l         [        R                  " U5      U l        X0l        S U l        S U l        SU l        [        TU ]%  5         g r^  )
sepr	   r  filenamer#   r6  r  append_headerrG  r   )r{   r  	separatorr#   rh   s       r.   r   CSVLogger.__init__c  s@     //9	!r0   c                    U R                   (       a  [        R                  R                  R	                  U R
                  5      (       ai  [        R                  R                  R                  U R
                  S5       n[        [        UR                  5       5      5      (       + U l
        S S S 5        SnOSn[        R                  R                  R                  U R
                  U5      U l        g ! , (       d  f       NM= f)Nrr  r  )r#   rB   r  r  r	  r  r(  r>  r   readliner  csv_file)r{   rM   r-  r   s       r.   r   CSVLogger.on_train_beginl  s    ;;uu{{!!$--00UU[[&&t}}c:a-1#ajjl2C-D)DD& ;DD))$--> ;:s   >-C22
D c                 b  ^ ^^	 T=(       d    0 mS m	T R                   c  [        TR                  5       5      T l         SnT R                    H  nUR                  S5      (       d  M  Sn  O   U(       d9  T R                   R                  T R                    Vs/ s H  nSU-   PM
     sn5        T R                  (       d{   " U 4S jS[
        R                  5      nS/T R                   -   n[
        R                  " T R                  XvS9T l        T R                  (       a  T R                  R                  5         [        R                  " SU05      nUR                  U	U4S	 jT R                    5       5        T R                  R                  U5        T R                  R                  5         g s  snf )
Nc                 :   [        U [        R                  5      =(       a    U R                  S:H  n[        U [        5      (       a  U $ [        U [
        R                  R                  5      (       a*  U(       d#  SSR                  [        [        U 5      5       S3$ U $ )Nr   z"[z, z]")
r   rc  r  ndimr  collectionsabcIterabler/  map)rT  is_zero_dim_ndarrays     r.   handle_value,CSVLogger.on_epoch_end.<locals>.handle_valuey  sp    ",Q

";"K!!S!!1koo6677+TYYs3{34C88r0   Fr2   Tc                   0   > \ rS rSr Y R                  rSrg)-CSVLogger.on_epoch_end.<locals>.CustomDialecti  r  N)ri   r  r  r	  r  	delimiterr  r   s   r.   CustomDialectr    s     HH	r0   r  r   )
fieldnamesdialectc              3   V   >#    U  H  oT" TR                  US 5      5      4v   M      g7f)NAN)rR  )rZ   keyr  rM   s     r.   r\   )CSVLogger.on_epoch_end.<locals>.<genexpr>  s'      
@I,txxT234	s   &))r  sortedr  extendr6  csvexcel
DictWriterr  r  writeheaderr  OrderedDictr  writerowr  )
r{   r   rM   val_keys_foundr  rT  r  r  row_dictr  s
   ` `      @r.   r   CSVLogger.on_epoch_endv  sB   zr
	 99tyy{+DI #Nyy>>&))%)N ! "		  dii!@i&1*i!@A{{%		 % "TYY.J..*DK !!'')**GU+;< 
@D		
 	
 	X&) "As   F,c                 F    U R                   R                  5         S U l        g rc   )r  rD  r6  r0  s     r.   r   CSVLogger.on_train_end  s    r0   )r#   r  r  r  r  r  r6  )r  Frc   )ri   r  r  r	  r
  r   r   r   r   r  rY  rZ  s   @r.   r  r  N  s"    &?-^ r0   r  zkeras.callbacks.LambdaCallbackc                   <   ^  \ rS rSrSr      SU 4S jjrSrU =r$ )LambdaCallbacki  a  Callback for creating simple, custom callbacks on-the-fly.

This callback is constructed with anonymous functions that will be called
at the appropriate time (during `Model.{fit | evaluate | predict}`).
Note that the callbacks expects positional arguments, as:

- `on_epoch_begin` and `on_epoch_end` expect two positional arguments:
  `epoch`, `logs`
- `on_batch_begin` and `on_batch_end` expect two positional arguments:
  `batch`, `logs`
- `on_train_begin` and `on_train_end` expect one positional argument:
  `logs`

Args:
    on_epoch_begin: called at the beginning of every epoch.
    on_epoch_end: called at the end of every epoch.
    on_batch_begin: called at the beginning of every batch.
    on_batch_end: called at the end of every batch.
    on_train_begin: called at the beginning of model training.
    on_train_end: called at the end of model training.

Example:

```python
# Print the batch number at the beginning of every batch.
batch_print_callback = LambdaCallback(
    on_batch_begin=lambda batch,logs: print(batch))

# Stream the epoch loss to a file in JSON format. The file content
# is not well-formed JSON but rather has a JSON object per line.
import json
json_log = open('loss_log.json', mode='wt', buffering=1)
json_logging_callback = LambdaCallback(
    on_epoch_end=lambda epoch, logs: json_log.write(
        json.dumps({'epoch': epoch, 'loss': logs['loss']}) + '\n'),
    on_train_end=lambda logs: json_log.close()
)

# Terminate some processes after having finished model training.
processes = ...
cleanup_callback = LambdaCallback(
    on_train_end=lambda logs: [
        p.terminate() for p in processes if p.is_alive()])

model.fit(...,
          callbacks=[batch_print_callback,
                     json_logging_callback,
                     cleanup_callback])
```
c                    > [         TU ]  5         U R                  R                  U5        Ub  Xl        Ub  X l        Ub  X0l        Ub  X@l        Ub  XPl        Ub  X`l	        g g rc   )
rG  r   __dict__r  r   r   r   r   r   r   )	r{   r   r   r   r   r   r   r  rh   s	           r.   r   LambdaCallback.__init__  so     	V$%"0# ,%"0# ,%"0# , $r0   )r   r   r   r   r   r   )NNNNNNrq  rZ  s   @r.   r  r    s'    1j - -r0   r  r  rc   )Fr
  r  r7   r  r  r  r*  r=  r   r  rc  tensorflow.compat.v2rC   v2rB   tf_keras.srcr   tf_keras.src.distributer   r   tf_keras.src.optimizersr   !tf_keras.src.optimizers.schedulesr   tf_keras.src.utilsr   r	   r
   r   tf_keras.src.utils.data_utilsr    tf_keras.src.utils.generic_utilsr   tf_keras.src.utils.mode_keysr   tensorflow.python.platformr   r   tensorflow.python.utilr    tensorflow.python.util.tf_exportr   tensorflow.tools.docsr   r  r  r   r/   r'   rG   rQ   r   r  r"   r\  r$   r    r  r@  deprecated_endpointsrn  rs  r  r  r  TensorBoardVersionSelectorr  r  r  r  r  r0   r.   <module>r     sE  " K   
  	 	 
   ! !   : 9 - D , ' ' , 2 4 1 = . 9 . 	?J 	4.n ,-cD cD .cDL ()xE xE *xEv	 *+.= .= ,.=b ./0X 0 00& -.nLH nL /nLb '($"h $" )$"N /0J4h J4 1J4Z 0R8M?x M? 9M?` ="E!!3*#3 * F*" -.lPH lP /lP^ -.CH C /CL 56D@H D@ 7D@N.
b +3O
+(MDD O
+ 4O
+d 12H) H) 3H)V )*X X +Xv ./K-X K- 0K-oc  Hs   I II