a
    Sic;                     @   s   d 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 ZdddZdddZdddZdddZdddZdS )z;Keras training and evaluation routines for eager execution.    N)backend)training_utils)training_utils_v1)loss_scale_optimizer)losses_utils)GradientTape)
tf_loggingc                 C   s<   t |d  ||| }W d    n1 s.0    Y  |S )N_loss)r   
name_scope)outputstargetsloss_fnoutput_nameloss r   Z/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/engine/training_eager_v1.py_eager_loss_fn   s    (r   c                    s   t j|}t jg }rdt jtkrJfdd jD }| j|||d  d}| fdd jD  |S )a  Calculates the metrics for each output of the given model.

    Args:
        model: The model on which metrics are being calculated.
        outputs: The outputs of the given model.
        targets: The predictions or targets of the given model.
        sample_weights: Optional list of sample weights for each output.
        masks: Optional list of masks for each output.

    Returns:
        Returns the metric results for each output of the model.
    c                    s"   g | ]}|d u rd n  dqS )Nr   )pop.0t)r   r   r   
<listcomp>:   s   z%_eager_metrics_fn.<locals>.<listcomp>T)r   sample_weightsmasks&return_weighted_and_unweighted_metricsskip_target_masksc                    s   g | ]}| j vr| qS r   )_compile_metric_functionsresult)r   m)modelr   r   r   J   s   
)	tfnestflattenlen_targets_handle_metrics_prepare_skip_target_masksextendmetrics)r   r   r   r   r   metric_resultsnew_targetsr   )r   r   r   _eager_metrics_fn%   s.    


r+   Fc              
   C   s  d}i }| j r||d< t|dkr4t|ts4|d }tdd tj|D r^tjtj	|}| |fi |}tj|}|rt
||}|rdd |D }dd |D }	tj|}g }
td	 d
d | jD }| j}|s|s|rtdntdt|D ]~\}}|r|| nd}|	| }t| j| d  |durt||| j}|du rj|}n.t||| j}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 s,0    Y  t| j dkrX|
!|| | |tjjkrpt"|}|| j#| | 7 }q|r|t"t$|7 }W d   n1 s0    Y  |||
|	fS )a  Calculates the loss for a given model.

    Args:
        model: The model on which metrics are being calculated.
        inputs: Either a dictionary of inputs to the model or a list of input
          arrays.
        targets: List of target arrays.
        output_loss_metrics: List of metrics that are used to aggregated output
          loss values.
        sample_weights: Optional list of sample weight arrays.
        training: Whether the model should be run in inference or training mode.

    Returns:
       Returns the model output, total loss, loss value calculated using the
       specified loss function and masks for each output. The total loss
       includes regularization losses and applies masking and sample weighting
       to the loss value.
    r   training   c                 s   s    | ]}t |tjttfV  qd S N)
isinstancenpndarrayfloatint)r   input_tr   r   r   	<genexpr>z   s   z_model_loss.<locals>.<genexpr>c                 S   s(   g | ] }|d ur t t|nd qS r.   )r   cast_if_floating_dtyper    convert_to_tensor)r   valr   r   r   r      s   z_model_loss.<locals>.<listcomp>c                 S   s   g | ]}t |d dqS )_keras_maskN)getattrr   r   r   r   r          r   c                 S   s   g | ]}|d ur|qS r.   r   )r   r   r   r   r   r      s   z?The model cannot be trained because it has no loss to optimize.z@The model cannot be evaluated because it has no loss to compute.Nr	   )sample_weight	reduction)r<   r=   )r=   )%_expects_training_argr#   r/   dictanyr    r!   r"   map_structurer7   r   #cast_if_floating_dtype_and_mismatchr   r
   loss_functionslosses
ValueError	enumerateoutput_namescastdtyper   squeeze_or_expand_dimensionshasattrcallcompute_weighted_lossReductionV2NONEr=   AUTOSUM_OVER_BATCH_SIZEreduce_weighted_lossr   appendscale_loss_for_distribution_loss_weights_listadd_n)r   inputsr   output_loss_metricsr   r,   
total_losskwargsoutsr   output_lossesloss_fnscustom_lossesir   weightsmask_per_sample_lossesweighted_lossesloss_reductionoutput_lossr   r   r   _model_lossS   s    



"&rg   c                 C   sN  t |rdnd$ t|   t L}t| |||||d\}}}	}
t| jtj	rd| j
|}n|}W d   n1 s|0    Y  |r| j}|rt| dr| || q|||}t| jtj	r| j|}| jt|| n
td |||	|
fW  d   W  d   S 1 s 0    Y  W d   n1 s@0    Y  dS )a$  Calculate the loss and gradient for one input batch.

       The model weights are updated if training is set to True.

    Args:
        model: Model whose loss has to be calculated.
        inputs: List of input arrays.
        targets: List of target arrays.
        output_loss_metrics: List of metrics that are used to aggregated output
          loss values.
        sample_weights: Optional list of sample weight arrays.
        training: The boolean represents if the weights of the model are
          updated. 'fit' methods will set this to True while 'evaluate' methods
          will set this to False.

    Returns:
        output of the model, total loss, the loss and the mask
        associated with each output.

    Raises:
        ValueError: If the model has no loss to optimize.
    r-   r   )rX   r   r,   N
_backwardszThe list of trainable weights is empty. Make sure that you are not setting model.trainable to False before compiling the model.)r   eager_learning_phase_scoper   RespectCompiledTrainableStater   rg   r/   	optimizerr   LossScaleOptimizerget_scaled_losstrainable_weightsrK   rh   gradientget_unscaled_gradientsapply_gradientsziploggingwarning)r   rW   r   rX   r   r,   taper[   rY   r\   r   scaled_total_lossrn   gradsr   r   r   _process_single_batch   sH    
"
rx   c           
      C   sb   t || }t| |||d|d\}}}}t|ts8|g}t| ||||d}	tj|}|||	dS )a  Calculates the loss and gradient updates for one input batch.

    Args:
        model: Model whose loss has to be calculated.
        inputs: Input batch data.
        targets: Target batch data.
        sample_weights: Sample weight batch data.
        output_loss_metrics: List of metrics that are used to aggregated output
          loss values.

    Returns:
        Dict with three items:
          'total_loss': list with a single tensor for overall loss,
          'output_losses': list of tensors for loss corresponding to each of the
            model output. Could be a empty list when model has only one output.
          'metrics': list of tensors for metric specified.
    Tr   r,   rX   r   r   rY   r\   r(   )	r   cast_to_model_input_dtypesrx   r/   listr+   r    r!   r"   
r   rW   r   r   rX   r[   rY   r\   r   metrics_resultsr   r   r   train_on_batchA  s&    

r   c           
   	   C   s   t || }td, t| |||d|d\}}}}W d   n1 sH0    Y  t|tsb|g}t| ||||d}	tj	
|}|||	dS )a  Calculates the loss for one input batch.

    Args:
        model: Model whose loss has to be calculated.
        inputs: Input batch data.
        targets: Target batch data.
        sample_weights: Sample weight batch data.
        output_loss_metrics: List of metrics that are used to aggregated output
          loss values.

    Returns:
        Dict with three items:
          'total_loss': single tensor for overall loss,
          'output_losses': list of tensors for loss corresponding to each of the
            model output. Could be a empty list when model has only one output.
          'metrics': list of tensors for metric specified.
    r   Fry   Nrz   r{   )r   r|   r   ri   rg   r/   r}   r+   r    r!   r"   r~   r   r   r   test_on_batchk  s(    ,

r   )NN)NNF)NNF)NN)NN)__doc__numpyr0   tensorflow.compat.v2compatv2r    kerasr   keras.enginer   r   keras.mixed_precisionr   keras.utilsr    tensorflow.python.eager.backpropr   tensorflow.python.platformr   rs   r   r+   rg   rx   r   r   r   r   r   r   <module>   s0   
2   
 *   
J 
+ 