






'''simple docstring'''

import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import VivitConfig
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


if is_torch_available():
						import torch
						from torch import nn

						from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VivitForVideoClassification, VivitModel
						from transformers.models.vivit.modeling_vivit import VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from transformers import VivitImageProcessor






class 				__magic_name__  :







	"""simple docstring"""



	def __init__(				self	,   _lowercase	,   _lowercase=2	,   _lowercase=True	,   _lowercase=True	,   _lowercase=10	,   _lowercase=10	,   _lowercase=8	,   _lowercase=[2, 4, 4]	,   _lowercase=3	,   _lowercase=768	,   _lowercase=5	,   _lowercase=4	,   _lowercase=37	,   _lowercase="gelu_fast"	,   _lowercase=0.0	,   _lowercase=0.0	,   _lowercase=0.02	,   _lowercase=1E-0_6	,   _lowercase=True	,   _lowercase=None	,   )    ->	str:
							lowercase_   : Union[str, Any]   	=      parent
							lowercase_   : Dict   	=      batch_size
							lowercase_   : int   	=      is_training
							lowercase_   : Tuple   	=      use_labels
							lowercase_   : int   	=      num_labels
							lowercase_   : str   	=      image_size
							lowercase_   : int   	=      num_frames
							lowercase_   : Tuple   	=      tubelet_size
							lowercase_   : List[str]   	=      num_channels
							lowercase_   : Dict   	=      hidden_size
							lowercase_   : List[str]   	=      num_hidden_layers
							lowercase_   : str   	=      num_attention_heads
							lowercase_   : Union[str, Any]   	=      intermediate_size
							lowercase_   : Union[str, Any]   	=      hidden_act
							lowercase_   : Any   	=      hidden_dropout_prob
							lowercase_   : Tuple   	=      attention_probs_dropout_prob
							lowercase_   : str   	=      initializer_range
							lowercase_   : Tuple   	=      layer_norm_eps
							lowercase_   : str   	=      qkv_bias
							lowercase_   : int   	=      scope

							lowercase_   : str   	=      (
							    (self.image_size // self.tubelet_size[2])
							    * (self.image_size // self.tubelet_size[1])
							    * (self.num_frames // self.tubelet_size[0])
							) + 1  # CLS token
	def 							lowerCamelCase__		(				self							)    ->	str:
							lowercase_   : str   	=      floats_tensor(
							    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]							)

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

							lowercase_   : Any   	=      self.get_config()

							return config, pixel_values, labels
	def 							lowerCamelCase__		(				self							)    ->	List[Any]:
							lowercase_   : Dict   	=      VivitConfig(
							    num_frames=self.num_frames	,   image_size=self.image_size	,   tubelet_size=self.tubelet_size	,   num_channels=self.num_channels	,   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	,   layer_norm_eps=self.layer_norm_eps	,   qkv_bias=self.qkv_bias	,   )
							lowercase_   : Dict   	=      self.num_labels
							return config
	def 							lowerCamelCase__		(				self	,   _lowercase	,   _lowercase	,   _lowercase							)    ->	str:
							lowercase_   : List[str]   	=      VivitModel(config=_lowercase							)
							model.to(_lowercase							)
							model.eval()
							lowercase_   : List[Any]   	=      model(_lowercase							)
							self.parent.assertEqual(result.last_hidden_state.shape	,   (self.batch_size, self.seq_length, self.hidden_size)							)
	def 							lowerCamelCase__		(				self	,   _lowercase	,   _lowercase	,   _lowercase							)    ->	List[str]:
							lowercase_   : Any   	=      VivitForVideoClassification(_lowercase							)
							model.to(_lowercase							)
							model.eval()

							lowercase_   : Union[str, Any]   	=      model(_lowercase							)

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







	def 							lowerCamelCase__		(				self							)    ->	List[Any]:
							lowercase_   : Optional[int]   	=      self.prepare_config_and_inputs()
							lowercase_	,   lowercase_	,   lowercase_   : Any   	=      config_and_inputs
							lowercase_   : Any   	=      {'pixel_values': pixel_values}
							return config, inputs_dict






@require_torch
class 				__magic_name__  (						UpperCAmelCase_,    unittest.TestCase					):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_       :   Optional[int]   =	(VivitModel, VivitForVideoClassification) if is_torch_available() else ()

	SCREAMING_SNAKE_CASE_       :   str   =	False
	SCREAMING_SNAKE_CASE_       :   Tuple   =	False
	SCREAMING_SNAKE_CASE_       :   List[Any]   =	False
	SCREAMING_SNAKE_CASE_       :   List[Any]   =	False
	def 							lowerCamelCase__		(				self							)    ->	Any:
							lowercase_   : List[str]   	=      VivitModelTester(self							)
							lowercase_   : Optional[int]   	=      ConfigTester(self	,   config_class=_lowercase	,   has_text_modality=_lowercase	,   hidden_size=37							)
	def 							lowerCamelCase__		(				self	,   _lowercase	,   _lowercase	,   _lowercase=False							)    ->	Tuple:
							lowercase_   : str   	=      copy.deepcopy(_lowercase							)

							if return_labels:
													if model_class in get_values(_lowercase							):
																			lowercase_   : Tuple   	=      torch.zeros(
																			    self.model_tester.batch_size	,   dtype=torch.long	,   device=_lowercase							)

							return inputs_dict
	def 							lowerCamelCase__		(				self							)    ->	Union[str, Any]:
							self.config_tester.run_common_tests()
	@unittest.skip(reason='Vivit does not use inputs_embeds'							)
	def 							lowerCamelCase__		(				self							)    ->	List[str]:
							pass
	def 							lowerCamelCase__		(				self							)    ->	Tuple:
							lowercase_	,   lowercase_   : Optional[int]   	=      self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													lowercase_   : Optional[int]   	=      model_class(_lowercase							)
													self.assertIsInstance(model.get_input_embeddings()	,   (nn.Module)							)
													lowercase_   : List[str]   	=      model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(_lowercase	,   nn.Linear							)							)
	def 							lowerCamelCase__		(				self							)    ->	int:
							lowercase_	,   lowercase_   : Tuple   	=      self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													lowercase_   : Any   	=      model_class(_lowercase							)
													lowercase_   : Dict   	=      inspect.signature(model.forward							)
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													lowercase_   : str   	=      [*signature.parameters.keys()]

													lowercase_   : Any   	=      ['pixel_values', 'head_mask']
													self.assertListEqual(arg_names[:2]	,   _lowercase							)
	def 							lowerCamelCase__		(				self							)    ->	List[Any]:
							lowercase_   : Any   	=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_lowercase							)
	def 							lowerCamelCase__		(				self							)    ->	int:
							lowercase_   : int   	=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_video_classification(*_lowercase							)
	@slow
	def 							lowerCamelCase__		(				self							)    ->	Union[str, Any]:
							for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													lowercase_   : Optional[Any]   	=      VivitModel.from_pretrained(_lowercase							)
													self.assertIsNotNone(_lowercase							)
	def 							lowerCamelCase__		(				self							)    ->	Optional[int]:
							lowercase_	,   lowercase_   : List[str]   	=      self.model_tester.prepare_config_and_inputs_for_common()
							lowercase_   : Tuple   	=      True

							for model_class in self.all_model_classes:
													lowercase_   : str   	=      self.model_tester.seq_length

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

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

													self.assertListEqual(
													    list(attentions[0].shape[-3:]							)	,   [self.model_tester.num_attention_heads, seq_len, seq_len]	,   )
													lowercase_   : List[Any]   	=      len(_lowercase							)

													# Check attention is always last and order is fine
													lowercase_   : Dict   	=      True
													lowercase_   : Optional[Any]   	=      True
													lowercase_   : Optional[int]   	=      model_class(_lowercase							)
													model.to(_lowercase							)
													model.eval()
													with torch.no_grad():
																			lowercase_   : Tuple   	=      model(**self._prepare_for_class(_lowercase	,   _lowercase							)							)

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

													lowercase_   : Optional[int]   	=      outputs.attentions

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

													self.assertListEqual(
													    list(self_attentions[0].shape[-3:]							)	,   [self.model_tester.num_attention_heads, seq_len, seq_len]	,   )
	def 							lowerCamelCase__		(				self							)    ->	Any:
							def check_hidden_states_output(_lowercase	,   _lowercase	,   _lowercase							):
													lowercase_   : List[Any]   	=      model_class(_lowercase							)
													model.to(_lowercase							)
													model.eval()

													with torch.no_grad():
																			lowercase_   : str   	=      model(**self._prepare_for_class(_lowercase	,   _lowercase							)							)

													lowercase_   : int   	=      outputs.hidden_states
													lowercase_   : Dict   	=      self.model_tester.num_hidden_layers + 1
													self.assertEqual(len(_lowercase							)	,   _lowercase							)

													lowercase_   : Optional[Any]   	=      self.model_tester.seq_length

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

							lowercase_	,   lowercase_   : List[str]   	=      self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													lowercase_   : Any   	=      True
													check_hidden_states_output(_lowercase	,   _lowercase	,   _lowercase							)

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													lowercase_   : Optional[int]   	=      True

													check_hidden_states_output(_lowercase	,   _lowercase	,   _lowercase							)







	@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'							)
	def 							lowerCamelCase__		(				self							)    ->	int:
							pass






def 						_UpperCAmelCase     (	)      ->      List[Any]:





						"""simple docstring"""
						lowercase_   : int   	=      hf_hub_download(
						    repo_id='hf-internal-testing/spaghetti-video'    ,      filename='eating_spaghetti_32_frames.npy'    ,      repo_type='dataset'				)
						lowercase_   : Any   	=      np.load(a				)
						return list(a				)






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







	"""simple docstring"""



	@cached_property
	def 							lowerCamelCase__		(				self							)    ->	Tuple:
							return VivitImageProcessor() if is_vision_available() else None







	@slow
	def 							lowerCamelCase__		(				self							)    ->	Dict:
							lowercase_   : Any   	=      VivitForVideoClassification.from_pretrained('google/vivit-b-16x2-kinetics400'							).to(_lowercase							)

							lowercase_   : Dict   	=      self.default_image_processor
							lowercase_   : Optional[Any]   	=      prepare_video()
							lowercase_   : List[str]   	=      image_processor(_lowercase	,   return_tensors='pt'							).to(_lowercase							)

							# forward pass
							with torch.no_grad():
													lowercase_   : Tuple   	=      model(**_lowercase							)

							# verify the logits
							lowercase_   : List[str]   	=      torch.Size((1, 400)							)
							self.assertEqual(outputs.logits.shape	,   _lowercase							)

							# taken from original model
							lowercase_   : Any   	=      torch.tensor([-1.05_43, 2.07_64, -0.21_04, 0.44_39, -0.96_58]							).to(_lowercase							)

							self.assertTrue(torch.allclose(outputs.logits[0, :5]	,   _lowercase	,   atol=1E-4							)							)








'''simple docstring'''

import unittest

from transformers import ErnieMTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


A:   Dict						=					get_tests_dir("fixtures/spiece.model")






@require_sentencepiece
@require_tokenizers
class 				__magic_name__  (						UpperCAmelCase_,    unittest.TestCase					):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_       :   int   =	ErnieMTokenizer
	SCREAMING_SNAKE_CASE_       :   Optional[Any]   =	False
	SCREAMING_SNAKE_CASE_       :   Dict   =	True
	SCREAMING_SNAKE_CASE_       :   Union[str, Any]   =	False
	SCREAMING_SNAKE_CASE_       :   Dict   =	False
	def 							lowerCamelCase__		(				self							)    ->	Any:
							super().setUp()

							# We have a SentencePiece fixture for testing
							lowercase_   : List[Any]   	=      ErnieMTokenizer(_lowercase	,   unk_token='<unk>'	,   pad_token='<pad>'							)
							tokenizer.save_pretrained(self.tmpdirname							)
	def 							lowerCamelCase__		(				self	,   _lowercase							)    ->	Optional[int]:
							lowercase_   : Optional[int]   	=      'this is a test'
							lowercase_   : Dict   	=      'this is a test'
							return input_text, output_text
	def 							lowerCamelCase__		(				self							)    ->	Any:
							lowercase_   : str   	=      '<pad>'
							lowercase_   : Optional[Any]   	=      0

							self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowercase							)	,   _lowercase							)
							self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowercase							)	,   _lowercase							)
	def 							lowerCamelCase__		(				self							)    ->	Dict:
							lowercase_   : List[str]   	=      list(self.get_tokenizer().get_vocab().keys()							)

							self.assertEqual(vocab_keys[0]	,   '<pad>'							)
							self.assertEqual(vocab_keys[1]	,   '<unk>'							)
							self.assertEqual(vocab_keys[-1]	,   '▁eloquent'							)
							self.assertEqual(len(_lowercase							)	,   3_0000							)
	def 							lowerCamelCase__		(				self							)    ->	Dict:
							self.assertEqual(self.get_tokenizer().vocab_size	,   3_0000							)
	def 							lowerCamelCase__		(				self							)    ->	List[str]:
							if not self.test_rust_tokenizer:
													return

							lowercase_   : Optional[int]   	=      self.get_tokenizer()
							lowercase_   : Optional[Any]   	=      self.get_rust_tokenizer()

							lowercase_   : Tuple   	=      'I was born in 92000, and this is falsé.'

							lowercase_   : Union[str, Any]   	=      tokenizer.tokenize(_lowercase							)
							lowercase_   : List[Any]   	=      rust_tokenizer.tokenize(_lowercase							)
							self.assertListEqual(_lowercase	,   _lowercase							)

							lowercase_   : Any   	=      tokenizer.encode(_lowercase	,   add_special_tokens=_lowercase							)
							lowercase_   : List[Any]   	=      rust_tokenizer.encode(_lowercase	,   add_special_tokens=_lowercase							)
							self.assertListEqual(_lowercase	,   _lowercase							)

							lowercase_   : Union[str, Any]   	=      self.get_rust_tokenizer()
							lowercase_   : Optional[Any]   	=      tokenizer.encode(_lowercase							)
							lowercase_   : str   	=      rust_tokenizer.encode(_lowercase							)
							self.assertListEqual(_lowercase	,   _lowercase							)
	def 							lowerCamelCase__		(				self							)    ->	Tuple:
							lowercase_   : Optional[int]   	=      ErnieMTokenizer(_lowercase	,   do_lower_case=_lowercase	,   unk_token='<unk>'	,   pad_token='<pad>'							)

							lowercase_   : Tuple   	=      tokenizer.tokenize('This is a test'							)
							self.assertListEqual(_lowercase	,   ['▁this', '▁is', '▁a', '▁test']							)

							self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowercase							)	,   [48, 25, 21, 1289]							)

							lowercase_   : Union[str, Any]   	=      tokenizer.tokenize('I was born in 92000, and this is falsé.'							)
							# ErnieMTokenizer(paddlenlp implementation) outputs '9' instead of '_9' so to mimic that '_9' is changed to '9'
							self.assertListEqual(
							    _lowercase	,   ['▁i', '▁was', '▁born', '▁in', '9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', 'é', '.']							)
							lowercase_   : int   	=      tokenizer.convert_tokens_to_ids(_lowercase							)
							self.assertListEqual(_lowercase	,   [31, 23, 386, 19, 518, 3050, 15, 17, 48, 25, 8256, 18, 1, 9]							)

							lowercase_   : Optional[int]   	=      tokenizer.convert_ids_to_tokens(_lowercase							)
							self.assertListEqual(
							    _lowercase	,   ['▁i', '▁was', '▁born', '▁in', '9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.']	,   )
	def 							lowerCamelCase__		(				self							)    ->	Any:
							lowercase_   : Tuple   	=      ErnieMTokenizer(_lowercase	,   unk_token='<unk>'	,   pad_token='<pad>'							)

							lowercase_   : List[Any]   	=      tokenizer.encode('sequence builders'							)
							lowercase_   : Optional[int]   	=      tokenizer.encode('multi-sequence build'							)

							lowercase_   : Union[str, Any]   	=      tokenizer.build_inputs_with_special_tokens(_lowercase							)
							lowercase_   : Optional[int]   	=      tokenizer.build_inputs_with_special_tokens(_lowercase	,   _lowercase							)

							assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
							assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + [
							    tokenizer.sep_token_id
							] + text_a + [tokenizer.sep_token_id]







	@slow
	def 							lowerCamelCase__		(				self							)    ->	Tuple:
							# fmt: off
							lowercase_   : Dict   	=      {'input_ids': [[0, 1_1062, 8_2772, 7, 15, 8_2772, 538, 5_1529, 237, 1_7198, 1290, 206, 9, 21_5175, 1314, 136, 1_7198, 1290, 206, 9, 5_6359, 42, 12_2009, 9, 1_6466, 16, 8_7344, 4537, 9, 4717, 7_8381, 6, 15_9958, 7, 15, 2_4480, 618, 4, 527, 2_2693, 9, 304, 4, 2777, 2_4480, 9874, 4, 4_3523, 594, 4, 803, 1_8392, 3_3189, 18, 4, 4_3523, 2_4447, 5, 5, 5, 16, 100, 2_4955, 8_3658, 9626, 14_4057, 15, 839, 2_2335, 16, 136, 2_4955, 8_3658, 8_3479, 15, 3_9102, 724, 16, 678, 645, 6460, 1328, 4589, 42, 12_2009, 11_5774, 23, 3559, 1328, 4_6876, 7, 136, 5_3894, 1940, 4_2227, 4_1159, 1_7721, 823, 425, 4, 2_7512, 9_8722, 206, 136, 5531, 4970, 919, 1_7336, 5, 2], [0, 2_0080, 618, 83, 8_2775, 47, 479, 9, 1517, 73, 5_3894, 333, 8_0581, 11_0117, 1_8811, 5256, 1295, 51, 15_2526, 297, 7986, 390, 12_4416, 538, 3_5431, 214, 98, 1_5044, 2_5737, 136, 7108, 4_3701, 23, 756, 13_5355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 581, 6_3773, 11_9455, 6, 14_7797, 8_8203, 7, 645, 70, 21, 3285, 1_0269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}
							# fmt: on

							self.tokenizer_integration_test_util(
							    expected_encoding=_lowercase	,   model_name='susnato/ernie-m-base_pytorch'	,   sequences=[
							        'Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides '
							        'general-purpose architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet...) for Natural '
							        'Language Understanding (NLU) and Natural Language Generation (NLG) with over32+ pretrained '
							        'models in100+ languages and deep interoperability between Jax, PyTorch and TensorFlow.',
							        'BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly '
							        'conditioning on both left and right context in all layers.',
							        'The quick brown fox jumps over the lazy dog.',
							    ]	,   )
