

import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

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

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


if is_torch_available():
		import torch
		from torch import nn

		from transformers import (
		    MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
		    VideoMAEForPreTraining,
		    VideoMAEForVideoClassification,
		    VideoMAEModel,
		)
		from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from transformers import VideoMAEImageProcessor



class lowerCamelCase			:



			'''simple docstring'''






			def __init__(				self	:						Any		,      lowerCAmelCase_	:						List[str]		,      lowerCAmelCase_	:						Optional[Any]=13		,      lowerCAmelCase_	:						str=10		,      lowerCAmelCase_	:						Dict=3		,      lowerCAmelCase_	:						Any=2		,      lowerCAmelCase_	:						str=2		,      lowerCAmelCase_	:						Any=2		,      lowerCAmelCase_	:						Union[str, Any]=True		,      lowerCAmelCase_	:						Any=True		,      lowerCAmelCase_	:						Dict=32		,      lowerCAmelCase_	:						Optional[int]=5		,      lowerCAmelCase_	:						Tuple=4		,      lowerCAmelCase_	:						Optional[int]=37		,      lowerCAmelCase_	:						Dict="gelu"		,      lowerCAmelCase_	:						Optional[int]=0.1		,      lowerCAmelCase_	:						Dict=0.1		,      lowerCAmelCase_	:						Union[str, Any]=10		,      lowerCAmelCase_	:						List[Any]=0.02		,      lowerCAmelCase_	:						str=0.9		,      lowerCAmelCase_	:						Any=None		,      )      ->		Optional[int]:





									'''simple docstring'''
									A__					:       Dict     =parent
									A__					:       Optional[Any]     =batch_size
									A__					:       Dict     =image_size
									A__					:       Union[str, Any]     =num_channels
									A__					:       Optional[Any]     =patch_size
									A__					:       List[Any]     =tubelet_size
									A__					:       List[Any]     =num_frames
									A__					:       List[str]     =is_training
									A__					:       Any     =use_labels
									A__					:       Tuple     =hidden_size
									A__					:       Tuple     =num_hidden_layers
									A__					:       List[Any]     =num_attention_heads
									A__					:       int     =intermediate_size
									A__					:       Optional[int]     =hidden_act
									A__					:       Any     =hidden_dropout_prob
									A__					:       Union[str, Any]     =attention_probs_dropout_prob
									A__					:       str     =type_sequence_label_size
									A__					:       List[Any]     =initializer_range
									A__					:       Optional[Any]     =mask_ratio
									A__					:       Optional[int]     =scope

									# in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame
									A__					:       Optional[Any]     =(image_size // patch_size) ** 2
									A__					:       Optional[Any]     =(num_frames // tubelet_size) * self.num_patches_per_frame

									# use this variable to define bool_masked_pos
									A__					:       Dict     =int(mask_ratio * self.seq_length			)


			def lowercase__						(				self	:						Optional[Any]			)      ->		Any:





									'''simple docstring'''
									A__					:       Optional[int]     =floats_tensor(
									    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]			)

									A__					:       Union[str, Any]     =None
									if self.use_labels:
															A__					:       Union[str, Any]     =ids_tensor([self.batch_size]		,      self.type_sequence_label_size			)

									A__					:       Any     =self.get_config()

									return config, pixel_values, labels


			def lowercase__						(				self	:						Optional[int]			)      ->		List[str]:





									'''simple docstring'''
									return VideoMAEConfig(
									    image_size=self.image_size		,      patch_size=self.patch_size		,      num_channels=self.num_channels		,      num_frames=self.num_frames		,      tubelet_size=self.tubelet_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		,      is_decoder=lowerCAmelCase_		,      initializer_range=self.initializer_range		,      )


			def lowercase__						(				self	:						Any		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						Tuple			)      ->		int:





									'''simple docstring'''
									A__					:       int     =VideoMAEModel(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       Optional[Any]     =model(lowerCAmelCase_			)
									self.parent.assertEqual(result.last_hidden_state.shape		,      (self.batch_size, self.seq_length, self.hidden_size)			)


			def lowercase__						(				self	:						List[str]		,      lowerCAmelCase_	:						Optional[Any]		,      lowerCAmelCase_	:						Union[str, Any]		,      lowerCAmelCase_	:						List[Any]			)      ->		Union[str, Any]:





									'''simple docstring'''
									A__					:       List[Any]     =VideoMAEForPreTraining(lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									# important: each video needs to have the same number of masked patches
									# hence we define a single mask, which we then repeat for each example in the batch
									A__					:       Optional[Any]     =torch.ones((self.num_masks,)			)
									A__					:       Optional[Any]     =torch.cat([mask, torch.zeros(self.seq_length - mask.size(0			)			)]			)
									A__					:       Dict     =mask.expand(self.batch_size		,      -1			).bool()

									A__					:       Any     =model(lowerCAmelCase_		,      lowerCAmelCase_			)
									# model only returns predictions for masked patches
									A__					:       List[Any]     =mask.sum().item()
									A__					:       List[str]     =3 * self.tubelet_size * self.patch_size**2
									self.parent.assertEqual(result.logits.shape		,      (self.batch_size, num_masked_patches, decoder_num_labels)			)



			def lowercase__						(				self	:						Union[str, Any]			)      ->		Any:





									'''simple docstring'''
									A__					:       int     =self.prepare_config_and_inputs()
									A__   ,						A__   ,						A__					:       Optional[Any]     =config_and_inputs
									A__					:       List[Any]     ={"""pixel_values""": pixel_values}
									return config, inputs_dict



@require_torch
class lowerCamelCase			(  _lowerCamelCase	,						_lowerCamelCase	,						unittest.TestCase						):



			'''simple docstring'''






			__snake_case        =	(
			    (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else ()
			)
			__snake_case        =	(
			    {'feature-extraction': VideoMAEModel, 'video-classification': VideoMAEForVideoClassification}
			    if is_torch_available()
			    else {}
			)

			__snake_case        =	False
			__snake_case        =	False
			__snake_case        =	False
			__snake_case        =	False


			def lowercase__						(				self	:						List[str]			)      ->		Tuple:





									'''simple docstring'''
									A__					:       int     =VideoMAEModelTester(self			)
									A__					:       Optional[Any]     =ConfigTester(self		,      config_class=lowerCAmelCase_		,      has_text_modality=lowerCAmelCase_		,      hidden_size=37			)


			def lowercase__						(				self	:						str		,      lowerCAmelCase_	:						Optional[int]		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						Union[str, Any]=False			)      ->		Optional[int]:





									'''simple docstring'''
									A__					:       Optional[int]     =copy.deepcopy(lowerCAmelCase_			)

									if model_class == VideoMAEForPreTraining:
															# important: each video needs to have the same number of masked patches
															# hence we define a single mask, which we then repeat for each example in the batch
															A__					:       Optional[Any]     =torch.ones((self.model_tester.num_masks,)			)
															A__					:       Any     =torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0			)			)]			)
															A__					:       str     =mask.expand(self.model_tester.batch_size		,      -1			).bool()
															A__					:       int     =bool_masked_pos.to(lowerCAmelCase_			)

									if return_labels:
															if model_class in [
															    *get_values(lowerCAmelCase_			),
															]:
																					A__					:       Any     =torch.zeros(
																					    self.model_tester.batch_size		,      dtype=torch.long		,      device=lowerCAmelCase_			)

									return inputs_dict


			def lowercase__						(				self	:						List[str]			)      ->		Optional[Any]:





									'''simple docstring'''
									self.config_tester.run_common_tests()


			@unittest.skip(reason="""VideoMAE does not use inputs_embeds"""			)
			def lowercase__						(				self	:						Dict			)      ->		Any:





									'''simple docstring'''
									pass


			def lowercase__						(				self	:						Tuple			)      ->		Union[str, Any]:





									'''simple docstring'''
									A__   ,						A__					:       str     =self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															A__					:       List[str]     =model_class(lowerCAmelCase_			)
															self.assertIsInstance(model.get_input_embeddings()		,      (nn.Module)			)
															A__					:       Tuple     =model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(lowerCAmelCase_		,      nn.Linear			)			)


			def lowercase__						(				self	:						List[Any]			)      ->		List[Any]:





									'''simple docstring'''
									A__   ,						A__					:       Optional[int]     =self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															A__					:       Tuple     =model_class(lowerCAmelCase_			)
															A__					:       Optional[Any]     =inspect.signature(model.forward			)
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															A__					:       Tuple     =[*signature.parameters.keys()]

															A__					:       Union[str, Any]     =["""pixel_values"""]
															self.assertListEqual(arg_names[:1]		,      lowerCAmelCase_			)


			def lowercase__						(				self	:						List[str]			)      ->		str:





									'''simple docstring'''
									A__					:       Dict     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowerCAmelCase_			)


			def lowercase__						(				self	:						Union[str, Any]			)      ->		Optional[Any]:





									'''simple docstring'''
									A__					:       int     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_pretraining(*lowerCAmelCase_			)


			@slow
			def lowercase__						(				self	:						Tuple			)      ->		str:





									'''simple docstring'''


									for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															A__					:       List[str]     =VideoMAEModel.from_pretrained(lowerCAmelCase_			)
															self.assertIsNotNone(lowerCAmelCase_			)


			def lowercase__						(				self	:						Tuple			)      ->		int:





									'''simple docstring'''


									if not self.has_attentions:
															pass

									else:
															A__   ,						A__					:       Optional[Any]     =self.model_tester.prepare_config_and_inputs_for_common()
															A__					:       Optional[int]     =True

															for model_class in self.all_model_classes:
																					A__					:       Optional[int]     =self.model_tester.seq_length - self.model_tester.num_masks
																					A__					:       Tuple     =(
																					    num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
																					)

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

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

																					self.assertListEqual(
																					    list(attentions[0].shape[-3:]			)		,      [self.model_tester.num_attention_heads, seq_len, seq_len]		,      )
																					A__					:       Union[str, Any]     =len(lowerCAmelCase_			)

																					# Check attention is always last and order is fine
																					A__					:       Any     =True
																					A__					:       Dict     =True
																					A__					:       Union[str, Any]     =model_class(lowerCAmelCase_			)
																					model.to(lowerCAmelCase_			)
																					model.eval()
																					with torch.no_grad():
																											A__					:       int     =model(**self._prepare_for_class(lowerCAmelCase_		,      lowerCAmelCase_			)			)

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

																					A__					:       Union[str, Any]     =outputs.attentions

																					self.assertEqual(len(lowerCAmelCase_			)		,      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 lowercase__						(				self	:						Optional[int]			)      ->		List[Any]:





									'''simple docstring'''


									def check_hidden_states_output(lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						Optional[Any]		,      lowerCAmelCase_	:						List[str]			):
															A__					:       str     =model_class(lowerCAmelCase_			)
															model.to(lowerCAmelCase_			)
															model.eval()

															with torch.no_grad():
																					A__					:       Optional[Any]     =model(**self._prepare_for_class(lowerCAmelCase_		,      lowerCAmelCase_			)			)

															A__					:       Optional[int]     =outputs.hidden_states
															A__					:       int     =self.model_tester.num_hidden_layers + 1
															self.assertEqual(len(lowerCAmelCase_			)		,      lowerCAmelCase_			)

															A__					:       List[Any]     =self.model_tester.seq_length - self.model_tester.num_masks
															A__					:       Any     =num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length

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

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

									for model_class in self.all_model_classes:
															A__					:       Any     =True
															check_hidden_states_output(lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_			)

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

															check_hidden_states_output(lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_			)



			@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""			)
			def lowercase__						(				self	:						Optional[Any]			)      ->		Optional[Any]:





									'''simple docstring'''
									pass


def 						__lowerCamelCase	(       )	->							Tuple:






						"""simple docstring"""





						A__					:       Optional[Any]     =hf_hub_download(
						    repo_id="""hf-internal-testing/spaghetti-video""",		filename="""eating_spaghetti.npy""",		repo_type="""dataset"""	)
						A__					:       Any     =np.load(UpperCAmelCase_	)
						return list(UpperCAmelCase_	)



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



			'''simple docstring'''






			@cached_property
			def lowercase__						(				self	:						Tuple			)      ->		Union[str, Any]:





									'''simple docstring'''
									return (
									    VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]		,      image_std=[0.5, 0.5, 0.5]			)
									    if is_vision_available()
									    else None
									)


			@slow
			def lowercase__						(				self	:						Dict			)      ->		str:





									'''simple docstring'''
									A__					:       Union[str, Any]     =VideoMAEForVideoClassification.from_pretrained("""MCG-NJU/videomae-base-finetuned-kinetics"""			).to(
									    lowerCAmelCase_			)

									A__					:       Any     =self.default_image_processor
									A__					:       Optional[Any]     =prepare_video()
									A__					:       Tuple     =image_processor(lowerCAmelCase_		,      return_tensors="""pt"""			).to(lowerCAmelCase_			)

									# forward pass
									with torch.no_grad():
															A__					:       Union[str, Any]     =model(**lowerCAmelCase_			)

									# verify the logits
									A__					:       Any     =torch.Size((1, 4_00)			)
									self.assertEqual(outputs.logits.shape		,      lowerCAmelCase_			)

									A__					:       List[str]     =torch.tensor([0.3669, -0.0688, -0.2421]			).to(lowerCAmelCase_			)

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



			@slow
			def lowercase__						(				self	:						Optional[int]			)      ->		int:





									'''simple docstring'''
									A__					:       List[str]     =VideoMAEForPreTraining.from_pretrained("""MCG-NJU/videomae-base-short"""			).to(lowerCAmelCase_			)

									A__					:       Any     =self.default_image_processor
									A__					:       str     =prepare_video()
									A__					:       Dict     =image_processor(lowerCAmelCase_		,      return_tensors="""pt"""			).to(lowerCAmelCase_			)

									# add boolean mask, indicating which patches to mask
									A__					:       List[str]     =hf_hub_download(repo_id="""hf-internal-testing/bool-masked-pos"""		,      filename="""bool_masked_pos.pt"""			)
									A__					:       List[str]     =torch.load(lowerCAmelCase_			)

									# forward pass
									with torch.no_grad():
															A__					:       Dict     =model(**lowerCAmelCase_			)

									# verify the logits
									A__					:       Tuple     =torch.Size([1, 14_08, 15_36]			)
									A__					:       Optional[Any]     =torch.tensor(
									    [[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]]		,      device=lowerCAmelCase_			)
									self.assertEqual(outputs.logits.shape		,      lowerCAmelCase_			)
									self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]		,      lowerCAmelCase_		,      atol=1e-4			)			)

									# verify the loss (`config.norm_pix_loss` = `True`)
									A__					:       int     =torch.tensor([0.5142]		,      device=lowerCAmelCase_			)
									self.assertTrue(torch.allclose(outputs.loss		,      lowerCAmelCase_		,      atol=1e-4			)			)

									# verify the loss (`config.norm_pix_loss` = `False`)
									A__					:       Dict     =VideoMAEForPreTraining.from_pretrained("""MCG-NJU/videomae-base-short"""		,      norm_pix_loss=lowerCAmelCase_			).to(
									    lowerCAmelCase_			)

									with torch.no_grad():
															A__					:       Optional[Any]     =model(**lowerCAmelCase_			)

									A__					:       Any     =torch.tensor(torch.tensor([0.6469]			)		,      device=lowerCAmelCase_			)
									self.assertTrue(torch.allclose(outputs.loss		,      lowerCAmelCase_		,      atol=1e-4			)			)




'''simple docstring'''



from typing import Dict

from .base import GenericTensor, Pipeline



class lowerCamelCase			(  lowercase_						):



			'''simple docstring'''






			def lowercase__						(				self	:						List[str]		,      lowerCAmelCase_	:						Tuple=None		,      lowerCAmelCase_	:						Dict=None		,      lowerCAmelCase_	:						Any=None		,      **lowerCAmelCase_	:						Union[str, Any]			)      ->		Optional[Any]:





									'''simple docstring'''
									if tokenize_kwargs is None:
															A__					:       List[Any]     ={}

									if truncation is not None:
															if "truncation" in tokenize_kwargs:
																					raise ValueError(
																					    """truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)"""			)
															A__					:       str     =truncation

									A__					:       Optional[int]     =tokenize_kwargs

									A__					:       List[Any]     ={}
									if return_tensors is not None:
															A__					:       Any     =return_tensors

									return preprocess_params, {}, postprocess_params


			def lowercase__						(				self	:						int		,      lowerCAmelCase_	:						Union[str, Any]		,      **lowerCAmelCase_	:						Dict			)      ->		Dict[str, GenericTensor]:





									'''simple docstring'''
									A__					:       List[str]     =self.framework
									A__					:       Union[str, Any]     =self.tokenizer(lowerCAmelCase_		,      return_tensors=lowerCAmelCase_		,      **lowerCAmelCase_			)
									return model_inputs


			def lowercase__						(				self	:						Optional[int]		,      lowerCAmelCase_	:						Dict			)      ->		Optional[Any]:





									'''simple docstring'''
									A__					:       Union[str, Any]     =self.model(**lowerCAmelCase_			)
									return model_outputs


			def lowercase__						(				self	:						Tuple		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						Any=False			)      ->		List[Any]:





									'''simple docstring'''
									# [0] is the first available tensor, logits or last_hidden_state.
									if return_tensors:
															return model_outputs[0]
									if self.framework == "pt":
															return model_outputs[0].tolist()
									elif self.framework == "tf":
															return model_outputs[0].numpy().tolist()



			def __call__(				self	:						int		,      *lowerCAmelCase_	:						Any		,      **lowerCAmelCase_	:						Union[str, Any]			)      ->		List[str]:





									'''simple docstring'''
									return super().__call__(*lowerCAmelCase_		,      **lowerCAmelCase_			)

