






import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

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

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 torch import nn

	from transformers import (
	    MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
	    TimesformerForVideoClassification,
	    TimesformerModel,
	)
	from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from transformers import VideoMAEImageProcessor



class 							SCREAMING_SNAKE_CASE__		:





					"""simple docstring"""






					def __init__(      self  :						List[Any]							,	__A  :						Tuple							,	__A  :						Optional[int]=1_3							,	__A  :						Tuple=1_0							,	__A  :						List[Any]=3							,	__A  :						Tuple=2							,	__A  :						List[str]=2							,	__A  :						Tuple=True							,	__A  :						Optional[Any]=True							,	__A  :						Optional[Any]=3_2							,	__A  :						Optional[Any]=5							,	__A  :						Any=4							,	__A  :						Any=3_7							,	__A  :						Optional[int]="gelu"							,	__A  :						List[str]=0.1							,	__A  :						int=0.1							,	__A  :						Dict=1_0							,	__A  :						str=0.0_2							,	__A  :						str="divided_space_time"							,	__A  :						List[Any]=None							,	):
						snake_case__				:   List[str]     =						parent
						snake_case__				:   str     =						batch_size
						snake_case__				:   Optional[Any]     =						image_size
						snake_case__				:   Dict     =						num_channels
						snake_case__				:   List[str]     =						patch_size
						snake_case__				:   int     =						num_frames
						snake_case__				:   List[str]     =						is_training
						snake_case__				:   Union[str, Any]     =						use_labels
						snake_case__				:   int     =						hidden_size
						snake_case__				:   List[Any]     =						num_hidden_layers
						snake_case__				:   str     =						num_attention_heads
						snake_case__				:   int     =						intermediate_size
						snake_case__				:   Tuple     =						hidden_act
						snake_case__				:   List[str]     =						hidden_dropout_prob
						snake_case__				:   int     =						attention_probs_dropout_prob
						snake_case__				:   List[str]     =						attention_type
						snake_case__				:   int     =						initializer_range
						snake_case__				:   List[str]     =						scope
						snake_case__				:   Any     =						num_labels

						# in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
						snake_case__				:   List[Any]     =						(image_size // patch_size) ** 2
						snake_case__				:   str     =						(num_frames) * self.num_patches_per_frame + 1



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

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

						snake_case__				:   Optional[Any]     =						self.get_config()

						return config, pixel_values, labels



					def  _lowercase  (      self  :						Any ):
						snake_case__				:   Tuple     =						TimesformerConfig(
						    image_size=self.image_size							,	patch_size=self.patch_size							,	num_channels=self.num_channels							,	num_frames=self.num_frames							,	hidden_size=self.hidden_size							,	num_hidden_layers=self.num_hidden_layers							,	num_attention_heads=self.num_attention_heads							,	intermediate_size=self.intermediate_size							,	hidden_act=self.hidden_act							,	hidden_dropout_prob=self.hidden_dropout_prob							,	attention_probs_dropout_prob=self.attention_probs_dropout_prob							,	initializer_range=self.initializer_range							,	attention_type=self.attention_type							,	)
						snake_case__				:   List[Any]     =						self.num_labels
						return config



					def  _lowercase  (      self  :						Dict							,	__A  :						Tuple							,	__A  :						str							,	__A  :						Union[str, Any] ):
						snake_case__				:   Any     =						TimesformerModel(config=__A )
						model.to(__A )
						model.eval()
						snake_case__				:   int     =						model(__A )
						self.parent.assertEqual(result.last_hidden_state.shape							,	(self.batch_size, self.seq_length, self.hidden_size) )



					def  _lowercase  (      self  :						Dict							,	__A  :						List[Any]							,	__A  :						Tuple							,	__A  :						str ):
						snake_case__				:   Any     =						TimesformerForVideoClassification(__A )
						model.to(__A )
						model.eval()

						snake_case__				:   Dict     =						model(__A )

						# verify the logits shape
						snake_case__				:   Union[str, Any]     =						torch.Size((self.batch_size, self.num_labels) )
						self.parent.assertEqual(result.logits.shape							,	__A )






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



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





					"""simple docstring"""






					a_			=	(TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
					a_			=	(
					    {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification}
					    if is_torch_available()
					    else {}
					)

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



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



					def  _lowercase  (      self  :						Dict							,	__A  :						Tuple							,	__A  :						Dict							,	__A  :						Union[str, Any]=False ):
						snake_case__				:   Optional[Any]     =						copy.deepcopy(__A )

						if return_labels:
							if model_class in get_values(__A ):
								snake_case__				:   List[str]     =						torch.zeros(
								    self.model_tester.batch_size							,	dtype=torch.long							,	device=__A )

						return inputs_dict



					def  _lowercase  (      self  :						List[str] ):
						self.config_tester.run_common_tests()



					@unittest.skip(reason="TimeSformer does not use inputs_embeds" )
					def  _lowercase  (      self  :						Union[str, Any] ):
						pass



					def  _lowercase  (      self  :						Dict ):
						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     =						model_class(__A )
							self.assertIsInstance(model.get_input_embeddings()							,	(nn.Module) )
							snake_case__				:   Tuple     =						model.get_output_embeddings()
							self.assertTrue(x is None or isinstance(__A							,	nn.Linear ) )



					def  _lowercase  (      self  :						Optional[Any] ):
						snake_case__,		snake_case__				:   str     =						self.model_tester.prepare_config_and_inputs_for_common()

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

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



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



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



					@slow
					def  _lowercase  (      self  :						Union[str, Any] ):
						for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							snake_case__				:   List[str]     =						TimesformerModel.from_pretrained(__A )
							self.assertIsNotNone(__A )



					def  _lowercase  (      self  :						Tuple ):
						if not self.has_attentions:
							pass

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

							for model_class in self.all_model_classes:
								snake_case__				:   List[Any]     =						self.model_tester.seq_length
								snake_case__				:   Optional[int]     =						self.model_tester.num_frames

								snake_case__				:   int     =						True
								snake_case__				:   Optional[Any]     =						False
								snake_case__				:   Optional[int]     =						True
								snake_case__				:   Optional[int]     =						model_class(__A )
								model.to(__A )
								model.eval()
								with torch.no_grad():
									snake_case__				:   str     =						model(**self._prepare_for_class(__A							,	__A ) )
								snake_case__				:   Dict     =						outputs.attentions
								self.assertEqual(len(__A )							,	self.model_tester.num_hidden_layers )

								# check that output_attentions also work using config
								del inputs_dict["output_attentions"]
								snake_case__				:   List[Any]     =						True
								snake_case__				:   List[str]     =						model_class(__A )
								model.to(__A )
								model.eval()
								with torch.no_grad():
									snake_case__				:   int     =						model(**self._prepare_for_class(__A							,	__A ) )
								snake_case__				:   Dict     =						outputs.attentions
								self.assertEqual(len(__A )							,	self.model_tester.num_hidden_layers )

								# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
								self.assertListEqual(
								    list(attentions[0].shape[-3:] )							,	[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]							,	)
								snake_case__				:   Dict     =						len(__A )

								# Check attention is always last and order is fine
								snake_case__				:   Union[str, Any]     =						True
								snake_case__				:   List[str]     =						True
								snake_case__				:   Optional[Any]     =						model_class(__A )
								model.to(__A )
								model.eval()
								with torch.no_grad():
									snake_case__				:   str     =						model(**self._prepare_for_class(__A							,	__A ) )

								self.assertEqual(out_len + 1							,	len(__A ) )

								snake_case__				:   str     =						outputs.attentions

								self.assertEqual(len(__A )							,	self.model_tester.num_hidden_layers )

								# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
								self.assertListEqual(
								    list(self_attentions[0].shape[-3:] )							,	[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]							,	)






					def  _lowercase  (      self  :						Optional[int] ):
						def check_hidden_states_output(__A  :						str							,	__A  :						Dict							,	__A  :						Optional[Any] ):
							snake_case__				:   Optional[int]     =						model_class(__A )
							model.to(__A )
							model.eval()

							with torch.no_grad():
								snake_case__				:   str     =						model(**self._prepare_for_class(__A							,	__A ) )

							snake_case__				:   Dict     =						outputs.hidden_states
							snake_case__				:   Union[str, Any]     =						self.model_tester.num_hidden_layers + 1
							self.assertEqual(len(__A )							,	__A )

							snake_case__				:   Tuple     =						self.model_tester.seq_length

							self.assertListEqual(
							    list(hidden_states[0].shape[-2:] )							,	[seq_length, self.model_tester.hidden_size]							,	)

						snake_case__,		snake_case__				:   int     =						self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							snake_case__				:   int     =						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__				:   str     =						True

							check_hidden_states_output(__A							,	__A							,	__A )







def   SCREAMING_SNAKE_CASE       (				):
	snake_case__				:   List[Any]     =						hf_hub_download(
	    repo_id="hf-internal-testing/spaghetti-video"  ,						filename="eating_spaghetti.npy"  ,						repo_type="dataset"     )
	snake_case__				:   List[Any]     =						np.load(snake_case_     )
	return list(snake_case_     )





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





					"""simple docstring"""






					@cached_property
					def  _lowercase  (      self  :						int ):
						# logits were tested with a different mean and std, so we use the same here
						return (
						    VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]							,	image_std=[0.5, 0.5, 0.5] )
						    if is_vision_available()
						    else None
						)






					@slow
					def  _lowercase  (      self  :						Optional[int] ):
						snake_case__				:   Tuple     =						TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to(
						    __A )

						snake_case__				:   Tuple     =						self.default_image_processor
						snake_case__				:   str     =						prepare_video()
						snake_case__				:   str     =						image_processor(video[:8]							,	return_tensors="pt" ).to(__A )

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

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

						snake_case__				:   Tuple     =						torch.tensor([-0.3_0_1_6, -0.7_7_1_3, -0.4_2_0_5] ).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
	)



