


'''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		:Tuple  ,_UpperCamelCase		:Optional[int]  ,_UpperCamelCase		:Optional[Any]=1_3  ,_UpperCamelCase		:List[Any]=1_0  ,_UpperCamelCase		:str=3  ,_UpperCamelCase		:Tuple=2  ,_UpperCamelCase		:List[str]=2  ,_UpperCamelCase		:Union[str, Any]=2  ,_UpperCamelCase		:Optional[int]=True  ,_UpperCamelCase		:Optional[Any]=True  ,_UpperCamelCase		:Optional[int]=3_2  ,_UpperCamelCase		:Tuple=5  ,_UpperCamelCase		:Any=4  ,_UpperCamelCase		:Dict=3_7  ,_UpperCamelCase		:Union[str, Any]="gelu"  ,_UpperCamelCase		:Dict=0.1  ,_UpperCamelCase		:Dict=0.1  ,_UpperCamelCase		:int=1_0  ,_UpperCamelCase		:int=0.02  ,_UpperCamelCase		:Tuple=0.9  ,_UpperCamelCase		:Union[str, Any]=None  ,):
									snake_case_		:							Union[str, Any]			       =						parent
									snake_case_		:							Optional[Any]			       =						batch_size
									snake_case_		:							Optional[int]			       =						image_size
									snake_case_		:							int			       =						num_channels
									snake_case_		:							Dict			       =						patch_size
									snake_case_		:							Any			       =						tubelet_size
									snake_case_		:							str			       =						num_frames
									snake_case_		:							Tuple			       =						is_training
									snake_case_		:							Optional[int]			       =						use_labels
									snake_case_		:							str			       =						hidden_size
									snake_case_		:							Optional[Any]			       =						num_hidden_layers
									snake_case_		:							Any			       =						num_attention_heads
									snake_case_		:							Optional[Any]			       =						intermediate_size
									snake_case_		:							Dict			       =						hidden_act
									snake_case_		:							str			       =						hidden_dropout_prob
									snake_case_		:							Optional[Any]			       =						attention_probs_dropout_prob
									snake_case_		:							Dict			       =						type_sequence_label_size
									snake_case_		:							Tuple			       =						initializer_range
									snake_case_		:							Tuple			       =						mask_ratio
									snake_case_		:							List[str]			       =						scope

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

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





							def 		a__   (  self		:Any			):
									snake_case_		:							str			       =						floats_tensor(
									    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]			)

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

									snake_case_		:							Union[str, Any]			       =						self.get_config()

									return config, pixel_values, labels





							def 		a__   (  self		:str			):
									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=_UpperCamelCase  ,initializer_range=self.initializer_range  ,)





							def 		a__   (  self		:Dict  ,_UpperCamelCase		:Optional[Any]  ,_UpperCamelCase		:Dict  ,_UpperCamelCase		:str			):
									snake_case_		:							Tuple			       =						VideoMAEModel(config=_UpperCamelCase			)
									model.to(_UpperCamelCase			)
									model.eval()
									snake_case_		:							Optional[Any]			       =						model(_UpperCamelCase			)
									self.parent.assertEqual(result.last_hidden_state.shape  ,(self.batch_size, self.seq_length, self.hidden_size)			)





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

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





							def 		a__   (  self		:Optional[Any]			):
									snake_case_		:							int			       =						self.prepare_config_and_inputs()
									snake_case_		:							Optional[int]			       =						config_and_inputs
									snake_case_		:							Optional[Any]			       =						{"pixel_values": pixel_values}
									return config, inputs_dict





@require_torch
class 						__UpperCamelCase	(						lowercase__						,  lowercase__						,  unittest.TestCase							):
							lowercase			:		List[str]   		=  (
							    (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else ()
							)
							lowercase			:		Tuple   		=  (
							    {'feature-extraction': VideoMAEModel, 'video-classification': VideoMAEForVideoClassification}
							    if is_torch_available()
							    else {}
							)

							lowercase			:		Dict   		=  False
							lowercase			:		int   		=  False
							lowercase			:		Any   		=  False
							lowercase			:		Optional[int]   		=  False





							def 		a__   (  self		:Dict			):
									snake_case_		:							Tuple			       =						VideoMAEModelTester(self			)
									snake_case_		:							Optional[Any]			       =						ConfigTester(self  ,config_class=_UpperCamelCase  ,has_text_modality=_UpperCamelCase  ,hidden_size=3_7			)





							def 		a__   (  self		:Optional[int]  ,_UpperCamelCase		:List[Any]  ,_UpperCamelCase		:str  ,_UpperCamelCase		:Dict=False			):
									snake_case_		:							Any			       =						copy.deepcopy(_UpperCamelCase			)

									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
											snake_case_		:							str			       =						torch.ones((self.model_tester.num_masks,)			)
											snake_case_		:							List[str]			       =						torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0			)			)]			)
											snake_case_		:							List[str]			       =						mask.expand(self.model_tester.batch_size  ,-1			).bool()
											snake_case_		:							List[str]			       =						bool_masked_pos.to(_UpperCamelCase			)

									if return_labels:
											if model_class in [
											    *get_values(_UpperCamelCase			),
											]:
													snake_case_		:							Union[str, Any]			       =						torch.zeros(
													    self.model_tester.batch_size  ,dtype=torch.long  ,device=_UpperCamelCase			)

									return inputs_dict





							def 		a__   (  self		:Optional[int]			):
									self.config_tester.run_common_tests()





							@unittest.skip(reason="""VideoMAE does not use inputs_embeds"""			)
							def 		a__   (  self		:List[Any]			):
									pass





							def 		a__   (  self		:Optional[int]			):
									snake_case_		:							List[Any]			       =						self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											snake_case_		:							int			       =						model_class(_UpperCamelCase			)
											self.assertIsInstance(model.get_input_embeddings()  ,(nn.Module)			)
											snake_case_		:							str			       =						model.get_output_embeddings()
											self.assertTrue(x is None or isinstance(_UpperCamelCase  ,nn.Linear			)			)





							def 		a__   (  self		:int			):
									snake_case_		:							Any			       =						self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											snake_case_		:							Optional[int]			       =						model_class(_UpperCamelCase			)
											snake_case_		:							List[str]			       =						inspect.signature(model.forward			)
											# signature.parameters is an OrderedDict => so arg_names order is deterministic
											snake_case_		:							str			       =						[*signature.parameters.keys()]

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





							def 		a__   (  self		:Optional[Any]			):
									snake_case_		:							Dict			       =						self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_UpperCamelCase			)





							def 		a__   (  self		:Optional[Any]			):
									snake_case_		:							Union[str, Any]			       =						self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_pretraining(*_UpperCamelCase			)





							@slow
							def 		a__   (  self		:int			):
									for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											snake_case_		:							Optional[Any]			       =						VideoMAEModel.from_pretrained(_UpperCamelCase			)
											self.assertIsNotNone(_UpperCamelCase			)





							def 		a__   (  self		:str			):
									if not self.has_attentions:
											pass

									else:
											snake_case_		:							Tuple			       =						self.model_tester.prepare_config_and_inputs_for_common()
											snake_case_		:							Any			       =						True

											for model_class in self.all_model_classes:
													snake_case_		:							List[str]			       =						self.model_tester.seq_length - self.model_tester.num_masks
													snake_case_		:							Tuple			       =						(
													    num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
													)

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

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

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

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

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

													snake_case_		:							Tuple			       =						outputs.attentions

													self.assertEqual(len(_UpperCamelCase			)  ,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 		a__   (  self		:List[str]			):
									def check_hidden_states_output(_UpperCamelCase		:Optional[int]  ,_UpperCamelCase		:Optional[Any]  ,_UpperCamelCase		:Union[str, Any]			):
											snake_case_		:							Tuple			       =						model_class(_UpperCamelCase			)
											model.to(_UpperCamelCase			)
											model.eval()

											with torch.no_grad():
													snake_case_		:							List[Any]			       =						model(**self._prepare_for_class(_UpperCamelCase  ,_UpperCamelCase			)			)

											snake_case_		:							List[str]			       =						outputs.hidden_states
											snake_case_		:							List[str]			       =						self.model_tester.num_hidden_layers + 1
											self.assertEqual(len(_UpperCamelCase			)  ,_UpperCamelCase			)

											snake_case_		:							str			       =						self.model_tester.seq_length - self.model_tester.num_masks
											snake_case_		:							Union[str, 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]  ,)

									snake_case_		:							Any			       =						self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											snake_case_		:							Optional[int]			       =						True
											check_hidden_states_output(_UpperCamelCase  ,_UpperCamelCase  ,_UpperCamelCase			)

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

											check_hidden_states_output(_UpperCamelCase  ,_UpperCamelCase  ,_UpperCamelCase			)





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





def      UpperCAmelCase      (		):







		'''simple docstring'''
		snake_case_		:							Optional[Any]			       =						hf_hub_download(
		    repo_id="""hf-internal-testing/spaghetti-video"""				,      filename="""eating_spaghetti.npy"""				,      repo_type="""dataset""" )
		snake_case_		:							List[Any]			       =						np.load(_lowerCamelCase )
		return list(_lowerCamelCase )






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





							@cached_property
							def 		a__   (  self		:Optional[Any]			):
									# 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 		a__   (  self		:Optional[Any]			):
									snake_case_		:							Union[str, Any]			       =						VideoMAEForVideoClassification.from_pretrained("""MCG-NJU/videomae-base-finetuned-kinetics"""			).to(
									    _UpperCamelCase			)

									snake_case_		:							List[str]			       =						self.default_image_processor
									snake_case_		:							str			       =						prepare_video()
									snake_case_		:							Optional[Any]			       =						image_processor(_UpperCamelCase  ,return_tensors="""pt"""			).to(_UpperCamelCase			)

									# forward pass
									with torch.no_grad():
											snake_case_		:							Any			       =						model(**_UpperCamelCase			)

									# verify the logits
									snake_case_		:							Union[str, Any]			       =						torch.Size((1, 4_0_0)			)
									self.assertEqual(outputs.logits.shape  ,_UpperCamelCase			)

									snake_case_		:							Dict			       =						torch.tensor([0.36_69, -0.06_88, -0.24_21]			).to(_UpperCamelCase			)

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





							@slow
							def 		a__   (  self		:Union[str, Any]			):
									snake_case_		:							List[Any]			       =						VideoMAEForPreTraining.from_pretrained("""MCG-NJU/videomae-base-short"""			).to(_UpperCamelCase			)

									snake_case_		:							List[Any]			       =						self.default_image_processor
									snake_case_		:							Optional[Any]			       =						prepare_video()
									snake_case_		:							List[str]			       =						image_processor(_UpperCamelCase  ,return_tensors="""pt"""			).to(_UpperCamelCase			)

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

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

									# verify the logits
									snake_case_		:							List[str]			       =						torch.Size([1, 1_4_0_8, 1_5_3_6]			)
									snake_case_		:							str			       =						torch.tensor(
									    [[0.79_94, 0.96_12, 0.85_08], [0.74_01, 0.89_58, 0.83_02], [0.58_62, 0.74_68, 0.73_25]]  ,device=_UpperCamelCase			)
									self.assertEqual(outputs.logits.shape  ,_UpperCamelCase			)
									self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]  ,_UpperCamelCase  ,atol=1E-4			)			)

									# verify the loss (`config.norm_pix_loss` = `True`)
									snake_case_		:							Tuple			       =						torch.tensor([0.51_42]  ,device=_UpperCamelCase			)
									self.assertTrue(torch.allclose(outputs.loss  ,_UpperCamelCase  ,atol=1E-4			)			)

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

									with torch.no_grad():
											snake_case_		:							Union[str, Any]			       =						model(**_UpperCamelCase			)

									snake_case_		:							Optional[int]			       =						torch.tensor(torch.tensor([0.64_69]			)  ,device=_UpperCamelCase			)
									self.assertTrue(torch.allclose(outputs.loss  ,_UpperCamelCase  ,atol=1E-4			)			)




'''simple docstring'''






from ...configuration_utils import PretrainedConfig
from ...utils import logging


__A	:	Optional[int]     =     logging.get_logger(__name__)

__A	:	List[Any]     =     {
    'studio-ousia/luke-base': 'https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json',
    'studio-ousia/luke-large': 'https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json',
}
class 						__UpperCamelCase	(						lowercase__							):
							lowercase			:		Union[str, Any]   		=  'luke'





							def __init__(  self		:List[str]  ,_UpperCamelCase		:Tuple=5_0_2_6_7  ,_UpperCamelCase		:Tuple=5_0_0_0_0_0  ,_UpperCamelCase		:str=7_6_8  ,_UpperCamelCase		:List[Any]=2_5_6  ,_UpperCamelCase		:List[str]=1_2  ,_UpperCamelCase		:str=1_2  ,_UpperCamelCase		:Union[str, Any]=3_0_7_2  ,_UpperCamelCase		:int="gelu"  ,_UpperCamelCase		:int=0.1  ,_UpperCamelCase		:Dict=0.1  ,_UpperCamelCase		:Dict=5_1_2  ,_UpperCamelCase		:Optional[Any]=2  ,_UpperCamelCase		:int=0.02  ,_UpperCamelCase		:Any=1E-1_2  ,_UpperCamelCase		:Tuple=True  ,_UpperCamelCase		:Any=None  ,_UpperCamelCase		:Any=1  ,_UpperCamelCase		:int=0  ,_UpperCamelCase		:List[Any]=2  ,**_UpperCamelCase		:str  ,):
									super().__init__(pad_token_id=_UpperCamelCase  ,bos_token_id=_UpperCamelCase  ,eos_token_id=_UpperCamelCase  ,**_UpperCamelCase			)

									snake_case_		:							Any			       =						vocab_size
									snake_case_		:							List[Any]			       =						entity_vocab_size
									snake_case_		:							Optional[Any]			       =						hidden_size
									snake_case_		:							List[Any]			       =						entity_emb_size
									snake_case_		:							Dict			       =						num_hidden_layers
									snake_case_		:							Union[str, Any]			       =						num_attention_heads
									snake_case_		:							Dict			       =						hidden_act
									snake_case_		:							Dict			       =						intermediate_size
									snake_case_		:							Any			       =						hidden_dropout_prob
									snake_case_		:							List[Any]			       =						attention_probs_dropout_prob
									snake_case_		:							Optional[Any]			       =						max_position_embeddings
									snake_case_		:							Any			       =						type_vocab_size
									snake_case_		:							int			       =						initializer_range
									snake_case_		:							Union[str, Any]			       =						layer_norm_eps
									snake_case_		:							Tuple			       =						use_entity_aware_attention
									snake_case_		:							Tuple			       =						classifier_dropout