
import os
import tempfile
import unittest

from transformers import NezhaConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import (
					    MODEL_FOR_PRETRAINING_MAPPING,
					    NezhaForMaskedLM,
					    NezhaForMultipleChoice,
					    NezhaForNextSentencePrediction,
					    NezhaForPreTraining,
					    NezhaForQuestionAnswering,
					    NezhaForSequenceClassification,
					    NezhaForTokenClassification,
					    NezhaModel,
					)
					from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST







class      A__							:






				def __init__(						self					:      str    ,     a					:      Optional[Any]    ,     a					:      int=13    ,     a					:      str=7    ,     a					:      str=True    ,     a					:      List[str]=True    ,     a					:      Optional[Any]=True    ,     a					:      int=True    ,     a					:      List[Any]=99    ,     a					:      List[Any]=32    ,     a					:      Tuple=5    ,     a					:      Any=4    ,     a					:      Optional[int]=37    ,     a					:      Tuple="gelu"    ,     a					:      Any=0.1    ,     a					:      int=0.1    ,     a					:      List[Any]=128    ,     a					:      Union[str, Any]=32    ,     a					:      Union[str, Any]=16    ,     a					:      Dict=2    ,     a					:      List[Any]=0.0_2    ,     a					:      Optional[Any]=3    ,     a					:      List[Any]=4    ,     a					:      Optional[int]=None    ,     ):






							'''simple docstring'''







							lowerCAmelCase__      :      Optional[Any]         =		parent
							lowerCAmelCase__      :      Dict         =		batch_size
							lowerCAmelCase__      :      Optional[Any]         =		seq_length
							lowerCAmelCase__      :      Optional[Any]         =		is_training
							lowerCAmelCase__      :      Union[str, Any]         =		use_input_mask
							lowerCAmelCase__      :      List[Any]         =		use_token_type_ids
							lowerCAmelCase__      :      str         =		use_labels
							lowerCAmelCase__      :      Optional[Any]         =		vocab_size
							lowerCAmelCase__      :      Union[str, Any]         =		hidden_size
							lowerCAmelCase__      :      Optional[int]         =		num_hidden_layers
							lowerCAmelCase__      :      Optional[int]         =		num_attention_heads
							lowerCAmelCase__      :      List[Any]         =		intermediate_size
							lowerCAmelCase__      :      List[str]         =		hidden_act
							lowerCAmelCase__      :      List[Any]         =		hidden_dropout_prob
							lowerCAmelCase__      :      Optional[int]         =		attention_probs_dropout_prob
							lowerCAmelCase__      :      Dict         =		max_position_embeddings
							lowerCAmelCase__      :      Any         =		type_vocab_size
							lowerCAmelCase__      :      Any         =		type_sequence_label_size
							lowerCAmelCase__      :      List[Any]         =		initializer_range
							lowerCAmelCase__      :      Dict         =		num_labels
							lowerCAmelCase__      :      Any         =		num_choices
							lowerCAmelCase__      :      Union[str, Any]         =		scope






				def 							_lowerCamelCase		(						self					:      Dict   ):






							'''simple docstring'''







							lowerCAmelCase__      :      int         =		ids_tensor([self.batch_size, self.seq_length]    ,     self.vocab_size   )

							lowerCAmelCase__      :      Tuple         =		None
							if self.use_input_mask:
										lowerCAmelCase__      :      Tuple         =		random_attention_mask([self.batch_size, self.seq_length]   )

							lowerCAmelCase__      :      Tuple         =		None
							if self.use_token_type_ids:
										lowerCAmelCase__      :      List[Any]         =		ids_tensor([self.batch_size, self.seq_length]    ,     self.type_vocab_size   )

							lowerCAmelCase__      :      Optional[int]         =		None
							lowerCAmelCase__      :      Optional[Any]         =		None
							lowerCAmelCase__      :      Optional[int]         =		None
							if self.use_labels:
										lowerCAmelCase__      :      Any         =		ids_tensor([self.batch_size]    ,     self.type_sequence_label_size   )
										lowerCAmelCase__      :      Union[str, Any]         =		ids_tensor([self.batch_size, self.seq_length]    ,     self.num_labels   )
										lowerCAmelCase__      :      List[Any]         =		ids_tensor([self.batch_size]    ,     self.num_choices   )

							lowerCAmelCase__      :      Dict         =		self.get_config()

							return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels






				def 							_lowerCamelCase		(						self					:      List[Any]   ):






							'''simple docstring'''







							return NezhaConfig(
							    vocab_size=self.vocab_size    ,     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    ,     max_position_embeddings=self.max_position_embeddings    ,     type_vocab_size=self.type_vocab_size    ,     is_decoder=a    ,     initializer_range=self.initializer_range    ,     )






				def 							_lowerCamelCase		(						self					:      Optional[Any]   ):






							'''simple docstring'''







							(
							    (
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				
							)      :      List[Any]         =		self.prepare_config_and_inputs()

							lowerCAmelCase__      :      List[Any]         =		True
							lowerCAmelCase__      :      Tuple         =		floats_tensor([self.batch_size, self.seq_length, self.hidden_size]   )
							lowerCAmelCase__      :      Tuple         =		ids_tensor([self.batch_size, self.seq_length]    ,     vocab_size=2   )

							return (
							    config,
							    input_ids,
							    token_type_ids,
							    input_mask,
							    sequence_labels,
							    token_labels,
							    choice_labels,
							    encoder_hidden_states,
							    encoder_attention_mask,
							)






				def 							_lowerCamelCase		(						self					:      Optional[Any]    ,     a					:      Optional[int]    ,     a					:      Tuple    ,     a					:      Optional[int]    ,     a					:      List[Any]    ,     a					:      Tuple    ,     a					:      List[str]    ,     a					:      Any   ):






							'''simple docstring'''







							lowerCAmelCase__      :      List[str]         =		NezhaModel(config=a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      Dict         =		model(a    ,     attention_mask=a    ,     token_type_ids=a   )
							lowerCAmelCase__      :      List[str]         =		model(a    ,     token_type_ids=a   )
							lowerCAmelCase__      :      Any         =		model(a   )
							self.parent.assertEqual(result.last_hidden_state.shape    ,     (self.batch_size, self.seq_length, self.hidden_size)   )
							self.parent.assertEqual(result.pooler_output.shape    ,     (self.batch_size, self.hidden_size)   )






				def 							_lowerCamelCase		(						self					:      List[Any]    ,     a					:      Union[str, Any]    ,     a					:      Dict    ,     a					:      List[Any]    ,     a					:      Optional[Any]    ,     a					:      int    ,     a					:      Tuple    ,     a					:      List[Any]    ,     a					:      Tuple    ,     a					:      List[str]    ,     ):






							'''simple docstring'''







							lowerCAmelCase__      :      Union[str, Any]         =		True
							lowerCAmelCase__      :      Optional[int]         =		NezhaModel(a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      Any         =		model(
							    a    ,     attention_mask=a    ,     token_type_ids=a    ,     encoder_hidden_states=a    ,     encoder_attention_mask=a    ,     )
							lowerCAmelCase__      :      Dict         =		model(
							    a    ,     attention_mask=a    ,     token_type_ids=a    ,     encoder_hidden_states=a    ,     )
							lowerCAmelCase__      :      List[str]         =		model(a    ,     attention_mask=a    ,     token_type_ids=a   )
							self.parent.assertEqual(result.last_hidden_state.shape    ,     (self.batch_size, self.seq_length, self.hidden_size)   )
							self.parent.assertEqual(result.pooler_output.shape    ,     (self.batch_size, self.hidden_size)   )






				def 							_lowerCamelCase		(						self					:      Tuple    ,     a					:      Optional[Any]    ,     a					:      List[Any]    ,     a					:      str    ,     a					:      List[str]    ,     a					:      Tuple    ,     a					:      List[Any]    ,     a					:      Optional[Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      List[Any]         =		NezhaForMaskedLM(config=a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      Dict         =		model(a    ,     attention_mask=a    ,     token_type_ids=a    ,     labels=a   )
							self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.seq_length, self.vocab_size)   )






				def 							_lowerCamelCase		(						self					:      List[Any]    ,     a					:      Optional[int]    ,     a					:      List[Any]    ,     a					:      int    ,     a					:      List[str]    ,     a					:      Union[str, Any]    ,     a					:      int    ,     a					:      Any   ):






							'''simple docstring'''







							lowerCAmelCase__      :      List[Any]         =		NezhaForNextSentencePrediction(config=a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      str         =		model(
							    a    ,     attention_mask=a    ,     token_type_ids=a    ,     labels=a    ,     )
							self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, 2)   )






				def 							_lowerCamelCase		(						self					:      int    ,     a					:      Optional[int]    ,     a					:      str    ,     a					:      List[str]    ,     a					:      int    ,     a					:      Dict    ,     a					:      Optional[Any]    ,     a					:      Optional[Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Tuple         =		NezhaForPreTraining(config=a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      Optional[int]         =		model(
							    a    ,     attention_mask=a    ,     token_type_ids=a    ,     labels=a    ,     next_sentence_label=a    ,     )
							self.parent.assertEqual(result.prediction_logits.shape    ,     (self.batch_size, self.seq_length, self.vocab_size)   )
							self.parent.assertEqual(result.seq_relationship_logits.shape    ,     (self.batch_size, 2)   )






				def 							_lowerCamelCase		(						self					:      Union[str, Any]    ,     a					:      Dict    ,     a					:      List[str]    ,     a					:      Any    ,     a					:      Any    ,     a					:      Union[str, Any]    ,     a					:      Tuple    ,     a					:      List[Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Optional[Any]         =		NezhaForQuestionAnswering(config=a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      Tuple         =		model(
							    a    ,     attention_mask=a    ,     token_type_ids=a    ,     start_positions=a    ,     end_positions=a    ,     )
							self.parent.assertEqual(result.start_logits.shape    ,     (self.batch_size, self.seq_length)   )
							self.parent.assertEqual(result.end_logits.shape    ,     (self.batch_size, self.seq_length)   )






				def 							_lowerCamelCase		(						self					:      Tuple    ,     a					:      str    ,     a					:      Union[str, Any]    ,     a					:      Tuple    ,     a					:      Optional[Any]    ,     a					:      Dict    ,     a					:      str    ,     a					:      int   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Any         =		self.num_labels
							lowerCAmelCase__      :      Optional[Any]         =		NezhaForSequenceClassification(a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      Tuple         =		model(a    ,     attention_mask=a    ,     token_type_ids=a    ,     labels=a   )
							self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.num_labels)   )






				def 							_lowerCamelCase		(						self					:      List[str]    ,     a					:      Dict    ,     a					:      str    ,     a					:      Optional[Any]    ,     a					:      Optional[int]    ,     a					:      List[str]    ,     a					:      Dict    ,     a					:      str   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Dict         =		self.num_labels
							lowerCAmelCase__      :      str         =		NezhaForTokenClassification(config=a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      Any         =		model(a    ,     attention_mask=a    ,     token_type_ids=a    ,     labels=a   )
							self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.seq_length, self.num_labels)   )






				def 							_lowerCamelCase		(						self					:      int    ,     a					:      Tuple    ,     a					:      List[Any]    ,     a					:      Tuple    ,     a					:      List[Any]    ,     a					:      Optional[int]    ,     a					:      Optional[int]    ,     a					:      Optional[Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Optional[Any]         =		self.num_choices
							lowerCAmelCase__      :      Any         =		NezhaForMultipleChoice(config=a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      int         =		input_ids.unsqueeze(1   ).expand(-1    ,     self.num_choices    ,     -1   ).contiguous()
							lowerCAmelCase__      :      str         =		token_type_ids.unsqueeze(1   ).expand(-1    ,     self.num_choices    ,     -1   ).contiguous()
							lowerCAmelCase__      :      Optional[Any]         =		input_mask.unsqueeze(1   ).expand(-1    ,     self.num_choices    ,     -1   ).contiguous()
							lowerCAmelCase__      :      Any         =		model(
							    a    ,     attention_mask=a    ,     token_type_ids=a    ,     labels=a    ,     )
							self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.num_choices)   )






				def 							_lowerCamelCase		(						self					:      Tuple   ):






							'''simple docstring'''







							lowerCAmelCase__      :      int         =		self.prepare_config_and_inputs()
							(
							    (
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				
							)      :      Any         =		config_and_inputs
							lowerCAmelCase__      :      str         =		{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
							return config, inputs_dict







@require_torch
class      A__							(     __magic_name__						,   __magic_name__						,   __magic_name__						,   unittest.TestCase	):
				lowercase			    =  (
				    (
				        NezhaModel,
				        NezhaForMaskedLM,
				        NezhaForMultipleChoice,
				        NezhaForNextSentencePrediction,
				        NezhaForPreTraining,
				        NezhaForQuestionAnswering,
				        NezhaForSequenceClassification,
				        NezhaForTokenClassification,
				    )
				    if is_torch_available()
				    else ()
				)
				lowercase			    =  (
				    {
				        'feature-extraction': NezhaModel,
				        'fill-mask': NezhaForMaskedLM,
				        'question-answering': NezhaForQuestionAnswering,
				        'text-classification': NezhaForSequenceClassification,
				        'token-classification': NezhaForTokenClassification,
				        'zero-shot': NezhaForSequenceClassification,
				    }
				    if is_torch_available()
				    else {}
				)
				lowercase			    =  True






				def 							_lowerCamelCase		(						self					:      str    ,     a					:      Tuple    ,     a					:      int    ,     a					:      Dict=False   ):






							'''simple docstring'''







							lowerCAmelCase__      :      int         =		super()._prepare_for_class(a    ,     a    ,     return_labels=a   )

							if return_labels:
										if model_class in get_values(a   ):
													lowerCAmelCase__      :      Tuple         =		torch.zeros(
													    (self.model_tester.batch_size, self.model_tester.seq_length)    ,     dtype=torch.long    ,     device=a   )
													lowerCAmelCase__      :      Optional[Any]         =		torch.zeros(
													    self.model_tester.batch_size    ,     dtype=torch.long    ,     device=a   )
							return inputs_dict






				def 							_lowerCamelCase		(						self					:      Union[str, Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Optional[int]         =		NezhaModelTester(self   )
							lowerCAmelCase__      :      Optional[int]         =		ConfigTester(self    ,     config_class=a    ,     hidden_size=37   )






				def 							_lowerCamelCase		(						self					:      Union[str, Any]   ):






							'''simple docstring'''







							self.config_tester.run_common_tests()






				def 							_lowerCamelCase		(						self					:      Optional[int]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      List[str]         =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*a   )






				def 							_lowerCamelCase		(						self					:      List[str]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      int         =		self.model_tester.prepare_config_and_inputs_for_decoder()
							self.model_tester.create_and_check_model_as_decoder(*a   )






				def 							_lowerCamelCase		(						self					:      Optional[Any]   ):






							'''simple docstring'''







							(
							    (
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				
							)      :      str         =		self.model_tester.prepare_config_and_inputs_for_decoder()

							lowerCAmelCase__      :      str         =		None

							self.model_tester.create_and_check_model_as_decoder(
							    a    ,     a    ,     a    ,     a    ,     a    ,     a    ,     a    ,     a    ,     a    ,     )






				def 							_lowerCamelCase		(						self					:      int   ):






							'''simple docstring'''







							lowerCAmelCase__      :      int         =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_lm(*a   )






				def 							_lowerCamelCase		(						self					:      List[Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Union[str, Any]         =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_multiple_choice(*a   )






				def 							_lowerCamelCase		(						self					:      int   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Optional[int]         =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_next_sequence_prediction(*a   )






				def 							_lowerCamelCase		(						self					:      Union[str, Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      List[str]         =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_pretraining(*a   )






				def 							_lowerCamelCase		(						self					:      int   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Optional[int]         =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*a   )






				def 							_lowerCamelCase		(						self					:      Optional[Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      int         =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(*a   )






				def 							_lowerCamelCase		(						self					:      List[Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Any         =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*a   )






				@slow
				def 							_lowerCamelCase		(						self					:      Union[str, Any]   ):






							'''simple docstring'''







							for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										lowerCAmelCase__      :      Optional[Any]         =		NezhaModel.from_pretrained(a   )
										self.assertIsNotNone(a   )






				@slow
				@require_torch_gpu
				def 							_lowerCamelCase		(						self					:      Optional[int]   ):






							'''simple docstring'''







							lowerCAmelCase__      ,				lowerCAmelCase__      :      Optional[int]         =		self.model_tester.prepare_config_and_inputs_for_common()
							for model_class in self.all_model_classes:
										# NezhaForMultipleChoice behaves incorrectly in JIT environments.
										if model_class == NezhaForMultipleChoice:
													return

										lowerCAmelCase__      :      Dict         =		True
										lowerCAmelCase__      :      Any         =		model_class(config=a   )

										lowerCAmelCase__      :      Union[str, Any]         =		self._prepare_for_class(a    ,     a   )
										lowerCAmelCase__      :      int         =		torch.jit.trace(
										    a    ,     (inputs_dict['input_ids'].to('cpu'   ), inputs_dict['attention_mask'].to('cpu'   ))   )

										with tempfile.TemporaryDirectory() as tmp:
													torch.jit.save(a    ,     os.path.join(a    ,     'bert.pt'   )   )
													lowerCAmelCase__      :      Any         =		torch.jit.load(os.path.join(a    ,     'bert.pt'   )    ,     map_location=a   )
													loaded(inputs_dict['input_ids'].to(a   )    ,     inputs_dict['attention_mask'].to(a   )   )







@require_torch
class      A__							(     unittest.TestCase	):






				@slow
				def 							_lowerCamelCase		(						self					:      Optional[int]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      str         =		NezhaModel.from_pretrained('sijunhe/nezha-cn-base'   )
							lowerCAmelCase__      :      Any         =		torch.tensor([[0, 1, 2, 3, 4, 5]]   )
							lowerCAmelCase__      :      Union[str, Any]         =		torch.tensor([[0, 1, 1, 1, 1, 1]]   )
							with torch.no_grad():
										lowerCAmelCase__      :      Optional[int]         =		model(a    ,     attention_mask=a   )[0]
							lowerCAmelCase__      :      Union[str, Any]         =		torch.Size((1, 6, 768)   )
							self.assertEqual(output.shape    ,     a   )
							lowerCAmelCase__      :      Optional[int]         =		torch.tensor([[[0.0_6_8_5, 0.2_4_4_1, 0.1_1_0_2], [0.0_6_0_0, 0.1_9_0_6, 0.1_3_4_9], [0.0_2_2_1, 0.0_8_1_9, 0.0_5_8_6]]]   )

							self.assertTrue(torch.allclose(output[:, 1:4, 1:4]    ,     a    ,     atol=1E-4   )   )






				@slow
				def 							_lowerCamelCase		(						self					:      List[Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Any         =		NezhaForMaskedLM.from_pretrained('sijunhe/nezha-cn-base'   )
							lowerCAmelCase__      :      Optional[int]         =		torch.tensor([[0, 1, 2, 3, 4, 5]]   )
							lowerCAmelCase__      :      Optional[int]         =		torch.tensor([[1, 1, 1, 1, 1, 1]]   )
							with torch.no_grad():
										lowerCAmelCase__      :      Optional[int]         =		model(a    ,     attention_mask=a   )[0]
							lowerCAmelCase__      :      int         =		torch.Size((1, 6, 21_128)   )
							self.assertEqual(output.shape    ,     a   )
							lowerCAmelCase__      :      List[Any]         =		torch.tensor(
							    [[-2.7_9_3_9, -1.7_9_0_2, -2.2_1_8_9], [-2.8_5_8_5, -1.8_9_0_8, -2.3_7_2_3], [-2.6_4_9_9, -1.7_7_5_0, -2.2_5_5_8]]   )

							self.assertTrue(torch.allclose(output[:, 1:4, 1:4]    ,     a    ,     atol=1E-4   )   )

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  lowerCAmelCase__			(  SCREAMING_SNAKE_CASE_       ,							SCREAMING_SNAKE_CASE_     )				->		int:
			lowerCAmelCase__      :      int         =		XCLIPTextConfig()

			# derive patch size from model name
			lowerCAmelCase__      :      Any         =		model_name.find('patch'     )
			lowerCAmelCase__      :      Any         =		int(model_name[start_idx + len('patch'     ) : start_idx + len('patch'     ) + 2]     )
			lowerCAmelCase__      :      Any         =		XCLIPVisionConfig(patch_size=SCREAMING_SNAKE_CASE_       ,							num_frames=SCREAMING_SNAKE_CASE_     )

			if "large" in model_name:
						lowerCAmelCase__      :      List[str]         =		768
						lowerCAmelCase__      :      Optional[int]         =		3_072
						lowerCAmelCase__      :      Any         =		12

						lowerCAmelCase__      :      Optional[int]         =		1_024
						lowerCAmelCase__      :      List[Any]         =		4_096
						lowerCAmelCase__      :      Optional[Any]         =		16
						lowerCAmelCase__      :      Any         =		24
						lowerCAmelCase__      :      Dict         =		768
						lowerCAmelCase__      :      List[str]         =		3_072

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

			lowerCAmelCase__      :      Any         =		XCLIPConfig.from_text_vision_configs(SCREAMING_SNAKE_CASE_       ,							SCREAMING_SNAKE_CASE_     )

			if "large" in model_name:
						lowerCAmelCase__      :      List[Any]         =		768

			return config
def  lowerCAmelCase__			(  SCREAMING_SNAKE_CASE_     )				->		List[Any]:
			# text encoder
			if name == "token_embedding.weight":
						lowerCAmelCase__      :      Optional[Any]         =		name.replace('token_embedding.weight'       ,							'text_model.embeddings.token_embedding.weight'     )
			if name == "positional_embedding":
						lowerCAmelCase__      :      int         =		name.replace('positional_embedding'       ,							'text_model.embeddings.position_embedding.weight'     )
			if "ln_1" in name:
						lowerCAmelCase__      :      Optional[Any]         =		name.replace('ln_1'       ,							'layer_norm1'     )
			if "ln_2" in name:
						lowerCAmelCase__      :      List[str]         =		name.replace('ln_2'       ,							'layer_norm2'     )
			if "c_fc" in name:
						lowerCAmelCase__      :      Tuple         =		name.replace('c_fc'       ,							'fc1'     )
			if "c_proj" in name:
						lowerCAmelCase__      :      Optional[Any]         =		name.replace('c_proj'       ,							'fc2'     )
			if name.startswith('transformer.resblocks'     ):
						lowerCAmelCase__      :      List[str]         =		name.replace('transformer.resblocks'       ,							'text_model.encoder.layers'     )
			if "attn.out_proj" in name and "message" not in name:
						lowerCAmelCase__      :      Optional[Any]         =		name.replace('attn.out_proj'       ,							'self_attn.out_proj'     )
			if "ln_final" in name:
						lowerCAmelCase__      :      List[str]         =		name.replace('ln_final'       ,							'text_model.final_layer_norm'     )
			# visual encoder
			if name == "visual.class_embedding":
						lowerCAmelCase__      :      Dict         =		name.replace('visual.class_embedding'       ,							'vision_model.embeddings.class_embedding'     )
			if name == "visual.positional_embedding":
						lowerCAmelCase__      :      Any         =		name.replace('visual.positional_embedding'       ,							'vision_model.embeddings.position_embedding.weight'     )
			if name.startswith('visual.transformer.resblocks'     ):
						lowerCAmelCase__      :      Union[str, Any]         =		name.replace('visual.transformer.resblocks'       ,							'vision_model.encoder.layers'     )
			if "visual.conv1" in name:
						lowerCAmelCase__      :      Dict         =		name.replace('visual.conv1'       ,							'vision_model.embeddings.patch_embedding'     )
			if "visual.ln_pre" in name:
						lowerCAmelCase__      :      Union[str, Any]         =		name.replace('visual.ln_pre'       ,							'vision_model.pre_layernorm'     )
			if "visual.ln_post" in name:
						lowerCAmelCase__      :      Tuple         =		name.replace('visual.ln_post'       ,							'vision_model.post_layernorm'     )
			if "visual.proj" in name:
						lowerCAmelCase__      :      Optional[Any]         =		name.replace('visual.proj'       ,							'visual_projection.weight'     )
			if "text_projection" in name:
						lowerCAmelCase__      :      Any         =		name.replace('text_projection'       ,							'text_projection.weight'     )
			# things on top
			if "prompts_visual_proj" in name:
						lowerCAmelCase__      :      str         =		name.replace('prompts_visual_proj'       ,							'prompts_visual_projection'     )
			if "prompts_visual_ln" in name:
						lowerCAmelCase__      :      Tuple         =		name.replace('prompts_visual_ln'       ,							'prompts_visual_layernorm'     )
			# mit
			if name == "mit.positional_embedding":
						lowerCAmelCase__      :      Dict         =		name.replace('positional'       ,							'position'     )
			if name.startswith('mit.resblocks'     ):
						lowerCAmelCase__      :      List[str]         =		name.replace('mit.resblocks'       ,							'mit.encoder.layers'     )
			# prompts generator
			if name.startswith('prompts_generator.norm'     ):
						lowerCAmelCase__      :      List[Any]         =		name.replace('prompts_generator.norm'       ,							'prompts_generator.layernorm'     )

			return name
def  lowerCAmelCase__			(  SCREAMING_SNAKE_CASE_       ,							SCREAMING_SNAKE_CASE_     )				->		Union[str, Any]:
			for key in orig_state_dict.copy().keys():
						lowerCAmelCase__      :      Any         =		orig_state_dict.pop(SCREAMING_SNAKE_CASE_     )

						if "attn.in_proj" in key:
									lowerCAmelCase__      :      str         =		key.split('.'     )
									if key.startswith('visual'     ):
												lowerCAmelCase__      :      str         =		key_split[3]
												lowerCAmelCase__      :      Optional[Any]         =		config.vision_config.hidden_size
												if "message_attn" in key:
															if "weight" in key:
																		lowerCAmelCase__      :      Any         =		val[
																		    :dim, :
																		]
																		lowerCAmelCase__      :      Optional[Any]         =		val[
																		    dim : dim * 2, :
																		]
																		lowerCAmelCase__      :      int         =		val[
																		    -dim:, :
																		]
															else:
																		lowerCAmelCase__      :      str         =		val[
																		    :dim
																		]
																		lowerCAmelCase__      :      Union[str, Any]         =		val[
																		    dim : dim * 2
																		]
																		lowerCAmelCase__      :      Any         =		val[
																		    -dim:
																		]
												else:
															if "weight" in key:
																		lowerCAmelCase__      :      str         =		val[
																		    :dim, :
																		]
																		lowerCAmelCase__      :      Tuple         =		val[
																		    dim : dim * 2, :
																		]
																		lowerCAmelCase__      :      int         =		val[
																		    -dim:, :
																		]
															else:
																		lowerCAmelCase__      :      List[Any]         =		val[:dim]
																		lowerCAmelCase__      :      Optional[Any]         =		val[
																		    dim : dim * 2
																		]
																		lowerCAmelCase__      :      int         =		val[-dim:]
									elif key.startswith('mit'     ):
												lowerCAmelCase__      :      Dict         =		key_split[2]
												lowerCAmelCase__      :      str         =		config.vision_config.mit_hidden_size
												if "weight" in key:
															lowerCAmelCase__      :      List[Any]         =		val[:dim, :]
															lowerCAmelCase__      :      List[Any]         =		val[dim : dim * 2, :]
															lowerCAmelCase__      :      Any         =		val[-dim:, :]
												else:
															lowerCAmelCase__      :      int         =		val[:dim]
															lowerCAmelCase__      :      Optional[Any]         =		val[dim : dim * 2]
															lowerCAmelCase__      :      List[str]         =		val[-dim:]
									else:
												lowerCAmelCase__      :      int         =		key_split[2]
												lowerCAmelCase__      :      Optional[Any]         =		config.text_config.hidden_size
												if "weight" in key:
															lowerCAmelCase__      :      int         =		val[:dim, :]
															lowerCAmelCase__      :      List[str]         =		val[
															    dim : dim * 2, :
															]
															lowerCAmelCase__      :      Dict         =		val[-dim:, :]
												else:
															lowerCAmelCase__      :      List[str]         =		val[:dim]
															lowerCAmelCase__      :      int         =		val[
															    dim : dim * 2
															]
															lowerCAmelCase__      :      Optional[int]         =		val[-dim:]
						else:
									lowerCAmelCase__      :      Optional[int]         =		rename_key(SCREAMING_SNAKE_CASE_     )
									if new_key_name in ["visual_projection.weight", "text_projection.weight"]:
												lowerCAmelCase__      :      List[str]         =		val.T
									lowerCAmelCase__      :      List[str]         =		val

			return orig_state_dict
def  lowerCAmelCase__			(  SCREAMING_SNAKE_CASE_     )				->		Dict:
			if num_frames == 8:
						lowerCAmelCase__      :      Tuple         =		'eating_spaghetti_8_frames.npy'
			elif num_frames == 16:
						lowerCAmelCase__      :      Dict         =		'eating_spaghetti.npy'
			elif num_frames == 32:
						lowerCAmelCase__      :      List[Any]         =		'eating_spaghetti_32_frames.npy'
			lowerCAmelCase__      :      Dict         =		hf_hub_download(
			    repo_id='hf-internal-testing/spaghetti-video'       ,							filename=SCREAMING_SNAKE_CASE_       ,							repo_type='dataset'       ,							)
			lowerCAmelCase__      :      Optional[int]         =		np.load(SCREAMING_SNAKE_CASE_     )
			return list(SCREAMING_SNAKE_CASE_     )
def  lowerCAmelCase__			(  SCREAMING_SNAKE_CASE_       ,							SCREAMING_SNAKE_CASE_=None       ,							SCREAMING_SNAKE_CASE_=False     )				->		str:
			lowerCAmelCase__      :      Optional[int]         =		{
			    # 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',
			}

			lowerCAmelCase__      :      Dict         =		model_to_url[model_name]
			lowerCAmelCase__      :      List[str]         =		8
			if "16-frames" in model_name:
						lowerCAmelCase__      :      Any         =		16
			elif "shot" in model_name:
						lowerCAmelCase__      :      str         =		32

			lowerCAmelCase__      :      str         =		get_xclip_config(SCREAMING_SNAKE_CASE_       ,							SCREAMING_SNAKE_CASE_     )
			lowerCAmelCase__      :      Any         =		XCLIPModel(SCREAMING_SNAKE_CASE_     )
			model.eval()

			if "drive" in checkpoint_url:
						lowerCAmelCase__      :      Any         =		'pytorch_model.bin'
						gdown.cached_download(SCREAMING_SNAKE_CASE_       ,							SCREAMING_SNAKE_CASE_       ,							quiet=SCREAMING_SNAKE_CASE_     )
						lowerCAmelCase__      :      Tuple         =		torch.load(SCREAMING_SNAKE_CASE_       ,							map_location='cpu'     )['model']
			else:
						lowerCAmelCase__      :      Optional[Any]         =		torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE_     )['model']

			lowerCAmelCase__      :      Optional[Any]         =		convert_state_dict(SCREAMING_SNAKE_CASE_       ,							SCREAMING_SNAKE_CASE_     )

			lowerCAmelCase__      :      Optional[int]         =		XCLIPModel(SCREAMING_SNAKE_CASE_     )
			lowerCAmelCase__      ,				lowerCAmelCase__      :      str         =		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()

			lowerCAmelCase__      :      Optional[int]         =		336 if model_name == 'xclip-large-patch14-16-frames' else 224
			lowerCAmelCase__      :      List[str]         =		VideoMAEImageProcessor(size=SCREAMING_SNAKE_CASE_     )
			lowerCAmelCase__      :      Tuple         =		CLIPTokenizer.from_pretrained('openai/clip-vit-base-patch32'     )
			lowerCAmelCase__      :      List[Any]         =		CLIPTokenizerFast.from_pretrained('openai/clip-vit-base-patch32'     )
			lowerCAmelCase__      :      Optional[Any]         =		XCLIPProcessor(image_processor=SCREAMING_SNAKE_CASE_       ,							tokenizer=SCREAMING_SNAKE_CASE_     )

			lowerCAmelCase__      :      List[Any]         =		prepare_video(SCREAMING_SNAKE_CASE_     )
			lowerCAmelCase__      :      str         =		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():
						lowerCAmelCase__      :      Union[str, Any]         =		model(**SCREAMING_SNAKE_CASE_     )

			# Verify outputs
			lowerCAmelCase__      :      Optional[Any]         =		outputs.logits_per_video
			lowerCAmelCase__      :      Tuple         =		logits_per_video.softmax(dim=1     )
			print('Probs:'       ,							SCREAMING_SNAKE_CASE_     )
			# kinetics-400
			if model_name == "xclip-base-patch32":
						lowerCAmelCase__      :      str         =		torch.tensor([[0.0019, 0.9951, 0.0030]]     )
			elif model_name == "xclip-base-patch32-16-frames":
						lowerCAmelCase__      :      Dict         =		torch.tensor([[7.0999e-04, 9.9883e-01, 4.5580e-04]]     )
			elif model_name == "xclip-base-patch16":
						lowerCAmelCase__      :      int         =		torch.tensor([[0.0083, 0.9681, 0.0236]]     )
			elif model_name == "xclip-base-patch16-16-frames":
						lowerCAmelCase__      :      Any         =		torch.tensor([[7.6937e-04, 9.9728e-01, 1.9473e-03]]     )
			elif model_name == "xclip-large-patch14":
						lowerCAmelCase__      :      Any         =		torch.tensor([[0.0062, 0.9864, 0.0075]]     )
			elif model_name == "xclip-large-patch14-16-frames":
						lowerCAmelCase__      :      Union[str, Any]         =		torch.tensor([[3.3877e-04, 9.9937e-01, 2.8888e-04]]     )
			# kinetics-600
			elif model_name == "xclip-base-patch16-kinetics-600":
						lowerCAmelCase__      :      Optional[int]         =		torch.tensor([[0.0555, 0.8914, 0.0531]]     )
			elif model_name == "xclip-base-patch16-kinetics-600-16-frames":
						lowerCAmelCase__      :      int         =		torch.tensor([[3.8554e-04, 9.9929e-01, 3.2754e-04]]     )
			elif model_name == "xclip-large-patch14-kinetics-600":
						lowerCAmelCase__      :      Dict         =		torch.tensor([[0.0036, 0.9920, 0.0045]]     )
			# few shot
			elif model_name == "xclip-base-patch16-hmdb-2-shot":
						lowerCAmelCase__      :      Optional[Any]         =		torch.tensor([[7.1890e-06, 9.9994e-01, 5.6559e-05]]     )
			elif model_name == "xclip-base-patch16-hmdb-4-shot":
						lowerCAmelCase__      :      Tuple         =		torch.tensor([[1.0320e-05, 9.9993e-01, 6.2435e-05]]     )
			elif model_name == "xclip-base-patch16-hmdb-8-shot":
						lowerCAmelCase__      :      int         =		torch.tensor([[4.1377e-06, 9.9990e-01, 9.8386e-05]]     )
			elif model_name == "xclip-base-patch16-hmdb-16-shot":
						lowerCAmelCase__      :      Optional[Any]         =		torch.tensor([[4.1347e-05, 9.9962e-01, 3.3411e-04]]     )
			elif model_name == "xclip-base-patch16-ucf-2-shot":
						lowerCAmelCase__      :      str         =		torch.tensor([[8.5857e-05, 9.9928e-01, 6.3291e-04]]     )
			elif model_name == "xclip-base-patch16-ucf-4-shot":
						lowerCAmelCase__      :      Optional[Any]         =		torch.tensor([[8.5857e-05, 9.9928e-01, 6.3291e-04]]     )
			elif model_name == "xclip-base-patch16-ucf-8-shot":
						lowerCAmelCase__      :      int         =		torch.tensor([[0.0027, 0.9904, 0.0070]]     )
			elif model_name == "xclip-base-patch16-ucf-16-shot":
						lowerCAmelCase__      :      Union[str, Any]         =		torch.tensor([[9.8219e-04, 9.9593e-01, 3.0863e-03]]     )
			# zero shot
			elif model_name == "xclip-base-patch16-zero-shot":
						lowerCAmelCase__      :      List[Any]         =		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)