



'''simple docstring'''




import copy
import unittest

from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, 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, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers import (
						    MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
						    MODEL_FOR_QUESTION_ANSWERING_MAPPING,
						    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
						    MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
						    LayoutLMvaConfig,
						    LayoutLMvaForQuestionAnswering,
						    LayoutLMvaForSequenceClassification,
						    LayoutLMvaForTokenClassification,
						    LayoutLMvaModel,
						)
						from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
						from PIL import Image

						from transformers import LayoutLMvaImageProcessor







class 	_lowerCAmelCase							:


	def __init__(self       ,      lowercase       ,      lowercase=2       ,      lowercase=3       ,      lowercase=4       ,      lowercase=2       ,      lowercase=7       ,      lowercase=True       ,      lowercase=True       ,      lowercase=True       ,      lowercase=True       ,      lowercase=99       ,      lowercase=36       ,      lowercase=3       ,      lowercase=4       ,      lowercase=37       ,      lowercase="gelu"       ,      lowercase=0.1       ,      lowercase=0.1       ,      lowercase=512       ,      lowercase=16       ,      lowercase=2       ,      lowercase=0.02       ,      lowercase=6       ,      lowercase=6       ,      lowercase=3       ,      lowercase=4       ,      lowercase=None       ,      lowercase=1000       ,      ):
				A_	:						int	=     parent
				A_	:						Optional[int]	=     batch_size
				A_	:						List[str]	=     num_channels
				A_	:						List[str]	=     image_size
				A_	:						Tuple	=     patch_size
				A_	:						List[str]	=     text_seq_length
				A_	:						Optional[int]	=     is_training
				A_	:						Any	=     use_input_mask
				A_	:						int	=     use_token_type_ids
				A_	:						List[Any]	=     use_labels
				A_	:						Union[str, Any]	=     vocab_size
				A_	:						Any	=     hidden_size
				A_	:						str	=     num_hidden_layers
				A_	:						Union[str, Any]	=     num_attention_heads
				A_	:						Union[str, Any]	=     intermediate_size
				A_	:						int	=     hidden_act
				A_	:						int	=     hidden_dropout_prob
				A_	:						Union[str, Any]	=     attention_probs_dropout_prob
				A_	:						List[Any]	=     max_position_embeddings
				A_	:						Optional[int]	=     type_vocab_size
				A_	:						Union[str, Any]	=     type_sequence_label_size
				A_	:						Any	=     initializer_range
				A_	:						List[str]	=     coordinate_size
				A_	:						Any	=     shape_size
				A_	:						Optional[int]	=     num_labels
				A_	:						List[str]	=     num_choices
				A_	:						str	=     scope
				A_	:						List[Any]	=     range_bbox

				# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
				A_	:						Optional[int]	=     text_seq_length
				A_	:						Any	=     (image_size // patch_size) ** 2 + 1
				A_	:						int	=     self.text_seq_length + self.image_seq_length


	def     _a	(self							):
				A_	:						Optional[int]	=     ids_tensor([self.batch_size, self.text_seq_length]       ,      self.vocab_size							)

				A_	:						List[Any]	=     ids_tensor([self.batch_size, self.text_seq_length, 4]       ,      self.range_bbox							)
				# Ensure that bbox is legal
				for i in range(bbox.shape[0]							):
							for j in range(bbox.shape[1]							):
										if bbox[i, j, 3] < bbox[i, j, 1]:
													A_	:						Dict	=     bbox[i, j, 3]
													A_	:						Optional[Any]	=     bbox[i, j, 1]
													A_	:						Tuple	=     t
										if bbox[i, j, 2] < bbox[i, j, 0]:
													A_	:						Union[str, Any]	=     bbox[i, j, 2]
													A_	:						Tuple	=     bbox[i, j, 0]
													A_	:						int	=     t

				A_	:						Optional[Any]	=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

				A_	:						Union[str, Any]	=     None
				if self.use_input_mask:
							A_	:						Dict	=     random_attention_mask([self.batch_size, self.text_seq_length]							)

				A_	:						Union[str, Any]	=     None
				if self.use_token_type_ids:
							A_	:						Any	=     ids_tensor([self.batch_size, self.text_seq_length]       ,      self.type_vocab_size							)

				A_	:						Optional[Any]	=     None
				A_	:						str	=     None
				if self.use_labels:
							A_	:						Any	=     ids_tensor([self.batch_size]       ,      self.type_sequence_label_size							)
							A_	:						int	=     ids_tensor([self.batch_size, self.text_seq_length]       ,      self.num_labels							)

				A_	:						List[Any]	=     LayoutLMvaConfig(
				    vocab_size=self.vocab_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       ,      max_position_embeddings=self.max_position_embeddings       ,      type_vocab_size=self.type_vocab_size       ,      initializer_range=self.initializer_range       ,      coordinate_size=self.coordinate_size       ,      shape_size=self.shape_size       ,      input_size=self.image_size       ,      patch_size=self.patch_size       ,      )

				return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels


	def     _a	(self       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase							):
				A_	:						List[Any]	=     LayoutLMvaModel(config=lowercase							)
				model.to(lowercase							)
				model.eval()

				# text + image
				A_	:						int	=     model(lowercase       ,      pixel_values=lowercase							)
				A_	:						Optional[int]	=     model(
				    lowercase       ,      bbox=lowercase       ,      pixel_values=lowercase       ,      attention_mask=lowercase       ,      token_type_ids=lowercase							)
				A_	:						int	=     model(lowercase       ,      bbox=lowercase       ,      pixel_values=lowercase       ,      token_type_ids=lowercase							)
				A_	:						List[Any]	=     model(lowercase       ,      bbox=lowercase       ,      pixel_values=lowercase							)

				self.parent.assertEqual(result.last_hidden_state.shape       ,      (self.batch_size, self.seq_length, self.hidden_size)							)

				# text only
				A_	:						Optional[int]	=     model(lowercase							)
				self.parent.assertEqual(
				    result.last_hidden_state.shape       ,      (self.batch_size, self.text_seq_length, self.hidden_size)							)

				# image only
				A_	:						List[str]	=     model(pixel_values=lowercase							)
				self.parent.assertEqual(
				    result.last_hidden_state.shape       ,      (self.batch_size, self.image_seq_length, self.hidden_size)							)


	def     _a	(self       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase							):
				A_	:						Optional[int]	=     self.num_labels
				A_	:						Any	=     LayoutLMvaForSequenceClassification(lowercase							)
				model.to(lowercase							)
				model.eval()
				A_	:						List[str]	=     model(
				    lowercase       ,      bbox=lowercase       ,      pixel_values=lowercase       ,      attention_mask=lowercase       ,      token_type_ids=lowercase       ,      labels=lowercase       ,      )
				self.parent.assertEqual(result.logits.shape       ,      (self.batch_size, self.num_labels)							)


	def     _a	(self       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase							):
				A_	:						int	=     self.num_labels
				A_	:						List[str]	=     LayoutLMvaForTokenClassification(config=lowercase							)
				model.to(lowercase							)
				model.eval()
				A_	:						List[str]	=     model(
				    lowercase       ,      bbox=lowercase       ,      pixel_values=lowercase       ,      attention_mask=lowercase       ,      token_type_ids=lowercase       ,      labels=lowercase       ,      )
				self.parent.assertEqual(result.logits.shape       ,      (self.batch_size, self.text_seq_length, self.num_labels)							)


	def     _a	(self       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase							):
				A_	:						Optional[Any]	=     LayoutLMvaForQuestionAnswering(config=lowercase							)
				model.to(lowercase							)
				model.eval()
				A_	:						Optional[int]	=     model(
				    lowercase       ,      bbox=lowercase       ,      pixel_values=lowercase       ,      attention_mask=lowercase       ,      token_type_ids=lowercase       ,      start_positions=lowercase       ,      end_positions=lowercase       ,      )
				self.parent.assertEqual(result.start_logits.shape       ,      (self.batch_size, self.seq_length)							)
				self.parent.assertEqual(result.end_logits.shape       ,      (self.batch_size, self.seq_length)							)


	def     _a	(self							):
				A_	:						List[str]	=     self.prepare_config_and_inputs()
				(
				    (
				    A_
				),    (
				    A_
				),    (
				    A_
				),    (
				    A_
				),    (
				    A_
				),    (
				    A_
				),    (
				    A_
				),    (
				    A_
				),    
				)	:						Optional[Any]	=     config_and_inputs
				A_	:						List[str]	=     {
				    """input_ids""": input_ids,
				    """bbox""": bbox,
				    """pixel_values""": pixel_values,
				    """token_type_ids""": token_type_ids,
				    """attention_mask""": input_mask,
				}
				return config, inputs_dict







@require_torch
class 	_lowerCAmelCase							(			__UpperCAmelCase      ,			__UpperCAmelCase      ,			unittest.TestCase ):
	__SCREAMING_SNAKE_CASE   :		Tuple					=					False
	__SCREAMING_SNAKE_CASE   :		Optional[int]					=					False
	__SCREAMING_SNAKE_CASE   :		Optional[Any]					=					False

	__SCREAMING_SNAKE_CASE   :		Optional[int]					=					(
	    (
	        LayoutLMvaModel,
	        LayoutLMvaForSequenceClassification,
	        LayoutLMvaForTokenClassification,
	        LayoutLMvaForQuestionAnswering,
	    )
	    if is_torch_available()
	    else ()
	)
	__SCREAMING_SNAKE_CASE   :		Optional[Any]					=					(
	    {'document-question-answering': LayoutLMvaForQuestionAnswering, 'feature-extraction': LayoutLMvaModel}
	    if is_torch_available()
	    else {}
	)


	def     _a	(self       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase							):
				# `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual
				# embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has
				# the sequence dimension of the text embedding only.
				# (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`)
				return True


	def     _a	(self							):
				A_	:						Dict	=     LayoutLMvaModelTester(self							)
				A_	:						Union[str, Any]	=     ConfigTester(self       ,      config_class=lowercase       ,      hidden_size=37							)


	def     _a	(self       ,      lowercase       ,      lowercase       ,      lowercase=False							):
				A_	:						Union[str, Any]	=     copy.deepcopy(lowercase							)
				if model_class in get_values(lowercase							):
							A_	:						int	=     {
							    k: v.unsqueeze(1							).expand(-1       ,      self.model_tester.num_choices       ,      -1							).contiguous()
							    if isinstance(lowercase       ,      torch.Tensor							) and v.ndim > 1
							    else v
							    for k, v in inputs_dict.items()
							}
				if return_labels:
							if model_class in get_values(lowercase							):
										A_	:						Optional[int]	=     torch.ones(self.model_tester.batch_size       ,      dtype=torch.long       ,      device=lowercase							)
							elif model_class in get_values(lowercase							):
										A_	:						int	=     torch.zeros(
										    self.model_tester.batch_size       ,      dtype=torch.long       ,      device=lowercase							)
										A_	:						Tuple	=     torch.zeros(
										    self.model_tester.batch_size       ,      dtype=torch.long       ,      device=lowercase							)
							elif model_class in [
							    *get_values(lowercase							),
							]:
										A_	:						int	=     torch.zeros(
										    self.model_tester.batch_size       ,      dtype=torch.long       ,      device=lowercase							)
							elif model_class in [
							    *get_values(lowercase							),
							]:
										A_	:						str	=     torch.zeros(
										    (self.model_tester.batch_size, self.model_tester.text_seq_length)       ,      dtype=torch.long       ,      device=lowercase       ,      )

				return inputs_dict


	def     _a	(self							):
				self.config_tester.run_common_tests()


	def     _a	(self							):
				A_	:						Optional[Any]	=     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*lowercase							)


	def     _a	(self							):
				A_	:						Optional[Any]	=     self.model_tester.prepare_config_and_inputs()
				for type in ["absolute", "relative_key", "relative_key_query"]:
							A_	:						Any	=     type
							self.model_tester.create_and_check_model(*lowercase							)


	def     _a	(self							):
				A_	:						str	=     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_sequence_classification(*lowercase							)


	def     _a	(self							):
				A_	:						Union[str, Any]	=     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_token_classification(*lowercase							)


	def     _a	(self							):
				A_	:						Union[str, Any]	=     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_question_answering(*lowercase							)


	@slow
	def     _a	(self							):
				for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							A_	:						Dict	=     LayoutLMvaModel.from_pretrained(lowercase							)
							self.assertIsNotNone(lowercase							)






def 	a			( ):
			'''simple docstring'''





			A_	:						Dict	=     Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )
			return image







@require_torch
class 	_lowerCAmelCase							(			unittest.TestCase ):


	@cached_property
	def     _a	(self							):
				return LayoutLMvaImageProcessor(apply_ocr=lowercase							) if is_vision_available() else None


	@slow
	def     _a	(self							):
				A_	:						List[str]	=     LayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base"""							).to(lowercase							)

				A_	:						Any	=     self.default_image_processor
				A_	:						int	=     prepare_img()
				A_	:						str	=     image_processor(images=lowercase       ,      return_tensors="""pt"""							).pixel_values.to(lowercase							)

				A_	:						Optional[Any]	=     torch.tensor([[1, 2]]							)
				A_	:						Any	=     torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]							).unsqueeze(0							)

				# forward pass
				A_	:						Union[str, Any]	=     model(
				    input_ids=input_ids.to(lowercase							)       ,      bbox=bbox.to(lowercase							)       ,      pixel_values=pixel_values.to(lowercase							)       ,      )

				# verify the logits
				A_	:						Union[str, Any]	=     torch.Size((1, 199, 768)							)
				self.assertEqual(outputs.last_hidden_state.shape       ,      lowercase							)

				A_	:						str	=     torch.tensor(
				    [[-0.05_29, 0.36_18, 0.16_32], [-0.15_87, -0.16_67, -0.04_00], [-0.15_57, -0.16_71, -0.05_05]]							).to(lowercase							)

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




'''simple docstring'''




import argparse
import json

import gdown
import numpy as np
import torch
from huggingface_hub import hf_hub_download

from transformers import (
    VideoMAEConfig,
    VideoMAEForPreTraining,
    VideoMAEForVideoClassification,
    VideoMAEImageProcessor,
)



def 	a			( lowerCamelCase__    ):
			'''simple docstring'''





			A_	:						Optional[int]	=     VideoMAEConfig()

			set_architecture_configs(lowerCamelCase__						,      lowerCamelCase__    )

			if "finetuned" not in model_name:
						A_	:						Dict	=     False

			if "finetuned" in model_name:
						A_	:						List[Any]	=     """huggingface/label-files"""
						if "kinetics" in model_name:
									A_	:						Dict	=     4_00
									A_	:						List[str]	=     """kinetics400-id2label.json"""
						elif "ssv2" in model_name:
									A_	:						Tuple	=     1_74
									A_	:						str	=     """something-something-v2-id2label.json"""
						else:
									raise ValueError("""Model name should either contain 'kinetics' or 'ssv2' in case it's fine-tuned."""    )
						A_	:						Dict	=     json.load(open(hf_hub_download(lowerCamelCase__						,      lowerCamelCase__						,      repo_type="""dataset"""    )						,      """r"""    )    )
						A_	:						List[str]	=     {int(lowerCamelCase__    ): v for k, v in idalabel.items()}
						A_	:						Optional[Any]	=     idalabel
						A_	:						Union[str, Any]	=     {v: k for k, v in idalabel.items()}

			return config



def 	a			( lowerCamelCase__						,      lowerCamelCase__    ):
			'''simple docstring'''





			if "small" in model_name:
						A_	:						int	=     3_84
						A_	:						Union[str, Any]	=     15_36
						A_	:						List[str]	=     12
						A_	:						Optional[int]	=     16
						A_	:						Any	=     12
						A_	:						int	=     3
						A_	:						Optional[Any]	=     1_92
						A_	:						Union[str, Any]	=     7_68
			elif "large" in model_name:
						A_	:						List[Any]	=     10_24
						A_	:						Optional[Any]	=     40_96
						A_	:						Optional[Any]	=     24
						A_	:						List[str]	=     16
						A_	:						Any	=     12
						A_	:						str	=     8
						A_	:						str	=     5_12
						A_	:						int	=     20_48
			elif "huge" in model_name:
						A_	:						Optional[Any]	=     12_80
						A_	:						str	=     51_20
						A_	:						str	=     32
						A_	:						int	=     16
						A_	:						Any	=     12
						A_	:						Union[str, Any]	=     8
						A_	:						Dict	=     6_40
						A_	:						Optional[Any]	=     25_60
			elif "base" not in model_name:
						raise ValueError("""Model name should include either \"small\", \"base\", \"large\", or \"huge\""""    )



def 	a			( lowerCamelCase__    ):
			'''simple docstring'''





			if "encoder." in name:
						A_	:						List[Any]	=     name.replace("""encoder."""						,      """"""    )
			if "cls_token" in name:
						A_	:						List[str]	=     name.replace("""cls_token"""						,      """videomae.embeddings.cls_token"""    )
			if "decoder_pos_embed" in name:
						A_	:						Tuple	=     name.replace("""decoder_pos_embed"""						,      """decoder.decoder_pos_embed"""    )
			if "pos_embed" in name and "decoder" not in name:
						A_	:						int	=     name.replace("""pos_embed"""						,      """videomae.embeddings.position_embeddings"""    )
			if "patch_embed.proj" in name:
						A_	:						Optional[Any]	=     name.replace("""patch_embed.proj"""						,      """videomae.embeddings.patch_embeddings.projection"""    )
			if "patch_embed.norm" in name:
						A_	:						Dict	=     name.replace("""patch_embed.norm"""						,      """videomae.embeddings.norm"""    )
			if "decoder.blocks" in name:
						A_	:						List[str]	=     name.replace("""decoder.blocks"""						,      """decoder.decoder_layers"""    )
			if "blocks" in name:
						A_	:						List[str]	=     name.replace("""blocks"""						,      """videomae.encoder.layer"""    )
			if "attn.proj" in name:
						A_	:						str	=     name.replace("""attn.proj"""						,      """attention.output.dense"""    )
			if "attn" in name and "bias" not in name:
						A_	:						str	=     name.replace("""attn"""						,      """attention.self"""    )
			if "attn" in name:
						A_	:						Union[str, Any]	=     name.replace("""attn"""						,      """attention.attention"""    )
			if "norm1" in name:
						A_	:						Any	=     name.replace("""norm1"""						,      """layernorm_before"""    )
			if "norm2" in name:
						A_	:						List[str]	=     name.replace("""norm2"""						,      """layernorm_after"""    )
			if "mlp.fc1" in name:
						A_	:						Dict	=     name.replace("""mlp.fc1"""						,      """intermediate.dense"""    )
			if "mlp.fc2" in name:
						A_	:						List[str]	=     name.replace("""mlp.fc2"""						,      """output.dense"""    )
			if "decoder_embed" in name:
						A_	:						Optional[Any]	=     name.replace("""decoder_embed"""						,      """decoder.decoder_embed"""    )
			if "decoder_norm" in name:
						A_	:						Tuple	=     name.replace("""decoder_norm"""						,      """decoder.decoder_norm"""    )
			if "decoder_pred" in name:
						A_	:						Tuple	=     name.replace("""decoder_pred"""						,      """decoder.decoder_pred"""    )
			if "norm.weight" in name and "decoder" not in name and "fc" not in name:
						A_	:						Dict	=     name.replace("""norm.weight"""						,      """videomae.layernorm.weight"""    )
			if "norm.bias" in name and "decoder" not in name and "fc" not in name:
						A_	:						List[str]	=     name.replace("""norm.bias"""						,      """videomae.layernorm.bias"""    )
			if "head" in name and "decoder" not in name:
						A_	:						Optional[Any]	=     name.replace("""head"""						,      """classifier"""    )

			return name



def 	a			( lowerCamelCase__						,      lowerCamelCase__    ):
			'''simple docstring'''





			for key in orig_state_dict.copy().keys():
						A_	:						str	=     orig_state_dict.pop(lowerCamelCase__    )

						if key.startswith("""encoder."""    ):
									A_	:						Tuple	=     key.replace("""encoder."""						,      """"""    )

						if "qkv" in key:
									A_	:						Optional[int]	=     key.split("""."""    )
									if key.startswith("""decoder.blocks"""    ):
												A_	:						Union[str, Any]	=     config.decoder_hidden_size
												A_	:						Any	=     int(key_split[2]    )
												A_	:						int	=     """decoder.decoder_layers."""
												if "weight" in key:
															A_	:						Optional[Any]	=     val[:dim, :]
															A_	:						Any	=     val[dim : dim * 2, :]
															A_	:						Dict	=     val[-dim:, :]
									else:
												A_	:						List[Any]	=     config.hidden_size
												A_	:						List[Any]	=     int(key_split[1]    )
												A_	:						int	=     """videomae.encoder.layer."""
												if "weight" in key:
															A_	:						Any	=     val[:dim, :]
															A_	:						Union[str, Any]	=     val[dim : dim * 2, :]
															A_	:						List[str]	=     val[-dim:, :]
						else:
									A_	:						Union[str, Any]	=     val

			return orig_state_dict



def 	a			( ):
			'''simple docstring'''





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



def 	a			( lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__    ):
			'''simple docstring'''





			A_	:						Any	=     get_videomae_config(lowerCamelCase__    )

			if "finetuned" in model_name:
						A_	:						List[str]	=     VideoMAEForVideoClassification(lowerCamelCase__    )
			else:
						A_	:						Optional[Any]	=     VideoMAEForPreTraining(lowerCamelCase__    )

			# download original checkpoint, hosted on Google Drive
			A_	:						Optional[Any]	=     """pytorch_model.bin"""
			gdown.cached_download(lowerCamelCase__						,      lowerCamelCase__						,      quiet=lowerCamelCase__    )
			A_	:						Any	=     torch.load(lowerCamelCase__						,      map_location="""cpu"""    )
			if "model" in files:
						A_	:						Any	=     files["""model"""]
			else:
						A_	:						Dict	=     files["""module"""]
			A_	:						Any	=     convert_state_dict(lowerCamelCase__						,      lowerCamelCase__    )

			model.load_state_dict(lowerCamelCase__    )
			model.eval()

			# verify model on basic input
			A_	:						int	=     VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]						,      image_std=[0.5, 0.5, 0.5]    )
			A_	:						Union[str, Any]	=     prepare_video()
			A_	:						str	=     image_processor(lowerCamelCase__						,      return_tensors="""pt"""    )

			if "finetuned" not in model_name:
						A_	:						List[str]	=     hf_hub_download(repo_id="""hf-internal-testing/bool-masked-pos"""						,      filename="""bool_masked_pos.pt"""    )
						A_	:						Optional[Any]	=     torch.load(lowerCamelCase__    )

			A_	:						Dict	=     model(**lowerCamelCase__    )
			A_	:						List[Any]	=     outputs.logits

			A_	:						Any	=     [
			    """videomae-small-finetuned-kinetics""",
			    """videomae-small-finetuned-ssv2""",
			    # Kinetics-400 checkpoints (short = pretrained only for 800 epochs instead of 1600)
			    """videomae-base-short""",
			    """videomae-base-short-finetuned-kinetics""",
			    """videomae-base""",
			    """videomae-base-finetuned-kinetics""",
			    """videomae-large""",
			    """videomae-large-finetuned-kinetics""",
			    """videomae-huge-finetuned-kinetics""",
			    # Something-Something-v2 checkpoints (short = pretrained only for 800 epochs instead of 2400)
			    """videomae-base-short-ssv2""",
			    """videomae-base-short-finetuned-ssv2""",
			    """videomae-base-ssv2""",
			    """videomae-base-finetuned-ssv2""",
			]

			# NOTE: logits were tested with image_mean and image_std equal to [0.5, 0.5, 0.5] and [0.5, 0.5, 0.5]
			if model_name == "videomae-small-finetuned-kinetics":
						A_	:						str	=     torch.Size([1, 4_00]    )
						A_	:						Optional[Any]	=     torch.tensor([-0.9_291, -0.4_061, -0.9_307]    )
			elif model_name == "videomae-small-finetuned-ssv2":
						A_	:						str	=     torch.Size([1, 1_74]    )
						A_	:						Union[str, Any]	=     torch.tensor([0.2_671, -0.4_689, -0.8_235]    )
			elif model_name == "videomae-base":
						A_	:						Tuple	=     torch.Size([1, 14_08, 15_36]    )
						A_	:						List[str]	=     torch.tensor([[0.7_739, 0.7_968, 0.7_089], [0.6_701, 0.7_487, 0.6_209], [0.4_287, 0.5_158, 0.4_773]]    )
			elif model_name == "videomae-base-short":
						A_	:						Dict	=     torch.Size([1, 14_08, 15_36]    )
						A_	:						List[str]	=     torch.tensor([[0.7_994, 0.9_612, 0.8_508], [0.7_401, 0.8_958, 0.8_302], [0.5_862, 0.7_468, 0.7_325]]    )
						# we verified the loss both for normalized and unnormalized targets for this one
						A_	:						List[Any]	=     torch.tensor([0.5_142]    ) if config.norm_pix_loss else torch.tensor([0.6_469]    )
			elif model_name == "videomae-large":
						A_	:						str	=     torch.Size([1, 14_08, 15_36]    )
						A_	:						Dict	=     torch.tensor([[0.7_149, 0.7_997, 0.6_966], [0.6_768, 0.7_869, 0.6_948], [0.5_139, 0.6_221, 0.5_605]]    )
			elif model_name == "videomae-large-finetuned-kinetics":
						A_	:						int	=     torch.Size([1, 4_00]    )
						A_	:						Optional[Any]	=     torch.tensor([0.0_771, 0.0_011, -0.3_625]    )
			elif model_name == "videomae-huge-finetuned-kinetics":
						A_	:						Union[str, Any]	=     torch.Size([1, 4_00]    )
						A_	:						Optional[int]	=     torch.tensor([0.2_433, 0.1_632, -0.4_894]    )
			elif model_name == "videomae-base-short-finetuned-kinetics":
						A_	:						List[Any]	=     torch.Size([1, 4_00]    )
						A_	:						Optional[Any]	=     torch.tensor([0.6_588, 0.0_990, -0.2_493]    )
			elif model_name == "videomae-base-finetuned-kinetics":
						A_	:						Union[str, Any]	=     torch.Size([1, 4_00]    )
						A_	:						Tuple	=     torch.tensor([0.3_669, -0.0_688, -0.2_421]    )
			elif model_name == "videomae-base-short-ssv2":
						A_	:						Optional[Any]	=     torch.Size([1, 14_08, 15_36]    )
						A_	:						List[Any]	=     torch.tensor([[0.4_712, 0.5_296, 0.5_786], [0.2_278, 0.2_729, 0.4_026], [0.0_352, 0.0_730, 0.2_506]]    )
			elif model_name == "videomae-base-short-finetuned-ssv2":
						A_	:						Any	=     torch.Size([1, 1_74]    )
						A_	:						Any	=     torch.tensor([-0.0_537, -0.1_539, -0.3_266]    )
			elif model_name == "videomae-base-ssv2":
						A_	:						Dict	=     torch.Size([1, 14_08, 15_36]    )
						A_	:						Dict	=     torch.tensor([[0.8_131, 0.8_727, 0.8_546], [0.7_366, 0.9_377, 0.8_870], [0.5_935, 0.8_874, 0.8_564]]    )
			elif model_name == "videomae-base-finetuned-ssv2":
						A_	:						Any	=     torch.Size([1, 1_74]    )
						A_	:						str	=     torch.tensor([0.1_961, -0.8_337, -0.6_389]    )
			else:
						raise ValueError(f'Model name not supported. Should be one of {model_names}'    )

			# verify logits
			assert logits.shape == expected_shape
			if "finetuned" in model_name:
						assert torch.allclose(logits[0, :3]						,      lowerCamelCase__						,      atol=1E-4    )
			else:
						print("""Logits:"""						,      logits[0, :3, :3]    )
						assert torch.allclose(logits[0, :3, :3]						,      lowerCamelCase__						,      atol=1E-4    )
			print("""Logits ok!"""    )

			# verify loss, if applicable
			if model_name == "videomae-base-short":
						A_	:						Optional[int]	=     outputs.loss
						assert torch.allclose(lowerCamelCase__						,      lowerCamelCase__						,      atol=1E-4    )
						print("""Loss ok!"""    )

			if pytorch_dump_folder_path is not None:
						print(f'Saving model and image processor to {pytorch_dump_folder_path}'    )
						image_processor.save_pretrained(lowerCamelCase__    )
						model.save_pretrained(lowerCamelCase__    )

			if push_to_hub:
						print("""Pushing to the hub..."""    )
						model.push_to_hub(lowerCamelCase__						,      organization="""nielsr"""    )


if __name__ == "__main__":
						lowerCamelCase							:Tuple				    =					argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    '''--checkpoint_url''',
						    default='''https://drive.google.com/u/1/uc?id=1tEhLyskjb755TJ65ptsrafUG2llSwQE1&amp;export=download&amp;confirm=t&amp;uuid=aa3276eb-fb7e-482a-adec-dc7171df14c4''',
						    type=str,
						    help=(
						        '''URL of the original PyTorch checkpoint (on Google Drive) you\'d like to convert. Should be a direct'''
						        ''' download link.'''
						    ),
						)
						parser.add_argument(
						    '''--pytorch_dump_folder_path''',
						    default='''/Users/nielsrogge/Documents/VideoMAE/Test''',
						    type=str,
						    help='''Path to the output PyTorch model directory.''',
						)
						parser.add_argument('''--model_name''', default='''videomae-base''', type=str, help='''Name of the model.''')
						parser.add_argument(
						    '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.'''
						)

						lowerCamelCase							:Union[str, Any]				    =					parser.parse_args()
						convert_videomae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)