
    BVh7                         d Z ddlZddlmZ ddlmZ ddlmZ ddl	m
Z
 ddl	mZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ d ZddZ	 	 	 ddZ	 	 	 ddZ	 	 ddZ	 	 ddZy)z;Keras training and evaluation routines for eager execution.    N)GradientTape)tensor_conversion)backend)training_utils)training_utils_v1)loss_scale_optimizer)losses_utils)math_ops)
tf_logging)nestc                 t    t        j                  |dz         5   |||       }d d d        |S # 1 sw Y   S xY w)N_loss)r   
name_scope)outputstargetsloss_fnoutput_namelosss        `/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/keras/engine/training_eager_v1.py_eager_loss_fnr       s;    +/0 %7G$D%	+%	+s   
-7c           	         t        j                  |      }t        j                  |      }g }|rtt        | j                        t        |      k7  r.| j                  D cg c]  }|dn|j	                  d       }}|}| j                  ||||d| j                               }|j                  | j                  D cg c]   }|| j                  vr|j                         " c}       |S c c}w c c}w )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.
  Nr   T)r   sample_weightsmasks&return_weighted_and_unweighted_metricsskip_target_masks)r   flattenlen_targetspop_handle_metrics_prepare_skip_target_masksextendmetrics_compile_metric_functionsresult)	modelr   r   r   r   metric_resultstnew_targetsms	            r   _eager_metrics_fnr+   &   s     LL!'LL!'. 5>>c'l*9>45!)$Q
/k  g**%/3::< + >N }}
	
%11	1 hhj 
 
's   C*<%C/c                    d}i }| j                   r||d<   t        |      dk(  rt        |t              s|d   }t	        d t        j                  |      D              r$t        j                  t        j                  |      } | |fi |}t        j                  |      }|rt        j                  ||      }|rVg }	|D ]M  }
|
8|	j                  t        j                  t        j                  |
                   =|	j                  d       O |	}|D cg c]  }t        |dd       }}t        j                  |      }g }t        j                   d      5  | j"                  D cg c]  }||	 }}| j$                  }|s|s|rt'        d      t'        d	      t)        |      D ]  \  }}|r||   nd}||   }t        j                   | j*                  |   d
z         5  |kt-        j.                  |||   j0                        }||}nCt-        j.                  |||   j0                        }t3        j4                  ||      \  }}}||z  }t7        |d      r|j9                  ||   ||         }t3        j:                  ||t2        j<                  j>                        }|j@                  }|t2        j<                  jB                  k(  rt2        j<                  jD                  }t3        jF                  ||      }n+ |||   ||   |      }t2        j<                  jD                  }ddd       t        | jH                        dkD  r|j                   ||                t2        j<                  jD                  k(  rt3        jJ                        }|| jL                  |   z  z  } |r+|t3        jJ                  t-        jN                  |            z  }ddd       ||||fS c c}w c c}w # 1 sw Y   xY w# 1 sw Y   %xY w)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              3   f   K   | ])  }t        |t        j                  t        t        f       + y w)N)
isinstancenpndarrayfloatint).0input_ts     r   	<genexpr>z_model_loss.<locals>.<genexpr>v   s*      	+
 2::uc23	+s   /1N_keras_maskr   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.r   )sample_weight	reduction)r9   r:   )r:   )(_expects_training_argr   r0   dictanyr   r   map_structurer   "convert_to_tensor_v2_with_dispatchr   #cast_if_floating_dtype_and_mismatchappendcast_if_floating_dtypegetattrr   r   loss_functionslosses
ValueError	enumerateoutput_namesr
   castdtyper	   squeeze_or_expand_dimensionshasattrcallcompute_weighted_lossReductionV2NONEr:   AUTOSUM_OVER_BATCH_SIZEreduce_weighted_lossr   scale_loss_for_distribution_loss_weights_listadd_n)r&   inputsr   output_loss_metricsr   r-   
total_losskwargsoutsnew_sample_weightsvalr(   r   output_lossesr   loss_fnscustom_lossesiweightsmask_per_sample_lossesweighted_lossesloss_reductionoutput_losss                            r   _model_lossri   Q   s   : *&
  !F:[Aj6AYF 	 	+\\&)	+ + <<fF 
v	 	 $	d	$CCG  (	!!"3"J"J@@E#G 	H 	!!$'( (N48
9q71mT*
9%
9LL!' -&! I)$33w7JH  LLMM	 ? @ 	@  > ? 	?  ) 6>
7%3q!g1Xde003g=> %HtT!W]]3$_G mmGT!W]];G991 D!W tOG7K(%ll71:tAw?
(>>#$00557/ #,,. |77<<<)55IIN %999+  
DG7K+'33GG.K%HV 
U]]	a	303K@A 
<33GG	G">>{KE,,Q/+==jm6>r L<<
..
') )jQI)T 
z=%	//a : %H %H#I) I)sE   O'O=%O,-O,1A/O= EO1(B1O=,O=1O:6O==Pc                 8   t        j                  |rdnd      5  t        j                  |       5  t	               5 }t        | |||||      \  }}}	}
t        | j                  t        j                        r| j                  j                  |      }n|}ddd       |r| j                  }|rt        | d      r| j                         nj                  |      }t        | j                  t        j                        r| j                  j                  |      }| j                  j!                  t#        ||             nt%        j&                  d       	
fcddd       cddd       S # 1 sw Y   xY w# 1 sw Y   nxY wddd       y# 1 sw Y   yxY w)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   ri   r0   	optimizerr   LossScaleOptimizerget_scaled_losstrainable_weightsrL   rk   gradientget_unscaled_gradientsapply_gradientsziploggingwarning)r&   rW   r   rX   r   r-   taper[   rY   r^   r   scaled_total_lossrq   gradss                 r   _process_single_batchr{      sv   8 ))x!Q?  22259 2	 '4
"5+! -dJu 
EOO%9%L%L	M!OO;;JG&' 11	 5,'


4!2
3-- 13DE%,??AOO::5AE
//
)
)#e5F*G
H / 	0 ]E1A 2  2  2' ' 2  2  2  2  2s;   FE;AE/CE;	F/E84E;;F	 FFc                     t        j                  ||       }t        | |||d|      \  }}}}t        |t              s|g}t        | ||||      }	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_dtypesr{   r0   listr+   r   r   
r&   rW   r   r   rX   r[   rY   r^   r   metrics_resultss
             r   train_on_batchr      s    , 77F&


'13 )$
M5 
D$	6D%T7>H/||J'*"($
& &    c           	      *   t        j                  ||       }t        j                  d      5  t	        | |||d|      \  }}}}ddd       t        t              s|g}t        | |||      }	t        j                        }||	dS # 1 sw Y   GxY w)ar  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   Fr}   Nr~   r   )
r   r   r   rl   ri   r0   r   r+   r   r   r   s
             r   test_on_batchr   I  s    , 77F&))!, 6) 3	5 +D*mU6 
D$	6D%T7>H/||J'*"($
& &6 6s   B		B)NN)NNF)__doc__numpyr1    tensorflow.python.eager.backpropr   tensorflow.python.frameworkr   tensorflow.python.kerasr   tensorflow.python.keras.enginer   r   'tensorflow.python.keras.mixed_precisionr   tensorflow.python.keras.utilsr	   tensorflow.python.opsr
   tensorflow.python.platformr   rv   tensorflow.python.utilr   r   r+   ri   r{   r   r    r   r   <module>r      sw    B  9 9 + 9 < H 6 * < '(\ %)#M0f /3)-#(<2D #''+	&&X "&&*	)&r   