


"""simple docstring"""
import argparse
import pickle

import numpy as np
import torch
from torch import nn

from transformers import ReformerConfig, ReformerModelWithLMHead
from transformers.utils import logging


logging.set_verbosity_info()

def 				_snake_case      (   __snake_case							:      str						, __snake_case							:      List[str]						, __snake_case							:      Tuple=None   ):




   """simple docstring"""







   assert torch_layer.weight.shape == weight.shape, F'{torch_layer} layer.weight does not match'
   _lowerCamelCase	:					List[str]   =		nn.Parameter(__snake_case   )
   if bias is not None:
      assert torch_layer.bias.shape == bias.shape, F'{torch_layer} layer.bias does not match'
      _lowerCamelCase	:					Tuple   =		nn.Parameter(__snake_case   )

def 				_snake_case      (   __snake_case							:      Any						, __snake_case							:      Tuple						, __snake_case							:      Optional[Any]   ):




   """simple docstring"""







   _lowerCamelCase	:					Optional[int]   =		np.asarray(weights[0]   )
   _lowerCamelCase	:					Any   =		np.asarray(weights[1]   )
   _lowerCamelCase	:					Dict   =		np.asarray(weights[2]   )

   set_param(
       torch_layer.self_attention.query_key						, torch.tensor(__snake_case   ).transpose(1						, 2   ).contiguous().view(-1						, __snake_case   )						, )
   set_param(
       torch_layer.self_attention.value						, torch.tensor(__snake_case   ).transpose(1						, 2   ).contiguous().view(-1						, __snake_case   )						, )
   set_param(
       torch_layer.output.dense						, torch.tensor(__snake_case   ).view(-1						, __snake_case   ).contiguous().transpose(0						, 1   )						, )

def 				_snake_case      (   __snake_case							:      int						, __snake_case							:      Union[str, Any]						, __snake_case							:      List[Any]   ):




   """simple docstring"""







   _lowerCamelCase	:					Optional[Any]   =		np.asarray(weights[0]   )
   _lowerCamelCase	:					str   =		np.asarray(weights[1]   )
   _lowerCamelCase	:					Any   =		np.asarray(weights[2]   )
   _lowerCamelCase	:					Optional[Any]   =		np.asarray(weights[3]   )

   set_param(
       torch_layer.self_attention.query						, torch.tensor(__snake_case   ).transpose(1						, 2   ).contiguous().view(-1						, __snake_case   )						, )
   set_param(
       torch_layer.self_attention.key						, torch.tensor(__snake_case   ).transpose(1						, 2   ).contiguous().view(-1						, __snake_case   )						, )
   set_param(
       torch_layer.self_attention.value						, torch.tensor(__snake_case   ).transpose(1						, 2   ).contiguous().view(-1						, __snake_case   )						, )
   set_param(
       torch_layer.output.dense						, torch.tensor(__snake_case   ).view(-1						, __snake_case   ).contiguous().transpose(0						, 1   )						, )

def 				_snake_case      (   __snake_case							:      List[str]						, __snake_case							:      Optional[Any]						, __snake_case							:      Dict   ):




   """simple docstring"""







   _lowerCamelCase	:					List[str]   =		weights[0][0][0]
   _lowerCamelCase	:					Optional[int]   =		np.asarray(layer_norm_a[0]   )
   _lowerCamelCase	:					str   =		np.asarray(layer_norm_a[1]   )
   set_param(
       torch_block.attention.layer_norm						, torch.tensor(__snake_case   )						, torch.tensor(__snake_case   )						, )

   # lsh weights + output
   _lowerCamelCase	:					Optional[Any]   =		weights[0][1]
   if len(__snake_case   ) < 4:
      set_layer_weights_in_torch_lsh(__snake_case						, torch_block.attention						, __snake_case   )
   else:
      set_layer_weights_in_torch_local(__snake_case						, torch_block.attention						, __snake_case   )

   # intermediate weighs
   _lowerCamelCase	:					int   =		weights[2][0][1][2]

   # Chunked Feed Forward
   if len(__snake_case   ) == 4:
      _lowerCamelCase	:					Any   =		intermediate_weights[2]

   # layernorm 2
   _lowerCamelCase	:					Any   =		np.asarray(intermediate_weights[0][0]   )
   _lowerCamelCase	:					int   =		np.asarray(intermediate_weights[0][1]   )
   set_param(
       torch_block.feed_forward.layer_norm						, torch.tensor(__snake_case   )						, torch.tensor(__snake_case   )						, )

   # intermediate dense
   _lowerCamelCase	:					Dict   =		np.asarray(intermediate_weights[1][0]   )
   _lowerCamelCase	:					Optional[int]   =		np.asarray(intermediate_weights[1][1]   )
   set_param(
       torch_block.feed_forward.dense.dense						, torch.tensor(__snake_case   ).transpose(0						, 1   ).contiguous()						, torch.tensor(__snake_case   )						, )

   # intermediate out
   _lowerCamelCase	:					Dict   =		np.asarray(intermediate_weights[4][0]   )
   _lowerCamelCase	:					List[Any]   =		np.asarray(intermediate_weights[4][1]   )
   set_param(
       torch_block.feed_forward.output.dense						, torch.tensor(__snake_case   ).transpose(0						, 1   ).contiguous()						, torch.tensor(__snake_case   )						, )

def 				_snake_case      (   __snake_case							:      Optional[int]						, __snake_case							:      Any						, __snake_case							:      Optional[Any]   ):




   """simple docstring"""







   _lowerCamelCase	:					Tuple   =		torch_model.reformer

   # word embeds
   _lowerCamelCase	:					Optional[Any]   =		np.asarray(weights[1]   )
   set_param(
       torch_model_reformer.embeddings.word_embeddings						, torch.tensor(__snake_case   )						, )

   if isinstance(weights[3]						, __snake_case   ):
      _lowerCamelCase	:					List[Any]   =		torch_model_reformer.embeddings.position_embeddings
      for emb_idx in range(len(position_embeddings.weights   )   ):
         _lowerCamelCase	:					Any   =		np.asarray(weights[3][emb_idx][0]   )
         assert (
             position_embeddings.weights[emb_idx].shape == emb_weights.shape
         ), F'{position_embeddings[emb_idx]} emb does not match'
         _lowerCamelCase	:					Optional[int]   =		nn.Parameter(torch.tensor(__snake_case   )   )

   _lowerCamelCase	:					List[str]   =		weights[5]
   assert len(torch_model_reformer.encoder.layers   ) * 4 == len(
       __snake_case   ), "HF and trax model do not have the same number of layers"
   for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers   ):
      _lowerCamelCase	:					str   =		trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)]
      set_block_weights_in_torch(__snake_case						, __snake_case						, __snake_case   )

   # output layer norm
   _lowerCamelCase	:					Any   =		np.asarray(weights[7][0]   )
   _lowerCamelCase	:					Union[str, Any]   =		np.asarray(weights[7][1]   )
   set_param(
       torch_model_reformer.encoder.layer_norm						, torch.tensor(__snake_case   )						, torch.tensor(__snake_case   )						, )

   # output embeddings
   _lowerCamelCase	:					Union[str, Any]   =		np.asarray(weights[9][0]   )
   _lowerCamelCase	:					str   =		np.asarray(weights[9][1]   )
   set_param(
       torch_model.lm_head.decoder						, torch.tensor(__snake_case   ).transpose(0						, 1   ).contiguous()						, torch.tensor(__snake_case   )						, )

def 				_snake_case      (   __snake_case							:      Optional[Any]						, __snake_case							:      Dict						, __snake_case							:      List[Any]   ):




   """simple docstring"""







   _lowerCamelCase	:					List[Any]   =		ReformerConfig.from_json_file(__snake_case   )
   print(F'Building PyTorch model from configuration: {config}'   )
   _lowerCamelCase	:					List[Any]   =		ReformerModelWithLMHead(__snake_case   )

   with open(__snake_case						, """rb"""   ) as f:
      _lowerCamelCase	:					Optional[int]   =		pickle.load(__snake_case   )["""weights"""]

   set_model_weights_in_torch(__snake_case						, __snake_case						, config.hidden_size   )

   # Save pytorch-model
   print(F'Save PyTorch model to {pytorch_dump_path}'   )
   torch.save(model.state_dict()						, __snake_case   )


if __name__ == "__main__":
 UpperCAmelCase				=						argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     """--trax_model_pkl_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path."""
 )
 parser.add_argument(
     """--config_file""",
     default=None,
     type=str,
     required=True,
     help=(
         """The config json file corresponding to the pre-trained Reformer model. \n"""
         """This specifies the model architecture."""
     ),
 )
 parser.add_argument(
     """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
 )
 UpperCAmelCase				=						parser.parse_args()
 convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)





'''simple docstring'''

from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union

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


if TYPE_CHECKING:
 from ...feature_extraction_utils import FeatureExtractionMixin
 from ...tokenization_utils_base import PreTrainedTokenizerBase
 from ...utils import TensorType

lowerCamelCase				:  Dict    		=      logging.get_logger(__name__)

lowerCamelCase				:  List[Any]    		=      {
    'openai/whisper-base': 'https://huggingface.co/openai/whisper-base/resolve/main/config.json',
}

# fmt: off
lowerCamelCase				:  Dict    		=      [
    1, 2, 7, 8, 9, 10, 14, 25,
    26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
    63, 90, 91, 92, 93, 357, 366, 438, 532, 685,
    705, 796, 930, 1_058, 1_220, 1_267, 1_279, 1_303, 1_343, 1_377,
    1_391, 1_635, 1_782, 1_875, 2_162, 2_361, 2_488, 3_467, 4_008, 4_211,
    4_600, 4_808, 5_299, 5_855, 6_329, 7_203, 9_609, 9_959, 10_563, 10_786,
    11_420, 11_709, 11_907, 13_163, 13_697, 13_700, 14_808, 15_306, 16_410, 16_791,
    17_992, 19_203, 19_510, 20_724, 22_305, 22_935, 27_007, 30_109, 30_420, 33_409,
    34_949, 40_283, 40_493, 40_549, 47_282, 49_146, 50_257, 50_359, 50_360, 50_361
]
lowerCamelCase				:  str    		=      [
    1, 2, 7, 8, 9, 10, 14, 25,
    26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
    63, 90, 91, 92, 93, 359, 503, 522, 542, 873,
    893, 902, 918, 922, 931, 1_350, 1_853, 1_982, 2_460, 2_627,
    3_246, 3_253, 3_268, 3_536, 3_846, 3_961, 4_183, 4_667, 6_585, 6_647,
    7_273, 9_061, 9_383, 10_428, 10_929, 11_938, 12_033, 12_331, 12_562, 13_793,
    14_157, 14_635, 15_265, 15_618, 16_553, 16_604, 18_362, 18_956, 20_075, 21_675,
    22_520, 26_130, 26_161, 26_435, 28_279, 29_464, 31_650, 32_302, 32_470, 36_865,
    42_863, 47_425, 49_870, 50_254, 50_258, 50_360, 50_361, 50_362
]
class     __lowerCAmelCase		(lowercase_	):





      '''simple docstring'''






      lowerCAmelCase__   :	List[str]       =				"""whisper"""
      lowerCAmelCase__   :	Dict       =				["""past_key_values"""]
      lowerCAmelCase__   :	Optional[int]       =				{"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}



      def __init__(self       :       int  ,		UpperCamelCase       :       Optional[int]=51865  ,		UpperCamelCase       :       Any=80  ,		UpperCamelCase       :       Dict=6  ,		UpperCamelCase       :       str=4  ,		UpperCamelCase       :       Optional[Any]=6  ,		UpperCamelCase       :       List[Any]=4  ,		UpperCamelCase       :       Tuple=1536  ,		UpperCamelCase       :       Dict=1536  ,		UpperCamelCase       :       Any=0.0  ,		UpperCamelCase       :       Any=0.0  ,		UpperCamelCase       :       int=50257  ,		UpperCamelCase       :       List[str]=True  ,		UpperCamelCase       :       List[Any]=True  ,		UpperCamelCase       :       List[str]="gelu"  ,		UpperCamelCase       :       Dict=256  ,		UpperCamelCase       :       Optional[int]=0.0  ,		UpperCamelCase       :       str=0.0  ,		UpperCamelCase       :       str=0.0  ,		UpperCamelCase       :       Dict=0.02  ,		UpperCamelCase       :       List[Any]=False  ,		UpperCamelCase       :       int=1500  ,		UpperCamelCase       :       List[str]=448  ,		UpperCamelCase       :       int=50256  ,		UpperCamelCase       :       Optional[int]=50256  ,		UpperCamelCase       :       Optional[Any]=50256  ,		UpperCamelCase       :       Any=None  ,		UpperCamelCase       :       Tuple=[220, 50256]  ,		UpperCamelCase       :       Optional[Any]=False  ,		UpperCamelCase       :       int=256  ,		UpperCamelCase       :       Optional[int]=False  ,		UpperCamelCase       :       int=0.05  ,		UpperCamelCase       :       List[Any]=10  ,		UpperCamelCase       :       Optional[int]=2  ,		UpperCamelCase       :       Optional[int]=0.0  ,		UpperCamelCase       :       Dict=10  ,		UpperCamelCase       :       Union[str, Any]=0  ,		UpperCamelCase       :       Union[str, Any]=7  ,		**UpperCamelCase       :       Union[str, Any]  ,		):

             '''simple docstring'''







             lowercase__      =					vocab_size
             lowercase__      =					num_mel_bins
             lowercase__      =					d_model
             lowercase__      =					encoder_layers
             lowercase__      =					encoder_attention_heads
             lowercase__      =					decoder_layers
             lowercase__      =					decoder_attention_heads
             lowercase__      =					decoder_ffn_dim
             lowercase__      =					encoder_ffn_dim
             lowercase__      =					dropout
             lowercase__      =					attention_dropout
             lowercase__      =					activation_dropout
             lowercase__      =					activation_function
             lowercase__      =					init_std
             lowercase__      =					encoder_layerdrop
             lowercase__      =					decoder_layerdrop
             lowercase__      =					use_cache
             lowercase__      =					encoder_layers
             lowercase__      =					scale_embedding  # scale factor will be sqrt(d_model) if True
             lowercase__      =					max_source_positions
             lowercase__      =					max_target_positions

             # Audio Classification-specific parameters. Feel free to ignore for other classes.
             lowercase__      =					classifier_proj_size
             lowercase__      =					use_weighted_layer_sum

             # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
             lowercase__      =					apply_spec_augment
             lowercase__      =					mask_time_prob
             lowercase__      =					mask_time_length
             lowercase__      =					mask_time_min_masks
             lowercase__      =					mask_feature_prob
             lowercase__      =					mask_feature_length
             lowercase__      =					mask_feature_min_masks

             lowercase__      =					median_filter_width

             super().__init__(
                 pad_token_id=UpperCamelCase  ,		bos_token_id=UpperCamelCase  ,		eos_token_id=UpperCamelCase  ,		is_encoder_decoder=UpperCamelCase  ,		decoder_start_token_id=UpperCamelCase  ,		suppress_tokens=UpperCamelCase  ,		begin_suppress_tokens=UpperCamelCase  ,		**UpperCamelCase  ,		)






class     __lowerCAmelCase		(lowercase_	):





      '''simple docstring'''






      @property
      def  UpperCamelCase__						(self       :       str					):

             '''simple docstring'''







             lowercase__      =					OrderedDict(
                 [
                     ('''input_features''', {0: '''batch''', 1: '''feature_size''', 2: '''encoder_sequence'''}),
                 ]					)
             if self.use_past:
                    lowercase__      =					{0: '''batch'''}
             else:
                    lowercase__      =					{0: '''batch''', 1: '''decoder_sequence'''}

             if self.use_past:
                    self.fill_with_past_key_values_(UpperCamelCase  ,		direction='''inputs'''					)

             return common_inputs



      def  UpperCamelCase__						(self       :       Union[str, Any]  ,		UpperCamelCase       :       Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"]  ,		UpperCamelCase       :       int = -1  ,		UpperCamelCase       :       int = -1  ,		UpperCamelCase       :       bool = False  ,		UpperCamelCase       :       Optional["TensorType"] = None  ,		UpperCamelCase       :       int = 22050  ,		UpperCamelCase       :       float = 5.0  ,		UpperCamelCase       :       int = 220  ,		):

             '''simple docstring'''







             lowercase__      =					OrderedDict()
             lowercase__      =					OnnxConfig.generate_dummy_inputs(
                 self  ,		preprocessor=preprocessor.feature_extractor  ,		batch_size=UpperCamelCase  ,		framework=UpperCamelCase  ,		sampling_rate=UpperCamelCase  ,		time_duration=UpperCamelCase  ,		frequency=UpperCamelCase  ,		)
             lowercase__      =					encoder_inputs['''input_features'''].shape[2]
             lowercase__      =					encoder_sequence_length // 2 if self.use_past else seq_length

             lowercase__      =					super().generate_dummy_inputs(
                 preprocessor.tokenizer  ,		UpperCamelCase  ,		UpperCamelCase  ,		UpperCamelCase  ,		UpperCamelCase					)

             lowercase__      =					encoder_inputs.pop('''input_features'''					)
             lowercase__      =					decoder_inputs.pop('''decoder_input_ids'''					)

             if "past_key_values" in decoder_inputs:
                    lowercase__      =					decoder_inputs.pop('''past_key_values'''					)

             return dummy_inputs






      @property
      def  UpperCamelCase__						(self       :       Union[str, Any]					):

             '''simple docstring'''







             return 1E-3




