





import json
import os
from functools import lru_cache
from typing import TYPE_CHECKING, List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
					from transformers.pipelines.conversational import Conversation

UpperCAmelCase_      							=     logging.get_logger(__name__)


UpperCAmelCase_      							=     {
    """vocab_file""": """vocab.json""",
    """merges_file""": """merges.txt""",
    """tokenizer_config_file""": """tokenizer_config.json""",
}

UpperCAmelCase_      							=     {
    """vocab_file""": {"""facebook/blenderbot-3B""": """https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json"""},
    """merges_file""": {"""facebook/blenderbot-3B""": """https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt"""},
    """tokenizer_config_file""": {
        """facebook/blenderbot-3B""": """https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json"""
    },
}

UpperCAmelCase_      							=     {"""facebook/blenderbot-3B""": 128}





@lru_cache()
# Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode
def 						lowerCamelCase__     (     )			-> Dict:



					'''simple docstring'''




					_snake_case									=				(
					    list(range(ord('!'						)       ,    ord('~'						) + 1						)						) + list(range(ord('¡'						)       ,    ord('¬'						) + 1						)						) + list(range(ord('®'						)       ,    ord('ÿ'						) + 1						)						)
					)
					_snake_case									=				bs[:]
					_snake_case									=				0
					for b in range(2**8						):
										if b not in bs:
															bs.append(_lowerCamelCase						)
															cs.append(2**8 + n						)
															n += 1
					_snake_case									=				[chr(_lowerCamelCase						) for n in cs]
					return dict(zip(_lowerCamelCase       ,    _lowerCamelCase						)						)





def 						lowerCamelCase__     (     UpperCamelCase__			:       Dict						)			-> List[Any]:



					'''simple docstring'''




					_snake_case									=				set()
					_snake_case									=				word[0]
					for char in word[1:]:
										pairs.add((prev_char, char)						)
										_snake_case									=				char
					return pairs




class 			UpperCamelCase_		(  a__					):
					lowerCAmelCase_							=	VOCAB_FILES_NAMES
					lowerCAmelCase_							=	PRETRAINED_VOCAB_FILES_MAP
					lowerCAmelCase_							=	PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					lowerCAmelCase_							=	['''input_ids''', '''attention_mask''']




					def __init__(		self				,						lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_="replace"				,						lowerCAmelCase_="<s>"				,						lowerCAmelCase_="</s>"				,						lowerCAmelCase_="</s>"				,						lowerCAmelCase_="<s>"				,						lowerCAmelCase_="<unk>"				,						lowerCAmelCase_="<pad>"				,						lowerCAmelCase_="<mask>"				,						lowerCAmelCase_=False				,						**lowerCAmelCase_				,						)		->							int:
										_snake_case									=				AddedToken(_A				,						lstrip=_A				,						rstrip=_A  ) if isinstance(_A				,						_A  ) else bos_token
										_snake_case									=				AddedToken(_A				,						lstrip=_A				,						rstrip=_A  ) if isinstance(_A				,						_A  ) else eos_token
										_snake_case									=				AddedToken(_A				,						lstrip=_A				,						rstrip=_A  ) if isinstance(_A				,						_A  ) else sep_token
										_snake_case									=				AddedToken(_A				,						lstrip=_A				,						rstrip=_A  ) if isinstance(_A				,						_A  ) else cls_token
										_snake_case									=				AddedToken(_A				,						lstrip=_A				,						rstrip=_A  ) if isinstance(_A				,						_A  ) else unk_token
										_snake_case									=				AddedToken(_A				,						lstrip=_A				,						rstrip=_A  ) if isinstance(_A				,						_A  ) else pad_token

										# Mask token behave like a normal word, i.e. include the space before it
										_snake_case									=				AddedToken(_A				,						lstrip=_A				,						rstrip=_A  ) if isinstance(_A				,						_A  ) else mask_token

										super().__init__(
										    errors=_A				,						bos_token=_A				,						eos_token=_A				,						unk_token=_A				,						sep_token=_A				,						cls_token=_A				,						pad_token=_A				,						mask_token=_A				,						add_prefix_space=_A				,						**_A				,						)

										with open(_A				,						encoding='utf-8'  ) as vocab_handle:
															_snake_case									=				json.load(_A  )
										_snake_case									=				{v: k for k, v in self.encoder.items()}
										_snake_case									=				errors  # how to handle errors in decoding
										_snake_case									=				bytes_to_unicode()
										_snake_case									=				{v: k for k, v in self.byte_encoder.items()}
										with open(_A				,						encoding='utf-8'  ) as merges_handle:
															_snake_case									=				merges_handle.read().split('\n'  )[1:-1]
										_snake_case									=				[tuple(merge.split()  ) for merge in bpe_merges]
										_snake_case									=				dict(zip(_A				,						range(len(_A  )  )  )  )
										_snake_case									=				{}
										_snake_case									=				add_prefix_space

										# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
										_snake_case									=				re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+'  )




					@property
					# Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot
					def 	lowerCAmelCase			(		self  )		->							Union[str, Any]:
										return len(self.encoder  )




					def 	lowerCAmelCase			(		self  )		->							int:
										return dict(self.encoder				,						**self.added_tokens_encoder  )




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_  )		->							Optional[int]:

										if token in self.cache:
															return self.cache[token]
										_snake_case									=				tuple(_A  )
										_snake_case									=				get_pairs(_A  )

										if not pairs:
															return token

										while True:
															_snake_case									=				min(_A				,						key=lambda lowerCAmelCase_  : self.bpe_ranks.get(_A				,						float('inf'  )  )  )
															if bigram not in self.bpe_ranks:
																				break
															_snake_case									=				bigram
															_snake_case									=				[]
															_snake_case									=				0
															while i < len(_A  ):
																				try:
																									_snake_case									=				word.index(_A				,						_A  )
																				except ValueError:
																									new_word.extend(word[i:]  )
																									break
																				else:
																									new_word.extend(word[i:j]  )
																									_snake_case									=				j

																				if word[i] == first and i < len(_A  ) - 1 and word[i + 1] == second:
																									new_word.append(first + second  )
																									i += 2
																				else:
																									new_word.append(word[i]  )
																									i += 1
															_snake_case									=				tuple(_A  )
															_snake_case									=				new_word
															if len(_A  ) == 1:
																				break
															else:
																				_snake_case									=				get_pairs(_A  )
										_snake_case									=				' '.join(_A  )
										_snake_case									=				word
										return word




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_  )		->							Any:
										_snake_case									=				[]
										for token in re.findall(self.pat				,						_A  ):
															_snake_case									=				''.join(
															    self.byte_encoder[b] for b in token.encode('utf-8'  )  )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
															bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_A  ).split(' '  )  )
										return bpe_tokens




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_  )		->							Union[str, Any]:
										return self.encoder.get(_A				,						self.encoder.get(self.unk_token  )  )




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_  )		->							List[Any]:
										return self.decoder.get(_A  )




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_  )		->							Optional[Any]:
										_snake_case									=				''.join(_A  )
										_snake_case									=				bytearray([self.byte_decoder[c] for c in text]  ).decode('utf-8'				,						errors=self.errors  )
										return text




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_ = None  )		->							Any:

										if not os.path.isdir(_A  ):
															logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''  )
															return
										_snake_case									=				os.path.join(
										    _A				,						(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']  )
										_snake_case									=				os.path.join(
										    _A				,						(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file']  )

										with open(_A				,						'w'				,						encoding='utf-8'  ) as f:
															f.write(json.dumps(self.encoder				,						indent=2				,						sort_keys=_A				,						ensure_ascii=_A  ) + '\n'  )

										_snake_case									=				0
										with open(_A				,						'w'				,						encoding='utf-8'  ) as writer:
															writer.write('#version: 0.2\n'  )
															for bpe_tokens, token_index in sorted(self.bpe_ranks.items()				,						key=lambda lowerCAmelCase_  : kv[1]  ):
																				if index != token_index:
																									logger.warning(
																									    F'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'''
																									    ' Please check that the tokenizer is not corrupted!'  )
																									_snake_case									=				token_index
																				writer.write(' '.join(_A  ) + '\n'  )
																				index += 1

										return vocab_file, merge_file




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = False  )		->							Union[str, Any]:

										if already_has_special_tokens:
															return super().get_special_tokens_mask(
															    token_ids_a=_A				,						token_ids_a=_A				,						already_has_special_tokens=_A  )

										if token_ids_a is None:
															return [1] + ([0] * len(_A  )) + [1]
										return [1] + ([0] * len(_A  )) + [1, 1] + ([0] * len(_A  )) + [1]




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_ = None  )		->							Union[str, Any]:
										_snake_case									=				[self.sep_token_id]
										_snake_case									=				[self.cls_token_id]

										if token_ids_a is None:
															return len(cls + token_ids_a + sep  ) * [0]
										return len(cls + token_ids_a + sep + sep + token_ids_a + sep  ) * [0]




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_=False				,						**lowerCAmelCase_  )		->							List[str]:
										_snake_case									=				kwargs.pop('add_prefix_space'				,						self.add_prefix_space  )
										if (is_split_into_words or add_prefix_space) and (len(_A  ) > 0 and not text[0].isspace()):
															_snake_case									=				' ' + text
										return (text, kwargs)




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_ = None  )		->							Tuple:
										return token_ids_a + [self.eos_token_id]






					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_  )		->							Tuple:
										_snake_case									=				[]
										for is_user, text in conversation.iter_texts():
															if is_user:
																				# We need to space prefix as it's being done within blenderbot
																				inputs.append(' ' + text  )
															else:
																				# Generated responses should contain them already.
																				inputs.append(_A  )

										_snake_case									=				'  '.join(_A  )
										_snake_case									=				self.encode(_A  )
										if len(_A  ) > self.model_max_length:
															_snake_case									=				input_ids[-self.model_max_length :]
															logger.warning(F'''Trimmed input from conversation as it was longer than {self.model_max_length} tokens.'''  )
										return input_ids













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




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

										# in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
										_snake_case									=				(image_size // patch_size) ** 2
										_snake_case									=				(num_frames) * self.num_patches_per_frame + 1




					def 	lowerCAmelCase			(		self  )		->							Optional[Any]:
										_snake_case									=				floats_tensor(
										    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]  )

										_snake_case									=				None
										if self.use_labels:
															_snake_case									=				ids_tensor([self.batch_size]				,						self.num_labels  )

										_snake_case									=				self.get_config()

										return config, pixel_values, labels




					def 	lowerCAmelCase			(		self  )		->							str:
										_snake_case									=				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				,						)
										_snake_case									=				self.num_labels
										return config




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_  )		->							Dict:
										_snake_case									=				TimesformerModel(config=lowerCAmelCase_  )
										model.to(lowerCAmelCase_  )
										model.eval()
										_snake_case									=				model(lowerCAmelCase_  )
										self.parent.assertEqual(result.last_hidden_state.shape				,						(self.batch_size, self.seq_length, self.hidden_size)  )




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_  )		->							Tuple:
										_snake_case									=				TimesformerForVideoClassification(lowerCAmelCase_  )
										model.to(lowerCAmelCase_  )
										model.eval()

										_snake_case									=				model(lowerCAmelCase_  )

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






					def 	lowerCAmelCase			(		self  )		->							Any:
										_snake_case									=				self.prepare_config_and_inputs()
										_snake_case							,     _snake_case							,     _snake_case									=				config_and_inputs
										_snake_case									=				{'pixel_values': pixel_values}
										return config, inputs_dict





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

					lowerCAmelCase_							=	False
					lowerCAmelCase_							=	False
					lowerCAmelCase_							=	False
					lowerCAmelCase_							=	False




					def 	lowerCAmelCase			(		self  )		->							Optional[Any]:
										_snake_case									=				TimesformerModelTester(self  )
										_snake_case									=				ConfigTester(
										    self				,						config_class=lowerCAmelCase_				,						has_text_modality=lowerCAmelCase_				,						hidden_size=37  )




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_=False  )		->							Any:
										_snake_case									=				copy.deepcopy(lowerCAmelCase_  )

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

										return inputs_dict




					def 	lowerCAmelCase			(		self  )		->							List[Any]:
										self.config_tester.run_common_tests()




					@unittest.skip(reason='TimeSformer does not use inputs_embeds'  )
					def 	lowerCAmelCase			(		self  )		->							Tuple:
										pass




					def 	lowerCAmelCase			(		self  )		->							Optional[Any]:
										_snake_case							,     _snake_case									=				self.model_tester.prepare_config_and_inputs_for_common()

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




					def 	lowerCAmelCase			(		self  )		->							Union[str, Any]:
										_snake_case							,     _snake_case									=				self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
															_snake_case									=				model_class(lowerCAmelCase_  )
															_snake_case									=				inspect.signature(model.forward  )
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															_snake_case									=				[*signature.parameters.keys()]

															_snake_case									=				['pixel_values']
															self.assertListEqual(arg_names[:1]				,						lowerCAmelCase_  )




					def 	lowerCAmelCase			(		self  )		->							List[str]:
										_snake_case									=				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase_  )




					def 	lowerCAmelCase			(		self  )		->							Union[str, Any]:
										_snake_case									=				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_video_classification(*lowerCAmelCase_  )




					@slow
					def 	lowerCAmelCase			(		self  )		->							List[Any]:
										for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_snake_case									=				TimesformerModel.from_pretrained(lowerCAmelCase_  )
															self.assertIsNotNone(lowerCAmelCase_  )




					def 	lowerCAmelCase			(		self  )		->							Union[str, Any]:
										if not self.has_attentions:
															pass

										else:
															_snake_case							,     _snake_case									=				self.model_tester.prepare_config_and_inputs_for_common()
															_snake_case									=				True

															for model_class in self.all_model_classes:
																				_snake_case									=				self.model_tester.seq_length
																				_snake_case									=				self.model_tester.num_frames

																				_snake_case									=				True
																				_snake_case									=				False
																				_snake_case									=				True
																				_snake_case									=				model_class(lowerCAmelCase_  )
																				model.to(lowerCAmelCase_  )
																				model.eval()
																				with torch.no_grad():
																									_snake_case									=				model(**self._prepare_for_class(lowerCAmelCase_				,						lowerCAmelCase_  )  )
																				_snake_case									=				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"]
																				_snake_case									=				True
																				_snake_case									=				model_class(lowerCAmelCase_  )
																				model.to(lowerCAmelCase_  )
																				model.eval()
																				with torch.no_grad():
																									_snake_case									=				model(**self._prepare_for_class(lowerCAmelCase_				,						lowerCAmelCase_  )  )
																				_snake_case									=				outputs.attentions
																				self.assertEqual(len(lowerCAmelCase_  )				,						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]				,						)
																				_snake_case									=				len(lowerCAmelCase_  )

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

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

																				_snake_case									=				outputs.attentions

																				self.assertEqual(len(lowerCAmelCase_  )				,						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 	lowerCAmelCase			(		self  )		->							Dict:
										def check_hidden_states_output(lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_  ):
															_snake_case									=				model_class(lowerCAmelCase_  )
															model.to(lowerCAmelCase_  )
															model.eval()

															with torch.no_grad():
																				_snake_case									=				model(**self._prepare_for_class(lowerCAmelCase_				,						lowerCAmelCase_  )  )

															_snake_case									=				outputs.hidden_states
															_snake_case									=				self.model_tester.num_hidden_layers + 1
															self.assertEqual(len(lowerCAmelCase_  )				,						lowerCAmelCase_  )

															_snake_case									=				self.model_tester.seq_length

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

										_snake_case							,     _snake_case									=				self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
															_snake_case									=				True
															check_hidden_states_output(lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_  )

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

															check_hidden_states_output(lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_  )





def 						lowerCamelCase__     (     )			-> Tuple:



					'''simple docstring'''




					_snake_case									=				hf_hub_download(
					    repo_id='hf-internal-testing/spaghetti-video'       ,    filename='eating_spaghetti.npy'       ,    repo_type='dataset'						)
					_snake_case									=				np.load(UpperCamelCase__						)
					return list(UpperCamelCase__						)




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




					@cached_property
					def 	lowerCAmelCase			(		self  )		->							Dict:
										# 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 	lowerCAmelCase			(		self  )		->							Optional[int]:
										_snake_case									=				TimesformerForVideoClassification.from_pretrained('facebook/timesformer-base-finetuned-k400'  ).to(
										    lowerCAmelCase_  )

										_snake_case									=				self.default_image_processor
										_snake_case									=				prepare_video()
										_snake_case									=				image_processor(video[:8]				,						return_tensors='pt'  ).to(lowerCAmelCase_  )

										# forward pass
										with torch.no_grad():
															_snake_case									=				model(**lowerCAmelCase_  )

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

										_snake_case									=				torch.tensor([-0.30_16, -0.77_13, -0.42_05]  ).to(lowerCAmelCase_  )

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



