


'''simple docstring'''



import logging
import os
import threading
import time


try:
      import warnings
except ImportError:
      __UpperCAmelCase      :Union[str, Any]			    =       None

try:
      import msvcrt
except ImportError:
      __UpperCAmelCase      :Tuple			    =       None

try:
      import fcntl
except ImportError:
      __UpperCAmelCase      :str			    =       None


# Backward compatibility
# ------------------------------------------------
try:
      TimeoutError
except NameError:
      __UpperCAmelCase      :Dict			    =       OSError


# Data
# ------------------------------------------------
__UpperCAmelCase      :Any			    =       [
    "Timeout",
    "BaseFileLock",
    "WindowsFileLock",
    "UnixFileLock",
    "SoftFileLock",
    "FileLock",
]

__UpperCAmelCase      :Tuple			    =       "3.0.12"


__UpperCAmelCase      :int			    =       None




def      _a     (						):





     '''simple docstring'''






     global _logger
     __UpperCAmelCase     :			Optional[int]  							=      _logger or logging.getLogger(__name__  )
     return _logger



class      a    (		_a	):


     """simple docstring"""






     def __init__(    self					:		str							,			snake_case					:		Optional[int]      )						->							Optional[Any]:
          __UpperCAmelCase     :			Any  							=      lock_file
          return None






     def __str__(    self					:		str      )						->							Union[str, Any]:
          __UpperCAmelCase     :			Tuple  							=      f'The file lock \'{self.lock_file}\' could not be acquired.'
          return temp



class      a    :


     """simple docstring"""






     def __init__(    self					:		Optional[Any]							,			snake_case					:		Dict      )						->							List[Any]:
          __UpperCAmelCase     :			Tuple  							=      lock
          return None

     def __enter__(    self					:		Any      )						->							List[str]:
          return self.lock






     def __exit__(    self					:		Tuple							,			snake_case					:		Tuple							,			snake_case					:		List[str]							,			snake_case					:		int      )						->							Union[str, Any]:
          self.lock.release()
          return None



class      a    :


     """simple docstring"""






     def __init__(    self					:		Optional[Any]							,			snake_case					:		Tuple							,			snake_case					:		str=-1							,			snake_case					:		Optional[int]=None      )						->							Dict:
          __UpperCAmelCase     :			List[Any]  							=      max_filename_length if max_filename_length is not None else 255
          # Hash the filename if it's too long
          __UpperCAmelCase     :			Optional[int]  							=      self.hash_filename_if_too_long(snake_case							,			snake_case      )
          # The path to the lock file.
          __UpperCAmelCase     :			Dict  							=      lock_file

          # The file descriptor for the *_lock_file* as it is returned by the
          # os.open() function.
          # This file lock is only NOT None, if the object currently holds the
          # lock.
          __UpperCAmelCase     :			Optional[int]  							=      None

          # The default timeout value.
          __UpperCAmelCase     :			Optional[Any]  							=      timeout

          # We use this lock primarily for the lock counter.
          __UpperCAmelCase     :			Tuple  							=      threading.Lock()

          # The lock counter is used for implementing the nested locking
          # mechanism. Whenever the lock is acquired, the counter is increased and
          # the lock is only released, when this value is 0 again.
          __UpperCAmelCase     :			str  							=      0
          return None

     @property
     def 			lowerCamelCase__			(    self					:		Dict      )						->							Optional[Any]:
          return self._lock_file

     @property
     def 			lowerCamelCase__			(    self					:		str      )						->							Dict:
          return self._timeout

     @timeout.setter
     def 			lowerCamelCase__			(    self					:		Optional[Any]							,			snake_case					:		str      )						->							Any:
          __UpperCAmelCase     :			Union[str, Any]  							=      float(snake_case      )
          return None

     def 			lowerCamelCase__			(    self					:		Optional[Any]      )						->							Dict:
          raise NotImplementedError()

     def 			lowerCamelCase__			(    self					:		int      )						->							Any:
          raise NotImplementedError()

     @property
     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							Optional[int]:
          return self._lock_file_fd is not None

     def 			lowerCamelCase__			(    self					:		Optional[Any]							,			snake_case					:		Tuple=None							,			snake_case					:		List[Any]=0.05      )						->							int:
          # Use the default timeout, if no timeout is provided.
          if timeout is None:
               __UpperCAmelCase     :			Dict  							=      self.timeout

          # Increment the number right at the beginning.
          # We can still undo it, if something fails.
          with self._thread_lock:
               self._lock_counter += 1

          __UpperCAmelCase     :			Optional[Any]  							=      id(self      )
          __UpperCAmelCase     :			Any  							=      self._lock_file
          __UpperCAmelCase     :			Dict  							=      time.time()
          try:
               while True:
                    with self._thread_lock:
                         if not self.is_locked:
                              logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}'      )
                              self._acquire()

                    if self.is_locked:
                         logger().debug(f'Lock {lock_id} acquired on {lock_filename}'      )
                         break
                    elif timeout >= 0 and time.time() - start_time > timeout:
                         logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}'      )
                         raise Timeout(self._lock_file      )
                    else:
                         logger().debug(
                             f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...'      )
                         time.sleep(snake_case      )
          except:  # noqa
               # Something did go wrong, so decrement the counter.
               with self._thread_lock:
                    __UpperCAmelCase     :			Dict  							=      max(0							,			self._lock_counter - 1      )

               raise
          return _Acquire_ReturnProxy(lock=self      )

     def 			lowerCamelCase__			(    self					:		Optional[int]							,			snake_case					:		Any=False      )						->							int:
          with self._thread_lock:
               if self.is_locked:
                    self._lock_counter -= 1

                    if self._lock_counter == 0 or force:
                         __UpperCAmelCase     :			Any  							=      id(self      )
                         __UpperCAmelCase     :			List[Any]  							=      self._lock_file

                         logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}'      )
                         self._release()
                         __UpperCAmelCase     :			str  							=      0
                         logger().debug(f'Lock {lock_id} released on {lock_filename}'      )

          return None

     def __enter__(    self					:		List[Any]      )						->							Tuple:
          self.acquire()
          return self

     def __exit__(    self					:		Union[str, Any]							,			snake_case					:		Optional[int]							,			snake_case					:		List[str]							,			snake_case					:		str      )						->							List[Any]:
          self.release()
          return None

     def __del__(    self					:		List[str]      )						->							List[str]:
          self.release(force=snake_case      )
          return None






     def 			lowerCamelCase__			(    self					:		Optional[Any]							,			snake_case					:		str							,			snake_case					:		int      )						->							str:
          __UpperCAmelCase     :			Any  							=      os.path.basename(snake_case      )
          if len(snake_case      ) > max_length and max_length > 0:
               __UpperCAmelCase     :			Optional[Any]  							=      os.path.dirname(snake_case      )
               __UpperCAmelCase     :			Tuple  							=      str(hash(snake_case      )      )
               __UpperCAmelCase     :			List[Any]  							=      filename[: max_length - len(snake_case      ) - 8] + '''...''' + hashed_filename + '''.lock'''
               return os.path.join(snake_case							,			snake_case      )
          else:
               return path



class      a    (		_a	):


     """simple docstring"""






     def __init__(    self					:		Tuple							,			snake_case					:		Optional[int]							,			snake_case					:		int=-1							,			snake_case					:		str=None      )						->							List[Any]:
          from .file_utils import relative_to_absolute_path

          super().__init__(snake_case							,			timeout=snake_case							,			max_filename_length=snake_case      )
          __UpperCAmelCase     :			List[str]  							=      '''\\\\?\\''' + relative_to_absolute_path(self.lock_file      )

     def 			lowerCamelCase__			(    self					:		List[Any]      )						->							int:
          __UpperCAmelCase     :			Optional[int]  							=      os.O_RDWR | os.O_CREAT | os.O_TRUNC

          try:
               __UpperCAmelCase     :			Optional[int]  							=      os.open(self._lock_file							,			snake_case      )
          except OSError:
               pass
          else:
               try:
                    msvcrt.locking(snake_case							,			msvcrt.LK_NBLCK							,			1      )
               except OSError:
                    os.close(snake_case      )
               else:
                    __UpperCAmelCase     :			Any  							=      fd
          return None






     def 			lowerCamelCase__			(    self					:		str      )						->							str:
          __UpperCAmelCase     :			Dict  							=      self._lock_file_fd
          __UpperCAmelCase     :			Optional[Any]  							=      None
          msvcrt.locking(snake_case							,			msvcrt.LK_UNLCK							,			1      )
          os.close(snake_case      )

          try:
               os.remove(self._lock_file      )
          # Probably another instance of the application
          # that acquired the file lock.
          except OSError:
               pass
          return None



class      a    (		_a	):


     """simple docstring"""






     def __init__(    self					:		Optional[int]							,			snake_case					:		Optional[int]							,			snake_case					:		List[Any]=-1							,			snake_case					:		List[Any]=None      )						->							int:
          __UpperCAmelCase     :			Optional[Any]  							=      os.statvfs(os.path.dirname(snake_case      )      ).f_namemax
          super().__init__(snake_case							,			timeout=snake_case							,			max_filename_length=snake_case      )

     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							Dict:
          __UpperCAmelCase     :			Optional[int]  							=      os.O_RDWR | os.O_CREAT | os.O_TRUNC
          __UpperCAmelCase     :			Union[str, Any]  							=      os.open(self._lock_file							,			snake_case      )

          try:
               fcntl.flock(snake_case							,			fcntl.LOCK_EX | fcntl.LOCK_NB      )
          except OSError:
               os.close(snake_case      )
          else:
               __UpperCAmelCase     :			Any  							=      fd
          return None






     def 			lowerCamelCase__			(    self					:		int      )						->							List[str]:
          # Do not remove the lockfile:
          #
          #   https://github.com/benediktschmitt/py-filelock/issues/31
          #   https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition
          __UpperCAmelCase     :			List[Any]  							=      self._lock_file_fd
          __UpperCAmelCase     :			str  							=      None
          fcntl.flock(snake_case							,			fcntl.LOCK_UN      )
          os.close(snake_case      )
          return None



class      a    (		_a	):


     """simple docstring"""






     def 			lowerCamelCase__			(    self					:		Tuple      )						->							Optional[Any]:
          __UpperCAmelCase     :			Union[str, Any]  							=      os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
          try:
               __UpperCAmelCase     :			List[Any]  							=      os.open(self._lock_file							,			snake_case      )
          except OSError:
               pass
          else:
               __UpperCAmelCase     :			str  							=      fd
          return None






     def 			lowerCamelCase__			(    self					:		Optional[Any]      )						->							Optional[int]:
          os.close(self._lock_file_fd      )
          __UpperCAmelCase     :			Optional[Any]  							=      None

          try:
               os.remove(self._lock_file      )
          # The file is already deleted and that's what we want.
          except OSError:
               pass
          return None



__UpperCAmelCase      :Optional[Any]			    =       None

if msvcrt:
      __UpperCAmelCase      :Any			    =       WindowsFileLock
elif fcntl:
      __UpperCAmelCase      :List[Any]			    =       UnixFileLock
else:
      __UpperCAmelCase      :Dict			    =       SoftFileLock

      if warnings is not None:
            warnings.warn("only soft file lock is available")



'''simple docstring'''



import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import TimesformerConfig
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,
          TimesformerForVideoClassification,
          TimesformerModel,
      )
      from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from transformers import VideoMAEImageProcessor



class      a    :


     """simple docstring"""






     def __init__(    self					:		List[str]							,			snake_case					:		Any							,			snake_case					:		Tuple=13							,			snake_case					:		Any=10							,			snake_case					:		Any=3							,			snake_case					:		Dict=2							,			snake_case					:		Optional[Any]=2							,			snake_case					:		Union[str, Any]=True							,			snake_case					:		Dict=True							,			snake_case					:		List[Any]=32							,			snake_case					:		Dict=5							,			snake_case					:		List[str]=4							,			snake_case					:		Dict=37							,			snake_case					:		Any="gelu"							,			snake_case					:		Optional[int]=0.1							,			snake_case					:		Union[str, Any]=0.1							,			snake_case					:		Optional[int]=10							,			snake_case					:		Dict=0.02							,			snake_case					:		Tuple="divided_space_time"							,			snake_case					:		List[Any]=None							,			)						->							Optional[int]:
          __UpperCAmelCase     :			Dict  							=      parent
          __UpperCAmelCase     :			Tuple  							=      batch_size
          __UpperCAmelCase     :			Optional[Any]  							=      image_size
          __UpperCAmelCase     :			Optional[int]  							=      num_channels
          __UpperCAmelCase     :			Optional[Any]  							=      patch_size
          __UpperCAmelCase     :			List[str]  							=      num_frames
          __UpperCAmelCase     :			Union[str, Any]  							=      is_training
          __UpperCAmelCase     :			str  							=      use_labels
          __UpperCAmelCase     :			Union[str, Any]  							=      hidden_size
          __UpperCAmelCase     :			Any  							=      num_hidden_layers
          __UpperCAmelCase     :			List[Any]  							=      num_attention_heads
          __UpperCAmelCase     :			Dict  							=      intermediate_size
          __UpperCAmelCase     :			List[str]  							=      hidden_act
          __UpperCAmelCase     :			List[Any]  							=      hidden_dropout_prob
          __UpperCAmelCase     :			int  							=      attention_probs_dropout_prob
          __UpperCAmelCase     :			Any  							=      attention_type
          __UpperCAmelCase     :			Optional[Any]  							=      initializer_range
          __UpperCAmelCase     :			str  							=      scope
          __UpperCAmelCase     :			List[str]  							=      num_labels

          # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
          __UpperCAmelCase     :			str  							=      (image_size // patch_size) ** 2
          __UpperCAmelCase     :			int  							=      (num_frames) * self.num_patches_per_frame + 1

     def 			lowerCamelCase__			(    self					:		List[Any]      )						->							Tuple:
          __UpperCAmelCase     :			List[str]  							=      floats_tensor(
              [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]      )

          __UpperCAmelCase     :			Dict  							=      None
          if self.use_labels:
               __UpperCAmelCase     :			List[str]  							=      ids_tensor([self.batch_size]							,			self.num_labels      )

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

          return config, pixel_values, labels

     def 			lowerCamelCase__			(    self					:		List[Any]      )						->							Optional[Any]:
          __UpperCAmelCase     :			str  							=      TimesformerConfig(
              image_size=self.image_size							,			patch_size=self.patch_size							,			num_channels=self.num_channels							,			num_frames=self.num_frames							,			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							,			initializer_range=self.initializer_range							,			attention_type=self.attention_type							,			)
          __UpperCAmelCase     :			Optional[int]  							=      self.num_labels
          return config

     def 			lowerCamelCase__			(    self					:		Dict							,			snake_case					:		Any							,			snake_case					:		Optional[int]							,			snake_case					:		List[Any]      )						->							Optional[Any]:
          __UpperCAmelCase     :			List[Any]  							=      TimesformerModel(config=snake_case      )
          model.to(snake_case      )
          model.eval()
          __UpperCAmelCase     :			Tuple  							=      model(snake_case      )
          self.parent.assertEqual(result.last_hidden_state.shape							,			(self.batch_size, self.seq_length, self.hidden_size)      )

     def 			lowerCamelCase__			(    self					:		int							,			snake_case					:		Tuple							,			snake_case					:		List[Any]							,			snake_case					:		Optional[Any]      )						->							str:
          __UpperCAmelCase     :			Union[str, Any]  							=      TimesformerForVideoClassification(snake_case      )
          model.to(snake_case      )
          model.eval()

          __UpperCAmelCase     :			str  							=      model(snake_case      )

          # verify the logits shape
          __UpperCAmelCase     :			List[str]  							=      torch.Size((self.batch_size, self.num_labels)      )
          self.parent.assertEqual(result.logits.shape							,			snake_case      )






     def 			lowerCamelCase__			(    self					:		Any      )						->							List[str]:
          __UpperCAmelCase     :			Optional[int]  							=      self.prepare_config_and_inputs()
          __UpperCAmelCase							,       __UpperCAmelCase							,       __UpperCAmelCase     :			int  							=      config_and_inputs
          __UpperCAmelCase     :			Optional[Any]  							=      {'''pixel_values''': pixel_values}
          return config, inputs_dict



@require_torch
class      a    (		_a     ,  _a     ,  unittest.TestCase	):


     """simple docstring"""






     SCREAMING_SNAKE_CASE	:			List[str]							       =       (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
     SCREAMING_SNAKE_CASE	:			Optional[Any]							       =       (
         {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification}
         if is_torch_available()
         else {}
     )

     SCREAMING_SNAKE_CASE	:			int							       =       False
     SCREAMING_SNAKE_CASE	:			str							       =       False
     SCREAMING_SNAKE_CASE	:			Union[str, Any]							       =       False
     SCREAMING_SNAKE_CASE	:			List[Any]							       =       False

     def 			lowerCamelCase__			(    self					:		int      )						->							str:
          __UpperCAmelCase     :			Tuple  							=      TimesformerModelTester(self      )
          __UpperCAmelCase     :			str  							=      ConfigTester(
              self							,			config_class=snake_case							,			has_text_modality=snake_case							,			hidden_size=37      )

     def 			lowerCamelCase__			(    self					:		Dict							,			snake_case					:		Optional[int]							,			snake_case					:		Optional[int]							,			snake_case					:		Optional[int]=False      )						->							Union[str, Any]:
          __UpperCAmelCase     :			Union[str, Any]  							=      copy.deepcopy(snake_case      )

          if return_labels:
               if model_class in get_values(snake_case      ):
                    __UpperCAmelCase     :			List[Any]  							=      torch.zeros(
                        self.model_tester.batch_size							,			dtype=torch.long							,			device=snake_case      )

          return inputs_dict

     def 			lowerCamelCase__			(    self					:		Optional[Any]      )						->							Union[str, Any]:
          self.config_tester.run_common_tests()

     @unittest.skip(reason='''TimeSformer does not use inputs_embeds'''      )
     def 			lowerCamelCase__			(    self					:		Any      )						->							Dict:
          pass

     def 			lowerCamelCase__			(    self					:		Optional[Any]      )						->							int:
          __UpperCAmelCase							,       __UpperCAmelCase     :			List[Any]  							=      self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               __UpperCAmelCase     :			Optional[Any]  							=      model_class(snake_case      )
               self.assertIsInstance(model.get_input_embeddings()							,			(nn.Module)      )
               __UpperCAmelCase     :			Dict  							=      model.get_output_embeddings()
               self.assertTrue(x is None or isinstance(snake_case							,			nn.Linear      )      )

     def 			lowerCamelCase__			(    self					:		List[Any]      )						->							List[Any]:
          __UpperCAmelCase							,       __UpperCAmelCase     :			Union[str, Any]  							=      self.model_tester.prepare_config_and_inputs_for_common()

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

               __UpperCAmelCase     :			List[str]  							=      ['''pixel_values''']
               self.assertListEqual(arg_names[:1]							,			snake_case      )

     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							Dict:
          __UpperCAmelCase     :			List[Any]  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*snake_case      )

     def 			lowerCamelCase__			(    self					:		Tuple      )						->							Dict:
          __UpperCAmelCase     :			List[str]  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_video_classification(*snake_case      )

     @slow
     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							str:
          for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __UpperCAmelCase     :			Optional[int]  							=      TimesformerModel.from_pretrained(snake_case      )
               self.assertIsNotNone(snake_case      )

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

          else:
               __UpperCAmelCase							,       __UpperCAmelCase     :			List[str]  							=      self.model_tester.prepare_config_and_inputs_for_common()
               __UpperCAmelCase     :			Optional[int]  							=      True

               for model_class in self.all_model_classes:
                    __UpperCAmelCase     :			Tuple  							=      self.model_tester.seq_length
                    __UpperCAmelCase     :			int  							=      self.model_tester.num_frames

                    __UpperCAmelCase     :			Optional[int]  							=      True
                    __UpperCAmelCase     :			Any  							=      False
                    __UpperCAmelCase     :			Optional[int]  							=      True
                    __UpperCAmelCase     :			Tuple  							=      model_class(snake_case      )
                    model.to(snake_case      )
                    model.eval()
                    with torch.no_grad():
                         __UpperCAmelCase     :			int  							=      model(**self._prepare_for_class(snake_case							,			snake_case      )      )
                    __UpperCAmelCase     :			str  							=      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"]
                    __UpperCAmelCase     :			Dict  							=      True
                    __UpperCAmelCase     :			str  							=      model_class(snake_case      )
                    model.to(snake_case      )
                    model.eval()
                    with torch.no_grad():
                         __UpperCAmelCase     :			List[Any]  							=      model(**self._prepare_for_class(snake_case							,			snake_case      )      )
                    __UpperCAmelCase     :			List[Any]  							=      outputs.attentions
                    self.assertEqual(len(snake_case      )							,			self.model_tester.num_hidden_layers      )

                    # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
                    self.assertListEqual(
                        list(attentions[0].shape[-3:]      )							,			[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]							,			)
                    __UpperCAmelCase     :			Tuple  							=      len(snake_case      )

                    # Check attention is always last and order is fine
                    __UpperCAmelCase     :			Optional[int]  							=      True
                    __UpperCAmelCase     :			Optional[int]  							=      True
                    __UpperCAmelCase     :			Union[str, Any]  							=      model_class(snake_case      )
                    model.to(snake_case      )
                    model.eval()
                    with torch.no_grad():
                         __UpperCAmelCase     :			Any  							=      model(**self._prepare_for_class(snake_case							,			snake_case      )      )

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

                    __UpperCAmelCase     :			Any  							=      outputs.attentions

                    self.assertEqual(len(snake_case      )							,			self.model_tester.num_hidden_layers      )

                    # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
                    self.assertListEqual(
                        list(self_attentions[0].shape[-3:]      )							,			[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]							,			)






     def 			lowerCamelCase__			(    self					:		Dict      )						->							Union[str, Any]:
          def check_hidden_states_output(snake_case					:		Optional[Any]							,			snake_case					:		Optional[int]							,			snake_case					:		Tuple      ):
               __UpperCAmelCase     :			str  							=      model_class(snake_case      )
               model.to(snake_case      )
               model.eval()

               with torch.no_grad():
                    __UpperCAmelCase     :			Any  							=      model(**self._prepare_for_class(snake_case							,			snake_case      )      )

               __UpperCAmelCase     :			int  							=      outputs.hidden_states
               __UpperCAmelCase     :			Union[str, Any]  							=      self.model_tester.num_hidden_layers + 1
               self.assertEqual(len(snake_case      )							,			snake_case      )

               __UpperCAmelCase     :			int  							=      self.model_tester.seq_length

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

          __UpperCAmelCase							,       __UpperCAmelCase     :			str  							=      self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               __UpperCAmelCase     :			str  							=      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"]
               __UpperCAmelCase     :			str  							=      True

               check_hidden_states_output(snake_case							,			snake_case							,			snake_case      )




def      _a     (						):





     '''simple docstring'''






     __UpperCAmelCase     :			Union[str, Any]  							=      hf_hub_download(
         repo_id='''hf-internal-testing/spaghetti-video'''      , filename='''eating_spaghetti.npy'''      , repo_type='''dataset'''  )
     __UpperCAmelCase     :			int  							=      np.load(_lowercase  )
     return list(_lowercase  )



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


     """simple docstring"""






     @cached_property
     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							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 			lowerCamelCase__			(    self					:		str      )						->							List[Any]:
          __UpperCAmelCase     :			Union[str, Any]  							=      TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400'''      ).to(
              snake_case      )

          __UpperCAmelCase     :			str  							=      self.default_image_processor
          __UpperCAmelCase     :			Dict  							=      prepare_video()
          __UpperCAmelCase     :			Union[str, Any]  							=      image_processor(video[:8]							,			return_tensors='''pt'''      ).to(snake_case      )

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

          # verify the logits
          __UpperCAmelCase     :			Optional[Any]  							=      torch.Size((1, 400)      )
          self.assertEqual(outputs.logits.shape							,			snake_case      )

          __UpperCAmelCase     :			List[Any]  							=      torch.tensor([-0.3_016, -0.7_713, -0.4_205]      ).to(snake_case      )

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