




import math







class     __lowerCAmelCase :

			"""simple docstring"""







			def __init__(      self			,						lowerCamelCase__=0							)    ->      Union[str, Any]:  # a graph with Node 0,1,...,N-1



							'''simple docstring'''
							__lowerCamelCase		       =    n
							__lowerCamelCase		       =    [
							    [math.inf for j in range(0			,						lowerCamelCase__							)] for i in range(0			,						lowerCamelCase__							)
							]  # adjacency matrix for weight
							__lowerCamelCase		       =    [
							    [math.inf for j in range(0			,						lowerCamelCase__							)] for i in range(0			,						lowerCamelCase__							)
							]  # dp[i][j] stores minimum distance from i to j


			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Optional[int]:



							'''simple docstring'''
							__lowerCamelCase		       =    w


			def       lowercase_    (      self							)    ->      Any:



							'''simple docstring'''
							for k in range(0			,						self.n							):
											for i in range(0			,						self.n							):
															for j in range(0			,						self.n							):
																			__lowerCamelCase		       =    min(self.dp[i][j]			,						self.dp[i][k] + self.dp[k][j]							)






			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Any:



							'''simple docstring'''
							return self.dp[u][v]


if __name__ == "__main__":
					__A        =    Graph(5)
					graph.add_edge(0, 2, 9)
					graph.add_edge(0, 4, 10)
					graph.add_edge(1, 3, 5)
					graph.add_edge(2, 3, 7)
					graph.add_edge(3, 0, 10)
					graph.add_edge(3, 1, 2)
					graph.add_edge(3, 2, 1)
					graph.add_edge(3, 4, 6)
					graph.add_edge(4, 1, 3)
					graph.add_edge(4, 2, 4)
					graph.add_edge(4, 3, 9)
					graph.floyd_warshall()
					graph.show_min(1, 4)
					graph.show_min(0, 3)








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

			"""simple docstring"""







			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			,						)    ->      Any:



							'''simple docstring'''
							__lowerCamelCase		       =    parent
							__lowerCamelCase		       =    batch_size
							__lowerCamelCase		       =    image_size
							__lowerCamelCase		       =    num_channels
							__lowerCamelCase		       =    patch_size
							__lowerCamelCase		       =    num_frames
							__lowerCamelCase		       =    is_training
							__lowerCamelCase		       =    use_labels
							__lowerCamelCase		       =    hidden_size
							__lowerCamelCase		       =    num_hidden_layers
							__lowerCamelCase		       =    num_attention_heads
							__lowerCamelCase		       =    intermediate_size
							__lowerCamelCase		       =    hidden_act
							__lowerCamelCase		       =    hidden_dropout_prob
							__lowerCamelCase		       =    attention_probs_dropout_prob
							__lowerCamelCase		       =    attention_type
							__lowerCamelCase		       =    initializer_range
							__lowerCamelCase		       =    scope
							__lowerCamelCase		       =    num_labels

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


			def       lowercase_    (      self							)    ->      Optional[int]:



							'''simple docstring'''
							__lowerCamelCase		       =    floats_tensor(
							    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]							)

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

							__lowerCamelCase		       =    self.get_config()

							return config, pixel_values, labels


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



							'''simple docstring'''
							__lowerCamelCase		       =    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			,						)
							__lowerCamelCase		       =    self.num_labels
							return config


			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Tuple:



							'''simple docstring'''
							__lowerCamelCase		       =    TimesformerModel(config=lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()
							__lowerCamelCase		       =    model(lowerCamelCase__							)
							self.parent.assertEqual(result.last_hidden_state.shape			,						(self.batch_size, self.seq_length, self.hidden_size)							)


			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Union[str, Any]:



							'''simple docstring'''
							__lowerCamelCase		       =    TimesformerForVideoClassification(lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()

							__lowerCamelCase		       =    model(lowerCamelCase__							)

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






			def       lowercase_    (      self							)    ->      Tuple:



							'''simple docstring'''
							__lowerCamelCase		       =    self.prepare_config_and_inputs()
							__lowerCamelCase       ,						__lowerCamelCase       ,						__lowerCamelCase		       =    config_and_inputs
							__lowerCamelCase		       =    {'pixel_values': pixel_values}
							return config, inputs_dict







@require_torch
class     __lowerCAmelCase (       __magic_name__			,				__magic_name__			,				unittest.TestCase ):

			"""simple docstring"""







			snake_case_   		=       (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
			snake_case_   		=       (
			    {'''feature-extraction''': TimesformerModel, '''video-classification''': TimesformerForVideoClassification}
			    if is_torch_available()
			    else {}
			)

			snake_case_   		=       False
			snake_case_   		=       False
			snake_case_   		=       False
			snake_case_   		=       False


			def       lowercase_    (      self							)    ->      List[str]:



							'''simple docstring'''
							__lowerCamelCase		       =    TimesformerModelTester(self							)
							__lowerCamelCase		       =    ConfigTester(
							    self			,						config_class=lowerCamelCase__			,						has_text_modality=lowerCamelCase__			,						hidden_size=37							)


			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__=False							)    ->      int:



							'''simple docstring'''
							__lowerCamelCase		       =    copy.deepcopy(lowerCamelCase__							)

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

							return inputs_dict


			def       lowercase_    (      self							)    ->      Optional[int]:



							'''simple docstring'''
							self.config_tester.run_common_tests()


			@unittest.skip(reason='TimeSformer does not use inputs_embeds'							)
			def       lowercase_    (      self							)    ->      List[str]:



							'''simple docstring'''
							pass


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



							'''simple docstring'''
							__lowerCamelCase       ,						__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs_for_common()

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


			def       lowercase_    (      self							)    ->      List[str]:



							'''simple docstring'''
							__lowerCamelCase       ,						__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs_for_common()

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

											__lowerCamelCase		       =    ['pixel_values']
											self.assertListEqual(arg_names[:1]			,						lowerCamelCase__							)


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



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCamelCase__							)


			def       lowercase_    (      self							)    ->      str:



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_video_classification(*lowerCamelCase__							)


			@slow
			def       lowercase_    (      self							)    ->      Dict:



							'''simple docstring'''
							for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__lowerCamelCase		       =    TimesformerModel.from_pretrained(lowerCamelCase__							)
											self.assertIsNotNone(lowerCamelCase__							)


			def       lowercase_    (      self							)    ->      List[Any]:



							'''simple docstring'''
							if not self.has_attentions:
											pass

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

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

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

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

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

															__lowerCamelCase		       =    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       lowercase_    (      self							)    ->      Tuple:



							'''simple docstring'''
							def check_hidden_states_output(lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							):
											__lowerCamelCase		       =    model_class(lowerCamelCase__							)
											model.to(lowerCamelCase__							)
											model.eval()

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

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

											__lowerCamelCase		       =    self.model_tester.seq_length

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

							__lowerCamelCase       ,						__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											__lowerCamelCase		       =    True
											check_hidden_states_output(lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)

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

											check_hidden_states_output(lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)







def 			lowerCamelCase_		(       )     ->       Any:





				"""simple docstring"""


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







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

			"""simple docstring"""







			@cached_property
			def       lowercase_    (      self							)    ->      List[Any]:



							'''simple docstring'''
							# 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       lowercase_    (      self							)    ->      List[str]:



							'''simple docstring'''
							__lowerCamelCase		       =    TimesformerForVideoClassification.from_pretrained('facebook/timesformer-base-finetuned-k400'							).to(
							    lowerCamelCase__							)

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

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

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

							__lowerCamelCase		       =    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							)							)


