




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 			_lowerCamelCase    :

      """simple docstring"""

      def __init__(  self       :			Optional[Any]			,							snake_case       :			List[Any]			,							snake_case       :			Dict=2			,							snake_case       :			Dict=True			,							snake_case       :			List[str]=True			,							snake_case       :			str=10			,							snake_case       :			str=10			,							snake_case       :			Tuple=8			,							snake_case       :			Optional[Any]=[2, 4, 4]			,							snake_case       :			str=3			,							snake_case       :			Dict=768			,							snake_case       :			Tuple=5			,							snake_case       :			int=4			,							snake_case       :			List[Any]=37			,							snake_case       :			Any="gelu_fast"			,							snake_case       :			str=0.0			,							snake_case       :			str=0.0			,							snake_case       :			Union[str, Any]=0.02			,							snake_case       :			Dict=1E-06			,							snake_case       :			Union[str, Any]=True			,							snake_case       :			Any=None			,							):
          __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    snake_case						(  self       :			Tuple					):
          __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    snake_case						(  self       :			Optional[Any]					):
          __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    snake_case						(  self       :			Optional[Any]			,							snake_case       :			List[Any]			,							snake_case       :			Optional[Any]			,							snake_case       :			Tuple					):
          __UpperCamelCase			=    VivitModel(config=lowerCamelCase__					)
          model.to(lowerCamelCase__					)
          model.eval()
          __UpperCamelCase			=    model(lowerCamelCase__					)
          self.parent.assertEqual(result.last_hidden_state.shape			,							(self.batch_size, self.seq_length, self.hidden_size)					)







      def    snake_case						(  self       :			Any			,							snake_case       :			Any			,							snake_case       :			Optional[Any]			,							snake_case       :			List[Any]					):
          __UpperCamelCase			=    VivitForVideoClassification(lowerCamelCase__					)
          model.to(lowerCamelCase__					)
          model.eval()

          __UpperCamelCase			=    model(lowerCamelCase__					)

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







      def    snake_case						(  self       :			int					):
          __UpperCamelCase			=    self.prepare_config_and_inputs()
          __UpperCamelCase		,   __UpperCamelCase		,   __UpperCamelCase			=    config_and_inputs
          __UpperCamelCase			=    {'''pixel_values''': pixel_values}
          return config, inputs_dict







@require_torch
class 			_lowerCamelCase    (      __UpperCAmelCase				,      unittest.TestCase ):

      """simple docstring"""

      lowerCAmelCase__      :			int     =       (VivitModel, VivitForVideoClassification) if is_torch_available() else ()

      lowerCAmelCase__      :			Any     =       False
      lowerCAmelCase__      :			str     =       False
      lowerCAmelCase__      :			Optional[Any]     =       False
      lowerCAmelCase__      :			Optional[Any]     =       False







      def    snake_case						(  self       :			Optional[Any]					):
          __UpperCamelCase			=    VivitModelTester(self					)
          __UpperCamelCase			=    ConfigTester(self			,							config_class=lowerCamelCase__			,							has_text_modality=lowerCamelCase__			,							hidden_size=37					)







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

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

          return inputs_dict







      def    snake_case						(  self       :			List[str]					):
          self.config_tester.run_common_tests()







      @unittest.skip(reason='''Vivit does not use inputs_embeds'''					)
      def    snake_case						(  self       :			List[Any]					):
          pass







      def    snake_case						(  self       :			Any					):
          __UpperCamelCase		,   __UpperCamelCase			=    self.model_tester.prepare_config_and_inputs_for_common()

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







      def    snake_case						(  self       :			str					):
          __UpperCamelCase		,   __UpperCamelCase			=    self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              __UpperCamelCase			=    model_class(lowerCamelCase__					)
              __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]			,							lowerCamelCase__					)







      def    snake_case						(  self       :			List[Any]					):
          __UpperCamelCase			=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowerCamelCase__					)







      def    snake_case						(  self       :			Any					):
          __UpperCamelCase			=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_video_classification(*lowerCamelCase__					)







      @slow
      def    snake_case						(  self       :			int					):
          for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __UpperCamelCase			=    VivitModel.from_pretrained(lowerCamelCase__					)
              self.assertIsNotNone(lowerCamelCase__					)







      def    snake_case						(  self       :			List[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(lowerCamelCase__					)
              model.to(lowerCamelCase__					)
              model.eval()
              with torch.no_grad():
                  __UpperCamelCase			=    model(**self._prepare_for_class(lowerCamelCase__			,							lowerCamelCase__					)					)
              __UpperCamelCase			=    outputs.attentions
              self.assertEqual(len(lowerCamelCase__					)			,							self.model_tester.num_hidden_layers					)

              # check that output_attentions also work using config
              del inputs_dict["output_attentions"]
              __UpperCamelCase			=    True
              __UpperCamelCase			=    model_class(lowerCamelCase__					)
              model.to(lowerCamelCase__					)
              model.eval()
              with torch.no_grad():
                  __UpperCamelCase			=    model(**self._prepare_for_class(lowerCamelCase__			,							lowerCamelCase__					)					)
              __UpperCamelCase			=    outputs.attentions
              self.assertEqual(len(lowerCamelCase__					)			,							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(lowerCamelCase__					)

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

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

              __UpperCamelCase			=    outputs.attentions

              self.assertEqual(len(lowerCamelCase__					)			,							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    snake_case						(  self       :			str					):
          def check_hidden_states_output(snake_case       :			Any			,							snake_case       :			int			,							snake_case       :			Dict					):
              __UpperCamelCase			=    model_class(lowerCamelCase__					)
              model.to(lowerCamelCase__					)
              model.eval()

              with torch.no_grad():
                  __UpperCamelCase			=    model(**self._prepare_for_class(lowerCamelCase__			,							lowerCamelCase__					)					)

              __UpperCamelCase			=    outputs.hidden_states
              __UpperCamelCase			=    self.model_tester.num_hidden_layers + 1
              self.assertEqual(len(lowerCamelCase__					)			,							lowerCamelCase__					)

              __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(lowerCamelCase__			,							lowerCamelCase__			,							lowerCamelCase__					)

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

              check_hidden_states_output(lowerCamelCase__			,							lowerCamelCase__			,							lowerCamelCase__					)







      @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''					)
      def    snake_case						(  self       :			List[Any]					):
          pass







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

    """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(lowercase_   )
    return list(lowercase_   )


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

      """simple docstring"""

      @cached_property
      def    snake_case						(  self       :			str					):
          return VivitImageProcessor() if is_vision_available() else None







      @slow
      def    snake_case						(  self       :			Optional[Any]					):
          __UpperCamelCase			=    VivitForVideoClassification.from_pretrained('''google/vivit-b-16x2-kinetics400'''					).to(lowerCamelCase__					)

          __UpperCamelCase			=    self.default_image_processor
          __UpperCamelCase			=    prepare_video()
          __UpperCamelCase			=    image_processor(lowerCamelCase__			,							return_tensors='''pt'''					).to(lowerCamelCase__					)

          # forward pass
          with torch.no_grad():
              __UpperCamelCase			=    model(**lowerCamelCase__					)

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

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

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







"""simple docstring"""






import numpy as np



def     a_		(   lowerCamelCase   ,     lowerCamelCase="utf-8"   ,     lowerCamelCase="surrogatepass"			):
				UpperCAmelCase__			 =				bin(int.from_bytes(text.encode(lowerCamelCase   ,     lowerCamelCase			)   ,     'big'			)			)[2:]
				return bits.zfill(8 * ((len(lowerCamelCase			) + 7) // 8)			)



def     a_		(   lowerCamelCase   ,     lowerCamelCase="utf-8"   ,     lowerCamelCase="surrogatepass"			):
				UpperCAmelCase__			 =				int(lowerCamelCase   ,     2			)
				return n.to_bytes((n.bit_length() + 7) // 8   ,     'big'			).decode(lowerCamelCase   ,     lowerCamelCase			) or "\0"



def     a_		(   lowerCamelCase   ,     lowerCamelCase			):
				if size_par + len(lowerCamelCase			) <= 2**size_par - (len(lowerCamelCase			) - 1):
								raise ValueError('size of parity don\'t match with size of data'			)

				UpperCAmelCase__			 =				[]
				UpperCAmelCase__			 =				[]
				UpperCAmelCase__			 =				[bin(lowerCamelCase			)[2:] for x in range(1   ,     size_par + len(lowerCamelCase			) + 1			)]

				# sorted information data for the size of the output data
				UpperCAmelCase__			 =				[]
				# data position template + parity
				UpperCAmelCase__			 =				[]
				# parity bit counter
				UpperCAmelCase__			 =				0
				# counter position of data bits
				UpperCAmelCase__			 =				0

				for x in range(1   ,     size_par + len(lowerCamelCase			) + 1			):
								# Performs a template of bit positions - who should be given,
								# and who should be parity
								if qtd_bp < size_par:
												if (np.log(lowerCamelCase			) / np.log(2			)).is_integer():
																data_out_gab.append('P'			)
																UpperCAmelCase__			 =				qtd_bp + 1
												else:
																data_out_gab.append('D'			)
								else:
												data_out_gab.append('D'			)

								# Sorts the data to the new output size
								if data_out_gab[-1] == "D":
												data_ord.append(data[cont_data]			)
												cont_data += 1
								else:
												data_ord.append(lowerCamelCase			)

    # Calculates parity
				UpperCAmelCase__			 =				0  # parity bit counter
				for bp in range(1   ,     size_par + 1			):
								# Bit counter one for a given parity
								UpperCAmelCase__			 =				0
								# counter to control the loop reading
								UpperCAmelCase__			 =				0
								for x in data_ord:
												if x is not None:
																try:
																				UpperCAmelCase__			 =				(bin_pos[cont_loop])[-1 * (bp)]
																except IndexError:
																				UpperCAmelCase__			 =				'0'
																if aux == "1" and x == "1":
																				cont_bo += 1
												cont_loop += 1
								parity.append(cont_bo % 2			)

								qtd_bp += 1

				# Mount the message
				UpperCAmelCase__			 =				0  # parity bit counter
				for x in range(0   ,     size_par + len(lowerCamelCase			)			):
								if data_ord[x] is None:
												data_out.append(str(parity[cont_bp]			)			)
												cont_bp += 1
								else:
												data_out.append(data_ord[x]			)

				return data_out



def     a_		(   lowerCamelCase   ,     lowerCamelCase			):
				UpperCAmelCase__			 =				[]
				# Parity bit counter
				UpperCAmelCase__			 =				0
				# Counter p data bit reading
				UpperCAmelCase__			 =				0
				# list of parity received
				UpperCAmelCase__			 =				[]
				UpperCAmelCase__			 =				[]

				for x in range(1   ,     len(lowerCamelCase			) + 1			):
								# Performs a template of bit positions - who should be given,
								#  and who should be parity
								if qtd_bp < size_par and (np.log(lowerCamelCase			) / np.log(2			)).is_integer():
												data_out_gab.append('P'			)
												UpperCAmelCase__			 =				qtd_bp + 1
								else:
												data_out_gab.append('D'			)

								# Sorts the data to the new output size
								if data_out_gab[-1] == "D":
												data_output.append(data[cont_data]			)
								else:
												parity_received.append(data[cont_data]			)
								cont_data += 1

				# -----------calculates the parity with the data
				UpperCAmelCase__			 =				[]
				UpperCAmelCase__			 =				[]
				UpperCAmelCase__			 =				[bin(lowerCamelCase			)[2:] for x in range(1   ,     size_par + len(lowerCamelCase			) + 1			)]

				#  sorted information data for the size of the output data
				UpperCAmelCase__			 =				[]
				# Data position feedback + parity
				UpperCAmelCase__			 =				[]
				# Parity bit counter
				UpperCAmelCase__			 =				0
				# Counter p data bit reading
				UpperCAmelCase__			 =				0

				for x in range(1   ,     size_par + len(lowerCamelCase			) + 1			):
								# Performs a template position of bits - who should be given,
								# and who should be parity
								if qtd_bp < size_par and (np.log(lowerCamelCase			) / np.log(2			)).is_integer():
												data_out_gab.append('P'			)
												UpperCAmelCase__			 =				qtd_bp + 1
								else:
												data_out_gab.append('D'			)

								# Sorts the data to the new output size
								if data_out_gab[-1] == "D":
												data_ord.append(data_output[cont_data]			)
												cont_data += 1
								else:
												data_ord.append(lowerCamelCase			)

    # Calculates parity
				UpperCAmelCase__			 =				0  # parity bit counter
				for bp in range(1   ,     size_par + 1			):
								# Bit counter one for a certain parity
								UpperCAmelCase__			 =				0
								# Counter to control loop reading
								UpperCAmelCase__			 =				0
								for x in data_ord:
												if x is not None:
																try:
																				UpperCAmelCase__			 =				(bin_pos[cont_loop])[-1 * (bp)]
																except IndexError:
																				UpperCAmelCase__			 =				'0'
																if aux == "1" and x == "1":
																				cont_bo += 1
												cont_loop += 1
								parity.append(str(cont_bo % 2			)			)

								qtd_bp += 1

				# Mount the message
				UpperCAmelCase__			 =				0  # Parity bit counter
				for x in range(0   ,     size_par + len(lowerCamelCase			)			):
								if data_ord[x] is None:
												data_out.append(str(parity[cont_bp]			)			)
												cont_bp += 1
								else:
												data_out.append(data_ord[x]			)

				UpperCAmelCase__			 =				parity_received == parity
				return data_output, ack



