
    &VfX                         d dl Z d dlZd dlmZ d dlmZ d dlmZ d dlmZ d dlm	Z	 d dl
mZ d dlmZ d d	lmZ  G d
 de          ZdZd Zd ZdS )    N)backend)initializers)ops)learning_rate_schedule)serialization_lib)KerasSaveable)tracking)	auto_namec                       e Zd Z	 	 	 	 	 	 	 	 	 	 d1dZd Zej        d             Zd Ze	d             Z
d	 Z	 	 	 	 d2dZ	 d3dZd Zd Zd Zd Zd Zd Zd4dZd Zd Zd Zd Zd Zd Ze	d             Zej        d             Zd Zd Zd Zd  Z d! Z!d" Z"d# Z#d5d$Z$d% Z%d& Z&d' Z'd( Z(d) Z)d* Z*d+ Z+d, Z,e-d4d-            Z. fd.Z/d4d/Z0d0 Z1 xZ2S )6BaseOptimizerNFGz?c                    d| _         |                    dd           t          j        d           |rt	          d|           |t          | j        j                  }|| _        || _	        || _
        || _        || _        || _        |	| _        |
| _        |
r|
dk    st	          d|
           |rM|dk    s|dk     rt	          d	|           |r-t!          |t"                    r|dk     rt	          d
|           || _        || _        t)          d |||fD                       }|dk    rt	          d| d| d|           d| _        g | _        g | _        t1          j        dd | j        fi          | _        i | _        t9          j        | j        |           5  t9          j        ddddd          }d d d            n# 1 swxY w Y   |                     |           || _         t!          |tB          j"                  r	|| _#        d S tI          |          r	|| _#        d S t!          |tJ                    st	          d|           t9          j        | j        |           5  t9          j        |dt9          j&                    dd          }d d d            n# 1 swxY w Y   |                     |           || _#        d S )NFdecayz<Argument `decay` is no longer supported and will be ignored.zArgument(s) not recognized:    z]`gradient_accumulation_steps` must be an integer >= 2. Received: gradient_accumulation_steps=   r   zC`ema_momentum` must be in the range [0, 1]. Received: ema_momentum=z]`ema_overwrite_frequency` must be an integer >= 1 or None. Received: ema_overwrite_frequency=c              3      K   | ]}|d uV  	d S N ).0as     `/var/www/html/software/conda/lib/python3.11/site-packages/keras/src/optimizers/base_optimizer.py	<genexpr>z)BaseOptimizer.__init__.<locals>.<genexpr>M   s7       
 
ATM
 
 
 
 
 
    zYOnly one of `clipnorm`, `clipvalue` and `global_clipnorm` can be set. Received: clipnorm=z, clipvalue=z, global_clipnorm=	variablesc                 6    t          | t          j                  S r   )
isinstancer   Variable)xs    r   <lambda>z(BaseOptimizer.__init__.<locals>.<lambda>^   s    jG,<== r   caller	iterationintonly_first_replica)namedtype	trainableaggregationzArgument `learning_rate` should be float, or an instance of LearningRateSchedule, or a callable (that takes in the current iteration value and returns the corresponding learning rate value). Received instead: learning_rate=learning_rate)'_lockpopwarningswarn
ValueErrorr
   	__class____name__r%   weight_decayclipnormglobal_clipnorm	clipvalueuse_emaloss_scale_factorgradient_accumulation_stepsr   r#   ema_momentumema_overwrite_frequencysumbuilt
_variables_trainable_variablesr	   Tracker_tracker_trainable_variables_indicesr   
name_scoper   _track_variable
iterationsr   LearningRateSchedule_learning_ratecallablefloatfloatx)selfr)   r1   r2   r4   r3   r5   r8   r9   r6   r7   r%   kwargsclip_args_sumrC   s                  r   __init__zBaseOptimizer.__init__   sQ    
::gt$$0MN    	FDFDDEEE<T^455D	( ."!2+F(& 	.!33 525 5    	a<!#3#3 =.:= =   ' 6<<*Q.. 1.1 1  
 )'>$ 
 
$,i#I
 
 
 
 
 1L.6L L&L L:IL L  
 
 $&! (==O
 
 -/)
 	$777 	 	 ) 0  J	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	Z((($ 1F
 
 	0 #0Dm$$ 	0"/DmU33  G 8E	G G   #DId;;;   ' 0!(!.**# 4! ! !                 ///"/Ds$   $G

GG.+J%%J),J)c                 <    | j                             d|           d S )Nr   )r?   add_to_storerI   variables     r   rB   zBaseOptimizer._track_variable   s     "";99999r   c                    | j         rg | _        | j        rg | _        t	          |          D ]\  }}|| j        |                     |          <   | j         r/| j                            |                     |d                     | j        r/| j                            |                     |d                     |d d          | _	        d| _
        d S )Naverage)r%   gradient_accumulatorT)r5   _model_variables_moving_averager7   _accumulated_gradients	enumerater@   _var_keyappendadd_variable_from_referencer=   r;   )rI   r   irP   s       r   buildzBaseOptimizer.build   s   < 	635D0+ 	-*,D'$Y// 	 	KAxIJD-dmmH.E.EF| 4;;44 & 5     / +2244 3 5     %.aaaL!


r   c                      t          |          S r   )idrO   s     r   rW   zBaseOptimizer._var_key   s    (||r   c                      | j         d d          S r   )r<   rI   s    r   r   zBaseOptimizer.variables   s    qqq!!r   c                 B    | j         |                     |                   S r   )r@   rW   rO   s     r   _get_variable_indexz!BaseOptimizer._get_variable_index   s    0x1H1HIIr   zerosmeanc           	         |                                   t          j        |          }t          j        | j        |           5  t          j        |||d||          }d d d            n# 1 swxY w Y   |                     |           |S )Nr    F)initializershaper&   r'   r(   r%   )_check_super_calledr   getr   rA   r%   r   rB   )rI   rf   re   r&   r(   r%   rP   s          r   add_variablezBaseOptimizer.add_variable   s     	  """"&{33	$777 	 	'''  H	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	X&&&s   A++A/2A/c                 8   |pd}t          |d          r"|j                            dd          dz   |z   }nBt          |j                                      dd                              dd          dz   |z   }|                     |j        ||j        |          S )z\Add an all-zeros variable with the shape and dtype of a reference
        variable.
        varpath/_:)rf   re   r&   r%   )hasattrrl   replacestrr%   ri   rf   r&   )rI   reference_variabler%   re   s       r   rY   z)BaseOptimizer.add_variable_from_reference   s     }u%v.. 	%*223<<sBTIDD &+,,44S#>>FFsCPP 
   $*#$*	 ! 
 
 	
r   c                 n    |D ]1}|                      |          | j        vrt          d| d          2d S )NzUnknown variable: z. This optimizer can only be called for the variables it was originally built with. When working with a new set of variables, you should recreate a new optimizer instance.)rW   r@   r.   )rI   r   vs      r   _check_variables_are_knownz(BaseOptimizer._check_variables_are_known   sc     	 	A}}Qt'HHH 9 9 9 9   I	 	r   c                 0    |                     |           dS )a  Assign a value to a variable.

        This should be used in optimizers instead of `variable.assign(value)` to
        support backend specific optimizations.
        Note that the variable can be a model variable or an optimizer variable;
        it can be a backend native variable or a Keras variable.

        Args:
            variable: The variable to update.
            value: The value to add to the variable.
        N)assignrI   rP   values      r   rx   zBaseOptimizer.assign   s     	r   c                 0    |                     |           dS )a  Add a value to a variable.

        This should be used in optimizers instead of
        `variable.assign_add(value)` to support backend specific optimizations.
        Note that the variable can be a model variable or an optimizer variable;
        it can be a backend native variable or a Keras variable.

        Args:
            variable: The variable to update.
            value: The value to add to the variable.
        N)
assign_addry   s      r   r|   zBaseOptimizer.assign_add        	E"""""r   c                 0    |                     |           dS )a  Subtract a value from a variable.

        This should be used in optimizers instead of
        `variable.assign_sub(value)` to support backend specific optimizations.
        Note that the variable can be a model variable or an optimizer variable;
        it can be a backend native variable or a Keras variable.

        Args:
            variable: The variable to update.
            value: The value to add to the variable.
        N)
assign_subry   s      r   r   zBaseOptimizer.assign_sub  r}   r   c                     t           r   )NotImplementedError)rI   gradientrP   r)   s       r   update_stepzBaseOptimizer.update_step  s    !!r   c                 T    t          | \  }}|                     ||           | j        S r   )zipapplyrC   )rI   grads_and_varsgradstrainable_variabless       r   apply_gradientszBaseOptimizer.apply_gradients  s/    %(.%9""

5-...r   c                 Z   t          |          dk    rdS |x| j        st          d          t          |          t          | j                  k    r5t          dt          |           dt          | j                   d          | j        }nzt          |          }| j        sOt          j        | j        |           5  | 	                    |           ddd           n# 1 swxY w Y   d| _        | 
                    |           t          j        | j        |           5  |                     ||          \  }}|                     ||          \  }}t          t          |                    dk    r	 ddd           dS | j        fd	|D             }|                     |          }|                     |           |                     ||           |D ]1}|j        (|                    |                    |                     2	 ddd           dS # 1 swxY w Y   dS )
a3  Update traininable variables according to provided gradient values.

        `grads` should be a list of gradient tensors
        with 1:1 mapping to the list of variables the optimizer was built with.

        `trainable_variables` can be provided
        on the first call to build the optimizer.
        r   NzWhen passing `grads` without `variables`, the optimizer must already be built on a list of variables. Call `optimizer.build(trainable_variables)` first. zWhen passing `grads` as a list of gradient tensors, the gradients must match `optimizer.variables` one-to-on. Received a list of z* gradients, but the optimizer is tracking z trainable variables.r    Tc                 "    g | ]}||n|z  S r   r   )r   gscales     r   
<listcomp>z'BaseOptimizer.apply.<locals>.<listcomp>X  s%    FFF1aiQYFFFr   )lenr;   r.   r@   r=   listr   rA   r%   r[   rv   ,_overwrite_variables_directly_with_gradients_filter_empty_gradientsr6   _clip_gradients_apply_weight_decay_backend_apply_gradients
constraintrx   )rI   r   r   rP   r   s       @r   r   zBaseOptimizer.apply  s@    u::?? F&:  J  
 5zzS!BCCCC +*-e**+ + .11J-K-K+ + +   #'";"&':";";: "'	$??? 4 4JJ23334 4 4 4 4 4 4 4 4 4 4 4 4 4 4!
++,?@@@	$777 	C 	C AA.  'E& *.)E)E** *&E& 4;;1$$	C 	C 	C 	C 	C 	C 	C 	C" *E FFFFFFF ((//E$$%8999 ))%1DEEE/ C C&2OOH$7$7$A$ABBBC9	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	Cs,   C$$C(+C(&AH BH  H$'H$c                      j         rK j        dz    j         z  dk    } fdD              fdt          j        |fd fd           n                      j                    j        rQ                      j                    j	        r0 j        dz    j	        z  dk    }t          j        | fdd             j        
                    d           d	S )
ar  Apply method that can be overridden by different backends.

        JAX overrides it in order to deal with statelessness in gradient
        accumulation and EMA handling.

        The below implementation is intended to be generally backend-agnostic,
        but may not work with all backends.

        This method does 4 things:
        - Call the optimizer's update_step() to update trainable variables
            and optimizer variables.
        - Update EMA variables, if EMA is configured.
        - Update gradient accumulators, if gradient accumulation is configured.
        - Update the iteration counter.
        r   r   c                 P    g | ]"}j                             |                   #S r   )rU   ra   )r   ru   rI   s     r   r   z:BaseOptimizer._backend_apply_gradients.<locals>.<listcomp>|  s?        +D,D,DQ,G,GH  r   c                     j         fdt          |           D             }                     | |j                                                    d S )Nc                 &    g | ]\  }}||z   z  S r   r   )r   r   acc_gstepss      r   r   zSBaseOptimizer._backend_apply_gradients.<locals>._update_step_fn.<locals>.<listcomp>  s3       ,4AuQY%'  r   )r7   r   _backend_update_stepr)   $_backend_reset_gradient_accumulators)r   r   r   	acc_gradsrI   s     @r   _update_step_fnz?BaseOptimizer._backend_apply_gradients.<locals>._update_step_fn  s}    8   8;E98M8M   )).0B   99;;;;;r   c                                  S r   r   )r   r   r   s   r   r   z8BaseOptimizer._backend_apply_gradients.<locals>.<lambda>  s    /BCC r   c                  0                                    S r   )(_backend_increment_gradient_accumulators)r   r   rI   s   r   r   z8BaseOptimizer._backend_apply_gradients.<locals>.<lambda>  s    EE9  r   c                  8                           j                  S r   )-_overwrite_model_variables_with_average_valuer=   r_   s   r   r   z8BaseOptimizer._backend_apply_gradients.<locals>.<lambda>  s    DNN1  r   c                      d S r   r   r   r   r   r   z8BaseOptimizer._backend_apply_gradients.<locals>.<lambda>  s    D r   N)r7   rC   r   condr   r)   r5   &_update_model_variables_moving_averager=   r9   r|   )rI   r   r   is_update_stepshould_overwrite_model_varsr   r   s   ```  @@r   r   z&BaseOptimizer._backend_apply_gradientse  s     + "	!#01456N   ,  I
	< 	< 	< 	< 	< 	< HCCCCCC         %%*D,>   < 	77)   +  Oa'0/145/6+ /    !L   	""1%%%%%r   c                 `    t          ||          D ]\  }}|                     |||           dS )zCollective update_step that can be overridden by the backend.

        It is overridden by torch for performance reasons, and
        by TF to support tf.distribute.
        N)r   r   )rI   r   r   r)   gradrk   s         r   r   z"BaseOptimizer._backend_update_step  sG     U$788 	7 	7ID#T36666	7 	7r   c                     | j         D ]5}|                    t          j        |j        |j                             6d S N)r&   )rU   rx   r   rb   rf   r&   )rI   g_accs     r   r   z2BaseOptimizer._backend_reset_gradient_accumulators  sJ    0 	D 	DELL5;ekBBBCCCC	D 	Dr   c                     d t          ||          D             }t          ||          D ]\  }}|                    |           d S )Nc                     g | ]
\  }}||z   S r   r   )r   r   r   s      r   r   zJBaseOptimizer._backend_increment_gradient_accumulators.<locals>.<listcomp>  s     HHHhaq5yHHHr   )r   rx   )rI   r   r   
new_g_accsn_g_accr   s         r   r   z6BaseOptimizer._backend_increment_gradient_accumulators  s[    HH#eY2G2GHHH
!*i88 	" 	"NGULL!!!!	" 	"r   c           
      B   |                                   | j        st          d| j        j         d          t          |          t          | j                  k    rBt          d| j        j         dt          |           dt          | j                   d          t          |          t          | j                  k    r5t          dt          |           dt          | j                   d          t          t          | j        |                    t          t          | j        |                    z   }t          j        |	          5 }|                     |           d d d            n# 1 swxY w Y   g }| j        D ]D}|                    |          }||                    |           /|                    |           Eg }| j        D ]D}|                    |          }||                    |           /|                    |           E||fS )
NzTo call `stateless_apply`, zx must be built (i.e. its variables must have been created). You can build it via `optimizer.build(trainable_variables)`.zNArgument `optimizer_variables` must be a list of tensors corresponding 1:1 to z(().variables. Received list with length z, but expected z variables.zArgument `optimizer_variables` must be a list of tensors corresponding 1:1 to the trainable variables list that the optimizer was built with. Received len(trainable_variables) == z& whereas the optimizer was built with )state_mapping)rg   r;   r.   r/   r0   r   r   r=   r   r   r   StatelessScoper   get_current_valuerX   )rI   optimizer_variablesr   r   mappingscoperu   new_vs           r   stateless_applyzBaseOptimizer.stateless_apply  s     """z 	Odn.E O O O  
 "##s4>':':::=(,(?= =-01D-E-E= =  //= = =   "##s4+D'E'EEE? 033F/G/G? ?
 t011? ? ?   )+>??
 
T^%899::;
 #'::: 	eJJu	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 !* 	. 	.A++A..E #**51111#**1----  	. 	.A++A..E #**51111#**1----"$777s   E66E:=E:c                 (    | j         
|| j         z  S |S )zScale the loss before computing gradients.

        Scales the loss before gradients are computed in a `train_step`. This
        is primarily useful during mixed precision training to prevent numeric
        underflow.
        )r6   )rI   losss     r   
scale_losszBaseOptimizer.scale_loss  s      !-$000r   c                 *    |                                  S r   )_get_current_learning_rater_   s    r   r)   zBaseOptimizer.learning_rate  s    ..000r   c                    t          | j        t          j                  r| j        }nd }t          |t          j                  r|| _        n_t          |          r|| _        nHt          | j        t          j                  rt          d          | j                            |           |6t          | j        t          j                  s| 	                    |           d S d S d S )Na  This optimizer was created with a `LearningRateSchedule` object as its `learning_rate` constructor argument, hence its learning rate is not settable. If you need the learning rate to be settable, you should instantiate the optimizer with a float `learning_rate` argument.)
r   rE   r   r   r   rD   rF   	TypeErrorrx   _untrack_variable)rI   r)   prev_lr_vars      r   r)   zBaseOptimizer.learning_rate  s   d)7+;<< 	-KKK1F
 
 	6 #0Dm$$ 	6"/D#%;%P  	  K   &&}555":!1,
 ,
" "";/////	 #"""r   c                 R   | j         st          d          t          | j        |          D ]z\  }}|j        |j        k    rPt          d|                     |           dt          |j                   dt          |j                   d          |                    |           {dS )z!Set the weights of the optimizer.zYou are calling `set_weights()` on an optimizer that has not yet been built. Please call `optimizer.build(trainable_variables)` to create the optimizer weights before calling `set_weights()`.zOptimizer variable z has shape z+ not compatible with provided weight shape .N)r;   r.   r   r<   rf   rW   rr   rx   )rI   weightsrP   weights       r   set_weightszBaseOptimizer.set_weights   s    z 	D   !$DOW = = 	$ 	$Hf~-- 9$--*A*A 9 98>**9 9$'$5$59 9 9  
 OOF####	$ 	$r   c                     t          | j                  D ])\  }}|                                |t          |          <   *dS )z'Get the state of this optimizer object.N)rV   r   numpyrr   )rI   storerZ   rP   s       r   save_own_variablesz BaseOptimizer.save_own_variables2  sD    $T^44 	- 	-KAx$NN,,E#a&&MM	- 	-r   c           	         t          |                                          t          | j                  k    rwd| j         dt          | j                   dt          |                                           d}t          | j                  dk    r|dz  }t	          j        |d           d	S t          | j                  D ]-\  }}|                    |t          |                              .d	S )
z'Set the state of this optimizer object.z)Skipping variable loading for optimizer 'z', because it has z+ variables whereas the saved optimizer has z variables. r   zCThis is likely because the optimizer has not been called/built yet.r   )
stacklevelN)	r   keysr   r%   r,   r-   rV   rx   rr   )rI   r   msgrZ   rP   s        r   load_own_variablesz BaseOptimizer.load_own_variables7  s   uzz||DN 3 333KDI K K"%dn"5"5K K+.uzz||+<+<K K K 
 4>""a''( M#!,,,,F$T^44 	+ 	+KAxOOE#a&&M****	+ 	+r   c                     t          | j        t          j                  r|                     | j                  S t          | j                  r|                                 S | j        S r   )r   rE   r   rD   rC   rF   r_   s    r   r   z(BaseOptimizer._get_current_learning_rateI  sf    !7!L
 
 	) &&t777d)** 	)&&(((""r   c                   
 t          |d         d          s||fS t          |          }t          |          }t          t          |          dz
  dd          D ]}||         ||         cj        r| j        r| j        }| j        dz   |z  dk    }| j        |                                        
t          j
        |fd
fd          }t          j
        |
fdfd          t          j
        |fd	fd
          }	                    |	           
                    |           n                               |                    |           |                    |           ||fS )a.  Overwrite the variables directly by their gradients.

        This method is designed for a special case where we want to overwrite
        the variable directly with its computed gradient. For example, in float8
        training, new `scale` and `amax_history` are computed as gradients, and
        we want to overwrite them directly instead of following the typical
        procedure such as gradient descent with a learning rate, gradient
        clipping and weight decaying.

        After the update, the processed pairs will be filtered out.
        r   overwrite_with_gradientr   c                  D    t          j         j         j                  S r   )r   rb   rf   r&   r   s   r   r   zLBaseOptimizer._overwrite_variables_directly_with_gradients.<locals>.<lambda>v  s    	!' A A A r   c                  .    t          j                   S r   r   maximumr   r   s   r   r   zLBaseOptimizer._overwrite_variables_directly_with_gradients.<locals>.<lambda>w      Au 5 5 r   c                  .    t          j                   S r   r   r   s   r   r   zLBaseOptimizer._overwrite_variables_directly_with_gradients.<locals>.<lambda>{  r   r   c                       S r   r   r   s   r   r   zLBaseOptimizer._overwrite_variables_directly_with_gradients.<locals>.<lambda>|  s     r   c                       S r   r   )new_gs   r   r   zLBaseOptimizer._overwrite_variables_directly_with_gradients.<locals>.<lambda>  s     r   c                       j         S r   )rz   )ru   s   r   r   zLBaseOptimizer._overwrite_variables_directly_with_gradients.<locals>.<lambda>  s	    qw r   )rp   r   ranger   r   r7   rC   rU   ra   r   r   rx   r+   )rI   r   varsfiltered_gradsfiltered_varsrZ   r   r   	new_g_accr   r   r   r   ru   s             @@@@r   r   z:BaseOptimizer._overwrite_variables_directly_with_gradientsR  s    tAw 9:: 	$; eT

 s>**Q.B77 	% 	%A!!$mA&6DAq( %3   <E&*o&9U%Ba%GN 70033E
 !$&AAAA55555! !I
  H&55555!			 E
  H& E HHUOOOLL++++HHQKKK""1%%%!!!$$$},,r   c                    t          |          }t          |          }g }t          t          |          dz
  dd          D ]N}||         D|                    |           |                    |          }|                    |j                   O|st          d          |r2t          j        dt          t          |                     d           ||fS )Nr   r   z'No gradients provided for any variable.z%Gradients do not exist for variables zc when minimizing the loss. If using `model.compile()`, did you forget to provide a `loss` argument?)
r   r   r   r+   rX   r%   r.   r,   r-   reversed)rI   r   r   r   r   missing_grad_varsrZ   ru   s           r   r   z%BaseOptimizer._filter_empty_gradients  s    eT

 s>**Q.B77 	1 	1Aa (""1%%%!%%a((!((000 	HFGGG 	M#!23344# # #   },,r   c                       j         r j         dk    r fd|D             S  j        r  j        dk    rt          | j                  S  j        r  j        dk    r j        fd|D             S |S )Nr   c                 B    g | ]}|                     |          n|S r   )_clip_by_norm)r   r   rI   s     r   r   z1BaseOptimizer._clip_gradients.<locals>.<listcomp>  s=       BC""1%%%A  r   c                 F    g | ]}|t          j        |           n|S r   )r   clip)r   r   ru   s     r   r   z1BaseOptimizer._clip_gradients.<locals>.<listcomp>  s2    NNN1!-CHQA&&&QNNNr   )r2   r3   clip_by_global_normr4   )rI   r   ru   s   ` @r   r   zBaseOptimizer._clip_gradients  s    = 
	T]Q..   GL    ! 	d&:Q&>&>&ud.BCCC^ 	 2 2ANNNNNNNNLr   c                     t           d          r j        rt          d          |r!t           fd|D                        _        nt                       _        |rMt          |          dk    r:t          j        d                    t          |                               _	        nd _	        t                       _        dS )a  Exclude variables from weight decay.

        This method must be called before the optimizer's `build` method is
        called. You can set specific variables to exclude out, or set a list of
        strings as the anchor words, if any of which appear in a variable's
        name, then the variable is excluded.

        Args:
            var_list: A list of `Variable`s to exclude from weight decay.
            var_names: A list of strings. If any string in `var_names` appear
                in the model variable's name, then this model variable is
                excluded from weight decay. For example, `var_names=['bias']`
                excludes all bias variables from weight decay.
        _builtzR`exclude_from_weight_decay()` can only be configued before the optimizer is built.c              3   B   K   | ]}                     |          V  d S r   )rW   )r   rP   rI   s     r   r   z:BaseOptimizer.exclude_from_weight_decay.<locals>.<genexpr>  s@       2 2,4h''2 2 2 2 2 2r   r   |N)rp   r   r.   set_exclude_from_weight_decayr   recompilejoin"_exclude_from_weight_decay_patterndict _exclude_from_weight_decay_cache)rI   var_list	var_namess   `  r   exclude_from_weight_decayz'BaseOptimizer.exclude_from_weight_decay  s     4"" 	t{ 	*    	4.1 2 2 2 28@2 2 2 / /D++ /2eeD+  	;Y!++68jY((7 7D33 7;D3 15---r   c                    |                      |          }t          | d          st                      | _        || j        v r| j        |         S t	          | dt                                }t	          | dd           }||v rd| j        |<   dS |'t          j        ||j                  	 d| j        |<   dS d| j        |<   dS )Nr   r   r   FT)	rW   rp   r   r   getattrr   r   searchr%   )rI   rP   variable_idr  !exclude_from_weight_decay_patterns        r   _use_weight_decayzBaseOptimizer._use_weight_decay  s    mmH-- t?@@ 	;48FFD1$???8EE %,.%
 %
! -46-
 -
) 333AFD1+>5,8	;X]KK FK5kBu=A-k:tr   c                    | j         d S |D ]s}|                     |          r\t          j        | j        |j                  }t          j        | j         |j                  }|                    |||z  |z  z
             td S r   )r1   r  r   castr)   r&   rx   )rI   r   rP   lrwds        r   r   z!BaseOptimizer._apply_weight_decay  s    $F! 	? 	?H%%h// ?Xd0(.AAXd/@@8b=2+= =>>>		? 	?r   c                 `    t          | d          st          d| j        j         d          d S )Nr*   zIn optimizer 'zh', you forgot to call `super().__init__()` as the first statement in the `__init__()` method. Go add it!)rp   RuntimeErrorr/   r0   r_   s    r   rg   z!BaseOptimizer._check_super_called  sK    tW%% 	!8     	 	r   c                    | j         rxt          || j                  D ]d\  }}t          j        | j        d          }t          j        ||j                  | j        z  }|	                    ||z  d|z
  |z  z              cdS dS )z8Update the stored moving average using the latest value.r   r   N)
r5   r   rT   r   	not_equalrC   r	  r&   r8   rx   )rI   r   rk   rR   not_first_stepmomentums         r   r   z4BaseOptimizer._update_model_variables_moving_average  s    < 	J ##T%I! ! J JW "%t!B!BH^SY77$:KK  x'1Q\S4HHIIII	J 	JJ Jr   c                    t          |          t          | j                  k    r5t          dt          |           dt          | j                   d          t          || j                  D ]\  }}|                    |           dS )z2Overwrite model variables with its moving average.zThe length of model variables (zT) to override does not match the length of model variables stored in the optimizer (z:). Please check if the optimizer was called on your model.N)r   rT   r.   r   rx   )rI   r   rk   average_vars       r   r   z;BaseOptimizer._overwrite_model_variables_with_average_value  s     "##s0(
 (
 
 
 C#6I2J2J C C <==C C C   !$!E!
 !
 	$ 	$C JJ{####	$ 	$r   c                 B    | j         r|                     |           dS dS )a  Set the final value of model's trainable variables.

        Sometimes there are some extra steps before ending the variable updates,
        such as overriding the model variables with its average value.

        Args:
          var_list: list of model variables.
        N)r5   r   )rI   r   s     r   finalize_variable_valuesz&BaseOptimizer.finalize_variable_values#  s7     < 	I >>xHHHHH		I 	Ir   c                     dS )N	Optimizerr   r_   s    r   	_obj_typezBaseOptimizer._obj_type2  s    {r   c                 :   t          | j        t          j                  rt          j        | j                  }nt          | j        t
          j                  r't          | j                                                  }n[t          j
        | j                  rt          | j                  }n-t          | j                  rt          j        | j                  }| j        || j        | j        | j        | j        | j        | j        | j        | j        | j        d}|S )a  Returns the config of the optimizer.

        An optimizer config is a Python dictionary (serializable)
        containing the configuration of an optimizer.
        The same optimizer can be reinstantiated later
        (without any saved state) from this configuration.

        Subclass optimizer should override this method to include other
        hyperparameters.

        Returns:
            Python dictionary.
        )r%   r)   r1   r2   r3   r4   r5   r8   r9   r6   r7   )r   rE   r   rD   	serializer   r   rG   r   r   	is_tensorrF   r   serialize_keras_objectr%   r1   r2   r3   r4   r5   r8   r9   r6   r7   )rI   r)   configs      r   
get_configzBaseOptimizer.get_config5  s    !7!L
 
 	 3<# MM +W-=>> 	!$"5";";"="=>>MM]4.// 	!$"566MMd)** 	-D# M
 I* -#3| -'+'C!%!7+/+K
 
 r   c                     d|v r:t          |d         t                    rt          j        |d         |          |d<    | di |S )a  Creates an optimizer from its config.

        This method is the reverse of `get_config`, capable of instantiating the
        same optimizer from the config dictionary.

        Args:
            config: A Python dictionary, typically the output of get_config.
            custom_objects: A Python dictionary mapping names to additional
              user-defined Python objects needed to recreate this optimizer.

        Returns:
            An optimizer instance.
        r)   )custom_objectsr   )r   r   r   deserialize_keras_object)clsr  r   s      r   from_configzBaseOptimizer.from_configb  sc     f$$&1488 %>/   '
 s}}V}}r   c                     |dk    r|                                   t          | d          r| j                            |          }t	                                          ||          S )Nr*   r?   )rg   rp   r?   tracksuper__setattr__)rI   r%   rz   r/   s      r   r'  zBaseOptimizer.__setattr__z  sa     7??$$&&&4$$ 	/M''..Eww""4///r   c                    t          j        t          j        |          |d          }|dk    }t          j        ||t          j        |                    }t          j        |t          j        |          |          }t          j        || j                  }t          j        |          t          j	        || j                  z  }|S )NT)keepdimsr   )
r   r:   squarewhere	ones_likesqrtmultiplyr2   convert_to_tensorr   )	rI   valuesaxesl2sumpred
l2sum_safel2normintermediatevalues_clips	            r   r   zBaseOptimizer._clip_by_norm  s    
6**D4@@@qyYtUCM%,@,@AA
4*!5!5u==|FDM::+L99CKDM=
 =
 
 r   c                     | j         j        }| j                                          | j                             |           |du r| j                                          d S d S )NT)r?   lockedunlockuntracklock)rI   rP   previous_lock_states      r   r   zBaseOptimizer._untrack_variable  sd    "m2h'''$&&M      '&r   )
NNNNFr   NNNN)rb   Nrc   N)Nrb   r   )NN)3r0   
__module____qualname__rL   rB   r	    no_automatic_dependency_trackingr[   rW   propertyr   ra   ri   rY   rv   rx   r|   r   r   r   r   r   r   r   r   r   r   r)   setterr   r   r   r   r   r   r   r  r  r   rg   r   r   r  r  r  classmethodr#  r'  r   r   __classcell__)r/   s   @r   r   r      sk         $$(}0 }0 }0 }0~: : : .  /.0   " " X"J J J    . :A
 
 
 
,    # # ## # #" " "  EC EC EC ECNF& F& F&P7 7 7D D D" " "
28 28 28h	 	 	 1 1 X1 0 0 0:$ $ $$- - -
+ + +$# # #5- 5- 5-n- - -.  &7 &7 &7 &7P  :? ? ?  
J 
J 
J$ $ $&I I I  + + +Z    [.	0 	0 	0 	0 	0   ! ! ! ! ! ! !r   r   aR  name: String. The name to use
            for momentum accumulator weights created by
            the optimizer.
        weight_decay: Float. If set, weight decay is applied.
        clipnorm: Float. If set, the gradient of each weight is individually
            clipped so that its norm is no higher than this value.
        clipvalue: Float. If set, the gradient of each weight is clipped to be
            no higher than this value.
        global_clipnorm: Float. If set, the gradient of all weights is clipped
            so that their global norm is no higher than this value.
        use_ema: Boolean, defaults to `False`.
            If `True`, exponential moving average
            (EMA) is applied. EMA consists of computing an exponential moving
            average of the weights of the model (as the weight values change
            after each training batch), and periodically overwriting the
            weights with their moving average.
        ema_momentum: Float, defaults to 0.99. Only used if `use_ema=True`.
            This is the momentum to use when computing
            the EMA of the model's weights:
            `new_average = ema_momentum * old_average + (1 - ema_momentum) *
            current_variable_value`.
        ema_overwrite_frequency: Int or None, defaults to None. Only used if
            `use_ema=True`. Every `ema_overwrite_frequency` steps of iterations,
            we overwrite the model variable by its moving average.
            If None, the optimizer
            does not overwrite model variables in the middle of training,
            and you need to explicitly overwrite the variables
            at the end of training by calling
            `optimizer.finalize_variable_values()` (which updates the model
            variables in-place). When using the built-in `fit()` training loop,
            this happens automatically after the last epoch,
            and you don't need to do anything.
        loss_scale_factor: Float or `None`. If a float, the scale factor will
            be multiplied the loss before computing gradients, and the inverse
            of the scale factor will be multiplied by the gradients before
            updating variables. Useful for preventing underflow during
            mixed precision training. Alternately,
            `keras.optimizers.LossScaleOptimizer` will
            automatically set a loss scale factor.
        gradient_accumulation_steps: Int or `None`. If an int, model & optimizer
            variables will not be updated at every step; instead they will be
            updated every `gradient_accumulation_steps` steps, using the average
            value of the gradients since the last update. This is known as
            "gradient accumulation". This can be useful
            when your batch size is very small, in order to reduce gradient
            noise at each update step.
c                     d | D             }t          j        t          j        |                    }t          j        |          S )z-Computes the global norm of multiple tensors.c                 ^    g | ]*}|t          j        t          j        |                    +S r   )r   r:   r*  )r   ru   s     r   r   zglobal_norm.<locals>.<listcomp>  s2       #$am
1mmmr   )r   r:   stackr-  )
value_listsquared_normssquared_norms      r   global_normrK    sK     (2  M 739]3344L8L!!!r   c                     t          |           }|t          j        d|z  d|z            z  }|||z
  z   fd| D             S )Ng      ?c                 "    g | ]}||z  n|S r   r   )r   ru   r   s     r   r   z'clip_by_global_norm.<locals>.<listcomp>  s%    BBB!AIIABBBr   )rK  r   minimum)rH  	clip_normuse_normscale_for_finiter   s       @r   r   r     sZ    :&&H 3;sX~sY#O#OO 8 34EBBBBzBBBBr   )r   r,   	keras.srcr   r   r   keras.src.optimizers.schedulesr   keras.src.savingr   keras.src.saving.keras_saveabler   keras.src.utilsr	   keras.src.utils.namingr
   r   base_optimizer_keyword_argsrK  r   r   r   r   <module>rY     s   				        " " " " " "       A A A A A A . . . . . . 9 9 9 9 9 9 $ $ $ $ $ $ , , , , , ,I! I! I! I! I!M I! I! I!X. b" " "C C C C Cr   