'''simple docstring'''




from __future__ import annotations

import unittest

from transformers import AutoTokenizer, PegasusConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
						import tensorflow as tf

						from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel





@require_tf
class 					__magic_name__		:
			UpperCamelCase__       = PegasusConfig
			UpperCamelCase__       = {}
			UpperCamelCase__       = '''gelu'''







			def __init__(			self       :						List[Any]       ,    lowercase_       :						int       ,    lowercase_       :						Optional[int]=13       ,    lowercase_       :						Dict=7       ,    lowercase_       :						Tuple=True       ,    lowercase_       :						List[str]=False       ,    lowercase_       :						Dict=99       ,    lowercase_       :						Any=32       ,    lowercase_       :						Union[str, Any]=2       ,    lowercase_       :						str=4       ,    lowercase_       :						Optional[int]=37       ,    lowercase_       :						List[Any]=0.1       ,    lowercase_       :						List[str]=0.1       ,    lowercase_       :						Optional[int]=40       ,    lowercase_       :						Any=2       ,    lowercase_       :						Optional[int]=1       ,    lowercase_       :						int=0       ,    ):
										lowercase_      :    int       		= parent
										lowercase_      :    int       		= batch_size
										lowercase_      :    str       		= seq_length
										lowercase_      :    List[Any]       		= is_training
										lowercase_      :    List[Any]       		= use_labels
										lowercase_      :    Optional[Any]       		= vocab_size
										lowercase_      :    List[Any]       		= hidden_size
										lowercase_      :    Optional[Any]       		= num_hidden_layers
										lowercase_      :    Optional[int]       		= num_attention_heads
										lowercase_      :    Tuple       		= intermediate_size

										lowercase_      :    Optional[int]       		= hidden_dropout_prob
										lowercase_      :    Optional[Any]       		= attention_probs_dropout_prob
										lowercase_      :    Tuple       		= max_position_embeddings
										lowercase_      :    Union[str, Any]       		= eos_token_id
										lowercase_      :    Any       		= pad_token_id
										lowercase_      :    Tuple       		= bos_token_id







			def 			SCREAMING_SNAKE_CASE_  (			self       :						Union[str, Any]					):
										lowercase_      :    Optional[int]       		= ids_tensor([self.batch_size, self.seq_length - 1]       ,    self.vocab_size					)
										lowercase_      :    int       		= tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size					)       ,    1					)
										lowercase_      :    Dict       		= tf.concat([input_ids, eos_tensor]       ,    axis=1					)

										lowercase_      :    Union[str, Any]       		= ids_tensor([self.batch_size, self.seq_length]       ,    self.vocab_size					)

										lowercase_      :    List[str]       		= self.config_cls(
										    vocab_size=self.vocab_size       ,    d_model=self.hidden_size       ,    encoder_layers=self.num_hidden_layers       ,    decoder_layers=self.num_hidden_layers       ,    encoder_attention_heads=self.num_attention_heads       ,    decoder_attention_heads=self.num_attention_heads       ,    encoder_ffn_dim=self.intermediate_size       ,    decoder_ffn_dim=self.intermediate_size       ,    dropout=self.hidden_dropout_prob       ,    attention_dropout=self.attention_probs_dropout_prob       ,    max_position_embeddings=self.max_position_embeddings       ,    eos_token_ids=[2]       ,    bos_token_id=self.bos_token_id       ,    pad_token_id=self.pad_token_id       ,    decoder_start_token_id=self.pad_token_id       ,    **self.config_updates       ,    )
										lowercase_      :    int       		= prepare_pegasus_inputs_dict(lowercase_       ,    lowercase_       ,    lowercase_					)
										return config, inputs_dict







			def 			SCREAMING_SNAKE_CASE_  (			self       :						int       ,    lowercase_       :						Any       ,    lowercase_       :						Union[str, Any]					):
										lowercase_      :    Any       		= TFPegasusModel(config=lowercase_					).get_decoder()
										lowercase_      :    Optional[Any]       		= inputs_dict["""input_ids"""]

										lowercase_      :    Dict       		= input_ids[:1, :]
										lowercase_      :    int       		= inputs_dict["""attention_mask"""][:1, :]
										lowercase_      :    Dict       		= inputs_dict["""head_mask"""]
										lowercase_      :    str       		= 1

										# first forward pass
										lowercase_      :    Optional[Any]       		= model(lowercase_       ,    attention_mask=lowercase_       ,    head_mask=lowercase_       ,    use_cache=lowercase_					)

										lowercase_		,		lowercase_      :    Dict       		= outputs.to_tuple()

										# create hypothetical next token and extent to next_input_ids
										lowercase_      :    Tuple       		= ids_tensor((self.batch_size, 3)       ,    config.vocab_size					)
										lowercase_      :    Optional[int]       		= tf.cast(ids_tensor((self.batch_size, 3)       ,    2					)       ,    tf.inta					)

										# append to next input_ids and
										lowercase_      :    List[Any]       		= tf.concat([input_ids, next_tokens]       ,    axis=-1					)
										lowercase_      :    Optional[Any]       		= tf.concat([attention_mask, next_attn_mask]       ,    axis=-1					)

										lowercase_      :    int       		= model(lowercase_       ,    attention_mask=lowercase_					)[0]
										lowercase_      :    int       		= model(lowercase_       ,    attention_mask=lowercase_       ,    past_key_values=lowercase_					)[0]

										self.parent.assertEqual(next_tokens.shape[1]       ,    output_from_past.shape[1]					)

										# select random slice
										lowercase_      :    str       		= int(ids_tensor((1,)       ,    output_from_past.shape[-1]					)					)
										lowercase_      :    int       		= output_from_no_past[:, -3:, random_slice_idx]
										lowercase_      :    Dict       		= output_from_past[:, :, random_slice_idx]

										# test that outputs are equal for slice
										tf.debugging.assert_near(lowercase_       ,    lowercase_       ,    rtol=1E-3					)




def 							lowerCamelCase			(   UpperCAmelCase__ :      int   ,   UpperCAmelCase__ :      List[Any]   ,   UpperCAmelCase__ :      Optional[int]   ,   UpperCAmelCase__ :      List[Any]=None   ,   UpperCAmelCase__ :      Optional[Any]=None   ,   UpperCAmelCase__ :      Union[str, Any]=None   ,   UpperCAmelCase__ :      Tuple=None   ,   UpperCAmelCase__ :      Optional[int]=None   ,   )    ->   Dict:
							if attention_mask is None:
														lowercase_      :    List[Any]       		= tf.cast(tf.math.not_equal(UpperCAmelCase__   ,   config.pad_token_id				)   ,   tf.inta				)
							if decoder_attention_mask is None:
														lowercase_      :    int       		= tf.concat(
														    [
														        tf.ones(decoder_input_ids[:, :1].shape   ,   dtype=tf.inta				),
														        tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:]   ,   config.pad_token_id				)   ,   tf.inta				),
														    ]   ,   axis=-1   ,   )
							if head_mask is None:
														lowercase_      :    Optional[int]       		= tf.ones((config.encoder_layers, config.encoder_attention_heads)				)
							if decoder_head_mask is None:
														lowercase_      :    Any       		= tf.ones((config.decoder_layers, config.decoder_attention_heads)				)
							if cross_attn_head_mask is None:
														lowercase_      :    Optional[Any]       		= tf.ones((config.decoder_layers, config.decoder_attention_heads)				)
							return {
							    "input_ids": input_ids,
							    "decoder_input_ids": decoder_input_ids,
							    "attention_mask": attention_mask,
							    "decoder_attention_mask": decoder_attention_mask,
							    "head_mask": head_mask,
							    "decoder_head_mask": decoder_head_mask,
							    "cross_attn_head_mask": cross_attn_head_mask,
							}





@require_tf
class 					__magic_name__		(					_UpperCAmelCase,  _UpperCAmelCase,  unittest.TestCase):
			UpperCamelCase__       = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else ()
			UpperCamelCase__       = (TFPegasusForConditionalGeneration,) if is_tf_available() else ()
			UpperCamelCase__       = (
			    {
			        '''conversational''': TFPegasusForConditionalGeneration,
			        '''feature-extraction''': TFPegasusModel,
			        '''summarization''': TFPegasusForConditionalGeneration,
			        '''text2text-generation''': TFPegasusForConditionalGeneration,
			        '''translation''': TFPegasusForConditionalGeneration,
			    }
			    if is_tf_available()
			    else {}
			)
			UpperCamelCase__       = True
			UpperCamelCase__       = False
			UpperCamelCase__       = False







			def 			SCREAMING_SNAKE_CASE_  (			self       :						List[str]					):
										lowercase_      :    Dict       		= TFPegasusModelTester(self					)
										lowercase_      :    Any       		= ConfigTester(self       ,    config_class=lowercase_					)







			def 			SCREAMING_SNAKE_CASE_  (			self       :						Dict					):
										self.config_tester.run_common_tests()







			def 			SCREAMING_SNAKE_CASE_  (			self       :						List[Any]					):
										lowercase_      :    int       		= self.model_tester.prepare_config_and_inputs_for_common()
										self.model_tester.check_decoder_model_past_large_inputs(*lowercase_					)





@require_sentencepiece
@require_tokenizers
@require_tf
class 					__magic_name__		(					unittest.TestCase):
			UpperCamelCase__       = [
			    ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''',
			    ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a  re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''',
			]
			UpperCamelCase__       = [
			    '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to'''
			    ''' reduce the risk of wildfires.''',
			    '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''',
			]  # differs slightly from pytorch, likely due to numerical differences in linear layers
			UpperCamelCase__       = '''google/pegasus-xsum'''







			@cached_property
			def 			SCREAMING_SNAKE_CASE_  (			self       :						Dict					):
										return AutoTokenizer.from_pretrained(self.model_name					)







			@cached_property
			def 			SCREAMING_SNAKE_CASE_  (			self       :						List[str]					):
										lowercase_      :    Any       		= TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name					)
										return model







			def 			SCREAMING_SNAKE_CASE_  (			self       :						Union[str, Any]       ,    **lowercase_       :						Any					):
										lowercase_      :    List[Any]       		= self.translate_src_text(**lowercase_					)
										assert self.expected_text == generated_words







			def 			SCREAMING_SNAKE_CASE_  (			self       :						Union[str, Any]       ,    **lowercase_       :						List[Any]					):
										lowercase_      :    Optional[Any]       		= self.tokenizer(self.src_text       ,    **lowercase_       ,    padding=lowercase_       ,    return_tensors="""tf"""					)
										lowercase_      :    int       		= self.model.generate(
										    model_inputs.input_ids       ,    attention_mask=model_inputs.attention_mask       ,    num_beams=2       ,    use_cache=lowercase_       ,    )
										lowercase_      :    Union[str, Any]       		= self.tokenizer.batch_decode(generated_ids.numpy()       ,    skip_special_tokens=lowercase_					)
										return generated_words







			@slow
			def 			SCREAMING_SNAKE_CASE_  (			self       :						Any					):
										self._assert_generated_batch_equal_expected()






'''simple docstring'''




import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import TimesformerConfig
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
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch
						from torch import nn

						from transformers import (
						    MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
						    TimesformerForVideoClassification,
						    TimesformerModel,
						)
						from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from transformers import VideoMAEImageProcessor





class 					__magic_name__		:







			def __init__(			self       :						int       ,    lowercase_       :						Optional[Any]       ,    lowercase_       :						List[Any]=13       ,    lowercase_       :						List[str]=10       ,    lowercase_       :						Union[str, Any]=3       ,    lowercase_       :						str=2       ,    lowercase_       :						Optional[Any]=2       ,    lowercase_       :						int=True       ,    lowercase_       :						List[Any]=True       ,    lowercase_       :						Union[str, Any]=32       ,    lowercase_       :						Union[str, Any]=5       ,    lowercase_       :						str=4       ,    lowercase_       :						Dict=37       ,    lowercase_       :						Tuple="gelu"       ,    lowercase_       :						int=0.1       ,    lowercase_       :						Optional[Any]=0.1       ,    lowercase_       :						Any=10       ,    lowercase_       :						Tuple=0.02       ,    lowercase_       :						Any="divided_space_time"       ,    lowercase_       :						Tuple=None       ,    ):
										lowercase_      :    int       		= parent
										lowercase_      :    str       		= batch_size
										lowercase_      :    List[str]       		= image_size
										lowercase_      :    str       		= num_channels
										lowercase_      :    List[Any]       		= patch_size
										lowercase_      :    Optional[Any]       		= num_frames
										lowercase_      :    Dict       		= is_training
										lowercase_      :    int       		= use_labels
										lowercase_      :    List[str]       		= hidden_size
										lowercase_      :    Dict       		= num_hidden_layers
										lowercase_      :    Dict       		= num_attention_heads
										lowercase_      :    Any       		= intermediate_size
										lowercase_      :    Optional[int]       		= hidden_act
										lowercase_      :    Optional[Any]       		= hidden_dropout_prob
										lowercase_      :    List[Any]       		= attention_probs_dropout_prob
										lowercase_      :    Any       		= attention_type
										lowercase_      :    Union[str, Any]       		= initializer_range
										lowercase_      :    List[str]       		= scope
										lowercase_      :    Optional[int]       		= num_labels

										# in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
										lowercase_      :    Dict       		= (image_size // patch_size) ** 2
										lowercase_      :    List[Any]       		= (num_frames) * self.num_patches_per_frame + 1







			def 			SCREAMING_SNAKE_CASE_  (			self       :						Union[str, Any]					):
										lowercase_      :    Optional[Any]       		= floats_tensor(
										    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]					)

										lowercase_      :    int       		= None
										if self.use_labels:
																	lowercase_      :    Optional[int]       		= ids_tensor([self.batch_size]       ,    self.num_labels					)

										lowercase_      :    Optional[Any]       		= self.get_config()

										return config, pixel_values, labels







			def 			SCREAMING_SNAKE_CASE_  (			self       :						List[str]					):
										lowercase_      :    int       		= TimesformerConfig(
										    image_size=self.image_size       ,    patch_size=self.patch_size       ,    num_channels=self.num_channels       ,    num_frames=self.num_frames       ,    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       ,    attention_type=self.attention_type       ,    )
										lowercase_      :    Any       		= self.num_labels
										return config







			def 			SCREAMING_SNAKE_CASE_  (			self       :						int       ,    lowercase_       :						List[Any]       ,    lowercase_       :						Dict       ,    lowercase_       :						List[str]					):
										lowercase_      :    Optional[Any]       		= TimesformerModel(config=lowercase_					)
										model.to(lowercase_					)
										model.eval()
										lowercase_      :    int       		= model(lowercase_					)
										self.parent.assertEqual(result.last_hidden_state.shape       ,    (self.batch_size, self.seq_length, self.hidden_size)					)







			def 			SCREAMING_SNAKE_CASE_  (			self       :						List[str]       ,    lowercase_       :						Optional[int]       ,    lowercase_       :						List[str]       ,    lowercase_       :						str					):
										lowercase_      :    Dict       		= TimesformerForVideoClassification(lowercase_					)
										model.to(lowercase_					)
										model.eval()

										lowercase_      :    int       		= model(lowercase_					)

										# verify the logits shape
										lowercase_      :    List[Any]       		= torch.Size((self.batch_size, self.num_labels)					)
										self.parent.assertEqual(result.logits.shape       ,    lowercase_					)







			def 			SCREAMING_SNAKE_CASE_  (			self       :						Optional[Any]					):
										lowercase_      :    List[str]       		= self.prepare_config_and_inputs()
										lowercase_		,		lowercase_		,		lowercase_      :    int       		= config_and_inputs
										lowercase_      :    List[Any]       		= {"""pixel_values""": pixel_values}
										return config, inputs_dict





@require_torch
class 					__magic_name__		(					_UpperCAmelCase,  _UpperCAmelCase,  unittest.TestCase):
			UpperCamelCase__       = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
			UpperCamelCase__       = (
			    {'''feature-extraction''': TimesformerModel, '''video-classification''': TimesformerForVideoClassification}
			    if is_torch_available()
			    else {}
			)

			UpperCamelCase__       = False
			UpperCamelCase__       = False
			UpperCamelCase__       = False
			UpperCamelCase__       = False







			def 			SCREAMING_SNAKE_CASE_  (			self       :						Dict					):
										lowercase_      :    Any       		= TimesformerModelTester(self					)
										lowercase_      :    Union[str, Any]       		= ConfigTester(
										    self       ,    config_class=lowercase_       ,    has_text_modality=lowercase_       ,    hidden_size=37					)







			def 			SCREAMING_SNAKE_CASE_  (			self       :						int       ,    lowercase_       :						Any       ,    lowercase_       :						List[str]       ,    lowercase_       :						Tuple=False					):
										lowercase_      :    List[Any]       		= copy.deepcopy(lowercase_					)

										if return_labels:
																	if model_class in get_values(lowercase_					):
																								lowercase_      :    List[str]       		= torch.zeros(
																								    self.model_tester.batch_size       ,    dtype=torch.long       ,    device=lowercase_					)

										return inputs_dict







			def 			SCREAMING_SNAKE_CASE_  (			self       :						Union[str, Any]					):
										self.config_tester.run_common_tests()







			@unittest.skip(reason="""TimeSformer does not use inputs_embeds"""					)
			def 			SCREAMING_SNAKE_CASE_  (			self       :						Optional[Any]					):
										pass







			def 			SCREAMING_SNAKE_CASE_  (			self       :						Optional[Any]					):
										lowercase_		,		lowercase_      :    Any       		= self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																	lowercase_      :    str       		= model_class(lowercase_					)
																	self.assertIsInstance(model.get_input_embeddings()       ,    (nn.Module)					)
																	lowercase_      :    Optional[int]       		= model.get_output_embeddings()
																	self.assertTrue(x is None or isinstance(lowercase_       ,    nn.Linear					)					)







			def 			SCREAMING_SNAKE_CASE_  (			self       :						Any					):
										lowercase_		,		lowercase_      :    str       		= self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																	lowercase_      :    Dict       		= model_class(lowercase_					)
																	lowercase_      :    Optional[Any]       		= inspect.signature(model.forward					)
																	# signature.parameters is an OrderedDict => so arg_names order is deterministic
																	lowercase_      :    Union[str, Any]       		= [*signature.parameters.keys()]

																	lowercase_      :    str       		= ["""pixel_values"""]
																	self.assertListEqual(arg_names[:1]       ,    lowercase_					)







			def 			SCREAMING_SNAKE_CASE_  (			self       :						str					):
										lowercase_      :    List[str]       		= self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowercase_					)







			def 			SCREAMING_SNAKE_CASE_  (			self       :						str					):
										lowercase_      :    str       		= self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_video_classification(*lowercase_					)







			@slow
			def 			SCREAMING_SNAKE_CASE_  (			self       :						Any					):
										for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	lowercase_      :    Any       		= TimesformerModel.from_pretrained(lowercase_					)
																	self.assertIsNotNone(lowercase_					)







			def 			SCREAMING_SNAKE_CASE_  (			self       :						str					):
										if not self.has_attentions:
																	pass

										else:
																	lowercase_		,		lowercase_      :    Any       		= self.model_tester.prepare_config_and_inputs_for_common()
																	lowercase_      :    List[str]       		= True

																	for model_class in self.all_model_classes:
																								lowercase_      :    str       		= self.model_tester.seq_length
																								lowercase_      :    int       		= self.model_tester.num_frames

																								lowercase_      :    int       		= True
																								lowercase_      :    Any       		= False
																								lowercase_      :    str       		= True
																								lowercase_      :    int       		= model_class(lowercase_					)
																								model.to(lowercase_					)
																								model.eval()
																								with torch.no_grad():
																															lowercase_      :    List[Any]       		= model(**self._prepare_for_class(lowercase_       ,    lowercase_					)					)
																								lowercase_      :    List[str]       		= 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"]
																								lowercase_      :    List[str]       		= True
																								lowercase_      :    str       		= model_class(lowercase_					)
																								model.to(lowercase_					)
																								model.eval()
																								with torch.no_grad():
																															lowercase_      :    Dict       		= model(**self._prepare_for_class(lowercase_       ,    lowercase_					)					)
																								lowercase_      :    int       		= outputs.attentions
																								self.assertEqual(len(lowercase_					)       ,    self.model_tester.num_hidden_layers					)

																								# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
																								self.assertListEqual(
																								    list(attentions[0].shape[-3:]					)       ,    [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]       ,    )
																								lowercase_      :    Optional[Any]       		= len(lowercase_					)

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

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

																								lowercase_      :    Optional[Any]       		= outputs.attentions

																								self.assertEqual(len(lowercase_					)       ,    self.model_tester.num_hidden_layers					)

																								# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
																								self.assertListEqual(
																								    list(self_attentions[0].shape[-3:]					)       ,    [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]       ,    )







			def 			SCREAMING_SNAKE_CASE_  (			self       :						Optional[Any]					):
										def check_hidden_states_output(lowercase_       :						Union[str, Any]       ,    lowercase_       :						Optional[int]       ,    lowercase_       :						Dict					):
																	lowercase_      :    List[str]       		= model_class(lowercase_					)
																	model.to(lowercase_					)
																	model.eval()

																	with torch.no_grad():
																								lowercase_      :    Optional[Any]       		= model(**self._prepare_for_class(lowercase_       ,    lowercase_					)					)

																	lowercase_      :    Dict       		= outputs.hidden_states
																	lowercase_      :    List[Any]       		= self.model_tester.num_hidden_layers + 1
																	self.assertEqual(len(lowercase_					)       ,    lowercase_					)

																	lowercase_      :    List[Any]       		= self.model_tester.seq_length

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

										lowercase_		,		lowercase_      :    List[Any]       		= self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																	lowercase_      :    List[str]       		= True
																	check_hidden_states_output(lowercase_       ,    lowercase_       ,    lowercase_					)

																	# check that output_hidden_states also work using config
																	del inputs_dict["output_hidden_states"]
																	lowercase_      :    Optional[int]       		= True

																	check_hidden_states_output(lowercase_       ,    lowercase_       ,    lowercase_					)




def 							lowerCamelCase			(   )    ->   Optional[int]:
							lowercase_      :    List[str]       		= hf_hub_download(
							    repo_id="""hf-internal-testing/spaghetti-video"""   ,   filename="""eating_spaghetti.npy"""   ,   repo_type="""dataset"""				)
							lowercase_      :    List[Any]       		= np.load(UpperCAmelCase__				)
							return list(UpperCAmelCase__				)





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







			@cached_property
			def 			SCREAMING_SNAKE_CASE_  (			self       :						str					):
										# logits were tested with a different mean and std, so we use the same here
										return (
										    VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]       ,    image_std=[0.5, 0.5, 0.5]					)
										    if is_vision_available()
										    else None
										)







			@slow
			def 			SCREAMING_SNAKE_CASE_  (			self       :						Dict					):
										lowercase_      :    Any       		= TimesformerForVideoClassification.from_pretrained("""facebook/timesformer-base-finetuned-k400"""					).to(
										    lowercase_					)

										lowercase_      :    Optional[Any]       		= self.default_image_processor
										lowercase_      :    Any       		= prepare_video()
										lowercase_      :    Optional[int]       		= image_processor(video[:8]       ,    return_tensors="""pt"""					).to(lowercase_					)

										# forward pass
										with torch.no_grad():
																	lowercase_      :    Optional[Any]       		= model(**lowercase_					)

										# verify the logits
										lowercase_      :    Any       		= torch.Size((1, 400)					)
										self.assertEqual(outputs.logits.shape       ,    lowercase_					)

										lowercase_      :    int       		= torch.tensor([-0.30_16, -0.77_13, -0.42_05]					).to(lowercase_					)

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





