


'''simple docstring'''
import logging
import math
import os
from dataclasses import dataclass, field
from glob import glob
from typing import Optional

from torch.utils.data import ConcatDataset

import transformers
from transformers import (
    CONFIG_MAPPING,
    MODEL_WITH_LM_HEAD_MAPPING,
    AutoConfig,
    AutoModelWithLMHead,
    AutoTokenizer,
    DataCollatorForLanguageModeling,
    DataCollatorForPermutationLanguageModeling,
    DataCollatorForWholeWordMask,
    HfArgumentParser,
    LineByLineTextDataset,
    LineByLineWithRefDataset,
    PreTrainedTokenizer,
    TextDataset,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


UpperCamelCase__          = logging.getLogger(__name__)


UpperCamelCase__          = list(MODEL_WITH_LM_HEAD_MAPPING.keys())
UpperCamelCase__          = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)




@dataclass
class      lowerCamelCase_  :
      lowerCAmelCase__							=	field(
          default=__a	,			metadata={
              'help': (
                  'The model checkpoint for weights initialization. Leave None if you want to train a model from'
                  ' scratch.'
              )
          }	,			)
      lowerCAmelCase__							=	field(
          default=__a	,			metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(__a )}	,			)
      lowerCAmelCase__							=	field(
          default=__a	,			metadata={'help': 'Pretrained config name or path if not the same as model_name'} )
      lowerCAmelCase__							=	field(
          default=__a	,			metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} )
      lowerCAmelCase__							=	field(
          default=__a	,			metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}	,			)




@dataclass
class      lowerCamelCase_  :
      lowerCAmelCase__							=	field(
          default=__a	,			metadata={'help': 'The input training data file (a text file).'} )
      lowerCAmelCase__							=	field(
          default=__a	,			metadata={
              'help': (
                  'The input training data files (multiple files in glob format). '
                  'Very often splitting large files to smaller files can prevent tokenizer going out of memory'
              )
          }	,			)
      lowerCAmelCase__							=	field(
          default=__a	,			metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'}	,			)
      lowerCAmelCase__							=	field(
          default=__a	,			metadata={'help': 'An optional input train ref data file for whole word mask in Chinese.'}	,			)
      lowerCAmelCase__							=	field(
          default=__a	,			metadata={'help': 'An optional input eval ref data file for whole word mask in Chinese.'}	,			)
      lowerCAmelCase__							=	field(
          default=__a	,			metadata={'help': 'Whether distinct lines of text in the dataset are to be handled as distinct sequences.'}	,			)

      lowerCAmelCase__							=	field(
          default=__a	,			metadata={'help': 'Train with masked-language modeling loss instead of language modeling.'} )
      lowerCAmelCase__							=	field(default=__a	,			metadata={'help': 'Whether ot not to use whole word mask.'} )
      lowerCAmelCase__							=	field(
          default=0.15	,			metadata={'help': 'Ratio of tokens to mask for masked language modeling loss'} )
      lowerCAmelCase__							=	field(
          default=1 / 6	,			metadata={
              'help': (
                  'Ratio of length of a span of masked tokens to surrounding context length for permutation language'
                  ' modeling.'
              )
          }	,			)
      lowerCAmelCase__							=	field(
          default=5	,			metadata={'help': 'Maximum length of a span of masked tokens for permutation language modeling.'} )

      lowerCAmelCase__							=	field(
          default=-1	,			metadata={
              'help': (
                  'Optional input sequence length after tokenization.'
                  'The training dataset will be truncated in block of this size for training.'
                  'Default to the model max input length for single sentence inputs (take into account special tokens).'
              )
          }	,			)
      lowerCAmelCase__							=	field(
          default=__a	,			metadata={'help': 'Overwrite the cached training and evaluation sets'} )





def    a__			(   lowerCAmelCase__    ,   lowerCAmelCase__    ,   lowerCAmelCase__ = False    ,   lowerCAmelCase__ = None    ,   )       ->      Tuple:
    def _dataset(lowerCAmelCase__    ,   lowerCAmelCase__=None		):
        if args.line_by_line:
            if ref_path is not None:
                if not args.whole_word_mask or not args.mlm:
                    raise ValueError('''You need to set world whole masking and mlm to True for Chinese Whole Word Mask'''		)
                return LineByLineWithRefDataset(
                    tokenizer=lowerCAmelCase__    ,   file_path=lowerCAmelCase__    ,   block_size=args.block_size    ,   ref_path=lowerCAmelCase__    ,   )

            return LineByLineTextDataset(tokenizer=lowerCAmelCase__    ,   file_path=lowerCAmelCase__    ,   block_size=args.block_size		)
        else:
            return TextDataset(
                tokenizer=lowerCAmelCase__    ,   file_path=lowerCAmelCase__    ,   block_size=args.block_size    ,   overwrite_cache=args.overwrite_cache    ,   cache_dir=lowerCAmelCase__    ,   )

    if evaluate:
        return _dataset(args.eval_data_file    ,   args.eval_ref_file		)
    elif args.train_data_files:
        return ConcatDataset([_dataset(lowerCAmelCase__		) for f in glob(args.train_data_files		)]		)
    else:
        return _dataset(args.train_data_file    ,   args.train_ref_file		)





def    a__			(   )       ->      Optional[int]:
    # See all possible arguments in src/transformers/training_args.py
    # or by passing the --help flag to this script.
    # We now keep distinct sets of args, for a cleaner separation of concerns.

    UpperCAmelCase__     :						Dict						=							HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)		)
    UpperCAmelCase__		,		UpperCAmelCase__		,		UpperCAmelCase__     :						int						=							parser.parse_args_into_dataclasses()

    if data_args.eval_data_file is None and training_args.do_eval:
        raise ValueError(
            '''Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file '''
            '''or remove the --do_eval argument.'''		)
    if (
        os.path.exists(training_args.output_dir		)
        and os.listdir(training_args.output_dir		)
        and training_args.do_train
        and not training_args.overwrite_output_dir
    ):
        raise ValueError(
            F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use"""
            ''' --overwrite_output_dir to overcome.'''		)

    # Setup logging
    logging.basicConfig(
        format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''    ,   datefmt='''%m/%d/%Y %H:%M:%S'''    ,   level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN    ,   )
    logger.warning(
        '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s'''    ,   training_args.local_rank    ,   training_args.device    ,   training_args.n_gpu    ,   bool(training_args.local_rank != -1		)    ,   training_args.fpaa    ,   )
    # Set the verbosity to info of the Transformers logger (on main process only):
    if is_main_process(training_args.local_rank		):
        transformers.utils.logging.set_verbosity_info()
        transformers.utils.logging.enable_default_handler()
        transformers.utils.logging.enable_explicit_format()
    logger.info('''Training/evaluation parameters %s'''    ,   lowerCAmelCase__		)

    # Set seed
    set_seed(training_args.seed		)

    # Load pretrained model and tokenizer
    #
    # Distributed training:
    # The .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.

    if model_args.config_name:
        UpperCAmelCase__     :						Any						=							AutoConfig.from_pretrained(model_args.config_name    ,   cache_dir=model_args.cache_dir		)
    elif model_args.model_name_or_path:
        UpperCAmelCase__     :						Optional[Any]						=							AutoConfig.from_pretrained(model_args.model_name_or_path    ,   cache_dir=model_args.cache_dir		)
    else:
        UpperCAmelCase__     :						List[Any]						=							CONFIG_MAPPING[model_args.model_type]()
        logger.warning('''You are instantiating a new config instance from scratch.'''		)

    if model_args.tokenizer_name:
        UpperCAmelCase__     :						str						=							AutoTokenizer.from_pretrained(model_args.tokenizer_name    ,   cache_dir=model_args.cache_dir		)
    elif model_args.model_name_or_path:
        UpperCAmelCase__     :						Optional[int]						=							AutoTokenizer.from_pretrained(model_args.model_name_or_path    ,   cache_dir=model_args.cache_dir		)
    else:
        raise ValueError(
            '''You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another'''
            ''' script, save it,and load it from here, using --tokenizer_name'''		)

    if model_args.model_name_or_path:
        UpperCAmelCase__     :						Dict						=							AutoModelWithLMHead.from_pretrained(
            model_args.model_name_or_path    ,   from_tf=bool('''.ckpt''' in model_args.model_name_or_path		)    ,   config=lowerCAmelCase__    ,   cache_dir=model_args.cache_dir    ,   )
    else:
        logger.info('''Training new model from scratch'''		)
        UpperCAmelCase__     :						List[Any]						=							AutoModelWithLMHead.from_config(lowerCAmelCase__		)

    model.resize_token_embeddings(len(lowerCAmelCase__		)		)

    if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm:
        raise ValueError(
            '''BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the'''
            '''--mlm flag (masked language modeling).'''		)

    if data_args.block_size <= 0:
        UpperCAmelCase__     :						str						=							tokenizer.max_len
        # Our input block size will be the max possible for the model
    else:
        UpperCAmelCase__     :						Union[str, Any]						=							min(data_args.block_size    ,   tokenizer.max_len		)

    # Get datasets

    UpperCAmelCase__     :						Union[str, Any]						=							(
        get_dataset(lowerCAmelCase__    ,   tokenizer=lowerCAmelCase__    ,   cache_dir=model_args.cache_dir		) if training_args.do_train else None
    )
    UpperCAmelCase__     :						List[Any]						=							(
        get_dataset(lowerCAmelCase__    ,   tokenizer=lowerCAmelCase__    ,   evaluate=lowerCAmelCase__    ,   cache_dir=model_args.cache_dir		)
        if training_args.do_eval
        else None
    )
    if config.model_type == "xlnet":
        UpperCAmelCase__     :						str						=							DataCollatorForPermutationLanguageModeling(
            tokenizer=lowerCAmelCase__    ,   plm_probability=data_args.plm_probability    ,   max_span_length=data_args.max_span_length    ,   )
    else:
        if data_args.mlm and data_args.whole_word_mask:
            UpperCAmelCase__     :						Optional[int]						=							DataCollatorForWholeWordMask(
                tokenizer=lowerCAmelCase__    ,   mlm_probability=data_args.mlm_probability		)
        else:
            UpperCAmelCase__     :						Optional[int]						=							DataCollatorForLanguageModeling(
                tokenizer=lowerCAmelCase__    ,   mlm=data_args.mlm    ,   mlm_probability=data_args.mlm_probability		)

    # Initialize our Trainer
    UpperCAmelCase__     :						Union[str, Any]						=							Trainer(
        model=lowerCAmelCase__    ,   args=lowerCAmelCase__    ,   data_collator=lowerCAmelCase__    ,   train_dataset=lowerCAmelCase__    ,   eval_dataset=lowerCAmelCase__    ,   prediction_loss_only=lowerCAmelCase__    ,   )

    # Training
    if training_args.do_train:
        UpperCAmelCase__     :						Dict						=							(
            model_args.model_name_or_path
            if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path		)
            else None
        )
        trainer.train(model_path=lowerCAmelCase__		)
        trainer.save_model()
        # For convenience, we also re-save the tokenizer to the same directory,
        # so that you can share your model easily on huggingface.co/models =)
        if trainer.is_world_master():
            tokenizer.save_pretrained(training_args.output_dir		)

    # Evaluation
    UpperCAmelCase__     :						Optional[Any]						=							{}
    if training_args.do_eval:
        logger.info('''*** Evaluate ***'''		)

        UpperCAmelCase__     :						Tuple						=							trainer.evaluate()

        UpperCAmelCase__     :						Any						=							math.exp(eval_output['''eval_loss''']		)
        UpperCAmelCase__     :						List[str]						=							{'''perplexity''': perplexity}

        UpperCAmelCase__     :						List[str]						=							os.path.join(training_args.output_dir    ,   '''eval_results_lm.txt'''		)
        if trainer.is_world_master():
            with open(lowerCAmelCase__    ,   '''w'''		) as writer:
                logger.info('''***** Eval results *****'''		)
                for key in sorted(result.keys()		):
                    logger.info('''  %s = %s'''    ,   lowerCAmelCase__    ,   str(result[key]		)		)
                    writer.write('''%s = %s\n''' % (key, str(result[key]		))		)

        results.update(lowerCAmelCase__		)

    return results





def    a__			(   lowerCAmelCase__		)       ->      str:
    # For xla_spawn (TPUs)
    main()


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




