






"""simple docstring"""



import argparse

import fairseq
import torch
from torch import nn

from transformers import (
    MBartaaTokenizer,
    MBartConfig,
    MBartForCausalLM,
    SpeechEncoderDecoderConfig,
    SpeechEncoderDecoderModel,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaModel,
    logging,
)


logging.set_verbosity_info()
__A		:       Optional[Any]  				=		logging.get_logger(__name__)

__A		:       Optional[Any]  				=		{
    '''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''',
    '''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''',
}
__A		:       Tuple  				=		[
    '''lm_head''',
    '''quantizer.weight_proj''',
    '''quantizer.codevectors''',
    '''project_q''',
    '''project_hid''',
]



def 						lowercase    (				__snake_case				: Any		,					__snake_case				: Optional[Any]		,					__snake_case				: int		,					__snake_case				: Union[str, Any]		,					__snake_case				: int	):
		for attribute in key.split('''.'''	):
				lowercase_ : List[Any]							       =   getattr(__snake_case		,					__snake_case	)

		if weight_type is not None:
				lowercase_ : Optional[int]							       =   getattr(__snake_case		,					__snake_case	).shape
		else:
				lowercase_ : Optional[int]							       =   hf_pointer.shape

		assert hf_shape == value.shape, (
		    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":
				lowercase_ : List[Any]							       =   value
		elif weight_type == "weight_g":
				lowercase_ : List[str]							       =   value
		elif weight_type == "weight_v":
				lowercase_ : List[str]							       =   value
		elif weight_type == "bias":
				lowercase_ : List[str]							       =   value
		else:
				lowercase_ : List[Any]							       =   value

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



def 						lowercase    (				__snake_case				: str		,					__snake_case				: Union[str, Any]	):
		lowercase_ : Optional[Any]							       =   []
		lowercase_ : int							       =   fairseq_model.state_dict()

		lowercase_ : List[Any]							       =   hf_model.feature_extractor
		lowercase_ : str							       =   hf_model.adapter

		for name, value in fairseq_dict.items():
				lowercase_ : int							       =   False
				if "conv_layers" in name:
						load_conv_layer(
						    __snake_case		,					__snake_case		,					__snake_case		,					__snake_case		,					hf_model.config.feat_extract_norm == '''group'''		,					)
						lowercase_ : List[Any]							       =   True
				elif any(x in name for x in ['''adaptor''', '''w2v_encoder.proj.''', '''w2v_proj_ln.''']	):
						load_adapter(__snake_case		,					__snake_case		,					__snake_case		,					__snake_case	)
						lowercase_ : List[Any]							       =   True
				else:
						for key, mapped_key in MAPPING.items():
								if key in name or key.split('''w2v_model.'''	)[-1] == name.split('''.'''	)[0]:
										lowercase_ : Optional[int]							       =   True
										if "*" in mapped_key:
												lowercase_ : Any							       =   name.split(__snake_case	)[0].split('''.'''	)[-2]
												lowercase_ : Any							       =   mapped_key.replace('''*'''		,					__snake_case	)
										if "weight_g" in name:
												lowercase_ : Optional[int]							       =   '''weight_g'''
										elif "weight_v" in name:
												lowercase_ : str							       =   '''weight_v'''
										elif "bias" in name:
												lowercase_ : Optional[int]							       =   '''bias'''
										elif "weight" in name:
												lowercase_ : Optional[Any]							       =   '''weight'''
										else:
												lowercase_ : List[Any]							       =   None
										set_recursively(__snake_case		,					__snake_case		,					__snake_case		,					__snake_case		,					__snake_case	)
								continue
				if not is_used:
						unused_weights.append(__snake_case	)

		logger.warning(F'''Unused weights: {unused_weights}'''	)



def 						lowercase    (				__snake_case				: Any		,					__snake_case				: str		,					__snake_case				: List[Any]		,					__snake_case				: List[Any]		,					__snake_case				: str	):
		lowercase_ : Union[str, Any]							       =   full_name.split('''conv_layers.'''	)[-1]
		lowercase_ : List[str]							       =   name.split('''.'''	)
		lowercase_ : int							       =   int(items[0]	)
		lowercase_ : Optional[int]							       =   int(items[1]	)

		if type_id == 0:
				if "bias" in name:
						assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
						    F'''{full_name} has size {value.shape}, but'''
						    F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'''
						)
						lowercase_ : Optional[int]							       =   value
						logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''	)
				elif "weight" in name:
						assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
						    F'''{full_name} has size {value.shape}, but'''
						    F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'''
						)
						lowercase_ : Tuple							       =   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:
						assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
						    F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was'''
						    " found."
						)
						lowercase_ : List[Any]							       =   value
						logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''	)
				elif "weight" in name:
						assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
						    F'''{full_name} has size {value.shape}, but'''
						    F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'''
						)
						lowercase_ : Optional[int]							       =   value
						logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''	)
		else:
				unused_weights.append(__snake_case	)



def 						lowercase    (				__snake_case				: Union[str, Any]		,					__snake_case				: List[str]		,					__snake_case				: str		,					__snake_case				: Optional[int]	):
		lowercase_ : Union[str, Any]							       =   full_name.split('''adaptor.'''	)[-1]
		lowercase_ : Optional[Any]							       =   name.split('''.'''	)

		if items[1].isdigit():
				lowercase_ : Optional[Any]							       =   int(items[1]	)
		else:
				lowercase_ : Tuple							       =   None

		if "adaptor" not in full_name:
				if "proj_ln" in full_name:
						# has to be layer norm
						if "bias" in name:
								assert (
								    value.shape == adapter.proj_layer_norm.bias.data.shape
								), F'''{full_name} has size {value.shape}, but {adapter.proj_layer_norm.bias.data.shape} was found.'''
								lowercase_ : int							       =   value
								logger.info(F'''Adapter proj layer norm bias was initialized from {full_name}.'''	)
						if "weight" in name:
								assert (
								    value.shape == adapter.proj_layer_norm.weight.data.shape
								), F'''{full_name} has size {value.shape}, but {adapter.proj_layer_norm.weight.data.shape} was found.'''
								lowercase_ : Tuple							       =   value
				else:
						# has to be projection layer
						if "bias" in name:
								assert (
								    value.shape == adapter.proj.bias.data.shape
								), F'''{full_name} has size {value.shape}, but {adapter.proj.bias.data.shape} was found.'''
								lowercase_ : List[Any]							       =   value
								logger.info(F'''Adapter proj layer bias was initialized from {full_name}.'''	)
						if "weight" in name:
								assert (
								    value.shape == adapter.proj.weight.data.shape
								), F'''{full_name} has size {value.shape}, but {adapter.proj.weight.data.shape} was found.'''
								lowercase_ : Any							       =   value
								logger.info(F'''Adapter proj layer weight was initialized from {full_name}.'''	)
		elif isinstance(__snake_case		,					__snake_case	):
				if "bias" in name:
						assert (
						    value.shape == adapter.layers[layer_id].conv.bias.data.shape
						), F'''{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.bias.data.shape} was found.'''
						lowercase_ : List[str]							       =   value
						logger.info(F'''Adapter layer {layer_id} bias was initialized from {full_name}.'''	)
				elif "weight" in name:
						assert (
						    value.shape == adapter.layers[layer_id].conv.weight.data.shape
						), F'''{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.weight.data.shape} was found.'''
						lowercase_ : Any							       =   value
						logger.info(F'''Adapter layer {layer_id} bias was initialized from {full_name}.'''	)
		else:
				unused_weights.append(__snake_case	)



def 						lowercase    (				__snake_case				: int	):
		lowercase_       ,					lowercase_ : Any							       =   emb.weight.shape
		lowercase_ : List[Any]							       =   nn.Linear(__snake_case		,					__snake_case		,					bias=__snake_case	)
		lowercase_ : Optional[Any]							       =   emb.weight.data
		return lin_layer



@torch.no_grad()
def 						lowercase    (				__snake_case				: Dict		,					__snake_case				: List[Any]		,					__snake_case				: List[Any]		,					__snake_case				: Dict		,					__snake_case				: Dict		,					__snake_case				: Optional[int]		,					__snake_case				: int		,					__snake_case				: str		,					__snake_case				: Optional[int]		,					__snake_case				: Optional[Any]		,					__snake_case				: Any		,					):
		lowercase_ : Any							       =   WavaVecaConfig.from_pretrained(
		    __snake_case		,					add_adapter=__snake_case		,					adapter_stride=__snake_case		,					adapter_kernel_size=__snake_case		,					use_auth_token=__snake_case		,					output_hidden_size=__snake_case		,					)
		lowercase_ : Any							       =   MBartConfig.from_pretrained(__snake_case	)

		# load model
		lowercase_       ,					lowercase_       ,					lowercase_ : List[str]							       =   fairseq.checkpoint_utils.load_model_ensemble_and_task(
		    [checkpoint_path]		,					arg_overrides={
		        '''config_yaml''': config_yaml_path,
		        '''data''': '''/'''.join(dict_path.split('''/'''	)[:-1]	),
		        '''w2v_path''': checkpoint_path,
		        '''load_pretrained_decoder_from''': None,
		    }		,					)
		lowercase_ : str							       =   model[0].eval()

		# load feature extractor
		lowercase_ : Optional[int]							       =   WavaVecaFeatureExtractor.from_pretrained(__snake_case		,					use_auth_token=__snake_case	)

		# set weights for wav2vec2 encoder
		lowercase_ : List[Any]							       =   WavaVecaModel(__snake_case	)

		recursively_load_weights_wavaveca(model.encoder		,					__snake_case	)

		# load decoder weights
		lowercase_ : Optional[int]							       =   MBartForCausalLM(__snake_case	)
		lowercase_       ,					lowercase_ : Dict							       =   hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict()		,					strict=__snake_case	)
		logger.warning(F'''The following keys are missing when loading the decoder weights: {missing_keys}'''	)
		logger.warning(F'''The following keys are unexpected when loading the decoder weights: {unexpected_keys}'''	)

		lowercase_ : int							       =   SpeechEncoderDecoderModel(encoder=__snake_case		,					decoder=__snake_case	)
		lowercase_ : Optional[int]							       =   False

		lowercase_ : Optional[Any]							       =   MBartaaTokenizer(__snake_case	)
		tokenizer.save_pretrained(__snake_case	)

		lowercase_ : List[str]							       =   hf_wavavec.config.to_dict()
		lowercase_ : List[Any]							       =   tokenizer.pad_token_id
		lowercase_ : Any							       =   tokenizer.bos_token_id
		lowercase_ : str							       =   tokenizer.eos_token_id
		lowercase_ : Dict							       =   '''mbart50'''
		lowercase_ : Tuple							       =   '''wav2vec2'''

		lowercase_ : Any							       =   tokenizer.eos_token_id
		lowercase_ : int							       =   2_5_0_0_0_4
		lowercase_ : Any							       =   tokenizer.eos_token_id

		lowercase_ : Any							       =   SpeechEncoderDecoderConfig.from_dict(__snake_case	)

		hf_wavavec.save_pretrained(__snake_case	)
		feature_extractor.save_pretrained(__snake_case	)


if __name__ == "__main__":
						__A		:       Optional[Any]  				=		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_yaml_path''', default=None, type=str, help='''Path to yaml file of fine-tuned model''')
						parser.add_argument(
						    '''--encoder_config_path''',
						    default='''facebook/wav2vec2-xls-r-1b''',
						    type=str,
						    help='''Path to hf encoder wav2vec2 checkpoint config''',
						)
						parser.add_argument(
						    '''--decoder_config_path''',
						    default='''facebook/mbart-large-50-one-to-many-mmt''',
						    type=str,
						    help='''Path to hf decoder checkpoint config''',
						)
						parser.add_argument('''--add_adapter''', default=True, type=bool, help='''whethere to add model adapter layers''')
						parser.add_argument('''--adapter_stride''', default=2, type=int, help='''stride of adapter layers''')
						parser.add_argument('''--adapter_kernel_size''', default=3, type=int, help='''kernel size of adapter layers''')
						parser.add_argument('''--encoder_output_dim''', default=1_024, type=int, help='''encoder output dim''')
						parser.add_argument('''--start_token_id''', default=250_004, type=int, help='''`decoder_start_token_id` of model config''')

						__A		:       Union[str, Any]  				=		parser.parse_args()
						convert_wavaveca_checkpoint(
						    args.checkpoint_path,
						    args.pytorch_dump_folder_path,
						    args.dict_path,
						    args.config_yaml_path,
						    encoder_config_path=args.encoder_config_path,
						    decoder_config_path=args.decoder_config_path,
						    add_adapter=args.add_adapter,
						    adapter_kernel_size=args.adapter_kernel_size,
						    adapter_stride=args.adapter_stride,
						    decoder_start_token_id=args.start_token_id,
						    encoder_output_dim=args.encoder_output_dim,
						)











"""simple docstring"""



import argparse
import os
import re

import packaging.version


__A		:       List[str]  				=		'''examples/'''
__A		:       int  				=		{
    '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''),
    '''init''': (re.compile(R'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''),
    '''setup''': (re.compile(R'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), R'''\1version="VERSION",'''),
    '''doc''': (re.compile(R'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''),
}
__A		:       Dict  				=		{
    '''init''': '''src/transformers/__init__.py''',
    '''setup''': '''setup.py''',
}
__A		:       Optional[int]  				=		'''README.md'''



def 						lowercase    (				__snake_case				: int		,					__snake_case				: Any		,					__snake_case				: int	):
		with open(__snake_case		,					'''r'''		,					encoding='''utf-8'''		,					newline='''\n'''	) as f:
				lowercase_ : int							       =   f.read()
		lowercase_       ,					lowercase_ : List[str]							       =   REPLACE_PATTERNS[pattern]
		lowercase_ : Union[str, Any]							       =   replace.replace('''VERSION'''		,					__snake_case	)
		lowercase_ : Optional[Any]							       =   re_pattern.sub(__snake_case		,					__snake_case	)
		with open(__snake_case		,					'''w'''		,					encoding='''utf-8'''		,					newline='''\n'''	) as f:
				f.write(__snake_case	)



def 						lowercase    (				__snake_case				: int	):
		for folder, directories, fnames in os.walk(__snake_case	):
				# Removing some of the folders with non-actively maintained examples from the walk
				if "research_projects" in directories:
						directories.remove('''research_projects'''	)
				if "legacy" in directories:
						directories.remove('''legacy'''	)
				for fname in fnames:
						if fname.endswith('''.py'''	):
								update_version_in_file(os.path.join(__snake_case		,					__snake_case	)		,					__snake_case		,					pattern='''examples'''	)



def 						lowercase    (				__snake_case				: Optional[Any]		,					__snake_case				: Optional[Any]=False	):
		for pattern, fname in REPLACE_FILES.items():
				update_version_in_file(__snake_case		,					__snake_case		,					__snake_case	)
		if not patch:
				update_version_in_examples(__snake_case	)



def 						lowercase    (				):
		lowercase_ : Union[str, Any]							       =   '''🤗 Transformers currently provides the following architectures'''
		lowercase_ : Union[str, Any]							       =   '''1. Want to contribute a new model?'''
		with open(__snake_case		,					'''r'''		,					encoding='''utf-8'''		,					newline='''\n'''	) as f:
				lowercase_ : List[str]							       =   f.readlines()

		# Find the start of the list.
		lowercase_ : Optional[Any]							       =   0
		while not lines[start_index].startswith(_start_prompt	):
				start_index += 1
		start_index += 1

		lowercase_ : str							       =   start_index
		# Update the lines in the model list.
		while not lines[index].startswith(_end_prompt	):
				if lines[index].startswith('''1.'''	):
						lowercase_ : str							       =   lines[index].replace(
						    '''https://huggingface.co/docs/transformers/main/model_doc'''		,					'''https://huggingface.co/docs/transformers/model_doc'''		,					)
				index += 1

		with open(__snake_case		,					'''w'''		,					encoding='''utf-8'''		,					newline='''\n'''	) as f:
				f.writelines(__snake_case	)



def 						lowercase    (				):
		with open(REPLACE_FILES['''init''']		,					'''r'''	) as f:
				lowercase_ : List[Any]							       =   f.read()
		lowercase_ : List[str]							       =   REPLACE_PATTERNS['''init'''][0].search(__snake_case	).groups()[0]
		return packaging.version.parse(__snake_case	)



def 						lowercase    (				__snake_case				: Optional[Any]=False	):
		lowercase_ : str							       =   get_version()
		if patch and default_version.is_devrelease:
				raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!'''	)
		if default_version.is_devrelease:
				lowercase_ : Optional[Any]							       =   default_version.base_version
		elif patch:
				lowercase_ : Optional[int]							       =   F'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}'''
		else:
				lowercase_ : Optional[int]							       =   F'''{default_version.major}.{default_version.minor + 1}.0'''

		# Now let's ask nicely if that's the right one.
		lowercase_ : int							       =   input(F'''Which version are you releasing? [{default_version}]'''	)
		if len(__snake_case	) == 0:
				lowercase_ : Dict							       =   default_version

		print(F'''Updating version to {version}.'''	)
		global_version_update(__snake_case		,					patch=__snake_case	)
		if not patch:
				print('''Cleaning main README, don\'t forget to run `make fix-copies`.'''	)
				clean_main_ref_in_model_list()



def 						lowercase    (				):
		lowercase_ : List[Any]							       =   get_version()
		lowercase_ : List[str]							       =   F'''{current_version.major}.{current_version.minor + 1}.0.dev0'''
		lowercase_ : Any							       =   current_version.base_version

		# Check with the user we got that right.
		lowercase_ : Tuple							       =   input(F'''Which version are we developing now? [{dev_version}]'''	)
		if len(__snake_case	) == 0:
				lowercase_ : str							       =   dev_version

		print(F'''Updating version to {version}.'''	)
		global_version_update(__snake_case	)
		print('''Cleaning main README, don\'t forget to run `make fix-copies`.'''	)
		clean_main_ref_in_model_list()


if __name__ == "__main__":
						__A		:       int  				=		argparse.ArgumentParser()
						parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''')
						parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''')
						__A		:       Any  				=		parser.parse_args()
						if not args.post_release:
												pre_release_work(patch=args.patch)
						elif args.patch:
												print('''Nothing to do after a patch :-)''')
						else:
												post_release_work()



