

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






						"""simple docstring"""




						def __init__(							self					:      int			,			snake_case_					:      float			,			snake_case_					:      Callable			,			snake_case_					:      int			,			snake_case_					:      float = 1.0			,			snake_case_					:      str = None			,			):



								'''simple docstring'''



								super().__init__()
								snake_case__						:       Any       						=  initial_learning_rate
								snake_case__						:       str       						=  warmup_steps
								snake_case__						:       Dict       						=  power
								snake_case__						:       Optional[int]       						=  decay_schedule_fn
								snake_case__						:       str       						=  name







						def __call__(							self					:      Any			,			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`.
										snake_case__						:       Tuple       						=  tf.cast(snake_case_			,			tf.floataa  )
										snake_case__						:       List[str]       						=  tf.cast(self.warmup_steps			,			tf.floataa  )
										snake_case__						:       int       						=  global_step_float / warmup_steps_float
										snake_case__						:       Dict       						=  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       __magic_name__							(							self					:      Tuple  ):



								'''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 	_a       (				__lowerCAmelCase		:      float   ,							__lowerCAmelCase		:      int   ,							__lowerCAmelCase		:      int   ,							__lowerCAmelCase		:      float = 0.0   ,							__lowerCAmelCase		:      float = 0.9   ,							__lowerCAmelCase		:      float = 0.999   ,							__lowerCAmelCase		:      float = 1e-8   ,							__lowerCAmelCase		:      Optional[float] = None   ,							__lowerCAmelCase		:      Optional[float] = None   ,							__lowerCAmelCase		:      float = 0.0   ,							__lowerCAmelCase		:      float = 1.0   ,							__lowerCAmelCase		:      Optional[List[str]] = None   ,							):

		"""simple docstring"""

		snake_case__						:       Union[str, Any]       						=  tf.keras.optimizers.schedules.PolynomialDecay(
		    initial_learning_rate=__lowerCAmelCase   ,							decay_steps=num_train_steps - num_warmup_steps   ,							end_learning_rate=init_lr * min_lr_ratio   ,							power=__lowerCAmelCase   ,							)
		if num_warmup_steps:
				snake_case__						:       Optional[int]       						=  WarmUp(
				    initial_learning_rate=__lowerCAmelCase   ,							decay_schedule_fn=__lowerCAmelCase   ,							warmup_steps=__lowerCAmelCase   ,							)
		if weight_decay_rate > 0.0:
				snake_case__						:       str       						=  AdamWeightDecay(
				    learning_rate=__lowerCAmelCase   ,							weight_decay_rate=__lowerCAmelCase   ,							beta_a=__lowerCAmelCase   ,							beta_a=__lowerCAmelCase   ,							epsilon=__lowerCAmelCase   ,							clipnorm=__lowerCAmelCase   ,							global_clipnorm=__lowerCAmelCase   ,							exclude_from_weight_decay=['''LayerNorm''', '''layer_norm''', '''bias''']   ,							include_in_weight_decay=__lowerCAmelCase   ,							)
		else:
				snake_case__						:       List[str]       						=  tf.keras.optimizers.Adam(
				    learning_rate=__lowerCAmelCase   ,							beta_a=__lowerCAmelCase   ,							beta_a=__lowerCAmelCase   ,							epsilon=__lowerCAmelCase   ,							clipnorm=__lowerCAmelCase   ,							global_clipnorm=__lowerCAmelCase   ,							)
		# 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     a			(				SCREAMING_SNAKE_CASE       ):






						"""simple docstring"""




						def __init__(							self					:      Tuple			,			snake_case_					:      Union[float, tf.keras.optimizers.schedules.LearningRateSchedule] = 0.0_0_1			,			snake_case_					:      float = 0.9			,			snake_case_					:      float = 0.9_9_9			,			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_					:      Any			,			):



								'''simple docstring'''



								super().__init__(snake_case_			,			snake_case_			,			snake_case_			,			snake_case_			,			snake_case_			,			snake_case_			,			**snake_case_  )
								snake_case__						:       str       						=  weight_decay_rate
								snake_case__						:       str       						=  include_in_weight_decay
								snake_case__						:       Union[str, Any]       						=  exclude_from_weight_decay







						@classmethod
						def       __magic_name__							(							cls					:      Dict			,			snake_case_					:      Optional[Any]  ):



								'''simple docstring'''



								snake_case__						:       Optional[Any]       						=  {'''WarmUp''': WarmUp}
								return super(snake_case_			,			cls  ).from_config(snake_case_			,			custom_objects=snake_case_  )







						def       __magic_name__							(							self					:      List[str]			,			snake_case_					:      Tuple			,			snake_case_					:      Dict			,			snake_case_					:      Any  ):



								'''simple docstring'''



								super(snake_case_			,			self  )._prepare_local(snake_case_			,			snake_case_			,			snake_case_  )
								snake_case__						:       Tuple       						=  tf.constant(
								    self.weight_decay_rate			,			name='''adam_weight_decay_rate'''  )







						def       __magic_name__							(							self					:      int			,			snake_case_					:      int			,			snake_case_					:      str			,			snake_case_					:      Any  ):



								'''simple docstring'''



								snake_case__						:       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       __magic_name__							(							self					:      List[Any]			,			snake_case_					:      List[Any]			,			snake_case_					:      List[str]=None			,			**snake_case_					:      str  ):



								'''simple docstring'''



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







						def       __magic_name__							(							self					:      str			,			snake_case_					:      List[str]			,			snake_case_					:      List[str]			,			snake_case_					:      List[Any]  ):



								'''simple docstring'''



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

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

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







						def       __magic_name__							(							self					:      Union[str, Any]			,			snake_case_					:      List[Any]			,			snake_case_					:      str			,			snake_case_					:      List[str]=None  ):



								'''simple docstring'''



								snake_case__						,       snake_case__						:       int       						=  self._get_lr(var.device			,			var.dtype.base_dtype			,			snake_case_  )
								snake_case__						:       List[str]       						=  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       __magic_name__							(							self					:      List[str]			,			snake_case_					:      Optional[int]			,			snake_case_					:      Any			,			snake_case_					:      List[Any]			,			snake_case_					:      Any=None  ):



								'''simple docstring'''



								snake_case__						,       snake_case__						:       int       						=  self._get_lr(var.device			,			var.dtype.base_dtype			,			snake_case_  )
								snake_case__						:       Tuple       						=  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       __magic_name__							(							self					:      Union[str, Any]  ):



								'''simple docstring'''



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







						def       __magic_name__							(							self					:      List[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     a			(				SCREAMING_SNAKE_CASE       ):






						"""simple docstring"""




						def __init__(							self					:      Tuple  ):



								'''simple docstring'''



								snake_case__						:       str       						=  []
								snake_case__						:       List[Any]       						=  None







						@property
						def       __magic_name__							(							self					:      Dict  ):



								'''simple docstring'''



								if self._accum_steps is None:
										snake_case__						:       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       __magic_name__							(							self					:      Tuple  ):



								'''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					:      List[Any]			,			snake_case_					:      int  ):



								'''simple docstring'''



								if not self._gradients:
										snake_case__						:       Optional[Any]       						=  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       __magic_name__							(							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 ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase__						:       Dict										=						logging.get_logger(__name__)

lowerCAmelCase__						:       Tuple										=						{"""ctrl""": """https://huggingface.co/ctrl/resolve/main/config.json"""}




class     a			(				SCREAMING_SNAKE_CASE       ):






						"""simple docstring"""




						__UpperCAmelCase			     =    """ctrl"""
						__UpperCAmelCase			     =    ["""past_key_values"""]
						__UpperCAmelCase			     =    {
						    """max_position_embeddings""": """n_positions""",
						    """hidden_size""": """n_embd""",
						    """num_attention_heads""": """n_head""",
						    """num_hidden_layers""": """n_layer""",
						}







						def __init__(							self					:      Tuple			,			snake_case_					:      Dict=2_4_6_5_3_4			,			snake_case_					:      Optional[int]=2_5_6			,			snake_case_					:      Dict=1_2_8_0			,			snake_case_					:      Union[str, Any]=8_1_9_2			,			snake_case_					:      Any=4_8			,			snake_case_					:      List[Any]=1_6			,			snake_case_					:      Optional[Any]=0.1			,			snake_case_					:      Union[str, Any]=0.1			,			snake_case_					:      Optional[Any]=1e-6			,			snake_case_					:      List[Any]=0.0_2			,			snake_case_					:      Dict=True			,			**snake_case_					:      List[Any]			,			):



								'''simple docstring'''



								snake_case__						:       Any       						=  vocab_size
								snake_case__						:       int       						=  n_positions
								snake_case__						:       Optional[int]       						=  n_embd
								snake_case__						:       str       						=  n_layer
								snake_case__						:       Any       						=  n_head
								snake_case__						:       str       						=  dff
								snake_case__						:       Any       						=  resid_pdrop
								snake_case__						:       Tuple       						=  embd_pdrop
								snake_case__						:       List[str]       						=  layer_norm_epsilon
								snake_case__						:       int       						=  initializer_range

								snake_case__						:       Optional[int]       						=  use_cache

								super().__init__(**snake_case_  )



