


"""simple docstring"""



import re
from typing import Callable, List, Optional, Union

import tensorflow as tf


try:
 from tensorflow.keras.optimizers.legacy import Adam
except ImportError:
 from tensorflow.keras.optimizers import Adam
class 					__magic_name__		(			tf.keras.optimizers.schedules.LearningRateSchedule     ):






       def __init__(   self  :    List[str]  ,     snake_case__  :    float  ,     snake_case__  :    Callable  ,     snake_case__  :    int  ,     snake_case__  :    float = 1.0  ,     snake_case__  :    str = None  ,     ):

              '''simple docstring'''






              super().__init__()
              lowercase		:Union[str, Any]       							=				initial_learning_rate
              lowercase		:Dict       							=				warmup_steps
              lowercase		:str       							=				power
              lowercase		:int       							=				decay_schedule_fn
              lowercase		:str       							=				name






       def __call__(   self  :    str  ,     snake_case__  :    List[Any]				):

              '''simple docstring'''






              with tf.name_scope(self.name or '''WarmUp'''				) as name:
                     # Implements polynomial warmup. i.e., if global_step < warmup_steps, the
                     # learning rate will be `global_step/num_warmup_steps * init_lr`.
                     lowercase		:Optional[int]       							=				tf.cast(snake_case__  ,     tf.floataa				)
                     lowercase		:Optional[int]       							=				tf.cast(self.warmup_steps  ,     tf.floataa				)
                     lowercase		:Optional[Any]       							=				global_step_float / warmup_steps_float
                     lowercase		:Tuple       							=				self.initial_learning_rate * tf.math.pow(snake_case__  ,     self.power				)
                     return tf.cond(
                         global_step_float < warmup_steps_float  ,     lambda: warmup_learning_rate  ,     lambda: self.decay_schedule_fn(step - self.warmup_steps				)  ,     name=snake_case__  ,     )







       def  __snake_case						(   self  :    List[str]				):

              '''simple docstring'''






              return {
                  "initial_learning_rate": self.initial_learning_rate,
                  "decay_schedule_fn": self.decay_schedule_fn,
                  "warmup_steps": self.warmup_steps,
                  "power": self.power,
                  "name": self.name,
              }







def       lowerCamelCase					(a_						:float				,				a_						:int				,				a_						:int				,				a_						:float = 0.0				,				a_						:float = 0.9				,				a_						:float = 0.9_99				,				a_						:float = 1E-8				,				a_						:Optional[float] = None				,				a_						:Optional[float] = None				,				a_						:float = 0.0				,				a_						:float = 1.0				,				a_						:Optional[List[str]] = None				,				)     ->							List[Any]:
       lowercase		:Tuple       							=				tf.keras.optimizers.schedules.PolynomialDecay(
           initial_learning_rate=a_				,				decay_steps=num_train_steps - num_warmup_steps				,				end_learning_rate=init_lr * min_lr_ratio				,				power=a_				,				)
       if num_warmup_steps:
              lowercase		:Any       							=				WarmUp(
                  initial_learning_rate=a_				,				decay_schedule_fn=a_				,				warmup_steps=a_				,				)
       if weight_decay_rate > 0.0:
              lowercase		:List[Any]       							=				AdamWeightDecay(
                  learning_rate=a_				,				weight_decay_rate=a_				,				beta_a=a_				,				beta_a=a_				,				epsilon=a_				,				clipnorm=a_				,				global_clipnorm=a_				,				exclude_from_weight_decay=['''LayerNorm''', '''layer_norm''', '''bias''']				,				include_in_weight_decay=a_				,				)
       else:
              lowercase		:str       							=				tf.keras.optimizers.Adam(
                  learning_rate=a_				,				beta_a=a_				,				beta_a=a_				,				epsilon=a_				,				clipnorm=a_				,				global_clipnorm=a_				,				)
       # We return the optimizer and the LR scheduler in order to better track the
       # evolution of the LR independently of the optimizer.
       return optimizer, lr_schedule
class 					__magic_name__		(			__UpperCAmelCase     ):






       def __init__(   self  :    Any  ,     snake_case__  :    Union[float, tf.keras.optimizers.schedules.LearningRateSchedule] = 0.0_01  ,     snake_case__  :    float = 0.9  ,     snake_case__  :    float = 0.9_99  ,     snake_case__  :    float = 1e-7  ,     snake_case__  :    bool = False  ,     snake_case__  :    float = 0.0  ,     snake_case__  :    Optional[List[str]] = None  ,     snake_case__  :    Optional[List[str]] = None  ,     snake_case__  :    str = "AdamWeightDecay"  ,     **snake_case__  :    List[Any]  ,     ):

              '''simple docstring'''






              super().__init__(snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     **snake_case__				)
              lowercase		:Optional[Any]       							=				weight_decay_rate
              lowercase		:int       							=				include_in_weight_decay
              lowercase		:Any       							=				exclude_from_weight_decay






       @classmethod
       def  __snake_case						(   cls  :    str  ,     snake_case__  :    List[str]				):

              '''simple docstring'''






              lowercase		:Tuple       							=				{'''WarmUp''': WarmUp}
              return super(snake_case__  ,     cls				).from_config(snake_case__  ,     custom_objects=snake_case__				)






       def  __snake_case						(   self  :    Dict  ,     snake_case__  :    Optional[int]  ,     snake_case__  :    Dict  ,     snake_case__  :    Union[str, Any]				):

              '''simple docstring'''






              super(snake_case__  ,     self				)._prepare_local(snake_case__  ,     snake_case__  ,     snake_case__				)
              lowercase		:List[str]       							=				tf.constant(
                  self.weight_decay_rate  ,     name='''adam_weight_decay_rate'''				)






       def  __snake_case						(   self  :    str  ,     snake_case__  :    Optional[Any]  ,     snake_case__  :    List[str]  ,     snake_case__  :    List[str]				):

              '''simple docstring'''






              lowercase		:Optional[Any]       							=				self._do_use_weight_decay(var.name				)
              if do_decay:
                     return var.assign_sub(
                         learning_rate * var * apply_state[(var.device, var.dtype.base_dtype)]['''weight_decay_rate''']  ,     use_locking=self._use_locking  ,     )
              return tf.no_op()






       def  __snake_case						(   self  :    str  ,     snake_case__  :    int  ,     snake_case__  :    Optional[Any]=None  ,     **snake_case__  :    List[Any]				):

              '''simple docstring'''






              lowercase		:List[Any]       							=				list(zip(*snake_case__				)				)
              return super(snake_case__  ,     self				).apply_gradients(zip(snake_case__  ,     snake_case__				)  ,     name=snake_case__  ,     **snake_case__				)






       def  __snake_case						(   self  :    List[str]  ,     snake_case__  :    Optional[Any]  ,     snake_case__  :    Tuple  ,     snake_case__  :    List[Any]				):

              '''simple docstring'''






              if apply_state is None:
                     return self._decayed_lr_t[var_dtype], {}

              lowercase		:int       							=				apply_state or {}
              lowercase		:Any       							=				apply_state.get((var_device, var_dtype)				)
              if coefficients is None:
                     lowercase		:List[str]       							=				self._fallback_apply_state(snake_case__  ,     snake_case__				)
                     lowercase		:int       							=				coefficients

              return coefficients["lr_t"], {"apply_state": apply_state}






       def  __snake_case						(   self  :    List[str]  ,     snake_case__  :    Optional[Any]  ,     snake_case__  :    Optional[int]  ,     snake_case__  :    List[Any]=None				):

              '''simple docstring'''






              lowercase		:Tuple       							=				self._get_lr(var.device  ,     var.dtype.base_dtype  ,     snake_case__				)
              lowercase		:Dict       							=				self._decay_weights_op(snake_case__  ,     snake_case__  ,     snake_case__				)
              with tf.control_dependencies([decay]				):
                     return super(snake_case__  ,     self				)._resource_apply_dense(snake_case__  ,     snake_case__  ,     **snake_case__				)






       def  __snake_case						(   self  :    Union[str, Any]  ,     snake_case__  :    List[Any]  ,     snake_case__  :    Union[str, Any]  ,     snake_case__  :    Tuple  ,     snake_case__  :    Optional[int]=None				):

              '''simple docstring'''






              lowercase		:Optional[Any]       							=				self._get_lr(var.device  ,     var.dtype.base_dtype  ,     snake_case__				)
              lowercase		:Any       							=				self._decay_weights_op(snake_case__  ,     snake_case__  ,     snake_case__				)
              with tf.control_dependencies([decay]				):
                     return super(snake_case__  ,     self				)._resource_apply_sparse(snake_case__  ,     snake_case__  ,     snake_case__  ,     **snake_case__				)






       def  __snake_case						(   self  :    int				):

              '''simple docstring'''






              lowercase		:Optional[int]       							=				super().get_config()
              config.update({'''weight_decay_rate''': self.weight_decay_rate}				)
              return config







       def  __snake_case						(   self  :    Union[str, Any]  ,     snake_case__  :    Tuple				):

              '''simple docstring'''






              if self.weight_decay_rate == 0:
                     return False

              if self._include_in_weight_decay:
                     for r in self._include_in_weight_decay:
                            if re.search(snake_case__  ,     snake_case__				) is not None:
                                   return True

              if self._exclude_from_weight_decay:
                     for r in self._exclude_from_weight_decay:
                            if re.search(snake_case__  ,     snake_case__				) is not None:
                                   return False
              return True







class 					__magic_name__		(			__UpperCAmelCase     ):






       def __init__(   self  :    Tuple				):

              '''simple docstring'''






              lowercase		:Dict       							=				[]
              lowercase		:Dict       							=				None






       @property
       def  __snake_case						(   self  :    Optional[int]				):

              '''simple docstring'''






              if self._accum_steps is None:
                     lowercase		:Optional[Any]       							=				tf.Variable(
                         tf.constant(0  ,     dtype=tf.intaa				)  ,     trainable=snake_case__  ,     synchronization=tf.VariableSynchronization.ON_READ  ,     aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA  ,     )

              return self._accum_steps.value()






       @property
       def  __snake_case						(   self  :    Dict				):

              '''simple docstring'''






              if not self._gradients:
                     raise ValueError('''The accumulator should be called first to initialize the gradients'''				)
              return [gradient.value() if gradient is not None else gradient for gradient in self._gradients]






       def __call__(   self  :    Union[str, Any]  ,     snake_case__  :    Any				):

              '''simple docstring'''






              if not self._gradients:
                     lowercase		:Dict       							=				self.step  # Create the step variable.
                     self._gradients.extend(
                         [
                             tf.Variable(
                                 tf.zeros_like(snake_case__				)  ,     trainable=snake_case__  ,     synchronization=tf.VariableSynchronization.ON_READ  ,     aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA  ,     )
                             if gradient is not None
                             else gradient
                             for gradient in gradients
                         ]				)
              if len(snake_case__				) != len(self._gradients				):
                     raise ValueError(f"""Expected {len(self._gradients				)} gradients, but got {len(snake_case__				)}"""				)

              for accum_gradient, gradient in zip(self._gradients  ,     snake_case__				):
                     if accum_gradient is not None and gradient is not None:
                            accum_gradient.assign_add(snake_case__				)

              self._accum_steps.assign_add(1				)







       def  __snake_case						(   self  :    str				):

              '''simple docstring'''






              if not self._gradients:
                     return
              self._accum_steps.assign(0				)
              for gradient in self._gradients:
                     if gradient is not None:
                            gradient.assign(tf.zeros_like(snake_case__				)				)










"""simple docstring"""



from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


UpperCAmelCase      		=			logging.get_logger(__name__)

UpperCAmelCase      		=			{
    '''facebook/deit-base-distilled-patch16-224''': (
        '''https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json'''
    ),
    # See all DeiT models at https://huggingface.co/models?filter=deit
}
class 					__magic_name__		(			__UpperCAmelCase     ):
       __A			:      Tuple        =   "deit"






       def __init__(   self  :    List[str]  ,     snake_case__  :    int=7_6_8  ,     snake_case__  :    List[Any]=1_2  ,     snake_case__  :    Dict=1_2  ,     snake_case__  :    List[Any]=3_0_7_2  ,     snake_case__  :    Optional[int]="gelu"  ,     snake_case__  :    Dict=0.0  ,     snake_case__  :    str=0.0  ,     snake_case__  :    List[str]=0.02  ,     snake_case__  :    Optional[int]=1e-1_2  ,     snake_case__  :    Any=2_2_4  ,     snake_case__  :    Optional[int]=1_6  ,     snake_case__  :    int=3  ,     snake_case__  :    str=True  ,     snake_case__  :    Optional[int]=1_6  ,     **snake_case__  :    List[Any]  ,     ):

              '''simple docstring'''






              super().__init__(**snake_case__				)

              lowercase		:List[str]       							=				hidden_size
              lowercase		:Union[str, Any]       							=				num_hidden_layers
              lowercase		:Optional[Any]       							=				num_attention_heads
              lowercase		:Optional[Any]       							=				intermediate_size
              lowercase		:int       							=				hidden_act
              lowercase		:int       							=				hidden_dropout_prob
              lowercase		:Dict       							=				attention_probs_dropout_prob
              lowercase		:Optional[int]       							=				initializer_range
              lowercase		:Tuple       							=				layer_norm_eps
              lowercase		:Optional[int]       							=				image_size
              lowercase		:Union[str, Any]       							=				patch_size
              lowercase		:Optional[Any]       							=				num_channels
              lowercase		:Tuple       							=				qkv_bias
              lowercase		:Optional[Any]       							=				encoder_stride







class 					__magic_name__		(			__UpperCAmelCase     ):
       __A			:      Optional[int]        =   version.parse("1.11"     )






       @property
       def  __snake_case						(   self  :    int				):

              '''simple docstring'''






              return OrderedDict(
                  [
                      ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
                  ]				)







       @property
       def  __snake_case						(   self  :    Optional[int]				):

              '''simple docstring'''






              return 1e-4

