B
    ӻd.                @   s  d Z ddlZddlZddlZddlZddlZddlZddlmZ ddl	m
Z ddl	mZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddlm!Z! ddlm"Z" ddlm#Z# ddlm$Z$ ddl%m&Z& ddl%m'Z( ddl%m)Z) ddl%m*Z* ddl+m,Z, ddl+m-Z- ddl+m.Z. ddl+m/Z/ ddl+m0Z0 ddl1m2Z3 dd l1m4Z4 dd!l5m6Z6 dd"l5m7Z7 dd#l5m8Z8 dd$l9m:Z: dd%l9m;Z; dd&l<m=Z= dd'l<m>Z> dd(l<m?Z? dd)l<m@Z@ dd*lAmBZB dd+lAmCZC dd,lDmEZE dd-lFmGZG dd.lFmHZH dd/lFmIZI dd0lFmJZJ dd1lFmKZK dd2lLmMZN dd3lOmPZP dd4lQmRZS dd5lQmTZU dd6lVmWZX dd7lYmZZZ dd8l[m\Z\ dd9l[m]Z] dd:l^m_Z_ dd;l`maZa yddlbZbW n eck
r   dZbY nX d<d= Zdd>d? Zed@dA Zfe_dBdCG dDdE dEe,jge@jhZidcdGdHZjdddIdJZkdKdL ZldMdN ZmdOdP ZndQdR ZodSdT ZpdUdV ZqdWdX ZrdYdZ Zsd[d\ Ztd]d^ Zud_d` Zvdadb ZwdS )ez*Training-related part of the Keras engine.    N)
directives)
checkpoint)checkpoint_management)dataset_ops)options)collective_all_reduce_strategy)distribution_strategy_context)values)cluster_coordinator)backprop)context)def_function)composite_tensor)errors)errors_impl)
func_graph)ops)sparse_tensor)tensor_shape)backend)	callbacks)optimizer_v1)
optimizers)
base_layer)base_layer_utils)compile_utils)data_adapter)training_utils)loss_scale_optimizer)policy)hdf5_format)save)saving_utils)
json_utils)model_serialization)generic_utils)layer_utils)tf_utils)version_utils)ask_to_proceed_with_overwrite)path_to_string)ModeKeys)	array_ops)math_ops)
sparse_ops)summary_ops_v2)	variables)
tf_logging)trace)	constants)loader_impl)base)py_checkpoint_reader)nest)tf_decorator)keras_export)doc_controlsc                s    fdd}t j |dS )z6Decorator that disallows multi-worker use of `method`.c                s(   |   rtd j | f||S )Nz){} is not supported in multi-worker mode.)_in_multi_worker_mode
ValueErrorformat__name__)selfargskwargs)method Y/var/www/html/venv/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py_method_wrapper^   s    
z-disable_multi_worker.<locals>._method_wrapper)targetZdecorator_func)r8   Zmake_decorator)rB   rE   rC   )rB   rD   disable_multi_worker[   s    rG   c             C   s`   ddl m} ddl m} | tks*| |jkr0|jS | tkr<tS tdd | jD | _| |  | S )z?Inject `Functional` into the hierarchy of this class if needed.r   )
functional)training_v1c             s   s   | ]}t |V  qd S )N)inject_functional_model_class).0r5   rC   rC   rD   	<genexpr>s   s   z0inject_functional_model_class.<locals>.<genexpr>)	tensorflow.python.keras.enginerH   rI   Model
Functionalobjecttuple	__bases____new__)clsrH   rI   rC   rC   rD   rJ   h   s    
rJ   c             C   s0   t | dkp.t | dkr d|kp.d|ko.d|kS )N      outputsinputs)len)r@   rA   rC   rC   rD   is_functional_model_init_params|   s    rZ   zkeras.Modelzkeras.models.Modelc                   s  e Zd ZdZeedejj	Z	 fddZ
ej fddZejdd Z fd	d
Zej fddZejdddZdddZdd Zejdd Zejdd Zedd Zedd Zedd Zedd  Zed!d" Zej d#d" Zd$d% Z!d&d' Z"dd/d0Z#d1d2 Z$d3d4 Z%dd5d6Z&d7d8 Z'd9d: Z(dd;d<Z)d=d> Z*dd?d@Z+ddAdBZ,dCdD Z-ddEdFZ.ddGdHZ/ddIdJZ0edKdL Z1edMdN Z2 fdOdPZ3ddQdRZ4ddSdTZ5ddUdVZ6dWdX Z7dYdZ Z8e9dd[d\Z:d]d^ Z;d_d` Z<dadb Z=eej>dcdd Z?ededf Z@edgdh ZAddidjZBedkdl ZCddmdnZDejdodp ZEdqdr ZFdsdt ZGdudv ZHdwdx ZIdydz ZJdd{d|ZKed}d~ ZLd fdd	ZMdd ZNdddZOdd ZPdd ZQedd ZR  ZSS )rN   al	  `Model` groups layers into an object with training and inference features.

  Args:
      inputs: The input(s) of the model: a `keras.Input` object or list of
          `keras.Input` objects.
      outputs: The output(s) of the model. See Functional API example below.
      name: String, the name of the model.

  There are two ways to instantiate a `Model`:

  1 - With the "Functional API", where you start from `Input`,
  you chain layer calls to specify the model's forward pass,
  and finally you create your model from inputs and outputs:

  ```python
  import tensorflow as tf

  inputs = tf.keras.Input(shape=(3,))
  x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
  outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)
  model = tf.keras.Model(inputs=inputs, outputs=outputs)
  ```

  Note: Only dicts, lists, and tuples of input tensors are supported. Nested
  inputs are not supported (e.g. lists of list or dicts of dict).

  2 - By subclassing the `Model` class: in that case, you should define your
  layers in `__init__` and you should implement the model's forward pass
  in `call`.

  ```python
  import tensorflow as tf

  class MyModel(tf.keras.Model):

    def __init__(self):
      super(MyModel, self).__init__()
      self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
      self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)

    def call(self, inputs):
      x = self.dense1(inputs)
      return self.dense2(x)

  model = MyModel()
  ```

  If you subclass `Model`, you can optionally have
  a `training` argument (boolean) in `call`, which you can use to specify
  a different behavior in training and inference:

  ```python
  import tensorflow as tf

  class MyModel(tf.keras.Model):

    def __init__(self):
      super(MyModel, self).__init__()
      self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
      self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
      self.dropout = tf.keras.layers.Dropout(0.5)

    def call(self, inputs, training=False):
      x = self.dense1(inputs)
      if training:
        x = self.dropout(x, training=training)
      return self.dense2(x)

  model = MyModel()
  ```

  Once the model is created, you can config the model with losses and metrics
  with `model.compile()`, train the model with `model.fit()`, or use the model
  to do prediction with `model.predict()`.
  )_train_counter_test_counter_predict_counter_steps_per_executionc                sN   t ||r2| tkr2ddlm} |j|ddi|S tt| j| f||S d S )Nr   )rH   	skip_initT)rZ   rN   rM   rH   rO   superrS   )rT   r@   rA   rH   )	__class__rC   rD   rS      s    zModel.__new__c       	   
      s  d| _ ddlm} t| rt| |jsdddddg fd	d
 D } fdd
 D }t| j |jj| f|| g }d}x0| jj	D ]$}t
||jrd}q|r|| qW |rx2|D ]}|j| f|| qW n|rtd|d S t dddddddh tt| jf   d| _d | _d | _d | _d | _d| _d | _d | _d | _d| _| dd | dd  t rt | _ nd | _ d | _!d | _"| #  d | _$d | _%t&j't()| d| _*d | _+| ,  d| _-d S )NTr   )rH   rX   rW   nameZ	trainabler_   c                s   i | ]}|kr | |qS rC   rC   )rK   k)rA   supported_kwargsrC   rD   
<dictcomp>   s    z"Model.__init__.<locals>.<dictcomp>c                s   i | ]}|kr | |qS rC   rC   )rK   rc   )rA   rd   rC   rD   re      s    Fz4The following keyword arguments aren't supported: {}dtypedynamicZautocast_is_compiled	optimizer)root).Z_is_model_for_instrumentationrM   rH   rZ   
isinstancerO   rJ   ra   __init__rR   
issubclassappend	TypeErrorr=   r%   Zvalidate_kwargsr`   rN   _is_graph_networkrX   rW   input_namesoutput_namesstop_traininghistorycompiled_losscompiled_metricsZ _compute_output_and_mask_jointlyZ_maybe_create_attribute
ds_contexthas_strategyget_strategy_distribution_strategy_cluster_coordinator_run_eagerly_reset_compile_cache_training_state_saved_model_inputs_spectrackable_utilsZ
Checkpointweakrefref_checkpointr^   _init_batch_counters_base_model_initialized)	r?   r@   rA   rH   Zmodel_kwargsZother_kwargsZclz_to_initZfound_functional_classZclz)ra   )rA   rd   rD   rl      sh    



zModel.__init__c             C   sB   t jj}t jdd|d| _t jdd|d| _t jdd|d| _d S )Nr   int64)rf   aggregation)r0   VariableAggregationV2ONLY_FIRST_REPLICAVariabler[   r\   r]   )r?   ZaggrC   rC   rD   r   =  s
    zModel._init_batch_countersc                sx   t | dds"tt| || d S tdd t|D rby
| j W n tk
r`   t	dY nX tt| || d S )NZ_self_setattr_trackingTc             s   s*   | ]"}t |tjtjfp t|V  qd S )N)rk   r   Layerr0   r   r   Zhas_weights)rK   vrC   rC   rD   rL   M  s   z$Model.__setattr__.<locals>.<genexpr>zsIt looks like you are subclassing `Model` and you forgot to call `super().__init__()`. Always start with this line.)
getattrr`   rN   __setattr__allr7   flattenr   AttributeErrorRuntimeError)r?   rb   value)ra   rC   rD   r   G  s    
zModel.__setattr__c       	   
      s  | j rtt| | dS |dkr*tdtttjt	f}t
||sTtdt||r| jst rvtd}nt }| 0 t
|trtdd |D rt|}t
|trdd |D }n(t
|t	rd	d
 | D }n
t|}i }| j}|j}t|dkrf|jr,|dt|j  }n|dd }xB|D ]"}|dkrVd|d< ntdq>W nt|dk r|tdy| j|f| W n$ tjt fk
r   tdY nX W dQ R X tt| | dS )aO  Builds the model based on input shapes received.

    This is to be used for subclassed models, which do not know at instantiation
    time what their inputs look like.

    This method only exists for users who want to call `model.build()` in a
    standalone way (as a substitute for calling the model on real data to
    build it). It will never be called by the framework (and thus it will
    never throw unexpected errors in an unrelated workflow).

    Args:
     input_shape: Single tuple, TensorShape, or list/dict of shapes, where
         shapes are tuples, integers, or TensorShapes.

    Raises:
      ValueError:
        1. In case of invalid user-provided data (not of type tuple,
           list, TensorShape, or dict).
        2. If the model requires call arguments that are agnostic
           to the input shapes (positional or kwarg in call signature).
        3. If not all layers were properly built.
        4. If float type inputs are not supported within the layers.

      In each of these cases, the user should build their model by calling it
      on real tensor data.
    NzKInput shape must be defined when calling build on a model subclass network.zSpecified input shape is not one of the valid types. Please specify a batch input shape of type tuple or list of input shapes. User provided input type: {}Zbuild_graphc             s   s    | ]}|d kpt |tV  qd S )N)rk   int)rK   drC   rC   rD   rL     s    zModel.build.<locals>.<genexpr>c             S   s   g | ]}t |qS rC   )r    generate_placeholders_from_shape)rK   shaperC   rC   rD   
<listcomp>  s   zModel.build.<locals>.<listcomp>c             S   s   i | ]\}}t ||qS rC   )r   r   )rK   rc   r   rC   rC   rD   re     s   zModel.build.<locals>.<dictcomp>rU   trainingFa  Currently, you cannot build your model if it has positional or keyword arguments that are not inputs to the model, but are required for its `call` method. Instead, in order to instantiate and build your model, `call` your model on real tensor data with all expected call arguments.zWYou can only call `build` on a model if its `call` method accepts an `inputs` argument.zYou cannot build your model by calling `build` if your layers do not support float type inputs. Instead, in order to instantiate and build your model, `call` your model on real tensor data (of the correct dtype).)!rp   r`   rN   buildr<   rQ   listr   ZTensorShapedictrk   r=   typerX   r   executing_eagerlyr   Z	FuncGraphr   Z	get_graphZ
as_defaultr   itemsr   r   _call_full_argspecr@   rY   defaultscallr   ZInvalidArgumentErrorro   )	r?   Zinput_shapeZvalid_typesgraphxrA   Zcall_signature	call_argsarg)ra   rC   rD   r   Y  sV    








zModel.buildNc             C   s   t ddS )a~  Calls the model on new inputs.

    In this case `call` just reapplies
    all ops in the graph to the new inputs
    (e.g. build a new computational graph from the provided inputs).

    Note: This method should not be called directly. It is only meant to be
    overridden when subclassing `tf.keras.Model`.
    To call a model on an input, always use the `__call__` method,
    i.e. `model(inputs)`, which relies on the underlying `call` method.

    Args:
        inputs: Input tensor, or dict/list/tuple of input tensors.
        training: Boolean or boolean scalar tensor, indicating whether to run
          the `Network` in training mode or inference mode.
        mask: A mask or list of masks. A mask can be
            either a tensor or None (no mask).

    Returns:
        A tensor if there is a single output, or
        a list of tensors if there are more than one outputs.
    zIWhen subclassing the `Model` class, you should implement a `call` method.N)NotImplementedError)r?   rX   r   maskrC   rC   rD   r     s    z
Model.callrmspropc       
   	   K   s   | j   d|kr,td |s,|d}|dd}	| j||f| || _| || _t	j
||| jd| _t	j||| j|	d| _| |pd |   d| _|pi | _W d	Q R X d	S )
aE  Configures the model for training.

    Args:
        optimizer: String (name of optimizer) or optimizer instance. See
          `tf.keras.optimizers`.
        loss: String (name of objective function), objective function or
          `tf.keras.losses.Loss` instance. See `tf.keras.losses`. An objective
          function is any callable with the signature `loss = fn(y_true,
          y_pred)`, where y_true = ground truth values with shape =
          `[batch_size, d0, .. dN]`, except sparse loss functions such as sparse
          categorical crossentropy where shape = `[batch_size, d0, .. dN-1]`.
          y_pred = predicted values with shape = `[batch_size, d0, .. dN]`. It
          returns a weighted loss float tensor. If a custom `Loss` instance is
          used and reduction is set to `None`, return value has the shape
          `[batch_size, d0, .. dN-1]` i.e. per-sample or per-timestep loss
          values; otherwise, it is a scalar. If the model has multiple outputs,
          you can use a different loss on each output by passing a dictionary
          or a list of losses. The loss value that will be minimized by the
          model will then be the sum of all individual losses, unless
          `loss_weights` is specified.
        metrics: List of metrics to be evaluated by the model during training
          and testing. Each of this can be a string (name of a built-in
          function), function or a `tf.keras.metrics.Metric` instance. See
          `tf.keras.metrics`. Typically you will use `metrics=['accuracy']`. A
          function is any callable with the signature `result = fn(y_true,
          y_pred)`. To specify different metrics for different outputs of a
          multi-output model, you could also pass a dictionary, such as
          `metrics={'output_a': 'accuracy', 'output_b': ['accuracy', 'mse']}`.
          You can also pass a list to specify a metric or a list of metrics
          for each output, such as `metrics=[['accuracy'], ['accuracy', 'mse']]`
          or `metrics=['accuracy', ['accuracy', 'mse']]`. When you pass the
          strings 'accuracy' or 'acc', we convert this to one of
          `tf.keras.metrics.BinaryAccuracy`,
          `tf.keras.metrics.CategoricalAccuracy`,
          `tf.keras.metrics.SparseCategoricalAccuracy` based on the loss
          function used and the model output shape. We do a similar
          conversion for the strings 'crossentropy' and 'ce' as well.
        loss_weights: Optional list or dictionary specifying scalar coefficients
          (Python floats) to weight the loss contributions of different model
          outputs. The loss value that will be minimized by the model will then
          be the *weighted sum* of all individual losses, weighted by the
          `loss_weights` coefficients.
            If a list, it is expected to have a 1:1 mapping to the model's
              outputs. If a dict, it is expected to map output names (strings)
              to scalar coefficients.
        weighted_metrics: List of metrics to be evaluated and weighted by
          `sample_weight` or `class_weight` during training and testing.
        run_eagerly: Bool. Defaults to `False`. If `True`, this `Model`'s
          logic will not be wrapped in a `tf.function`. Recommended to leave
          this as `None` unless your `Model` cannot be run inside a
          `tf.function`. `run_eagerly=True` is not supported when using
          `tf.distribute.experimental.ParameterServerStrategy`.
        steps_per_execution: Int. Defaults to 1. The number of batches to
          run during each `tf.function` call. Running multiple batches
          inside a single `tf.function` call can greatly improve performance
          on TPUs or small models with a large Python overhead.
          At most, one full epoch will be run each
          execution. If a number larger than the size of the epoch is passed,
          the execution will be truncated to the size of the epoch.
          Note that if `steps_per_execution` is set to `N`,
          `Callback.on_batch_begin` and `Callback.on_batch_end` methods
          will only be called every `N` batches
          (i.e. before/after each `tf.function` execution).
        **kwargs: Arguments supported for backwards compatibility only.

    Raises:
        ValueError: In case of invalid arguments for
            `optimizer`, `loss` or `metrics`.
    Z experimental_steps_per_executionzThe argument `steps_per_execution` is no longer experimental. Pass `steps_per_execution` instead of `experimental_steps_per_execution`.from_serializedF)rr   )rr   r   rV   TN)distribute_strategyscopeloggingwarningpop_validate_compiler|   _get_optimizerri   r   ZLossesContainerrr   ru   ZMetricsContainerrv   _configure_steps_per_executionr}   rh   loss)
r?   ri   r   metricsloss_weightsweighted_metricsrun_eagerlysteps_per_executionrA   r   rC   rC   rD   compile  s$    N


zModel.compilec                sF   t | jtjr| jj n| jjdkr*d nd  fdd}t||S )z7Wraps `optimizer` in `LossScaleOptimizer` if necessary.Zmixed_float16rg   Nc                sB   t | }  d k	r>t| tjs> dkr2t| } nt|  } | S )Nrg   )r   getrk   lsoZLossScaleOptimizerZLossScaleOptimizerV1)opt)
loss_scalerC   rD   _get_single_optimizerT  s    
z3Model._get_optimizer.<locals>._get_single_optimizer)rk   Z_dtype_policyr   ZPolicyV1r   rb   r7   map_structure)r?   ri   r   rC   )r   rD   r   G  s    

zModel._get_optimizerc             C   s&   d | _ d | _d | _d | _|  | _d S )N)train_functiontest_functionpredict_functiontrain_tf_functionZ_get_trainable_stateZ_compiled_trainable_state)r?   rC   rC   rD   r}   `  s
    zModel._reset_compile_cachec             C   s   t j|dt jjd| _d S )Nr   )rf   r   )r0   r   r   r   r^   )r?   r   rC   rC   rD   r   n  s    z$Model._configure_steps_per_executionc             C   s   dS )NFrC   )r?   rC   rC   rD   _should_compute_masku  s    zModel._should_compute_maskc             C   sX   g }| j r6| jdk	r || jj7 }| jdk	r6|| jj7 }x|  D ]}||j q@W |S )a  Returns the model's metrics added using `compile`, `add_metric` APIs.

    Note: Metrics passed to `compile()` are available only after a `keras.Model`
    has been trained/evaluated on actual data.

    Examples:

    >>> inputs = tf.keras.layers.Input(shape=(3,))
    >>> outputs = tf.keras.layers.Dense(2)(inputs)
    >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
    >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
    >>> [m.name for m in model.metrics]
    []

    >>> x = np.random.random((2, 3))
    >>> y = np.random.randint(0, 2, (2, 2))
    >>> model.fit(x, y)
    >>> [m.name for m in model.metrics]
    ['loss', 'mae']

    >>> inputs = tf.keras.layers.Input(shape=(3,))
    >>> d = tf.keras.layers.Dense(2, name='out')
    >>> output_1 = d(inputs)
    >>> output_2 = d(inputs)
    >>> model = tf.keras.models.Model(
    ...    inputs=inputs, outputs=[output_1, output_2])
    >>> model.add_metric(
    ...    tf.reduce_sum(output_2), name='mean', aggregation='mean')
    >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
    >>> model.fit(x, (y, y))
    >>> [m.name for m in model.metrics]
    ['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
    'out_1_acc', 'mean']

    N)rh   ru   r   rv   _flatten_layersextend_metrics)r?   r   lrC   rC   rD   r   y  s    %

zModel.metricsc             C   s   dd | j D S )aH  Returns the model's display labels for all outputs.

    Note: `metrics_names` are available only after a `keras.Model` has been
    trained/evaluated on actual data.

    Examples:

    >>> inputs = tf.keras.layers.Input(shape=(3,))
    >>> outputs = tf.keras.layers.Dense(2)(inputs)
    >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
    >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
    >>> model.metrics_names
    []

    >>> x = np.random.random((2, 3))
    >>> y = np.random.randint(0, 2, (2, 2))
    >>> model.fit(x, y)
    >>> model.metrics_names
    ['loss', 'mae']

    >>> inputs = tf.keras.layers.Input(shape=(3,))
    >>> d = tf.keras.layers.Dense(2, name='out')
    >>> output_1 = d(inputs)
    >>> output_2 = d(inputs)
    >>> model = tf.keras.models.Model(
    ...    inputs=inputs, outputs=[output_1, output_2])
    >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
    >>> model.fit(x, (y, y))
    >>> model.metrics_names
    ['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
    'out_1_acc']

    c             S   s   g | ]
}|j qS rC   )rb   )rK   mrC   rC   rD   r     s    z'Model.metrics_names.<locals>.<listcomp>)r   )r?   rC   rC   rD   metrics_names  s    &zModel.metrics_namesc             C   s   | j pt S )z:The `tf.distribute.Strategy` this model was created under.)rz   rw   ry   )r?   rC   rC   rD   r     s    zModel.distribute_strategyc             C   sJ   | j r| jdkrtd| jr,| jr,td| j pH| jpHt oH| jdkS )a  Settable attribute indicating whether the model should run eagerly.

    Running eagerly means that your model will be run step by step,
    like Python code. Your model might run slower, but it should become easier
    for you to debug it by stepping into individual layer calls.

    By default, we will attempt to compile your model to a static graph to
    deliver the best execution performance.

    Returns:
      Boolean, whether the model should run eagerly.
    FzYour model contains layers that can only be successfully run in eager execution (layers constructed with `dynamic=True`). You cannot set `run_eagerly=False`.zRWhen using `Model` with `ParameterServerStrategy`, `run_eagerly` is not supported.N)rg   r|   r<   r{   r   Zfunctions_run_eagerly)r?   rC   rC   rD   r     s    zModel.run_eagerlyc             C   s
   || _ d S )N)r|   )r?   r   rC   rC   rD   r     s    c          	   C   s   t |}t |\}}}t &}| |dd}| j|||| jd}W dQ R X | jj|| j	|d | j
||| i }x6| jD ],}	|	 }
t|
tr||
 q~|
||	j< q~W |S )a  The logic for one training step.

    This method can be overridden to support custom training logic.
    For concrete examples of how to override this method see
    [Customizing what happends in fit](https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit).
    This method is called by `Model.make_train_function`.

    This method should contain the mathematical logic for one step of training.
    This typically includes the forward pass, loss calculation, backpropagation,
    and metric updates.

    Configuration details for *how* this logic is run (e.g. `tf.function` and
    `tf.distribute.Strategy` settings), should be left to
    `Model.make_train_function`, which can also be overridden.

    Args:
      data: A nested structure of `Tensor`s.

    Returns:
      A `dict` containing values that will be passed to
      `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the
      values of the `Model`'s metrics are returned. Example:
      `{'loss': 0.2, 'accuracy': 0.7}`.

    T)r   )regularization_lossesN)tape)r   	expand_1dunpack_x_y_sample_weightr   ZGradientTaperu   lossesri   Zminimizetrainable_variablesrv   update_stater   resultrk   r   updaterb   )r?   datar   ysample_weightr   y_predr   return_metricsmetricr   rC   rC   rD   
train_step  s    


zModel.train_stepc                s    j dk	r j S  fdd j  dkr> fddn fdd jsftjdd	 _ _  jr fd
d _  j S )a  Creates a function that executes one step of training.

    This method can be overridden to support custom training logic.
    This method is called by `Model.fit` and `Model.train_on_batch`.

    Typically, this method directly controls `tf.function` and
    `tf.distribute.Strategy` settings, and delegates the actual training
    logic to `Model.train_step`.

    This function is cached the first time `Model.fit` or
    `Model.train_on_batch` is called. The cache is cleared whenever
    `Model.compile` is called.

    Returns:
      Function. The function created by this method should accept a
      `tf.data.Iterator`, and return a `dict` containing values that will
      be passed to `tf.keras.Callbacks.on_train_batch_end`, such as
      `{'loss': 0.2, 'accuracy': 0.7}`.
    Nc                sH    fdd}t |} jj||fd}t|jdd}t| jd |S )zRuns a single training step.c          	      s4     | }tt|  jd W d Q R X |S )NrV   )r   r   control_dependencies_minimum_control_depsr[   
assign_add)r   rW   )modelrC   rD   run_stepG  s    
zBModel.make_train_function.<locals>.step_function.<locals>.run_step)r@   first)	reduction)step)nextr   runreduce_per_replicawrite_scalar_summariesr[   )r   iteratorr   r   rW   )r?   )r   rD   step_functionD  s    z0Model.make_train_function.<locals>.step_functionrV   c                s
    | S )z(Runs a training execution with one step.rC   )r   )r?   r   rC   rD   r   W  s    z1Model.make_train_function.<locals>.train_functionc                s$   xt  jD ]} | }qW |S )z.Runs a training execution with multiple steps.)r-   ranger^   )r   _rW   )r?   r   rC   rD   r   ]  s    T)experimental_relax_shapesc                s    j j| fdS )N)r@   )r{   schedule)r   )r?   r   rC   rD   <lambda>k  s   z+Model.make_train_function.<locals>.<lambda>)	r   r^   numpyitemr   r   functionr   r{   )r?   rC   )r?   r   r   rD   make_train_function-  s    

zModel.make_train_functionrV   auto        Tr   
   Fc       !      C   s   t dd |   | d td |dkr@| jjr<d}nd}|rbtj|||f|d\\}}}}|rvt	|\}}}| jjrt
| j| _| j ^ t| F tj||||||||	|
|||| | jd}t|tjstj|d|d	k| |||jd
}d| _|  | _| jd	 |  d}| ||_d}x| D ]\}}|   | | |!  xz|" D ]n}t#j$d|||ddN |%| | |}|j&rt'(  |}||j) }|*|| | jrP W dQ R X qnW W dQ R X t+,|}|dkrt-dt..|}|r| /||rt0| dddkrbtj||||pH||d	d|||| | jd| _1| j2||||pt||||||ddd} dd | 3 D } |4|  |5|| |}| jr>P q>W t0| dddk	r| `1|j6|d | j7S Q R X W dQ R X dS )a1  Trains the model for a fixed number of epochs (iterations on a dataset).

    Args:
        x: Input data. It could be:
          - A Numpy array (or array-like), or a list of arrays
            (in case the model has multiple inputs).
          - A TensorFlow tensor, or a list of tensors
            (in case the model has multiple inputs).
          - A dict mapping input names to the corresponding array/tensors,
            if the model has named inputs.
          - A `tf.data` dataset. Should return a tuple
            of either `(inputs, targets)` or
            `(inputs, targets, sample_weights)`.
          - A generator or `keras.utils.Sequence` returning `(inputs, targets)`
            or `(inputs, targets, sample_weights)`.
          - A `tf.keras.utils.experimental.DatasetCreator`, which wraps a
            callable that takes a single argument of type
            `tf.distribute.InputContext`, and returns a `tf.data.Dataset`.
            `DatasetCreator` should be used when users prefer to specify the
            per-replica batching and sharding logic for the `Dataset`.
            See `tf.keras.utils.experimental.DatasetCreator` doc for more
            information.
          A more detailed description of unpacking behavior for iterator types
          (Dataset, generator, Sequence) is given below. If using
          `tf.distribute.experimental.ParameterServerStrategy`, only
          `DatasetCreator` type is supported for `x`.
        y: Target data. Like the input data `x`,
          it could be either Numpy array(s) or TensorFlow tensor(s).
          It should be consistent with `x` (you cannot have Numpy inputs and
          tensor targets, or inversely). If `x` is a dataset, generator,
          or `keras.utils.Sequence` instance, `y` should
          not be specified (since targets will be obtained from `x`).
        batch_size: Integer or `None`.
            Number of samples per gradient update.
            If unspecified, `batch_size` will default to 32.
            Do not specify the `batch_size` if your data is in the
            form of datasets, generators, or `keras.utils.Sequence` instances
            (since they generate batches).
        epochs: Integer. Number of epochs to train the model.
            An epoch is an iteration over the entire `x` and `y`
            data provided.
            Note that in conjunction with `initial_epoch`,
            `epochs` is to be understood as "final epoch".
            The model is not trained for a number of iterations
            given by `epochs`, but merely until the epoch
            of index `epochs` is reached.
        verbose: 'auto', 0, 1, or 2. Verbosity mode.
            0 = silent, 1 = progress bar, 2 = one line per epoch.
            'auto' defaults to 1 for most cases, but 2 when used with
            `ParameterServerStrategy`. Note that the progress bar is not
            particularly useful when logged to a file, so verbose=2 is
            recommended when not running interactively (eg, in a production
            environment).
        callbacks: List of `keras.callbacks.Callback` instances.
            List of callbacks to apply during training.
            See `tf.keras.callbacks`. Note `tf.keras.callbacks.ProgbarLogger`
            and `tf.keras.callbacks.History` callbacks are created automatically
            and need not be passed into `model.fit`.
            `tf.keras.callbacks.ProgbarLogger` is created or not based on
            `verbose` argument to `model.fit`.
            Callbacks with batch-level calls are currently unsupported with
            `tf.distribute.experimental.ParameterServerStrategy`, and users are
            advised to implement epoch-level calls instead with an appropriate
            `steps_per_epoch` value.
        validation_split: Float between 0 and 1.
            Fraction of the training data to be used as validation data.
            The model will set apart this fraction of the training data,
            will not train on it, and will evaluate
            the loss and any model metrics
            on this data at the end of each epoch.
            The validation data is selected from the last samples
            in the `x` and `y` data provided, before shuffling. This argument is
            not supported when `x` is a dataset, generator or
           `keras.utils.Sequence` instance.
            `validation_split` is not yet supported with
            `tf.distribute.experimental.ParameterServerStrategy`.
        validation_data: Data on which to evaluate
            the loss and any model metrics at the end of each epoch.
            The model will not be trained on this data. Thus, note the fact
            that the validation loss of data provided using `validation_split`
            or `validation_data` is not affected by regularization layers like
            noise and dropout.
            `validation_data` will override `validation_split`.
            `validation_data` could be:
              - A tuple `(x_val, y_val)` of Numpy arrays or tensors.
              - A tuple `(x_val, y_val, val_sample_weights)` of NumPy arrays.
              - A `tf.data.Dataset`.
              - A Python generator or `keras.utils.Sequence` returning
              `(inputs, targets)` or `(inputs, targets, sample_weights)`.
            `validation_data` is not yet supported with
            `tf.distribute.experimental.ParameterServerStrategy`.
        shuffle: Boolean (whether to shuffle the training data
            before each epoch) or str (for 'batch'). This argument is ignored
            when `x` is a generator or an object of tf.data.Dataset.
            'batch' is a special option for dealing
            with the limitations of HDF5 data; it shuffles in batch-sized
            chunks. Has no effect when `steps_per_epoch` is not `None`.
        class_weight: Optional dictionary mapping class indices (integers)
            to a weight (float) value, used for weighting the loss function
            (during training only).
            This can be useful to tell the model to
            "pay more attention" to samples from
            an under-represented class.
        sample_weight: Optional Numpy array of weights for
            the training samples, used for weighting the loss function
            (during training only). You can either pass a flat (1D)
            Numpy array with the same length as the input samples
            (1:1 mapping between weights and samples),
            or in the case of temporal data,
            you can pass a 2D array with shape
            `(samples, sequence_length)`,
            to apply a different weight to every timestep of every sample. This
            argument is not supported when `x` is a dataset, generator, or
           `keras.utils.Sequence` instance, instead provide the sample_weights
            as the third element of `x`.
        initial_epoch: Integer.
            Epoch at which to start training
            (useful for resuming a previous training run).
        steps_per_epoch: Integer or `None`.
            Total number of steps (batches of samples)
            before declaring one epoch finished and starting the
            next epoch. When training with input tensors such as
            TensorFlow data tensors, the default `None` is equal to
            the number of samples in your dataset divided by
            the batch size, or 1 if that cannot be determined. If x is a
            `tf.data` dataset, and 'steps_per_epoch'
            is None, the epoch will run until the input dataset is exhausted.
            When passing an infinitely repeating dataset, you must specify the
            `steps_per_epoch` argument. If `steps_per_epoch=-1` the training
            will run indefinitely with an infinitely repeating dataset.
            This argument is not supported with array inputs.
            When using `tf.distribute.experimental.ParameterServerStrategy`:
              * `steps_per_epoch=None` is not supported.
        validation_steps: Only relevant if `validation_data` is provided and
            is a `tf.data` dataset. Total number of steps (batches of
            samples) to draw before stopping when performing validation
            at the end of every epoch. If 'validation_steps' is None, validation
            will run until the `validation_data` dataset is exhausted. In the
            case of an infinitely repeated dataset, it will run into an
            infinite loop. If 'validation_steps' is specified and only part of
            the dataset will be consumed, the evaluation will start from the
            beginning of the dataset at each epoch. This ensures that the same
            validation samples are used every time.
        validation_batch_size: Integer or `None`.
            Number of samples per validation batch.
            If unspecified, will default to `batch_size`.
            Do not specify the `validation_batch_size` if your data is in the
            form of datasets, generators, or `keras.utils.Sequence` instances
            (since they generate batches).
        validation_freq: Only relevant if validation data is provided. Integer
            or `collections.abc.Container` instance (e.g. list, tuple, etc.).
            If an integer, specifies how many training epochs to run before a
            new validation run is performed, e.g. `validation_freq=2` runs
            validation every 2 epochs. If a Container, specifies the epochs on
            which to run validation, e.g. `validation_freq=[1, 2, 10]` runs
            validation at the end of the 1st, 2nd, and 10th epochs.
        max_queue_size: Integer. Used for generator or `keras.utils.Sequence`
            input only. Maximum size for the generator queue.
            If unspecified, `max_queue_size` will default to 10.
        workers: Integer. Used for generator or `keras.utils.Sequence` input
            only. Maximum number of processes to spin up
            when using process-based threading. If unspecified, `workers`
            will default to 1.
        use_multiprocessing: Boolean. Used for generator or
            `keras.utils.Sequence` input only. If `True`, use process-based
            threading. If unspecified, `use_multiprocessing` will default to
            `False`. Note that because this implementation relies on
            multiprocessing, you should not pass non-picklable arguments to
            the generator as they can't be passed easily to children processes.

    Unpacking behavior for iterator-like inputs:
        A common pattern is to pass a tf.data.Dataset, generator, or
      tf.keras.utils.Sequence to the `x` argument of fit, which will in fact
      yield not only features (x) but optionally targets (y) and sample weights.
      Keras requires that the output of such iterator-likes be unambiguous. The
      iterator should return a tuple of length 1, 2, or 3, where the optional
      second and third elements will be used for y and sample_weight
      respectively. Any other type provided will be wrapped in a length one
      tuple, effectively treating everything as 'x'. When yielding dicts, they
      should still adhere to the top-level tuple structure.
      e.g. `({"x0": x0, "x1": x1}, y)`. Keras will not attempt to separate
      features, targets, and weights from the keys of a single dict.
        A notable unsupported data type is the namedtuple. The reason is that
      it behaves like both an ordered datatype (tuple) and a mapping
      datatype (dict). So given a namedtuple of the form:
          `namedtuple("example_tuple", ["y", "x"])`
      it is ambiguous whether to reverse the order of the elements when
      interpreting the value. Even worse is a tuple of the form:
          `namedtuple("other_tuple", ["x", "y", "z"])`
      where it is unclear if the tuple was intended to be unpacked into x, y,
      and sample_weight or passed through as a single element to `x`. As a
      result the data processing code will simply raise a ValueError if it
      encounters a namedtuple. (Along with instructions to remedy the issue.)

    Returns:
        A `History` object. Its `History.history` attribute is
        a record of training loss values and metrics values
        at successive epochs, as well as validation loss values
        and validation metrics values (if applicable).

    Raises:
        RuntimeError: 1. If the model was never compiled or,
        2. If `model.fit` is  wrapped in `tf.function`.

        ValueError: In case of mismatch between the provided input data
            and what the model expects or when the input data is empty.
    rN   fitr   rU   rV   )validation_split)r   r   r   
batch_sizesteps_per_epochinitial_epochepochsshuffleclass_weightmax_queue_sizeworkersuse_multiprocessingr   r   Tr   )add_historyadd_progbarr   verboser   stepsFNtrain)Z	epoch_numstep_numr   _rz,Expect x to be a non-empty array or dataset._eval_data_handler)r   r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r  r   r   r   r   return_dict_use_cached_eval_datasetc             S   s   i | ]\}}|d | qS )Zval_rC   )rK   rb   valrC   rC   rD   re     s    zModel.fit.<locals>.<dictcomp>)logs)8r(   disallow_legacy_graph_assert_compile_was_called_check_call_args_disallow_inside_tf_functionr   _should_use_with_coordinatorr   Ztrain_validation_splitr   r
   ClusterCoordinatorr{   r   r   RespectCompiledTrainableStateget_data_handlerr^   rk   callbacks_moduleCallbackListinferred_stepsrs   r   r   r[   assignZon_train_begin#_maybe_load_initial_epoch_from_ckptZ_initial_epochenumerate_epochsreset_metricsZon_epoch_begincatch_stop_iterationr  r2   TraceZon_train_batch_beginshould_syncr   
async_waitstep_incrementZon_train_batch_endr'   sync_to_numpy_or_python_typer<   copy_should_evalr   r  evaluater   r   Zon_epoch_endZon_train_endrt   )!r?   r   r   r   r   r  r   r   validation_datar   r   r   r   r   validation_stepsZvalidation_batch_sizevalidation_freqr   r   r   Zval_xZval_yZval_sample_weightdata_handlerZtraining_logsr  epochr   r   tmp_logsend_stepZ
epoch_logsZval_logsrC   rC   rD   r   p  s     e














z	Model.fitc       	      C   s   t |}t |\}}}| |dd}| j|||| jd | j||| i }x6| jD ],}| }t	|t
rx|| qV|||j< qVW |S )a  The logic for one evaluation step.

    This method can be overridden to support custom evaluation logic.
    This method is called by `Model.make_test_function`.

    This function should contain the mathematical logic for one step of
    evaluation.
    This typically includes the forward pass, loss calculation, and metrics
    updates.

    Configuration details for *how* this logic is run (e.g. `tf.function` and
    `tf.distribute.Strategy` settings), should be left to
    `Model.make_test_function`, which can also be overridden.

    Args:
      data: A nested structure of `Tensor`s.

    Returns:
      A `dict` containing values that will be passed to
      `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the
      values of the `Model`'s metrics are returned.
    F)r   )r   )r   r   r   ru   r   rv   r   r   r   rk   r   r   rb   )	r?   r   r   r   r   r   r   r   r   rC   rC   rD   	test_step  s    

zModel.test_stepc                s    j dk	r j S  fdd j  dkr> fddn fdd js`tjdd	 _  jr| fd
d _  j S )a  Creates a function that executes one step of evaluation.

    This method can be overridden to support custom evaluation logic.
    This method is called by `Model.evaluate` and `Model.test_on_batch`.

    Typically, this method directly controls `tf.function` and
    `tf.distribute.Strategy` settings, and delegates the actual evaluation
    logic to `Model.test_step`.

    This function is cached the first time `Model.evaluate` or
    `Model.test_on_batch` is called. The cache is cleared whenever
    `Model.compile` is called.

    Returns:
      Function. The function created by this method should accept a
      `tf.data.Iterator`, and return a `dict` containing values that will
      be passed to `tf.keras.Callbacks.on_test_batch_end`.
    Nc                s:    fdd}t |} jj||fd}t|jdd}|S )zRuns a single evaluation step.c          	      s4     | }tt|  jd W d Q R X |S )NrV   )r+  r   r   r   r\   r   )r   rW   )r   rC   rD   r     s    
zAModel.make_test_function.<locals>.step_function.<locals>.run_step)r@   r   )r   )r   r   r   r   )r   r   r   r   rW   )r?   )r   rD   r     s    z/Model.make_test_function.<locals>.step_functionrV   c                s
    | S )z+Runs an evaluation execution with one step.rC   )r   )r?   r   rC   rD   r   -  s    z/Model.make_test_function.<locals>.test_functionc                s$   xt  jD ]} | }qW |S )z1Runs an evaluation execution with multiple steps.)r-   r   r^   )r   r   rW   )r?   r   rC   rD   r   3  s    T)r   c                s    j j| fdS )N)r@   )r{   r   )r   )r?   r   rC   rD   r   @  s   z*Model.make_test_function.<locals>.<lambda>)r   r^   r   r   r   r   r   r{   )r?   rC   )r?   r   r   rD   make_test_function  s    

zModel.make_test_functionc             K   s  t dd |   | d td |dd}|rDtd|f | jjrZt	
| j| _| j ^ |rt| dddk	r| j}n$tj|||||dd	||	|
| | jd
}t|tjstj|d|dk| |d	|jd}i }|  | _| jd |  x| D ]\}}|   | t xl| D ]`}tj d|d	dD |!| | |}|j"r\t#$  |}||j% }|&|| W dQ R X q"W W dQ R X qW t'(|}|j)|d |r|S t*|| j+S W dQ R X dS )a6  Returns the loss value & metrics values for the model in test mode.

    Computation is done in batches (see the `batch_size` arg.)

    Args:
        x: Input data. It could be:
          - A Numpy array (or array-like), or a list of arrays
            (in case the model has multiple inputs).
          - A TensorFlow tensor, or a list of tensors
            (in case the model has multiple inputs).
          - A dict mapping input names to the corresponding array/tensors,
            if the model has named inputs.
          - A `tf.data` dataset. Should return a tuple
            of either `(inputs, targets)` or
            `(inputs, targets, sample_weights)`.
          - A generator or `keras.utils.Sequence` returning `(inputs, targets)`
            or `(inputs, targets, sample_weights)`.
          A more detailed description of unpacking behavior for iterator types
          (Dataset, generator, Sequence) is given in the `Unpacking behavior
          for iterator-like inputs` section of `Model.fit`.
        y: Target data. Like the input data `x`, it could be either Numpy
          array(s) or TensorFlow tensor(s). It should be consistent with `x`
          (you cannot have Numpy inputs and tensor targets, or inversely). If
          `x` is a dataset, generator or `keras.utils.Sequence` instance, `y`
          should not be specified (since targets will be obtained from the
          iterator/dataset).
        batch_size: Integer or `None`. Number of samples per batch of
          computation. If unspecified, `batch_size` will default to 32. Do not
          specify the `batch_size` if your data is in the form of a dataset,
          generators, or `keras.utils.Sequence` instances (since they generate
          batches).
        verbose: 0 or 1. Verbosity mode. 0 = silent, 1 = progress bar.
        sample_weight: Optional Numpy array of weights for the test samples,
          used for weighting the loss function. You can either pass a flat (1D)
          Numpy array with the same length as the input samples
            (1:1 mapping between weights and samples), or in the case of
              temporal data, you can pass a 2D array with shape `(samples,
              sequence_length)`, to apply a different weight to every timestep
              of every sample. This argument is not supported when `x` is a
              dataset, instead pass sample weights as the third element of `x`.
        steps: Integer or `None`. Total number of steps (batches of samples)
          before declaring the evaluation round finished. Ignored with the
          default value of `None`. If x is a `tf.data` dataset and `steps` is
          None, 'evaluate' will run until the dataset is exhausted. This
          argument is not supported with array inputs.
        callbacks: List of `keras.callbacks.Callback` instances. List of
          callbacks to apply during evaluation. See
          [callbacks](/api_docs/python/tf/keras/callbacks).
        max_queue_size: Integer. Used for generator or `keras.utils.Sequence`
          input only. Maximum size for the generator queue. If unspecified,
          `max_queue_size` will default to 10.
        workers: Integer. Used for generator or `keras.utils.Sequence` input
          only. Maximum number of processes to spin up when using process-based
          threading. If unspecified, `workers` will default to 1.
        use_multiprocessing: Boolean. Used for generator or
          `keras.utils.Sequence` input only. If `True`, use process-based
          threading. If unspecified, `use_multiprocessing` will default to
          `False`. Note that because this implementation relies on
          multiprocessing, you should not pass non-picklable arguments to the
          generator as they can't be passed easily to children processes.
        return_dict: If `True`, loss and metric results are returned as a dict,
          with each key being the name of the metric. If `False`, they are
          returned as a list.
        **kwargs: Unused at this time.

    See the discussion of `Unpacking behavior for iterator-like inputs` for
    `Model.fit`.

    `Model.evaluate` is not yet supported with
    `tf.distribute.experimental.ParameterServerStrategy`.

    Returns:
        Scalar test loss (if the model has a single output and no metrics)
        or list of scalars (if the model has multiple outputs
        and/or metrics). The attribute `model.metrics_names` will give you
        the display labels for the scalar outputs.

    Raises:
        RuntimeError: If `model.evaluate` is wrapped in `tf.function`.
        ValueError: in case of invalid arguments.
    rN   r#  r	  FzInvalid keyword arguments: %sr  Nr   rV   )r   r   r   r   r   r   r   r   r   r   r   r   T)r   r  r   r  r   r  test)r  r  )r  ),r(   r  r  r  r  r   ro   r   r  r
   r  r{   r   r   r  r   r  r^   rk   r  r  r  r,  r   r\   r  Zon_test_beginr  r  r  r  r2   r  Zon_test_batch_beginr  r   r  r  Zon_test_batch_endr'   r   Zon_test_endflatten_metrics_in_orderr   )r?   r   r   r   r  r   r  r   r   r   r   r  rA   Zuse_cached_eval_datasetr'  r  r   r   r   r)  r*  rC   rC   rD   r#  E  sr    ^








*
zModel.evaluatec             C   s&   t |}t |\}}}| |ddS )a  The logic for one inference step.

    This method can be overridden to support custom inference logic.
    This method is called by `Model.make_predict_function`.

    This method should contain the mathematical logic for one step of inference.
    This typically includes the forward pass.

    Configuration details for *how* this logic is run (e.g. `tf.function` and
    `tf.distribute.Strategy` settings), should be left to
    `Model.make_predict_function`, which can also be overridden.

    Args:
      data: A nested structure of `Tensor`s.

    Returns:
      The result of one inference step, typically the output of calling the
      `Model` on data.
    F)r   )r   r   r   )r?   r   r   r   rC   rC   rD   predict_step  s    
zModel.predict_stepc                sv    j dk	r j S  fdd jdks8 j  dkrH fdd}n fdd} jsjtj|dd	}| _  j S )
a  Creates a function that executes one step of inference.

    This method can be overridden to support custom inference logic.
    This method is called by `Model.predict` and `Model.predict_on_batch`.

    Typically, this method directly controls `tf.function` and
    `tf.distribute.Strategy` settings, and delegates the actual evaluation
    logic to `Model.predict_step`.

    This function is cached the first time `Model.predict` or
    `Model.predict_on_batch` is called. The cache is cleared whenever
    `Model.compile` is called.

    Returns:
      Function. The function created by this method should accept a
      `tf.data.Iterator`, and return the outputs of the `Model`.
    Nc                s:    fdd}t |} jj||fd}t|jdd}|S )zRuns a single evaluation step.c          	      s4     | }tt|  jd W d Q R X |S )NrV   )r/  r   r   r   r]   r   )r   rW   )r   rC   rD   r     s    
zDModel.make_predict_function.<locals>.step_function.<locals>.run_step)r@   concat)r   )r   r   r   r   )r   r   r   r   rW   )r?   )r   rD   r     s    z2Model.make_predict_function.<locals>.step_functionrV   c                s
    | S )z+Runs an evaluation execution with one step.rC   )r   )r?   r   rC   rD   r   '  s    z5Model.make_predict_function.<locals>.predict_functionc                s`    | }xPt  jd D ]<}tjdd t|D d  | }tdd ||}qW |S )z1Runs an evaluation execution with multiple steps.rV   c             S   s    g | ]}|t j|d djfqS )T)dynamic_batch)r'   get_tensor_specr   )rK   trC   rC   rD   r   2  s   zIModel.make_predict_function.<locals>.predict_function.<locals>.<listcomp>)Zshape_invariantsc             S   s   t | |gS )N)r0  )t1t2rC   rC   rD   r   6      zGModel.make_predict_function.<locals>.predict_function.<locals>.<lambda>)r-   r   r^   r   Zset_loop_optionsr7   r   r   )r   rW   r   Zstep_outputs)r?   r   rC   rD   r   -  s    


T)r   )r   r^   r   r   r   r   r   )r?   r   rC   )r?   r   rD   make_predict_function  s    


zModel.make_predict_functionc	             C   s.  t dd | d td d}	| jjr6| j}	d| _| jrBd| _d}
| j  t	j
t	jf}|  srt| jrt||ry&t }tjj}||j_||}W n tk
r   td Y nX tj|||dd|||| | jd
}t|tjstj|d|dk| |d|jd	}|  | _ | j!"d |#  d}x|$ D ]\}}|%  x|& D ]x}|'| |  |}|j(r~t)*  |}|
dkrt+,d
d |}
nt+-|dd |
| ||j. }|/|d|i qVW W dQ R X q:W |dkrtd|0  W dQ R X t+-|t1|
}|	dk	r$|	| _t23|S )a  Generates output predictions for the input samples.

    Computation is done in batches. This method is designed for performance in
    large scale inputs. For small amount of inputs that fit in one batch,
    directly using `__call__` is recommended for faster execution, e.g.,
    `model(x)`, or `model(x, training=False)` if you have layers such as
    `tf.keras.layers.BatchNormalization` that behaves differently during
    inference. Also, note the fact that test loss is not affected by
    regularization layers like noise and dropout.

    Args:
        x: Input samples. It could be:
          - A Numpy array (or array-like), or a list of arrays
            (in case the model has multiple inputs).
          - A TensorFlow tensor, or a list of tensors
            (in case the model has multiple inputs).
          - A `tf.data` dataset.
          - A generator or `keras.utils.Sequence` instance.
          A more detailed description of unpacking behavior for iterator types
          (Dataset, generator, Sequence) is given in the `Unpacking behavior
          for iterator-like inputs` section of `Model.fit`.
        batch_size: Integer or `None`.
            Number of samples per batch.
            If unspecified, `batch_size` will default to 32.
            Do not specify the `batch_size` if your data is in the
            form of dataset, generators, or `keras.utils.Sequence` instances
            (since they generate batches).
        verbose: Verbosity mode, 0 or 1.
        steps: Total number of steps (batches of samples)
            before declaring the prediction round finished.
            Ignored with the default value of `None`. If x is a `tf.data`
            dataset and `steps` is None, `predict` will
            run until the input dataset is exhausted.
        callbacks: List of `keras.callbacks.Callback` instances.
            List of callbacks to apply during prediction.
            See [callbacks](/api_docs/python/tf/keras/callbacks).
        max_queue_size: Integer. Used for generator or `keras.utils.Sequence`
            input only. Maximum size for the generator queue.
            If unspecified, `max_queue_size` will default to 10.
        workers: Integer. Used for generator or `keras.utils.Sequence` input
            only. Maximum number of processes to spin up when using
            process-based threading. If unspecified, `workers` will default
            to 1.
        use_multiprocessing: Boolean. Used for generator or
            `keras.utils.Sequence` input only. If `True`, use process-based
            threading. If unspecified, `use_multiprocessing` will default to
            `False`. Note that because this implementation relies on
            multiprocessing, you should not pass non-picklable arguments to
            the generator as they can't be passed easily to children processes.

    See the discussion of `Unpacking behavior for iterator-like inputs` for
    `Model.fit`. Note that Model.predict uses the same interpretation rules as
    `Model.fit` and `Model.evaluate`, so inputs must be unambiguous for all
    three methods.

    Returns:
        Numpy array(s) of predictions.

    Raises:
        RuntimeError: If `model.predict` is wrapped in `tf.function`.
        ValueError: In case of mismatch between the provided
            input data and the model's expectations,
            or in case a stateful model receives a number of samples
            that is not a multiple of the batch size.
    rN   predictNzUsing Model.predict with MultiWorkerDistributionStrategy or TPUStrategy and AutoShardPolicy.FILE might lead to out-of-order result. Consider setting it to AutoShardPolicy.DATA.r   rV   )
r   r   r   r   r   r   r   r   r   r   T)r   r  r   r  r   r  c             S   s   | gS )NrC   )batch_outputrC   rC   rD   r     r6  zModel.predict.<locals>.<lambda>c             S   s
   |  |S )N)rn   )outputr9  rC   rC   rD   r     r6  rW   z,Expect x to be a non-empty array or dataset.)4r(   r  r  r  r   r  rz   r{   r   r   Z	DatasetV1Z	DatasetV2r;   _is_tpu_multi_hostrk   options_libOptionsZAutoShardPolicyZDATAZexperimental_distributeZauto_shard_policyZwith_optionsr<   warningswarnr   r  r^   r  r  r  r7  r   r]   r  Zon_predict_beginr  r  r  Zon_predict_batch_beginr  r   r  r7   r   Zmap_structure_up_tor  Zon_predict_batch_endZon_predict_endr0  r'   r   )r?   r   r   r  r  r   r   r   r   Zoriginal_pss_strategyrW   Zdataset_typesr   Zdata_optionr'  Zbatch_outputsr   r   r   Ztmp_batch_outputsr*  Zall_outputsrC   rC   rD   r8  A  s    J










&

zModel.predictc             C   s   x| j D ]}|  qW dS )aO  Resets the state of all the metrics in the model.

    Examples:

    >>> inputs = tf.keras.layers.Input(shape=(3,))
    >>> outputs = tf.keras.layers.Dense(2)(inputs)
    >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
    >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])

    >>> x = np.random.random((2, 3))
    >>> y = np.random.randint(0, 2, (2, 2))
    >>> _ = model.fit(x, y, verbose=0)
    >>> assert all(float(m.result()) for m in model.metrics)

    >>> model.reset_metrics()
    >>> assert all(float(m.result()) == 0 for m in model.metrics)

    N)r   Zreset_state)r?   r   rC   rC   rD   r    s    zModel.reset_metricsc       	   
   C   s   |    | d td | j D t| . t| j||||}| 	 | _
| 
|}W dQ R X W dQ R X |rz|   t|}|r|S t|| jS dS )a@  Runs a single gradient update on a single batch of data.

    Args:
        x: Input data. It could be:
          - A Numpy array (or array-like), or a list of arrays
              (in case the model has multiple inputs).
          - A TensorFlow tensor, or a list of tensors
              (in case the model has multiple inputs).
          - A dict mapping input names to the corresponding array/tensors,
              if the model has named inputs.
        y: Target data. Like the input data `x`, it could be either Numpy
          array(s) or TensorFlow tensor(s). It should be consistent with `x`
          (you cannot have Numpy inputs and tensor targets, or inversely).
        sample_weight: Optional array of the same length as x, containing
          weights to apply to the model's loss for each sample. In the case of
          temporal data, you can pass a 2D array with shape (samples,
          sequence_length), to apply a different weight to every timestep of
          every sample.
        class_weight: Optional dictionary mapping class indices (integers) to a
          weight (float) to apply to the model's loss for the samples from this
          class during training. This can be useful to tell the model to "pay
          more attention" to samples from an under-represented class.
        reset_metrics: If `True`, the metrics returned will be only for this
          batch. If `False`, the metrics will be statefully accumulated across
          batches.
        return_dict: If `True`, loss and metric results are returned as a dict,
          with each key being the name of the metric. If `False`, they are
          returned as a list.

    Returns:
        Scalar training loss
        (if the model has a single output and no metrics)
        or list of scalars (if the model has multiple outputs
        and/or metrics). The attribute `model.metrics_names` will give you
        the display labels for the scalar outputs.

    Raises:
      RuntimeError: If `model.train_on_batch` is wrapped in `tf.function`.
      ValueError: In case of invalid user-provided arguments.
    train_on_batchN)r  r  r  r   r   r   r  r   single_batch_iteratorr   r   r  r'   r   r.  r   )	r?   r   r   r   r   r  r  r   r  rC   rC   rD   r@    s     /



zModel.train_on_batchc          	   C   s   |    | d td | j , t| j|||}|  | _| |}W dQ R X |rb| 	  t
|}|rt|S t|| jS dS )a  Test the model on a single batch of samples.

    Args:
        x: Input data. It could be:
          - A Numpy array (or array-like), or a list of arrays (in case the
              model has multiple inputs).
          - A TensorFlow tensor, or a list of tensors (in case the model has
              multiple inputs).
          - A dict mapping input names to the corresponding array/tensors, if
              the model has named inputs.
        y: Target data. Like the input data `x`, it could be either Numpy
          array(s) or TensorFlow tensor(s). It should be consistent with `x`
          (you cannot have Numpy inputs and tensor targets, or inversely).
        sample_weight: Optional array of the same length as x, containing
          weights to apply to the model's loss for each sample. In the case of
          temporal data, you can pass a 2D array with shape (samples,
          sequence_length), to apply a different weight to every timestep of
          every sample.
        reset_metrics: If `True`, the metrics returned will be only for this
          batch. If `False`, the metrics will be statefully accumulated across
          batches.
        return_dict: If `True`, loss and metric results are returned as a dict,
          with each key being the name of the metric. If `False`, they are
          returned as a list.

    Returns:
        Scalar test loss (if the model has a single output and no metrics)
        or list of scalars (if the model has multiple outputs
        and/or metrics). The attribute `model.metrics_names` will give you
        the display labels for the scalar outputs.

    Raises:
        RuntimeError: If `model.test_on_batch` is wrapped in `tf.function`.
        ValueError: In case of invalid user-provided arguments.
    test_on_batchN)r  r  r  r   r   r   rA  r,  r   r  r'   r   r.  r   )r?   r   r   r   r  r  r   r  rC   rC   rD   rB  @  s    )



zModel.test_on_batchc          	   C   sT   |  d td | j ( t| j|}|  | _| |}W dQ R X t	|S )aJ  Returns predictions for a single batch of samples.

    Args:
        x: Input data. It could be:
          - A Numpy array (or array-like), or a list of arrays (in case the
              model has multiple inputs).
          - A TensorFlow tensor, or a list of tensors (in case the model has
              multiple inputs).

    Returns:
        Numpy array(s) of predictions.

    Raises:
        RuntimeError: If `model.predict_on_batch` is wrapped in `tf.function`.
        ValueError: In case of mismatch between given number of inputs and
          expectations of the model.
    predict_on_batchN)
r  r  r   r   r   rA  r7  r   r'   r   )r?   r   r   rW   rC   rC   rD   rC  z  s    

zModel.predict_on_batchc             C   s0   t d | j|||||||||	|
||||dS )zFits the model on data yielded batch-by-batch by a Python generator.

    DEPRECATED:
      `Model.fit` now supports generators, so there is no longer any need to use
      this endpoint.
    z`Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.)r   r   r  r   r$  r%  r&  r   r   r   r   r   r   )r>  r?  r   )r?   	generatorr   r   r  r   r$  r%  r&  r   r   r   r   r   r   rC   rC   rD   fit_generator  s     
zModel.fit_generatorc          	   C   s,   t d | d | j|||||||dS )zEvaluates the model on a data generator.

    DEPRECATED:
      `Model.evaluate` now supports generators, so there is no longer any need
      to use this endpoint.
    z`Model.evaluate_generator` is deprecated and will be removed in a future version. Please use `Model.evaluate`, which supports generators.evaluate_generator)r  r   r   r   r  r   )r>  r?  r  r#  )r?   rD  r  r   r   r   r   r  rC   rC   rD   rF    s    

zModel.evaluate_generatorc          	   C   s"   t d | j|||||||dS )zGenerates predictions for the input samples from a data generator.

    DEPRECATED:
      `Model.predict` now supports generators, so there is no longer any need
      to use this endpoint.
    z`Model.predict_generator` is deprecated and will be removed in a future version. Please use `Model.predict`, which supports generators.)r  r   r   r   r  r   )r>  r?  r8  )r?   rD  r  r   r   r   r   r  rC   rC   rD   predict_generator  s    
zModel.predict_generatorc             C   sD   |    | jsg S g }x| jD ]}||j7 }qW || j7 }| |S )N)_assert_weights_created
_trainable_self_tracked_trackablesr   _trainable_weights_dedup_weights)r?   r   trackable_objrC   rC   rD   trainable_weights  s    
zModel.trainable_weightsc             C   st   |    g }x| jD ]}||j7 }qW | js`g }x| jD ]}||j7 }q8W || j | | j }n
|| j }| |S )N)rH  rJ  non_trainable_variablesrI  r   rK  _non_trainable_weightsrL  )r?   rO  rM  r   rC   rC   rD   non_trainable_weights  s    
zModel.non_trainable_weightsc          	      s$   | j   tt|  S Q R X dS )z[Retrieves the weights of the model.

    Returns:
        A flat list of Numpy arrays.
    N)r   r   r`   rN   get_weights)r?   )ra   rC   rD   rR    s    zModel.get_weightsc          
   C   s   t | ||||||| dS )a!  Saves the model to Tensorflow SavedModel or a single HDF5 file.

    Please see `tf.keras.models.save_model` or the
    [Serialization and Saving guide](https://keras.io/guides/serialization_and_saving/)
    for details.

    Args:
        filepath: String, PathLike, path to SavedModel or H5 file to save the
            model.
        overwrite: Whether to silently overwrite any existing file at the
            target location, or provide the user with a manual prompt.
        include_optimizer: If True, save optimizer's state together.
        save_format: Either `'tf'` or `'h5'`, indicating whether to save the
            model to Tensorflow SavedModel or HDF5. Defaults to 'tf' in TF 2.X,
            and 'h5' in TF 1.X.
        signatures: Signatures to save with the SavedModel. Applicable to the
            'tf' format only. Please see the `signatures` argument in
            `tf.saved_model.save` for details.
        options: (only applies to SavedModel format)
            `tf.saved_model.SaveOptions` object that specifies options for
            saving to SavedModel.
        save_traces: (only applies to SavedModel format) When enabled, the
            SavedModel will store the function traces for each layer. This
            can be disabled, so that only the configs of each layer are stored.
            Defaults to `True`. Disabling this will decrease serialization time
            and reduce file size, but it requires that all custom layers/models
            implement a `get_config()` method.

    Example:

    ```python
    from keras.models import load_model

    model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
    del model  # deletes the existing model

    # returns a compiled model
    # identical to the previous one
    model = load_model('my_model.h5')
    ```
    N)r!   Z
save_model)r?   filepath	overwriteZinclude_optimizersave_formatZ
signaturesr   Zsave_tracesrC   rC   rD   r!   !  s    3z
Model.savec       
   	   C   s@  |    t|}t|}|dkr2|r,d}qhd}n6|  }|dkrLd}n|dkrZd}ntd|f |dkr|rtd| |dkrtdkrtd|dkr|d	 }n|}|st	j
|rt|}|sdS |dkrt|d
}	t|	| j W dQ R X n>t st  | jj||d tjt	j
||d|gd dS )a  Saves all layer weights.

    Either saves in HDF5 or in TensorFlow format based on the `save_format`
    argument.

    When saving in HDF5 format, the weight file has:
      - `layer_names` (attribute), a list of strings
          (ordered names of model layers).
      - For every layer, a `group` named `layer.name`
          - For every such layer group, a group attribute `weight_names`,
              a list of strings
              (ordered names of weights tensor of the layer).
          - For every weight in the layer, a dataset
              storing the weight value, named after the weight tensor.

    When saving in TensorFlow format, all objects referenced by the network are
    saved in the same format as `tf.train.Checkpoint`, including any `Layer`
    instances or `Optimizer` instances assigned to object attributes. For
    networks constructed from inputs and outputs using `tf.keras.Model(inputs,
    outputs)`, `Layer` instances used by the network are tracked/saved
    automatically. For user-defined classes which inherit from `tf.keras.Model`,
    `Layer` instances must be assigned to object attributes, typically in the
    constructor. See the documentation of `tf.train.Checkpoint` and
    `tf.keras.Model` for details.

    While the formats are the same, do not mix `save_weights` and
    `tf.train.Checkpoint`. Checkpoints saved by `Model.save_weights` should be
    loaded using `Model.load_weights`. Checkpoints saved using
    `tf.train.Checkpoint.save` should be restored using the corresponding
    `tf.train.Checkpoint.restore`. Prefer `tf.train.Checkpoint` over
    `save_weights` for training checkpoints.

    The TensorFlow format matches objects and variables by starting at a root
    object, `self` for `save_weights`, and greedily matching attribute
    names. For `Model.save` this is the `Model`, and for `Checkpoint.save` this
    is the `Checkpoint` even if the `Checkpoint` has a model attached. This
    means saving a `tf.keras.Model` using `save_weights` and loading into a
    `tf.train.Checkpoint` with a `Model` attached (or vice versa) will not match
    the `Model`'s variables. See the [guide to training
    checkpoints](https://www.tensorflow.org/guide/checkpoint) for details
    on the TensorFlow format.

    Args:
        filepath: String or PathLike, path to the file to save the weights to.
            When saving in TensorFlow format, this is the prefix used for
            checkpoint files (multiple files are generated). Note that the '.h5'
            suffix causes weights to be saved in HDF5 format.
        overwrite: Whether to silently overwrite any existing file at the
            target location, or provide the user with a manual prompt.
        save_format: Either 'tf' or 'h5'. A `filepath` ending in '.h5' or
            '.keras' will default to HDF5 if `save_format` is `None`. Otherwise
            `None` defaults to 'tf'.
        options: Optional `tf.train.CheckpointOptions` object that specifies
            options for saving weights.

    Raises:
        ImportError: If h5py is not available when attempting to save in HDF5
            format.
        ValueError: For invalid/unknown format arguments.
    Nh5tf)Z
tensorflowrW  )Zhdf5rV  Zkerasz7Unknown format "%s". Was expecting one of {"tf", "h5"}.zsave_weights got save_format="tf"/"tensorflow", but the filepath ("%s") looks like an HDF5 file. Omit the ".h5"/".keras" when saving in TensorFlow format.z1`save_weights` requires h5py when saving in hdf5.z.indexw)r   T)save_dirZmodel_checkpoint_pathZsave_relative_pathsZall_model_checkpoint_paths)rH  r*   r"   is_hdf5_filepathlowerstripr<   h5pyImportErrorospathisfiler)   Filer    Zsave_weights_to_hdf5_grouplayersr   r   r   get_sessionr   writer   Z update_checkpoint_state_internaldirname)
r?   rS  rT  rU  r   Zfilepath_is_h5Zuser_formatZcheck_filepathproceedfrC   rC   rD   save_weightsW  sP    A




zModel.save_weightsc       
   	   C   s:  t | jr,| jjjdkr,t|s,td|r<|s<tdt|\}}|dkr| j	
||}|rjtdt st  }tj||d |  nd}tdkrtd| js| jstd	|   t|d
H}d|jkrd|kr|d }|rtj|| j|d nt|| j W dQ R X x| jD ]}	|	  q$W |S )a	  Loads all layer weights, either from a TensorFlow or an HDF5 weight file.

    If `by_name` is False weights are loaded based on the network's
    topology. This means the architecture should be the same as when the weights
    were saved.  Note that layers that don't have weights are not taken into
    account in the topological ordering, so adding or removing layers is fine as
    long as they don't have weights.

    If `by_name` is True, weights are loaded into layers only if they share the
    same name. This is useful for fine-tuning or transfer-learning models where
    some of the layers have changed.

    Only topological loading (`by_name=False`) is supported when loading weights
    from the TensorFlow format. Note that topological loading differs slightly
    between TensorFlow and HDF5 formats for user-defined classes inheriting from
    `tf.keras.Model`: HDF5 loads based on a flattened list of weights, while the
    TensorFlow format loads based on the object-local names of attributes to
    which layers are assigned in the `Model`'s constructor.

    Args:
        filepath: String, path to the weights file to load. For weight files in
            TensorFlow format, this is the file prefix (the same as was passed
            to `save_weights`). This can also be a path to a SavedModel
            saved from `model.save`.
        by_name: Boolean, whether to load weights by name or by topological
            order. Only topological loading is supported for weight files in
            TensorFlow format.
        skip_mismatch: Boolean, whether to skip loading of layers where there is
            a mismatch in the number of weights, or a mismatch in the shape of
            the weight (only valid when `by_name=True`).
        options: Optional `tf.train.CheckpointOptions` object that specifies
            options for loading weights.

    Returns:
        When loading a weight file in TensorFlow format, returns the same status
        object as `tf.train.Checkpoint.restore`. When graph building, restore
        ops are run automatically as soon as the network is built (on first call
        for user-defined classes inheriting from `Model`, immediately if it is
        already built).

        When loading weights in HDF5 format, returns `None`.

    Raises:
        ImportError: If h5py is not available and the weight file is in HDF5
            format.
        ValueError: If `skip_mismatch` is set to `True` when `by_name` is
          `False`.
    rV   zULoad weights is not yet supported with TPUStrategy with steps_per_run greater than 1.z\When calling model.load_weights, skip_mismatch can only be set to True when by_name is True.rW  zWeights may only be loaded based on topology into Models when loading TensorFlow-formatted weights (got by_name=True to load_weights).)statussessionNz<`load_weights` requires h5py when loading weights from HDF5.zUnable to load weights saved in HDF5 format into a subclassed Model which has not created its variables yet. Call the Model first, then load the weights.rZlayer_namesZmodel_weights)skip_mismatch)r   is_tpu_strategyrz   extendedZsteps_per_runr"   rZ  r<   _detect_save_formatr   readr   r   r   rd  r   Zstreaming_restoreZassert_nontrivial_matchr]  r^  rp   builtrH  rb  attrsr    Z$load_weights_from_hdf5_group_by_namerc  Zload_weights_from_hdf5_groupZfinalize_state)
r?   rS  Zby_namerm  r   rU  rj  rk  rh  layerrC   rC   rD   load_weights  sF    5

zModel.load_weightsc             C   s.   ddl m} |  }| jj||t d}|S )zUtil shared between different serialization methods.

    Returns:
        Model config with Keras version information added.
    r   )__version__)
class_nameconfigkeras_versionr   )tensorflow.python.kerasrv  
get_configra   r>   r   )r?   ry  rx  model_configrC   rC   rD   _updated_config2	  s    zModel._updated_configc             C   s   t d S )N)r   )r?   rC   rC   rD   r{  C	  s    zModel.get_configc          	   C   sV   ddl m} t 8 |||\}}}| |||dd}||| |S Q R X d S )Nr   )rH   rb   )rX   rW   rb   )rM   rH   r%   ZSharedObjectLoadingScopeZreconstruct_from_configr   Zconnect_ancillary_layers)rT   rx  Zcustom_objectsrH   Zinput_tensorsZoutput_tensorsZcreated_layersr   rC   rC   rD   from_configF	  s    
zModel.from_configc             K   s    |   }tj|fdtji|S )aA  Returns a JSON string containing the network configuration.

    To load a network from a JSON save file, use
    `keras.models.model_from_json(json_string, custom_objects={})`.

    Args:
        **kwargs: Additional keyword arguments
            to be passed to `json.dumps()`.

    Returns:
        A JSON string.
    default)r}  jsondumpsr#   Zget_json_type)r?   rA   r|  rC   rC   rD   to_jsonW	  s    zModel.to_jsonc             K   s   t ddS )a  Returns a yaml string containing the network configuration.

    Note: Since TF 2.6, this method is no longer supported and will raise a
    RuntimeError.

    To load a network from a yaml save file, use
    `keras.models.model_from_yaml(yaml_string, custom_objects={})`.

    `custom_objects` should be a dictionary mapping
    the names of custom losses / layers / etc to the corresponding
    functions / classes.

    Args:
        **kwargs: Additional keyword arguments
            to be passed to `yaml.dump()`.

    Returns:
        A YAML string.

    Raises:
        RuntimeError: announces that the method poses a security risk
    zMethod `model.to_yaml()` has been removed due to security risk of arbitrary code execution. Please use `model.to_json()` instead.N)r   )r?   rA   rC   rC   rD   to_yamlh	  s    zModel.to_yamlc             C   s2   x,| j D ]"}t|drt|ddr|  qW d S )Nreset_statesstatefulF)rc  hasattrr   r  )r?   rt  rC   rC   rD   r  	  s    zModel.reset_statesc             C   sB   t d g }x.| jD ]$}t|ddrt|dr||j7 }qW |S )a  Deprecated, do NOT use!

    Returns the `updates` from all layers that are stateful.

    This is useful for separating training updates and
    state updates, e.g. when we need to update a layer's internal state
    during prediction.

    Returns:
        A list of update ops.
    z`Model.state_updates` will be removed in a future version. This property should not be used in TensorFlow 2.0, as `updates` are applied automatically.r  Fupdates)r>  r?  rc  r   r  r  )r?   state_updatesrt  rC   rC   rD   r  	  s    

zModel.state_updatesc             C   s   |  | jS )zReturns the list of all layer variables/weights.

    Note: This will not track the weights of nested `tf.Modules` that are not
    themselves Keras layers.

    Returns:
      A list of variables.
    )rL  _undeduplicated_weights)r?   rC   rC   rD   weights	  s    
zModel.weightsc             C   s:   |    g }x| jD ]}||j7 }qW || j| j 7 }|S )z?Returns the undeduplicated list of all layer variables/weights.)rH  rJ  r0   rK  rP  )r?   r  rt  rC   rC   rD   r  	  s    zModel._undeduplicated_weightsc             C   s$   | j stdtj| |||d dS )a  Prints a string summary of the network.

    Args:
        line_length: Total length of printed lines
            (e.g. set this to adapt the display to different
            terminal window sizes).
        positions: Relative or absolute positions of log elements
            in each line. If not provided,
            defaults to `[.33, .55, .67, 1.]`.
        print_fn: Print function to use. Defaults to `print`.
            It will be called on each line of the summary.
            You can set it to a custom function
            in order to capture the string summary.

    Raises:
        ValueError: if `summary()` is called before the model is built.
    zThis model has not yet been built. Build the model first by calling `build()` or calling `fit()` with some data, or specify an `input_shape` argument in the first layer(s) for automatic build.)line_length	positionsprint_fnN)rr  r<   r&   Zprint_summary)r?   r  r  r  rC   rC   rD   summary	  s    zModel.summaryc             C   s   t | jdddS )NF)Zinclude_self	recursive)r   r   )r?   rC   rC   rD   rc  	  s    zModel.layersc             C   s   |dk	r|dk	rt d|dk	r`t| j|krVt dt| d tt| j d n
| j| S |dk	rx| jD ]}|j|krp|S qpW t d| d t ddS )	a  Retrieves a layer based on either its name (unique) or index.

    If `name` and `index` are both provided, `index` will take precedence.
    Indices are based on order of horizontal graph traversal (bottom-up).

    Args:
        name: String, name of layer.
        index: Integer, index of layer.

    Returns:
        A layer instance.

    Raises:
        ValueError: In case of invalid layer name or index.
    Nz+Provide only a layer name or a layer index.z%Was asked to retrieve layer at index z but model only has z layers.zNo such layer: .z+Provide either a layer name or layer index.)r<   rY   rc  strrb   )r?   rb   indexrt  rC   rC   rD   	get_layer	  s    


zModel.get_layerc             C   s   | j d k	rd S | j}|s"t|}t|}g }x,t||D ]\}}|tj	|d|d q<W t
||}|| _ | jjdkr| jd krtdd || _d S )NF)r1  rb   Z
Sequentialc             S   s   | d krd S | j S )N)r   )r   rC   rC   rD   r   
  r6  z&Model._set_save_spec.<locals>.<lambda>)r   rq   r   Zcreate_pseudo_input_namesr7   r   ziprn   r'   r2  Zpack_sequence_asra   r>   Z_build_input_shaper   )r?   rX   rq   Zflat_inputsspecsrb   ZtensorrC   rC   rD   _set_save_spec	  s     



zModel._set_save_specc             C   s8   | j r
dS d| jjkr4| jtkr4| js4td| j dS )aa  Asserts that all the weights for the model have been created.

    For a non-dynamic model, the weights must already be created after the
    layer has been called. For a dynamic model, the exact list of weights can
    never be known for certain since it may change at any time during execution.

    We run this check right before accessing weights or getting the Numpy value
    for the current weights. Otherwise, if the layer has never been called,
    the user would just get an empty list, which is misleading.

    Raises:
      ValueError: if the weights of the network has not yet been created.
    Nr   zWeights for model %s have not yet been created. Weights are created when the Model is first called on inputs or `build()` is called with an `input_shape`.)rg   ra   __dict__rN   rr  r<   rb   )r?   rC   rC   rD   rH  
  s    
zModel._assert_weights_createdc             C   st   | j }|jr$|jdt|j  }n|j}d|kr<|d t|dkrp|dd }td| d t| d dS )z.Check that `call` has only one positional arg.Nr   rU   zModels passed to `z\` can only have `training` and the first argument in `call` as positional arguments, found: r  )r   r   r@   rY   remover<   r  )r?   method_nameZfullargspecZpositional_args
extra_argsrC   rC   rD   r  0
  s    
zModel._check_call_argsc       	      K   sj  t dd t|D r$td|d|dd |dd |dddk	rTtd	|d
ddk	rltdt|dh }|rtd|f | jrt	 rt
 }x*| jD ] }|j|std||f qW | j}xDt|D ]6}x0t|dg D ] }|j|std||f qW qW xJt|D ]<}x4t|dg D ]$}|j|s8td||f q8W q&W dS )z5Performs validation checks for the default `compile`.c             s   s   | ]}t |tjV  qd S )N)rk   r   Z	Optimizer)rK   r   rC   rC   rD   rL   F
  s   z*Model._validate_compile.<locals>.<genexpr>z `tf.compat.v1.keras` Optimizer (zs) is not supported when eager execution is enabled. Use a `tf.keras` Optimizer instead, or disable eager execution.ZcloningNZexperimental_run_tf_functionZ
distributezxDistribute argument in compile is not available in TF 2.0 please create the model under the distribution strategy scope.Ztarget_tensorsz@target_tensors argument is not supported when executing eagerly.Zsample_weight_modez,Invalid keyword argument(s) in `compile`: %saA  Variable (%s) was not created in the distribution strategy scope of (%s). It is most likely due to not all layers or the model or optimizer being created outside the distribution strategy scope. Try to make sure your code looks similar to the following.
with strategy.scope():
  model=_create_model()
  model.compile(...)r0   ae  Metric (%s) passed to model.compile was created inside of a different distribution strategy scope than the model. All metrics must be created in the same distribution strategy scope as the model (in this case %s). If you pass in a string identifier for a metric to compile the metric will automatically be created in the correct distribution strategy scope.Z_weightsar  Optimizer (%s) passed to model.compile was created inside of a different distribution strategy scope than the model. All optimizers must be created in the same distribution strategy scope as the model (in this case %s). If you pass in a string identifier for an optimizer to compile the optimizer will automatically be created in the correct distribution strategy scope.)anyr7   r   r<   r   setro   rr  rw   rx   ry   r0   ro  Zvariable_created_in_scoper   r   )	r?   ri   r   rA   Zinvalid_kwargsstrategyr   r   r   rC   rC   rD   r   C
  sJ    

zModel._validate_compilec             C   s    | j dk	r| j j|tjdS |S )a  Maybe load initial epoch from ckpt considering possible worker recovery.

    Refer to tensorflow/python/keras/distribute/worker_training_state.py
    for more information.

    Args:
      initial_epoch: The original initial_epoch user passes in in `fit()`.

    Returns:
      If the training is recovering from previous failure under multi-worker
      training setting, return the epoch the training is supposed to continue
      at. Otherwise, return the `initial_epoch` the user passes in.
    N)mode)r~   Z"maybe_load_initial_epoch_from_ckptr+   ZTRAIN)r?   r   rC   rC   rD   r  
  s    
z)Model._maybe_load_initial_epoch_from_ckptc             C   s   | j stdd S )NzZYou must compile your model before training/testing. Use `model.compile(optimizer, loss)`.)rh   r   )r?   rC   rC   rD   r  
  s    z Model._assert_compile_was_calledc             C   s   |  | dS )zDThis method is for compat with Modelv1. Only inputs are needed here.N)r  )r?   rX   rW   r   rC   rC   rD   _set_inputs
  s    zModel._set_inputsc             C   s
   t | S )N)r$   ZModelSavedModelSaver)r?   rC   rC   rD   _trackable_saved_model_saver
  s    z"Model._trackable_saved_model_saverr   c                sp   |dkr8| j }| j}| j}| j}d | _ d | _d | _d | _tt| j|f|}|dkrl|| _ || _|| _|| _|S )NZ
savedmodel)r   r   r   r   r`   rN   _trackable_children)r?   	save_typerA   r   r   r   r   children)ra   rC   rD   r  
  s     zModel._trackable_childrenc             C   s<   |d }t |tr|| dkS t |tr0||kS tdd S )NrV   r   z/Expected `validation_freq` to be a list or int.)rk   r   r   r<   )r?   r(  r&  rC   rC   rD   r"  
  s    

zModel._should_evalc             C   sZ   |    | jj}| jj}|s<|dk	r,| jj}|dk	r<| jj}| j| jj||| jj	d}|S )a  Used for saving or cloning a Model.

    Args:
      user_metrics: Whether to return user-supplied metrics or `Metric` objects.
        Defaults to returning the user-supplied metrics.

    Returns:
      Dictionary of arguments that were used when compiling the model.
    N)ri   r   r   r   r   )
r  rv   Z_user_metricsZ_user_weighted_metricsr   Z_weighted_metricsri   ru   Z_user_lossesZ_user_loss_weights)r?   Zuser_metricsZsaved_metricsZsaved_weighted_metricsZcompile_argsrC   rC   rD   _get_compile_args
  s    
zModel._get_compile_argsc             C   s   | S )NrC   )r?   rC   rC   rD   _get_callback_model
  s    zModel._get_callback_modelc             C   s   | j j S )N)r   ro  r;   )r?   rC   rC   rD   r;   
  s    zModel._in_multi_worker_modec             C   s   | j S )N)rh   )r?   rC   rC   rD   _compile_was_called
  s    zModel._compile_was_called)NN)r   NNNNNN)NNNrV   r   Nr   NTNNr   NNNrV   r   rV   F)NNNrV   NNNr   rV   FF)Nr   NNr   rV   F)NNNTF)NNTF)NrV   rV   NNNrV   Nr   rV   FTr   )NNr   rV   Fr   )NNr   rV   Fr   )TTNNNT)TNN)FFN)N)NNN)NN)NN)r   )T)Tr>   
__module____qualname____doc__	frozenset	itertoolschainr   r   Z_TF_MODULE_IGNORED_PROPERTIESrS   	trackableZ no_automatic_dependency_trackingrl   r   r   r%   r  r   r:   Zdoc_in_current_and_subclassesr   r   r   r}   r   propertyr   r   r   r   r   setterr   r   r   r+  r,  r#  r/  r7  r8  r  r@  rB  rC  rE  rF  rG  rN  rQ  rR  r!   ri  ru  r}  r{  classmethodr~  r  r  r  Zdo_not_generate_docsr  r  r  r  rc  r  r  rH  r  r   r  r  r  r  r  r"  r  r  r;   r  __classcell__rC   rC   )ra   rD   rN      s2  L	`
f      
f2(!0D                  
  [)A          
 D      
      
>   
5            
     
     
     
1  
s  
b


$F


 rN   r   c                s    fdd}t || S )a  Reduce PerReplica objects.

  Args:
    values: Structure of `PerReplica` objects or `Tensor`s. `Tensor`s are
      returned as-is.
    strategy: `tf.distribute.Strategy` object.
    reduction: One of 'first', 'concat'.

  Returns:
    Structure of `Tensor`s.
  c                sr    dkrt rt| S t| s&| S  dkr<| d S  dkrftrVt| S t| S ntddS )z$Reduce a single `PerReplica` object.r0  r   r   z(`reduction` must be "first" or "concat".N)#_collective_all_reduce_multi_worker_multi_worker_concat_is_per_replica_instanceunwrapr;  _tpu_multi_host_concatr0  r<   )r   )r   r  rC   rD   _reduce	  s    

z#reduce_per_replica.<locals>._reduce)r7   r   )r	   r  r   r  rC   )r   r  rD   r   
  s    r   c             C   sJ   t | d tjrtj|| dS t| d r8tj| |dS tj| |dS dS )zConcats `tensor`s along `axis`.r   )axisZ	sp_inputs)r  N)	rk   r   ZSparseTensorr.   Zsparse_concat_v2
_is_scalarr,   stackr0  )Ztensorsr  rC   rC   rD   r0    s
    r0  c             C   s   t | o| jjdkS )NrV   )r   rn  ro  Z	num_hosts)r  rC   rC   rD   r;  &  s    
r;  c             C   sB   | | }|jj}g }x"t|D ]}|||d| 7 }q W t|S )z'Correctly order TPU PerReplica objects.N)r  ro  num_replicas_per_hostr   r0  )r   r  replicasr  ordered_replicas
replica_idrC   rC   rD   r  +  s    
r  c             C   s   t | tjo| j S )N)rk   r   ZCollectiveAllReduceStrategyro  r;   )r  rC   rC   rD   r  :  s    r  c             C   s   |j | dd}t| r@tjdd | jD dd}|j |dd}n"|j tjt| d dddd}tj|||jd}g }t	|j
j}x"t|D ]}|||d| 7 }qW t|S )zDOrder PerReplica objects for CollectiveAllReduceStrategy and concat.r   )r  c             S   s$   g | ]}t jt |d  d dqS )r   )r  )r,   expand_dims_v2r   )rK   Zsingle_valuerC   rC   rD   r   H  s   z(_multi_worker_concat.<locals>.<listcomp>)Znum_or_size_splitsnumN)gatherr  r,   r0  r	   r  r   splitZnum_replicas_in_syncrY   ro  Zworker_devicesr   )r   r  r  ZshapesZ
all_shapesr  Znum_replicas_per_workerr  rC   rC   rD   r  B  s$    
r  c             C   s   t | tjtjfo| jjdkS )Nr   )rk   r   ZTensorr0   r   r   Zrank)r   rC   rC   rD   r  ]  s    r  c             C   s6   x0|   D ]$\}}t|r
tjd| ||d q
W d S )NZbatch_)r   )r   r  r/   Zscalar)r  r   rb   r   rC   rC   rD   r   a  s    r   c             C   s>   t  rg S tj| dd} x| D ]}t|tjs |gS q W g S )zBReturns the minimum control dependencies to ensure step succeeded.T)Zexpand_composites)r   r   r7   r   rk   r0   r   )rW   outrC   rC   rD   r   g  s    

r   c             C   s    t  rdj| d}t|d S )NaI  Detected a call to `Model.{method_name}` inside a `tf.function`. `Model.{method_name} is a high-level endpoint that manages its own `tf.function`. Please move the call to `Model.{method_name}` outside of all enclosing `tf.function`s. Note that you can call a `Model` directly on `Tensor`s inside a `tf.function` like: `model(x)`.)r  )r   Zinside_functionr=   r   )r  	error_msgrC   rC   rD   r  s  s    r  c             C   st   t | } t| r| dfS t| r(d}nDt| rhtj| t	j
t	j}t|rX|} d}qltd| nd}| |fS )z-Returns path to weights file and save format.rV  rW  zUnable to load weights. filepath {} appears to be a SavedModel directory, but checkpoint either doesn't exist, or is incorrectly formatted.)r*   r"   rZ  _is_readable_tf_checkpoint	sm_loaderZcontains_saved_modelr_  r`  joinsm_constantsZVARIABLES_DIRECTORYZVARIABLES_FILENAMEr<   r=   )rS  rU  Z	ckpt_pathrC   rC   rD   rp    s    


rp  c             C   s*   yt |  dS  tjk
r$   dS X d S )NTF)r6   ZNewCheckpointReaderr   ZDataLossError)rS  rC   rC   rD   r    s
    
r  c             C   sl   g }x"|D ]}|| kr
| | |  q
W x*t|  D ]}||kr6| | |  q6W t|dkrh|d S |S )zFTurns the `logs` dict into a list as per key order of `metrics_names`.rV   r   )rn   sortedkeysrY   )r  r   resultsrb   keyrC   rC   rD   r.    s    
r.  c             C   s   t | tjot | tjS )N)rk   	ds_valuesZDistributedValuesr   ZCompositeTensor)objrC   rC   rD   r    s    r  )r   )r   )xr  r!  r  r  r_  r>  r   Z tensorflow.python.autograph.langr   Ztensorflow.python.checkpointr   r   r   Ztensorflow.python.data.opsr   r   r<  Ztensorflow.python.distributer   r   rw   r	   r  Z(tensorflow.python.distribute.coordinatorr
   Ztensorflow.python.eagerr   r   r   Ztensorflow.python.frameworkr   r   r   r   r   r   r   rz  r   r   r  r   r   rM   r   r   r   r   r   Z'tensorflow.python.keras.mixed_precisionr   r   r   Ztensorflow.python.keras.savingr    r!   r"   Z*tensorflow.python.keras.saving.saved_modelr#   r$   Ztensorflow.python.keras.utilsr%   r&   r'   r(   Z&tensorflow.python.keras.utils.io_utilsr)   r*   Z'tensorflow.python.keras.utils.mode_keysr+   Ztensorflow.python.opsr,   r-   r.   r/   r0   Ztensorflow.python.platformr1   r   Ztensorflow.python.profilerr2   Ztensorflow.python.saved_modelr3   r  r4   r  Ztensorflow.python.trackabler5   r  Ztensorflow.python.trainingr6   Ztensorflow.python.utilr7   r8   Z tensorflow.python.util.tf_exportr9   Ztensorflow.tools.docsr:   r]  r^  rG   rJ   rZ   r   ZModelVersionSelectorrN   r   r0  r;  r  r  r  r  r   r   r  rp  r  r.  r  rC   rC   rC   rD   <module>   s   
                     
 

	