'''simple docstring'''




import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()





class 					__magic_name__		(					_UpperCAmelCase,  unittest.TestCase):
   UpperCamelCase__       = KandinskyInpaintPipeline
   UpperCamelCase__       = ['''prompt''', '''image_embeds''', '''negative_image_embeds''', '''image''', '''mask_image''']
   UpperCamelCase__       = [
       '''prompt''',
       '''negative_prompt''',
       '''image_embeds''',
       '''negative_image_embeds''',
       '''image''',
       '''mask_image''',
   ]
   UpperCamelCase__       = [
       '''generator''',
       '''height''',
       '''width''',
       '''latents''',
       '''guidance_scale''',
       '''negative_prompt''',
       '''num_inference_steps''',
       '''return_dict''',
       '''guidance_scale''',
       '''num_images_per_prompt''',
       '''output_type''',
       '''return_dict''',
   ]
   UpperCamelCase__       = False







   @property
   def 			SCREAMING_SNAKE_CASE_  (			self       :						int					):
          return 32







   @property
   def 			SCREAMING_SNAKE_CASE_  (			self       :						List[str]					):
          return 32







   @property
   def 			SCREAMING_SNAKE_CASE_  (			self       :						Dict					):
          return self.time_input_dim







   @property
   def 			SCREAMING_SNAKE_CASE_  (			self       :						str					):
          return self.time_input_dim * 4







   @property
   def 			SCREAMING_SNAKE_CASE_  (			self       :						List[str]					):
          return 100







   @property
   def 			SCREAMING_SNAKE_CASE_  (			self       :						List[Any]					):
          lowercase_      :    Optional[int]       		= XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base"""					)
          return tokenizer







   @property
   def 			SCREAMING_SNAKE_CASE_  (			self       :						int					):
          torch.manual_seed(0					)
          lowercase_      :    int       		= MCLIPConfig(
              numDims=self.cross_attention_dim       ,    transformerDimensions=self.text_embedder_hidden_size       ,    hidden_size=self.text_embedder_hidden_size       ,    intermediate_size=37       ,    num_attention_heads=4       ,    num_hidden_layers=5       ,    vocab_size=1005       ,    )

          lowercase_      :    List[str]       		= MultilingualCLIP(lowercase_					)
          lowercase_      :    Any       		= text_encoder.eval()

          return text_encoder







   @property
   def 			SCREAMING_SNAKE_CASE_  (			self       :						Dict					):
          torch.manual_seed(0					)

          lowercase_      :    int       		= {
              """in_channels""": 9,
              # Out channels is double in channels because predicts mean and variance
              """out_channels""": 8,
              """addition_embed_type""": """text_image""",
              """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""),
              """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""),
              """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""",
              """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2),
              """layers_per_block""": 1,
              """encoder_hid_dim""": self.text_embedder_hidden_size,
              """encoder_hid_dim_type""": """text_image_proj""",
              """cross_attention_dim""": self.cross_attention_dim,
              """attention_head_dim""": 4,
              """resnet_time_scale_shift""": """scale_shift""",
              """class_embed_type""": None,
          }

          lowercase_      :    Dict       		= UNetaDConditionModel(**lowercase_					)
          return model







   @property
   def 			SCREAMING_SNAKE_CASE_  (			self       :						Tuple					):
          return {
              "block_out_channels": [32, 64],
              "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
              "in_channels": 3,
              "latent_channels": 4,
              "layers_per_block": 1,
              "norm_num_groups": 8,
              "norm_type": "spatial",
              "num_vq_embeddings": 12,
              "out_channels": 3,
              "up_block_types": [
                  "AttnUpDecoderBlock2D",
                  "UpDecoderBlock2D",
              ],
              "vq_embed_dim": 4,
          }







   @property
   def 			SCREAMING_SNAKE_CASE_  (			self       :						List[str]					):
          torch.manual_seed(0					)
          lowercase_      :    Optional[Any]       		= VQModel(**self.dummy_movq_kwargs					)
          return model







   def 			SCREAMING_SNAKE_CASE_  (			self       :						List[Any]					):
          lowercase_      :    int       		= self.dummy_text_encoder
          lowercase_      :    int       		= self.dummy_tokenizer
          lowercase_      :    List[str]       		= self.dummy_unet
          lowercase_      :    int       		= self.dummy_movq

          lowercase_      :    Optional[Any]       		= DDIMScheduler(
              num_train_timesteps=1000       ,    beta_schedule="""linear"""       ,    beta_start=0.0_00_85       ,    beta_end=0.0_12       ,    clip_sample=lowercase_       ,    set_alpha_to_one=lowercase_       ,    steps_offset=1       ,    prediction_type="""epsilon"""       ,    thresholding=lowercase_       ,    )

          lowercase_      :    Any       		= {
              """text_encoder""": text_encoder,
              """tokenizer""": tokenizer,
              """unet""": unet,
              """scheduler""": scheduler,
              """movq""": movq,
          }

          return components







   def 			SCREAMING_SNAKE_CASE_  (			self       :						List[Any]       ,    lowercase_       :						Optional[Any]       ,    lowercase_       :						Dict=0					):
          lowercase_      :    List[str]       		= floats_tensor((1, self.cross_attention_dim)       ,    rng=random.Random(lowercase_					)					).to(lowercase_					)
          lowercase_      :    Dict       		= floats_tensor((1, self.cross_attention_dim)       ,    rng=random.Random(seed + 1					)					).to(lowercase_					)
          # create init_image
          lowercase_      :    Optional[Any]       		= floats_tensor((1, 3, 64, 64)       ,    rng=random.Random(lowercase_					)					).to(lowercase_					)
          lowercase_      :    Dict       		= image.cpu().permute(0       ,    2       ,    3       ,    1					)[0]
          lowercase_      :    Dict       		= Image.fromarray(np.uinta(lowercase_					)					).convert("""RGB"""					).resize((256, 256)					)
          # create mask
          lowercase_      :    Tuple       		= np.ones((64, 64)       ,    dtype=np.floataa					)
          lowercase_      :    Any       		= 0

          if str(lowercase_					).startswith("""mps"""					):
                 lowercase_      :    Optional[Any]       		= torch.manual_seed(lowercase_					)
          else:
                 lowercase_      :    List[Any]       		= torch.Generator(device=lowercase_					).manual_seed(lowercase_					)
          lowercase_      :    Union[str, Any]       		= {
              """prompt""": """horse""",
              """image""": init_image,
              """mask_image""": mask,
              """image_embeds""": image_embeds,
              """negative_image_embeds""": negative_image_embeds,
              """generator""": generator,
              """height""": 64,
              """width""": 64,
              """num_inference_steps""": 2,
              """guidance_scale""": 4.0,
              """output_type""": """np""",
          }
          return inputs







   def 			SCREAMING_SNAKE_CASE_  (			self       :						List[str]					):
          lowercase_      :    Optional[int]       		= """cpu"""

          lowercase_      :    Tuple       		= self.get_dummy_components()

          lowercase_      :    List[Any]       		= self.pipeline_class(**lowercase_					)
          lowercase_      :    Dict       		= pipe.to(lowercase_					)

          pipe.set_progress_bar_config(disable=lowercase_					)

          lowercase_      :    Union[str, Any]       		= pipe(**self.get_dummy_inputs(lowercase_					)					)
          lowercase_      :    Dict       		= output.images

          lowercase_      :    str       		= pipe(
              **self.get_dummy_inputs(lowercase_					)       ,    return_dict=lowercase_       ,    )[0]

          lowercase_      :    List[Any]       		= image[0, -3:, -3:, -1]
          lowercase_      :    Optional[Any]       		= image_from_tuple[0, -3:, -3:, -1]

          print(f'''image.shape {image.shape}'''					)

          assert image.shape == (1, 64, 64, 3)

          lowercase_      :    Optional[Any]       		= np.array(
              [0.8_32_69_19, 0.73_79_04_67, 0.20_91_85_81, 0.9_30_96_12, 0.5_51_17_91, 0.43_71_33_28, 0.5_51_33_21, 0.49_92_29_34, 0.59_49_77_86]					)

          assert (
              np.abs(image_slice.flatten() - expected_slice					).max() < 1E-2
          ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}'''
          assert (
              np.abs(image_from_tuple_slice.flatten() - expected_slice					).max() < 1E-2
          ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'''







   def 			SCREAMING_SNAKE_CASE_  (			self       :						Optional[int]					):
          super().test_inference_batch_single_identical(expected_max_diff=3E-3					)





@slow
@require_torch_gpu
class 					__magic_name__		(					unittest.TestCase):







   def 			SCREAMING_SNAKE_CASE_  (			self       :						Any					):
          # clean up the VRAM after each test
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()







   def 			SCREAMING_SNAKE_CASE_  (			self       :						List[Any]					):
          lowercase_      :    Any       		= load_numpy(
              """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
              """/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy"""					)

          lowercase_      :    str       		= load_image(
              """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png"""					)
          lowercase_      :    Dict       		= np.ones((768, 768)       ,    dtype=np.floataa					)
          lowercase_      :    Union[str, Any]       		= 0

          lowercase_      :    Optional[Any]       		= """a hat"""

          lowercase_      :    List[str]       		= KandinskyPriorPipeline.from_pretrained(
              """kandinsky-community/kandinsky-2-1-prior"""       ,    torch_dtype=torch.floataa					)
          pipe_prior.to(lowercase_					)

          lowercase_      :    Optional[Any]       		= KandinskyInpaintPipeline.from_pretrained(
              """kandinsky-community/kandinsky-2-1-inpaint"""       ,    torch_dtype=torch.floataa					)
          lowercase_      :    Tuple       		= pipeline.to(lowercase_					)
          pipeline.set_progress_bar_config(disable=lowercase_					)

          lowercase_      :    Optional[Any]       		= torch.Generator(device="""cpu"""					).manual_seed(0					)
          lowercase_      :    Any       		= pipe_prior(
              lowercase_       ,    generator=lowercase_       ,    num_inference_steps=5       ,    negative_prompt=""""""       ,    ).to_tuple()

          lowercase_      :    Optional[int]       		= pipeline(
              lowercase_       ,    image=lowercase_       ,    mask_image=lowercase_       ,    image_embeds=lowercase_       ,    negative_image_embeds=lowercase_       ,    generator=lowercase_       ,    num_inference_steps=100       ,    height=768       ,    width=768       ,    output_type="""np"""       ,    )

          lowercase_      :    Optional[int]       		= output.images[0]

          assert image.shape == (768, 768, 3)

          assert_mean_pixel_difference(lowercase_       ,    lowercase_					)






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





