






import inspect
import unittest
import warnings
from math import ceil, floor

from transformers import LevitConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch

	from transformers import (
	    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
	    MODEL_MAPPING,
	    LevitForImageClassification,
	    LevitForImageClassificationWithTeacher,
	    LevitModel,
	)
	from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import LevitImageProcessor



class 							SCREAMING_SNAKE_CASE__		(       UpperCamelCase_		):





					"""simple docstring"""






					def  _lowercase  (      self  :						Any ):
						snake_case__				:   List[Any]     =						self.config_class(**self.inputs_dict )
						self.parent.assertTrue(hasattr(__A							,	"hidden_sizes" ) )
						self.parent.assertTrue(hasattr(__A							,	"num_attention_heads" ) )



class 							SCREAMING_SNAKE_CASE__		:





					"""simple docstring"""






					def __init__(      self  :						Any							,	__A  :						Optional[int]							,	__A  :						Dict=1_3							,	__A  :						Union[str, Any]=6_4							,	__A  :						int=3							,	__A  :						List[str]=3							,	__A  :						Optional[Any]=2							,	__A  :						Dict=1							,	__A  :						Optional[int]=1_6							,	__A  :						Any=[1_2_8, 2_5_6, 3_8_4]							,	__A  :						List[str]=[4, 6, 8]							,	__A  :						Optional[Any]=[2, 3, 4]							,	__A  :						str=[1_6, 1_6, 1_6]							,	__A  :						Dict=0							,	__A  :						Dict=[2, 2, 2]							,	__A  :						Dict=[2, 2, 2]							,	__A  :						Dict=0.0_2							,	__A  :						Dict=True							,	__A  :						Dict=True							,	__A  :						str=2							,	):
						snake_case__				:   Optional[Any]     =						parent
						snake_case__				:   Union[str, Any]     =						batch_size
						snake_case__				:   List[Any]     =						image_size
						snake_case__				:   Tuple     =						num_channels
						snake_case__				:   int     =						kernel_size
						snake_case__				:   Dict     =						stride
						snake_case__				:   Union[str, Any]     =						padding
						snake_case__				:   int     =						hidden_sizes
						snake_case__				:   List[str]     =						num_attention_heads
						snake_case__				:   int     =						depths
						snake_case__				:   Optional[Any]     =						key_dim
						snake_case__				:   Dict     =						drop_path_rate
						snake_case__				:   Union[str, Any]     =						patch_size
						snake_case__				:   str     =						attention_ratio
						snake_case__				:   Union[str, Any]     =						mlp_ratio
						snake_case__				:   Optional[Any]     =						initializer_range
						snake_case__				:   Optional[Any]     =						[
						    ["Subsample", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
						    ["Subsample", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
						]
						snake_case__				:   Union[str, Any]     =						is_training
						snake_case__				:   Dict     =						use_labels
						snake_case__				:   List[Any]     =						num_labels
						snake_case__				:   Dict     =						initializer_range



					def  _lowercase  (      self  :						Tuple ):
						snake_case__				:   int     =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

						snake_case__				:   Tuple     =						None
						if self.use_labels:
							snake_case__				:   int     =						ids_tensor([self.batch_size]							,	self.num_labels )

						snake_case__				:   Dict     =						self.get_config()
						return config, pixel_values, labels



					def  _lowercase  (      self  :						Dict ):
						return LevitConfig(
						    image_size=self.image_size							,	num_channels=self.num_channels							,	kernel_size=self.kernel_size							,	stride=self.stride							,	padding=self.padding							,	patch_size=self.patch_size							,	hidden_sizes=self.hidden_sizes							,	num_attention_heads=self.num_attention_heads							,	depths=self.depths							,	key_dim=self.key_dim							,	drop_path_rate=self.drop_path_rate							,	mlp_ratio=self.mlp_ratio							,	attention_ratio=self.attention_ratio							,	initializer_range=self.initializer_range							,	down_ops=self.down_ops							,	)



					def  _lowercase  (      self  :						Dict							,	__A  :						int							,	__A  :						List[str]							,	__A  :						List[str] ):
						snake_case__				:   Any     =						LevitModel(config=__A )
						model.to(__A )
						model.eval()
						snake_case__				:   Optional[int]     =						model(__A )
						snake_case__				:   Optional[int]     =						(self.image_size, self.image_size)
						snake_case__,		snake_case__				:   Any     =						image_size[0], image_size[1]
						for _ in range(4 ):
							snake_case__				:   List[str]     =						floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1 )
							snake_case__				:   str     =						floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1 )
						self.parent.assertEqual(
						    result.last_hidden_state.shape							,	(self.batch_size, ceil(height / 4 ) * ceil(width / 4 ), self.hidden_sizes[-1])							,	)



					def  _lowercase  (      self  :						Dict							,	__A  :						Tuple							,	__A  :						Optional[int]							,	__A  :						Optional[Any] ):
						snake_case__				:   Tuple     =						self.num_labels
						snake_case__				:   Optional[Any]     =						LevitForImageClassification(__A )
						model.to(__A )
						model.eval()
						snake_case__				:   Dict     =						model(__A							,	labels=__A )
						self.parent.assertEqual(result.logits.shape							,	(self.batch_size, self.num_labels) )






					def  _lowercase  (      self  :						Optional[Any] ):
						snake_case__				:   Any     =						self.prepare_config_and_inputs()
						snake_case__,		snake_case__,		snake_case__				:   Dict     =						config_and_inputs
						snake_case__				:   Any     =						{"pixel_values": pixel_values}
						return config, inputs_dict



@require_torch
class 							SCREAMING_SNAKE_CASE__		(       UpperCamelCase_				,     UpperCamelCase_				,     unittest.TestCase		):





					"""simple docstring"""






					a_			=	(
					    (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher)
					    if is_torch_available()
					    else ()
					)
					a_			=	(
					    {
					        "feature-extraction": LevitModel,
					        "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher),
					    }
					    if is_torch_available()
					    else {}
					)

					a_			=	False
					a_			=	False
					a_			=	False
					a_			=	False
					a_			=	False



					def  _lowercase  (      self  :						Any ):
						snake_case__				:   str     =						LevitModelTester(self )
						snake_case__				:   Optional[Any]     =						ConfigTester(self							,	config_class=__A							,	has_text_modality=__A							,	hidden_size=3_7 )



					def  _lowercase  (      self  :						List[str] ):
						self.create_and_test_config_common_properties()
						self.config_tester.create_and_test_config_to_json_string()
						self.config_tester.create_and_test_config_to_json_file()
						self.config_tester.create_and_test_config_from_and_save_pretrained()
						self.config_tester.create_and_test_config_with_num_labels()
						self.config_tester.check_config_can_be_init_without_params()
						self.config_tester.check_config_arguments_init()



					def  _lowercase  (      self  :						Optional[int] ):
						return



					@unittest.skip(reason="Levit does not use inputs_embeds" )
					def  _lowercase  (      self  :						Dict ):
						pass



					@unittest.skip(reason="Levit does not support input and output embeddings" )
					def  _lowercase  (      self  :						str ):
						pass



					@unittest.skip(reason="Levit does not output attentions" )
					def  _lowercase  (      self  :						Optional[int] ):
						pass



					def  _lowercase  (      self  :						int ):
						snake_case__,		snake_case__				:   str     =						self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							snake_case__				:   Optional[int]     =						model_class(__A )
							snake_case__				:   str     =						inspect.signature(model.forward )
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							snake_case__				:   Optional[int]     =						[*signature.parameters.keys()]

							snake_case__				:   Tuple     =						["pixel_values"]
							self.assertListEqual(arg_names[:1]							,	__A )



					def  _lowercase  (      self  :						Tuple ):
						def check_hidden_states_output(__A  :						Any							,	__A  :						Dict							,	__A  :						Any ):
							snake_case__				:   int     =						model_class(__A )
							model.to(__A )
							model.eval()

							with torch.no_grad():
								snake_case__				:   List[Any]     =						model(**self._prepare_for_class(__A							,	__A ) )

							snake_case__				:   Optional[Any]     =						outputs.hidden_states

							snake_case__				:   int     =						len(self.model_tester.depths ) + 1
							self.assertEqual(len(__A )							,	__A )

							snake_case__				:   Dict     =						(self.model_tester.image_size, self.model_tester.image_size)
							snake_case__,		snake_case__				:   str     =						image_size[0], image_size[1]
							for _ in range(4 ):
								snake_case__				:   Dict     =						floor(
								    (
								        (height + 2 * self.model_tester.padding - self.model_tester.kernel_size)
								        / self.model_tester.stride
								    )
								    + 1 )
								snake_case__				:   Union[str, Any]     =						floor(
								    (
								        (width + 2 * self.model_tester.padding - self.model_tester.kernel_size)
								        / self.model_tester.stride
								    )
								    + 1 )
							# verify the first hidden states (first block)
							self.assertListEqual(
							    list(hidden_states[0].shape[-2:] )							,	[
							        height * width,
							        self.model_tester.hidden_sizes[0],
							    ]							,	)

						snake_case__,		snake_case__				:   Union[str, Any]     =						self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							snake_case__				:   Any     =						True
							check_hidden_states_output(__A							,	__A							,	__A )

							# check that output_hidden_states also work using config
							del inputs_dict["output_hidden_states"]
							snake_case__				:   List[Any]     =						True

							check_hidden_states_output(__A							,	__A							,	__A )



					@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." )
					def  _lowercase  (      self  :						Tuple ):
						pass



					def  _lowercase  (      self  :						List[str]							,	__A  :						str							,	__A  :						Optional[int]							,	__A  :						Optional[int]=False ):
						snake_case__				:   Optional[Any]     =						super()._prepare_for_class(__A							,	__A							,	return_labels=__A )

						if return_labels:
							if model_class.__name__ == "LevitForImageClassificationWithTeacher":
								del inputs_dict["labels"]

						return inputs_dict



					def  _lowercase  (      self  :						List[str] ):
						snake_case__				:   List[Any]     =						self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__A )



					def  _lowercase  (      self  :						Tuple ):
						snake_case__				:   Dict     =						self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*__A )



					def  _lowercase  (      self  :						List[Any] ):
						if not self.model_tester.is_training:
							return

						snake_case__,		snake_case__				:   List[Any]     =						self.model_tester.prepare_config_and_inputs_for_common()
						snake_case__				:   Union[str, Any]     =						True

						for model_class in self.all_model_classes:
							# LevitForImageClassificationWithTeacher supports inference-only
							if (
							    model_class in get_values(__A )
							    or model_class.__name__ == "LevitForImageClassificationWithTeacher"
							):
								continue
							snake_case__				:   List[str]     =						model_class(__A )
							model.to(__A )
							model.train()
							snake_case__				:   Dict     =						self._prepare_for_class(__A							,	__A							,	return_labels=__A )
							snake_case__				:   Tuple     =						model(**__A ).loss
							loss.backward()



					def  _lowercase  (      self  :						Tuple ):
						snake_case__,		snake_case__				:   List[str]     =						self.model_tester.prepare_config_and_inputs_for_common()
						if not self.model_tester.is_training:
							return

						snake_case__				:   str     =						False
						snake_case__				:   List[str]     =						True

						for model_class in self.all_model_classes:
							if model_class in get_values(__A ) or not model_class.supports_gradient_checkpointing:
								continue
							# LevitForImageClassificationWithTeacher supports inference-only
							if model_class.__name__ == "LevitForImageClassificationWithTeacher":
								continue
							snake_case__				:   Union[str, Any]     =						model_class(__A )
							model.gradient_checkpointing_enable()
							model.to(__A )
							model.train()
							snake_case__				:   int     =						self._prepare_for_class(__A							,	__A							,	return_labels=__A )
							snake_case__				:   Tuple     =						model(**__A ).loss
							loss.backward()



					def  _lowercase  (      self  :						Dict ):
						snake_case__,		snake_case__				:   List[str]     =						self.model_tester.prepare_config_and_inputs_for_common()

						snake_case__				:   Tuple     =						[
						    {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float},
						    {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long},
						    {"title": "regression", "num_labels": 1, "dtype": torch.float},
						]

						for model_class in self.all_model_classes:
							if (
							    model_class
							    not in [
							        *get_values(__A ),
							    ]
							    or model_class.__name__ == "LevitForImageClassificationWithTeacher"
							):
								continue

							for problem_type in problem_types:
								with self.subTest(msg=f'''Testing {model_class} with {problem_type['title']}''' ):
									snake_case__				:   Optional[Any]     =						problem_type["title"]
									snake_case__				:   str     =						problem_type["num_labels"]

									snake_case__				:   int     =						model_class(__A )
									model.to(__A )
									model.train()

									snake_case__				:   Optional[int]     =						self._prepare_for_class(__A							,	__A							,	return_labels=__A )

									if problem_type["num_labels"] > 1:
										snake_case__				:   Optional[int]     =						inputs["labels"].unsqueeze(1 ).repeat(1							,	problem_type["num_labels"] )

									snake_case__				:   List[Any]     =						inputs["labels"].to(problem_type["dtype"] )

									# This tests that we do not trigger the warning form PyTorch "Using a target size that is different
									# to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
									# they have the same size." which is a symptom something in wrong for the regression problem.
									# See https://github.com/huggingface/transformers/issues/11780
									with warnings.catch_warnings(record=__A ) as warning_list:
										snake_case__				:   List[str]     =						model(**__A ).loss
									for w in warning_list:
										if "Using a target size that is different to the input size" in str(w.message ):
											raise ValueError(
											    f'''Something is going wrong in the regression problem: intercepted {w.message}''' )

									loss.backward()






					@slow
					def  _lowercase  (      self  :						List[str] ):
						for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							snake_case__				:   int     =						LevitModel.from_pretrained(__A )
							self.assertIsNotNone(__A )







def   SCREAMING_SNAKE_CASE       (				):
	snake_case__				:   Any     =						Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"     )
	return image





@require_torch
@require_vision
class 							SCREAMING_SNAKE_CASE__		(       unittest.TestCase		):





					"""simple docstring"""






					@cached_property
					def  _lowercase  (      self  :						Dict ):
						return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] )






					@slow
					def  _lowercase  (      self  :						Optional[Any] ):
						snake_case__				:   Dict     =						LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(
						    __A )

						snake_case__				:   Any     =						self.default_image_processor
						snake_case__				:   List[Any]     =						prepare_img()
						snake_case__				:   Optional[int]     =						image_processor(images=__A							,	return_tensors="pt" ).to(__A )

						# forward pass
						with torch.no_grad():
							snake_case__				:   Optional[int]     =						model(**__A )

						# verify the logits
						snake_case__				:   Optional[int]     =						torch.Size((1, 1_0_0_0) )
						self.assertEqual(outputs.logits.shape							,	__A )

						snake_case__				:   Union[str, Any]     =						torch.tensor([1.0_4_4_8, -0.3_7_4_5, -1.8_3_1_7] ).to(__A )

						self.assertTrue(torch.allclose(outputs.logits[0, :3]							,	__A							,	atol=1e-4 ) )











import argparse

import fairseq
import torch

from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging


logging.set_verbosity_info()
__lowerCamelCase      :    int   		=   logging.get_logger(__name__)

__lowerCamelCase      :    int   		=   {
    """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""",
}
__lowerCamelCase      :    Tuple   		=   [
    """lm_head""",
    """quantizer.weight_proj""",
    """quantizer.codevectors""",
    """project_q""",
    """project_hid""",
    """label_embeddings_concat""",
    """speaker_proj""",
    """layer_norm_for_extract""",
]







def   SCREAMING_SNAKE_CASE       (				snake_case_      :							Tuple  ,						snake_case_      :							Union[str, Any]  ,						snake_case_      :							Union[str, Any]  ,						snake_case_      :							Any  ,						snake_case_      :							Union[str, Any]     ):
	for attribute in key.split("."     ):
		snake_case__				:   int     =						getattr(snake_case_  ,						snake_case_     )

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

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







def   SCREAMING_SNAKE_CASE       (				snake_case_      :							Any  ,						snake_case_      :							Union[str, Any]     ):
	snake_case__				:   str     =						[]
	snake_case__				:   Optional[int]     =						fairseq_model.state_dict()

	snake_case__				:   int     =						hf_model.unispeech_sat.feature_extractor

	for name, value in fairseq_dict.items():
		snake_case__				:   Dict     =						False
		if "conv_layers" in name:
			load_conv_layer(
			    snake_case_  ,						snake_case_  ,						snake_case_  ,						snake_case_  ,						hf_model.config.feat_extract_norm == "group"  ,						)
			snake_case__				:   str     =						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__				:   int     =						True
					if "*" in mapped_key:
						snake_case__				:   Any     =						name.split(snake_case_     )[0].split("."     )[-2]
						snake_case__				:   Any     =						mapped_key.replace("*"  ,						snake_case_     )
					if "weight_g" in name:
						snake_case__				:   List[Any]     =						"weight_g"
					elif "weight_v" in name:
						snake_case__				:   Optional[Any]     =						"weight_v"
					elif "bias" in name:
						snake_case__				:   Optional[Any]     =						"bias"
					elif "weight" in name:
						# TODO: don't match quantizer.weight_proj
						snake_case__				:   Optional[Any]     =						"weight"
					else:
						snake_case__				:   Optional[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   SCREAMING_SNAKE_CASE       (				snake_case_      :							Any  ,						snake_case_      :							List[str]  ,						snake_case_      :							List[Any]  ,						snake_case_      :							Optional[Any]  ,						snake_case_      :							str     ):
	snake_case__				:   Tuple     =						full_name.split("conv_layers."     )[-1]
	snake_case__				:   Union[str, Any]     =						name.split("."     )
	snake_case__				:   str     =						int(items[0]     )
	snake_case__				:   str     =						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__				:   Optional[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__				:   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_     )







@torch.no_grad()
def   SCREAMING_SNAKE_CASE       (				snake_case_      :							int  ,						snake_case_      :							Any  ,						snake_case_      :							Optional[int]=None  ,						snake_case_      :							Optional[int]=None  ,						snake_case_      :							Any=True     ):
	if config_path is not None:
		snake_case__				:   Tuple     =						UniSpeechSatConfig.from_pretrained(snake_case_     )
	else:
		snake_case__				:   Tuple     =						UniSpeechSatConfig()

	snake_case__				:   str     =						""

	if is_finetuned:
		snake_case__				:   Tuple     =						UniSpeechSatForCTC(snake_case_     )
	else:
		snake_case__				:   Any     =						UniSpeechSatForPreTraining(snake_case_     )

	snake_case__,		snake_case__,		snake_case__				:   Any     =						fairseq.checkpoint_utils.load_model_ensemble_and_task(
	    [checkpoint_path]  ,						arg_overrides={"data": "/".join(dict_path.split("/"     )[:-1]     )}     )
	snake_case__				:   Tuple     =						model[0].eval()

	recursively_load_weights(snake_case_  ,						snake_case_     )

	hf_wavavec.save_pretrained(snake_case_     )


if __name__ == "__main__":
	__lowerCamelCase      :    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"""
	)
	__lowerCamelCase      :    List[Any]   		=   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
	)



