





"""simple docstring"""





from __future__ import annotations

import unittest

import numpy as np

from transformers import OPTConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
						import tensorflow as tf

						from transformers import GPTaTokenizer, TFOPTForCausalLM, TFOPTModel


def       a__					(					_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE=None  ,	_SCREAMING_SNAKE_CASE=None    ):




		"""simple docstring"""


		if attention_mask is None:
				UpperCamelCase   =	tf.cast(tf.math.not_equal(_SCREAMING_SNAKE_CASE  ,	config.pad_token_id    )  ,	tf.inta    )
		return {"input_ids": input_ids, "attention_mask": attention_mask}





@require_tf
class        _lowerCamelCase      :
						UpperCAmelCase_ =			OPTConfig
						UpperCAmelCase_ =			{}
						UpperCAmelCase_ =			"gelu"


						def __init__(self   ,							__a   ,							__a=13   ,							__a=7   ,							__a=True   ,							__a=False   ,							__a=99   ,							__a=16   ,							__a=2   ,							__a=4   ,							__a=4   ,							__a="gelu"   ,							__a=0.1   ,							__a=0.1   ,							__a=20   ,							__a=2   ,							__a=1   ,							__a=0   ,							__a=16   ,							__a=16   ,							) ->   Any:
								UpperCamelCase   =	parent
								UpperCamelCase   =	batch_size
								UpperCamelCase   =	seq_length
								UpperCamelCase   =	is_training
								UpperCamelCase   =	use_labels
								UpperCamelCase   =	vocab_size
								UpperCamelCase   =	hidden_size
								UpperCamelCase   =	num_hidden_layers
								UpperCamelCase   =	num_attention_heads
								UpperCamelCase   =	intermediate_size
								UpperCamelCase   =	hidden_act
								UpperCamelCase   =	hidden_dropout_prob
								UpperCamelCase   =	attention_probs_dropout_prob
								UpperCamelCase   =	max_position_embeddings
								UpperCamelCase   =	eos_token_id
								UpperCamelCase   =	pad_token_id
								UpperCamelCase   =	bos_token_id
								UpperCamelCase   =	embed_dim
								UpperCamelCase   =	word_embed_proj_dim
								UpperCamelCase   =	False


						def     snake_case_   (self		) ->   str:
								UpperCamelCase   =	ids_tensor([self.batch_size, self.seq_length - 1]   ,							self.vocab_size		)
								UpperCamelCase   =	tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size		)   ,							1		)
								UpperCamelCase   =	tf.concat([input_ids, eos_tensor]   ,							axis=1		)

								UpperCamelCase   =	self.config_cls(
								    vocab_size=self.vocab_size   ,							hidden_size=self.hidden_size   ,							num_hidden_layers=self.num_hidden_layers   ,							num_attention_heads=self.num_attention_heads   ,							ffn_dim=self.intermediate_size   ,							dropout=self.hidden_dropout_prob   ,							attention_dropout=self.attention_probs_dropout_prob   ,							max_position_embeddings=self.max_position_embeddings   ,							eos_token_id=self.eos_token_id   ,							bos_token_id=self.bos_token_id   ,							pad_token_id=self.pad_token_id   ,							embed_dim=self.embed_dim   ,							word_embed_proj_dim=self.word_embed_proj_dim   ,							is_encoder_decoder=__a   ,							**self.config_updates   ,							)
								UpperCamelCase   =	prepare_opt_inputs_dict(__a   ,							__a		)
								return config, inputs_dict




						def     snake_case_   (self   ,							__a   ,							__a		) ->   List[str]:
								UpperCamelCase   =	TFOPTModel(config=__a		)
								UpperCamelCase   =	inputs_dict["input_ids"]

								UpperCamelCase   =	input_ids[:1, :]
								UpperCamelCase   =	inputs_dict["attention_mask"][:1, :]
								UpperCamelCase   =	1

								# first forward pass
								UpperCamelCase   =	model(__a   ,							attention_mask=__a   ,							use_cache=__a		)

								UpperCamelCase   ,				UpperCamelCase   =	outputs.to_tuple()

								# create hypothetical next token and extent to next_input_ids
								UpperCamelCase   =	ids_tensor((self.batch_size, 3)   ,							config.vocab_size		)
								UpperCamelCase   =	tf.cast(ids_tensor((self.batch_size, 3)   ,							2		)   ,							tf.inta		)

								# append to next input_ids and
								UpperCamelCase   =	tf.concat([input_ids, next_tokens]   ,							axis=-1		)
								UpperCamelCase   =	tf.concat([attention_mask, next_attn_mask]   ,							axis=-1		)

								UpperCamelCase   =	model(__a   ,							attention_mask=__a		)[0]
								UpperCamelCase   =	model(__a   ,							attention_mask=__a   ,							past_key_values=__a		)[0]

								self.parent.assertEqual(next_tokens.shape[1]   ,							output_from_past.shape[1]		)

								# select random slice
								UpperCamelCase   =	int(ids_tensor((1,)   ,							output_from_past.shape[-1]		)		)
								UpperCamelCase   =	output_from_no_past[:, -3:, random_slice_idx]
								UpperCamelCase   =	output_from_past[:, :, random_slice_idx]

								# test that outputs are equal for slice
								tf.debugging.assert_near(__a   ,							__a   ,							rtol=1e-3		)





@require_tf
class        _lowerCamelCase      (       _lowercase  ,			_lowercase  ,			unittest.TestCase ):
						UpperCAmelCase_ =			(TFOPTModel, TFOPTForCausalLM) if is_tf_available() else ()
						UpperCAmelCase_ =			(TFOPTForCausalLM,) if is_tf_available() else ()
						UpperCAmelCase_ =			(
						    {"feature-extraction": TFOPTModel, "text-generation": TFOPTForCausalLM} if is_tf_available() else {}
						)
						UpperCAmelCase_ =			False
						UpperCAmelCase_ =			False
						UpperCAmelCase_ =			False
						UpperCAmelCase_ =			10


						def     snake_case_   (self		) ->   Union[str, Any]:
								UpperCamelCase   =	TFOPTModelTester(self		)
								UpperCamelCase   =	ConfigTester(self   ,							config_class=__a		)


						def     snake_case_   (self		) ->   Optional[Any]:
								self.config_tester.run_common_tests()


						def     snake_case_   (self		) ->   Tuple:
								UpperCamelCase   =	self.model_tester.prepare_config_and_inputs_for_common()
								self.model_tester.check_decoder_model_past_large_inputs(*__a		)




						def     snake_case_   (self		) ->   Union[str, Any]:
								UpperCamelCase   ,				UpperCamelCase   =	self.model_tester.prepare_config_and_inputs_for_common()

								def _get_word_embedding_weight(__a   ,							__a		):
										if hasattr(__a   ,							"weight"		):
												return embedding_layer.weight
										else:
												# Here we build the word embeddings weights if not exists.
												# And then we retry to get the attribute once built.
												model.build()
												if hasattr(__a   ,							"weight"		):
														return embedding_layer.weight
												else:
														return None

								for model_class in self.all_model_classes:
										for size in [config.vocab_size - 10, config.vocab_size + 10]:
												# build the embeddings
												UpperCamelCase   =	model_class(config=__a		)
												UpperCamelCase   =	_get_word_embedding_weight(__a   ,							model.get_input_embeddings()		)
												UpperCamelCase   =	_get_word_embedding_weight(__a   ,							model.get_output_embeddings()		)

												# reshape the embeddings
												model.resize_token_embeddings(__a		)
												UpperCamelCase   =	_get_word_embedding_weight(__a   ,							model.get_input_embeddings()		)
												UpperCamelCase   =	_get_word_embedding_weight(__a   ,							model.get_output_embeddings()		)

												# check that the resized embeddings size matches the desired size.
												UpperCamelCase   =	size if size is not None else config.vocab_size

												self.assertEqual(new_input_embeddings.shape[0]   ,							__a		)

												# check that weights remain the same after resizing
												UpperCamelCase   =	True
												for pa, pa in zip(old_input_embeddings.value()   ,							new_input_embeddings.value()		):
														if tf.math.reduce_sum(tf.math.abs(pa - pa		)		) > 0:
																UpperCamelCase   =	False
												self.assertTrue(__a		)

												if old_output_embeddings is not None and new_output_embeddings is not None:
														self.assertEqual(new_output_embeddings.shape[0]   ,							__a		)

														UpperCamelCase   =	True
														for pa, pa in zip(old_output_embeddings.value()   ,							new_output_embeddings.value()		):
																if tf.math.reduce_sum(tf.math.abs(pa - pa		)		) > 0:
																		UpperCamelCase   =	False
														self.assertTrue(__a		)



def       a__					(					_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		return tf.constant(_SCREAMING_SNAKE_CASE  ,	dtype=tf.intaa    )





@require_tf
class        _lowerCamelCase      (       unittest.TestCase ):
						UpperCAmelCase_ =			99


						def     snake_case_   (self		) ->   Optional[Any]:
								UpperCamelCase   =	tf.ones((4, 1)   ,							dtype=tf.intaa		) * 2
								UpperCamelCase   =	tf.concat([ids_tensor((4, 6)   ,							self.vocab_size - 3		) + 3, eos_column_vector]   ,							axis=1		)
								UpperCamelCase   =	input_ids.shape[0]
								UpperCamelCase   =	OPTConfig(
								    vocab_size=self.vocab_size   ,							hidden_size=24   ,							num_hidden_layers=2   ,							num_attention_heads=2   ,							ffn_dim=32   ,							max_position_embeddings=48   ,							eos_token_id=2   ,							pad_token_id=1   ,							bos_token_id=0   ,							)
								return config, input_ids, batch_size





@require_sentencepiece
@require_tf
class        _lowerCamelCase      (       unittest.TestCase ):


						@slow
						def     snake_case_   (self		) ->   Optional[int]:
								UpperCamelCase   =	TFOPTModel.from_pretrained("facebook/opt-350m"		)
								UpperCamelCase   =	_long_tensor([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]]		)
								UpperCamelCase   =	tf.not_equal(__a   ,							model.config.pad_token_id		)
								with tf.GradientTape():
										UpperCamelCase   =	model(input_ids=__a   ,							attention_mask=__a		).last_hidden_state
								UpperCamelCase   =	(1, 11, 5_12)
								self.assertEqual(output.shape   ,							__a		)
								UpperCamelCase   =	tf.constant(
								    [[-0.2873, -1.9218, -0.3033], [-1.2710, -0.1338, -0.1902], [0.4095, 0.1214, -1.3121]]		)
								self.assertTrue(np.allclose(output[:, :3, :3]   ,							__a   ,							atol=4e-3		)		)

								UpperCamelCase   =	tf.function(__a   ,							jit_compile=__a		)
								UpperCamelCase   =	xla_generate(__a   ,							__a		)[0]
								self.assertTrue(np.allclose(output[:, :3, :3]   ,							__a   ,							atol=4e-2		)		)





@require_tf
@slow
class        _lowerCamelCase      (       unittest.TestCase ):


						def     snake_case_   (self		) ->   Dict:
								super().setUp()
								UpperCamelCase   =	"facebook/opt-350m"




						def     snake_case_   (self		) ->   List[Any]:
								UpperCamelCase   =	TFOPTForCausalLM.from_pretrained(self.path_model		)
								UpperCamelCase   =	GPTaTokenizer.from_pretrained(self.path_model		)

								UpperCamelCase   =	[
								    "Today is a beautiful day and I want to",
								    "In the city of",
								    "Paris is the capital of France and",
								    "Computers and mobile phones have taken",
								]
								# verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False
								UpperCamelCase   =	tokenizer(__a   ,							return_tensors="tf"   ,							padding=__a   ,							add_special_tokens=__a		)
								UpperCamelCase   =	tf.math.reduce_mean(model(inputs.input_ids   ,							attention_mask=inputs.attention_mask		)[0]   ,							axis=-1		)
								UpperCamelCase   =	tf.constant(
								    [
								        [1.3851, -13.8923, -10.5229, -10.7533, -0.2309, -10.2384, -0.5365, -9.0947, -5.1670],
								        [-4.7073, -10.6276, -3.9415, -21.5242, -0.2822, -0.2822, -0.2822, -0.2822, -0.2822],
								        [0.6247, -3.4229, -8.9179, -1.4297, -14.1650, 1.4146, -9.0218, -0.2703, -0.2703],
								        [6.4783, -1.9913, -10.7926, -2.3336, 1.5092, -0.9974, -6.8213, 1.3477, 1.3477],
								    ]		)
								self.assertTrue(np.allclose(__a   ,							__a   ,							atol=1e-4		)		)

								UpperCamelCase   =	tf.function(__a   ,							jit_compile=__a		)
								UpperCamelCase   =	tf.math.reduce_mean(xla_generate(inputs.input_ids   ,							attention_mask=inputs.attention_mask		)[0]   ,							axis=-1		)
								self.assertTrue(np.allclose(__a   ,							__a   ,							atol=1e-4		)		)





@require_tf
@slow
class        _lowerCamelCase      (       unittest.TestCase ):


						@property
						def     snake_case_   (self		) ->   List[str]:
								return [
								    "Today is a beautiful day and I want",
								    "In the city of",
								    "Paris is the capital of France and",
								    "Computers and mobile phones have taken",
								]


						def     snake_case_   (self		) ->   str:
								UpperCamelCase   =	"facebook/opt-125m"

								UpperCamelCase   =	[
								    "Today is a beautiful day and I want to",
								    "In the city of New York, the city",
								    "Paris is the capital of France and the capital",
								    "Computers and mobile phones have taken over the",
								]

								UpperCamelCase   =	[]
								UpperCamelCase   =	GPTaTokenizer.from_pretrained(__a		)
								UpperCamelCase   =	TFOPTForCausalLM.from_pretrained(__a		)

								for prompt in self.prompts:
										UpperCamelCase   =	tokenizer(__a   ,							return_tensors="tf"		).input_ids

										UpperCamelCase   =	model.generate(__a   ,							max_length=10		)

										UpperCamelCase   =	tokenizer.batch_decode(__a   ,							skip_special_tokens=__a		)
										predicted_outputs += generated_string

								self.assertListEqual(__a   ,							__a		)


						def     snake_case_   (self		) ->   List[str]:
								UpperCamelCase   =	"facebook/opt-350m"

								UpperCamelCase   =	GPTaTokenizer.from_pretrained(__a		)
								UpperCamelCase   =	TFOPTForCausalLM.from_pretrained(__a		)

								UpperCamelCase   =	"left"

								# use different length sentences to test batching
								UpperCamelCase   =	[
								    "Hello, my dog is a little",
								    "Today, I",
								]

								UpperCamelCase   =	tokenizer(__a   ,							return_tensors="tf"   ,							padding=__a		)
								UpperCamelCase   =	inputs["input_ids"]

								UpperCamelCase   =	model.generate(input_ids=__a   ,							attention_mask=inputs["attention_mask"]		)

								UpperCamelCase   =	tokenizer(sentences[0]   ,							return_tensors="tf"		).input_ids
								UpperCamelCase   =	model.generate(input_ids=__a		)

								UpperCamelCase   =	inputs_non_padded.shape[-1] - tf.math.reduce_sum(
								    tf.cast(inputs["attention_mask"][-1]   ,							tf.intaa		)		)
								UpperCamelCase   =	tokenizer(sentences[1]   ,							return_tensors="tf"		).input_ids
								UpperCamelCase   =	model.generate(input_ids=__a   ,							max_length=model.config.max_length - num_paddings		)

								UpperCamelCase   =	tokenizer.batch_decode(__a   ,							skip_special_tokens=__a		)
								UpperCamelCase   =	tokenizer.decode(output_non_padded[0]   ,							skip_special_tokens=__a		)
								UpperCamelCase   =	tokenizer.decode(output_padded[0]   ,							skip_special_tokens=__a		)

								UpperCamelCase   =	[
								    "Hello, my dog is a little bit of a dork.\nI'm a little bit",
								    "Today, I was in the middle of a conversation with a friend about the",
								]
								self.assertListEqual(__a   ,							__a		)
								self.assertListEqual(__a   ,							[non_padded_sentence, padded_sentence]		)




						def     snake_case_   (self		) ->   List[str]:
								UpperCamelCase   =	"facebook/opt-350m"

								UpperCamelCase   =	[
								    "Today is a beautiful day and I want to",
								    "In the city of San Francisco, the city",
								    "Paris is the capital of France and the capital",
								    "Computers and mobile phones have taken over the",
								]

								UpperCamelCase   =	[]
								UpperCamelCase   =	GPTaTokenizer.from_pretrained(__a		)
								UpperCamelCase   =	TFOPTForCausalLM.from_pretrained(__a		)

								for prompt in self.prompts:
										UpperCamelCase   =	tokenizer(__a   ,							return_tensors="tf"		).input_ids

										UpperCamelCase   =	model.generate(__a   ,							max_length=10		)

										UpperCamelCase   =	tokenizer.batch_decode(__a   ,							skip_special_tokens=__a		)
										predicted_outputs += generated_string

								self.assertListEqual(__a   ,							__a		)













"""simple docstring"""





import argparse

import gdown
import numpy as np
import torch
from huggingface_hub import hf_hub_download

from transformers import (
    CLIPTokenizer,
    CLIPTokenizerFast,
    VideoMAEImageProcessor,
    XCLIPConfig,
    XCLIPModel,
    XCLIPProcessor,
    XCLIPTextConfig,
    XCLIPVisionConfig,
)


def       a__					(					_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		UpperCamelCase   =	XCLIPTextConfig()

		# derive patch size from model name
		UpperCamelCase   =	model_name.find("patch"    )
		UpperCamelCase   =	int(model_name[start_idx + len("patch"    ) : start_idx + len("patch"    ) + 2]    )
		UpperCamelCase   =	XCLIPVisionConfig(patch_size=_SCREAMING_SNAKE_CASE  ,	num_frames=_SCREAMING_SNAKE_CASE    )

		if "large" in model_name:
				UpperCamelCase   =	768
				UpperCamelCase   =	3_072
				UpperCamelCase   =	12

				UpperCamelCase   =	1_024
				UpperCamelCase   =	4_096
				UpperCamelCase   =	16
				UpperCamelCase   =	24
				UpperCamelCase   =	768
				UpperCamelCase   =	3_072

		if model_name == "xclip-large-patch14-16-frames":
				UpperCamelCase   =	336

		UpperCamelCase   =	XCLIPConfig.from_text_vision_configs(_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    )

		if "large" in model_name:
				UpperCamelCase   =	768

		return config


def       a__					(					_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		if name == "token_embedding.weight":
				UpperCamelCase   =	name.replace("token_embedding.weight"  ,	"text_model.embeddings.token_embedding.weight"    )
		if name == "positional_embedding":
				UpperCamelCase   =	name.replace("positional_embedding"  ,	"text_model.embeddings.position_embedding.weight"    )
		if "ln_1" in name:
				UpperCamelCase   =	name.replace("ln_1"  ,	"layer_norm1"    )
		if "ln_2" in name:
				UpperCamelCase   =	name.replace("ln_2"  ,	"layer_norm2"    )
		if "c_fc" in name:
				UpperCamelCase   =	name.replace("c_fc"  ,	"fc1"    )
		if "c_proj" in name:
				UpperCamelCase   =	name.replace("c_proj"  ,	"fc2"    )
		if name.startswith("transformer.resblocks"    ):
				UpperCamelCase   =	name.replace("transformer.resblocks"  ,	"text_model.encoder.layers"    )
		if "attn.out_proj" in name and "message" not in name:
				UpperCamelCase   =	name.replace("attn.out_proj"  ,	"self_attn.out_proj"    )
		if "ln_final" in name:
				UpperCamelCase   =	name.replace("ln_final"  ,	"text_model.final_layer_norm"    )
		# visual encoder
		if name == "visual.class_embedding":
				UpperCamelCase   =	name.replace("visual.class_embedding"  ,	"vision_model.embeddings.class_embedding"    )
		if name == "visual.positional_embedding":
				UpperCamelCase   =	name.replace("visual.positional_embedding"  ,	"vision_model.embeddings.position_embedding.weight"    )
		if name.startswith("visual.transformer.resblocks"    ):
				UpperCamelCase   =	name.replace("visual.transformer.resblocks"  ,	"vision_model.encoder.layers"    )
		if "visual.conv1" in name:
				UpperCamelCase   =	name.replace("visual.conv1"  ,	"vision_model.embeddings.patch_embedding"    )
		if "visual.ln_pre" in name:
				UpperCamelCase   =	name.replace("visual.ln_pre"  ,	"vision_model.pre_layernorm"    )
		if "visual.ln_post" in name:
				UpperCamelCase   =	name.replace("visual.ln_post"  ,	"vision_model.post_layernorm"    )
		if "visual.proj" in name:
				UpperCamelCase   =	name.replace("visual.proj"  ,	"visual_projection.weight"    )
		if "text_projection" in name:
				UpperCamelCase   =	name.replace("text_projection"  ,	"text_projection.weight"    )
		# things on top
		if "prompts_visual_proj" in name:
				UpperCamelCase   =	name.replace("prompts_visual_proj"  ,	"prompts_visual_projection"    )
		if "prompts_visual_ln" in name:
				UpperCamelCase   =	name.replace("prompts_visual_ln"  ,	"prompts_visual_layernorm"    )
		# mit
		if name == "mit.positional_embedding":
				UpperCamelCase   =	name.replace("positional"  ,	"position"    )
		if name.startswith("mit.resblocks"    ):
				UpperCamelCase   =	name.replace("mit.resblocks"  ,	"mit.encoder.layers"    )
		# prompts generator
		if name.startswith("prompts_generator.norm"    ):
				UpperCamelCase   =	name.replace("prompts_generator.norm"  ,	"prompts_generator.layernorm"    )

		return name


def       a__					(					_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		for key in orig_state_dict.copy().keys():
				UpperCamelCase   =	orig_state_dict.pop(_SCREAMING_SNAKE_CASE    )

				if "attn.in_proj" in key:
						UpperCamelCase   =	key.split("."    )
						if key.startswith("visual"    ):
								UpperCamelCase   =	key_split[3]
								UpperCamelCase   =	config.vision_config.hidden_size
								if "message_attn" in key:
										if "weight" in key:
												UpperCamelCase   =	val[
												    :dim, :
												]
												UpperCamelCase   =	val[
												    dim : dim * 2, :
												]
												UpperCamelCase   =	val[
												    -dim:, :
												]
										else:
												UpperCamelCase   =	val[
												    :dim
												]
												UpperCamelCase   =	val[
												    dim : dim * 2
												]
												UpperCamelCase   =	val[
												    -dim:
												]
								else:
										if "weight" in key:
												UpperCamelCase   =	val[
												    :dim, :
												]
												UpperCamelCase   =	val[
												    dim : dim * 2, :
												]
												UpperCamelCase   =	val[
												    -dim:, :
												]
										else:
												UpperCamelCase   =	val[:dim]
												UpperCamelCase   =	val[
												    dim : dim * 2
												]
												UpperCamelCase   =	val[-dim:]
						elif key.startswith("mit"    ):
								UpperCamelCase   =	key_split[2]
								UpperCamelCase   =	config.vision_config.mit_hidden_size
								if "weight" in key:
										UpperCamelCase   =	val[:dim, :]
										UpperCamelCase   =	val[dim : dim * 2, :]
										UpperCamelCase   =	val[-dim:, :]
								else:
										UpperCamelCase   =	val[:dim]
										UpperCamelCase   =	val[dim : dim * 2]
										UpperCamelCase   =	val[-dim:]
						else:
								UpperCamelCase   =	key_split[2]
								UpperCamelCase   =	config.text_config.hidden_size
								if "weight" in key:
										UpperCamelCase   =	val[:dim, :]
										UpperCamelCase   =	val[
										    dim : dim * 2, :
										]
										UpperCamelCase   =	val[-dim:, :]
								else:
										UpperCamelCase   =	val[:dim]
										UpperCamelCase   =	val[
										    dim : dim * 2
										]
										UpperCamelCase   =	val[-dim:]
				else:
						UpperCamelCase   =	rename_key(_SCREAMING_SNAKE_CASE    )
						if new_key_name in ["visual_projection.weight", "text_projection.weight"]:
								UpperCamelCase   =	val.T
						UpperCamelCase   =	val

		return orig_state_dict


def       a__					(					_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		if num_frames == 8:
				UpperCamelCase   =	"eating_spaghetti_8_frames.npy"
		elif num_frames == 16:
				UpperCamelCase   =	"eating_spaghetti.npy"
		elif num_frames == 32:
				UpperCamelCase   =	"eating_spaghetti_32_frames.npy"
		UpperCamelCase   =	hf_hub_download(
		    repo_id="hf-internal-testing/spaghetti-video"  ,	filename=_SCREAMING_SNAKE_CASE  ,	repo_type="dataset"  ,	)
		UpperCamelCase   =	np.load(_SCREAMING_SNAKE_CASE    )
		return list(_SCREAMING_SNAKE_CASE    )


def       a__					(					_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE=None  ,	_SCREAMING_SNAKE_CASE=False    ):




		"""simple docstring"""


		UpperCamelCase   =	{
		    # fully supervised kinetics-400 checkpoints
		    "xclip-base-patch32": "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth",
		    "xclip-base-patch32-16-frames": (
		        "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth"
		    ),
		    "xclip-base-patch16": "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth",
		    "xclip-base-patch16-16-frames": (
		        "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth"
		    ),
		    "xclip-large-patch14": "https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&amp;export=download&amp;confirm=t&amp;uuid=b26caedc-88e2-473e-830a-9d158b653cdb",
		    "xclip-large-patch14-16-frames": "https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&amp;export=download&amp;confirm=t&amp;uuid=538fa810-e671-4050-b385-9a623f89804f",
		    # fully supervised kinetics-600 checkpoints
		    "xclip-base-patch16-kinetics-600": (
		        "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth"
		    ),
		    "xclip-base-patch16-kinetics-600-16-frames": (
		        "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth"
		    ),
		    "xclip-large-patch14-kinetics-600": "https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&amp;export=download&amp;confirm=t&amp;uuid=141d4977-4a65-44ae-864f-4b0c19f838be",
		    # few shot
		    "xclip-base-patch16-hmdb-2-shot": (
		        "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth"
		    ),
		    "xclip-base-patch16-hmdb-4-shot": (
		        "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth"
		    ),
		    "xclip-base-patch16-hmdb-8-shot": (
		        "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth"
		    ),
		    "xclip-base-patch16-hmdb-16-shot": (
		        "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth"
		    ),
		    "xclip-base-patch16-ucf-2-shot": (
		        "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth"
		    ),
		    "xclip-base-patch16-ucf-4-shot": (
		        "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth"
		    ),
		    "xclip-base-patch16-ucf-8-shot": (
		        "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth"
		    ),
		    "xclip-base-patch16-ucf-16-shot": (
		        "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth"
		    ),
		    # zero shot
		    "xclip-base-patch16-zero-shot": "https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth",
		}

		UpperCamelCase   =	model_to_url[model_name]
		UpperCamelCase   =	8
		if "16-frames" in model_name:
				UpperCamelCase   =	16
		elif "shot" in model_name:
				UpperCamelCase   =	32

		UpperCamelCase   =	get_xclip_config(_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    )
		UpperCamelCase   =	XCLIPModel(_SCREAMING_SNAKE_CASE    )
		model.eval()

		if "drive" in checkpoint_url:
				UpperCamelCase   =	"pytorch_model.bin"
				gdown.cached_download(_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE  ,	quiet=_SCREAMING_SNAKE_CASE    )
				UpperCamelCase   =	torch.load(_SCREAMING_SNAKE_CASE  ,	map_location="cpu"    )["model"]
		else:
				UpperCamelCase   =	torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE    )["model"]

		UpperCamelCase   =	convert_state_dict(_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    )

		UpperCamelCase   =	XCLIPModel(_SCREAMING_SNAKE_CASE    )
		UpperCamelCase   ,				UpperCamelCase   =	model.load_state_dict(_SCREAMING_SNAKE_CASE  ,	strict=_SCREAMING_SNAKE_CASE    )
		assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"]
		model.eval()

		UpperCamelCase   =	336 if model_name == "xclip-large-patch14-16-frames" else 224
		UpperCamelCase   =	VideoMAEImageProcessor(size=_SCREAMING_SNAKE_CASE    )
		UpperCamelCase   =	CLIPTokenizer.from_pretrained("openai/clip-vit-base-patch32"    )
		UpperCamelCase   =	CLIPTokenizerFast.from_pretrained("openai/clip-vit-base-patch32"    )
		UpperCamelCase   =	XCLIPProcessor(image_processor=_SCREAMING_SNAKE_CASE  ,	tokenizer=_SCREAMING_SNAKE_CASE    )

		UpperCamelCase   =	prepare_video(_SCREAMING_SNAKE_CASE    )
		UpperCamelCase   =	processor(
		    text=["playing sports", "eating spaghetti", "go shopping"]  ,	videos=_SCREAMING_SNAKE_CASE  ,	return_tensors="pt"  ,	padding=_SCREAMING_SNAKE_CASE    )

		print("Shape of pixel values:"  ,	inputs.pixel_values.shape    )

		with torch.no_grad():
				UpperCamelCase   =	model(**_SCREAMING_SNAKE_CASE    )

		# Verify outputs
		UpperCamelCase   =	outputs.logits_per_video
		UpperCamelCase   =	logits_per_video.softmax(dim=1    )
		print("Probs:"  ,	_SCREAMING_SNAKE_CASE    )
		# kinetics-400
		if model_name == "xclip-base-patch32":
				UpperCamelCase   =	torch.tensor([[0.00_19, 0.99_51, 0.00_30]]    )
		elif model_name == "xclip-base-patch32-16-frames":
				UpperCamelCase   =	torch.tensor([[7.0999e-04, 9.9883e-01, 4.5580e-04]]    )
		elif model_name == "xclip-base-patch16":
				UpperCamelCase   =	torch.tensor([[0.00_83, 0.96_81, 0.02_36]]    )
		elif model_name == "xclip-base-patch16-16-frames":
				UpperCamelCase   =	torch.tensor([[7.6937e-04, 9.9728e-01, 1.9473e-03]]    )
		elif model_name == "xclip-large-patch14":
				UpperCamelCase   =	torch.tensor([[0.00_62, 0.98_64, 0.00_75]]    )
		elif model_name == "xclip-large-patch14-16-frames":
				UpperCamelCase   =	torch.tensor([[3.3877e-04, 9.9937e-01, 2.8888e-04]]    )
		# kinetics-600
		elif model_name == "xclip-base-patch16-kinetics-600":
				UpperCamelCase   =	torch.tensor([[0.05_55, 0.89_14, 0.05_31]]    )
		elif model_name == "xclip-base-patch16-kinetics-600-16-frames":
				UpperCamelCase   =	torch.tensor([[3.8554e-04, 9.9929e-01, 3.2754e-04]]    )
		elif model_name == "xclip-large-patch14-kinetics-600":
				UpperCamelCase   =	torch.tensor([[0.00_36, 0.99_20, 0.00_45]]    )
		# few shot
		elif model_name == "xclip-base-patch16-hmdb-2-shot":
				UpperCamelCase   =	torch.tensor([[7.1890e-06, 9.9994e-01, 5.6559e-05]]    )
		elif model_name == "xclip-base-patch16-hmdb-4-shot":
				UpperCamelCase   =	torch.tensor([[1.0320e-05, 9.9993e-01, 6.2435e-05]]    )
		elif model_name == "xclip-base-patch16-hmdb-8-shot":
				UpperCamelCase   =	torch.tensor([[4.1377e-06, 9.9990e-01, 9.8386e-05]]    )
		elif model_name == "xclip-base-patch16-hmdb-16-shot":
				UpperCamelCase   =	torch.tensor([[4.1347e-05, 9.9962e-01, 3.3411e-04]]    )
		elif model_name == "xclip-base-patch16-ucf-2-shot":
				UpperCamelCase   =	torch.tensor([[8.5857e-05, 9.9928e-01, 6.3291e-04]]    )
		elif model_name == "xclip-base-patch16-ucf-4-shot":
				UpperCamelCase   =	torch.tensor([[8.5857e-05, 9.9928e-01, 6.3291e-04]]    )
		elif model_name == "xclip-base-patch16-ucf-8-shot":
				UpperCamelCase   =	torch.tensor([[0.00_27, 0.99_04, 0.00_70]]    )
		elif model_name == "xclip-base-patch16-ucf-16-shot":
				UpperCamelCase   =	torch.tensor([[9.8219e-04, 9.9593e-01, 3.0863e-03]]    )
		# zero shot
		elif model_name == "xclip-base-patch16-zero-shot":
				UpperCamelCase   =	torch.tensor([[3.5082e-04, 9.9785e-01, 1.7966e-03]]    )
		else:
				raise ValueError(F"Model name {model_name} not supported"    )
		assert torch.allclose(_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE  ,	atol=1e-3    )
		print("Looks ok!"    )

		if pytorch_dump_folder_path is not None:
				print(F"Saving model {model_name} to {pytorch_dump_folder_path}"    )
				model.save_pretrained(_SCREAMING_SNAKE_CASE    )

		if push_to_hub:
				print("Pushing model, processor and slow tokenizer files to the hub..."    )
				model.push_to_hub(_SCREAMING_SNAKE_CASE  ,	organization="nielsr"    )
				processor.push_to_hub(_SCREAMING_SNAKE_CASE  ,	organization="nielsr"    )
				slow_tokenizer.push_to_hub(_SCREAMING_SNAKE_CASE  ,	organization="nielsr"    )


if __name__ == "__main__":
						lowerCAmelCase__     			=			argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    '''--model_name''',
						    default='''xclip-base-patch32''',
						    type=str,
						    help='''Name of the model.''',
						)
						parser.add_argument(
						    '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
						)
						parser.add_argument(
						    '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.'''
						)

						lowerCAmelCase__     			=			parser.parse_args()
						convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)






