"""simple docstring"""






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




					"""simple docstring"""

					def __init__(							self  :      Optional[Any]       ,lowerCamelCase__  :      List[Any]       ,lowerCamelCase__  :      Dict=2       ,lowerCamelCase__  :      Dict=True       ,lowerCamelCase__  :      List[str]=True       ,lowerCamelCase__  :      str=10       ,lowerCamelCase__  :      str=10       ,lowerCamelCase__  :      Tuple=8       ,lowerCamelCase__  :      Optional[Any]=[2, 4, 4]       ,lowerCamelCase__  :      str=3       ,lowerCamelCase__  :      Dict=768       ,lowerCamelCase__  :      Tuple=5       ,lowerCamelCase__  :      int=4       ,lowerCamelCase__  :      List[Any]=37       ,lowerCamelCase__  :      Any="gelu_fast"       ,lowerCamelCase__  :      str=0.0       ,lowerCamelCase__  :      str=0.0       ,lowerCamelCase__  :      Union[str, Any]=0.0_2       ,lowerCamelCase__  :      Dict=1e-06       ,lowerCamelCase__  :      Union[str, Any]=True       ,lowerCamelCase__  :      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 						__lowerCAmelCase		(							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 						__lowerCAmelCase		(							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 						__lowerCAmelCase		(							self  :      Optional[Any]       ,lowerCamelCase__  :      List[Any]       ,lowerCamelCase__  :      Optional[Any]       ,lowerCamelCase__  :      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 						__lowerCAmelCase		(							self  :      Any       ,lowerCamelCase__  :      Any       ,lowerCamelCase__  :      Optional[Any]       ,lowerCamelCase__  :      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 						__lowerCAmelCase		(							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 							snake_case			(					__UpperCAmelCase ,       unittest.TestCase							):




					"""simple docstring"""

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

					snake_case__							       =					False
					snake_case__							       =					False
					snake_case__							       =					False
					snake_case__							       =					False







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







					def 						__lowerCAmelCase		(							self  :      Union[str, Any]       ,lowerCamelCase__  :      Any       ,lowerCamelCase__  :      Optional[int]       ,lowerCamelCase__  :      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 						__lowerCAmelCase		(							self  :      List[str]     ):
									self.config_tester.run_common_tests()







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







					def 						__lowerCAmelCase		(							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 						__lowerCAmelCase		(							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 						__lowerCAmelCase		(							self  :      List[Any]     ):
									UpperCAmelCase__			 =				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowerCamelCase__     )







					def 						__lowerCAmelCase		(							self  :      Any     ):
									UpperCAmelCase__			 =				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_video_classification(*lowerCamelCase__     )







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







					def 						__lowerCAmelCase		(							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 						__lowerCAmelCase		(							self  :      str     ):
									def check_hidden_states_output(lowerCamelCase__  :      Any       ,lowerCamelCase__  :      int       ,lowerCamelCase__  :      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 						__lowerCAmelCase		(							self  :      List[Any]     ):
									pass






def     a_		(   ):
				UpperCAmelCase__			 =				hf_hub_download(
				    repo_id='hf-internal-testing/spaghetti-video'   ,     filename='eating_spaghetti_32_frames.npy'   ,     repo_type='dataset'			)
				UpperCAmelCase__			 =				np.load(lowerCamelCase			)
				return list(lowerCamelCase			)







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




					"""simple docstring"""

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







					@slow
					def 						__lowerCAmelCase		(							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.0_5_4_3, 2.0_7_6_4, -0.2_1_0_4, 0.4_4_3_9, -0.9_6_5_8]     ).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



