
    &Vf0e                         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	  G d dej
                  Zd	 Zd
 Zd Zd Z G d dej
                  Z G d dej                  ZdS )    )backend)lossesmetrics)ops)tree)get_object_namec                   P     e Zd Zd	 fd	Zd
dZd Zd Zd Zed             Z	 xZ
S )MetricsListmetrics_listNc                 h    t                                          |           || _        || _        d S )Nname)super__init__r   output_name)selfr   r   r   	__class__s       ]/var/www/html/software/conda/lib/python3.11/site-packages/keras/src/trainers/compile_utils.pyr   zMetricsList.__init__
   s3    d###&    c                 J    | j         D ]}|                    |||           d S )N)sample_weight)r   update_state)r   y_truey_predr   ms        r   r   zMetricsList.update_state   s<     	H 	HANN66NGGGG	H 	Hr   c                 B    | j         D ]}|                                 d S N)r   reset_stater   r   s     r   r   zMetricsList.reset_state   s,     	 	AMMOOOO	 	r   c                 $    d | j         D             S )Nc                 B    i | ]}|j         |                                S  )r   result.0r   s     r   
<dictcomp>z*MetricsList.get_result.<locals>.<dictcomp>   s$    999q

999r   r   r   s    r   
get_resultzMetricsList.get_result   s    99DL9999r   c                     t           r   NotImplementedErrorr(   s    r   
get_configzMetricsList.get_config       !!r   c                     t           r   r+   clsconfigs     r   from_configzMetricsList.from_config       !!r   )r   Nr   )__name__
__module____qualname__r   r   r   r)   r-   classmethodr3   __classcell__r   s   @r   r   r   	   s        ' ' ' ' ' '
H H H H  : : :" " " " " [" " " " "r   r   c                 ^    | dS t          | t                    rdS t          |           rdS dS )NTF)
isinstancestrcallable)values    r   is_function_liker@   "   s;    }t% t t5r   c                     t          | j                  }t          |j                  }| j        d         }|j        d         }|dk    }||k     p|dk    o|dk    }||fS )N   )lenshape)r   r   y_t_ranky_p_ranky_t_last_dimy_p_last_dim	is_binaryis_sparse_categoricals           r   is_binary_or_sparse_categoricalrL   ,   sq    6<  H6<  H<#L<#L!I8E|q0E\A5E  +++r   c                 4   | d S t          |                                           dvrt          j        |           }nt	          ||          \  }}|r#t          j        t          |                     }nG|r#t          j        t          |                     }n"t          j        t          |                     }t          | t                     r| }nt          |          }t          |t          j
                  st          j        |          }||_        |S )N)accuracyaccr   )r=   lowermetrics_modulegetrL   BinaryAccuracySparseCategoricalAccuracyCategoricalAccuracyr<   r	   MetricMeanMetricWrapperr   )
identifierr   r   
metric_objrJ   rK   metric_names          r   
get_metricr[   9   s%   t :&999#'
33

+JF,
 ,
(	(  		'6C
OOLLLJJ" 	'A__  JJ (;__  J *c"" 2 %j11j."788 B#5jAA
!JOr   c                    | d S t          |                                           dvrt          j        |           }n=t	          ||          \  }}|rt          j        }n|rt          j        }nt          j        }t          |t          j	                  s=t          | t                     r| }nt          |          }t          j        ||          }|S )N)crossentropycer   )r=   rP   losses_modulerR   rL   binary_crossentropysparse_categorical_crossentropycategorical_crossentropyr<   Lossr	   LossFunctionWrapper)rX   r   r   loss_objrJ   rK   	loss_names          r   get_lossrg   \   s    t :&<<< $Z00+JF,
 ,
(	(  	>$8HH" 	>$DHH$=Hh 233 Oj#&& 	2"II'11I 4XINNNOr   c                        e Zd Z	 	 d fd	Zed             Zed             Zd Zd Zd Z	dd	Z
d
 Zd Zd Zed             Z xZS )CompileMetricscompile_metricNc                    t                                          |           |rDt          |t          t          t
          f          s"t          d| dt          |                     |rDt          |t          t          t
          f          s"t          d| dt          |                     || _        || _	        d| _
        d| _        || _        d S )Nr   zTExpected `metrics` argument to be a list, tuple, or dict. Received instead: metrics=	 of type zfExpected `weighted_metrics` argument to be a list, tuple, or dict. Received instead: weighted_metrics=Fcompile_metrics)r   r   r<   listtupledict
ValueErrortype_user_metrics_user_weighted_metricsbuiltr   output_names)r   r   weighted_metricsr   rv   r   s        r   r   zCompileMetrics.__init__y   s    	d### 	:geT/BCC 	O-4O O?CG}}O O    	JtUD1%
 %
 	 4<L4 4 0114 4  
 %&6#
%	(r   c                     | j         sg S g }| j        | j        z   D ]I}t          |t                    r|                    |j                   2||                    |           J|S r   )ru   _flat_metrics_flat_weighted_metricsr<   r   extendr   append)r   r   r   s      r   r   zCompileMetrics.metrics   sv    z 	I#d&AA 	" 	"A![)) "qy))))q!!!r   c                 h    | j         sg S g }| j        D ]}||                    |j                   |S r   )ru   r   r{   	variables)r   varsr   s      r   r~   zCompileMetrics.variables   sH     z 	I 	) 	)A}AK(((r   c                 |   | j         r| j         }nt          |t                    r/t          t	          |                                                    }nXt          |t          t          f          r8t          |          }t          d |D                       rd |D             }nd }nd }d}|rt          |          }| 	                    |          }| 	                    |          }| j
        }| j        }|                     |||||d          | _        |                     |||||d          | _        d| _        d S )Nc              3   6   K   | ]}t          |d           V  dS _keras_historyNhasattrr&   xs     r   	<genexpr>z'CompileMetrics.build.<locals>.<genexpr>   -      @@A71.//@@@@@@r   c                 0    g | ]}|j         j        j        S r#   r   	operationr   r   s     r   
<listcomp>z(CompileMetrics.build.<locals>.<listcomp>   !    PPPA 0 : ?PPPr   rC   r   )argument_namerw   T)rv   r<   rp   sortedrn   keysro   rD   all
_flatten_yrs   rt   _build_metrics_setry   rz   ru   )r   r   r   rv   num_outputsr   rw   s          r   buildzCompileMetrics.build   sc    	,LL%% 
	!$v{{}}"5"566LLu.. 	f++K@@@@@@@ $PPPPP#LK 	,l++K(((($6!44# 5 
 
 '+&=&=, '> '
 '
# 


r   c                    g }t          |t                    r6|                                D ]!}||vrt          d| d| d| d|           "|dk    r|s|                    d            nt          |t                    rt          j        |          }t          |t                    s|g}t          d |D                       st          d| d| d|           |                    t          fd	|D                                  n6t          |t          t          f          rt          |          t                    k    r9t          d
| d| d| dt          |           dt                     d          t          t          |                    D ]\  }	\  }
t          |
t                    s|
g}
|r||	         nd }t          d |
D                       st          d| d|
           |                    t          fd|
D             |                     nt          |t                    r|t          d| d| d|           |                                D ]f}t          ||         t                    s||         g||<   t          d ||         D                       st          d| d| d||                    gt          |          D ]W\  }||v r8|                    t          fd||         D             |                     B|                    d            X|S )NzIn the dict argument `z`, key 'z5' does not correspond to any model output. Received:
=rC   c              3   4   K   | ]}t          |          V  d S r   r@   r%   s     r   r   z4CompileMetrics._build_metrics_set.<locals>.<genexpr>   s+      @@1+A..@@@@@@r   zExpected all entries in the `z/` list to be metric objects. Received instead:
c                 N    g | ]!}|t          |d         d                   "S )Nr   r[   )r&   r   r   r   s     r   r   z5CompileMetrics._build_metrics_set.<locals>.<listcomp>   s:        ! } 'q&)VAY??,}}r   z7For a model with multiple outputs, when providing the `zY` argument as a list, it should have as many entries as the model has outputs. Received:

of length  whereas the model has 	 outputs.c              3   4   K   | ]}t          |          V  d S r   r   r&   es     r   r   z4CompileMetrics._build_metrics_set.<locals>.<genexpr>  s+      @@q/22@@@@@@r   z$All entries in the sublists of the `zQ` list should be metric objects. Found the following sublist with unknown types: c                 6    g | ]}|t          |          S r   r   r&   r   ypyts     r   r   z5CompileMetrics._build_metrics_set.<locals>.<listcomp>  s2       $%#$= !+1b" 5 5#0==r   )r   z
Argument `zY` can only be provided as a dict when the model also returns a dict of outputs. Received c              3   4   K   | ]}t          |          V  d S r   r   r   s     r   r   z4CompileMetrics._build_metrics_set.<locals>.<genexpr>#  s+      JJq/22JJJJJJr   z)` dict should be metric objects. At key 'z3', found the following sublist with unknown types: c                 6    g | ]}|t          |          S r   r   r   s     r   r   z5CompileMetrics._build_metrics_set.<locals>.<listcomp>.  s2     !" !" !"()'(} %/q"b$9$9'4}}r   )r<   rp   r   rq   r|   r   flattenrn   r   r   ro   rD   	enumeratezip)r   r   r   rv   r   r   r   flat_metricsr   idxmlsr   r   s       ``     @@r   r   z!CompileMetrics._build_metrics_set   s&    gt$$ 	  |++$H H H H H.;H H>EH H   , ! ##D))))gt,, 4"l733G!'400 (&iG@@@@@@@ $5 5 5(5 5+25 5  
 ##    %,       'D%=11 ?2w<<3v;;..$2/<2 2 0=2 2 @G2 2 #&g,,	2 2
 v;;2 2 2   +400+ +  &C#r2 &c400 $"e0<F<,,$D@@C@@@@@ (, -, , '*, ,   !''#    ),  
 )-  	 	 	 	. GT** 2'$>] > >$1> >4;> >  
 $LLNN 	 	D%gdmT:: 8)0JJGDMJJJJJ (C -C C'+C C 4;4=C C   %(ff$E$E 2 2LD"bw$++'!" !" !" !" !"-4T]!" !" !"
 -1  	 	 	 	 %++D1111r   c                     t          |t                    r4| j        r-g }| j        D ]!}||v r|                    ||                    "|S t	          j        |          S r   r<   rp   rv   r|   r   r   r   yr$   r   s       r   r   zCompileMetrics._flatten_y:  h    a 	4#4 	F) + +199MM!D'***M|Ar   c                 |   | j         s|                     ||           |                     |          }|                     |          }t          | j        ||          D ]\  }}}|r|                    ||           ^|                               t                    t          |          k     r(fdt          t          |                    D             n&d t          t          |                    D             t          | j        ||          D ] \  }}}}|r|                    |||           !d S )Nc                      g | ]
}d          S r   r#   r&   _r   s     r   r   z/CompileMetrics.update_state.<locals>.<listcomp>O       N N Naq!1 N N Nr   c                     g | ]}d S r   r#   r&   r   s     r   r   z/CompileMetrics.update_state.<locals>.<listcomp>Q  s    >>>aT>>>r   )	ru   r   r   r   ry   r   rD   rangerz   )r   r   r   r   r   y_ty_ps_ws      `    r   r   zCompileMetrics.update_stateC  sV   z 	'JJvv&&&((((t166BB 	) 	)KAsC )sC((($ OOM::M=!!CKK// N N N N5V;M;M N N N>>5V+=+=>>>M #'!
 !
 	. 	.AsC  .sC---		. 	.r   c                     | j         sd S | j        D ]}|r|                                 | j        D ]}|r|                                 d S r   )ru   ry   r   rz   r    s     r   r   zCompileMetrics.reset_stateX  sk    z 	F# 	  	 A  , 	  	 A  	  	 r   c                    | j         st          d          i }i }| j        D ]}|s|j        D ]s}|j        }|j        r|j         d| }||vr|                                ||<   d||<   =||         }||xx         dz  cc<   | d| }|                                ||<   t| j        D ]}|s|j        D ]}|j        }|j        r|j         d| }||vr|                                ||<   d||<   =d|j         }|j        r|j         d| }||vrd||<   n||         }||xx         dz  cc<   | d| }|                                ||<   |S )Nz<Cannot get result() since the metric has not yet been built.r   rC   	weighted_)ru   rq   ry   r   r   r   r$   rz   )r   resultsunique_name_countersr   r   r   indexs          r   r$   zCompileMetrics.resultb  s   z 	N   !% 	/ 	/C [ / /v? 7!o6666D333$%HHJJGDM12(..06E(...!3...",,U,,D$%HHJJGDMM/ . 	/ 	/C [ / /v? 7!o6666D333$%HHJJGDM12(../qv//D ;"%/::D::#77756,T22 4T :,T222a7222"&0000$%HHJJGDMM#/$ r   c                     t           r   r+   r(   s    r   r-   zCompileMetrics.get_config  r.   r   c                     t           r   r+   r0   s     r   r3   zCompileMetrics.from_config  r4   r   )rj   Nr   )r5   r6   r7   r   propertyr   r~   r   r   r   r   r   r$   r-   r8   r3   r9   r:   s   @r   ri   ri   x   s
       
 ) ) ) ) ) )6 	 	 X	 	 	 X	& & &Pd d dL  . . . .*     , , ,\" " " " " [" " " " "r   ri   c                   ^     e Zd Z	 	 	 d
 fd	Zd ZddZd ZddZd Ze	d	             Z
 xZS )CompileLossNsum_over_batch_sizec                    |rJt          |t          t          t          t          f          s"t          d| dt          |                     || _        || _        d| _	        || _
        t                                          d|           d S )NzExpected `loss_weights` argument to be a float (single output case) or a list, tuple, or dict (multiple output case). Received instead: loss_weights=rl   Fcompile_loss)r   	reduction)r<   rn   ro   rp   floatrq   rr   
_user_loss_user_loss_weightsru   rv   r   r   )r   lossloss_weightsr   rv   r   s        r   r   zCompileLoss.__init__  s      		
4e4!
 !
 		 0 3?0 0  --	0 0   ".
(n	BBBBBr   c           
         | j         r| j         }nt          t                    r/t          t	                                                              }nXt          t          t          f          r8t                    }t          d D                       rd D             }nd }nd }d}|rt          |          }| 	                              | j
        | j        }g }g }t          t                    r0                                D ]}||vrt          d| d           |dk    rt          t                    rt          j                  t          t                    rt                    dk    rd         t                    s"t          d dt!                               t          t                    rt                    dk    rd         t                    r,t          j                  rt          j        fd	          t                    r|                    t)                               |rNt          |t*                    s"t          d
| dt!          |                     |                    |           n|                    d           nt          t          t          f          rnt          j                  t                    t                    k    r3t          d dt                     dt                     d          t          d D                       st          d           fdD             }|rt          |t          t          f          st          d|           t          |          t                    k    r3t          d| dt          |           dt                     d          t          d |D                       st          d|           t	          |          }nd D             }nt          t                    r|t          d                                           D ]w}t          |         t                    r*t          |                   dk    r|         d         |<   t          |                   st          d| d|                    xt-          |          D ]h\  }}	}
|v rI|         r+|                    t)          |         |	|
                     =|                    d            S|                    d            i|rt          |t                    st          d|           |                                D ]Q}||vrt          d| d|           t          ||         t*                    st          d| d||                    R|D ]7}||v r|                    ||                    "|                    d           8nd  |D             }|| _        || _        d!| _        d S )"Nc              3   6   K   | ]}t          |d           V  dS r   r   r   s     r   r   z$CompileLoss.build.<locals>.<genexpr>  r   r   c                 0    g | ]}|j         j        j        S r#   r   r   s     r   r   z%CompileLoss.build.<locals>.<listcomp>  r   r   rC   z"In the dict argument `loss`, key 'z:' does not correspond to any model output. Received:
loss=r   zcWhen there is only a single output, the `loss` argument must be a callable. Received instead:
loss=rl   c                     S r   r#   )r   r   s    r   <lambda>z#CompileLoss.build.<locals>.<lambda>  s     r   zwWhen there is only a single output, the `loss_weights` argument must be a Python float. Received instead: loss_weights=      ?zFor a model with multiple outputs, when providing the `loss` argument as a list, it should have as many entries as the model has outputs. Received:
loss=r   r   r   c              3   4   K   | ]}t          |          V  d S r   r   r   s     r   r   z$CompileLoss.build.<locals>.<genexpr>  s+      99q'**999999r   zFor a model with multiple outputs, when providing the `loss` argument as a list, each list entry should be a callable (the loss function corresponding to that output). Received: loss=c                 6    g | ]}|t          |          S r   )rg   )r&   fnr   r   s     r   r   z%CompileLoss.build.<locals>.<listcomp>  s-       13r~VV,,~~~r   zIf the `loss` argument is provided as a list/tuple, the `loss_weight` argument should also be provided as a list/tuple, of equal length. Received: loss_weights=zFor a model with multiple outputs, when providing the `loss_weights` argument as a list, it should have as many entries as the model has outputs. Received: loss_weights=z of length c              3   N   K   | ] }t          |t          t          f          V  !d S r   )r<   intr   r   s     r   r   z$CompileLoss.build.<locals>.<genexpr>  s0      MM1:a#u66MMMMMMr   zFor a model with multiple outputs, when providing the `loss_weights` argument as a list, each list entry should be a Python int or float (the weighting coefficient corresponding to the loss for that output). Received: loss_weights=c                     g | ]}d S r   r#   r   s     r   r   z%CompileLoss.build.<locals>.<listcomp>"  s    $7$7$7QS$7$7$7r   zlArgument `loss` can only be provided as a dict when the model also returns a dict of outputs. Received loss=zFor a model with multiple outputs, when providing the `loss` argument as a dict, each dict entry should be a callable (the loss function corresponding to that output). At key 'z', received invalid type:
zIf the `loss` argument is provided as a dict, the `loss_weight` argument should also be provided as a dict. Received: loss_weights=z*In the dict argument `loss_weights`, key 'zB' does not correspond to any model output. Received: loss_weights=zFor a model with multiple outputs, when providing the `loss_weights` argument as a dict, each dict entry should be a Python float (the weighting coefficient corresponding to the loss for that output). At key 'c                     g | ]}d S r   r#   r   s     r   r   z%CompileLoss.build.<locals>.<listcomp>Z  s    $>$>$>QS$>$>$>r   T)rv   r<   rp   r   rn   r   ro   rD   r   r   r   r   rq   r   r   r@   rr   	is_nestedmap_structurer|   rg   r   r   flat_lossesflat_loss_weightsru   )r   r   r   rv   r   r   r   r   r   r   r   r   s    ``        @r   r   zCompileLoss.build  sZ    	,LL%% 
	!$v{{}}"5"566LLu.. 	f++K@@@@@@@ $PPPPP#LK 	,l++K((.dD!! 			  |++$2 2 2+/2 2   , !$%% *|D))$%% #d))q..Aw#D))  K/3K K>B4jjK K  
 &$'' #CKK1,<,<D!! 	>dnV&<&< 	> %nnnnf==D D!! v	?xff==>>> .!,66 $5 ;G5 5 !%\ 2 2	5 5   "((6666!((----tUm,, h	?<%%D4yyCKK'' D (,D D :=TD D .1[[	D D D   99D99999  - '+	- -      7;  K  8!,u>> $A 3?A A   |$$F33$2 <H2 2 #&l"3"3	2 2
 v;;2 2 2   MMMMMMM $O AM	O O   %)$6$6!!$7$7$$7$7$7!!d## 7	?# ,%), ,  
 		 
 
d4j$// /CT
OOq4H4H!%dADJ'T
33 $Q $(	Q Q EIJ	Q Q   !$L&& A A - -b"4<<Dz 1#**8DJB+G+GHHHH#**40000&&t,,,, ?!,55 $I:FI I  
 )--//  D<//(M $M M>JM M  
 &l4&8%@@ (L ?C	L L
 8DD7IL L   ) 6 6D|++)00d1CDDDD)005555	6 %?$>+$>$>$>!&!2


r   c                     t          j        | j                  5  |                     |||          cd d d            S # 1 swxY w Y   d S r   )r   
name_scoper   call)r   r   r   r   s       r   __call__zCompileLoss.__call___  s    ^DI&& 	< 	<99VV];;	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	<s   >AAc                     t          |t                    r4| j        r-g }| j        D ]!}||v r|                    ||                    "|S t	          j        |          S r   r   r   s       r   r   zCompileLoss._flatten_yc  r   r   c           	      |   | j         s|                     ||           |                     |          }|                     |          }^|                               t                    t          |          k     r(fdt	          t          |                    D             nd |D             g }t          | j        ||| j                  D ]T\  }}}}|rJ|t          j	         |||          t          j                              z  }	|                    |	           U|rt          |          }
|
S d S )Nc                      g | ]
}d          S r   r#   r   s     r   r   z$CompileLoss.call.<locals>.<listcomp>w  r   r   c                     g | ]}d S r   r#   r   s     r   r   z$CompileLoss.call.<locals>.<listcomp>y  s    222aT222r   )dtype)ru   r   r   rD   r   r   r   r   r   castr   floatxr|   sum)r   r   r   r   loss_valuesr   r   r   loss_weightr?   
total_losss      `       r   r   zCompileLoss.calll  se   z 	'JJvv&&&(((($ OOM::M=!!CKK// N N N N5V;M;M N N N226222M:=";
 ;
 	* 	*6D#sK  *#chDc=119I9I' ' '  ""5))) 	[))Jtr   c                     t           r   r+   r(   s    r   r-   zCompileLoss.get_config  r.   r   c                     t           r   r+   r0   s     r   r3   zCompileLoss.from_config  r4   r   )Nr   Nr   )r5   r6   r7   r   r   r   r   r   r-   r8   r3   r9   r:   s   @r   r   r     s         'C C C C C C.m m m^< < < <     B" " " " " [" " " " "r   r   N)	keras.srcr   r   r_   r   rQ   r   r   keras.src.utils.namingr	   rV   r   r@   rL   r[   rg   ri   rc   r   r#   r   r   <module>r      sR         - - - - - - / / / / / /             2 2 2 2 2 2" " " " ".' " " "2  
, 
, 
,     F  8]" ]" ]" ]" ]"^* ]" ]" ]"@	z" z" z" z" z"-$ z" z" z" z" z"r   