code: 
  
  
  
  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        UpperCAmelCase__  :
  
  
  
   def __init__(  self		,	lowercase		,	lowercase=2		,	lowercase=True		,	lowercase=True		,	lowercase=1_0		,	lowercase=1_0		,	lowercase=8		,	lowercase=[2, 4, 4]		,	lowercase=3		,	lowercase=7_6_8		,	lowercase=5		,	lowercase=4		,	lowercase=3_7		,	lowercase="gelu_fast"		,	lowercase=0.0		,	lowercase=0.0		,	lowercase=0.02		,	lowercase=1E-06		,	lowercase=True		,	lowercase=None		,	)  ->							str:
    __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    __lowerCamelCase				(  self			)  ->							Optional[Any]:
    __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    __lowerCamelCase				(  self			)  ->							List[str]:
    __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    __lowerCamelCase				(  self		,	lowercase		,	lowercase		,	lowercase			)  ->							List[Any]:
    __UpperCamelCase				      =  VivitModel(config=lowercase			)
    model.to(lowercase			)
    model.eval()
    __UpperCamelCase				      =  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			)  ->							Optional[Any]:
    __UpperCamelCase				      =  VivitForVideoClassification(lowercase			)
    model.to(lowercase			)
    model.eval()
  
    __UpperCamelCase				      =  model(lowercase			)
  
    # verify the logits shape
    __UpperCamelCase				      =  torch.Size((self.batch_size, self.num_labels)			)
    self.parent.assertEqual(result.logits.shape		,	lowercase			)
  
  
  
  
   def    __lowerCamelCase				(  self			)  ->							Any:
    __UpperCamelCase				      =  self.prepare_config_and_inputs()
    __UpperCamelCase      ,		__UpperCamelCase      ,		__UpperCamelCase				      =  config_and_inputs
    __UpperCamelCase				      =  {"""pixel_values""": pixel_values}
    return config, inputs_dict
  
  
  @require_torch
  class        UpperCAmelCase__  (    lowercase_							,			unittest.TestCase):
   __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    __lowerCamelCase				(  self			)  ->							Any:
    __UpperCamelCase				      =  VivitModelTester(self			)
    __UpperCamelCase				      =  ConfigTester(self		,	config_class=lowercase		,	has_text_modality=lowercase		,	hidden_size=3_7			)
  
  
  
   def    __lowerCamelCase				(  self		,	lowercase		,	lowercase		,	lowercase=False			)  ->							Optional[int]:
    __UpperCamelCase				      =  copy.deepcopy(lowercase			)
  
    if return_labels:
     if model_class in get_values(lowercase			):
      __UpperCamelCase				      =  torch.zeros(
          self.model_tester.batch_size		,	dtype=torch.long		,	device=lowercase			)
  
    return inputs_dict
  
  
  
   def    __lowerCamelCase				(  self			)  ->							Dict:
    self.config_tester.run_common_tests()
  
  
  
   @unittest.skip(reason="""Vivit does not use inputs_embeds"""			)
   def    __lowerCamelCase				(  self			)  ->							str:
    pass
  
  
  
   def    __lowerCamelCase				(  self			)  ->							Optional[int]:
    __UpperCamelCase      ,		__UpperCamelCase				      =  self.model_tester.prepare_config_and_inputs_for_common()
  
    for model_class in self.all_model_classes:
     __UpperCamelCase				      =  model_class(lowercase			)
     self.assertIsInstance(model.get_input_embeddings()		,	(nn.Module)			)
     __UpperCamelCase				      =  model.get_output_embeddings()
     self.assertTrue(x is None or isinstance(lowercase		,	nn.Linear			)			)
  
  
  
   def    __lowerCamelCase				(  self			)  ->							int:
    __UpperCamelCase      ,		__UpperCamelCase				      =  self.model_tester.prepare_config_and_inputs_for_common()
  
    for model_class in self.all_model_classes:
     __UpperCamelCase				      =  model_class(lowercase			)
     __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]		,	lowercase			)
  
  
  
   def    __lowerCamelCase				(  self			)  ->							Optional[int]:
    __UpperCamelCase				      =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*lowercase			)
  
  
  
   def    __lowerCamelCase				(  self			)  ->							List[Any]:
    __UpperCamelCase				      =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_video_classification(*lowercase			)
  
  
  
   @slow
   def    __lowerCamelCase				(  self			)  ->							Dict:
  
  
  
  
  
  
  
    for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __UpperCamelCase				      =  VivitModel.from_pretrained(lowercase			)
     self.assertIsNotNone(lowercase			)
  
  
  
   def    __lowerCamelCase				(  self			)  ->							str:
    __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(lowercase			)
     model.to(lowercase			)
     model.eval()
     with torch.no_grad():
      __UpperCamelCase				      =  model(**self._prepare_for_class(lowercase		,	lowercase			)			)
     __UpperCamelCase				      =  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"]
     __UpperCamelCase				      =  True
     __UpperCamelCase				      =  model_class(lowercase			)
     model.to(lowercase			)
     model.eval()
     with torch.no_grad():
      __UpperCamelCase				      =  model(**self._prepare_for_class(lowercase		,	lowercase			)			)
     __UpperCamelCase				      =  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]		,	)
     __UpperCamelCase				      =  len(lowercase			)
  
     # Check attention is always last and order is fine
     __UpperCamelCase				      =  True
     __UpperCamelCase				      =  True
     __UpperCamelCase				      =  model_class(lowercase			)
     model.to(lowercase			)
     model.eval()
     with torch.no_grad():
      __UpperCamelCase				      =  model(**self._prepare_for_class(lowercase		,	lowercase			)			)
  
     self.assertEqual(out_len + 1		,	len(lowercase			)			)
  
     __UpperCamelCase				      =  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			)  ->							Union[str, Any]:
  
  
  
  
  
  
  
    def check_hidden_states_output(lowercase		,	lowercase		,	lowercase			):
     __UpperCamelCase				      =  model_class(lowercase			)
     model.to(lowercase			)
     model.eval()
  
     with torch.no_grad():
      __UpperCamelCase				      =  model(**self._prepare_for_class(lowercase		,	lowercase			)			)
  
     __UpperCamelCase				      =  outputs.hidden_states
     __UpperCamelCase				      =  self.model_tester.num_hidden_layers + 1
     self.assertEqual(len(lowercase			)		,	lowercase			)
  
     __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(lowercase		,	lowercase		,	lowercase			)
  
     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     __UpperCamelCase				      =  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			)  ->							List[Any]:
    pass
  
  
  
  
  
  
  
  def _lowercase   (  ):
  
  
  
   '''simple docstring'''
  
  
  
   __UpperCamelCase				      =  hf_hub_download(
       repo_id="""hf-internal-testing/spaghetti-video"""							,filename="""eating_spaghetti_32_frames.npy"""							,repo_type="""dataset"""       )
   __UpperCamelCase				      =  np.load(__A       )
   return list(__A       )
  
  
  
  
  
  
  @require_torch
  @require_vision
  class        UpperCAmelCase__  (    unittest.TestCase):
  
  
  
   @cached_property
   def    __lowerCamelCase				(  self			)  ->							int:
    return VivitImageProcessor() if is_vision_available() else None
  
  
  
  
   @slow
   def    __lowerCamelCase				(  self			)  ->							Optional[int]:
    __UpperCamelCase				      =  VivitForVideoClassification.from_pretrained("""google/vivit-b-16x2-kinetics400"""			).to(lowercase			)
  
    __UpperCamelCase				      =  self.default_image_processor
    __UpperCamelCase				      =  prepare_video()
    __UpperCamelCase				      =  image_processor(lowercase		,	return_tensors="""pt"""			).to(lowercase			)
  
    # forward pass
    with torch.no_grad():
     __UpperCamelCase				      =  model(**lowercase			)
  
    # verify the logits
    __UpperCamelCase				      =  torch.Size((1, 4_0_0)			)
    self.assertEqual(outputs.logits.shape		,	lowercase			)
  
    # taken from original model
    __UpperCamelCase				      =  torch.tensor([-1.0_543, 2.0_764, -0.2_104, 0.4_439, -0.9_658]			).to(lowercase			)
  
    self.assertTrue(torch.allclose(outputs.logits[0, :5]		,	lowercase		,	atol=1E-4			)			)
  
  
  
  
  
  
style_context: 
  
  
  
  '''simple docstring'''
  
  
  
  import textwrap
  
  import pyarrow as pa
  import pytest
  
  from datasets import Features, Image
  from datasets.packaged_modules.text.text import Text
  
  from ..utils import require_pil
  
  
  
  
  
  
  
  @pytest.fixture
  def _lowercase   (  __A       ):
  
  
  
   '''simple docstring'''
  
  
  
   __UpperCamelCase				      =  tmp_path / """text.txt"""
   __UpperCamelCase				      =  textwrap.dedent(
       """\
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
          Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
          Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
          Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  
          Second paragraph:
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
          Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
          Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
          Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
          """       )
   with open(__A							,"""w"""							,encoding="""utf-8"""       ) as f:
    f.write(__A       )
   return str(__A       )
  
  
  
  
  
  
  
  @pytest.fixture
  def _lowercase   (  __A							,__A       ):
  
  
  
   '''simple docstring'''
  
  
  
   __UpperCamelCase				      =  tmp_path / """text_with_image.txt"""
   with open(__A							,"""w"""							,encoding="""utf-8"""       ) as f:
    f.write(__A       )
   return str(__A       )
  
  
  
  
  
  
  
  @pytest.mark.parametrize("""keep_linebreaks"""							,[True, False]       )
  def _lowercase   (  __A							,__A       ):
  
  
  
   '''simple docstring'''
  
  
  
   with open(__A							,encoding="""utf-8"""       ) as f:
    __UpperCamelCase				      =  f.read().splitlines(keepends=__A       )
   __UpperCamelCase				      =  Text(keep_linebreaks=__A							,encoding="""utf-8"""       )
   __UpperCamelCase				      =  text._generate_tables([[text_file]]       )
   __UpperCamelCase				      =  pa.concat_tables([table for _, table in generator]       ).to_pydict()["""text"""]
   assert generated_content == expected_content
  
  
  
  
  
  
  
  @require_pil
  def _lowercase   (  __A       ):
  
  
  
   '''simple docstring'''
  
  
  
   with open(__A							,encoding="""utf-8"""       ) as f:
    __UpperCamelCase				      =  f.read().splitlines()[0]
   __UpperCamelCase				      =  Text(encoding="""utf-8"""							,features=Features({"""image""": Image()}       )       )
   __UpperCamelCase				      =  text._generate_tables([[text_file_with_image]]       )
   __UpperCamelCase				      =  pa.concat_tables([table for _, table in generator]       )
   assert pa_table.schema.field("""image"""       ).type == Image()()
   __UpperCamelCase				      =  pa_table.to_pydict()["""image"""]
   assert generated_content == [{"path": image_file, "bytes": None}]
  
  
  
  
  
  
  
  @pytest.mark.parametrize("""sample_by"""							,["""line""", """paragraph""", """document"""]       )
  def _lowercase   (  __A							,__A       ):
  
  
  
   '''simple docstring'''
  
  
  
   with open(__A							,encoding="""utf-8"""       ) as f:
    __UpperCamelCase				      =  f.read()
   if sample_by == "line":
    __UpperCamelCase				      =  expected_content.splitlines()
   elif sample_by == "paragraph":
    __UpperCamelCase				      =  expected_content.split("""\n\n"""       )
   elif sample_by == "document":
    __UpperCamelCase				      =  [expected_content]
   __UpperCamelCase				      =  Text(sample_by=__A							,encoding="""utf-8"""							,chunksize=100       )
   __UpperCamelCase				      =  text._generate_tables([[text_file]]       )
   __UpperCamelCase				      =  pa.concat_tables([table for _, table in generator]       ).to_pydict()["""text"""]
   assert generated_content == expected_content
  
  
  
  
  
  