"""simple docstring"""







import argparse

import fairseq
import torch

from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging


logging.set_verbosity_info()
_a					:					str=			logging.get_logger(__name__)

_a					:					str=			{
    "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",
    "encoder.layer_norm_for_extract": "layer_norm_for_extract",
    "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",
    "label_embs_concat": "label_embeddings_concat",
    "mask_emb": "masked_spec_embed",
    "spk_proj": "speaker_proj",
}
_a					:					List[str]=			[
    "lm_head",
    "quantizer.weight_proj",
    "quantizer.codevectors",
    "project_q",
    "project_hid",
    "label_embeddings_concat",
    "speaker_proj",
    "layer_norm_for_extract",
]
def   __UpperCAmelCase    (   UpperCAmelCase_   :    Union[str, Any]      ,							UpperCAmelCase_   :    Optional[Any]      ,							UpperCAmelCase_   :    List[Any]      ,							UpperCAmelCase_   :    Optional[int]      ,							UpperCAmelCase_   :    List[str]  )							->      Optional[int]:

	'''simple docstring'''





	for attribute in key.split('.'  ):
		__snake_case      :							Any						=			getattr(UpperCAmelCase_      ,							UpperCAmelCase_  )

	if weight_type is not None:
		__snake_case      :							Dict						=			getattr(UpperCAmelCase_      ,							UpperCAmelCase_  ).shape
	else:
		__snake_case      :							List[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":
		__snake_case      :							Any						=			value
	elif weight_type == "weight_g":
		__snake_case      :							Any						=			value
	elif weight_type == "weight_v":
		__snake_case      :							Union[str, Any]						=			value
	elif weight_type == "bias":
		__snake_case      :							List[str]						=			value
	else:
		__snake_case      :							List[Any]						=			value

	logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}."  )
def   __UpperCAmelCase    (   UpperCAmelCase_   :    Optional[Any]      ,							UpperCAmelCase_   :    Tuple  )							->      Tuple:

	'''simple docstring'''





	__snake_case      :							Dict						=			[]
	__snake_case      :							Any						=			fairseq_model.state_dict()

	__snake_case      :							Union[str, Any]						=			hf_model.unispeech_sat.feature_extractor

	for name, value in fairseq_dict.items():
		__snake_case      :							Tuple						=			False
		if "conv_layers" in name:
			load_conv_layer(
			    UpperCAmelCase_      ,							UpperCAmelCase_      ,							UpperCAmelCase_      ,							UpperCAmelCase_      ,							hf_model.config.feat_extract_norm == 'group'      ,							)
			__snake_case      :							Optional[Any]						=			True
		else:
			for key, mapped_key in MAPPING.items():
				__snake_case      :							Optional[int]						=			'unispeech_sat.' + 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]:
					if "layer_norm_for_extract" in name and (".".join(name.split('.'  )[:-1]  ) != key):
						# special case since naming is very similar
						continue
					__snake_case      :							Union[str, Any]						=			True
					if "*" in mapped_key:
						__snake_case      :							Dict						=			name.split(UpperCAmelCase_  )[0].split('.'  )[-2]
						__snake_case      :							Tuple						=			mapped_key.replace('*'      ,							UpperCAmelCase_  )
					if "weight_g" in name:
						__snake_case      :							Union[str, Any]						=			'weight_g'
					elif "weight_v" in name:
						__snake_case      :							str						=			'weight_v'
					elif "bias" in name:
						__snake_case      :							List[Any]						=			'bias'
					elif "weight" in name:
						# TODO: don't match quantizer.weight_proj
						__snake_case      :							Optional[Any]						=			'weight'
					else:
						__snake_case      :							int						=			None
					set_recursively(UpperCAmelCase_      ,							UpperCAmelCase_      ,							UpperCAmelCase_      ,							UpperCAmelCase_      ,							UpperCAmelCase_  )
				continue
		if not is_used:
			unused_weights.append(UpperCAmelCase_  )

	logger.warning(F"Unused weights: {unused_weights}"  )
def   __UpperCAmelCase    (   UpperCAmelCase_   :    Tuple      ,							UpperCAmelCase_   :    Tuple      ,							UpperCAmelCase_   :    Dict      ,							UpperCAmelCase_   :    Union[str, Any]      ,							UpperCAmelCase_   :    Union[str, Any]  )							->      Tuple:

	'''simple docstring'''





	__snake_case      :							Dict						=			full_name.split('conv_layers.'  )[-1]
	__snake_case      :							Optional[int]						=			name.split('.'  )
	__snake_case      :							int						=			int(items[0]  )
	__snake_case      :							int						=			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."  )
			__snake_case      :							Any						=			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."  )
			__snake_case      :							Any						=			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[layer_id].layer_norm.bias.data.shape} was found."  )
			__snake_case      :							List[Any]						=			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[layer_id].layer_norm.weight.data.shape} was found."  )
			__snake_case      :							Any						=			value
			logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."  )
	else:
		unused_weights.append(UpperCAmelCase_  )
@torch.no_grad()
def   __UpperCAmelCase    (   UpperCAmelCase_   :    int      ,							UpperCAmelCase_   :    List[Any]      ,							UpperCAmelCase_   :    Union[str, Any]=None      ,							UpperCAmelCase_   :    Optional[int]=None      ,							UpperCAmelCase_   :    Dict=True  )							->      str:

	'''simple docstring'''





	if config_path is not None:
		__snake_case      :							Optional[Any]						=			UniSpeechSatConfig.from_pretrained(UpperCAmelCase_  )
	else:
		__snake_case      :							Any						=			UniSpeechSatConfig()

	__snake_case      :							Optional[Any]						=			''

	if is_finetuned:
		__snake_case      :							Union[str, Any]						=			UniSpeechSatForCTC(UpperCAmelCase_  )
	else:
		__snake_case      :							Optional[Any]						=			UniSpeechSatForPreTraining(UpperCAmelCase_  )

	__snake_case		,    __snake_case		,    __snake_case      :							List[Any]						=			fairseq.checkpoint_utils.load_model_ensemble_and_task(
	    [checkpoint_path]      ,							arg_overrides={'data': '/'.join(dict_path.split('/'  )[:-1]  )}  )
	__snake_case      :							Optional[int]						=			model[0].eval()

	recursively_load_weights(UpperCAmelCase_      ,							UpperCAmelCase_  )

	hf_wavavec.save_pretrained(UpperCAmelCase_  )


if __name__ == "__main__":
	_a					:					int=			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"
	)
	_a					:					Optional[int]=			parser.parse_args()
	convert_unispeech_sat_checkpoint(
	    args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
	)






"""simple docstring"""







import subprocess
import sys

from transformers import BertConfig, BertModel, BertTokenizer, pipeline
from transformers.testing_utils import TestCasePlus, require_torch

class 		UpperCamelCase      (   lowercase						):



				@require_torch
				def  _lowercase					(self    :				Union[str, Any])   ->     Optional[Any]:
					# this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before
					# `transformers` is loaded, and it's too late for inside pytest - so we are changing it
					# while running an external program

					# python one-liner segments

					# this must be loaded before socket.socket is monkey-patched
					__snake_case      :							Any						=			'\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        '

					__snake_case      :							Tuple						=			'\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n        '

					__snake_case      :							int						=			'\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")\nsocket.socket = offline_socket\n        '

					# Force fetching the files so that we can use the cache
					__snake_case      :							int						=			'hf-internal-testing/tiny-random-bert'
					BertConfig.from_pretrained(_A)
					BertModel.from_pretrained(_A)
					BertTokenizer.from_pretrained(_A)
					pipeline(task='fill-mask'     ,  model=_A)

					# baseline - just load from_pretrained with normal network
					__snake_case      :							Union[str, Any]						=			[sys.executable, '-c', '\n'.join([load, run, mock])]

					# should succeed
					__snake_case      :							Union[str, Any]						=			self.get_env()
					# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
					__snake_case      :							str						=			'1'
					__snake_case      :							Union[str, Any]						=			subprocess.run(_A     ,  env=_A     ,  check=_A     ,  capture_output=_A)
					self.assertEqual(result.returncode     ,  0     ,  result.stderr)
					self.assertIn('success'     ,  result.stdout.decode())



				@require_torch
				def  _lowercase					(self    :				Union[str, Any])   ->     Union[str, Any]:
					# python one-liner segments
					# this must be loaded before socket.socket is monkey-patched
					__snake_case      :							Optional[Any]						=			'\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        '

					__snake_case      :							Optional[Any]						=			'\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n        '

					__snake_case      :							Union[str, Any]						=			'\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")\nsocket.socket = offline_socket\n        '

					# Force fetching the files so that we can use the cache
					__snake_case      :							str						=			'hf-internal-testing/tiny-random-bert'
					BertConfig.from_pretrained(_A)
					BertModel.from_pretrained(_A)
					BertTokenizer.from_pretrained(_A)
					pipeline(task='fill-mask'     ,  model=_A)

					# baseline - just load from_pretrained with normal network
					__snake_case      :							Any						=			[sys.executable, '-c', '\n'.join([load, run, mock])]

					# should succeed
					__snake_case      :							int						=			self.get_env()
					__snake_case      :							Tuple						=			subprocess.run(_A     ,  env=_A     ,  check=_A     ,  capture_output=_A)
					self.assertEqual(result.returncode     ,  0     ,  result.stderr)
					self.assertIn('success'     ,  result.stdout.decode())



				@require_torch
				def  _lowercase					(self    :				int)   ->     Any:
					# this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before
					# `transformers` is loaded, and it's too late for inside pytest - so we are changing it
					# while running an external program

					# python one-liner segments

					# this must be loaded before socket.socket is monkey-patched
					__snake_case      :							int						=			'\nfrom transformers import BertConfig, BertModel, BertTokenizer\n        '

					__snake_case      :							int						=			'\nmname = "hf-internal-testing/tiny-random-bert-sharded"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint("success")\n        '

					__snake_case      :							Optional[int]						=			'\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")\nsocket.socket = offline_socket\n        '

					# baseline - just load from_pretrained with normal network
					__snake_case      :							Optional[Any]						=			[sys.executable, '-c', '\n'.join([load, run])]

					# should succeed
					__snake_case      :							Optional[int]						=			self.get_env()
					__snake_case      :							Dict						=			subprocess.run(_A     ,  env=_A     ,  check=_A     ,  capture_output=_A)
					self.assertEqual(result.returncode     ,  0     ,  result.stderr)
					self.assertIn('success'     ,  result.stdout.decode())

					# next emulate no network
					__snake_case      :							Optional[Any]						=			[sys.executable, '-c', '\n'.join([load, mock, run])]

					# Doesn't fail anymore since the model is in the cache due to other tests, so commenting this.
					# env["TRANSFORMERS_OFFLINE"] = "0"
					# result = subprocess.run(cmd, env=env, check=False, capture_output=True)
					# self.assertEqual(result.returncode, 1, result.stderr)

					# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
					__snake_case      :							Union[str, Any]						=			'1'
					__snake_case      :							str						=			subprocess.run(_A     ,  env=_A     ,  check=_A     ,  capture_output=_A)
					self.assertEqual(result.returncode     ,  0     ,  result.stderr)
					self.assertIn('success'     ,  result.stdout.decode())



				@require_torch
				def  _lowercase					(self    :				str)   ->     Dict:
					__snake_case      :							Dict						=			'\nfrom transformers import pipeline\n        '
					__snake_case      :							List[Any]						=			'\nmname = "hf-internal-testing/tiny-random-bert"\npipe = pipeline(model=mname)\n        '

					__snake_case      :							List[str]						=			'\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")\nsocket.socket = offline_socket\n        '
					__snake_case      :							str						=			self.get_env()
					__snake_case      :							Tuple						=			'1'
					__snake_case      :							Tuple						=			[sys.executable, '-c', '\n'.join([load, mock, run])]
					__snake_case      :							Optional[Any]						=			subprocess.run(_A     ,  env=_A     ,  check=_A     ,  capture_output=_A)
					self.assertEqual(result.returncode     ,  1     ,  result.stderr)
					self.assertIn(
					    'You cannot infer task automatically within `pipeline` when using offline mode'     ,  result.stderr.decode().replace('\n'     ,  '')     ,  )






				@require_torch
				def  _lowercase					(self    :				int)   ->     Optional[Any]:
					__snake_case      :							int						=			'\nfrom transformers import AutoModel\n        '
					__snake_case      :							str						=			'\nmname = "hf-internal-testing/test_dynamic_model"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint("success")\n        '

					# baseline - just load from_pretrained with normal network
					__snake_case      :							str						=			[sys.executable, '-c', '\n'.join([load, run])]

					# should succeed
					__snake_case      :							str						=			self.get_env()
					__snake_case      :							Dict						=			subprocess.run(_A     ,  env=_A     ,  check=_A     ,  capture_output=_A)
					self.assertEqual(result.returncode     ,  0     ,  result.stderr)
					self.assertIn('success'     ,  result.stdout.decode())

					# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
					__snake_case      :							List[str]						=			'1'
					__snake_case      :							Optional[int]						=			subprocess.run(_A     ,  env=_A     ,  check=_A     ,  capture_output=_A)
					self.assertEqual(result.returncode     ,  0     ,  result.stderr)
					self.assertIn('success'     ,  result.stdout.decode())





