

import json
import os
import pickle
import subprocess
from hashlib import mda
from pathlib import Path
from tempfile import gettempdir
from textwrap import dedent
from types import CodeType, FunctionType
from unittest import TestCase
from unittest.mock import patch

import pytest
from multiprocess import Pool
from packaging import version

import datasets
from datasets.fingerprint import Hasher, fingerprint_transform
from datasets.table import InMemoryTable

from .utils import (
    require_regex,
    require_spacy,
    require_spacy_model,
    require_tiktoken,
    require_torch,
    require_transformers,
)



class 					lowercase		:



 '''simple docstring'''


 def __init__(self , __a				)				->      Tuple:






  """simple docstring"""





  UpperCAmelCase__           =       foo




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






  """simple docstring"""





  return self.foo







class 					lowercase		( datasets.Dataset      ):



 '''simple docstring'''


 @fingerprint_transform(inplace=__a				)
 def 						UpperCamelCase__							(self , __a , *__a , **__a				)				->      List[Any]:






  """simple docstring"""





  return DatasetChild(self.data , fingerprint=__a				)




 @fingerprint_transform(inplace=__a				)
 def 						UpperCamelCase__							(self , __a , *__a , **__a				)				->      Optional[Any]:






  """simple docstring"""





  return DatasetChild(self.data , fingerprint=__a				)







class 					lowercase		:



 '''simple docstring'''


 def __init__(self , __a				)				->      int:






  """simple docstring"""





  UpperCAmelCase__           =       callable




 def __call__(self , *__a , **__a				)				->      List[str]:






  """simple docstring"""





  if self.callable is not None:
   return self.callable(*__a , **__a				)




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






  """simple docstring"""





  raise pickle.PicklingError()







class 					lowercase		( _UpperCamelCase      ):



 '''simple docstring'''


 @require_transformers
 @pytest.mark.integration
 def 						UpperCamelCase__							(self				)				->      Union[str, Any]:






  """simple docstring"""





  from transformers import AutoTokenizer

  def encode(__a				):
   return tokenizer(__a				)

  # TODO: add hash consistency tests across sessions
  UpperCAmelCase__           =       AutoTokenizer.from_pretrained('bert-base-uncased'				)
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(lambda __a				: tokenizer(__a				)				)				).hexdigest()
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  UpperCAmelCase__           =       AutoTokenizer.from_pretrained('bert-base-cased'				)
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(lambda __a				: tokenizer(__a				)				)				).hexdigest()
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  UpperCAmelCase__           =       AutoTokenizer.from_pretrained('bert-base-uncased'				)
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(lambda __a				: tokenizer(__a				)				)				).hexdigest()
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  self.assertEqual(__a , __a				)
  self.assertNotEqual(__a , __a				)
  self.assertEqual(__a , __a				)
  self.assertNotEqual(__a , __a				)
  self.assertEqual(__a , __a				)
  self.assertNotEqual(__a , __a				)




 @require_transformers
 @pytest.mark.integration
 def 						UpperCamelCase__							(self				)				->      Optional[Any]:






  """simple docstring"""





  from transformers import AutoTokenizer

  UpperCAmelCase__           =       AutoTokenizer.from_pretrained('gpt2'				)
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  tokenizer('Hello world !'				)  # call once to change the tokenizer's cache
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  self.assertEqual(__a , __a				)




 @require_regex
 def 						UpperCamelCase__							(self				)				->      Optional[Any]:






  """simple docstring"""





  import regex

  UpperCAmelCase__           =       regex.Regex('foo'				)
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  UpperCAmelCase__           =       regex.Regex('bar'				)
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  UpperCAmelCase__           =       regex.Regex('foo'				)
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  self.assertEqual(__a , __a				)
  self.assertNotEqual(__a , __a				)







class 					lowercase		( _UpperCamelCase      ):



 '''simple docstring'''


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






  """simple docstring"""





  def func():
   return foo

  UpperCAmelCase__           =       [0]
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  UpperCAmelCase__           =       [1]
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  UpperCAmelCase__           =       [0]
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  self.assertEqual(__a , __a				)
  self.assertNotEqual(__a , __a				)




 def 						UpperCamelCase__							(self				)				->      Any:






  """simple docstring"""





  def func():
   pass

  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()

  def func():
   pass

  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  self.assertEqual(__a , __a				)




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






  """simple docstring"""





  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(Foo([0]				)				)				).hexdigest()
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(Foo([1]				)				)				).hexdigest()
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(Foo([0]				)				)				).hexdigest()
  self.assertEqual(__a , __a				)
  self.assertNotEqual(__a , __a				)




 def 						UpperCamelCase__							(self				)				->      Any:






  """simple docstring"""





  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(Foo([0]				).__call__				)				).hexdigest()
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(Foo([1]				).__call__				)				).hexdigest()
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(Foo([0]				).__call__				)				).hexdigest()
  self.assertEqual(__a , __a				)
  self.assertNotEqual(__a , __a				)




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






  """simple docstring"""





  UpperCAmelCase__           =       (
      'co_argcount',
      'co_kwonlyargcount',
      'co_nlocals',
      'co_stacksize',
      'co_flags',
      'co_code',
      'co_consts',
      'co_names',
      'co_varnames',
      'co_filename',
      'co_name',
      'co_firstlineno',
      'co_lnotab',
      'co_freevars',
      'co_cellvars',
  )

  def _create_code_pyaa(*__a				):
   if hasattr(args[-3] , 'encode'				):
    UpperCAmelCase__           =       list(__a				)
    UpperCAmelCase__           =       args[-3].encode()  # co_lnotab
    UpperCAmelCase__           =       args[-10].encode()  # co_code
   if hasattr(__a , 'co_posonlyargcount'				):
    if len(__a				) == 16:
     return CodeType(*__a				)
    elif len(__a				) == 15:
     return CodeType(args[0] , 0 , *args[1:]				)
    return CodeType(args[0] , 0 , 0 , *args[1:]				)
   elif hasattr(__a , 'co_kwonlyargcount'				):
    if len(__a				) == 16:
     return CodeType(args[0] , *args[2:]				)
    elif len(__a				) == 15:
     return CodeType(*__a				)
    return CodeType(args[0] , 0 , *args[1:]				)
   if len(__a				) == 16:
    return CodeType(args[0] , *args[3:]				)
   elif len(__a				) == 15:
    return CodeType(args[0] , *args[2:]				)
   return CodeType(*__a				)

  def create_ipython_func(__a , __a				):
   def func():
    return returned_obj

   UpperCAmelCase__           =       func.__code__
   # Use _create_code from dill in order to make it work for different python versions
   if datasets.config.PY_VERSION < version.parse('3.8'				):
    UpperCAmelCase__           =       _create_code_pyaa(
        *[getattr(__a , __a				) if k != 'co_filename' else co_filename for k in code_args_pyaa]				)
   else:
    UpperCAmelCase__           =       code.replace(co_filename=__a				)
   return FunctionType(__a , func.__globals__ , func.__name__ , func.__defaults__ , func.__closure__				)

  UpperCAmelCase__       ,					UpperCAmelCase__           =       '<ipython-input-2-e0383a102aae>', [0]
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(create_ipython_func(__a , __a				)				)				).hexdigest()
  UpperCAmelCase__       ,					UpperCAmelCase__           =       '<ipython-input-2-e0383a102aae>', [1]
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(create_ipython_func(__a , __a				)				)				).hexdigest()
  UpperCAmelCase__       ,					UpperCAmelCase__           =       '<ipython-input-5-713f6613acf3>', [0]
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(create_ipython_func(__a , __a				)				)				).hexdigest()
  self.assertEqual(__a , __a				)
  self.assertNotEqual(__a , __a				)

  UpperCAmelCase__       ,					UpperCAmelCase__           =       os.path.join(gettempdir() , 'ipykernel_12345' , '321456789.py'				), [0]
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(create_ipython_func(__a , __a				)				)				).hexdigest()
  UpperCAmelCase__       ,					UpperCAmelCase__           =       os.path.join(gettempdir() , 'ipykernel_12345' , '321456789.py'				), [1]
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(create_ipython_func(__a , __a				)				)				).hexdigest()
  UpperCAmelCase__       ,					UpperCAmelCase__           =       os.path.join(gettempdir() , 'ipykernel_12345' , '654123987.py'				), [0]
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(create_ipython_func(__a , __a				)				)				).hexdigest()
  self.assertEqual(__a , __a				)
  self.assertNotEqual(__a , __a				)




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






  """simple docstring"""





  UpperCAmelCase__       ,					UpperCAmelCase__           =       [0], [1]

  def func():
   return foo, bar

  UpperCAmelCase__           =       '__main__'

  def globalvars_mocka_side_effect(__a , *__a , **__a				):
   return {"foo": foo, "bar": bar}

  def globalvars_mocka_side_effect(__a , *__a , **__a				):
   return {"bar": bar, "foo": foo}

  with patch('dill.detect.globalvars' , side_effect=__a				) as globalvars_mocka:
   UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
   self.assertGreater(globalvars_mocka.call_count , 0				)
  with patch('dill.detect.globalvars' , side_effect=__a				) as globalvars_mocka:
   UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
   self.assertGreater(globalvars_mocka.call_count , 0				)
  self.assertEqual(__a , __a				)







class 					lowercase		( _UpperCamelCase      ):



 '''simple docstring'''


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






  """simple docstring"""





  UpperCAmelCase__           =       Hasher.hash('hello'				)
  UpperCAmelCase__           =       Hasher.hash('hello'				)
  UpperCAmelCase__           =       Hasher.hash('there'				)
  self.assertEqual(__a , __a				)
  self.assertNotEqual(__a , __a				)




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






  """simple docstring"""





  UpperCAmelCase__           =       Hasher.hash(Foo('hello'				)				)
  UpperCAmelCase__           =       Hasher.hash(Foo('hello'				)				)
  UpperCAmelCase__           =       Hasher.hash(Foo('there'				)				)
  self.assertEqual(__a , __a				)
  self.assertNotEqual(__a , __a				)




 def 						UpperCamelCase__							(self				)				->      Dict:






  """simple docstring"""





  UpperCAmelCase__           =       Hasher()
  for x in ["hello", Foo('hello'				)]:
   hasher.update(__a				)
  UpperCAmelCase__           =       hasher.hexdigest()
  UpperCAmelCase__           =       Hasher()
  for x in ["hello", Foo('hello'				)]:
   hasher.update(__a				)
  UpperCAmelCase__           =       hasher.hexdigest()
  UpperCAmelCase__           =       Hasher()
  for x in ["there", Foo('there'				)]:
   hasher.update(__a				)
  UpperCAmelCase__           =       hasher.hexdigest()
  self.assertEqual(__a , __a				)
  self.assertNotEqual(__a , __a				)




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






  """simple docstring"""





  with self.assertRaises(pickle.PicklingError				):
   Hasher.hash(UnpicklableCallable(Foo('hello'				)				)				)




 def 						UpperCamelCase__							(self				)				->      str:






  """simple docstring"""





  UpperCAmelCase__           =       'abc'
  UpperCAmelCase__           =       [string, string]  # two strings have the same ids
  UpperCAmelCase__           =       [string, string]
  UpperCAmelCase__           =       json.loads(F"[\"{string}\", \"{string}\"]"				)  # two strings have different ids
  self.assertIs(obja[0] , __a				)
  self.assertIs(obja[0] , obja[1]				)
  self.assertIs(obja[0] , __a				)
  self.assertIs(obja[0] , obja[1]				)
  self.assertIsNot(obja[0] , __a				)
  self.assertIsNot(obja[0] , obja[1]				)
  UpperCAmelCase__           =       Hasher.hash(__a				)
  UpperCAmelCase__           =       Hasher.hash(__a				)
  UpperCAmelCase__           =       Hasher.hash(__a				)
  self.assertEqual(__a , __a				)
  self.assertEqual(__a , __a				)




 @require_tiktoken
 def 						UpperCamelCase__							(self				)				->      Union[str, Any]:






  """simple docstring"""





  import tiktoken

  UpperCAmelCase__           =       tiktoken.get_encoding('gpt2'				)
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  UpperCAmelCase__           =       tiktoken.get_encoding('r50k_base'				)
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  UpperCAmelCase__           =       tiktoken.get_encoding('gpt2'				)
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  self.assertEqual(__a , __a				)
  self.assertNotEqual(__a , __a				)




 @require_torch
 def 						UpperCamelCase__							(self				)				->      Optional[int]:






  """simple docstring"""





  import torch

  UpperCAmelCase__           =       torch.tensor([1.0]				)
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  UpperCAmelCase__           =       torch.tensor([2.0]				)
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  UpperCAmelCase__           =       torch.tensor([1.0]				)
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  self.assertEqual(__a , __a				)
  self.assertNotEqual(__a , __a				)




 @require_spacy
 @require_spacy_model('en_core_web_sm'				)
 @require_spacy_model('fr_core_news_sm'				)
 @pytest.mark.integration
 def 						UpperCamelCase__							(self				)				->      List[Any]:






  """simple docstring"""





  import spacy

  UpperCAmelCase__           =       spacy.load('en_core_web_sm'				)
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  UpperCAmelCase__           =       spacy.load('fr_core_news_sm'				)
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  UpperCAmelCase__           =       spacy.load('en_core_web_sm'				)
  UpperCAmelCase__           =       mda(datasets.utils.py_utils.dumps(__a				)				).hexdigest()
  self.assertEqual(__a , __a				)
  self.assertNotEqual(__a , __a				)







@pytest.mark.integration
def 		UpperCamelCase_(    snake_case__:						Path     ) ->				Tuple:
 UpperCAmelCase__           =       tmp_path / 'dir1'
 UpperCAmelCase__           =       tmp_path / 'dir2'
 dira.mkdir()
 dira.mkdir()
 UpperCAmelCase__           =       'script.py'
 UpperCAmelCase__           =       dedent(
     '\n    from datasets.fingerprint import Hasher\n    def foo():\n        pass\n    print(Hasher.hash(foo))\n    '     )
 UpperCAmelCase__           =       dira / script_filename
 UpperCAmelCase__           =       dira / script_filename
 with script_patha.open('w'     ) as f:
  f.write(snake_case__     )
 with script_patha.open('w'     ) as f:
  f.write(snake_case__     )
 UpperCAmelCase__           =       subprocess.check_output(['python', str(snake_case__     )]     )
 UpperCAmelCase__           =       subprocess.check_output(['python', str(snake_case__     )]     )
 assert fingerprinta == fingerprinta
def 		UpperCamelCase_(    ) ->				str:
 UpperCAmelCase__           =       {'a': [0, 1, 2]}
 UpperCAmelCase__           =       DatasetChild(InMemoryTable.from_pydict(snake_case__     )     )
 UpperCAmelCase__           =       dataset.funca()._fingerprint
 assert expected_fingerprint == dataset.funca()._fingerprint
 assert expected_fingerprint != dataset.funca()._fingerprint

 with Pool(2     ) as p:
  assert expected_fingerprint == p.apply_async(dataset.funca     ).get()._fingerprint
  assert expected_fingerprint != p.apply_async(dataset.funca     ).get()._fingerprint
def 		UpperCamelCase_(    ) ->				Tuple:
 UpperCAmelCase__           =       {'a': [0, 1, 2]}



 class 					lowercase		( datasets.Dataset      ):



  '''simple docstring'''


  @fingerprint_transform(inplace=__a				)
  def 						UpperCamelCase__							(self , __a				)				->      Dict:






   """simple docstring"""





   return DummyDatasetChild(self.data , fingerprint=__a				)







 UpperCAmelCase__           =       DummyDatasetChild(InMemoryTable.from_pydict(snake_case__     )     ).func()



 class 					lowercase		( datasets.Dataset      ):



  '''simple docstring'''


  @fingerprint_transform(inplace=__a , version='1.0.0'				)
  def 						UpperCamelCase__							(self , __a				)				->      Optional[int]:






   """simple docstring"""





   return DummyDatasetChild(self.data , fingerprint=__a				)







 UpperCAmelCase__           =       DummyDatasetChild(InMemoryTable.from_pydict(snake_case__     )     ).func()



 class 					lowercase		( datasets.Dataset      ):



  '''simple docstring'''


  @fingerprint_transform(inplace=__a , version='2.0.0'				)
  def 						UpperCamelCase__							(self , __a				)				->      List[str]:






   """simple docstring"""





   return DummyDatasetChild(self.data , fingerprint=__a				)







 UpperCAmelCase__           =       DummyDatasetChild(InMemoryTable.from_pydict(snake_case__     )     ).func()

 assert len({fingeprint_no_version, fingeprint_a, fingeprint_a}     ) == 3







def 		UpperCamelCase_(    ) ->				Optional[int]:
 # AttributeError: module 'dill._dill' has no attribute 'stack'
 UpperCAmelCase__           =       Hasher()
 hasher.update(lambda snake_case__     : x     )






import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import VivitConfig
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


if is_torch_available():
 import torch
 from torch import nn

 from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VivitForVideoClassification, VivitModel
 from transformers.models.vivit.modeling_vivit import VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from transformers import VivitImageProcessor



class 					lowercase		:



 '''simple docstring'''


 def __init__(self , __a , __a=2 , __a=True , __a=True , __a=10 , __a=10 , __a=8 , __a=[2, 4, 4] , __a=3 , __a=768 , __a=5 , __a=4 , __a=37 , __a="gelu_fast" , __a=0.0 , __a=0.0 , __a=0.02 , __a=1E-0_6 , __a=True , __a=None , )				->      List[Any]:






  """simple docstring"""





  UpperCAmelCase__           =       parent
  UpperCAmelCase__           =       batch_size
  UpperCAmelCase__           =       is_training
  UpperCAmelCase__           =       use_labels
  UpperCAmelCase__           =       num_labels
  UpperCAmelCase__           =       image_size
  UpperCAmelCase__           =       num_frames
  UpperCAmelCase__           =       tubelet_size
  UpperCAmelCase__           =       num_channels
  UpperCAmelCase__           =       hidden_size
  UpperCAmelCase__           =       num_hidden_layers
  UpperCAmelCase__           =       num_attention_heads
  UpperCAmelCase__           =       intermediate_size
  UpperCAmelCase__           =       hidden_act
  UpperCAmelCase__           =       hidden_dropout_prob
  UpperCAmelCase__           =       attention_probs_dropout_prob
  UpperCAmelCase__           =       initializer_range
  UpperCAmelCase__           =       layer_norm_eps
  UpperCAmelCase__           =       qkv_bias
  UpperCAmelCase__           =       scope

  UpperCAmelCase__           =       (
      (self.image_size // self.tubelet_size[2])
      * (self.image_size // self.tubelet_size[1])
      * (self.num_frames // self.tubelet_size[0])
  ) + 1  # CLS token




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






  """simple docstring"""





  UpperCAmelCase__           =       floats_tensor(
      [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]				)

  UpperCAmelCase__           =       None
  if self.use_labels:
   UpperCAmelCase__           =       ids_tensor([self.batch_size] , self.num_labels				)

  UpperCAmelCase__           =       self.get_config()

  return config, pixel_values, labels




 def 						UpperCamelCase__							(self				)				->      Tuple:






  """simple docstring"""





  UpperCAmelCase__           =       VivitConfig(
      num_frames=self.num_frames , image_size=self.image_size , tubelet_size=self.tubelet_size , num_channels=self.num_channels , 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 , layer_norm_eps=self.layer_norm_eps , qkv_bias=self.qkv_bias , )
  UpperCAmelCase__           =       self.num_labels
  return config




 def 						UpperCamelCase__							(self , __a , __a , __a				)				->      str:






  """simple docstring"""





  UpperCAmelCase__           =       VivitModel(config=__a				)
  model.to(__a				)
  model.eval()
  UpperCAmelCase__           =       model(__a				)
  self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)				)




 def 						UpperCamelCase__							(self , __a , __a , __a				)				->      Optional[int]:






  """simple docstring"""





  UpperCAmelCase__           =       VivitForVideoClassification(__a				)
  model.to(__a				)
  model.eval()

  UpperCAmelCase__           =       model(__a				)

  # verify the logits shape
  UpperCAmelCase__           =       torch.Size((self.batch_size, self.num_labels)				)
  self.parent.assertEqual(result.logits.shape , __a				)




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






  """simple docstring"""





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







@require_torch
class 					lowercase		( _UpperCamelCase				,       unittest.TestCase      ):



 '''simple docstring'''


 __SCREAMING_SNAKE_CASE      							=       (VivitModel, VivitForVideoClassification) if is_torch_available() else ()

 __SCREAMING_SNAKE_CASE      							=       False
 __SCREAMING_SNAKE_CASE      							=       False
 __SCREAMING_SNAKE_CASE      							=       False
 __SCREAMING_SNAKE_CASE      							=       False




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






  """simple docstring"""





  UpperCAmelCase__           =       VivitModelTester(self				)
  UpperCAmelCase__           =       ConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37				)




 def 						UpperCamelCase__							(self , __a , __a , __a=False				)				->      int:






  """simple docstring"""





  UpperCAmelCase__           =       copy.deepcopy(__a				)

  if return_labels:
   if model_class in get_values(__a				):
    UpperCAmelCase__           =       torch.zeros(
        self.model_tester.batch_size , dtype=torch.long , device=__a				)

  return inputs_dict




 def 						UpperCamelCase__							(self				)				->      Tuple:






  """simple docstring"""





  self.config_tester.run_common_tests()




 @unittest.skip(reason='Vivit does not use inputs_embeds'				)
 def 						UpperCamelCase__							(self				)				->      str:






  """simple docstring"""





  pass




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






  """simple docstring"""





  UpperCAmelCase__       ,					UpperCAmelCase__           =       self.model_tester.prepare_config_and_inputs_for_common()

  for model_class in self.all_model_classes:
   UpperCAmelCase__           =       model_class(__a				)
   self.assertIsInstance(model.get_input_embeddings() , (nn.Module)				)
   UpperCAmelCase__           =       model.get_output_embeddings()
   self.assertTrue(x is None or isinstance(__a , nn.Linear				)				)




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






  """simple docstring"""





  UpperCAmelCase__       ,					UpperCAmelCase__           =       self.model_tester.prepare_config_and_inputs_for_common()

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

   UpperCAmelCase__           =       ['pixel_values', 'head_mask']
   self.assertListEqual(arg_names[:2] , __a				)




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






  """simple docstring"""





  UpperCAmelCase__           =       self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_model(*__a				)




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






  """simple docstring"""





  UpperCAmelCase__           =       self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_for_video_classification(*__a				)




 @slow
 def 						UpperCamelCase__							(self				)				->      Optional[int]:






  """simple docstring"""





  for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
   UpperCAmelCase__           =       VivitModel.from_pretrained(__a				)
   self.assertIsNotNone(__a				)




 def 						UpperCamelCase__							(self				)				->      Any:






  """simple docstring"""





  UpperCAmelCase__       ,					UpperCAmelCase__           =       self.model_tester.prepare_config_and_inputs_for_common()
  UpperCAmelCase__           =       True

  for model_class in self.all_model_classes:
   UpperCAmelCase__           =       self.model_tester.seq_length

   UpperCAmelCase__           =       True
   UpperCAmelCase__           =       False
   UpperCAmelCase__           =       True
   UpperCAmelCase__           =       model_class(__a				)
   model.to(__a				)
   model.eval()
   with torch.no_grad():
    UpperCAmelCase__           =       model(**self._prepare_for_class(__a , __a				)				)
   UpperCAmelCase__           =       outputs.attentions
   self.assertEqual(len(__a				) , self.model_tester.num_hidden_layers				)

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

   self.assertListEqual(
       list(attentions[0].shape[-3:]				) , [self.model_tester.num_attention_heads, seq_len, seq_len] , )
   UpperCAmelCase__           =       len(__a				)

   # Check attention is always last and order is fine
   UpperCAmelCase__           =       True
   UpperCAmelCase__           =       True
   UpperCAmelCase__           =       model_class(__a				)
   model.to(__a				)
   model.eval()
   with torch.no_grad():
    UpperCAmelCase__           =       model(**self._prepare_for_class(__a , __a				)				)

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

   UpperCAmelCase__           =       outputs.attentions

   self.assertEqual(len(__a				) , 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				)				->      Optional[int]:






  """simple docstring"""





  def check_hidden_states_output(__a , __a , __a				):
   UpperCAmelCase__           =       model_class(__a				)
   model.to(__a				)
   model.eval()

   with torch.no_grad():
    UpperCAmelCase__           =       model(**self._prepare_for_class(__a , __a				)				)

   UpperCAmelCase__           =       outputs.hidden_states
   UpperCAmelCase__           =       self.model_tester.num_hidden_layers + 1
   self.assertEqual(len(__a				) , __a				)

   UpperCAmelCase__           =       self.model_tester.seq_length

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

  UpperCAmelCase__       ,					UpperCAmelCase__           =       self.model_tester.prepare_config_and_inputs_for_common()

  for model_class in self.all_model_classes:
   UpperCAmelCase__           =       True
   check_hidden_states_output(__a , __a , __a				)

   # check that output_hidden_states also work using config
   del inputs_dict["output_hidden_states"]
   UpperCAmelCase__           =       True

   check_hidden_states_output(__a , __a , __a				)




 @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'				)
 def 						UpperCamelCase__							(self				)				->      List[str]:






  """simple docstring"""





  pass







def 		UpperCamelCase_(    ) ->				List[Any]:
 UpperCAmelCase__           =       hf_hub_download(
     repo_id='hf-internal-testing/spaghetti-video'						,					filename='eating_spaghetti_32_frames.npy'						,					repo_type='dataset'     )
 UpperCAmelCase__           =       np.load(snake_case__     )
 return list(snake_case__     )







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



 '''simple docstring'''


 @cached_property
 def 						UpperCamelCase__							(self				)				->      List[str]:






  """simple docstring"""





  return VivitImageProcessor() if is_vision_available() else None




 @slow
 def 						UpperCamelCase__							(self				)				->      str:






  """simple docstring"""





  UpperCAmelCase__           =       VivitForVideoClassification.from_pretrained('google/vivit-b-16x2-kinetics400'				).to(__a				)

  UpperCAmelCase__           =       self.default_image_processor
  UpperCAmelCase__           =       prepare_video()
  UpperCAmelCase__           =       image_processor(__a , return_tensors='pt'				).to(__a				)

  # forward pass
  with torch.no_grad():
   UpperCAmelCase__           =       model(**__a				)

  # verify the logits
  UpperCAmelCase__           =       torch.Size((1, 400)				)
  self.assertEqual(outputs.logits.shape , __a				)

  # taken from original model
  UpperCAmelCase__           =       torch.tensor([-1.05_43, 2.07_64, -0.21_04, 0.44_39, -0.96_58]				).to(__a				)

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



