from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


__a:			Tuple	       =       logging.get_logger(__name__)

__a:			Optional[Any]	       =       {
    """microsoft/focalnet-tiny""": """https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json""",
}



class       UpperCAmelCase  (						a__   ,						a__ ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   "focalnet"

       def __init__(						self     ,       __lowerCAmelCase=224     ,       __lowerCAmelCase=4     ,       __lowerCAmelCase=3     ,       __lowerCAmelCase=96     ,       __lowerCAmelCase=False     ,       __lowerCAmelCase=[192, 384, 768, 768]     ,       __lowerCAmelCase=[2, 2, 6, 2]     ,       __lowerCAmelCase=[2, 2, 2, 2]     ,       __lowerCAmelCase=[3, 3, 3, 3]     ,       __lowerCAmelCase="gelu"     ,       __lowerCAmelCase=4.0     ,       __lowerCAmelCase=0.0     ,       __lowerCAmelCase=0.1     ,       __lowerCAmelCase=False     ,       __lowerCAmelCase=1E-4     ,       __lowerCAmelCase=False     ,       __lowerCAmelCase=False     ,       __lowerCAmelCase=False     ,       __lowerCAmelCase=0.0_2     ,       __lowerCAmelCase=1E-5     ,       __lowerCAmelCase=32     ,       __lowerCAmelCase=None     ,       __lowerCAmelCase=None     ,       **__lowerCAmelCase     ,       )  ->  Union[str, Any]:
        super().__init__(**__lowerCAmelCase			)

        lowercase__    :   int						= image_size
        lowercase__    :   str						= patch_size
        lowercase__    :   Optional[Any]						= num_channels
        lowercase__    :   Tuple						= embed_dim
        lowercase__    :   Tuple						= use_conv_embed
        lowercase__    :   List[str]						= hidden_sizes
        lowercase__    :   List[str]						= depths
        lowercase__    :   Optional[Any]						= focal_levels
        lowercase__    :   Optional[Any]						= focal_windows
        lowercase__    :   Union[str, Any]						= hidden_act
        lowercase__    :   Dict						= mlp_ratio
        lowercase__    :   Dict						= hidden_dropout_prob
        lowercase__    :   Tuple						= drop_path_rate
        lowercase__    :   Optional[int]						= use_layerscale
        lowercase__    :   Tuple						= layerscale_value
        lowercase__    :   List[Any]						= use_post_layernorm
        lowercase__    :   List[str]						= use_post_layernorm_in_modulation
        lowercase__    :   Tuple						= normalize_modulator
        lowercase__    :   Any						= initializer_range
        lowercase__    :   Optional[Any]						= layer_norm_eps
        lowercase__    :   Optional[Any]						= encoder_stride
        lowercase__    :   Dict						= ['''stem'''] + [F"""stage{idx}""" for idx in range(1     ,       len(self.depths			) + 1			)]
        lowercase__    :   Union[str, Any]						= get_aligned_output_features_output_indices(
            out_features=__lowerCAmelCase     ,       out_indices=__lowerCAmelCase     ,       stage_names=self.stage_names			)


'''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       UpperCAmelCase  (						tf.keras.optimizers.schedules.LearningRateSchedule ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase = 1.0     ,       __lowerCAmelCase = None     ,       )  ->  Union[str, Any]:
        super().__init__()
        lowercase__    :   Any						= initial_learning_rate
        lowercase__    :   str						= warmup_steps
        lowercase__    :   Dict						= power
        lowercase__    :   int						= decay_schedule_fn
        lowercase__    :   Dict						= name

       def __call__(						self     ,       __lowerCAmelCase			)  ->  int:
        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__    :   Union[str, Any]						= tf.cast(__lowerCAmelCase     ,       tf.floataa			)
         lowercase__    :   Optional[int]						= tf.cast(self.warmup_steps     ,       tf.floataa			)
         lowercase__    :   Dict						= global_step_float / warmup_steps_float
         lowercase__    :   Dict						= self.initial_learning_rate * tf.math.pow(__lowerCAmelCase     ,       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=__lowerCAmelCase     ,       )


       def _lowerCAmelCase(						self			)  ->  List[str]:
        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       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase = 0.0		,					UpperCAmelCase = 0.9		,					UpperCAmelCase = 0.9_9_9		,					UpperCAmelCase = 1E-8		,					UpperCAmelCase = None		,					UpperCAmelCase = None		,					UpperCAmelCase = 0.0		,					UpperCAmelCase = 1.0		,					UpperCAmelCase = None		,					):
 lowercase__    :   List[Any]						= tf.keras.optimizers.schedules.PolynomialDecay(
     initial_learning_rate=UpperCAmelCase		,					decay_steps=num_train_steps - num_warmup_steps		,					end_learning_rate=init_lr * min_lr_ratio		,					power=UpperCAmelCase		,					)
 if num_warmup_steps:
  lowercase__    :   Optional[Any]						= WarmUp(
      initial_learning_rate=UpperCAmelCase		,					decay_schedule_fn=UpperCAmelCase		,					warmup_steps=UpperCAmelCase		,					)
 if weight_decay_rate > 0.0:
  lowercase__    :   str						= AdamWeightDecay(
      learning_rate=UpperCAmelCase		,					weight_decay_rate=UpperCAmelCase		,					beta_a=UpperCAmelCase		,					beta_a=UpperCAmelCase		,					epsilon=UpperCAmelCase		,					clipnorm=UpperCAmelCase		,					global_clipnorm=UpperCAmelCase		,					exclude_from_weight_decay=['''LayerNorm''', '''layer_norm''', '''bias''']		,					include_in_weight_decay=UpperCAmelCase		,					)
 else:
  lowercase__    :   Any						= tf.keras.optimizers.Adam(
      learning_rate=UpperCAmelCase		,					beta_a=UpperCAmelCase		,					beta_a=UpperCAmelCase		,					epsilon=UpperCAmelCase		,					clipnorm=UpperCAmelCase		,					global_clipnorm=UpperCAmelCase		,					)
 # 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       UpperCAmelCase  (						a__ ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase = 0.0_0_1     ,       __lowerCAmelCase = 0.9     ,       __lowerCAmelCase = 0.9_9_9     ,       __lowerCAmelCase = 1E-7     ,       __lowerCAmelCase = False     ,       __lowerCAmelCase = 0.0     ,       __lowerCAmelCase = None     ,       __lowerCAmelCase = None     ,       __lowerCAmelCase = "AdamWeightDecay"     ,       **__lowerCAmelCase     ,       )  ->  str:
        super().__init__(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       **__lowerCAmelCase			)
        lowercase__    :   int						= weight_decay_rate
        lowercase__    :   Dict						= include_in_weight_decay
        lowercase__    :   List[str]						= exclude_from_weight_decay

       @classmethod
       def _lowerCAmelCase(						cls     ,       __lowerCAmelCase			)  ->  str:
        lowercase__    :   int						= {'''WarmUp''': WarmUp}
        return super(__lowerCAmelCase     ,       cls			).from_config(__lowerCAmelCase     ,       custom_objects=__lowerCAmelCase			)

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)  ->  List[str]:
        super(__lowerCAmelCase     ,       self			)._prepare_local(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)
        lowercase__    :   Any						= tf.constant(
            self.weight_decay_rate     ,       name='''adam_weight_decay_rate'''			)

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)  ->  Tuple:
        lowercase__    :   str						= 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 _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase=None     ,       **__lowerCAmelCase			)  ->  List[Any]:
        lowercase__			,							lowercase__    :   Any						= list(zip(*__lowerCAmelCase			)			)
        return super(__lowerCAmelCase     ,       self			).apply_gradients(zip(__lowerCAmelCase     ,       __lowerCAmelCase			)     ,       name=__lowerCAmelCase     ,       **__lowerCAmelCase			)

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)  ->  Optional[int]:
        if apply_state is None:
         return self._decayed_lr_t[var_dtype], {}

        lowercase__    :   Union[str, Any]						= apply_state or {}
        lowercase__    :   Optional[Any]						= apply_state.get((var_device, var_dtype)			)
        if coefficients is None:
         lowercase__    :   Union[str, Any]						= self._fallback_apply_state(__lowerCAmelCase     ,       __lowerCAmelCase			)
         lowercase__    :   Optional[int]						= coefficients

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

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase=None			)  ->  Any:
        lowercase__			,							lowercase__    :   Dict						= self._get_lr(var.device     ,       var.dtype.base_dtype     ,       __lowerCAmelCase			)
        lowercase__    :   List[str]						= self._decay_weights_op(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)
        with tf.control_dependencies([decay]			):
         return super(__lowerCAmelCase     ,       self			)._resource_apply_dense(__lowerCAmelCase     ,       __lowerCAmelCase     ,       **__lowerCAmelCase			)

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase=None			)  ->  List[str]:
        lowercase__			,							lowercase__    :   List[Any]						= self._get_lr(var.device     ,       var.dtype.base_dtype     ,       __lowerCAmelCase			)
        lowercase__    :   Union[str, Any]						= self._decay_weights_op(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)
        with tf.control_dependencies([decay]			):
         return super(__lowerCAmelCase     ,       self			)._resource_apply_sparse(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       **__lowerCAmelCase			)

       def _lowerCAmelCase(						self			)  ->  List[str]:
        lowercase__    :   Optional[Any]						= super().get_config()
        config.update({'''weight_decay_rate''': self.weight_decay_rate}			)
        return config


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  List[Any]:
        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(__lowerCAmelCase     ,       __lowerCAmelCase			) is not None:
           return True

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



class       UpperCAmelCase  (						a__ ):





       '''simple docstring'''



       def __init__(						self			)  ->  List[Any]:
        lowercase__    :   List[str]						= []
        lowercase__    :   Optional[int]						= None

       @property
       def _lowerCAmelCase(						self			)  ->  Optional[Any]:
        if self._accum_steps is None:
         lowercase__    :   int						= tf.Variable(
             tf.constant(0     ,       dtype=tf.intaa			)     ,       trainable=__lowerCAmelCase     ,       synchronization=tf.VariableSynchronization.ON_READ     ,       aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA     ,       )

        return self._accum_steps.value()

       @property
       def _lowerCAmelCase(						self			)  ->  Union[str, Any]:
        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     ,       __lowerCAmelCase			)  ->  Optional[Any]:
        if not self._gradients:
         lowercase__    :   str						= self.step  # Create the step variable.
         self._gradients.extend(
             [
                 tf.Variable(
                     tf.zeros_like(__lowerCAmelCase			)     ,       trainable=__lowerCAmelCase     ,       synchronization=tf.VariableSynchronization.ON_READ     ,       aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA     ,       )
                 if gradient is not None
                 else gradient
                 for gradient in gradients
             ]			)
        if len(__lowerCAmelCase			) != len(self._gradients			):
         raise ValueError(F"""Expected {len(self._gradients			)} gradients, but got {len(__lowerCAmelCase			)}"""			)

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

        self._accum_steps.assign_add(1			)


       def _lowerCAmelCase(						self			)  ->  Optional[Any]:
        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(__lowerCAmelCase			)			)

