


'''simple docstring'''



import argparse

import torch
from torch import nn

from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration



def      UpperCAmelCase__   (      UpperCAmelCase_       :							Optional[Any]				)	->						Dict:
     __lowerCamelCase  :      Any														=						[
         'encoder.version',
         'decoder.version',
         'model.encoder.version',
         'model.decoder.version',
         'decoder.output_projection.weight',
         '_float_tensor',
         'encoder.embed_positions._float_tensor',
         'decoder.embed_positions._float_tensor',
     ]
     for k in ignore_keys:
          state_dict.pop(UpperCAmelCase_ ,       UpperCAmelCase_				)



def      UpperCAmelCase__   (      UpperCAmelCase_       :							Tuple				)	->						Optional[Any]:
     __lowerCamelCase  :      Optional[Any]														=						list(s_dict.keys()				)
     for key in keys:
          if "transformer_layers" in key:
               __lowerCamelCase  :      List[str]														=						s_dict.pop(UpperCAmelCase_				)
          elif "subsample" in key:
               __lowerCamelCase  :      Optional[int]														=						s_dict.pop(UpperCAmelCase_				)



def      UpperCAmelCase__   (      UpperCAmelCase_       :							Optional[Any]				)	->						int:
     __lowerCamelCase							,			__lowerCamelCase  :      List[str]														=						emb.weight.shape
     __lowerCamelCase  :      List[str]														=						nn.Linear(UpperCAmelCase_ ,       UpperCAmelCase_ ,       bias=UpperCAmelCase_				)
     __lowerCamelCase  :      int														=						emb.weight.data
     return lin_layer



def      UpperCAmelCase__   (      UpperCAmelCase_       :							int ,       UpperCAmelCase_       :							Any				)	->						List[Any]:
     __lowerCamelCase  :      Tuple														=						torch.load(UpperCAmelCase_ ,       map_location='cpu'				)
     __lowerCamelCase  :      Any														=						mam_aaa['args']
     __lowerCamelCase  :      Any														=						mam_aaa['model']
     __lowerCamelCase  :      Optional[Any]														=						state_dict['decoder.output_projection.weight']

     remove_ignore_keys_(UpperCAmelCase_				)
     rename_keys(UpperCAmelCase_				)

     __lowerCamelCase  :      Tuple														=						state_dict['decoder.embed_tokens.weight'].shape[0]

     __lowerCamelCase  :      Optional[int]														=						args.share_decoder_input_output_embed

     __lowerCamelCase  :      Optional[int]														=						[int(UpperCAmelCase_				) for i in args.conv_kernel_sizes.split(','				)]
     __lowerCamelCase  :      int														=						SpeechaTextConfig(
         vocab_size=UpperCAmelCase_ ,       max_source_positions=args.max_source_positions ,       max_target_positions=args.max_target_positions ,       encoder_layers=args.encoder_layers ,       decoder_layers=args.decoder_layers ,       encoder_attention_heads=args.encoder_attention_heads ,       decoder_attention_heads=args.decoder_attention_heads ,       encoder_ffn_dim=args.encoder_ffn_embed_dim ,       decoder_ffn_dim=args.decoder_ffn_embed_dim ,       d_model=args.encoder_embed_dim ,       dropout=args.dropout ,       attention_dropout=args.attention_dropout ,       activation_dropout=args.activation_dropout ,       activation_function='relu' ,       num_conv_layers=len(UpperCAmelCase_				) ,       conv_channels=args.conv_channels ,       conv_kernel_sizes=UpperCAmelCase_ ,       input_feat_per_channel=args.input_feat_per_channel ,       input_channels=args.input_channels ,       tie_word_embeddings=UpperCAmelCase_ ,       num_beams=5 ,       max_length=2_00 ,       use_cache=UpperCAmelCase_ ,       decoder_start_token_id=2 ,       early_stopping=UpperCAmelCase_ ,       )

     __lowerCamelCase  :      str														=						SpeechaTextForConditionalGeneration(UpperCAmelCase_				)
     __lowerCamelCase							,			__lowerCamelCase  :      Optional[int]														=						model.model.load_state_dict(UpperCAmelCase_ ,       strict=UpperCAmelCase_				)
     if len(UpperCAmelCase_				) > 0 and not set(UpperCAmelCase_				) <= {
         "encoder.embed_positions.weights",
         "decoder.embed_positions.weights",
     }:
          raise ValueError(
              'Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights`  are allowed to be missing,'
              F' but all the following weights are missing {missing}'				)

     if tie_embeds:
          __lowerCamelCase  :      List[Any]														=						make_linear_from_emb(model.model.decoder.embed_tokens				)
     else:
          __lowerCamelCase  :      int														=						lm_head_weights

     model.save_pretrained(UpperCAmelCase_				)


if __name__ == "__main__":
      A__						:   Any				=    argparse.ArgumentParser()
      # Required parameters
      parser.add_argument("""--fairseq_path""", type=str, help="""Path to the fairseq model (.pt) file.""")
      parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
      A__						:   List[str]				=    parser.parse_args()
      convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)










'''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     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_ = 1.0     ,	SCREAMING_SNAKE_CASE_ = None     ,	)							->	Any:
         super().__init__()
         __lowerCamelCase  :      Optional[Any]														=						initial_learning_rate
         __lowerCamelCase  :      Optional[Any]														=						warmup_steps
         __lowerCamelCase  :      Union[str, Any]														=						power
         __lowerCamelCase  :      Optional[int]														=						decay_schedule_fn
         __lowerCamelCase  :      Any														=						name







    def __call__(				self     ,	SCREAMING_SNAKE_CASE_      )							->	str:
         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`.
              __lowerCamelCase  :      str														=						tf.cast(SCREAMING_SNAKE_CASE_     ,	tf.floataa      )
              __lowerCamelCase  :      Optional[int]														=						tf.cast(self.warmup_steps     ,	tf.floataa      )
              __lowerCamelCase  :      List[Any]														=						global_step_float / warmup_steps_float
              __lowerCamelCase  :      Optional[Any]														=						self.initial_learning_rate * tf.math.pow(SCREAMING_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=SCREAMING_SNAKE_CASE_     ,	)







    def  lowercase_							(				self      )							->	Optional[Any]:
         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_       :							float ,       UpperCAmelCase_       :							int ,       UpperCAmelCase_       :							int ,       UpperCAmelCase_       :							float = 0.0 ,       UpperCAmelCase_       :							float = 0.9 ,       UpperCAmelCase_       :							float = 0.999 ,       UpperCAmelCase_       :							float = 1e-8 ,       UpperCAmelCase_       :							Optional[float] = None ,       UpperCAmelCase_       :							Optional[float] = None ,       UpperCAmelCase_       :							float = 0.0 ,       UpperCAmelCase_       :							float = 1.0 ,       UpperCAmelCase_       :							Optional[List[str]] = None ,       )	->						int:
     __lowerCamelCase  :      int														=						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:
          __lowerCamelCase  :      str														=						WarmUp(
              initial_learning_rate=UpperCAmelCase_ ,       decay_schedule_fn=UpperCAmelCase_ ,       warmup_steps=UpperCAmelCase_ ,       )
     if weight_decay_rate > 0.0:
          __lowerCamelCase  :      List[Any]														=						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:
          __lowerCamelCase  :      Tuple														=						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_    (_UpperCAmelCase    ):





    """simple docstring"""






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







    @classmethod
    def  lowercase_							(				cls     ,	SCREAMING_SNAKE_CASE_      )							->	Dict:
         __lowerCamelCase  :      Any														=						{'WarmUp': WarmUp}
         return super(SCREAMING_SNAKE_CASE_     ,	cls      ).from_config(SCREAMING_SNAKE_CASE_     ,	custom_objects=SCREAMING_SNAKE_CASE_      )







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )							->	Optional[int]:
         super(SCREAMING_SNAKE_CASE_     ,	self      )._prepare_local(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      Union[str, Any]														=						tf.constant(
             self.weight_decay_rate     ,	name='adam_weight_decay_rate'      )







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )							->	int:
         __lowerCamelCase  :      Tuple														=						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  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=None     ,	**SCREAMING_SNAKE_CASE_      )							->	List[str]:
         __lowerCamelCase							,			__lowerCamelCase  :      Optional[Any]														=						list(zip(*SCREAMING_SNAKE_CASE_      )      )
         return super(SCREAMING_SNAKE_CASE_     ,	self      ).apply_gradients(zip(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )     ,	name=SCREAMING_SNAKE_CASE_     ,	**SCREAMING_SNAKE_CASE_      )







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )							->	str:
         if apply_state is None:
              return self._decayed_lr_t[var_dtype], {}

         __lowerCamelCase  :      Optional[int]														=						apply_state or {}
         __lowerCamelCase  :      Dict														=						apply_state.get((var_device, var_dtype)      )
         if coefficients is None:
              __lowerCamelCase  :      List[Any]														=						self._fallback_apply_state(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )
              __lowerCamelCase  :      Optional[Any]														=						coefficients

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







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=None      )							->	str:
         __lowerCamelCase							,			__lowerCamelCase  :      Dict														=						self._get_lr(var.device     ,	var.dtype.base_dtype     ,	SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      Optional[Any]														=						self._decay_weights_op(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )
         with tf.control_dependencies([decay]      ):
              return super(SCREAMING_SNAKE_CASE_     ,	self      )._resource_apply_dense(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	**SCREAMING_SNAKE_CASE_      )







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







    def  lowercase_							(				self      )							->	List[Any]:
         __lowerCamelCase  :      Any														=						super().get_config()
         config.update({'weight_decay_rate': self.weight_decay_rate}      )
         return config







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_      )							->	Dict:
         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(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      ) is not None:
                        return True

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







class   UpperCAmelCase_    (_UpperCAmelCase    ):





    """simple docstring"""






    def __init__(				self      )							->	Tuple:
         __lowerCamelCase  :      Tuple														=						[]
         __lowerCamelCase  :      Optional[Any]														=						None







    @property
    def  lowercase_							(				self      )							->	List[str]:
         if self._accum_steps is None:
              __lowerCamelCase  :      Tuple														=						tf.Variable(
                  tf.constant(0     ,	dtype=tf.intaa      )     ,	trainable=SCREAMING_SNAKE_CASE_     ,	synchronization=tf.VariableSynchronization.ON_READ     ,	aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA     ,	)

         return self._accum_steps.value()







    @property
    def  lowercase_							(				self      )							->	List[str]:
         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     ,	SCREAMING_SNAKE_CASE_      )							->	str:
         if not self._gradients:
              __lowerCamelCase  :      List[str]														=						self.step  # Create the step variable.
              self._gradients.extend(
                  [
                      tf.Variable(
                          tf.zeros_like(SCREAMING_SNAKE_CASE_      )     ,	trainable=SCREAMING_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(SCREAMING_SNAKE_CASE_      ) != len(self._gradients      ):
              raise ValueError(f'Expected {len(self._gradients      )} gradients, but got {len(SCREAMING_SNAKE_CASE_      )}'      )

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

         self._accum_steps.assign_add(1      )







    def  lowercase_							(				self      )							->	int:
         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(SCREAMING_SNAKE_CASE_      )      )






