




"""simple docstring"""







from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor






class       SCREAMING_SNAKE_CASE__					:


						def __init__(							self				:			Union[str, Any]						,						lowerCAmelCase				:			Union[str, Any]						,						lowerCAmelCase				:			Union[str, Any]=3						,						lowerCAmelCase				:			Union[str, Any]=32						,						lowerCAmelCase				:			Dict=3						,						lowerCAmelCase				:			str=10						,						lowerCAmelCase				:			Optional[int]=[10, 20, 30, 40]						,						lowerCAmelCase				:			Optional[Any]=[1, 1, 2, 1]						,						lowerCAmelCase				:			List[str]=True						,						lowerCAmelCase				:			str=True						,						lowerCAmelCase				:			Dict="relu"						,						lowerCAmelCase				:			str=3						,						lowerCAmelCase				:			Any=None						,						):
										lowerCAmelCase  =				parent
										lowerCAmelCase  =				batch_size
										lowerCAmelCase  =				image_size
										lowerCAmelCase  =				num_channels
										lowerCAmelCase  =				embeddings_size
										lowerCAmelCase  =				hidden_sizes
										lowerCAmelCase  =				depths
										lowerCAmelCase  =				is_training
										lowerCAmelCase  =				use_labels
										lowerCAmelCase  =				hidden_act
										lowerCAmelCase  =				num_labels
										lowerCAmelCase  =				scope
										lowerCAmelCase  =				len(lowerCAmelCase					)


						def   __lowercase (							self				:			List[str]					):
										lowerCAmelCase  =				floats_tensor([self.batch_size, 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				:			Tuple					):
										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   __lowercase (							self				:			Tuple						,						lowerCAmelCase				:			List[str]						,						lowerCAmelCase				:			Dict						,						lowerCAmelCase				:			int					):
										lowerCAmelCase  =				TFRegNetModel(config=lowerCAmelCase					)
										lowerCAmelCase  =				model(lowerCAmelCase						,						training=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   __lowercase (							self				:			Tuple						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			str						,						lowerCAmelCase				:			int					):
										lowerCAmelCase  =				self.num_labels
										lowerCAmelCase  =				TFRegNetForImageClassification(lowerCAmelCase					)
										lowerCAmelCase  =				model(lowerCAmelCase						,						labels=lowerCAmelCase						,						training=lowerCAmelCase					)
										self.parent.assertEqual(result.logits.shape						,						(self.batch_size, self.num_labels)					)




						def   __lowercase (							self				:			Dict					):
										lowerCAmelCase  =				self.prepare_config_and_inputs()
										lowerCAmelCase ,						lowerCAmelCase ,						lowerCAmelCase  =				config_and_inputs
										lowerCAmelCase  =				{"""pixel_values""": pixel_values}
										return config, inputs_dict






@require_tf
class       SCREAMING_SNAKE_CASE__					(					_a						,				_a						,				unittest.TestCase					):
						_a    						=						(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
						_a    						=						(
						    {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification}
						    if is_tf_available()
						    else {}
						)

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


						def   __lowercase (							self				:			Optional[int]					):
										lowerCAmelCase  =				TFRegNetModelTester(self					)
										lowerCAmelCase  =				ConfigTester(self						,						config_class=lowerCAmelCase						,						has_text_modality=lowerCAmelCase					)


						def   __lowercase (							self				:			Dict					):
										return


						@unittest.skip(reason="""RegNet does not use inputs_embeds"""					)
						def   __lowercase (							self				:			Any					):
										pass


						@unittest.skipIf(
						    not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""					)					) == 0						,						reason="""TF does not support backprop for grouped convolutions on CPU."""						,						)
						@slow
						def   __lowercase (							self				:			List[str]					):
										super().test_keras_fit()


						@unittest.skip(reason="""RegNet does not support input and output embeddings"""					)
						def   __lowercase (							self				:			int					):
										pass


						def   __lowercase (							self				:			str					):
										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.call					)
														# 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				:			Tuple					):
										lowerCAmelCase  =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase					)


						def   __lowercase (							self				:			List[str]					):
										def check_hidden_states_output(lowerCAmelCase				:			Any						,						lowerCAmelCase				:			Any						,						lowerCAmelCase				:			Dict					):
														lowerCAmelCase  =				model_class(lowerCAmelCase					)
														lowerCAmelCase  =				model(**self._prepare_for_class(lowerCAmelCase						,						lowerCAmelCase					)						,						training=lowerCAmelCase					)

														lowerCAmelCase  =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

														lowerCAmelCase  =				self.model_tester.num_stages
														self.assertEqual(len(lowerCAmelCase					)						,						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]						,						)

										lowerCAmelCase ,						lowerCAmelCase  =				self.model_tester.prepare_config_and_inputs_for_common()
										lowerCAmelCase  =				["""basic""", """bottleneck"""]
										for model_class in self.all_model_classes:
														for layer_type in layers_type:
																		lowerCAmelCase  =				layer_type
																		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   __lowercase (							self				:			Optional[Any]					):
										lowerCAmelCase ,						lowerCAmelCase  =				self.model_tester.prepare_config_and_inputs_for_common()

										def check_equivalence(lowerCAmelCase				:			List[Any]						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			List[Any]						,						lowerCAmelCase				:			str={}					):
														lowerCAmelCase  =				model(lowerCAmelCase						,						return_dict=lowerCAmelCase						,						**lowerCAmelCase					)
														lowerCAmelCase  =				model(lowerCAmelCase						,						return_dict=lowerCAmelCase						,						**lowerCAmelCase					).to_tuple()

														def recursive_check(lowerCAmelCase				:			Tuple						,						lowerCAmelCase				:			str					):
																		if isinstance(lowerCAmelCase						,						(List, Tuple)					):
																						for tuple_iterable_value, dict_iterable_value in zip(lowerCAmelCase						,						lowerCAmelCase					):
																										recursive_check(lowerCAmelCase						,						lowerCAmelCase					)
																		elif tuple_object is None:
																						return
																		else:
																						self.assertTrue(
																						    all(tf.equal(lowerCAmelCase						,						lowerCAmelCase					)					)						,						msg=(
																						        """Tuple and dict output are not equal. Difference:"""
																						        f''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object					)					)}'''
																						    )						,						)

																		recursive_check(lowerCAmelCase						,						lowerCAmelCase					)

										for model_class in self.all_model_classes:
														lowerCAmelCase  =				model_class(lowerCAmelCase					)

														lowerCAmelCase  =				self._prepare_for_class(lowerCAmelCase						,						lowerCAmelCase					)
														lowerCAmelCase  =				self._prepare_for_class(lowerCAmelCase						,						lowerCAmelCase					)
														check_equivalence(lowerCAmelCase						,						lowerCAmelCase						,						lowerCAmelCase					)

														lowerCAmelCase  =				self._prepare_for_class(lowerCAmelCase						,						lowerCAmelCase						,						return_labels=lowerCAmelCase					)
														lowerCAmelCase  =				self._prepare_for_class(lowerCAmelCase						,						lowerCAmelCase						,						return_labels=lowerCAmelCase					)
														check_equivalence(lowerCAmelCase						,						lowerCAmelCase						,						lowerCAmelCase					)

														lowerCAmelCase  =				self._prepare_for_class(lowerCAmelCase						,						lowerCAmelCase					)
														lowerCAmelCase  =				self._prepare_for_class(lowerCAmelCase						,						lowerCAmelCase					)
														check_equivalence(lowerCAmelCase						,						lowerCAmelCase						,						lowerCAmelCase						,						{"""output_hidden_states""": True}					)

														lowerCAmelCase  =				self._prepare_for_class(lowerCAmelCase						,						lowerCAmelCase						,						return_labels=lowerCAmelCase					)
														lowerCAmelCase  =				self._prepare_for_class(lowerCAmelCase						,						lowerCAmelCase						,						return_labels=lowerCAmelCase					)
														check_equivalence(lowerCAmelCase						,						lowerCAmelCase						,						lowerCAmelCase						,						{"""output_hidden_states""": True}					)


						def   __lowercase (							self				:			Optional[Any]					):
										lowerCAmelCase  =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase					)




						@slow
						def   __lowercase (							self				:			str					):
										for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														lowerCAmelCase  =				TFRegNetModel.from_pretrained(lowerCAmelCase					)
														self.assertIsNotNone(lowerCAmelCase					)





def 							lowercase					()     ->  Optional[Any]:


				'''simple docstring'''






				lowerCAmelCase  =				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
				return image






@require_tf
@require_vision
class       SCREAMING_SNAKE_CASE__					(					unittest.TestCase					):


						@cached_property
						def   __lowercase (							self				:			List[str]					):
										return (
										    AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)
										    if is_vision_available()
										    else None
										)




						@slow
						def   __lowercase (							self				:			Any					):
										lowerCAmelCase  =				TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)

										lowerCAmelCase  =				self.default_image_processor
										lowerCAmelCase  =				prepare_img()
										lowerCAmelCase  =				image_processor(images=lowerCAmelCase						,						return_tensors="""tf"""					)

										# forward pass
										lowerCAmelCase  =				model(**lowerCAmelCase						,						training=lowerCAmelCase					)

										# verify the logits
										lowerCAmelCase  =				tf.TensorShape((1, 1000)					)
										self.assertEqual(outputs.logits.shape						,						lowerCAmelCase					)

										lowerCAmelCase  =				tf.constant([-0.4180, -1.5051, -3.4836]					)

										tf.debugging.assert_near(outputs.logits[0, :3]						,						lowerCAmelCase						,						atol=1e-4					)











"""simple docstring"""







from __future__ import annotations

import math
import random
from collections.abc import Collection
from typing import overload






class       SCREAMING_SNAKE_CASE__					:


						def __init__(							self				:			Dict						,						lowerCAmelCase				:			Collection[float] | None = None					):
										if components is None:
														lowerCAmelCase  =				[]
										lowerCAmelCase  =				list(lowerCAmelCase					)


						def __len__(							self				:			List[Any]					):
										return len(self.__components					)


						def __str__(							self				:			str					):
										return "(" + ",".join(map(lowerCAmelCase						,						self.__components					)					) + ")"


						def __add__(							self				:			Any						,						lowerCAmelCase				:			Vector					):
										lowerCAmelCase  =				len(self					)
										if size == len(lowerCAmelCase					):
														lowerCAmelCase  =				[self.__components[i] + other.component(lowerCAmelCase					) for i in range(lowerCAmelCase					)]
														return Vector(lowerCAmelCase					)
										else:
														raise Exception("""must have the same size"""					)


						def __sub__(							self				:			List[Any]						,						lowerCAmelCase				:			Vector					):
										lowerCAmelCase  =				len(self					)
										if size == len(lowerCAmelCase					):
														lowerCAmelCase  =				[self.__components[i] - other.component(lowerCAmelCase					) for i in range(lowerCAmelCase					)]
														return Vector(lowerCAmelCase					)
										else:  # error case
														raise Exception("""must have the same size"""					)


						@overload
						def __mul__(							self				:			Optional[int]						,						lowerCAmelCase				:			float					):
										...


						@overload
						def __mul__(							self				:			List[Any]						,						lowerCAmelCase				:			Vector					):
										...


						def __mul__(							self				:			Dict						,						lowerCAmelCase				:			float | Vector					):
										if isinstance(lowerCAmelCase						,						(float, int)					):
														lowerCAmelCase  =				[c * other for c in self.__components]
														return Vector(lowerCAmelCase					)
										elif isinstance(lowerCAmelCase						,						lowerCAmelCase					) and len(self					) == len(lowerCAmelCase					):
														lowerCAmelCase  =				len(self					)
														lowerCAmelCase  =				[self.__components[i] * other.component(lowerCAmelCase					) for i in range(lowerCAmelCase					)]
														return sum(lowerCAmelCase					)
										else:  # error case
														raise Exception("""invalid operand!"""					)


						def   __lowercase (							self				:			Tuple					):
										return Vector(self.__components					)


						def   __lowercase (							self				:			Dict						,						lowerCAmelCase				:			int					):
										if isinstance(lowerCAmelCase						,						lowerCAmelCase					) and -len(self.__components					) <= i < len(self.__components					):
														return self.__components[i]
										else:
														raise Exception("""index out of range"""					)


						def   __lowercase (							self				:			Any						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			float					):
										assert -len(self.__components					) <= pos < len(self.__components					)
										lowerCAmelCase  =				value


						def   __lowercase (							self				:			Optional[int]					):
										if len(self.__components					) == 0:
														raise Exception("""Vector is empty"""					)
										lowerCAmelCase  =				[c**2 for c in self.__components]
										return math.sqrt(sum(lowerCAmelCase					)					)




						def   __lowercase (							self				:			str						,						lowerCAmelCase				:			Vector						,						lowerCAmelCase				:			bool = False					):
										lowerCAmelCase  =				self * other
										lowerCAmelCase  =				self.euclidean_length() * other.euclidean_length()
										if deg:
														return math.degrees(math.acos(num / den					)					)
										else:
														return math.acos(num / den					)





def 							lowercase					(snake_case__   : int )     ->  Vector:


				'''simple docstring'''






				assert isinstance(snake_case__      ,       snake_case__ )
				return Vector([0] * dimension )





def 							lowercase					(snake_case__   : int      ,       snake_case__   : int )     ->  Vector:


				'''simple docstring'''






				assert isinstance(snake_case__      ,       snake_case__ ) and (isinstance(snake_case__      ,       snake_case__ ))
				lowerCAmelCase  =				[0] * dimension
				lowerCAmelCase  =				1
				return Vector(snake_case__ )





def 							lowercase					(snake_case__   : float      ,       snake_case__   : Vector      ,       snake_case__   : Vector )     ->  Vector:


				'''simple docstring'''






				assert (
				    isinstance(snake_case__      ,       snake_case__ )
				    and isinstance(snake_case__      ,       snake_case__ )
				    and (isinstance(snake_case__      ,       (int, float) ))
				)
				return x * scalar + y





def 							lowercase					(snake_case__   : int      ,       snake_case__   : int      ,       snake_case__   : int )     ->  Vector:


				'''simple docstring'''






				random.seed(snake_case__ )
				lowerCAmelCase  =				[random.randint(snake_case__      ,       snake_case__ ) for _ in range(snake_case__ )]
				return Vector(snake_case__ )






class       SCREAMING_SNAKE_CASE__					:


						def __init__(							self				:			Any						,						lowerCAmelCase				:			list[list[float]]						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			int					):
										lowerCAmelCase  =				matrix
										lowerCAmelCase  =				w
										lowerCAmelCase  =				h


						def __str__(							self				:			List[str]					):
										lowerCAmelCase  =				""""""
										for i in range(self.__height					):
														ans += "|"
														for j in range(self.__width					):
																		if j < self.__width - 1:
																						ans += str(self.__matrix[i][j]					) + ","
																		else:
																						ans += str(self.__matrix[i][j]					) + "|\n"
										return ans


						def __add__(							self				:			Optional[Any]						,						lowerCAmelCase				:			Matrix					):
										if self.__width == other.width() and self.__height == other.height():
														lowerCAmelCase  =				[]
														for i in range(self.__height					):
																		lowerCAmelCase  =				[
																		    self.__matrix[i][j] + other.component(lowerCAmelCase						,						lowerCAmelCase					)
																		    for j in range(self.__width					)
																		]
																		matrix.append(lowerCAmelCase					)
														return Matrix(lowerCAmelCase						,						self.__width						,						self.__height					)
										else:
														raise Exception("""matrix must have the same dimension!"""					)


						def __sub__(							self				:			Union[str, Any]						,						lowerCAmelCase				:			Matrix					):
										if self.__width == other.width() and self.__height == other.height():
														lowerCAmelCase  =				[]
														for i in range(self.__height					):
																		lowerCAmelCase  =				[
																		    self.__matrix[i][j] - other.component(lowerCAmelCase						,						lowerCAmelCase					)
																		    for j in range(self.__width					)
																		]
																		matrix.append(lowerCAmelCase					)
														return Matrix(lowerCAmelCase						,						self.__width						,						self.__height					)
										else:
														raise Exception("""matrices must have the same dimension!"""					)


						@overload
						def __mul__(							self				:			Any						,						lowerCAmelCase				:			float					):
										...


						@overload
						def __mul__(							self				:			Optional[int]						,						lowerCAmelCase				:			Vector					):
										...


						def __mul__(							self				:			Dict						,						lowerCAmelCase				:			float | Vector					):
										if isinstance(lowerCAmelCase						,						lowerCAmelCase					):  # matrix-vector
														if len(lowerCAmelCase					) == self.__width:
																		lowerCAmelCase  =				zero_vector(self.__height					)
																		for i in range(self.__height					):
																						lowerCAmelCase  =				[
																						    self.__matrix[i][j] * other.component(lowerCAmelCase					)
																						    for j in range(self.__width					)
																						]
																						ans.change_component(lowerCAmelCase						,						sum(lowerCAmelCase					)					)
																		return ans
														else:
																		raise Exception(
																		    """vector must have the same size as the """
																		    """number of columns of the matrix!"""					)
										elif isinstance(lowerCAmelCase						,						(int, float)					):  # matrix-scalar
														lowerCAmelCase  =				[
														    [self.__matrix[i][j] * other for j in range(self.__width					)]
														    for i in range(self.__height					)
														]
														return Matrix(lowerCAmelCase						,						self.__width						,						self.__height					)
										return None


						def   __lowercase (							self				:			Any					):
										return self.__height


						def   __lowercase (							self				:			int					):
										return self.__width


						def   __lowercase (							self				:			Optional[Any]						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			int					):
										if 0 <= x < self.__height and 0 <= y < self.__width:
														return self.__matrix[x][y]
										else:
														raise Exception("""change_component: indices out of bounds"""					)


						def   __lowercase (							self				:			int						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			float					):
										if 0 <= x < self.__height and 0 <= y < self.__width:
														lowerCAmelCase  =				value
										else:
														raise Exception("""change_component: indices out of bounds"""					)


						def   __lowercase (							self				:			int						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			int					):
										if self.__height != self.__width:
														raise Exception("""Matrix is not square"""					)
										lowerCAmelCase  =				self.__matrix[:x] + self.__matrix[x + 1 :]
										for i in range(len(lowerCAmelCase					)					):
														lowerCAmelCase  =				minor[i][:y] + minor[i][y + 1 :]
										return Matrix(lowerCAmelCase						,						self.__width - 1						,						self.__height - 1					).determinant()


						def   __lowercase (							self				:			Optional[Any]						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			int					):
										if self.__height != self.__width:
														raise Exception("""Matrix is not square"""					)
										if 0 <= x < self.__height and 0 <= y < self.__width:
														return (-1) ** (x + y) * self.minor(lowerCAmelCase						,						lowerCAmelCase					)
										else:
														raise Exception("""Indices out of bounds"""					)




						def   __lowercase (							self				:			List[Any]					):
										if self.__height != self.__width:
														raise Exception("""Matrix is not square"""					)
										if self.__height < 1:
														raise Exception("""Matrix has no element"""					)
										elif self.__height == 1:
														return self.__matrix[0][0]
										elif self.__height == 2:
														return (
														    self.__matrix[0][0] * self.__matrix[1][1]
														    - self.__matrix[0][1] * self.__matrix[1][0]
														)
										else:
														lowerCAmelCase  =				[
														    self.__matrix[0][y] * self.cofactor(0						,						lowerCAmelCase					) for y in range(self.__width					)
														]
														return sum(lowerCAmelCase					)





def 							lowercase					(snake_case__   : int )     ->  Matrix:


				'''simple docstring'''






				lowerCAmelCase  =				[[0] * n for _ in range(snake_case__ )]
				return Matrix(snake_case__      ,       snake_case__      ,       snake_case__ )






def 							lowercase					(snake_case__   : int      ,       snake_case__   : int      ,       snake_case__   : int      ,       snake_case__   : int )     ->  Matrix:


				'''simple docstring'''






				random.seed(snake_case__ )
				lowerCAmelCase  =				[
				    [random.randint(snake_case__      ,       snake_case__ ) for _ in range(snake_case__ )] for _ in range(snake_case__ )
				]
				return Matrix(snake_case__      ,       snake_case__      ,       snake_case__ )





