



'''simple docstring'''




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 			UpperCamelCase_ :





	def __init__(  self		,		A		,		A=13		,		A=10		,		A=3		,		A=2		,		A=2		,		A=2		,		A=True		,		A=True		,		A=32		,		A=5		,		A=4		,		A=37		,		A="gelu"		,		A=0.1		,		A=0.1		,		A=10		,		A=0.0_2		,		A=0.9		,		A=None		,		)			->			Optional[Any]:
								UpperCAmelCase     :		str							     =		parent
								UpperCAmelCase     :		Optional[int]							     =		batch_size
								UpperCAmelCase     :		List[Any]							     =		image_size
								UpperCAmelCase     :		Optional[int]							     =		num_channels
								UpperCAmelCase     :		List[Any]							     =		patch_size
								UpperCAmelCase     :		Optional[Any]							     =		tubelet_size
								UpperCAmelCase     :		Dict							     =		num_frames
								UpperCAmelCase     :		Optional[int]							     =		is_training
								UpperCAmelCase     :		Dict							     =		use_labels
								UpperCAmelCase     :		Optional[int]							     =		hidden_size
								UpperCAmelCase     :		Any							     =		num_hidden_layers
								UpperCAmelCase     :		Optional[int]							     =		num_attention_heads
								UpperCAmelCase     :		Optional[Any]							     =		intermediate_size
								UpperCAmelCase     :		List[str]							     =		hidden_act
								UpperCAmelCase     :		int							     =		hidden_dropout_prob
								UpperCAmelCase     :		List[Any]							     =		attention_probs_dropout_prob
								UpperCAmelCase     :		Dict							     =		type_sequence_label_size
								UpperCAmelCase     :		Dict							     =		initializer_range
								UpperCAmelCase     :		Optional[Any]							     =		mask_ratio
								UpperCAmelCase     :		Union[str, Any]							     =		scope

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

								# use this variable to define bool_masked_pos
								UpperCAmelCase     :		Optional[Any]							     =		int(mask_ratio * self.seq_length    )





	def  _lowercase(  self    )			->			List[Any]:
								UpperCAmelCase     :		Tuple							     =		floats_tensor(
								    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]    )

								UpperCAmelCase     :		Dict							     =		None
								if self.use_labels:
															UpperCAmelCase     :		int							     =		ids_tensor([self.batch_size]		,		self.type_sequence_label_size    )

								UpperCAmelCase     :		List[Any]							     =		self.get_config()

								return config, pixel_values, labels





	def  _lowercase(  self    )			->			Optional[Any]:
								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=A		,		initializer_range=self.initializer_range		,		)





	def  _lowercase(  self		,		A		,		A		,		A    )			->			Optional[Any]:
								UpperCAmelCase     :		str							     =		VideoMAEModel(config=A    )
								model.to(A    )
								model.eval()
								UpperCAmelCase     :		Union[str, Any]							     =		model(A    )
								self.parent.assertEqual(result.last_hidden_state.shape		,		(self.batch_size, self.seq_length, self.hidden_size)    )





	def  _lowercase(  self		,		A		,		A		,		A    )			->			Optional[int]:
								UpperCAmelCase     :		List[str]							     =		VideoMAEForPreTraining(A    )
								model.to(A    )
								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
								UpperCAmelCase     :		int							     =		torch.ones((self.num_masks,)    )
								UpperCAmelCase     :		Tuple							     =		torch.cat([mask, torch.zeros(self.seq_length - mask.size(0    )    )]    )
								UpperCAmelCase     :		List[Any]							     =		mask.expand(self.batch_size		,		-1    ).bool()

								UpperCAmelCase     :		Optional[Any]							     =		model(A		,		A    )
								# model only returns predictions for masked patches
								UpperCAmelCase     :		str							     =		mask.sum().item()
								UpperCAmelCase     :		Tuple							     =		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    )			->			Optional[int]:
								UpperCAmelCase     :		Optional[Any]							     =		self.prepare_config_and_inputs()
								UpperCAmelCase     ,     UpperCAmelCase     ,     UpperCAmelCase     :		List[str]							     =		config_and_inputs
								UpperCAmelCase     :		Dict							     =		{"""pixel_values""": pixel_values}
								return config, inputs_dict




@require_torch
class 			UpperCamelCase_ (							__magic_name__      ,     __magic_name__      ,     unittest.TestCase			):
	lowercase          = (
	    (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else ()
	)
	lowercase          = (
	    {'feature-extraction': VideoMAEModel, 'video-classification': VideoMAEForVideoClassification}
	    if is_torch_available()
	    else {}
	)

	lowercase          = False
	lowercase          = False
	lowercase          = False
	lowercase          = False





	def  _lowercase(  self    )			->			Optional[Any]:
								UpperCAmelCase     :		List[Any]							     =		VideoMAEModelTester(self    )
								UpperCAmelCase     :		str							     =		ConfigTester(self		,		config_class=A		,		has_text_modality=A		,		hidden_size=37    )





	def  _lowercase(  self		,		A		,		A		,		A=False    )			->			int:
								UpperCAmelCase     :		List[str]							     =		copy.deepcopy(A    )

								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
															UpperCAmelCase     :		Optional[Any]							     =		torch.ones((self.model_tester.num_masks,)    )
															UpperCAmelCase     :		int							     =		torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0    )    )]    )
															UpperCAmelCase     :		List[Any]							     =		mask.expand(self.model_tester.batch_size		,		-1    ).bool()
															UpperCAmelCase     :		Tuple							     =		bool_masked_pos.to(A    )

								if return_labels:
															if model_class in [
															    *get_values(A    ),
															]:
																						UpperCAmelCase     :		str							     =		torch.zeros(
																						    self.model_tester.batch_size		,		dtype=torch.long		,		device=A    )

								return inputs_dict





	def  _lowercase(  self    )			->			Tuple:
								self.config_tester.run_common_tests()





	@unittest.skip(reason="""VideoMAE does not use inputs_embeds"""    )
	def  _lowercase(  self    )			->			int:
								pass





	def  _lowercase(  self    )			->			Dict:
								UpperCAmelCase     ,     UpperCAmelCase     :		int							     =		self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															UpperCAmelCase     :		Union[str, Any]							     =		model_class(A    )
															self.assertIsInstance(model.get_input_embeddings()		,		(nn.Module)    )
															UpperCAmelCase     :		Any							     =		model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(A		,		nn.Linear    )    )





	def  _lowercase(  self    )			->			Dict:
								UpperCAmelCase     ,     UpperCAmelCase     :		int							     =		self.model_tester.prepare_config_and_inputs_for_common()

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

															UpperCAmelCase     :		Any							     =		["""pixel_values"""]
															self.assertListEqual(arg_names[:1]		,		A    )





	def  _lowercase(  self    )			->			Tuple:
								UpperCAmelCase     :		List[str]							     =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*A    )





	def  _lowercase(  self    )			->			List[str]:
								UpperCAmelCase     :		Union[str, Any]							     =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_pretraining(*A    )





	@slow
	def  _lowercase(  self    )			->			int:
								for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															UpperCAmelCase     :		Dict							     =		VideoMAEModel.from_pretrained(A    )
															self.assertIsNotNone(A    )





	def  _lowercase(  self    )			->			Optional[int]:
								if not self.has_attentions:
															pass

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

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

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

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

																						self.assertListEqual(
																						    list(attentions[0].shape[-3:]    )		,		[self.model_tester.num_attention_heads, seq_len, seq_len]		,		)
																						UpperCAmelCase     :		Optional[int]							     =		len(A    )

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

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

																						UpperCAmelCase     :		Any							     =		outputs.attentions

																						self.assertEqual(len(A    )		,		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    )			->			Any:
								def check_hidden_states_output(A		,		A		,		A    ):
															UpperCAmelCase     :		str							     =		model_class(A    )
															model.to(A    )
															model.eval()

															with torch.no_grad():
																						UpperCAmelCase     :		List[str]							     =		model(**self._prepare_for_class(A		,		A    )    )

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

															UpperCAmelCase     :		Optional[int]							     =		self.model_tester.seq_length - self.model_tester.num_masks
															UpperCAmelCase     :		List[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]		,		)

								UpperCAmelCase     ,     UpperCAmelCase     :		List[Any]							     =		self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															UpperCAmelCase     :		List[Any]							     =		True
															check_hidden_states_output(A		,		A		,		A    )

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

															check_hidden_states_output(A		,		A		,		A    )






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




def       __lowerCamelCase  (					)      ->			Optional[int]:
							UpperCAmelCase     :		int							     =		hf_hub_download(
							    repo_id="""hf-internal-testing/spaghetti-video"""	,				filename="""eating_spaghetti.npy"""	,				repo_type="""dataset"""		)
							UpperCAmelCase     :		List[Any]							     =		np.load(_lowercase		)
							return list(_lowercase		)


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





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





	@slow
	def  _lowercase(  self    )			->			Optional[Any]:
								UpperCAmelCase     :		List[str]							     =		VideoMAEForVideoClassification.from_pretrained("""MCG-NJU/videomae-base-finetuned-kinetics"""    ).to(
								    A    )

								UpperCAmelCase     :		Optional[int]							     =		self.default_image_processor
								UpperCAmelCase     :		Optional[int]							     =		prepare_video()
								UpperCAmelCase     :		Dict							     =		image_processor(A		,		return_tensors="""pt"""    ).to(A    )

								# forward pass
								with torch.no_grad():
															UpperCAmelCase     :		Optional[int]							     =		model(**A    )

								# verify the logits
								UpperCAmelCase     :		Optional[Any]							     =		torch.Size((1, 400)    )
								self.assertEqual(outputs.logits.shape		,		A    )

								UpperCAmelCase     :		int							     =		torch.tensor([0.3_6_6_9, -0.0_6_8_8, -0.2_4_2_1]    ).to(A    )

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






	@slow
	def  _lowercase(  self    )			->			Union[str, Any]:
								UpperCAmelCase     :		List[Any]							     =		VideoMAEForPreTraining.from_pretrained("""MCG-NJU/videomae-base-short"""    ).to(A    )

								UpperCAmelCase     :		Dict							     =		self.default_image_processor
								UpperCAmelCase     :		Dict							     =		prepare_video()
								UpperCAmelCase     :		Optional[Any]							     =		image_processor(A		,		return_tensors="""pt"""    ).to(A    )

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

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

								# verify the logits
								UpperCAmelCase     :		Union[str, Any]							     =		torch.Size([1, 1408, 1536]    )
								UpperCAmelCase     :		int							     =		torch.tensor(
								    [[0.7_9_9_4, 0.9_6_1_2, 0.8_5_0_8], [0.7_4_0_1, 0.8_9_5_8, 0.8_3_0_2], [0.5_8_6_2, 0.7_4_6_8, 0.7_3_2_5]]		,		device=A    )
								self.assertEqual(outputs.logits.shape		,		A    )
								self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]		,		A		,		atol=1e-4    )    )

								# verify the loss (`config.norm_pix_loss` = `True`)
								UpperCAmelCase     :		Union[str, Any]							     =		torch.tensor([0.5_1_4_2]		,		device=A    )
								self.assertTrue(torch.allclose(outputs.loss		,		A		,		atol=1e-4    )    )

								# verify the loss (`config.norm_pix_loss` = `False`)
								UpperCAmelCase     :		List[Any]							     =		VideoMAEForPreTraining.from_pretrained("""MCG-NJU/videomae-base-short"""		,		norm_pix_loss=A    ).to(
								    A    )

								with torch.no_grad():
															UpperCAmelCase     :		str							     =		model(**A    )

								UpperCAmelCase     :		str							     =		torch.tensor(torch.tensor([0.6_4_6_9]    )		,		device=A    )
								self.assertTrue(torch.allclose(outputs.loss		,		A		,		atol=1e-4    )    )






'''simple docstring'''




import unittest

import torch
from torch import nn

from accelerate.test_utils import require_cuda
from accelerate.utils.memory import find_executable_batch_size, release_memory



def       __lowerCamelCase  (					)      ->			Any:
							raise RuntimeError("""CUDA out of memory."""		)

class 			UpperCamelCase_ (							nn.Module			):





	def __init__(  self    )			->			Any:
								super().__init__()
								UpperCAmelCase     :		Tuple							     =		nn.Linear(3		,		4    )
								UpperCAmelCase     :		Tuple							     =		nn.BatchNormad(4    )
								UpperCAmelCase     :		int							     =		nn.Linear(4		,		5    )






	def  _lowercase(  self		,		A    )			->			Any:
								return self.lineara(self.batchnorm(self.lineara(A    )    )    )




class 			UpperCamelCase_ (							unittest.TestCase			):





	def  _lowercase(  self    )			->			Optional[Any]:
								UpperCAmelCase     :		Optional[int]							     =		[]

								@find_executable_batch_size(starting_batch_size=128    )
								def mock_training_loop_function(A    ):
															nonlocal batch_sizes
															batch_sizes.append(A    )
															if batch_size != 8:
																						raise_fake_out_of_memory()

								mock_training_loop_function()
								self.assertListEqual(A		,		[128, 64, 32, 16, 8]    )





	def  _lowercase(  self    )			->			Any:
								UpperCAmelCase     :		Optional[Any]							     =		[]

								@find_executable_batch_size(starting_batch_size=128    )
								def mock_training_loop_function(A		,		A    ):
															nonlocal batch_sizes
															batch_sizes.append(A    )
															if batch_size != 8:
																						raise_fake_out_of_memory()
															return batch_size, arga

								UpperCAmelCase     ,     UpperCAmelCase     :		Optional[int]							     =		mock_training_loop_function("""hello"""    )
								self.assertListEqual(A		,		[128, 64, 32, 16, 8]    )
								self.assertListEqual([bs, arga]		,		[8, """hello"""]    )





	def  _lowercase(  self    )			->			Any:
								@find_executable_batch_size(starting_batch_size=0    )
								def mock_training_loop_function(A    ):
															pass

								with self.assertRaises(A    ) as cm:
															mock_training_loop_function()
															self.assertIn("""No executable batch size found, reached zero."""		,		cm.exception.args[0]    )





	def  _lowercase(  self    )			->			Optional[int]:
								@find_executable_batch_size(starting_batch_size=16    )
								def mock_training_loop_function(A    ):
															if batch_size > 0:
																						raise_fake_out_of_memory()
															pass

								with self.assertRaises(A    ) as cm:
															mock_training_loop_function()
															self.assertIn("""No executable batch size found, reached zero."""		,		cm.exception.args[0]    )





	def  _lowercase(  self    )			->			Optional[Any]:
								@find_executable_batch_size(starting_batch_size=128    )
								def mock_training_loop_function(A		,		A		,		A    ):
															if batch_size != 8:
																						raise raise_fake_out_of_memory()

								with self.assertRaises(A    ) as cm:
															mock_training_loop_function(128		,		"""hello"""		,		"""world"""    )
															self.assertIn("""Batch size was passed into `f`"""		,		cm.exception.args[0]    )
															self.assertIn("""`f(arg1='hello', arg2='world')"""		,		cm.exception.args[0]    )





	def  _lowercase(  self    )			->			int:
								@find_executable_batch_size(starting_batch_size=16    )
								def mock_training_loop_function(A    ):
															raise ValueError("""Oops, we had an error!"""    )

								with self.assertRaises(A    ) as cm:
															mock_training_loop_function()
															self.assertIn("""Oops, we had an error!"""		,		cm.exception.args[0]    )






	@require_cuda
	def  _lowercase(  self    )			->			Optional[int]:
								UpperCAmelCase     :		Optional[Any]							     =		torch.cuda.memory_allocated()
								UpperCAmelCase     :		List[str]							     =		ModelForTest()
								model.cuda()
								self.assertGreater(torch.cuda.memory_allocated()		,		A    )
								UpperCAmelCase     :		Tuple							     =		release_memory(A    )
								self.assertEqual(torch.cuda.memory_allocated()		,		A    )

