

from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging


_UpperCamelCase     =    logging.get_logger(__name__)

_UpperCamelCase     =    {
    '''google/bigbird-pegasus-large-arxiv''': (
        '''https://huggingface.co/google/bigbird-pegasus-large-arxiv/resolve/main/config.json'''
    ),
    '''google/bigbird-pegasus-large-pubmed''': (
        '''https://huggingface.co/google/bigbird-pegasus-large-pubmed/resolve/main/config.json'''
    ),
    '''google/bigbird-pegasus-large-bigpatent''': (
        '''https://huggingface.co/google/bigbird-pegasus-large-bigpatent/resolve/main/config.json'''
    ),
    # See all BigBirdPegasus models at https://huggingface.co/models?filter=bigbird_pegasus
}



class 					lowercase		( _UpperCamelCase      ):



 '''simple docstring'''


 __SCREAMING_SNAKE_CASE      							=       """bigbird_pegasus"""
 __SCREAMING_SNAKE_CASE      							=       ["""past_key_values"""]
 __SCREAMING_SNAKE_CASE      							=       {
     """num_attention_heads""": """encoder_attention_heads""",
     """hidden_size""": """d_model""",
     """attention_probs_dropout_prob""": """attention_dropout""",
 }




 def __init__(self , __a=96103 , __a=4096 , __a=16 , __a=4096 , __a=16 , __a=16 , __a=4096 , __a=16 , __a=0.0 , __a=0.0 , __a=True , __a=True , __a="gelu_new" , __a=1024 , __a=0.1 , __a=0.0 , __a=0.0 , __a=0.02 , __a=2 , __a=0.0 , __a=True , __a=0 , __a=2 , __a=1 , __a="block_sparse" , __a=64 , __a=3 , __a=False , **__a , )				->      Tuple:






  """simple docstring"""





  UpperCAmelCase__           =       vocab_size
  UpperCAmelCase__           =       max_position_embeddings
  UpperCAmelCase__           =       d_model
  UpperCAmelCase__           =       encoder_ffn_dim
  UpperCAmelCase__           =       encoder_layers
  UpperCAmelCase__           =       encoder_attention_heads
  UpperCAmelCase__           =       decoder_ffn_dim
  UpperCAmelCase__           =       decoder_layers
  UpperCAmelCase__           =       decoder_attention_heads
  UpperCAmelCase__           =       dropout
  UpperCAmelCase__           =       attention_dropout
  UpperCAmelCase__           =       activation_dropout
  UpperCAmelCase__           =       activation_function
  UpperCAmelCase__           =       init_std
  UpperCAmelCase__           =       encoder_layerdrop
  UpperCAmelCase__           =       decoder_layerdrop
  UpperCAmelCase__           =       classifier_dropout
  UpperCAmelCase__           =       use_cache
  UpperCAmelCase__           =       encoder_layers
  UpperCAmelCase__           =       scale_embedding  # scale factor will be sqrt(d_model) if True

  # extra config
  UpperCAmelCase__           =       attention_type
  UpperCAmelCase__           =       block_size
  UpperCAmelCase__           =       num_random_blocks
  UpperCAmelCase__           =       use_bias

  super().__init__(
      pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , is_encoder_decoder=__a , decoder_start_token_id=__a , **__a , )







class 					lowercase		( _UpperCamelCase      ):



 '''simple docstring'''


 @property
 def 						UpperCamelCase__							(self				)				->      Mapping[str, Mapping[int, str]]:






  """simple docstring"""





  if self.task in ["default", "seq2seq-lm"]:
   UpperCAmelCase__           =       OrderedDict(
       [
           ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
           ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
       ]				)

   if self.use_past:
    UpperCAmelCase__           =       {0: 'batch'}
    UpperCAmelCase__           =       {0: 'batch', 1: 'past_decoder_sequence + sequence'}
   else:
    UpperCAmelCase__           =       {0: 'batch', 1: 'decoder_sequence'}
    UpperCAmelCase__           =       {0: 'batch', 1: 'decoder_sequence'}

   if self.use_past:
    self.fill_with_past_key_values_(__a , direction='inputs'				)
  elif self.task == "causal-lm":
   # TODO: figure this case out.
   UpperCAmelCase__           =       OrderedDict(
       [
           ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
           ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
       ]				)
   if self.use_past:
    UpperCAmelCase__       ,					UpperCAmelCase__           =       self.num_layers
    for i in range(__a				):
     UpperCAmelCase__           =       {0: 'batch', 2: 'past_sequence + sequence'}
     UpperCAmelCase__           =       {0: 'batch', 2: 'past_sequence + sequence'}
  else:
   UpperCAmelCase__           =       OrderedDict(
       [
           ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
           ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
           ('decoder_input_ids', {0: 'batch', 1: 'decoder_sequence'}),
           ('decoder_attention_mask', {0: 'batch', 1: 'decoder_sequence'}),
       ]				)

  return common_inputs




 @property
 def 						UpperCamelCase__							(self				)				->      Mapping[str, Mapping[int, str]]:






  """simple docstring"""





  if self.task in ["default", "seq2seq-lm"]:
   UpperCAmelCase__           =       super().outputs
  else:
   UpperCAmelCase__           =       super(__a , self				).outputs
   if self.use_past:
    UpperCAmelCase__       ,					UpperCAmelCase__           =       self.num_layers
    for i in range(__a				):
     UpperCAmelCase__           =       {0: 'batch', 2: 'past_sequence + sequence'}
     UpperCAmelCase__           =       {0: 'batch', 2: 'past_sequence + sequence'}
  return common_outputs




 def 						UpperCamelCase__							(self , __a , __a = -1 , __a = -1 , __a = False , __a = None , )				->      Mapping[str, Any]:






  """simple docstring"""





  UpperCAmelCase__           =       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
      __a , __a , __a , __a , __a				)

  # Generate decoder inputs
  UpperCAmelCase__           =       seq_length if not self.use_past else 1
  UpperCAmelCase__           =       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
      __a , __a , __a , __a , __a				)
  UpperCAmelCase__           =       {F"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
  UpperCAmelCase__           =       dict(**__a , **__a				)

  if self.use_past:
   if not is_torch_available():
    raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'				)
   else:
    import torch
   UpperCAmelCase__       ,					UpperCAmelCase__           =       common_inputs['input_ids'].shape
   UpperCAmelCase__           =       common_inputs['decoder_input_ids'].shape[1]
   UpperCAmelCase__       ,					UpperCAmelCase__           =       self.num_attention_heads
   UpperCAmelCase__           =       (
       batch,
       num_encoder_attention_heads,
       encoder_seq_length,
       self._config.hidden_size // num_encoder_attention_heads,
   )
   UpperCAmelCase__           =       decoder_seq_length + 3
   UpperCAmelCase__           =       (
       batch,
       num_decoder_attention_heads,
       decoder_past_length,
       self._config.hidden_size // num_decoder_attention_heads,
   )

   UpperCAmelCase__           =       torch.cat(
       [common_inputs['decoder_attention_mask'], torch.ones(__a , __a				)] , dim=1				)

   UpperCAmelCase__           =       []
   # If the number of encoder and decoder layers are present in the model configuration, both are considered
   UpperCAmelCase__       ,					UpperCAmelCase__           =       self.num_layers
   UpperCAmelCase__           =       min(__a , __a				)
   UpperCAmelCase__           =       max(__a , __a				) - min_num_layers
   UpperCAmelCase__           =       'encoder' if num_encoder_layers > num_decoder_layers else 'decoder'

   for _ in range(__a				):
    common_inputs["past_key_values"].append(
        (
            torch.zeros(__a				),
            torch.zeros(__a				),
            torch.zeros(__a				),
            torch.zeros(__a				),
        )				)
   # TODO: test this.
   UpperCAmelCase__           =       encoder_shape if remaining_side_name == 'encoder' else decoder_shape
   for _ in range(__a , __a				):
    common_inputs["past_key_values"].append((torch.zeros(__a				), torch.zeros(__a				))				)
  return common_inputs




 def 						UpperCamelCase__							(self , __a , __a = -1 , __a = -1 , __a = False , __a = None , )				->      Mapping[str, Any]:






  """simple docstring"""





  UpperCAmelCase__           =       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
      __a , __a , __a , __a , __a				)

  if self.use_past:
   if not is_torch_available():
    raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'				)
   else:
    import torch
   UpperCAmelCase__       ,					UpperCAmelCase__           =       common_inputs['input_ids'].shape
   # Not using the same length for past_key_values
   UpperCAmelCase__           =       seqlen + 2
   UpperCAmelCase__       ,					UpperCAmelCase__           =       self.num_layers
   UpperCAmelCase__       ,					UpperCAmelCase__           =       self.num_attention_heads
   UpperCAmelCase__           =       (
       batch,
       num_encoder_attention_heads,
       past_key_values_length,
       self._config.hidden_size // num_encoder_attention_heads,
   )

   UpperCAmelCase__           =       common_inputs['attention_mask'].dtype
   UpperCAmelCase__           =       torch.cat(
       [common_inputs['attention_mask'], torch.ones(__a , __a , dtype=__a				)] , dim=1				)
   UpperCAmelCase__           =       [
       (torch.zeros(__a				), torch.zeros(__a				)) for _ in range(__a				)
   ]
  return common_inputs




 def 						UpperCamelCase__							(self , __a , __a = -1 , __a = -1 , __a = False , __a = None , )				->      Mapping[str, Any]:






  """simple docstring"""





  UpperCAmelCase__           =       compute_effective_axis_dimension(
      __a , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0				)

  # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
  UpperCAmelCase__           =       tokenizer.num_special_tokens_to_add(__a				)
  UpperCAmelCase__           =       compute_effective_axis_dimension(
      __a , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__a				)

  # Generate dummy inputs according to compute batch and sequence
  UpperCAmelCase__           =       [' '.join([tokenizer.unk_token]				) * seq_length] * batch_size
  UpperCAmelCase__           =       dict(tokenizer(__a , return_tensors=__a				)				)
  return common_inputs




 def 						UpperCamelCase__							(self , __a , __a = -1 , __a = -1 , __a = False , __a = None , )				->      Mapping[str, Any]:






  """simple docstring"""





  if self.task in ["default", "seq2seq-lm"]:
   UpperCAmelCase__           =       self._generate_dummy_inputs_for_default_and_seqaseq_lm(
       __a , batch_size=__a , seq_length=__a , is_pair=__a , framework=__a				)

  elif self.task == "causal-lm":
   UpperCAmelCase__           =       self._generate_dummy_inputs_for_causal_lm(
       __a , batch_size=__a , seq_length=__a , is_pair=__a , framework=__a				)
  else:
   UpperCAmelCase__           =       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
       __a , batch_size=__a , seq_length=__a , is_pair=__a , framework=__a				)

  return common_inputs




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






  """simple docstring"""





  if self.task in ["default", "seq2seq-lm"]:
   UpperCAmelCase__           =       super()._flatten_past_key_values_(__a , __a , __a , __a				)
  else:
   UpperCAmelCase__           =       super(__a , self				)._flatten_past_key_values_(
       __a , __a , __a , __a				)






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



