



import argparse
import os

import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType


########################################################################
# This is a fully working simple example to use Accelerate
# and perform gradient accumulation
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
#   - single CPU or single GPU
#   - multi GPUS (using PyTorch distributed mode)
#   - (multi) TPUs
#   - fp16 (mixed-precision) or fp32 (normal precision)
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################


lowercase_													=      16
lowercase_													=      32






def        __lowerCAmelCase		(	__lowerCamelCase						:     Accelerator					, __lowerCamelCase						:     int = 16						)	->    List[Any]:
					__lowerCAmelCase						 =AutoTokenizer.from_pretrained("""bert-base-cased"""						)
					__lowerCAmelCase						 =load_dataset("""glue"""					, """mrpc"""						)

					def tokenize_function(__lowerCamelCase						:     int						):
										# max_length=None => use the model max length (it's actually the default)
										__lowerCAmelCase						 =tokenizer(examples["""sentence1"""]					, examples["""sentence2"""]					, truncation=__lowerCamelCase					, max_length=__lowerCamelCase						)
										return outputs

					# Apply the method we just defined to all the examples in all the splits of the dataset
					# starting with the main process first:
					with accelerator.main_process_first():
										__lowerCAmelCase						 =datasets.map(
										    __lowerCamelCase					, batched=__lowerCamelCase					, remove_columns=["""idx""", """sentence1""", """sentence2"""]					, )

					# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
					# transformers library
					__lowerCAmelCase						 =tokenized_datasets.rename_column("""label"""					, """labels"""						)

					def collate_fn(__lowerCamelCase						:     Optional[int]						):
										# On TPU it's best to pad everything to the same length or training will be very slow.
										__lowerCAmelCase						 =128 if accelerator.distributed_type == DistributedType.TPU else None
										# When using mixed precision we want round multiples of 8/16
										if accelerator.mixed_precision == "fp8":
															__lowerCAmelCase						 =16
										elif accelerator.mixed_precision != "no":
															__lowerCAmelCase						 =8
										else:
															__lowerCAmelCase						 =None

										return tokenizer.pad(
										    __lowerCamelCase					, padding="""longest"""					, max_length=__lowerCamelCase					, pad_to_multiple_of=__lowerCamelCase					, return_tensors="""pt"""					, )

					# Instantiate dataloaders.
					__lowerCAmelCase						 =DataLoader(
					    tokenized_datasets["""train"""]					, shuffle=__lowerCamelCase					, collate_fn=__lowerCamelCase					, batch_size=__lowerCamelCase						)
					__lowerCAmelCase						 =DataLoader(
					    tokenized_datasets["""validation"""]					, shuffle=__lowerCamelCase					, collate_fn=__lowerCamelCase					, batch_size=__lowerCamelCase						)

					return train_dataloader, eval_dataloader


# For testing only
if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1":
				from accelerate.test_utils.training import mocked_dataloaders

				lowercase_													=      mocked_dataloaders  # noqa: F811






def        __lowerCAmelCase		(	__lowerCamelCase						:     List[str]					, __lowerCamelCase						:     Any						)	->    Union[str, Any]:
					# For testing only
					if os.environ.get("""TESTING_MOCKED_DATALOADERS"""					, __lowerCamelCase						) == "1":
										__lowerCAmelCase						 =2
					# New Code #
					__lowerCAmelCase						 =int(args.gradient_accumulation_steps						)
					# Initialize accelerator
					__lowerCAmelCase						 =Accelerator(
					    cpu=args.cpu					, mixed_precision=args.mixed_precision					, gradient_accumulation_steps=__lowerCamelCase						)
					if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1:
										raise NotImplementedError(
										    """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`"""						)
					# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
					__lowerCAmelCase						 =config["""lr"""]
					__lowerCAmelCase						 =int(config["""num_epochs"""]						)
					__lowerCAmelCase						 =int(config["""seed"""]						)
					__lowerCAmelCase						 =int(config["""batch_size"""]						)

					__lowerCAmelCase						 =evaluate.load("""glue"""					, """mrpc"""						)

					set_seed(__lowerCamelCase						)
					__lowerCAmelCase ,						__lowerCAmelCase						 =get_dataloaders(__lowerCamelCase					, __lowerCamelCase						)
					# Instantiate the model (we build the model here so that the seed also control new weights initialization)
					__lowerCAmelCase						 =AutoModelForSequenceClassification.from_pretrained("""bert-base-cased"""					, return_dict=__lowerCamelCase						)

					# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
					# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
					# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
					__lowerCAmelCase						 =model.to(accelerator.device						)

					# Instantiate optimizer
					__lowerCAmelCase						 =AdamW(params=model.parameters()					, lr=__lowerCamelCase						)

					# Instantiate scheduler
					__lowerCAmelCase						 =get_linear_schedule_with_warmup(
					    optimizer=__lowerCamelCase					, num_warmup_steps=100					, num_training_steps=(len(__lowerCamelCase						) * num_epochs)					, )

					# Prepare everything
					# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
					# prepare method.
					__lowerCAmelCase ,						__lowerCAmelCase ,						__lowerCAmelCase ,						__lowerCAmelCase ,						__lowerCAmelCase						 =accelerator.prepare(
					    __lowerCamelCase					, __lowerCamelCase					, __lowerCamelCase					, __lowerCamelCase					, __lowerCamelCase						)

					# Now we train the model
					for epoch in range(__lowerCamelCase						):
										model.train()
										for step, batch in enumerate(__lowerCamelCase						):
															# We could avoid this line since we set the accelerator with `device_placement=True`.
															batch.to(accelerator.device						)
															# New code #
															# We use the new `accumulate` context manager to perform gradient accumulation
															# We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests.
															with accelerator.accumulate(__lowerCamelCase						):
																				__lowerCAmelCase						 =model(**__lowerCamelCase						)
																				__lowerCAmelCase						 =output.loss
																				accelerator.backward(__lowerCamelCase						)
																				optimizer.step()
																				lr_scheduler.step()
																				optimizer.zero_grad()

										model.eval()
										for step, batch in enumerate(__lowerCamelCase						):
															# We could avoid this line since we set the accelerator with `device_placement=True`.
															batch.to(accelerator.device						)
															with torch.no_grad():
																				__lowerCAmelCase						 =model(**__lowerCamelCase						)
															__lowerCAmelCase						 =outputs.logits.argmax(dim=-1						)
															__lowerCAmelCase ,						__lowerCAmelCase						 =accelerator.gather_for_metrics((predictions, batch["""labels"""])						)
															metric.add_batch(
															    predictions=__lowerCamelCase					, references=__lowerCamelCase					, )

										__lowerCAmelCase						 =metric.compute()
										# Use accelerator.print to print only on the main process.
										accelerator.print(f"""epoch {epoch}:"""					, __lowerCamelCase						)






def        __lowerCAmelCase		(	)	->    Optional[Any]:
					__lowerCAmelCase						 =argparse.ArgumentParser(description="""Simple example of training script."""						)
					parser.add_argument(
					    """--mixed_precision"""					, type=__lowerCamelCase					, default=__lowerCamelCase					, choices=["""no""", """fp16""", """bf16""", """fp8"""]					, help="""Whether to use mixed precision. Choose"""
					    """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."""
					    """and an Nvidia Ampere GPU."""					, )
					# New Code #
					parser.add_argument(
					    """--gradient_accumulation_steps"""					, type=__lowerCamelCase					, default=1					, help="""The number of minibatches to be ran before gradients are accumulated."""					, )
					parser.add_argument("""--cpu"""					, action="""store_true"""					, help="""If passed, will train on the CPU."""						)
					__lowerCAmelCase						 =parser.parse_args()
					__lowerCAmelCase						 ={"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16}
					training_function(__lowerCamelCase					, __lowerCamelCase						)


if __name__ == "__main__":
				main()









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))




