



import argparse
import json
import os

import fairseq
import torch
from fairseq.data import Dictionary

from transformers import (
    WavaVecaConfig,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaForPreTraining,
    WavaVecaProcessor,
    logging,
)
from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification


logging.set_verbosity_info()
_lowercase     							=						logging.get_logger(__name__)

_lowercase     							=						{
    "post_extract_proj": "feature_projection.projection",
    "encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
    "self_attn.k_proj": "encoder.layers.*.attention.k_proj",
    "self_attn.v_proj": "encoder.layers.*.attention.v_proj",
    "self_attn.q_proj": "encoder.layers.*.attention.q_proj",
    "self_attn.out_proj": "encoder.layers.*.attention.out_proj",
    "self_attn_layer_norm": "encoder.layers.*.layer_norm",
    "fc1": "encoder.layers.*.feed_forward.intermediate_dense",
    "fc2": "encoder.layers.*.feed_forward.output_dense",
    "final_layer_norm": "encoder.layers.*.final_layer_norm",
    "encoder.layer_norm": "encoder.layer_norm",
    "adapter_layer": "encoder.layers.*.adapter_layer",
    "w2v_model.layer_norm": "feature_projection.layer_norm",
    "quantizer.weight_proj": "quantizer.weight_proj",
    "quantizer.vars": "quantizer.codevectors",
    "project_q": "project_q",
    "final_proj": "project_hid",
    "w2v_encoder.proj": "lm_head",
    "mask_emb": "masked_spec_embed",
    "pooling_layer.linear": "projector",
    "pooling_layer.projection": "classifier",
}
_lowercase     							=						[
    "lm_head",
    "quantizer.weight_proj",
    "quantizer.codevectors",
    "project_q",
    "project_hid",
    "projector",
    "classifier",
]






def      _A				(UpperCamelCase		:      Optional[Any] )  ->Optional[int]:



			'''simple docstring'''







			lowerCamelCase__ :      Any								=		{}
			with open(_lowerCamelCase      ,			"""r""" ) as file:
						for line_number, line in enumerate(_lowerCamelCase ):
									lowerCamelCase__ :      Dict								=		line.strip()
									if line:
												lowerCamelCase__ :      Optional[int]								=		line.split()
												lowerCamelCase__ :      Dict								=		line_number
												lowerCamelCase__ :      Dict								=		words[0]
												lowerCamelCase__ :      List[str]								=		value
			return result






def      _A				(UpperCamelCase		:      Tuple      ,			UpperCamelCase		:      Optional[Any]      ,			UpperCamelCase		:      str      ,			UpperCamelCase		:      Any      ,			UpperCamelCase		:      Optional[int] )  ->int:



			'''simple docstring'''







			for attribute in key.split(""".""" ):
						lowerCamelCase__ :      Dict								=		getattr(_lowerCamelCase      ,			_lowerCamelCase )

			lowerCamelCase__ :      str								=		None
			for param_key in PARAM_MAPPING.keys():
						if full_name.endswith(_lowerCamelCase ):
									lowerCamelCase__ :      List[str]								=		PARAM_MAPPING[full_name.split(""".""" )[-1]]
									lowerCamelCase__ :      Union[str, Any]								=		"param"

			if weight_type is not None and weight_type != "param":
						lowerCamelCase__ :      Optional[int]								=		getattr(_lowerCamelCase      ,			_lowerCamelCase ).shape
			elif weight_type is not None and weight_type == "param":
						lowerCamelCase__ :      str								=		hf_pointer
						for attribute in hf_param_name.split(""".""" ):
									lowerCamelCase__ :      Optional[Any]								=		getattr(_lowerCamelCase      ,			_lowerCamelCase )
						lowerCamelCase__ :      int								=		shape_pointer.shape

						# let's reduce dimension
						lowerCamelCase__ :      List[Any]								=		value[0]
			else:
						lowerCamelCase__ :      Optional[Any]								=		hf_pointer.shape

			if hf_shape != value.shape:
						raise ValueError(
						    f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"
						    f" {value.shape} for {full_name}" )

			if weight_type == "weight":
						lowerCamelCase__ :      int								=		value
			elif weight_type == "weight_g":
						lowerCamelCase__ :      List[Any]								=		value
			elif weight_type == "weight_v":
						lowerCamelCase__ :      List[Any]								=		value
			elif weight_type == "bias":
						lowerCamelCase__ :      Optional[int]								=		value
			elif weight_type == "param":
						for attribute in hf_param_name.split(""".""" ):
									lowerCamelCase__ :      List[str]								=		getattr(_lowerCamelCase      ,			_lowerCamelCase )
						lowerCamelCase__ :      Dict								=		value
			else:
						lowerCamelCase__ :      Any								=		value

			logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." )






def      _A				(UpperCamelCase		:      Optional[int]      ,			UpperCamelCase		:      Any      ,			UpperCamelCase		:      Dict      ,			UpperCamelCase		:      List[str]      ,			UpperCamelCase		:      Optional[Any] )  ->Dict:



			'''simple docstring'''







			lowerCamelCase__ :      Optional[int]								=		None
			for param_key in PARAM_MAPPING.keys():
						if full_name.endswith(_lowerCamelCase ):
									lowerCamelCase__ :      Union[str, Any]								=		PARAM_MAPPING[full_name.split(""".""" )[-1]]
									lowerCamelCase__ :      Dict								=		"param"

			if weight_type is not None and weight_type != "param":
						lowerCamelCase__ :      Any								=		".".join([key, weight_type] )
			elif weight_type is not None and weight_type == "param":
						lowerCamelCase__ :      List[str]								=		".".join([key, hf_param_name] )
			else:
						lowerCamelCase__ :      Optional[Any]								=		key

			lowerCamelCase__ :      int								=		value if "lm_head" in full_key else value[0]


_lowercase     							=						{
    "W_a": "linear_1.weight",
    "W_b": "linear_2.weight",
    "b_a": "linear_1.bias",
    "b_b": "linear_2.bias",
    "ln_W": "norm.weight",
    "ln_b": "norm.bias",
}






def      _A				(UpperCamelCase		:      Tuple      ,			UpperCamelCase		:      List[str]      ,			UpperCamelCase		:      Union[str, Any]=None      ,			UpperCamelCase		:      List[Any]=None )  ->List[str]:



			'''simple docstring'''







			lowerCamelCase__ :      List[str]								=		False
			for key, mapped_key in MAPPING.items():
						lowerCamelCase__ :      Optional[Any]								=		"wav2vec2." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
						if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]:
									lowerCamelCase__ :      List[Any]								=		True
									if "*" in mapped_key:
												lowerCamelCase__ :      Any								=		name.split(_lowerCamelCase )[0].split(""".""" )[-2]
												lowerCamelCase__ :      Dict								=		mapped_key.replace("""*"""      ,			_lowerCamelCase )
									if "weight_g" in name:
												lowerCamelCase__ :      List[str]								=		"weight_g"
									elif "weight_v" in name:
												lowerCamelCase__ :      str								=		"weight_v"
									elif "bias" in name:
												lowerCamelCase__ :      Optional[Any]								=		"bias"
									elif "weight" in name:
												# TODO: don't match quantizer.weight_proj
												lowerCamelCase__ :      List[Any]								=		"weight"
									else:
												lowerCamelCase__ :      Dict								=		None
									if hf_dict is not None:
												rename_dict(_lowerCamelCase      ,			_lowerCamelCase      ,			_lowerCamelCase      ,			_lowerCamelCase      ,			_lowerCamelCase )
									else:
												set_recursively(_lowerCamelCase      ,			_lowerCamelCase      ,			_lowerCamelCase      ,			_lowerCamelCase      ,			_lowerCamelCase )
									return is_used
			return is_used






def      _A				(UpperCamelCase		:      Union[str, Any]      ,			UpperCamelCase		:      Union[str, Any]      ,			UpperCamelCase		:      Union[str, Any] )  ->Optional[Any]:



			'''simple docstring'''







			lowerCamelCase__ :      List[Any]								=		[]
			lowerCamelCase__ :      Optional[int]								=		fairseq_model.state_dict()

			lowerCamelCase__ :      List[Any]								=		hf_model.wavaveca.feature_extractor

			for name, value in fairseq_dict.items():
						lowerCamelCase__ :      List[Any]								=		False
						if "conv_layers" in name:
									load_conv_layer(
									    _lowerCamelCase      ,			_lowerCamelCase      ,			_lowerCamelCase      ,			_lowerCamelCase      ,			hf_model.config.feat_extract_norm == """group"""      ,			)
									lowerCamelCase__ :      List[str]								=		True
						else:
									lowerCamelCase__ :      Any								=		load_wavaveca_layer(_lowerCamelCase      ,			_lowerCamelCase      ,			_lowerCamelCase )
						if not is_used:
									unused_weights.append(_lowerCamelCase )

			logger.warning(f"Unused weights: {unused_weights}" )






def      _A				(UpperCamelCase		:      Any      ,			UpperCamelCase		:      Optional[int]      ,			UpperCamelCase		:      Optional[Any]      ,			UpperCamelCase		:      Optional[int]      ,			UpperCamelCase		:      Any )  ->Union[str, Any]:



			'''simple docstring'''







			lowerCamelCase__ :      Tuple								=		full_name.split("""conv_layers.""" )[-1]
			lowerCamelCase__ :      Optional[int]								=		name.split(""".""" )
			lowerCamelCase__ :      str								=		int(items[0] )
			lowerCamelCase__ :      Union[str, Any]								=		int(items[1] )

			if type_id == 0:
						if "bias" in name:
									if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
												raise ValueError(
												    f"{full_name} has size {value.shape}, but"
												    f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." )
									lowerCamelCase__ :      List[str]								=		value
									logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." )
						elif "weight" in name:
									if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
												raise ValueError(
												    f"{full_name} has size {value.shape}, but"
												    f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." )
									lowerCamelCase__ :      str								=		value
									logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." )
			elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
						if "bias" in name:
									if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
												raise ValueError(
												    f"{full_name} has size {value.shape}, but"
												    f" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found." )
									lowerCamelCase__ :      Dict								=		value
									logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." )
						elif "weight" in name:
									if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
												raise ValueError(
												    f"{full_name} has size {value.shape}, but"
												    f" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found." )
									lowerCamelCase__ :      List[Any]								=		value
									logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." )
			else:
						unused_weights.append(_lowerCamelCase )






@torch.no_grad()
def      _A				(UpperCamelCase		:      Tuple      ,			UpperCamelCase		:      int      ,			UpperCamelCase		:      Any=None      ,			UpperCamelCase		:      int=None      ,			UpperCamelCase		:      Dict=True      ,			UpperCamelCase		:      Dict=False )  ->Any:



			'''simple docstring'''







			if config_path is not None:
						lowerCamelCase__ :      Optional[int]								=		WavaVecaConfig.from_pretrained(_lowerCamelCase )
			else:
						lowerCamelCase__ :      List[str]								=		WavaVecaConfig()

			if is_seq_class:
						lowerCamelCase__ :      Dict								=		read_txt_into_dict(_lowerCamelCase )
						lowerCamelCase__ :      str								=		idalabel
						lowerCamelCase__ :      Optional[int]								=		WavaVecaForSequenceClassification(_lowerCamelCase )
						lowerCamelCase__ :      Union[str, Any]								=		WavaVecaFeatureExtractor(
						    feature_size=1      ,			sampling_rate=16000      ,			padding_value=0      ,			do_normalize=_lowerCamelCase      ,			return_attention_mask=_lowerCamelCase      ,			)
						feature_extractor.save_pretrained(_lowerCamelCase )

			elif is_finetuned:
						if dict_path:
									lowerCamelCase__ :      Tuple								=		Dictionary.load(_lowerCamelCase )

									# important change bos & pad token id since CTC symbol is <pad> and
									# not <s> as in fairseq
									lowerCamelCase__ :      Union[str, Any]								=		target_dict.pad_index
									lowerCamelCase__ :      List[Any]								=		target_dict.bos_index
									lowerCamelCase__ :      Dict								=		target_dict.eos_index
									lowerCamelCase__ :      List[str]								=		len(target_dict.symbols )
									lowerCamelCase__ :      Optional[int]								=		os.path.join(_lowerCamelCase      ,			"""vocab.json""" )
									if not os.path.isdir(_lowerCamelCase ):
												logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(_lowerCamelCase ) )
												return
									os.makedirs(_lowerCamelCase      ,			exist_ok=_lowerCamelCase )
									lowerCamelCase__ :      Any								=		target_dict.indices

									# fairseq has the <pad> and <s> switched
									lowerCamelCase__ :      List[str]								=		0
									lowerCamelCase__ :      List[Any]								=		1
									with open(_lowerCamelCase      ,			"""w"""      ,			encoding="""utf-8""" ) as vocab_handle:
												json.dump(_lowerCamelCase      ,			_lowerCamelCase )
									lowerCamelCase__ :      Any								=		WavaVecaCTCTokenizer(
									    _lowerCamelCase      ,			unk_token=target_dict.unk_word      ,			pad_token=target_dict.pad_word      ,			bos_token=target_dict.bos_word      ,			eos_token=target_dict.eos_word      ,			word_delimiter_token="""|"""      ,			do_lower_case=_lowerCamelCase      ,			)
									lowerCamelCase__ :      int								=		True if config.feat_extract_norm == "layer" else False
									lowerCamelCase__ :      List[str]								=		WavaVecaFeatureExtractor(
									    feature_size=1      ,			sampling_rate=16000      ,			padding_value=0      ,			do_normalize=_lowerCamelCase      ,			return_attention_mask=_lowerCamelCase      ,			)
									lowerCamelCase__ :      Any								=		WavaVecaProcessor(feature_extractor=_lowerCamelCase      ,			tokenizer=_lowerCamelCase )
									processor.save_pretrained(_lowerCamelCase )

						lowerCamelCase__ :      int								=		WavaVecaForCTC(_lowerCamelCase )
			else:
						lowerCamelCase__ :      List[Any]								=		WavaVecaForPreTraining(_lowerCamelCase )

			if is_finetuned or is_seq_class:
						lowerCamelCase__ :      Union[str, Any]								=		fairseq.checkpoint_utils.load_model_ensemble_and_task(
						    [checkpoint_path]      ,			arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} )
			else:
						lowerCamelCase__ :      List[str]								=		argparse.Namespace(task="""audio_pretraining""" )
						lowerCamelCase__ :      List[str]								=		fairseq.tasks.setup_task(_lowerCamelCase )

						lowerCamelCase__ :      Any								=		fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]      ,			task=_lowerCamelCase )

			lowerCamelCase__ :      Dict								=		model[0].eval()

			recursively_load_weights(_lowerCamelCase      ,			_lowerCamelCase      ,			not is_finetuned )

			hf_wavavec.save_pretrained(_lowerCamelCase )


if __name__ == "__main__":
				_lowercase     							=						argparse.ArgumentParser()
				parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
				parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''')
				parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''')
				parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
				parser.add_argument(
				    '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not'''
				)
				parser.add_argument(
				    '''--is_seq_class''',
				    action='''store_true''',
				    help='''Whether the model to convert is a fine-tuned sequence classification model or not''',
				)
				_lowercase     							=						parser.parse_args()

				_lowercase     							=						not args.not_finetuned and not args.is_seq_class
				convert_wavaveca_checkpoint(
				    args.checkpoint_path,
				    args.pytorch_dump_folder_path,
				    args.config_path,
				    args.dict_path,
				    is_finetuned,
				    args.is_seq_class,
				)








import argparse
import hashlib
import os
import urllib
import warnings

import torch
from torch import nn
from tqdm import tqdm

from transformers import WhisperConfig, WhisperForConditionalGeneration


_lowercase     							=						{
    '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''',
    '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''',
    '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''',
    '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''',
    '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''',
    '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''',
    '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''',
    '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''',
    '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''',
    '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''',
}






def      _A				(UpperCamelCase		:      Any )  ->List[str]:



			'''simple docstring'''







			lowerCamelCase__ :      List[str]								=		["""layers""", """blocks"""]
			for k in ignore_keys:
						state_dict.pop(UpperCamelCase      ,			UpperCamelCase )


_lowercase     							=						{
    '''blocks''': '''layers''',
    '''mlp.0''': '''fc1''',
    '''mlp.2''': '''fc2''',
    '''mlp_ln''': '''final_layer_norm''',
    '''.attn.query''': '''.self_attn.q_proj''',
    '''.attn.key''': '''.self_attn.k_proj''',
    '''.attn.value''': '''.self_attn.v_proj''',
    '''.attn_ln''': '''.self_attn_layer_norm''',
    '''.attn.out''': '''.self_attn.out_proj''',
    '''.cross_attn.query''': '''.encoder_attn.q_proj''',
    '''.cross_attn.key''': '''.encoder_attn.k_proj''',
    '''.cross_attn.value''': '''.encoder_attn.v_proj''',
    '''.cross_attn_ln''': '''.encoder_attn_layer_norm''',
    '''.cross_attn.out''': '''.encoder_attn.out_proj''',
    '''decoder.ln.''': '''decoder.layer_norm.''',
    '''encoder.ln.''': '''encoder.layer_norm.''',
    '''token_embedding''': '''embed_tokens''',
    '''encoder.positional_embedding''': '''encoder.embed_positions.weight''',
    '''decoder.positional_embedding''': '''decoder.embed_positions.weight''',
    '''ln_post''': '''layer_norm''',
}






def      _A				(UpperCamelCase		:      Union[str, Any] )  ->Optional[Any]:



			'''simple docstring'''







			lowerCamelCase__ :      Union[str, Any]								=		list(s_dict.keys() )
			for key in keys:
						lowerCamelCase__ :      Dict								=		key
						for k, v in WHISPER_MAPPING.items():
									if k in key:
												lowerCamelCase__ :      Tuple								=		new_key.replace(UpperCamelCase      ,			UpperCamelCase )

						print(f"{key} -> {new_key}" )

						lowerCamelCase__ :      int								=		s_dict.pop(UpperCamelCase )
			return s_dict






def      _A				(UpperCamelCase		:      List[Any] )  ->Optional[Any]:



			'''simple docstring'''







			lowerCamelCase__							,lowerCamelCase__ :      int								=		emb.weight.shape
			lowerCamelCase__ :      Optional[int]								=		nn.Linear(UpperCamelCase      ,			UpperCamelCase      ,			bias=UpperCamelCase )
			lowerCamelCase__ :      List[str]								=		emb.weight.data
			return lin_layer






def      _A				(UpperCamelCase		:      str      ,			UpperCamelCase		:      str )  ->bytes:



			'''simple docstring'''







			os.makedirs(UpperCamelCase      ,			exist_ok=UpperCamelCase )
			lowerCamelCase__ :      Any								=		os.path.basename(UpperCamelCase )

			lowerCamelCase__ :      int								=		url.split("""/""" )[-2]
			lowerCamelCase__ :      Optional[int]								=		os.path.join(UpperCamelCase      ,			UpperCamelCase )

			if os.path.exists(UpperCamelCase ) and not os.path.isfile(UpperCamelCase ):
						raise RuntimeError(f"{download_target} exists and is not a regular file" )

			if os.path.isfile(UpperCamelCase ):
						lowerCamelCase__ :      Dict								=		open(UpperCamelCase      ,			"""rb""" ).read()
						if hashlib.shaaaa(UpperCamelCase ).hexdigest() == expected_shaaaa:
									return model_bytes
						else:
									warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file" )

			with urllib.request.urlopen(UpperCamelCase ) as source, open(UpperCamelCase      ,			"""wb""" ) as output:
						with tqdm(
						    total=int(source.info().get("""Content-Length""" ) )      ,			ncols=80      ,			unit="""iB"""      ,			unit_scale=UpperCamelCase      ,			unit_divisor=1024 ) as loop:
									while True:
												lowerCamelCase__ :      Tuple								=		source.read(8192 )
												if not buffer:
															break

												output.write(UpperCamelCase )
												loop.update(len(UpperCamelCase ) )

			lowerCamelCase__ :      Any								=		open(UpperCamelCase      ,			"""rb""" ).read()
			if hashlib.shaaaa(UpperCamelCase ).hexdigest() != expected_shaaaa:
						raise RuntimeError(
						    """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.""" )

			return model_bytes






def      _A				(UpperCamelCase		:      Dict      ,			UpperCamelCase		:      Any )  ->Optional[Any]:



			'''simple docstring'''







			if ".pt" not in checkpoint_path:
						lowerCamelCase__ :      Optional[Any]								=		_download(_MODELS[checkpoint_path] )
			else:
						lowerCamelCase__ :      Optional[Any]								=		torch.load(UpperCamelCase      ,			map_location="""cpu""" )
			lowerCamelCase__ :      Optional[int]								=		original_checkpoint["""dims"""]
			lowerCamelCase__ :      int								=		original_checkpoint["""model_state_dict"""]
			lowerCamelCase__ :      Optional[int]								=		state_dict["""decoder.token_embedding.weight"""]
			remove_ignore_keys_(UpperCamelCase )
			rename_keys(UpperCamelCase )
			lowerCamelCase__ :      Optional[int]								=		True
			lowerCamelCase__ :      str								=		state_dict["""decoder.layers.0.fc1.weight"""].shape[0]

			lowerCamelCase__ :      List[str]								=		WhisperConfig(
			    vocab_size=dimensions["""n_vocab"""]      ,			encoder_ffn_dim=UpperCamelCase      ,			decoder_ffn_dim=UpperCamelCase      ,			num_mel_bins=dimensions["""n_mels"""]      ,			d_model=dimensions["""n_audio_state"""]      ,			max_target_positions=dimensions["""n_text_ctx"""]      ,			encoder_layers=dimensions["""n_audio_layer"""]      ,			encoder_attention_heads=dimensions["""n_audio_head"""]      ,			decoder_layers=dimensions["""n_text_layer"""]      ,			decoder_attention_heads=dimensions["""n_text_state"""]      ,			max_source_positions=dimensions["""n_audio_ctx"""]      ,			)

			lowerCamelCase__ :      List[str]								=		WhisperForConditionalGeneration(UpperCamelCase )
			lowerCamelCase__							,lowerCamelCase__ :      str								=		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[str]								=		make_linear_from_emb(model.model.decoder.embed_tokens )
			else:
						lowerCamelCase__ :      int								=		proj_out_weights

			model.save_pretrained(UpperCamelCase )


if __name__ == "__main__":
				_lowercase     							=						argparse.ArgumentParser()
				# # Required parameters
				parser.add_argument('''--checkpoint_path''', type=str, help='''Patht to the downloaded checkpoints''')
				parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
				_lowercase     							=						parser.parse_args()

				convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)



