




"""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 							lowercase   :







				def __init__(				self :       Union[str, Any]   ,  _lowerCamelCase :       Any   ,  _lowerCamelCase :       str=3   ,  _lowerCamelCase :       str=32   ,  _lowerCamelCase :       str=3   ,  _lowerCamelCase :       str=10   ,  _lowerCamelCase :       int=[10, 20, 30, 40]   ,  _lowerCamelCase :       Union[str, Any]=[1, 1, 2, 1]   ,  _lowerCamelCase :       Optional[int]=True   ,  _lowerCamelCase :       str=True   ,  _lowerCamelCase :       Any="relu"   ,  _lowerCamelCase :       List[str]=3   ,  _lowerCamelCase :       str=None   ,  _lowerCamelCase :       Optional[Any]=["stage2", "stage3", "stage4"]   ,  _lowerCamelCase :       Optional[int]=[2, 3, 4]   ,  ):



					"""simple docstring"""

					A_	:					Optional[int]						 =		parent
					A_	:					Union[str, Any]						 =		batch_size
					A_	:					Optional[Any]						 =		image_size
					A_	:					Any						 =		num_channels
					A_	:					Any						 =		embeddings_size
					A_	:					int						 =		hidden_sizes
					A_	:					Optional[Any]						 =		depths
					A_	:					Optional[int]						 =		is_training
					A_	:					List[str]						 =		use_labels
					A_	:					List[Any]						 =		hidden_act
					A_	:					List[Any]						 =		num_labels
					A_	:					List[Any]						 =		scope
					A_	:					Optional[int]						 =		len(_lowerCamelCase							)
					A_	:					str						 =		out_features
					A_	:					Any						 =		out_indices







				def        a_	(				self :       int							):



					"""simple docstring"""

					A_	:					List[str]						 =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

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

					return config, pixel_values, labels







				def        a_	(				self :       List[Any]							):



					"""simple docstring"""

					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        a_	(				self :       str   ,  _lowerCamelCase :       Any   ,  _lowerCamelCase :       Any   ,  _lowerCamelCase :       int							):



					"""simple docstring"""

					A_	:					Any						 =		ResNetModel(config=_lowerCamelCase							)
					model.to(_lowerCamelCase							)
					model.eval()
					A_	:					Optional[Any]						 =		model(_lowerCamelCase							)
					# 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        a_	(				self :       Tuple   ,  _lowerCamelCase :       Optional[int]   ,  _lowerCamelCase :       Optional[Any]   ,  _lowerCamelCase :       int							):



					"""simple docstring"""

					A_	:					Union[str, Any]						 =		self.num_labels
					A_	:					Union[str, Any]						 =		ResNetForImageClassification(_lowerCamelCase							)
					model.to(_lowerCamelCase							)
					model.eval()
					A_	:					List[Any]						 =		model(_lowerCamelCase   ,  labels=_lowerCamelCase							)
					self.parent.assertEqual(result.logits.shape   ,  (self.batch_size, self.num_labels)							)







				def        a_	(				self :       Dict   ,  _lowerCamelCase :       Dict   ,  _lowerCamelCase :       Optional[Any]   ,  _lowerCamelCase :       Optional[Any]							):



					"""simple docstring"""

					A_	:					Tuple						 =		ResNetBackbone(config=_lowerCamelCase							)
					model.to(_lowerCamelCase							)
					model.eval()
					A_	:					Union[str, Any]						 =		model(_lowerCamelCase							)

					# 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
					A_	:					Dict						 =		None
					A_	:					Optional[int]						 =		ResNetBackbone(config=_lowerCamelCase							)
					model.to(_lowerCamelCase							)
					model.eval()
					A_	:					Optional[int]						 =		model(_lowerCamelCase							)

					# 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        a_	(				self :       Union[str, Any]							):



					"""simple docstring"""

					A_	:					List[Any]						 =		self.prepare_config_and_inputs()
					A_ ,			A_ ,			A_	:					Optional[int]						 =		config_and_inputs
					A_	:					str						 =		{'''pixel_values''': pixel_values}
					return config, inputs_dict

@require_torch
class 							lowercase   (     __UpperCAmelCase  ,						__UpperCAmelCase  ,						unittest.TestCase):
				__lowerCAmelCase     :     List[str]								= (
				    (
				        ResNetModel,
				        ResNetForImageClassification,
				        ResNetBackbone,
				    )
				    if is_torch_available()
				    else ()
				)
				__lowerCAmelCase     :     Dict								= (
				    {"""feature-extraction""": ResNetModel, """image-classification""": ResNetForImageClassification}
				    if is_torch_available()
				    else {}
				)

				__lowerCAmelCase     :     Any								= True
				__lowerCAmelCase     :     Optional[Any]								= False
				__lowerCAmelCase     :     str								= False
				__lowerCAmelCase     :     Tuple								= False
				__lowerCAmelCase     :     Dict								= False







				def        a_	(				self :       Optional[int]							):



					"""simple docstring"""

					A_	:					Union[str, Any]						 =		ResNetModelTester(self							)
					A_	:					Union[str, Any]						 =		ConfigTester(self   ,  config_class=_lowerCamelCase   ,  has_text_modality=_lowerCamelCase							)







				def        a_	(				self :       Optional[Any]							):



					"""simple docstring"""

					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        a_	(				self :       int							):



					"""simple docstring"""

					return







				@unittest.skip(reason='''ResNet does not use inputs_embeds'''							)
				def        a_	(				self :       int							):



					"""simple docstring"""

					pass







				@unittest.skip(reason='''ResNet does not support input and output embeddings'''							)
				def        a_	(				self :       List[Any]							):



					"""simple docstring"""

					pass







				def        a_	(				self :       List[Any]							):



					"""simple docstring"""

					A_ ,			A_	:					List[str]						 =		self.model_tester.prepare_config_and_inputs_for_common()

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

						A_	:					Union[str, Any]						 =		['''pixel_values''']
						self.assertListEqual(arg_names[:1]   ,  _lowerCamelCase							)







				def        a_	(				self :       Dict							):



					"""simple docstring"""

					A_	:					Optional[int]						 =		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*_lowerCamelCase							)







				def        a_	(				self :       Tuple							):



					"""simple docstring"""

					A_	:					Any						 =		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_backbone(*_lowerCamelCase							)







				def        a_	(				self :       Dict							):



					"""simple docstring"""

					A_ ,			A_	:					Optional[Any]						 =		self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
						A_	:					Union[str, Any]						 =		model_class(config=_lowerCamelCase							)
						for name, module in model.named_modules():
							if isinstance(_lowerCamelCase   ,  (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        a_	(				self :       Optional[Any]							):



					"""simple docstring"""

					def check_hidden_states_output(_lowerCamelCase :       int   ,  _lowerCamelCase :       Dict   ,  _lowerCamelCase :       List[str]							):
						A_	:					int						 =		model_class(_lowerCamelCase							)
						model.to(_lowerCamelCase							)
						model.eval()

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

						A_	:					str						 =		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

						A_	:					Any						 =		self.model_tester.num_stages
						self.assertEqual(len(_lowerCamelCase							)   ,  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]   ,  )

					A_ ,			A_	:					List[str]						 =		self.model_tester.prepare_config_and_inputs_for_common()
					A_	:					List[str]						 =		['''basic''', '''bottleneck''']
					for model_class in self.all_model_classes:
						for layer_type in layers_type:
							A_	:					Any						 =		layer_type
							A_	:					Tuple						 =		True
							check_hidden_states_output(_lowerCamelCase   ,  _lowerCamelCase   ,  _lowerCamelCase							)

							# check that output_hidden_states also work using config
							del inputs_dict["output_hidden_states"]
							A_	:					Any						 =		True

							check_hidden_states_output(_lowerCamelCase   ,  _lowerCamelCase   ,  _lowerCamelCase							)







				@unittest.skip(reason='''ResNet does not use feedforward chunking'''							)
				def        a_	(				self :       int							):



					"""simple docstring"""

					pass







				def        a_	(				self :       Dict							):



					"""simple docstring"""

					A_	:					Tuple						 =		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase							)







				@slow
				def        a_	(				self :       List[str]							):



					"""simple docstring"""

					for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						A_	:					List[Any]						 =		ResNetModel.from_pretrained(_lowerCamelCase							)
						self.assertIsNotNone(_lowerCamelCase							)

def 		lowercase_   (		):




	"""simple docstring"""






	A_	:					List[str]						 =		Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
	return image

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







				@cached_property
				def        a_	(				self :       Any							):



					"""simple docstring"""

					return (
					    AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)
					    if is_vision_available()
					    else None
					)







				@slow
				def        a_	(				self :       Dict							):



					"""simple docstring"""

					A_	:					Optional[Any]						 =		ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							).to(_lowerCamelCase							)

					A_	:					List[str]						 =		self.default_image_processor
					A_	:					Any						 =		prepare_img()
					A_	:					List[str]						 =		image_processor(images=_lowerCamelCase   ,  return_tensors='''pt'''							).to(_lowerCamelCase							)

					# forward pass
					with torch.no_grad():
						A_	:					List[Any]						 =		model(**_lowerCamelCase							)

					# verify the logits
					A_	:					int						 =		torch.Size((1, 10_00)							)
					self.assertEqual(outputs.logits.shape   ,  _lowerCamelCase							)

					A_	:					List[str]						 =		torch.tensor([-11.1069, -9.7877, -8.3777]							).to(_lowerCamelCase							)

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

@require_torch
class 							lowercase   (     __UpperCAmelCase  ,						unittest.TestCase):
				__lowerCAmelCase     :     int								= (ResNetBackbone,) if is_torch_available() else ()
				__lowerCAmelCase     :     Tuple								= False
				__lowerCAmelCase     :     Optional[int]								= ResNetConfig







				def        a_	(				self :       Any							):



					"""simple docstring"""

					A_	:					Union[str, Any]						 =		ResNetModelTester(self							)











"""simple docstring"""

from __future__ import annotations

def 		lowercase_   (		_UpperCAmelCase	,   _UpperCAmelCase	,   _UpperCAmelCase						):




	"""simple docstring"""






	assert (
	    c % greatest_common_divisor(_UpperCAmelCase	,   _UpperCAmelCase						) == 0
	)  # greatest_common_divisor(a,b) function implemented below
	((A_) ,			(A_) ,			(A_))	:					List[Any]						 =		extended_gcd(_UpperCAmelCase	,   _UpperCAmelCase						)  # extended_gcd(a,b) function implemented below
	A_	:					int						 =		c / d
	return (r * x, r * y)

def 		lowercase_   (		_UpperCAmelCase	,   _UpperCAmelCase	,   _UpperCAmelCase	,   _UpperCAmelCase = 2						):




	"""simple docstring"""






	((A_) ,			(A_))	:					Any						 =		diophantine(_UpperCAmelCase	,   _UpperCAmelCase	,   _UpperCAmelCase						)  # Initial value
	A_	:					Union[str, Any]						 =		greatest_common_divisor(_UpperCAmelCase	,   _UpperCAmelCase						)
	A_	:					List[str]						 =		a // d
	A_	:					str						 =		b // d

	for i in range(_UpperCAmelCase						):
		A_	:					int						 =		xa + i * q
		A_	:					str						 =		ya - i * p
		print(_UpperCAmelCase	,   _UpperCAmelCase						)

def 		lowercase_   (		_UpperCAmelCase	,   _UpperCAmelCase						):




	"""simple docstring"""






	if a < b:
		A_ ,			A_	:					Tuple						 =		b, a

	while a % b != 0:
		A_ ,			A_	:					int						 =		b, a % b

	return b

def 		lowercase_   (		_UpperCAmelCase	,   _UpperCAmelCase						):




	"""simple docstring"""






	assert a >= 0 and b >= 0

	if b == 0:
		A_ ,			A_ ,			A_	:					str						 =		a, 1, 0
	else:
		((A_) ,			(A_) ,			(A_))	:					List[str]						 =		extended_gcd(_UpperCAmelCase	,   a % b						)
		A_	:					Optional[int]						 =		q
		A_	:					Tuple						 =		p - q * (a // b)

	assert a % d == 0 and b % d == 0
	assert d == a * x + b * y

	return (d, x, y)


if __name__ == "__main__":
		from doctest import testmod

		testmod(name='diophantine', verbose=True)
		testmod(name='diophantine_all_soln', verbose=True)
		testmod(name='extended_gcd', verbose=True)
		testmod(name='greatest_common_divisor', verbose=True)





