a
    SicSV                    @   s  d Z ddlZddlZddlZddlm  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/Z0 zddl1m2Z2 W n e3y   dZ2Y n0 G dd dej4Z4G d d! d!e4Z5G d"d# d#Z6G d$d% d%Z7d&d' Z8d(d) Z9d*d+ Z:d,d- Z;dS ).z-V1 Training-related part of the Keras engine.    N)backend)losses)metrics)
optimizers)distributed_training_utils)distributed_training_utils_v1)
base_layer)training)training_arrays_v1)training_distributed_v1)training_eager_v1)training_generator_v1)training_utils)training_utils_v1)loss_scale_optimizer)optimizer_v1)optimizer_v2)saving_utils)model_serialization)
data_utils)layer_utils)losses_utils)
tf_inspect)tf_utils)ModeKeys)
tf_logging)issparsec                       s,  e Zd ZdZ fddZdd Zejjj	dd Z
dd	 Zd fdd	Zejjj	dddZejjj	dd Ze fddZe fddZedd Zejdd Zdd Zdd!d"Zdd#d$Zdd%d&Zd'd( Zdd)d*Zdd+d,Zd-d. Zdd/d0Zdd1d2Zdd3d4Zd5d6 Zd7d8 Z d9d: Z!d;d< Z"d=d> Z#d?d@ Z$ddAdBZ%dCdD Z&ejjj	ddEdFZ'dGdH Z(dIdJ Z)dKdL Z*dMdN Z+ejjj	dOdP Z,dQdR Z-ddSdTZ.dUdV Z/dWdX Z0dYdZ Z1d[d\ Z2d]d^ Z3dd_d`Z4ddadbZ5dcdd Z6dedf Z7dgdh Z8didj Z9dkdl Z:ddmdnZ;ddpdqZ<ddrdsZ=dtdu Z>dvdw Z?ddxdyZ@ejjj	dzd{ ZAejjj	d|d} ZBed~d ZCedd ZDedd ZEedd ZFedd ZGedd ZHedd ZIedd ZJedd ZKedd ZLdd ZMdd ZNdd ZOdd ZPedd ZQdddZRedd ZS  ZTS )Modelaf  `Model` groups layers into an object with training and inference features.

    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)
    ```

    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().__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().__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()
    ```
    c                    sh   t  j|i | d | _d | _tjj rDtj	 rD| 
tj  d| _d | _tjj | _d| _d S )NF)super__init___distribution_strategy#_compile_time_distribution_strategytfcompatv1#executing_eagerly_outside_functions
distributehas_strategy_set_strategyget_strategy_compile_distribution_run_eagerly_experimental_run_tf_function_v1_compile_was_called)selfargskwargs	__class__ T/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/engine/training_v1.pyr   y   s    

zModel.__init__c                 C   s   d S Nr3   r.   r3   r3   r4   _init_batch_counters   s    zModel._init_batch_countersc                 C   s
   || _ d S r5   )r!   r.   strategyr3   r3   r4   r(      s    zModel._set_strategyc                 C   sP   | j p
| j}|rD|  tj| W  d   S 1 s:0    Y  tj| S )zgRetrieves the weights of the model.

        Returns:
            A flat list of Numpy arrays.
        N)r    r!   scoper   Layerget_weightsr8   r3   r3   r4   r<      s    
*zModel.get_weightsFc                    s<   t | jr,| jjjdkr,t|s,tdt 	|||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`).
            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`).

        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`.
           zULoad weights is not yet supported with TPUStrategy with steps_per_run greater than 1.)
r   is_tpu_strategyr    extendedsteps_per_runr   is_hdf5_filepath
ValueErrorr   load_weights)r.   filepathby_nameskip_mismatchr1   r3   r4   rC      s    /zModel.load_weightsrmspropNc	                 K   s  |    |	dd| _|	dd| _d| _|	dd |	dd| _h d}
t|	 |
 }|rntd	|f |	| _	| j	rd| _| j
rtd
| j	f | | tdd tj| jD }|rtjj rtd|d|dustjj sd| _|dur2tjj s| jrtdtd || _d| _n$tj rVtj rVtj | _t | jtjjjj!j"rvt#dt | jtjj!j"rt#d| js| $| j
||| t | jtjj%j&r| j'| jddd |pi | _(|| _)|| _*|pg | _+|| _,| j
r|durtdg | _-| . | _/i | _0i | _1| 2  t3 s\| jdur\t45| j | 6  | j7r|| j8r|| j9sdS d| _:t;j<=dd t>?| j(| j@| _A| B|}tC| j9| j@| jA|D ]6\}}}}tD|||}|jE|| j
d | j-F| qt>G| j-| | j
r(| H||| dS t4I J  | K|| | L  | jM| j9| jN| O | P d t>Q| j-| | R  d| _Sd| _Td| _U| jV| _W| jr| js| jXD ]*}| j}|jYZ|std||f qW d   n1 s0    Y  dS )a  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
                `scalar_loss = fn(y_true, y_pred)`. 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.
            metrics: List of metrics to be evaluated by the model during
                training and testing. Typically you will use
                `metrics=['accuracy']`.  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
                (len = len(outputs)) of lists of metrics such as
                `metrics=[['accuracy'], ['accuracy', 'mse']]` or
                `metrics=['accuracy', ['accuracy', 'mse']]`.
            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 tensor, it is expected to map
                output names (strings) to scalar coefficients.
            sample_weight_mode: If you need to do timestep-wise
                sample weighting (2D weights), set this to `"temporal"`.
                `None` defaults to sample-wise weights (1D).
                If the model has multiple outputs, you can use a different
                `sample_weight_mode` on each output by passing a
                dictionary or a list of modes.
            weighted_metrics: List of metrics to be evaluated and weighted
                by sample_weight or class_weight during training and testing.
            target_tensors: By default, Keras will create placeholders for the
                model's target, which will be fed with the target data during
                training. If instead you would like to use your own
                target tensors (in turn, Keras will not expect external
                Numpy data for these targets at training time), you
                can specify them via the `target_tensors` argument. It can be
                a single tensor (for a single-output model), a list of tensors,
                or a dict mapping output names to target tensors.
            distribute: NOT SUPPORTED IN TF 2.0, please create and compile the
                model under distribution strategy scope instead of passing it to
                compile.
            **kwargs: Any additional arguments.

        Raises:
            ValueError: In case of invalid arguments for
                `optimizer`, `loss`, `metrics` or `sample_weight_mode`.
        run_eagerlyNexperimental_run_tf_functionTcloningfrom_serializedF>   	feed_dictrun_metadataoptionsfetchesz,Invalid keyword argument(s) in `compile`: %szsSession keyword arguments are not supported when `run_eagerly=True`. You passed the following Session arguments: %sc                 s   s(   | ] }t |tjot |tj V  qd S r5   )
isinstancer   	OptimizerTFOptimizer.0optr3   r3   r4   	<genexpr>A  s   z Model.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.zxDistribute argument in compile is not available in TF 2.0 please create the model under the distribution strategy scope.zkDistribute argument in compile is deprecated please create the model under the distribution strategy scope.zm`tf.compat.v1.distribute.experimental.ParameterServerStrategy` currently only works with the tf.Estimator APIzN`tf.distribute.experimental.ParameterServerStrategy` is only supported in TF2.	optimizer)name	overwritezFtarget_tensors argument is not supported when running a model eagerly.compile)rH   )targetsskip_target_masksmasksaA  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(...))[_assert_built_as_v1popr+   r,   r-   _from_serializedsetkeys	TypeError_function_kwargsrH   rB   _set_optimizeranyr"   nestflattenrW   r#   r$   r%   __internal__tf2enabledloggingwarningr    r*   r&   r'   in_cross_replica_contextr)   rP   experimentalParameterServerStrategyNotImplementedError1_validate_compile_param_for_distribution_strategytracking	Trackable_track_trackablelossloss_weightssample_weight_mode_compile_metrics_compile_weighted_metrics_training_endpoints_get_trainable_state_compiled_trainable_state_distributed_model_cache_distributed_function_cache_clear_lossesexecuting_eagerlyr   (configure_and_create_distributed_session_init_metric_attributesbuiltinputsoutputs_is_compiledr   keras_api_gaugeget_cellr   prepare_loss_functionsoutput_namesloss_functions"_process_target_tensor_for_compilezip_TrainingEndpointcreate_training_targetappendprepare_loss_weights_compile_eagerly	get_graph
as_default_cache_output_metric_attributes_set_metric_attributes_handle_metrics_targets_prepare_skip_target_masks_prepare_output_masksprepare_sample_weight_modes*_compile_weights_loss_and_weighted_metricstrain_functiontest_functionpredict_functiontrainable_weights_collected_trainable_weights	variablesr?   variable_created_in_scope)r.   rW   rv   r   rw   rx   weighted_metricstarget_tensorsr&   r0   allowed_kwargsunknown_kwargsis_any_keras_optimizer_v1onltendpointvr9   r3   r3   r4   rZ      s0   E
	




	

	
zModel.compilec                 C   s   t | dsi | _d S )Nr   )hasattrr   r6   r3   r3   r4   0_init_distributed_function_cache_if_not_compiled  s    
z6Model._init_distributed_function_cache_if_not_compiledc                    sR   g }| j r&t| dst jS || j7 }|| j |tt| j	ddd |S )zMReturns the model's metrics added using `compile`, `add_metric`
        APIs.r-   Finclude_self	recursive)
r   r   r   r   _compile_metric_functionsextend_metrics_get_metrics_from_layerslist_flatten_layersr.   r   r1   r3   r4   r     s    

zModel.metricsc                    sZ   dg}| j rBt| dst jS t| jdkrB|dd | jD  |dd | jD 7 }|S )z3Returns the model's display labels for all outputs.rv   r-   r=   c                 S   s   g | ]}|  s| qS r3   )should_skip_target	loss_namerT   er3   r3   r4   
<listcomp>9  s   z'Model.metrics_names.<locals>.<listcomp>c                 S   s   g | ]
}|j qS r3   rX   rT   mr3   r3   r4   r   A      )r   r   r   metrics_nameslenr{   r   r   )r.   r   r1   r3   r4   r   (  s    
	zModel.metrics_namesc                 C   sj   | j du rt std| js<| j du r4tj S | j S n*t sLtd| j du r^tdt S d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.
        TzBYou can only set `run_eagerly=True` if eager execution is enabled.NzYour model contains layers that can only be successfully run in eager execution (layers constructed with `dynamic=True`). You must enable eager execution with `tf.enable_eager_execution()`.FzYour model contains layers that can only be successfully run in eager execution (layers constructed with `dynamic=True`). You cannot set `run_eagerly=False`.)r+   r"   r   rB   dynamicconfigfunctions_run_eagerlyr6   r3   r3   r4   rH   D  s"    


zModel.run_eagerlyc                 C   s
   || _ d S r5   )r+   r.   valuer3   r3   r4   rH   q  s    c                 C   s   t |tjjjjtjjfr"td| jrF|  r>t	
t	 S t	 S t|rXt S t|rjt S | jrxt S t S dS )z>Select training loop for fit/eval/predict based on the inputs.a  For performance reasons Keras `fit`, `evaluate` and`predict` accept tf.data `Datasets` as input but not iterators that have been manually generated from Datasets by users. Please directly pass in the original `Dataset` object instead of passing in `iter(dataset)`.N)rP   r"   r#   r$   dataIteratorrB   r    _in_multi_worker_moder   #DistributionMultiWorkerTrainingLoop$DistributionSingleWorkerTrainingLoopr   is_generator_or_sequencer   GeneratorOrSequenceTrainingLoopr   is_eager_dataset_or_iterator"EagerDatasetOrIteratorTrainingLooprH   GeneratorLikeTrainingLoopr
   ArrayLikeTrainingLoop)r.   r   r3   r3   r4   _select_training_loopu  s$    


zModel._select_training_loopr=           Tr   
   c                 K   s   |    tjdd d|v r6td |d}|rJtdt	| | 
  | d | |}|j| |||||||||	|
||||||||dS )a#  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)`.
            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 symbolic tensors, 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: 0, 1, or 2. Verbosity mode.
                0 = silent, 1 = progress bar, 2 = one line per epoch.
                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`.
            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_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.
                `validation_data` will override `validation_split`.
                `validation_data` could be:
                  - tuple `(x_val, y_val)` of Numpy arrays or tensors
                  - tuple `(x_val, y_val, val_sample_weights)` of Numpy arrays
                  - dataset
                For the first two cases, `batch_size` must be provided.
                For the last case, `validation_steps` could be provided.
            shuffle: Boolean (whether to shuffle the training data
                before each epoch) or str (for 'batch').
                '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.
                In this case you should make sure to specify
                `sample_weight_mode="temporal"` in `compile()`. 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.  This argument is not supported with array inputs.
            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 a infinite dataset, it will run into a
                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_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. If 0, will execute the generator on the main
                thread.
            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.
            **kwargs: Used for backwards compatibility.

        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: If the model was never compiled.
            ValueError: In case of mismatch between the provided input data
                and what the model expects.
        fitTnb_epochz;The `nb_epoch` argument in `fit` has been renamed `epochs`.z Unrecognized keyword arguments: )xy
batch_sizeepochsverbose	callbacksvalidation_splitvalidation_datashuffleclass_weightsample_weightinitial_epochsteps_per_epochvalidation_stepsvalidation_freqmax_queue_sizeworkersuse_multiprocessing)r^   r   r   r   ra   rl   rm   r_   rc   str_assert_compile_was_called_check_call_argsr   r   )r.   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r0   funcr3   r3   r4   r     sD     ,


z	Model.fitc                 C   sV   |    tjdd |   | d | |}|j| |||||||||	|
dS )aB  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.
              - A generator or `keras.utils.Sequence` instance.
            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 symbolic tensors, 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.
                In this case you should make sure to specify
                `sample_weight_mode="temporal"` in `compile()`. 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. If 0, will execute the generator on the main thread.
            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.

        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:
            ValueError: in case of invalid arguments.
        evaluateT)
r   r   r   r   r   stepsr   r   r   r   )	r^   r   r   r   ra   r   r   r   r   )r.   r   r   r   r   r   r   r   r   r   r   r   r3   r3   r4   r   m  s$    [

zModel.evaluatec	           
      C   sJ   |    tjdd | d | |}	|	j| ||||||||d	S )a  Generates output predictions for the input samples.

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

        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.
            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 symbolic tensors, 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. If 0, will execute the generator on the main thread.
            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.


        Returns:
            Numpy array(s) of predictions.

        Raises:
            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.
        predictT)r   r   r   r   r   r   r   r   )r^   r   r   r   ra   r   r   r   )
r.   r   r   r   r   r   r   r   r   r   r3   r3   r4   r     s    A

zModel.predictc                 C   s.   |   }|D ]}|  q| jr*t|  dS )zResets the state of metrics.N)_get_training_eval_metricsreset_stater    r   _reset_metrics)r.   r   r   r3   r3   r4   reset_metrics.  s
    
zModel.reset_metricsc           
      C   s  |    | d | jr*tj r*td| j||||dd\}}}| jsP| jrt	j
| |||| jd}|d |d  |d  }d	d
 |D }n`t| }|t|pg  t|pg  }	tt ts|	dg7 }	| j|d |   | |	}|r|   t|dkr|d S |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.
              - A `tf.data` dataset.
            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, `y` should not be specified
              (since targets will be obtained from the iterator).
            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. In this case you should make sure to specify
              sample_weight_mode="temporal" in compile(). This argument is not
              supported when `x` is a dataset.
            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.

        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:
          ValueError: In case of invalid user-provided arguments.
        train_on_batchzU`train_on_batch` is not supported for models distributed with tf.distribute.Strategy.T)r   r   extract_tensors_from_datasetsample_weightsoutput_loss_metrics
total_lossoutput_lossesr   c                 S   s   g | ]}t |qS r3   _non_none_constant_valuerT   r   r3   r3   r4   r     r   z(Model.train_on_batch.<locals>.<listcomp>r   r=   r   )r   r   r    r"   r&   rn   rq   _standardize_user_datarH   r   r   _output_loss_metricsr   ModelInputsas_listr   rP   r   symbolic_learning_phaseint_update_sample_weight_modes_make_train_functionr   r   r   )
r.   r   r   r   r   r   r   output_dictr   insr3   r3   r4   r   8  sV    2


zModel.train_on_batchc           	      C   s   |    | d | jr*tj r*td| j|||dd\}}}| jsN| jrt	j
| |||| jd}|d |d  |d  }d	d
 |D }nHt| }|t|pg  t|pg  }| j|d |   | |}|r|   t|dkr|d S |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.
              - A `tf.data` dataset.
            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 `y` should
              not be specified (since targets will be obtained from the
              iterator).
            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.
                In this case you should make sure to specify
                sample_weight_mode="temporal" in compile(). This argument is not
                supported when `x` is a dataset.
            reset_metrics: If `True`, the metrics returned will be only for this
              batch. If `False`, the metrics will be statefully accumulated
              across batches.

        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:
            ValueError: In case of invalid user-provided arguments.
        test_on_batchzT`test_on_batch` is not supported for models distributed with tf.distribute.Strategy.T)r   r   r   r   r   r   c                 S   s   g | ]}t |qS r3   r   r  r3   r3   r4   r     r   z'Model.test_on_batch.<locals>.<listcomp>r  r=   r   )r   r   r    r"   r&   rn   rq   r  rH   r   r  r  r   r  r  r   r
  _make_test_functionr   r   r   )	r.   r   r   r   r   r   r  r   r   r3   r3   r4   r    sJ    '

zModel.test_on_batchc                 C   s   |  d | jr"tj r"td| j|dd\}}}| jsB| jrvt	|}t
|tjjrnt|dkrn|d }| |S |   | |}t|dkr|d S |S )aL  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).
              - A `tf.data` dataset.

        Returns:
            Numpy array(s) of predictions.

        Raises:
            ValueError: In case of mismatch between given number of inputs and
              expectations of the model.
        predict_on_batchzW`predict_on_batch` is not supported for models distributed with tf.distribute.Strategy.T)r   r=   r   )r   r    r"   r&   rn   rq   r  rH   r   cast_if_floating_dtyperP   collectionsabcSequencer   _make_predict_functionr   )r.   r   r   _r   r3   r3   r4   r    s,    


zModel.predict_on_batchc                 C   s4   t jdd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.   
stacklevel)r   r   r   r   r   r   r   r   r   r   r   r   r   )warningswarnr   )r.   	generatorr   r   r   r   r   r   r   r   r   r   r   r   r   r3   r3   r4   fit_generator.  s(    zModel.fit_generatorc              	   C   s0   t jdd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.r  r  evaluate_generatorr   r   r   r   r   r   )r  r  r   r   r.   r  r   r   r   r   r   r   r3   r3   r4   r  \  s    
zModel.evaluate_generatorc              	   C   s&   t jdd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   r3   r3   r4   predict_generator~  s    zModel.predict_generatorc                 C   sv   | j j}|jr&|jdt|j  }n|j}d|v r>|d t|dkrr|dd }td| d t| d dS )z.Check that `call` has only one positional arg.Nr	   r  zModels passed to `z\` can only have `training` and the first argument in `call` as positional arguments, found: .)
_call_specfull_argspecdefaultsr/   r   removerB   r   )r.   method_namefullargspecpositional_args
extra_argsr3   r3   r4   r     s&    
zModel._check_call_argsc                 C   s   t |ttfr dd |D | _nt|| _| jjdkrt | jtj	st | jtrdt
d| j | jt | jtjst
d| j| jf t	| j| _dS )zSets self.optimizer.

        Sets self.optimizer to `optimizer`, potentially wrapping it with a
        LossScaleOptimizer.

        Args:
          optimizer: The optimizer(s) to assign to self.optimizer.
        c                 S   s   g | ]}t |qS r3   )r   getrS   r3   r3   r4   r     r   z(Model._set_optimizer.<locals>.<listcomp>mixed_float16z{When the "mixed_float16" dtype policy is used, you can only pass a single optimizer. Using policy %s and got optimizers: %sz"optimizer" must be an instance of tf.keras.optimizers.Optimizer when a dype policy with a loss scale  used, but got: %s. Using policy: %sN)rP   r   tuplerW   r   r+  _dtype_policyrX   r   LossScaleOptimizerrB   r   OptimizerV2)r.   rW   r3   r3   r4   re     s,    	
zModel._set_optimizerc                 C   s&   t |\}}}| j|||||ddS )z%Unpack and check the validation data.r   )r   r   r   
steps_name)r   unpack_validation_datar  )r.   r   r   r   val_xval_yval_sample_weightsr3   r3   r4   _prepare_validation_data  s    zModel._prepare_validation_datac                 C   s^   | j rZ|rtd|rtd|r*td|r6tdt| rZ| jrR| jrR| jsZtdd S )Nz@sample_weight_mode is not supported with tf.distribute.Strategy.z>weighted_metrics is not supported with tf.distribute.Strategy.z<target_tensors is not supported with tf.distribute.Strategy.zNWe currently do not support enabling `run_eagerly` with distribution strategy.zWe currently do not support distribution strategy with a `Sequential` model that is created without `input_shape`/`input_dim` set in its first layer or a subclassed model.)r    rq   rB   r   is_distributing_by_cloningr   r   r   )r.   rH   rx   r   r   r3   r3   r4   rr     s:    z7Model._validate_compile_param_for_distribution_strategyc                 C   s   | j rdd | jD S |d urt|tr0|g kst|trdt|t| jkrtdt| j|f qt|trt|	 
| j}|rtdj|t| jdg }| jD ]}|||d  q|}qt|r|g}qtd|ndd | jD }|S )Nc                 S   s   g | ]}d qS r5   r3   rT   r  r3   r3   r4   r     r   z<Model._process_target_tensor_for_compile.<locals>.<listcomp>zWhen passing a list as `target_tensors`, it should have one entry per model output. The model has %s outputs, but you passed target_tensors=%sz`Unknown entry in `target_tensors` dictionary: "{name}". Only expected the following keys: {keys})rX   rb   zTExpected `target_tensors` to be a list or tuple or dict or a single tensor, but got:c                 S   s   g | ]}d qS r5   r3   r8  r3   r3   r4   r   =  r   )rH   r   rP   r   r   r   rB   dictra   rb   
differenceformatr   r   r+  r"   	is_tensorrc   )r.   r   unexpected_target_tensor_namestmp_target_tensorsrX   r3   r3   r4   r     sN    



	z(Model._process_target_tensor_for_compilec                 C   s<   t | j| |   | || d | _|   | j| _d S r5   )	r   r   r{   _prepare_sample_weightsr   r   r   r   r   )r.   r   r   rx   r3   r3   r4   r   @  s    zModel._compile_eagerlyc                 C   sP   | j s
dS |r:tdd |D r:| jD ]}|jp2d|_q&n| jD ]
}d|_q@dS )a  Updates sample weight modes based on training/eval inputs.

        Sample weight placeholders will be created for all or no outputs
        based on whether sample_weight is provided for any output.

        If model contains `_sample_weight_modes` we check if the input
        `sample_weights` corresponds to the sample weight modes.
          1. Set sample weight mode to be 'temporal' for output i, if `compile`
            sample_weight_mode was set to `temporal` and sample weight inputs
            are given for one or more outputs.
          2. Set sample weight mode to be 'samplewise' for output i, if
            `compile` sample_weight_mode was not set and sample weight inputs
            are given for one or more outputs.
          3. Reset sample weight mode to None for output i if sample weight mode
            was set but there is no sample weight input.

        Args:
          sample_weights: List of sample weights of the same length as model
            outputs or None.
        Nc                 s   s   | ]}|d uV  qd S r5   r3   )rT   sr3   r3   r4   rV   g  r   z4Model._update_sample_weight_modes.<locals>.<genexpr>
samplewise)r   rf   r{   rx   )r.   r   r   r3   r3   r4   r
  P  s    

z!Model._update_sample_weight_modesc                 C   s.   | j s
dS tdd | jD }|r*|   |S )NFc                 s   s   | ]}|  V  qd S r5   )sample_weights_mismatchr   r3   r3   r4   rV   s  s   zEModel._recompile_weights_loss_and_weighted_metrics.<locals>.<genexpr>)r   rf   r{   r   )r.   	recompiler3   r3   r4   ,_recompile_weights_loss_and_weighted_metricsp  s    z2Model._recompile_weights_loss_and_weighted_metricsc              	   C   s   t   ` |dur | | | | |  }| j| j| j| 	 | j
|dd | || _W d   n1 sr0    Y  dS )aS  Compiles the model loss and weighted metric sub-graphs.

        This may be used to set graph tensors as sample weights (instead of
        creating placeholders). This functionality is necessary for
        `tf.keras.estimator.model_to_estimator`, which calls Keras models in a
        v1 graph, and creates iterator tensors for inputs, targets, and sample
        weights.

        Args:
          sample_weights: List of tensors to use as the sample weights. Must be
            the same length as the number of outputs. If left as `None`,
            placeholders are used instead.
        NT)r[   r\   r   r]   return_weighted_metrics)r   r   r   r
  r?  r   r   r   r   r   r   _prepare_total_lossr   )r.   r   r]   r3   r3   r4   r   {  s    

z0Model._compile_weights_loss_and_weighted_metricsc                 C   s   dd | j D S )a  Boolean mask for whether the target in the output list should be skipped.

        If the loss function corresponding to a model output is None, then this
        output will be skipped during total loss calculation and feed targets
        preparation.

        Returns:
          A boolean list for whether the corresponding target in the output list
          should be skipped during loss calculation.
        c                 S   s   g | ]}|d u qS r5   r3   )rT   r   r3   r3   r4   r     r   z4Model._prepare_skip_target_masks.<locals>.<listcomp>)r   r6   r3   r3   r4   r     s    z Model._prepare_skip_target_masksc                 C   s   dd | j D S )z-Returns masks corresponding to model outputs.c                 S   s   g | ]}t |d dqS )_keras_maskN)getattr)rT   r   r3   r3   r4   r     r   z/Model._prepare_output_masks.<locals>.<listcomp>)r   r6   r3   r3   r4   r     s    zModel._prepare_output_masksc              
   C   s  | j rtdg }td t| j|D ]R\}}| r@q,|jj}|j	}|j
}|j}| }	|j}
t|	 |durt||j}|
du r|}
ntj||
d\}}}
|
|9 }
t|dr
|||}tj||
tjjd}|j}|tjjkrtjj}tj||d}n||||
d}tjj}W d   n1 s60    Y  t| jdkrZ|| |tjjkrrt|}| ||  q,|s| j!st"d	| #d| #| j$ }|rt%t&|}| t| t&|}|rt%|}nd
}W d   n1 s
0    Y  |S )a  Computes total loss from loss functions.

        Args:
            masks: List of mask values corresponding to each model output.

        Returns:
            A list of loss weights of python floats.

        Raises:
            TypeError: If model run_eagerly is True.
        zEtotal loss can not be computed when compiled with run_eagerly = True.rv   Nr   	reduction)r   rJ  )rJ  r=   z@The model cannot be compiled because it has no loss to optimize.r   )'rH   rc   r   
name_scoper   r{   r   training_targettargetoutputloss_fnloss_weightr   r   r"   castdtyper   squeeze_or_expand_dimensionsr   callcompute_weighted_lossReductionV2NONErJ  AUTOSUM_OVER_BATCH_SIZEreduce_weighted_lossr   r   output_loss_metricscale_loss_for_distributionr   r   rB   get_losses_forr   add_ncast_losses_to_common_dtype)r.   r]   	loss_listr   masky_truey_predrO  rP  r   r   r  per_sample_lossesweighted_lossesloss_reductionoutput_losscustom_lossestotal_custom_lossr   r3   r3   r4   rF    s    
"

$zModel._prepare_total_lossc                 C   s0   t | dr| jr| jS t | dr,| jr,| jS | S )z*Returns the Callback Model for this Model._replicated_modelcallback_model)r   rj  rk  r6   r3   r3   r4   _get_callback_model,  s
    zModel._get_callback_modelc                 C   s*   | j |d }t|| _| j|  d S )Nr   )r    unwrapDistributedCallbackModelrj  set_original_model)r.   grouped_modelfirst_replicated_modelr3   r3   r4   _make_callback_model;  s    zModel._make_callback_modelc                 C   s  t |tjjjjtjjtjfs(t	|rD|dur@t
d||dS | jddd}t|d}|rt|}|dur| jrt| jr| jj}nd}|dur|| dkrt
d|||| }||krt
d||t |tjjtjjjjtjjfrrtjjtjtjjj|d d j}	|	durr|	| dkrPt
d	|	||	| }
|
|krrt
d
|
||du r|| }|du r|du rd}|S )a  Validates that the `batch_size` provided is consistent with InputLayer.

        It's possible that the user specified a static batch size in their
        InputLayer. If so, this method checks the provided `batch_size` and `x`
        arguments are consistent with this static batch size. Also, if
        `batch_size` is `None`, this method will attempt to infer the batch size
        from the static batch size of the InputLayer. Lastly, ValueError will be
        raised if `x` is a tf.data.Dataset and `batch_size` is specified as we
        expect users to provide batched datasets.

        Args:
          batch_size: The batch_size provided as an argument to
            fit/evaluate/predict.
          steps: The steps provided as an argument to fit/evaluate/predict.
          x: The data passed as `x` to fit/evaluate/predict.

        Returns:
          The validated batch_size, auto-inferred from the first layer if not
          provided.
        NzlThe `batch_size` argument must not be specified for the given input type. Received input: {}, batch_size: {}Fr   r=   r   zOThe `batch_size` argument ({}) must be divisible the by number of replicas ({})zhThe `batch_size` argument value {} is incompatible with the specified batch size of your Input Layer: {}zXThe batch output shape of your `Dataset` {} cannot be divisible by number of replicas {}z{The batch output shape of your `Dataset` is {}, which is incompatible with the specified batch size of your Input Layer: {}    )rP   r"   r#   r$   r   Datasetr   r  r   isgeneratorrB   r;  r   nextr   get_static_batch_sizer    r   global_batch_size_supportednum_replicas_in_syncr   	Dimensionrg   rh   get_output_shapesr   )r.   r   r   r   layersfirst_layerstatic_batch_sizenum_splits_for_dsper_replica_batch_sizeds_batch_sizeds_per_replica_batch_sizer3   r3   r4   _validate_or_infer_batch_sizeF  s    




	
	
z#Model._validate_or_infer_batch_sizec                 C   sn   |dur6t |t | jkrFtdt | jt |ndgt | j }t| j|D ]\}}|||j qRdS )z*Sets sample weight attribute on the model.Nz^Provided sample weights must have same length as the number of outputs. Expected: {}, got: {}.)r   r{   rB   r;  r   populate_sample_weightrx   )r.   r   r   weightr3   r3   r4   r?    s    zModel._prepare_sample_weightsc                 C   s~   g }| j D ]4}|du s"|jjdu r.|d q
||j  q
tj|| j|| j| j	d| _
tj|| j|| j| j	dd| _dS )zBCaches metric name and function attributes for every model output.N)rK   T)rK   is_weighted)r   shaperankr   r  r   collect_per_output_metric_infor   r   r`   _per_output_metrics_per_output_weighted_metrics)r.   r   r   output_shapesrN  r3   r3   r4   r     s,    

z%Model._cache_output_metric_attributesc                 C   sX   t | jdkr,t|dds,d| j| |f }d}|}|| jv rTd||f }|d7 }q4|S )a'  Makes the metric name unique.

          If there are multiple outputs for which the metrics are calculated,
          the metric names have to be made unique by appending an integer.

        Args:
          metric_name: Metric name that corresponds to the metric specified by
            the user. For example: 'acc'.
          metric_fn: The Metric object.
          output_index: The index of the model output for which the metric name
            is being added.

        Returns:
          string, name of the model's unique metric name
        r=   r`   Fz%s_%sz%s_%d)r   r   rH  r   )r.   metric_name	metric_fnoutput_indexjbase_metric_namer3   r3   r4   _add_unique_metric_name  s    

zModel._add_unique_metric_namec                 C   s
   g | _ dS )z$Initialized model metric attributes.N)r   r6   r3   r3   r4   r     s    zModel._init_metric_attributesc                 C   sF   t  }| D ]0\}}| |||}||_|||< | j| q|S )at  Sets the metric attributes on the model for the given output.

        Args:
          metrics_dict: A dict with metric names as keys and metric fns as
            values.
          output_index: The index of the model output for which the metric
            attributes are added.

        Returns:
          Metrics dict updated with unique metric names as keys.
        )r  OrderedDictitemsr  _namer   r   )r.   metrics_dictr  updated_metrics_dictr  r  r3   r3   r4   !_set_per_output_metric_attributes  s    z'Model._set_per_output_metric_attributesc                 C   s   g }g }t | jD ]b\}}| rD|| j|  || j|  q|| | j| | || | j| | qt| jdkr| jD ]}| stj	|
 d|_q|| _|| _dS )zBSets the metric attributes on the model for all the model outputs.r=   r   N)	enumerater{   r   r   r  r  r  r   metrics_moduleMeanr   r[  )r.   updated_per_output_metrics#updated_per_output_weighted_metricsir   r3   r3   r4   r   4  s6    

	

zModel._set_metric_attributesc           
   	   C   sb   g }|  D ]P\}}t|. tj|||||d}	||	 W d   q1 sR0    Y  q|S )a  Calls metric functions for a single output.

        Args:
          metrics_dict: A dict with metric names as keys and metric fns as
            values.
          y_true: Target output.
          y_pred: Predicted output.
          mask: Computed mask value for the current output.
          weights: Weights to be applied on the current output.

        Returns:
          A list of metric result tensors.
        )weightsra  N)r  r   rK  r   call_metric_functionr   )
r.   r  rb  rc  ra  r  metric_resultsr  r  metric_resultr3   r3   r4   _handle_per_output_metricsW  s    
*z Model._handle_per_output_metricsc                 C   s   |pdgt | }g }td tt |D ]}	||	 r<q.|rH||	 nd}
|rX||	 nd}|rh||	 nd}|st|s|| | j|	 ||
| |s|r.|| j| j|	 ||
||r||	 ndd q.W d   n1 s0    Y  |S )a  Handles calling metric functions.

        Args:
          outputs: List of outputs (predictions).
          targets: List of targets.
          skip_target_masks: Optional. List of boolean for whether the
            corresponding target should be ignored or not.
          sample_weights: Optional list of sample weight arrays.
          masks: List of computed output mask values.
          return_weighted_metrics: Flag that indicates whether weighted metrics
            should be computed instead of unweighted metrics. This flag is
            ignored when `return_weighted_and_unweighted_metrics` is enabled.
          return_weighted_and_unweighted_metrics: Flag that is used to indicate
            whether both weighted and unweighted metrics should be computed.
            When this is not enabled, we use `return_weighted_metrics` param to
            indicate whether weighted or unweighted metrics should be returned.

        Returns:
          A list of metric result tensors.
        Fr   N)r  )r   r   rK  ranger   r  r  r  )r.   r   r[   r\   r   r]   rE  &return_weighted_and_unweighted_metricsr  r  rN  rM  output_maskr3   r3   r4   r   p  sJ     	
$zModel._handle_metricsc                 C   s6   t | dsdS t| jt| jkr2ttjdd dS )a[  Check trainable weights count consistency.

        This will raise a warning if `trainable_weights` and
        `_collected_trainable_weights` are inconsistent (i.e. have different
        number of parameters).
        Inconsistency will typically arise when one modifies `model.trainable`
        without calling `model.compile` again.
        r   NzDiscrepancy between trainable weights and collected trainable weights, did you set `model.trainable` without calling `model.compile` after ?r=   )r   r   r   r   rl   log_first_nWARNr6   r3   r3   r4   $_check_trainable_weights_consistency  s    	

z*Model._check_trainable_weights_consistencyc              	   C   s  |   }|   t| jtr$tdt| dd d u s:|r|  }| | j	 | j
| j | j }tt ts||t g7 }t   tdB | jj| j| jd}|| d 7 }|| | j7 }W d    n1 s0    Y  |  }dd |D }W d    n1 s0    Y  td@ tj|| jg| f|dd| j}t| d| W d    n1 sn0    Y  | | d S )Nz:The `optimizer` in `compile` should be a single optimizer.r   r	   )paramsrv   c                 S   s   g | ]}t |d r|jqS _call_resultr   r  r   r3   r3   r4   r     s   
z.Model._make_train_function.<locals>.<listcomp>updatesrX   )rD  r  rP   rW   r   rB   rH  r|   _set_trainable_stater}   _feed_inputs_feed_targets_feed_sample_weightsr   r  r	  r   r   rK  get_updatesr   r   get_updates_forr   r   functionrd   setattr)r.   has_recompiledcurrent_trainable_stater   r  r   metrics_tensorsfnr3   r3   r4   r    sR    .&
,zModel._make_train_functionc                 C   s   |   }t| dd d u s|r| j| j | j }t  & |  }dd |D }W d    n1 sf0    Y  t	dF | j
}tj|| jg| f|dd| j}t| d| W d    n1 s0    Y  d S )Nr   c                 S   s   g | ]}t |d r|jqS r  r  r   r3   r3   r4   r   	  s   
z-Model._make_test_function.<locals>.<listcomp>
evaluationr  )rD  rH  r  r  r  r   r   r   r   rK  state_updatesr  r   rd   r  )r.   r  r   r   r  r  r  r3   r3   r4   r  	  s2    $
zModel._make_test_functionc                 C   s|   t | dsd | _| jd u rx| j}t| di }ttj0 tj|| j	f| j
dd|| _W d    n1 sn0    Y  d S )Nr   rd   r  )r   r   r  rH  r   rK  r   PREDICTr  r   r  )r.   r   r0   r3   r3   r4   r  (	  s    

zModel._make_predict_functionc                 C   sL   |t jkr|   | jS |t jkr0|   | jS |t jkrH|   | j	S d S r5   )
r   TRAINr  r   TESTr  r   r  r  r   )r.   moder3   r3   r4   _make_execution_function9	  s    


zModel._make_execution_functionc
                 C   s  |rt d|dur0| r0t| jr0t dt|tjjrL|rLt	
| | j}
|
 @ tjj rpd}nt }tj|d }t|tjrjt|}|durt|}|durt|}|||f}q||f}n|}|
jj||d}|r|td|d }|dkr||}|	 o*|
jj}t|
rZ|sZ|jd }|| dkrZd	}|j||d
}n$t|tjjs~J t	|||| W d   n1 s0    Y  |S )a  Runs validation checks on input and target data passed by the user.

        This is called when using tf.distribute.Strategy to train, evaluate or
        serve the model.

        Args:
          x: Input data. A numpy array or `tf.data` dataset.
          y: Target data. A numpy array or None if x is a `tf.data` dataset.
          sample_weight: An optional sample-weight array passed by the user to
            weight the importance of each sample in `x`.
          class_weight: An optional class-weight array by the user to
            weight the importance of samples in `x` based on the class they
            belong to, as conveyed by `y`.
          batch_size: Integer batch size. If provided, it is used to run
            additional validation checks on stateful models.
          validation_split: Float between 0 and 1.
            Fraction of the training data to be used as validation data.
          shuffle: Boolean whether to shuffle the training data before each
            epoch.
          epochs: Integer epochs. If > 1, repeat the numpy training data epochs
            times when converting to training dataset.
          allow_partial_batch: Boolean whether to enforce that all batches have
            the same size.

        Returns:
          Dataset instance.

        Raises:
          ValueError: In case of invalid user-provided data.
          RuntimeError: If the model was never compiled.
        zL`class_weight` is currently not supported when using tf.distribute.Strategy.NzB`sample_weight` is currently not supported when using TPUStrategy.r   )sessioni      r=   T)drop_remainder)rq   allr   r>   r    rP   r"   r   rt  r   verify_dataset_shuffledr:   r#   r$   r%   get_sessionrg   rh   npndarrayr   list_to_tupler?   experimental_make_numpy_datasetr   maxrepeat"experimental_require_static_shapesr  batchvalidate_dataset_input)r.   r   r   r   r   r   r   r   r   allow_partial_batchr9   r  first_x_valuein_tupledsr  dataset_sizer3   r3   r4   #_distribution_standardize_user_dataD	  sj    +







	
$z)Model._distribution_standardize_user_datar   c              
   C   sT  t |tjjjjtjjfrRt||||	 |
r8t| d}|rt	|\}}}n@t |tjjjj
rt||||	 |}t|\}}}d}nd}|rt||| | js| ||\}}}d}ng }t | jt}d}|}d}| js| jr| |||| d}| j}|s:|r:|r:|s:tdd |D r:g g dfS | j||||||||dS )a  Runs validation checks on input and target data passed by the user.

        Also standardizes the data to lists of arrays, in order.

        Also builds and compiles the model on the fly if it is a subclassed
        model that has never been called before (and thus has no
        inputs/outputs).

        This is a purely internal method, subject to refactoring at any time.

        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.
          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, `y` should not
            be specified (since targets will be obtained from the iterator).
          sample_weight: An optional sample-weight array passed by the user to
            weight the importance of each sample in `x`.
          class_weight: An optional class-weight array by the user to
            weight the importance of samples in `x` based on the class they
            belong to, as conveyed by `y`. If both `sample_weight` and
            `class_weight` are provided, the weights are multiplied.
          batch_size: Integer batch size. If provided, it is used to run
            additional validation checks on stateful models.
          check_steps: boolean, True if we want to check for validity of `steps`
            and False, otherwise. For example, when we are standardizing one
            batch of data for train_on_batch/predict_on_batch/test_on_batch
            APIs, `steps` value is not required and we should not check for its
            validity in these cases.
          steps_name: The public API's parameter name for `steps`.
          steps: Integer or `None`. Total number of steps (batches of samples)
            to execute.
          validation_split: Float between 0 and 1.
            Fraction of the training data to be used as validation data.
          shuffle: Boolean whether to shuffle the training data before each
            epoch.
          extract_tensors_from_dataset: Boolean. When `x` is a dataset instance,
            this indicates whether to extract actual tensors from the dataset or
            instead output the dataset instance itself.
            Set to True when calling from `train_on_batch`/etc.

        Returns:
          A tuple of 3: inputs (arrays or dicts, depending on whether `x` was a
          dict or not), target arrays, sample-weight arrays.  If the model's
          input and targets are symbolic, these lists are empty (since the model
          takes no user-provided data, instead the data comes from the symbolic
          inputs/targets).

        Raises:
          ValueError: In case of invalid user-provided data.
          RuntimeError: If the model was never compiled.
        TFc                 s   s   | ]}t |V  qd S r5   _is_symbolic_tensorr  r3   r3   r4   rV   U
  r   z/Model._standardize_user_data.<locals>.<genexpr>N)rH   dict_inputs
is_datasetr   r   )rP   r"   r#   r$   r   rt  r   r  r  r   r   unpack_iterator_inputcheck_steps_argumentr   _build_model_with_inputsr9  r   rW   _compile_from_inputsrH   rf   _standardize_tensors)r.   r   r   r   r   r   check_stepsr1  r   r   r   r   r  iterator
all_inputsy_inputr  is_build_calledis_compile_calledrH   r3   r3   r4   r  	  sz    J




zModel._standardize_user_datac	                 C   s  |r| j }	d }
n| js"| j}	d }
n| j}	| j}
t|tjjjj	tjj	fs\t
j||	|
ddd}t|tjj	rtjj|}t|tr|d }nrtjj|dd}tjj| jdd}g }t||D ]\}}|t|| qtjj||dd}dd }tj||}tjj|dd}tjj| jdd}t||D ]\}}tjj||dd q*|d urt
| j| j | j}| j}| js|d }n| j}t
j||d dd	d
}t
||}t
||}dd t||||D }| j st
!||| | jr|st
"|| j#| t$j%|||dd\}}}ng }d }| j&rf|rf|sf|d j'd | dkrft(dt)|d j'd  d |rt|tjjjj	tjj	fst*t|	|}|||fS )NFinput)check_batch_axisexception_prefixr   )expand_compositesc                 S   sB   t | r| jS t| dr4t| dr4t| j| jS t| S dS )z9Grab type_spec without converting array-likes to tensors.r  rR  N)	r   is_extension_type
_type_specr   r"   
TensorSpecr  rR  type_spec_from_value)r   r3   r3   r4   _type_spec_from_value
  s
    
z9Model._standardize_tensors.<locals>._type_spec_from_valueTrM  )shapesr  r  c                 S   s$   g | ]\}}}}t ||||qS r3   )r   standardize_weights)rT   refswcwr  r3   r3   r4   r   
  s   
z.Model._standardize_tensors.<locals>.<listcomp>)check_all_flatzzIn a stateful network, you should only pass inputs with a number of samples that can be divided by the batch size. Found: z samples)+input_names_is_graph_network_feed_input_names_feed_input_shapesrP   r"   r#   r$   r   rt  r   standardize_input_dataro   get_structurer-  rg   rh   r   r   r   _convert_scipy_sparse_tensorpack_sequence_asmap_structureassert_same_structurer   r{   rx   _feed_output_names_sample_weight_modes_feed_output_shapesstandardize_sample_weightsstandardize_class_weightsr    check_array_lengths#check_loss_and_target_compatibility_feed_loss_fnsr   handle_partial_sample_weightsstatefulr  rB   r   r9  )r.   r   r   r   rH   r  r  r   r   feed_input_namesfeed_input_shapesx_shapesflat_inputsflat_expected_inputsconverted_xabr  feed_output_namesfeed_sample_weight_modesfeed_output_shapesr   class_weightsr  r3   r3   r4   r  d
  s    



zModel._standardize_tensorsc                    s:  g }d} }t  tjjjjtjjfr6t \ }}t | t  t	t
fr^|t	 7 }n8t  trd}t  } fdd|D }n
|  |D ]}t|rtd|f qt |tjjjjtjjtjjjjfr
| jst | j dd }	tj|	 }
nt r"t }
n }
| |
 |||fS )zNBuild the model (set model inputs/outputs), mainly for subclass
        model.FTc                    s   g | ]} | qS r3   r3   )rT   kr   r3   r4   r     r   z2Model._build_model_with_inputs.<locals>.<listcomp>as  All SparseTensor and RaggedTensor inputs must be explicitly declared using a keras.Input() with sparse=True or ragged=True. We found an undeclared input %s. For Sequential models, please add a keras.Input() as your first Layer. For subclassed models, please call self._set_inputs() on your input set, which you can create using keras.Input() for each input to your model.c                 S   s   t | j| jS r5   )r"   r  r  rR  )r   r3   r3   r4   create_tensor_specC  s    z:Model._build_model_with_inputs.<locals>.create_tensor_spec)rP   r"   r#   r$   r   rt  r   r   validate_input_typesr   r-  r9  sortedrb   r   is_composite_or_composite_valuerB   r   r   r  rR  rg   r  has_tensors_set_inputs)r.   r   r[   processed_inputsis_dict_inputsorig_inputsr  rb   input_tensorr  cast_inputsr3   r  r4   r    sP    






zModel._build_model_with_inputsc                 C   s.  |d urXt |r t || j}t j||ddd t|ttfrN|t|7 }n
|| t	dd |D rt
dd |D stdt| d t| t|tjjjjtjjtjjjjf}|st rd }n0|d urt|ttfs|g}d	d
 |D }nd }| j| j| j| j| j| j|| j| j| jd	 d S )NFrM  )
allow_dict
field_namec                 s   s   | ]}t |V  qd S r5   r"   r<  r  r3   r3   r4   rV   `  r   z-Model._compile_from_inputs.<locals>.<genexpr>c                 s   s   | ]}t |V  qd S r5   r%  r  r3   r3   r4   rV   a  r   zODo not pass inputs that mix Numpy arrays and TensorFlow tensors. You passed: x=z; y=c                 S   s   g | ]}t |r|qS r3   r  r  r3   r3   r4   r   y  r   z.Model._compile_from_inputs.<locals>.<listcomp>)	rW   rv   r   r   rw   r   rx   rH   rI   )r   r  #cast_if_floating_dtype_and_mismatchr   r  rP   r   r-  r   rf   r  rB   r   r"   r#   r$   r   rt  r   r   rZ   rW   rv   ry   rz   rw   rx   rH   r,   )r.   r  rM  r   orig_targetr  r   r3   r3   r4   r  N  s^    



zModel._compile_from_inputsc                 C   s   |  | | |}|du r~i }| jrR|du rBtjj sBt }|durR||d< z| |fi |}W n t	y|   d}Y n0 | 
| dS )a  Set model's input and output specs based on the input data received.

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

        Args:
          inputs: Single array, or list of arrays. The arrays could be
            placeholders, Numpy arrays, data tensors, or TensorSpecs.
            - if placeholders: the model is built on top of these placeholders,
              and we expect Numpy data to be fed for them when calling
              `fit`/etc.
            - if Numpy data or TensorShapes: we create placeholders matching the
              TensorShapes or shapes of the Numpy arrays. We expect Numpy data
              to be fed for these placeholders when calling `fit`/etc.
            - if data tensors: the model is built on top of these tensors.
              We do not expect any Numpy data to be provided when calling
              `fit`/etc.
          outputs: None, a data tensor, or a list of tensors. If None, the
            outputs will be determined by invoking `self.call()`, otherwise the
            provided value will be used.
          training: Boolean or None. Only relevant in symbolic mode. Specifies
            whether to build the model's graph in inference mode (False),
            training mode (True), or using the Keras learning phase (None).
        Raises:
          ValueError: If dict inputs are passed to a Sequential Model where the
            first layer isn't FeatureLayer.
        Nr	   )_set_save_spec_set_input_attrs_expects_training_argr"   r#   r$   r%   r   learning_phaserq   _set_output_attrs)r.   r   r   r	   r0   r3   r3   r4   r    s"    



zModel._set_inputsc                 C   s@  | j rtd| jjdkr| jst|rFdt|j	 dd  }ndt
|tjrldt|	 dd  }n>t
|trt| jd stdd}ndt|jdd  }|| _| |}t|}| }|jdd	| _ | | _g | _g | _g | _| D ]<\}}t|r| j| | j| | jt| q|S )
z3Sets attributes related to the inputs of the Model.zModel inputs are already set.
Sequentialr5   r=   Nr   zpPassing a dictionary input to a Sequential Model which doesn't have FeatureLayer as the first layer is an error.T)return_single_as_list)r   rB   r2   __name__r   r"   r<  r-  r  r  rP   TensorShaper9  r   is_feature_layerr|  _build_input_shape_maybe_cast_inputsr  get_symbolic_inputsget_input_namesr  r  r  r  as_dictr   is_placeholderr   	int_shape)r.   r   input_shapemodel_inputsr  r   r3   r3   r4   r)    s>    





zModel._set_input_attrsc                 C   s(   t j|}|| _t|| _d| _dS )z4Sets attributes related to the outputs of the Model.TN)r"   rg   rh   r   r   generic_output_namesr   r   )r.   r   r3   r3   r4   r,    s    zModel._set_output_attrsc                 C   s   dd | j D S )z(The output target tensors for the model.c                 S   s   g | ]}|  r|jjqS r3   )has_training_targetrL  rM  r   r3   r3   r4   r     s   z"Model._targets.<locals>.<listcomp>r{   r6   r3   r3   r4   r     s    zModel._targetsc                 C   s   dd | j D S )Nc                 S   s   g | ]}|  r|jjqS r3   )has_feedable_training_targetrL  rM  r   r3   r3   r4   r     s   z'Model._feed_targets.<locals>.<listcomp>r=  r6   r3   r3   r4   r    s    zModel._feed_targetsc                 C   s   dd | j D S )Nc                 S   s   g | ]}|  r|jqS r3   )r>  output_namer   r3   r3   r4   r     s   z,Model._feed_output_names.<locals>.<listcomp>r=  r6   r3   r3   r4   r     s    zModel._feed_output_namesc                 C   s   dd | j D S )Nc                 S   s   g | ]}|  r|jqS r3   )r>  feed_output_shaper   r3   r3   r4   r     s   z-Model._feed_output_shapes.<locals>.<listcomp>r=  r6   r3   r3   r4   r    s    zModel._feed_output_shapesc                 C   s   dd | j D S )Nc                 S   s   g | ]}|  r|jqS r3   )r>  rO  r   r3   r3   r4   r     s   z(Model._feed_loss_fns.<locals>.<listcomp>r=  r6   r3   r3   r4   r    s    zModel._feed_loss_fnsc                 C   s   dd | j D S )Nc                 S   s   g | ]
}|j qS r3   )rP  r   r3   r3   r4   r   '  r   z,Model._loss_weights_list.<locals>.<listcomp>r=  r6   r3   r3   r4   _loss_weights_list%  s    zModel._loss_weights_listc                 C   s   t | drdd | jD S d S )Nr{   c                 S   s   g | ]}|j d ur|j qS r5   )r[  r   r3   r3   r4   r   ,  s   
z.Model._output_loss_metrics.<locals>.<listcomp>)r   r{   r6   r3   r3   r4   r  )  s
    
zModel._output_loss_metricsc                 C   s   dd | j D S )Nc                 S   s   g | ]
}|j qS r3   rI  r   r3   r3   r4   r   5  r   z(Model.sample_weights.<locals>.<listcomp>r=  r6   r3   r3   r4   r   3  s    zModel.sample_weightsc                 C   s   dd | j D S )Nc                 S   s   g | ]
}|j qS r3   )rx   r   r3   r3   r4   r   9  r   z.Model._sample_weight_modes.<locals>.<listcomp>r=  r6   r3   r3   r4   r  7  s    zModel._sample_weight_modesc                 C   s   dd | j D S )Nc                 S   s   g | ]}|j d ur|j qS r5   rI  r   r3   r3   r4   r   =  s   
z.Model._feed_sample_weights.<locals>.<listcomp>r=  r6   r3   r3   r4   r  ;  s    zModel._feed_sample_weightsc                 C   s   | j dur| j ||S |S )aL  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()`.
          mode: The mode for running `model.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)_training_state"maybe_load_initial_epoch_from_ckpt)r.   r   r  r3   r3   r4   #_maybe_load_initial_epoch_from_ckptC  s
    
z)Model._maybe_load_initial_epoch_from_ckptc                 C   s4   g }| t| ddpg  | t| ddp,g  |S )zReturns all the metrics that are to be reported.

        This includes the output loss metrics, compile metrics/weighted metrics,
        add_metric metrics.
        r  Nr   )r   rH  r   r3   r3   r4   r   X  s    z Model._get_training_eval_metricsc                 C   s   | j stdd S )NzZYou must compile your model before training/testing. Use `model.compile(optimizer, loss)`.)_compile_was_calledRuntimeErrorr6   r3   r3   r4   r   c  s    z Model._assert_compile_was_calledc                 C   s,   | j }|stj rtj }|o*|j S )a  Method to infer if this `Model` is working in multi-worker settings.

        Multi-worker training refers to the setup where the training is
        distributed across multiple workers, as opposed to the case where
        only a local process performs the training. This function is
        used to infer for example whether or not a distribute coordinator
        should be run, and thus TensorFlow servers should be started for
        communication with other servers in the cluster, or whether or not
        saving/restoring checkpoints is relevant for preemption fault tolerance.

        Experimental. Signature and implementation are subject to change.

        Returns:
          Whether this model indicates it's working in multi-worker settings.
        )r    r"   r&   r'   r)   r?   r   r8   r3   r3   r4   r   o  s    
zModel._in_multi_worker_modec                 C   s
   t | S r5   )r   ModelSavedModelSaverr6   r3   r3   r4   _trackable_saved_model_saver  s    z"Model._trackable_saved_model_saverc                 C   s(   ~|    | j| j| j| j| jd}|S )N)rv   r   rw   rx   r   )r   rv   ry   rw   rx   rz   )r.   user_metricsr0   r3   r3   r4   _get_compile_args  s    zModel._get_compile_argsc                 C   s   | j S r5   )r-   r6   r3   r3   r4   rE    s    zModel._compile_was_called)FF)rG   NNNNNNN)NNNr=   r=   Nr   NTNNr   NNr=   r   r=   F)
NNNr=   NNNr   r=   F)Nr   NNr   r=   F)NNNT)NNT)Nr=   r=   NNNr=   Nr   r=   FTr   )NNr   r=   Fr   )NNr   r=   Fr   )N)N)N)N)NNNNFF)NNNNr   Fr=   F)
NNNNFr   Nr   FF)NN)NN)T)Ur/  
__module____qualname____doc__r   r7   r"   ri   rs    no_automatic_dependency_trackingr(   r<   rC   rZ   r   propertyr   r   rH   setterr   r   r   r   r   r   r  r  r  r  r!  r   re   r6  rr   r   r   r
  rD  r   r   r   rF  rl  rr  r  r?  r   r  r   r  r   r  r   r  r  r  r  r  r  r  r  r  r  r  r)  r,  r   r  r   r  r  rA  r  r   r  r  rD  r   r   r   rH  rJ  rE  __classcell__r3   r3   r1   r4   r   9   s  ?
9          0

,
+                  
 R          
r       
R    
m
V6             
1      
%      
 #%2
 &y

{
'$ 
      
H8!        
           
 )  
  K<
5
1








	




r   c                       sR   e Zd ZdZ fddZdd Zddd	Zdd
dZdddZ fddZ	  Z
S )rn  z=Model that is used for callbacks with tf.distribute.Strategy.c                    s   t    |j| _d S r5   )r   r   rW   )r.   modelr1   r3   r4   r     s    
z!DistributedCallbackModel.__init__c                 C   s
   || _ d S r5   )_original_model)r.   
orig_modelr3   r3   r4   ro    s    z+DistributedCallbackModel.set_original_modelTNc                 C   s   | j j|||d d S )N)rY   save_format)rj  save_weights)r.   rD   rY   rU  r3   r3   r4   rV    s    z%DistributedCallbackModel.save_weightsc                 C   s*   |   }| j| | jj|ddd d S )NTF)rY   include_optimizer)r<   rS  set_weightssave)r.   rD   rY   rW  distributed_model_weightsr3   r3   r4   rY    s
    zDistributedCallbackModel.saveFc                 C   s0   | j j|dd | j  }t| j j| | d S )NF)rE   )rS  rC   r<   r   rX  r    )r.   rD   rE   orig_model_weightsr3   r3   r4   rC     s    
z%DistributedCallbackModel.load_weightsc                    s&   |dvrt d| d  t |S )N)_setattr_tracking_layerszYou are accessing attribute zF of the DistributedCallbackModel that may not have been set correctly.)rl   rm   r   __getattr__)r.   itemr1   r3   r4   r^    s
    
z$DistributedCallbackModel.__getattr__)TN)TT)F)r/  rK  rL  rM  r   ro  rV  rY  rC   r^  rQ  r3   r3   r1   r4   rn    s   



rn  c                   @   s  e Zd ZdZd/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
edd Zejdd Zd0ddZedd Zejdd Zedd Zejdd Zedd Zejdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zed)d* Zd+d, Zd-d. ZdS )1r   a  A container for the training output/target and related entities.

    In the case of model with multiple outputs, there is a one-to-one mapping
    between model output (y_pred), model target (y_true), loss, metrics etc.
    By unifying these entities into one class, different entity can access
    information between each other, rather than currently access different list
    of attributes of the model.
    Nc	           	      C   s4   || _ || _|| _|| _|| _|| _|| _|| _dS )a  Initialize the _TrainingEndpoint.

        Note that the output and output_name should be stable as long as the
        model structure doesn't change. The training_target suppose to be
        mutable since the information is provided via `compile()`

        Args:
          output: the output tensor of the model.
          output_name: the unique name of the output tensor.
          loss_fn: the loss function for the output tensor.
          loss_weight: float, the weights for the loss.
          training_target: the _TrainingTarget for the model.
          output_loss_metric: the metric object for the loss function.
          sample_weight: the weights for how a sample is weighted during metric
            and loss calculation. Could be None.
          sample_weight_mode: string, 'temporal', 'samplewise' or None. The mode
            for how the sample_weight is populated.
        N)_output_output_name_loss_fn_loss_weight_training_target_output_loss_metric_sample_weight_sample_weight_mode)	r.   rN  r?  rO  rP  rL  r[  r   rx   r3   r3   r4   r     s    z_TrainingEndpoint.__init__c                 C   s   | j S r5   )r`  r6   r3   r3   r4   rN    s    z_TrainingEndpoint.outputc                 C   s   | j S r5   )ra  r6   r3   r3   r4   r?    s    z_TrainingEndpoint.output_namec                 C   s   t | jS r5   )r   r8  rN  r6   r3   r3   r4   r    s    z_TrainingEndpoint.shapec                 C   s   | j S r5   rb  r6   r3   r3   r4   rO    s    z_TrainingEndpoint.loss_fnc                 C   s   | j S r5   rc  r6   r3   r3   r4   rP    s    z_TrainingEndpoint.loss_weightc                 C   s
   || _ d S r5   ri  r   r3   r3   r4   rP    s    c                 C   s   | j S r5   rd  r6   r3   r3   r4   rL    s    z!_TrainingEndpoint.training_targetc                 C   s
   || _ d S r5   rj  r   r3   r3   r4   rL    s    Fc                 C   s   |   rtd|r(tdddd| _dS |  r<td| _nz|durXt|sXd}d}nd}d}|du rtj	| j
t| j}tjt| j| jd t| j|d}t|||d| _dS )a  Create training_target instance and update the self.training_target.

        Note that the input target should just be a tensor or None, and
        corresponding training target will be created based on the output and
        loss_fn.

        Args:
          target: the target tensor for the current output. Could be None.
          run_eagerly: boolean, whether the model is in run_eagerly mode.

        Raises:
          ValueError if the training_target field for the current instance has
          already been populated.
        zWThe training_target field for the _TrainingEndpoint instance has already been populatedNTF)feedableskip_target_weights_target)ndimrX   sparserR  )r<  rB   _TrainingTargetrL  r   r   r7  r   LABEL_DTYPES_FOR_LOSSESr+  rO  rR  rN  placeholderr   r  r?  	is_sparse)r.   rM  rH   rk  rl  target_dtyper3   r3   r4   r     s>    
z(_TrainingEndpoint.create_training_targetc                 C   s   | j S r5   re  r6   r3   r3   r4   r[  S  s    z$_TrainingEndpoint.output_loss_metricc                 C   s
   || _ d S r5   ru  r   r3   r3   r4   r[  W  s    c                 C   s   | j S r5   rf  r6   r3   r3   r4   r   [  s    z_TrainingEndpoint.sample_weightc                 C   s
   || _ d S r5   rv  r   r3   r3   r4   r   _  s    c                 C   s   | j S r5   rg  r6   r3   r3   r4   rx   c  s    z$_TrainingEndpoint.sample_weight_modec                 C   s
   || _ d S r5   rw  r   r3   r3   r4   rx   g  s    c                 C   s
   | j d u S r5   rh  r6   r3   r3   r4   r   k  s    z$_TrainingEndpoint.should_skip_targetc                 C   s   |   p| jd u p| jjS r5   )r   rL  rl  r6   r3   r3   r4   should_skip_target_weightsn  s
    z,_TrainingEndpoint.should_skip_target_weightsc                 C   s
   | j d uS r5   )rL  r6   r3   r3   r4   r<  u  s    z%_TrainingEndpoint.has_training_targetc                 C   s   |    o| jd uo| jjS r5   )r   rL  rk  r6   r3   r3   r4   r>  x  s
    
z._TrainingEndpoint.has_feedable_training_targetc                 C   s   | j d ur| jd S d S )N_loss)rb  ra  r6   r3   r3   r4   r     s    

z_TrainingEndpoint.loss_namec                 C   s   |   sdS t| jtjr(| jjtjks6t| jtjrrt	 dkr^| j
d df| j
dd  S | j
dd d S n<t| jtjrt| jtjrtt| jjjddu rdS | j
S dS )z)The output shape for the feedable target.Nchannels_firstr   r=   r  )r=   )r>  rP   rO  r   LossFunctionWrapperr  sparse_categorical_crossentropySparseCategoricalCrossentropyr   image_data_formatr  LossrH  r/  r6   r3   r3   r4   r@    s$    z#_TrainingEndpoint.feed_output_shapec                 C   s(   | j dur| jdu p&| j du o&| jduS )z5Check if the sample weight and the mode match or not.N)rx   r   r6   r3   r3   r4   rB    s    z)_TrainingEndpoint.sample_weights_mismatchc                 C   s   |du r*|   s |du s t r*d| _dS |dv s6J |dkrPdgg}ddg}ndg}dg}|dur|j|std|j||| _n*tjj	j
tj|t d|| jd d| _dS )	z?Populate the sample weight and based on the sample weight mode.N)temporalrA  r  g      ?z8Received sample weight with shape {}. Expected shape {}.)rR  _sample_weights)r  rX   )rx  r"   r   rf  r  is_compatible_withrB   r;  r#   r$   placeholder_with_defaultconstantr   floatxr?  )r.   r   rx   default_valuer  r3   r3   r4   r    s8    
z(_TrainingEndpoint.populate_sample_weight)NNNNN)F)r/  rK  rL  rM  r   rO  rN  r?  r  rO  rP  rP  rL  r   r[  r   rx   r   rx  r<  r>  r   r@  rB  r  r3   r3   r3   r4   r     sZ        
&








8







r   c                   @   s>   e Zd ZdZdddZedd Zedd	 Zed
d ZdS )rp  a  Container for a target tensor (y_true) and its metadata (shape, loss...).

    Args:
      target: A target tensor for the model. It may be `None` if the
        output is excluded from loss computation. It is still kept as None
        since each output of the model should have a corresponding target. If
        the target is None, the rest of the attributes will be None as well.
      feedable: Boolean, whether the target is feedable (requires data to be
        passed in `fit` or `train_on_batch`), or not (model compiled with
        `target_tensors` argument).
      skip_target_weights: Boolean, whether the target should be skipped during
        weights calculation.
    FTc                 C   s   || _ || _|| _d S r5   )rm  	_feedable_skip_target_weights)r.   rM  rk  rl  r3   r3   r4   r     s    z_TrainingTarget.__init__c                 C   s   | j S r5   )rm  r6   r3   r3   r4   rM    s    z_TrainingTarget.targetc                 C   s   | j S r5   )r  r6   r3   r3   r4   rk    s    z_TrainingTarget.feedablec                 C   s   | j S r5   )r  r6   r3   r3   r4   rl    s    z#_TrainingTarget.skip_target_weightsN)FT)	r/  rK  rL  rM  r   rO  rM  rk  rl  r3   r3   r3   r4   rp    s   


rp  c                 C   s
   t | S r5   r%  )r   r3   r3   r4   r    s    r  c                 C   s   t durt | rt|rl|  }|j|j }}|j|j }}t	t
|dt
|dfd}t|||S tjj rtd|  S n| S dS )an  Handle scipy sparse tensor conversions.

    This method takes a value 'value' and returns the proper conversion. If
    value is a scipy sparse tensor and the expected input is a dense tensor,
    we densify 'value'. If value is a scipy sparse tensor and the expected input
    is a TF SparseTensor, we convert 'value' to a SparseTensor. If 'value' is
    not a scipy sparse tensor, or scipy is not imported, we pass it through
    unchanged.

    Args:
      value: An object that may be a scipy sparse tensor
      expected_input: The expected input placeholder.

    Returns:
      The possibly-converted 'value'.
    Nr=   zA SciPy sparse matrix was passed to a model that expects dense inputs. Please densify your inputs first, such as by calling `x.toarray().)r   r   rs  tocoorowcolr   r  r  concatenateexpand_dimsr"   SparseTensorr#   r$   r%   rB   toarray)r   expected_input
sparse_coor  r  r   r  indicesr3   r3   r4   r    s    

r  c                 C   sP   g }t | } | D ]8}t|tr>||j |t|j q||j q|S )zReturns list of metrics from the given layers.

    This will not include the `compile` metrics of a model layer.

    Args:
      layers: List of layers.

    Returns:
      List of metrics.
    )	r   filter_empty_layer_containersrP   r   r   r   r   r|  r   )r|  r   layerr3   r3   r4   r     s    

r   c                 C   s   t | }|d ur|S | S r5   )r"   get_static_value)r   constant_valuer3   r3   r4   r  1  s    
r  )<rM  r  r  numpyr  tensorflow.compat.v2r#   v2r"   kerasr   r   r   r  r   keras.distributer   r   keras.enginer   r	   training_libr
   r   r   r   r   r   keras.mixed_precisionr   keras.optimizersr   keras.optimizers.optimizer_v2r   Zkeras.savingr   keras.saving.saved_modelr   keras.utilsr   r   r   r   r   Zkeras.utils.mode_keysr   tensorflow.python.platformr   rl   scipy.sparser   ImportErrorr   rn  r   rp  r  r  r   r  r3   r3   r3   r4   <module>   s   
                        z0  !'