"""simple docstring"""
import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


a_ 	=     logging.get_logger(__name__)

a_ 	=     list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
a_ 	=     tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)




@dataclass
class        __snake_case	:
      a__				=		field(
          default=__lowerCAmelCase	,				metadata={"""help""": """Model type selected in the list: """ + """, """.join(__lowerCAmelCase    )}    )
      a__				=		field(
          default=__lowerCAmelCase	,				metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""}    )
      a__				=		field(
          default=128	,				metadata={
              """help""": (
                  """The maximum total input sequence length after tokenization. Sequences longer """
                  """than this will be truncated, sequences shorter will be padded."""
              )
          }	,				)
      a__				=		field(
          default=128	,				metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""}	,				)
      a__				=		field(
          default=64	,				metadata={
              """help""": (
                  """The maximum number of tokens for the question. Questions longer than this will """
                  """be truncated to this length."""
              )
          }	,				)
      a__				=		field(
          default=30	,				metadata={
              """help""": (
                  """The maximum length of an answer that can be generated. This is needed because the start """
                  """and end predictions are not conditioned on one another."""
              )
          }	,				)
      a__				=		field(
          default=__lowerCAmelCase	,				metadata={"""help""": """Overwrite the cached training and evaluation sets"""}    )
      a__				=		field(
          default=__lowerCAmelCase	,				metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""}    )
      a__				=		field(
          default=0.0	,				metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}    )
      a__				=		field(
          default=20	,				metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}    )
      a__				=		field(
          default=0	,				metadata={
              """help""": (
                  """language id of input for language-specific xlm models (see"""
                  """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"""
              )
          }	,				)
      a__				=		field(default=1	,				metadata={"""help""": """multiple threads for converting example to features"""}    )







class        __snake_case	(					__lowerCAmelCase    ):
      a__				=		"""train"""
      a__				=		"""dev"""







class        __snake_case	(					__lowerCAmelCase    ):
      a__				=		42
      a__				=		42
      a__				=		42
      a__				=		42



      def __init__(						self   ,      lowercase   ,      lowercase   ,      lowercase = None   ,      lowercase = Split.train   ,      lowercase = False   ,      lowercase = None   ,      lowercase = "pt"   ,      )     ->      Optional[int]:





        '''simple docstring'''





        a__:					Optional[Any]      							=     args
        a__:					str      							=     is_language_sensitive
        a__:					Union[str, Any]      							=     SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
        if isinstance(_a   ,      _a):
          try:
            a__:					int      							=     Split[mode]
          except KeyError:
            raise KeyError('mode is not a valid split name')
        a__:					List[str]      							=     mode
        # Load data features from cache or dataset file
        a__:					Union[str, Any]      							=     "v2" if args.version_2_with_negative else "v1"
        a__:					List[str]      							=     os.path.join(
            cache_dir if cache_dir is not None else args.data_dir   ,      f'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}'   ,      )

        # Make sure only the first process in distributed training processes the dataset,
        # and the others will use the cache.
        a__:					Optional[Any]      							=     cached_features_file + ".lock"
        with FileLock(_a):
          if os.path.exists(_a) and not args.overwrite_cache:
            a__:					List[Any]      							=     time.time()
            a__:					Dict      							=     torch.load(_a)

            # Legacy cache files have only features, while new cache files
            # will have dataset and examples also.
            a__:					Dict      							=     self.old_features["features"]
            a__:					Optional[Any]      							=     self.old_features.get('dataset'   ,      _a)
            a__:					str      							=     self.old_features.get('examples'   ,      _a)
            logger.info(
                f'Loading features from cached file {cached_features_file} [took %.3f s]'   ,      time.time() - start)

            if self.dataset is None or self.examples is None:
              logger.warning(
                  f'Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'
                  ' future run')
          else:
            if mode == Split.dev:
              a__:					Optional[int]      							=     self.processor.get_dev_examples(args.data_dir)
            else:
              a__:					Optional[Any]      							=     self.processor.get_train_examples(args.data_dir)

            a__:					List[Any]      							=     squad_convert_examples_to_features(
                examples=self.examples   ,      tokenizer=_a   ,      max_seq_length=args.max_seq_length   ,      doc_stride=args.doc_stride   ,      max_query_length=args.max_query_length   ,      is_training=mode == Split.train   ,      threads=args.threads   ,      return_dataset=_a   ,      )

            a__:					Any      							=     time.time()
            torch.save(
                {'features': self.features, 'dataset': self.dataset, 'examples': self.examples}   ,      _a   ,      )
            # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
            logger.info(
                f'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]')



      def __len__(						self)     ->      Optional[Any]:





        '''simple docstring'''





        return len(self.features)



      def __getitem__(						self   ,      lowercase)     ->      Any:





        '''simple docstring'''





        a__:					List[Any]      							=     self.features[i]

        a__:					Union[str, Any]      							=     torch.tensor(feature.input_ids   ,      dtype=torch.long)
        a__:					Dict      							=     torch.tensor(feature.attention_mask   ,      dtype=torch.long)
        a__:					List[str]      							=     torch.tensor(feature.token_type_ids   ,      dtype=torch.long)
        a__:					Tuple      							=     torch.tensor(feature.cls_index   ,      dtype=torch.long)
        a__:					str      							=     torch.tensor(feature.p_mask   ,      dtype=torch.float)
        a__:					Dict      							=     torch.tensor(feature.is_impossible   ,      dtype=torch.float)

        a__:					Union[str, Any]      							=     {
            "input_ids": input_ids,
            "attention_mask": attention_mask,
            "token_type_ids": token_type_ids,
        }

        if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
          del inputs["token_type_ids"]

        if self.args.model_type in ["xlnet", "xlm"]:
          inputs.update({'cls_index': cls_index, 'p_mask': p_mask})
          if self.args.version_2_with_negative:
            inputs.update({'is_impossible': is_impossible})
          if self.is_language_sensitive:
            inputs.update({'langs': (torch.ones(input_ids.shape   ,      dtype=torch.intaa) * self.args.lang_id)})

        if self.mode == Split.train:
          a__:					Optional[int]      							=     torch.tensor(feature.start_position   ,      dtype=torch.long)
          a__:					List[Any]      							=     torch.tensor(feature.end_position   ,      dtype=torch.long)
          inputs.update({'start_positions': start_positions, 'end_positions': end_positions})

        return inputs



"""simple docstring"""
import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import VideoMAEConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import (
     MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
     VideoMAEForPreTraining,
     VideoMAEForVideoClassification,
     VideoMAEModel,
 )
 from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from transformers import VideoMAEImageProcessor




class        __snake_case	:



      def __init__(						self   ,      lowercase   ,      lowercase=13   ,      lowercase=10   ,      lowercase=3   ,      lowercase=2   ,      lowercase=2   ,      lowercase=2   ,      lowercase=True   ,      lowercase=True   ,      lowercase=32   ,      lowercase=5   ,      lowercase=4   ,      lowercase=37   ,      lowercase="gelu"   ,      lowercase=0.1   ,      lowercase=0.1   ,      lowercase=10   ,      lowercase=0.02   ,      lowercase=0.9   ,      lowercase=None   ,      )     ->      Optional[Any]:





        '''simple docstring'''





        a__:					int      							=     parent
        a__:					int      							=     batch_size
        a__:					int      							=     image_size
        a__:					Optional[int]      							=     num_channels
        a__:					List[str]      							=     patch_size
        a__:					List[str]      							=     tubelet_size
        a__:					Any      							=     num_frames
        a__:					Any      							=     is_training
        a__:					Dict      							=     use_labels
        a__:					Optional[Any]      							=     hidden_size
        a__:					Optional[int]      							=     num_hidden_layers
        a__:					Optional[Any]      							=     num_attention_heads
        a__:					Optional[Any]      							=     intermediate_size
        a__:					Any      							=     hidden_act
        a__:					Dict      							=     hidden_dropout_prob
        a__:					Union[str, Any]      							=     attention_probs_dropout_prob
        a__:					List[Any]      							=     type_sequence_label_size
        a__:					Optional[Any]      							=     initializer_range
        a__:					List[str]      							=     mask_ratio
        a__:					Union[str, Any]      							=     scope

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

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



      def   lowerCamelCase_       (						self)     ->      Optional[Any]:





        '''simple docstring'''





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

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

        a__:					Optional[int]      							=     self.get_config()

        return config, pixel_values, labels



      def   lowerCamelCase_       (						self)     ->      Union[str, Any]:





        '''simple docstring'''





        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=lowercase   ,      initializer_range=self.initializer_range   ,      )



      def   lowerCamelCase_       (						self   ,      lowercase   ,      lowercase   ,      lowercase)     ->      str:





        '''simple docstring'''





        a__:					Any      							=     VideoMAEModel(config=lowercase)
        model.to(lowercase)
        model.eval()
        a__:					Optional[Any]      							=     model(lowercase)
        self.parent.assertEqual(result.last_hidden_state.shape   ,      (self.batch_size, self.seq_length, self.hidden_size))



      def   lowerCamelCase_       (						self   ,      lowercase   ,      lowercase   ,      lowercase)     ->      int:





        '''simple docstring'''





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

        a__:					Union[str, Any]      							=     model(lowercase   ,      lowercase)
        # model only returns predictions for masked patches
        a__:					List[str]      							=     mask.sum().item()
        a__:					str      							=     3 * self.tubelet_size * self.patch_size**2
        self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, num_masked_patches, decoder_num_labels))



      def   lowerCamelCase_       (						self)     ->      int:





        '''simple docstring'''





        a__:					Dict      							=     self.prepare_config_and_inputs()
        a__							,   a__							,   a__:					Dict      							=     config_and_inputs
        a__:					Any      							=     {'pixel_values': pixel_values}
        return config, inputs_dict







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

      a__				=		False
      a__				=		False
      a__				=		False
      a__				=		False



      def   lowerCamelCase_       (						self)     ->      Tuple:





        '''simple docstring'''





        a__:					List[str]      							=     VideoMAEModelTester(self)
        a__:					str      							=     ConfigTester(self   ,      config_class=lowercase   ,      has_text_modality=lowercase   ,      hidden_size=37)



      def   lowerCamelCase_       (						self   ,      lowercase   ,      lowercase   ,      lowercase=False)     ->      Any:





        '''simple docstring'''





        a__:					Optional[int]      							=     copy.deepcopy(lowercase)

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

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

        return inputs_dict



      def   lowerCamelCase_       (						self)     ->      Optional[int]:





        '''simple docstring'''





        self.config_tester.run_common_tests()



      @unittest.skip(reason='VideoMAE does not use inputs_embeds')
      def   lowerCamelCase_       (						self)     ->      Optional[Any]:





        '''simple docstring'''





        pass



      def   lowerCamelCase_       (						self)     ->      int:





        '''simple docstring'''





        a__							,   a__:					Any      							=     self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          a__:					Union[str, Any]      							=     model_class(lowercase)
          self.assertIsInstance(model.get_input_embeddings()   ,      (nn.Module))
          a__:					str      							=     model.get_output_embeddings()
          self.assertTrue(x is None or isinstance(lowercase   ,      nn.Linear))



      def   lowerCamelCase_       (						self)     ->      List[Any]:





        '''simple docstring'''





        a__							,   a__:					Union[str, Any]      							=     self.model_tester.prepare_config_and_inputs_for_common()

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

          a__:					Tuple      							=     ['pixel_values']
          self.assertListEqual(arg_names[:1]   ,      lowercase)



      def   lowerCamelCase_       (						self)     ->      Union[str, Any]:





        '''simple docstring'''





        a__:					Dict      							=     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase)



      def   lowerCamelCase_       (						self)     ->      List[str]:





        '''simple docstring'''





        a__:					Optional[Any]      							=     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_pretraining(*lowercase)



      @slow
      def   lowerCamelCase_       (						self)     ->      Union[str, Any]:





        '''simple docstring'''





        for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          a__:					int      							=     VideoMAEModel.from_pretrained(lowercase)
          self.assertIsNotNone(lowercase)



      def   lowerCamelCase_       (						self)     ->      Union[str, Any]:





        '''simple docstring'''





        if not self.has_attentions:
          pass

        else:
          a__							,   a__:					Any      							=     self.model_tester.prepare_config_and_inputs_for_common()
          a__:					str      							=     True

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

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

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

            self.assertListEqual(
                list(attentions[0].shape[-3:])   ,      [self.model_tester.num_attention_heads, seq_len, seq_len]   ,      )
            a__:					Optional[Any]      							=     len(lowercase)

            # Check attention is always last and order is fine
            a__:					str      							=     True
            a__:					Dict      							=     True
            a__:					Tuple      							=     model_class(lowercase)
            model.to(lowercase)
            model.eval()
            with torch.no_grad():
              a__:					Optional[Any]      							=     model(**self._prepare_for_class(lowercase   ,      lowercase))

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

            a__:					int      							=     outputs.attentions

            self.assertEqual(len(lowercase)   ,      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   lowerCamelCase_       (						self)     ->      List[Any]:





        '''simple docstring'''





        def check_hidden_states_output(lowercase   ,      lowercase   ,      lowercase):
          a__:					Union[str, Any]      							=     model_class(lowercase)
          model.to(lowercase)
          model.eval()

          with torch.no_grad():
            a__:					Tuple      							=     model(**self._prepare_for_class(lowercase   ,      lowercase))

          a__:					Dict      							=     outputs.hidden_states
          a__:					Union[str, Any]      							=     self.model_tester.num_hidden_layers + 1
          self.assertEqual(len(lowercase)   ,      lowercase)

          a__:					Union[str, Any]      							=     self.model_tester.seq_length - self.model_tester.num_masks
          a__:					Optional[Any]      							=     num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length

          self.assertListEqual(
              list(hidden_states[0].shape[-2:])   ,      [seq_length, self.model_tester.hidden_size]   ,      )

        a__							,   a__:					List[str]      							=     self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          a__:					Dict      							=     True
          check_hidden_states_output(lowercase   ,      lowercase   ,      lowercase)

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

          check_hidden_states_output(lowercase   ,      lowercase   ,      lowercase)



      @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.')
      def   lowerCamelCase_       (						self)     ->      int:





        '''simple docstring'''





        pass







def 						__a       (     )     ->List[Any]:
  a__:					List[str]      							=     hf_hub_download(
      repo_id='hf-internal-testing/spaghetti-video'		,					filename='eating_spaghetti.npy'		,					repo_type='dataset'       )
  a__:					Dict      							=     np.load(_SCREAMING_SNAKE_CASE       )
  return list(_SCREAMING_SNAKE_CASE       )




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



      @cached_property
      def   lowerCamelCase_       (						self)     ->      str:





        '''simple docstring'''





        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   lowerCamelCase_       (						self)     ->      Union[str, Any]:





        '''simple docstring'''





        a__:					Dict      							=     VideoMAEForVideoClassification.from_pretrained('MCG-NJU/videomae-base-finetuned-kinetics').to(
            lowercase)

        a__:					Dict      							=     self.default_image_processor
        a__:					str      							=     prepare_video()
        a__:					Tuple      							=     image_processor(lowercase   ,      return_tensors='pt').to(lowercase)

        # forward pass
        with torch.no_grad():
          a__:					List[Any]      							=     model(**lowercase)

        # verify the logits
        a__:					str      							=     torch.Size((1, 4_00))
        self.assertEqual(outputs.logits.shape   ,      lowercase)

        a__:					Optional[Any]      							=     torch.tensor([0.3669, -0.0688, -0.2421]).to(lowercase)

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



      @slow
      def   lowerCamelCase_       (						self)     ->      Dict:





        '''simple docstring'''





        a__:					Tuple      							=     VideoMAEForPreTraining.from_pretrained('MCG-NJU/videomae-base-short').to(lowercase)

        a__:					Optional[Any]      							=     self.default_image_processor
        a__:					List[Any]      							=     prepare_video()
        a__:					Union[str, Any]      							=     image_processor(lowercase   ,      return_tensors='pt').to(lowercase)

        # add boolean mask, indicating which patches to mask
        a__:					Optional[Any]      							=     hf_hub_download(repo_id='hf-internal-testing/bool-masked-pos'   ,      filename='bool_masked_pos.pt')
        a__:					Any      							=     torch.load(lowercase)

        # forward pass
        with torch.no_grad():
          a__:					Any      							=     model(**lowercase)

        # verify the logits
        a__:					Union[str, Any]      							=     torch.Size([1, 14_08, 15_36])
        a__:					Union[str, Any]      							=     torch.tensor(
            [[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]]   ,      device=lowercase)
        self.assertEqual(outputs.logits.shape   ,      lowercase)
        self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]   ,      lowercase   ,      atol=1e-4))

        # verify the loss (`config.norm_pix_loss` = `True`)
        a__:					Optional[int]      							=     torch.tensor([0.5142]   ,      device=lowercase)
        self.assertTrue(torch.allclose(outputs.loss   ,      lowercase   ,      atol=1e-4))

        # verify the loss (`config.norm_pix_loss` = `False`)
        a__:					int      							=     VideoMAEForPreTraining.from_pretrained('MCG-NJU/videomae-base-short'   ,      norm_pix_loss=lowercase).to(
            lowercase)

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

        a__:					Optional[int]      							=     torch.tensor(torch.tensor([0.6469])   ,      device=lowercase)
        self.assertTrue(torch.allclose(outputs.loss   ,      lowercase   ,      atol=1e-4))


