


'''simple docstring'''
import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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 RegNetForImageClassification, RegNetModel
		from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor
class   lowercase      :

		"""simple docstring"""

		def __init__(						self       ,  UpperCamelCase_       ,  UpperCamelCase_=3       ,  UpperCamelCase_=32       ,  UpperCamelCase_=3       ,  UpperCamelCase_=10       ,  UpperCamelCase_=[10, 20, 30, 40]       ,  UpperCamelCase_=[1, 1, 2, 1]       ,  UpperCamelCase_=True       ,  UpperCamelCase_=True       ,  UpperCamelCase_="relu"       ,  UpperCamelCase_=3       ,  UpperCamelCase_=None       ,  ):

							'''simple docstring'''


							UpperCamelCase__  :Optional[int]				   =					parent
							UpperCamelCase__  :List[str]				   =					batch_size
							UpperCamelCase__  :int				   =					image_size
							UpperCamelCase__  :Any				   =					num_channels
							UpperCamelCase__  :Optional[int]				   =					embeddings_size
							UpperCamelCase__  :Dict				   =					hidden_sizes
							UpperCamelCase__  :Optional[int]				   =					depths
							UpperCamelCase__  :int				   =					is_training
							UpperCamelCase__  :List[Any]				   =					use_labels
							UpperCamelCase__  :Union[str, Any]				   =					hidden_act
							UpperCamelCase__  :Dict				   =					num_labels
							UpperCamelCase__  :Union[str, Any]				   =					scope
							UpperCamelCase__  :Optional[int]				   =					len(UpperCamelCase_				)




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__  :Union[str, Any]				   =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

							UpperCamelCase__  :List[Any]				   =					None
							if self.use_labels:
												UpperCamelCase__  :Dict				   =					ids_tensor([self.batch_size]       ,  self.num_labels				)

							UpperCamelCase__  :Optional[int]				   =					self.get_config()

							return config, pixel_values, labels




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							return RegNetConfig(
							    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       ,  )




		def        lowerCAmelCase__							(						self       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_				):

							'''simple docstring'''


							UpperCamelCase__  :int				   =					RegNetModel(config=UpperCamelCase_				)
							model.to(UpperCamelCase_				)
							model.eval()
							UpperCamelCase__  :Tuple				   =					model(UpperCamelCase_				)
							# 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        lowerCAmelCase__							(						self       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_				):

							'''simple docstring'''


							UpperCamelCase__  :int				   =					self.num_labels
							UpperCamelCase__  :Union[str, Any]				   =					RegNetForImageClassification(UpperCamelCase_				)
							model.to(UpperCamelCase_				)
							model.eval()
							UpperCamelCase__  :Union[str, Any]				   =					model(UpperCamelCase_       ,  labels=UpperCamelCase_				)
							self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.num_labels)				)




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


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



@require_torch
class   lowercase      (				A__      ,						A__      ,						unittest.TestCase   ):

		"""simple docstring"""

		_a       					=							(RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
		_a       					=							(
		    {'feature-extraction': RegNetModel, 'image-classification': RegNetForImageClassification}
		    if is_torch_available()
		    else {}
		)

		_a       					=							False
		_a       					=							False
		_a       					=							False
		_a       					=							False




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__  :Union[str, Any]				   =					RegNetModelTester(self				)
							UpperCamelCase__  :Union[str, Any]				   =					ConfigTester(self       ,  config_class=UpperCamelCase_       ,  has_text_modality=UpperCamelCase_				)




		def        lowerCAmelCase__							(						self				):

							'''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        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							return




		@unittest.skip(reason='''RegNet does not use inputs_embeds'''				)
		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							pass




		@unittest.skip(reason='''RegNet does not support input and output embeddings'''				)
		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							pass




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


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

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

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




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__  :List[Any]				   =					self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCamelCase_				)




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__   ,							UpperCamelCase__  :Tuple				   =					self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												UpperCamelCase__  :Optional[Any]				   =					model_class(config=UpperCamelCase_				)
												for name, module in model.named_modules():
																	if isinstance(UpperCamelCase_       ,  (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        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							def check_hidden_states_output(UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_				):
												UpperCamelCase__  :Tuple				   =					model_class(UpperCamelCase_				)
												model.to(UpperCamelCase_				)
												model.eval()

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

												UpperCamelCase__  :List[str]				   =					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

												UpperCamelCase__  :int				   =					self.model_tester.num_stages
												self.assertEqual(len(UpperCamelCase_				)       ,  expected_num_stages + 1				)

												# RegNet'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 // 2, self.model_tester.image_size // 2]       ,  )

							UpperCamelCase__   ,							UpperCamelCase__  :str				   =					self.model_tester.prepare_config_and_inputs_for_common()
							UpperCamelCase__  :Union[str, Any]				   =					['''basic''', '''bottleneck''']
							for model_class in self.all_model_classes:
												for layer_type in layers_type:
																	UpperCamelCase__  :Optional[int]				   =					layer_type
																	UpperCamelCase__  :Any				   =					True
																	check_hidden_states_output(UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_				)

																	# check that output_hidden_states also work using config
																	del inputs_dict["output_hidden_states"]
																	UpperCamelCase__  :Union[str, Any]				   =					True

																	check_hidden_states_output(UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_				)




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__  :Union[str, Any]				   =					self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*UpperCamelCase_				)




		@slow
		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												UpperCamelCase__  :Union[str, Any]				   =					RegNetModel.from_pretrained(UpperCamelCase_				)
												self.assertIsNotNone(UpperCamelCase_				)



def      a (     )    ->      str:



					'''simple docstring'''






					UpperCamelCase__  :int				   =					Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''  )
					return image







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

		"""simple docstring"""

		@cached_property
		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


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




		@slow
		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							UpperCamelCase__  :Tuple				   =					RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				).to(UpperCamelCase_				)

							UpperCamelCase__  :Tuple				   =					self.default_image_processor
							UpperCamelCase__  :List[Any]				   =					prepare_img()
							UpperCamelCase__  :Optional[Any]				   =					image_processor(images=UpperCamelCase_       ,  return_tensors='''pt'''				).to(UpperCamelCase_				)

							# forward pass
							with torch.no_grad():
												UpperCamelCase__  :Tuple				   =					model(**UpperCamelCase_				)

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

							UpperCamelCase__  :Union[str, Any]				   =					torch.tensor([-0.4180, -1.5051, -3.4836]				).to(UpperCamelCase_				)

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



'''simple docstring'''
from __future__ import annotations

from decimal import Decimal

from numpy import array


def      a (     __a  )    ->      list[list[float]]:



					'''simple docstring'''






					UpperCamelCase__  :int				   =					Decimal

					# Check if the provided matrix has 2 rows and 2 columns
					# since this implementation only works for 2x2 matrices
					if len(__a  ) == 2 and len(matrix[0]  ) == 2 and len(matrix[1]  ) == 2:
										# Calculate the determinant of the matrix
										UpperCamelCase__  :str				   =					float(
										    d(matrix[0][0]  ) * d(matrix[1][1]  ) - d(matrix[1][0]  ) * d(matrix[0][1]  )  )
										if determinant == 0:
															raise ValueError('''This matrix has no inverse.'''  )

										# Creates a copy of the matrix with swapped positions of the elements
										UpperCamelCase__  :List[Any]				   =					[[0.0, 0.0], [0.0, 0.0]]
										UpperCamelCase__   ,							UpperCamelCase__  :Union[str, Any]				   =					matrix[1][1], matrix[0][0]
										UpperCamelCase__   ,							UpperCamelCase__  :Dict				   =					-matrix[1][0], -matrix[0][1]

										# Calculate the inverse of the matrix
										return [
										    [(float(d(__a  )  ) / determinant) or 0.0 for n in row] for row in swapped_matrix
										]
					elif (
					    len(__a  ) == 3
					    and len(matrix[0]  ) == 3
					    and len(matrix[1]  ) == 3
					    and len(matrix[2]  ) == 3
					):
										# Calculate the determinant of the matrix using Sarrus rule
										UpperCamelCase__  :int				   =					float(
										    (
										        (d(matrix[0][0]  ) * d(matrix[1][1]  ) * d(matrix[2][2]  ))
										        + (d(matrix[0][1]  ) * d(matrix[1][2]  ) * d(matrix[2][0]  ))
										        + (d(matrix[0][2]  ) * d(matrix[1][0]  ) * d(matrix[2][1]  ))
										    )
										    - (
										        (d(matrix[0][2]  ) * d(matrix[1][1]  ) * d(matrix[2][0]  ))
										        + (d(matrix[0][1]  ) * d(matrix[1][0]  ) * d(matrix[2][2]  ))
										        + (d(matrix[0][0]  ) * d(matrix[1][2]  ) * d(matrix[2][1]  ))
										    )  )
										if determinant == 0:
															raise ValueError('''This matrix has no inverse.'''  )

										# Creating cofactor matrix
										UpperCamelCase__  :List[Any]				   =					[
										    [d(0.0  ), d(0.0  ), d(0.0  )],
										    [d(0.0  ), d(0.0  ), d(0.0  )],
										    [d(0.0  ), d(0.0  ), d(0.0  )],
										]
										UpperCamelCase__  :Tuple				   =					(d(matrix[1][1]  ) * d(matrix[2][2]  )) - (
										    d(matrix[1][2]  ) * d(matrix[2][1]  )
										)
										UpperCamelCase__  :List[str]				   =					-(
										    (d(matrix[1][0]  ) * d(matrix[2][2]  )) - (d(matrix[1][2]  ) * d(matrix[2][0]  ))
										)
										UpperCamelCase__  :Union[str, Any]				   =					(d(matrix[1][0]  ) * d(matrix[2][1]  )) - (
										    d(matrix[1][1]  ) * d(matrix[2][0]  )
										)
										UpperCamelCase__  :List[Any]				   =					-(
										    (d(matrix[0][1]  ) * d(matrix[2][2]  )) - (d(matrix[0][2]  ) * d(matrix[2][1]  ))
										)
										UpperCamelCase__  :Optional[int]				   =					(d(matrix[0][0]  ) * d(matrix[2][2]  )) - (
										    d(matrix[0][2]  ) * d(matrix[2][0]  )
										)
										UpperCamelCase__  :List[Any]				   =					-(
										    (d(matrix[0][0]  ) * d(matrix[2][1]  )) - (d(matrix[0][1]  ) * d(matrix[2][0]  ))
										)
										UpperCamelCase__  :List[Any]				   =					(d(matrix[0][1]  ) * d(matrix[1][2]  )) - (
										    d(matrix[0][2]  ) * d(matrix[1][1]  )
										)
										UpperCamelCase__  :List[str]				   =					-(
										    (d(matrix[0][0]  ) * d(matrix[1][2]  )) - (d(matrix[0][2]  ) * d(matrix[1][0]  ))
										)
										UpperCamelCase__  :Dict				   =					(d(matrix[0][0]  ) * d(matrix[1][1]  )) - (
										    d(matrix[0][1]  ) * d(matrix[1][0]  )
										)

										# Transpose the cofactor matrix (Adjoint matrix)
										UpperCamelCase__  :Optional[Any]				   =					array(__a  )
										for i in range(3  ):
															for j in range(3  ):
																				UpperCamelCase__  :Optional[Any]				   =					cofactor_matrix[j][i]

        # Inverse of the matrix using the formula (1/determinant) * adjoint matrix
										UpperCamelCase__  :Any				   =					array(__a  )
										for i in range(3  ):
															for j in range(3  ):
																				inverse_matrix[i][j] /= d(__a  )

        # Calculate the inverse of the matrix
										return [[float(d(__a  )  ) or 0.0 for n in row] for row in inverse_matrix]
					raise ValueError('''Please provide a matrix of size 2x2 or 3x3.'''  )