



'''simple docstring'''




import inspect
import unittest

from transformers import ResNetConfig
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_backbone_common import BackboneTesterMixin
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 ResNetBackbone, ResNetForImageClassification, ResNetModel
							from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor

class      UpperCamelCase_					:





	def __init__(    self						,						A						,						A=3						,						A=32						,						A=3						,						A=10						,						A=[10, 20, 30, 40]						,						A=[1, 1, 2, 1]						,						A=True						,						A=True						,						A="relu"						,						A=3						,						A=None						,						A=["stage2", "stage3", "stage4"]						,						A=[2, 3, 4]						,						)     ->     Optional[int]:
								UpperCAmelCase	:						List[str]					=						parent
								UpperCAmelCase	:						List[str]					=						batch_size
								UpperCAmelCase	:						List[Any]					=						image_size
								UpperCAmelCase	:						Tuple					=						num_channels
								UpperCAmelCase	:						Dict					=						embeddings_size
								UpperCAmelCase	:						Union[str, Any]					=						hidden_sizes
								UpperCAmelCase	:						List[str]					=						depths
								UpperCAmelCase	:						str					=						is_training
								UpperCAmelCase	:						Tuple					=						use_labels
								UpperCAmelCase	:						str					=						hidden_act
								UpperCAmelCase	:						Tuple					=						num_labels
								UpperCAmelCase	:						Tuple					=						scope
								UpperCAmelCase	:						List[Any]					=						len(A       )
								UpperCAmelCase	:						Tuple					=						out_features
								UpperCAmelCase	:						Tuple					=						out_indices





	def 					_lowercase(    self       )     ->     Any:
								UpperCAmelCase	:						Optional[int]					=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

								UpperCAmelCase	:						str					=						None
								if self.use_labels:
															UpperCAmelCase	:						List[str]					=						ids_tensor([self.batch_size]						,						self.num_labels       )

								UpperCAmelCase	:						List[str]					=						self.get_config()

								return config, pixel_values, labels





	def 					_lowercase(    self       )     ->     Optional[Any]:
								return ResNetConfig(
								    num_channels=self.num_channels						,						embeddings_size=self.embeddings_size						,						hidden_sizes=self.hidden_sizes						,						depths=self.depths						,						hidden_act=self.hidden_act						,						num_labels=self.num_labels						,						out_features=self.out_features						,						out_indices=self.out_indices						,						)





	def 					_lowercase(    self						,						A						,						A						,						A       )     ->     Union[str, Any]:
								UpperCAmelCase	:						Dict					=						ResNetModel(config=A       )
								model.to(A       )
								model.eval()
								UpperCAmelCase	:						str					=						model(A       )
								# expected last hidden states: B, C, H // 32, W // 32
								self.parent.assertEqual(
								    result.last_hidden_state.shape						,						(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)						,						)





	def 					_lowercase(    self						,						A						,						A						,						A       )     ->     List[str]:
								UpperCAmelCase	:						List[Any]					=						self.num_labels
								UpperCAmelCase	:						str					=						ResNetForImageClassification(A       )
								model.to(A       )
								model.eval()
								UpperCAmelCase	:						Union[str, Any]					=						model(A						,						labels=A       )
								self.parent.assertEqual(result.logits.shape						,						(self.batch_size, self.num_labels)       )





	def 					_lowercase(    self						,						A						,						A						,						A       )     ->     str:
								UpperCAmelCase	:						List[str]					=						ResNetBackbone(config=A       )
								model.to(A       )
								model.eval()
								UpperCAmelCase	:						List[Any]					=						model(A       )

								# verify feature maps
								self.parent.assertEqual(len(result.feature_maps       )						,						len(config.out_features       )       )
								self.parent.assertListEqual(list(result.feature_maps[0].shape       )						,						[self.batch_size, self.hidden_sizes[1], 4, 4]       )

								# verify channels
								self.parent.assertEqual(len(model.channels       )						,						len(config.out_features       )       )
								self.parent.assertListEqual(model.channels						,						config.hidden_sizes[1:]       )

								# verify backbone works with out_features=None
								UpperCAmelCase	:						Union[str, Any]					=						None
								UpperCAmelCase	:						Tuple					=						ResNetBackbone(config=A       )
								model.to(A       )
								model.eval()
								UpperCAmelCase	:						Dict					=						model(A       )

								# verify feature maps
								self.parent.assertEqual(len(result.feature_maps       )						,						1       )
								self.parent.assertListEqual(list(result.feature_maps[0].shape       )						,						[self.batch_size, self.hidden_sizes[-1], 1, 1]       )

								# verify channels
								self.parent.assertEqual(len(model.channels       )						,						1       )
								self.parent.assertListEqual(model.channels						,						[config.hidden_sizes[-1]]       )






	def 					_lowercase(    self       )     ->     Dict:
								UpperCAmelCase	:						List[str]					=						self.prepare_config_and_inputs()
								UpperCAmelCase	,	UpperCAmelCase	,	UpperCAmelCase	:						Dict					=						config_and_inputs
								UpperCAmelCase	:						List[Any]					=						{"""pixel_values""": pixel_values}
								return config, inputs_dict




@require_torch
class      UpperCamelCase_					(				__magic_name__ ,	__magic_name__ ,	unittest.TestCase     ):
	lowercase		=					(
	    (
	        ResNetModel,
	        ResNetForImageClassification,
	        ResNetBackbone,
	    )
	    if is_torch_available()
	    else ()
	)
	lowercase		=					(
	    {'feature-extraction': ResNetModel, 'image-classification': ResNetForImageClassification}
	    if is_torch_available()
	    else {}
	)

	lowercase		=					True
	lowercase		=					False
	lowercase		=					False
	lowercase		=					False
	lowercase		=					False





	def 					_lowercase(    self       )     ->     Optional[Any]:
								UpperCAmelCase	:						Dict					=						ResNetModelTester(self       )
								UpperCAmelCase	:						str					=						ConfigTester(self						,						config_class=A						,						has_text_modality=A       )





	def 					_lowercase(    self       )     ->     List[str]:
								self.create_and_test_config_common_properties()
								self.config_tester.create_and_test_config_to_json_string()
								self.config_tester.create_and_test_config_to_json_file()
								self.config_tester.create_and_test_config_from_and_save_pretrained()
								self.config_tester.create_and_test_config_with_num_labels()
								self.config_tester.check_config_can_be_init_without_params()
								self.config_tester.check_config_arguments_init()





	def 					_lowercase(    self       )     ->     List[Any]:
								return





	@unittest.skip(reason="""ResNet does not use inputs_embeds"""       )
	def 					_lowercase(    self       )     ->     Any:
								pass





	@unittest.skip(reason="""ResNet does not support input and output embeddings"""       )
	def 					_lowercase(    self       )     ->     List[Any]:
								pass





	def 					_lowercase(    self       )     ->     Union[str, Any]:
								UpperCAmelCase	,	UpperCAmelCase	:						Optional[int]					=						self.model_tester.prepare_config_and_inputs_for_common()

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

															UpperCAmelCase	:						List[Any]					=						["""pixel_values"""]
															self.assertListEqual(arg_names[:1]						,						A       )





	def 					_lowercase(    self       )     ->     Optional[Any]:
								UpperCAmelCase	:						Any					=						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*A       )





	def 					_lowercase(    self       )     ->     Dict:
								UpperCAmelCase	:						Optional[Any]					=						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_backbone(*A       )





	def 					_lowercase(    self       )     ->     Dict:
								UpperCAmelCase	,	UpperCAmelCase	:						Any					=						self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															UpperCAmelCase	:						Union[str, Any]					=						model_class(config=A       )
															for name, module in model.named_modules():
																						if isinstance(A						,						(nn.BatchNormad, nn.GroupNorm)       ):
																													self.assertTrue(
																													    torch.all(module.weight == 1       )						,						msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''						,						)
																													self.assertTrue(
																													    torch.all(module.bias == 0       )						,						msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''						,						)





	def 					_lowercase(    self       )     ->     Any:
								def check_hidden_states_output(A						,						A						,						A       ):
															UpperCAmelCase	:						int					=						model_class(A       )
															model.to(A       )
															model.eval()

															with torch.no_grad():
																						UpperCAmelCase	:						List[Any]					=						model(**self._prepare_for_class(A						,						A       )       )

															UpperCAmelCase	:						int					=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

															UpperCAmelCase	:						Union[str, Any]					=						self.model_tester.num_stages
															self.assertEqual(len(A       )						,						expected_num_stages + 1       )

															# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
															self.assertListEqual(
															    list(hidden_states[0].shape[-2:]       )						,						[self.model_tester.image_size // 4, self.model_tester.image_size // 4]						,						)

								UpperCAmelCase	,	UpperCAmelCase	:						str					=						self.model_tester.prepare_config_and_inputs_for_common()
								UpperCAmelCase	:						Any					=						["""basic""", """bottleneck"""]
								for model_class in self.all_model_classes:
															for layer_type in layers_type:
																						UpperCAmelCase	:						Optional[int]					=						layer_type
																						UpperCAmelCase	:						List[str]					=						True
																						check_hidden_states_output(A						,						A						,						A       )

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

																						check_hidden_states_output(A						,						A						,						A       )





	@unittest.skip(reason="""ResNet does not use feedforward chunking"""       )
	def 					_lowercase(    self       )     ->     List[Any]:
								pass





	def 					_lowercase(    self       )     ->     str:
								UpperCAmelCase	:						Union[str, Any]					=						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*A       )






	@slow
	def 					_lowercase(    self       )     ->     Optional[Any]:
								for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															UpperCAmelCase	:						List[str]					=						ResNetModel.from_pretrained(A       )
															self.assertIsNotNone(A       )




def  __lowerCamelCase    (   ) ->     str:
							UpperCAmelCase	:						int					=						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
							return image

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





	@cached_property
	def 					_lowercase(    self       )     ->     List[str]:
								return (
								    AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )
								    if is_vision_available()
								    else None
								)






	@slow
	def 					_lowercase(    self       )     ->     str:
								UpperCAmelCase	:						Any					=						ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ).to(A       )

								UpperCAmelCase	:						List[str]					=						self.default_image_processor
								UpperCAmelCase	:						int					=						prepare_img()
								UpperCAmelCase	:						int					=						image_processor(images=A						,						return_tensors="""pt"""       ).to(A       )

								# forward pass
								with torch.no_grad():
															UpperCAmelCase	:						List[str]					=						model(**A       )

								# verify the logits
								UpperCAmelCase	:						Union[str, Any]					=						torch.Size((1, 1000)       )
								self.assertEqual(outputs.logits.shape						,						A       )

								UpperCAmelCase	:						List[str]					=						torch.tensor([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]       ).to(A       )

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




@require_torch
class      UpperCamelCase_					(				__magic_name__ ,	unittest.TestCase     ):
	lowercase		=					(ResNetBackbone,) if is_torch_available() else ()
	lowercase		=					False
	lowercase		=					ResNetConfig





	def 					_lowercase(    self       )     ->     str:
								UpperCAmelCase	:						Optional[Any]					=						ResNetModelTester(self       )






'''simple docstring'''




class      UpperCamelCase_					:





	def __init__(    self       )     ->     None:
								UpperCAmelCase	:						int					=						[0, 1]






	def 					_lowercase(    self						,						A       )     ->     list:
								if (difference := index - (len(self.sequence       ) - 2)) >= 1:
															for _ in range(A       ):
																						self.sequence.append(self.sequence[-1] + self.sequence[-2]       )
								return self.sequence[:index]




def  __lowerCamelCase    (   ) ->     None:
							print(
							    """Fibonacci Series Using Dynamic Programming\n"""      ,							"""Enter the index of the Fibonacci number you want to calculate """      ,							"""in the prompt below. (To exit enter exit or Ctrl-C)\n"""      ,							sep=""""""      ,							)
							UpperCAmelCase	:						Tuple					=						Fibonacci()

							while True:
														UpperCAmelCase	:						str					=						input(""">> """						)
														if prompt in {"exit", "quit"}:
																					break

														try:
																					UpperCAmelCase	:						int					=						int(_lowercase						)
														except ValueError:
																					print("""Enter a number or 'exit'"""						)
																					continue

														print(fibonacci.get(_lowercase						)						)


if __name__ == "__main__":
							main()

