



import argparse
import json

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation






def        __lowerCAmelCase		(	__lowerCamelCase						:     Optional[int]						)	->    Dict:
					__lowerCAmelCase						 =384
					if "tiny" in model_name:
										__lowerCAmelCase						 =[3, 3, 9, 3]
										__lowerCAmelCase						 =[96, 192, 384, 768]
					if "small" in model_name:
										__lowerCAmelCase						 =[3, 3, 27, 3]
										__lowerCAmelCase						 =[96, 192, 384, 768]
					if "base" in model_name:
										__lowerCAmelCase						 =[3, 3, 27, 3]
										__lowerCAmelCase						 =[128, 256, 512, 1024]
										__lowerCAmelCase						 =512
					if "large" in model_name:
										__lowerCAmelCase						 =[3, 3, 27, 3]
										__lowerCAmelCase						 =[192, 384, 768, 1536]
										__lowerCAmelCase						 =768
					if "xlarge" in model_name:
										__lowerCAmelCase						 =[3, 3, 27, 3]
										__lowerCAmelCase						 =[256, 512, 1024, 2048]
										__lowerCAmelCase						 =1024

					# set label information
					__lowerCAmelCase						 =150
					__lowerCAmelCase						 ="""huggingface/label-files"""
					__lowerCAmelCase						 ="""ade20k-id2label.json"""
					__lowerCAmelCase						 =json.load(open(hf_hub_download(__lowerCamelCase					, __lowerCamelCase					, repo_type="""dataset"""						)					, """r"""						)						)
					__lowerCAmelCase						 ={int(__lowerCamelCase						): v for k, v in idalabel.items()}
					__lowerCAmelCase						 ={v: k for k, v in idalabel.items()}

					__lowerCAmelCase						 =ConvNextConfig(
					    depths=__lowerCamelCase					, hidden_sizes=__lowerCamelCase					, out_features=["""stage1""", """stage2""", """stage3""", """stage4"""]						)
					__lowerCAmelCase						 =UperNetConfig(
					    backbone_config=__lowerCamelCase					, auxiliary_in_channels=__lowerCamelCase					, num_labels=__lowerCamelCase					, idalabel=__lowerCamelCase					, labelaid=__lowerCamelCase					, )

					return config






def        __lowerCAmelCase		(	__lowerCamelCase						:     Any						)	->    int:
					__lowerCAmelCase						 =[]

					# fmt: off
					# stem
					rename_keys.append(("""backbone.downsample_layers.0.0.weight""", """backbone.embeddings.patch_embeddings.weight""")						)
					rename_keys.append(("""backbone.downsample_layers.0.0.bias""", """backbone.embeddings.patch_embeddings.bias""")						)
					rename_keys.append(("""backbone.downsample_layers.0.1.weight""", """backbone.embeddings.layernorm.weight""")						)
					rename_keys.append(("""backbone.downsample_layers.0.1.bias""", """backbone.embeddings.layernorm.bias""")						)
					# stages
					for i in range(len(config.backbone_config.depths						)						):
										for j in range(config.backbone_config.depths[i]						):
															rename_keys.append((f"""backbone.stages.{i}.{j}.gamma""", f"""backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter""")						)
															rename_keys.append((f"""backbone.stages.{i}.{j}.depthwise_conv.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.dwconv.weight""")						)
															rename_keys.append((f"""backbone.stages.{i}.{j}.depthwise_conv.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.dwconv.bias""")						)
															rename_keys.append((f"""backbone.stages.{i}.{j}.norm.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.layernorm.weight""")						)
															rename_keys.append((f"""backbone.stages.{i}.{j}.norm.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.layernorm.bias""")						)
															rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv1.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight""")						)
															rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv1.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias""")						)
															rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv2.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight""")						)
															rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv2.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias""")						)
										if i > 0:
															rename_keys.append((f"""backbone.downsample_layers.{i}.0.weight""", f"""backbone.encoder.stages.{i}.downsampling_layer.0.weight""")						)
															rename_keys.append((f"""backbone.downsample_layers.{i}.0.bias""", f"""backbone.encoder.stages.{i}.downsampling_layer.0.bias""")						)
															rename_keys.append((f"""backbone.downsample_layers.{i}.1.weight""", f"""backbone.encoder.stages.{i}.downsampling_layer.1.weight""")						)
															rename_keys.append((f"""backbone.downsample_layers.{i}.1.bias""", f"""backbone.encoder.stages.{i}.downsampling_layer.1.bias""")						)

										rename_keys.append((f"""backbone.norm{i}.weight""", f"""backbone.hidden_states_norms.stage{i+1}.weight""")						)
										rename_keys.append((f"""backbone.norm{i}.bias""", f"""backbone.hidden_states_norms.stage{i+1}.bias""")						)

					# decode head
					rename_keys.extend(
					    [
					        ("""decode_head.conv_seg.weight""", """decode_head.classifier.weight"""),
					        ("""decode_head.conv_seg.bias""", """decode_head.classifier.bias"""),
					        ("""auxiliary_head.conv_seg.weight""", """auxiliary_head.classifier.weight"""),
					        ("""auxiliary_head.conv_seg.bias""", """auxiliary_head.classifier.bias"""),
					    ]						)
					# fmt: on

					return rename_keys






def        __lowerCAmelCase		(	__lowerCamelCase						:     str					, __lowerCamelCase						:     str					, __lowerCamelCase						:     Dict						)	->    Union[str, Any]:
					__lowerCAmelCase						 =dct.pop(__lowerCamelCase						)
					__lowerCAmelCase						 =val






def        __lowerCAmelCase		(	__lowerCamelCase						:     int					, __lowerCamelCase						:     List[str]					, __lowerCamelCase						:     Optional[int]						)	->    str:
					__lowerCAmelCase						 ={
					    """upernet-convnext-tiny""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth""",
					    """upernet-convnext-small""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth""",
					    """upernet-convnext-base""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth""",
					    """upernet-convnext-large""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth""",
					    """upernet-convnext-xlarge""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth""",
					}
					__lowerCAmelCase						 =model_name_to_url[model_name]
					__lowerCAmelCase						 =torch.hub.load_state_dict_from_url(__lowerCamelCase					, map_location="""cpu"""						)["""state_dict"""]

					__lowerCAmelCase						 =get_upernet_config(__lowerCamelCase						)
					__lowerCAmelCase						 =UperNetForSemanticSegmentation(__lowerCamelCase						)
					model.eval()

					# replace "bn" => "batch_norm"
					for key in state_dict.copy().keys():
										__lowerCAmelCase						 =state_dict.pop(__lowerCamelCase						)
										if "bn" in key:
															__lowerCAmelCase						 =key.replace("""bn"""					, """batch_norm"""						)
										__lowerCAmelCase						 =val

					# rename keys
					__lowerCAmelCase						 =create_rename_keys(__lowerCamelCase						)
					for src, dest in rename_keys:
										rename_key(__lowerCamelCase					, __lowerCamelCase					, __lowerCamelCase						)

					model.load_state_dict(__lowerCamelCase						)

					# verify on image
					__lowerCAmelCase						 ="""https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg"""
					__lowerCAmelCase						 =Image.open(requests.get(__lowerCamelCase					, stream=__lowerCamelCase						).raw						).convert("""RGB"""						)

					__lowerCAmelCase						 =SegformerImageProcessor()
					__lowerCAmelCase						 =processor(__lowerCamelCase					, return_tensors="""pt"""						).pixel_values

					with torch.no_grad():
										__lowerCAmelCase						 =model(__lowerCamelCase						)

					if model_name == "upernet-convnext-tiny":
										__lowerCAmelCase						 =torch.tensor(
										    [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]						)
					elif model_name == "upernet-convnext-small":
										__lowerCAmelCase						 =torch.tensor(
										    [[-8.8236, -8.8236, -8.6771], [-8.8236, -8.8236, -8.6771], [-8.7638, -8.7638, -8.6240]]						)
					elif model_name == "upernet-convnext-base":
										__lowerCAmelCase						 =torch.tensor(
										    [[-8.8558, -8.8558, -8.6905], [-8.8558, -8.8558, -8.6905], [-8.7669, -8.7669, -8.6021]]						)
					elif model_name == "upernet-convnext-large":
										__lowerCAmelCase						 =torch.tensor(
										    [[-8.6660, -8.6660, -8.6210], [-8.6660, -8.6660, -8.6210], [-8.6310, -8.6310, -8.5964]]						)
					elif model_name == "upernet-convnext-xlarge":
										__lowerCAmelCase						 =torch.tensor(
										    [[-8.4980, -8.4980, -8.3977], [-8.4980, -8.4980, -8.3977], [-8.4379, -8.4379, -8.3412]]						)
					print("""Logits:"""					, outputs.logits[0, 0, :3, :3]						)
					assert torch.allclose(outputs.logits[0, 0, :3, :3]					, __lowerCamelCase					, atol=1E-4						)
					print("""Looks ok!"""						)

					if pytorch_dump_folder_path is not None:
										print(f"""Saving model {model_name} to {pytorch_dump_folder_path}"""						)
										model.save_pretrained(__lowerCamelCase						)
										print(f"""Saving processor to {pytorch_dump_folder_path}"""						)
										processor.save_pretrained(__lowerCamelCase						)

					if push_to_hub:
										print(f"""Pushing model and processor for {model_name} to hub"""						)
										model.push_to_hub(f"""openmmlab/{model_name}"""						)
										processor.push_to_hub(f"""openmmlab/{model_name}"""						)


if __name__ == "__main__":
				lowercase_													=      argparse.ArgumentParser()
				# Required parameters
				parser.add_argument(
				    '''--model_name''',
				    default='''upernet-convnext-tiny''',
				    type=str,
				    choices=[F"upernet-convnext-{size}" for size in ['''tiny''', '''small''', '''base''', '''large''', '''xlarge''']],
				    help='''Name of the ConvNext UperNet model you\'d like to convert.''',
				)
				parser.add_argument(
				    '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
				)
				parser.add_argument(
				    '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.'''
				)

				lowercase_													=      parser.parse_args()
				convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)









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



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

						# in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame
						__lowerCAmelCase						 =(image_size // patch_size) ** 2
						__lowerCAmelCase						 =(num_frames // tubelet_size) * self.num_patches_per_frame

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



	def 		UpperCamelCase				(    self				:     Any)->				int:
						__lowerCAmelCase						 =floats_tensor(
						    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size])

						__lowerCAmelCase						 =None
						if self.use_labels:
											__lowerCAmelCase						 =ids_tensor([self.batch_size]					,						self.type_sequence_label_size)

						__lowerCAmelCase						 =self.get_config()

						return config, pixel_values, labels



	def 		UpperCamelCase				(    self				:     Optional[int])->				List[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=snake_case_					,						initializer_range=self.initializer_range					,						)



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



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

						__lowerCAmelCase						 =model(snake_case_					,						snake_case_)
						# model only returns predictions for masked patches
						__lowerCAmelCase						 =mask.sum().item()
						__lowerCAmelCase						 =3 * self.tubelet_size * self.patch_size**2
						self.parent.assertEqual(result.logits.shape					,						(self.batch_size, num_masked_patches, decoder_num_labels))



	def 		UpperCamelCase				(    self				:     List[Any])->				List[str]:
						__lowerCAmelCase						 =self.prepare_config_and_inputs()
						__lowerCAmelCase ,						__lowerCAmelCase ,						__lowerCAmelCase						 =config_and_inputs
						__lowerCAmelCase						 ={"""pixel_values""": pixel_values}
						return config, inputs_dict






@require_torch
class     __a			(  SCREAMING_SNAKE_CASE						,     SCREAMING_SNAKE_CASE						,     unittest.TestCase					):
	SCREAMING_SNAKE_CASE  	=							(
	    (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else ()
	)
	SCREAMING_SNAKE_CASE  	=							(
	    {"feature-extraction": VideoMAEModel, "video-classification": VideoMAEForVideoClassification}
	    if is_torch_available()
	    else {}
	)

	SCREAMING_SNAKE_CASE  	=							False
	SCREAMING_SNAKE_CASE  	=							False
	SCREAMING_SNAKE_CASE  	=							False
	SCREAMING_SNAKE_CASE  	=							False



	def 		UpperCamelCase				(    self				:     List[Any])->				List[Any]:
						__lowerCAmelCase						 =VideoMAEModelTester(self)
						__lowerCAmelCase						 =ConfigTester(self					,						config_class=snake_case_					,						has_text_modality=snake_case_					,						hidden_size=37)



	def 		UpperCamelCase				(    self				:     Tuple					,						snake_case_				:     str					,						snake_case_				:     Tuple					,						snake_case_				:     List[str]=False)->				Tuple:
						__lowerCAmelCase						 =copy.deepcopy(snake_case_)

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

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

						return inputs_dict



	def 		UpperCamelCase				(    self				:     List[str])->				Any:
						self.config_tester.run_common_tests()



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



	def 		UpperCamelCase				(    self				:     Union[str, Any])->				Tuple:
						__lowerCAmelCase ,						__lowerCAmelCase						 =self.model_tester.prepare_config_and_inputs_for_common()

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



	def 		UpperCamelCase				(    self				:     Optional[int])->				List[str]:
						__lowerCAmelCase ,						__lowerCAmelCase						 =self.model_tester.prepare_config_and_inputs_for_common()

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

											__lowerCAmelCase						 =["""pixel_values"""]
											self.assertListEqual(arg_names[:1]					,						snake_case_)



	def 		UpperCamelCase				(    self				:     str)->				List[Any]:
						__lowerCAmelCase						 =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*snake_case_)



	def 		UpperCamelCase				(    self				:     List[Any])->				Any:
						__lowerCAmelCase						 =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_pretraining(*snake_case_)



	@slow
	def 		UpperCamelCase				(    self				:     List[Any])->				Any:
						for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__lowerCAmelCase						 =VideoMAEModel.from_pretrained(snake_case_)
											self.assertIsNotNone(snake_case_)



	def 		UpperCamelCase				(    self				:     List[Any])->				List[str]:
						if not self.has_attentions:
											pass

						else:
											__lowerCAmelCase ,						__lowerCAmelCase						 =self.model_tester.prepare_config_and_inputs_for_common()
											__lowerCAmelCase						 =True

											for model_class in self.all_model_classes:
																__lowerCAmelCase						 =self.model_tester.seq_length - self.model_tester.num_masks
																__lowerCAmelCase						 =(
																    num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
																)

																__lowerCAmelCase						 =True
																__lowerCAmelCase						 =False
																__lowerCAmelCase						 =True
																__lowerCAmelCase						 =model_class(snake_case_)
																model.to(snake_case_)
																model.eval()
																with torch.no_grad():
																					__lowerCAmelCase						 =model(**self._prepare_for_class(snake_case_					,						snake_case_))
																__lowerCAmelCase						 =outputs.attentions
																self.assertEqual(len(snake_case_)					,						self.model_tester.num_hidden_layers)

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

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

																# Check attention is always last and order is fine
																__lowerCAmelCase						 =True
																__lowerCAmelCase						 =True
																__lowerCAmelCase						 =model_class(snake_case_)
																model.to(snake_case_)
																model.eval()
																with torch.no_grad():
																					__lowerCAmelCase						 =model(**self._prepare_for_class(snake_case_					,						snake_case_))

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

																__lowerCAmelCase						 =outputs.attentions

																self.assertEqual(len(snake_case_)					,						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 		UpperCamelCase				(    self				:     Tuple)->				Any:
						def check_hidden_states_output(snake_case_				:     Tuple					,						snake_case_				:     Tuple					,						snake_case_				:     int):
											__lowerCAmelCase						 =model_class(snake_case_)
											model.to(snake_case_)
											model.eval()

											with torch.no_grad():
																__lowerCAmelCase						 =model(**self._prepare_for_class(snake_case_					,						snake_case_))

											__lowerCAmelCase						 =outputs.hidden_states
											__lowerCAmelCase						 =self.model_tester.num_hidden_layers + 1
											self.assertEqual(len(snake_case_)					,						snake_case_)

											__lowerCAmelCase						 =self.model_tester.seq_length - self.model_tester.num_masks
											__lowerCAmelCase						 =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]					,						)

						__lowerCAmelCase ,						__lowerCAmelCase						 =self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
											__lowerCAmelCase						 =True
											check_hidden_states_output(snake_case_					,						snake_case_					,						snake_case_)

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											__lowerCAmelCase						 =True

											check_hidden_states_output(snake_case_					,						snake_case_					,						snake_case_)



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






def        __lowerCAmelCase		(	)	->    Any:
					__lowerCAmelCase						 =hf_hub_download(
					    repo_id="""hf-internal-testing/spaghetti-video"""					, filename="""eating_spaghetti.npy"""					, repo_type="""dataset"""						)
					__lowerCAmelCase						 =np.load(__lowerCamelCase						)
					return list(__lowerCamelCase						)






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



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

						__lowerCAmelCase						 =self.default_image_processor
						__lowerCAmelCase						 =prepare_video()
						__lowerCAmelCase						 =image_processor(snake_case_					,						return_tensors="""pt""").to(snake_case_)

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

						# verify the logits
						__lowerCAmelCase						 =torch.Size((1, 4_00))
						self.assertEqual(outputs.logits.shape					,						snake_case_)

						__lowerCAmelCase						 =torch.tensor([0.3_6_6_9, -0.0_6_8_8, -0.2_4_2_1]).to(snake_case_)

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



	@slow
	def 		UpperCamelCase				(    self				:     str)->				str:
						__lowerCAmelCase						 =VideoMAEForPreTraining.from_pretrained("""MCG-NJU/videomae-base-short""").to(snake_case_)

						__lowerCAmelCase						 =self.default_image_processor
						__lowerCAmelCase						 =prepare_video()
						__lowerCAmelCase						 =image_processor(snake_case_					,						return_tensors="""pt""").to(snake_case_)

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

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

						# verify the logits
						__lowerCAmelCase						 =torch.Size([1, 14_08, 15_36])
						__lowerCAmelCase						 =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=snake_case_)
						self.assertEqual(outputs.logits.shape					,						snake_case_)
						self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]					,						snake_case_					,						atol=1e-4))

						# verify the loss (`config.norm_pix_loss` = `True`)
						__lowerCAmelCase						 =torch.tensor([0.5_1_4_2]					,						device=snake_case_)
						self.assertTrue(torch.allclose(outputs.loss					,						snake_case_					,						atol=1e-4))

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

						with torch.no_grad():
											__lowerCAmelCase						 =model(**snake_case_)

						__lowerCAmelCase						 =torch.tensor(torch.tensor([0.6_4_6_9])					,						device=snake_case_)
						self.assertTrue(torch.allclose(outputs.loss					,						snake_case_					,						atol=1e-4))




