





import inspect
import unittest

from transformers import ResNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
			import jax
			import jax.numpy as jnp

			from transformers.models.resnet.modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel

if is_vision_available():
			from PIL import Image

			from transformers import AutoImageProcessor


class 			__lowerCAmelCase				(					unittest.TestCase			):


	'''simple docstring'''





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

	def       snake_case__(	self:	List[str] ):
			lowercase__				:			Any            =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

			lowercase__				:			str            =		self.get_config()

			return config, pixel_values

	def       snake_case__(	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,				image_size=self.image_size,				)

	def       snake_case__(	self:	Dict,				lowerCamelCase_:	Optional[Any],				lowerCamelCase_:	Any ):
			lowercase__				:			List[Any]            =		FlaxResNetModel(config=lowerCamelCase_ )
			lowercase__				:			Tuple            =		model(lowerCamelCase_ )

			# Output shape (b, c, h, w)
			self.parent.assertEqual(
			    result.last_hidden_state.shape,				(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32),				)

	def       snake_case__(	self:	Dict,				lowerCamelCase_:	List[str],				lowerCamelCase_:	Optional[Any] ):
			lowercase__				:			Union[str, Any]            =		self.num_labels
			lowercase__				:			str            =		FlaxResNetForImageClassification(config=lowerCamelCase_ )
			lowercase__				:			Optional[int]            =		model(lowerCamelCase_ )
			self.parent.assertEqual(result.logits.shape,				(self.batch_size, self.num_labels) )





	def       snake_case__(	self:	int ):
			lowercase__				:			Any            =		self.prepare_config_and_inputs()
			lowercase__      ,							lowercase__				:			List[Any]            =		config_and_inputs
			lowercase__				:			List[Any]            =		{'pixel_values': pixel_values}
			return config, inputs_dict


@require_flax
class 			__lowerCAmelCase				(					_UpperCamelCase      ,						unittest.TestCase			):


	'''simple docstring'''





	_A       	=							(FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else ()

	_A       	=							False
	_A       	=							False
	_A       	=							False

	def       snake_case__(	self:	List[str] ):
			lowercase__				:			Optional[Any]            =		FlaxResNetModelTester(self )
			lowercase__				:			int            =		ConfigTester(self,				config_class=lowerCamelCase_,				has_text_modality=lowerCamelCase_ )

	def       snake_case__(	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       snake_case__(	self:	int ):
			return

	def       snake_case__(	self:	Union[str, Any] ):
			lowercase__				:			int            =		self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*lowerCamelCase_ )

	def       snake_case__(	self:	Dict ):
			lowercase__				:			int            =		self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_ )

	@unittest.skip(reason='ResNet does not use inputs_embeds' )
	def       snake_case__(	self:	Any ):
			pass

	@unittest.skip(reason='ResNet does not support input and output embeddings' )
	def       snake_case__(	self:	Optional[int] ):
			pass

	def       snake_case__(	self:	Union[str, Any] ):
			lowercase__      ,							lowercase__				:			List[str]            =		self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
					lowercase__				:			Union[str, Any]            =		model_class(lowerCamelCase_ )
					lowercase__				:			Dict            =		inspect.signature(model.__call__ )
					# signature.parameters is an OrderedDict => so arg_names order is deterministic
					lowercase__				:			Any            =		[*signature.parameters.keys()]

					lowercase__				:			Optional[Any]            =		['pixel_values']
					self.assertListEqual(arg_names[:1],				lowerCamelCase_ )

	def       snake_case__(	self:	Optional[Any] ):
			def check_hidden_states_output(lowerCamelCase_:	Any,				lowerCamelCase_:	Union[str, Any],				lowerCamelCase_:	Optional[int] ):
					lowercase__				:			List[Any]            =		model_class(lowerCamelCase_ )

					lowercase__				:			List[str]            =		model(**self._prepare_for_class(lowerCamelCase_,				lowerCamelCase_ ) )

					lowercase__				:			List[Any]            =		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

					lowercase__				:			Tuple            =		self.model_tester.num_stages
					self.assertEqual(len(lowerCamelCase_ ),				expected_num_stages + 1 )

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





	def       snake_case__(	self:	Union[str, Any] ):
			lowercase__      ,							lowercase__				:			List[str]            =		self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
					with self.subTest(model_class.__name__ ):
							lowercase__				:			Tuple            =		self._prepare_for_class(lowerCamelCase_,				lowerCamelCase_ )
							lowercase__				:			str            =		model_class(lowerCamelCase_ )

							@jax.jit
							def model_jitted(lowerCamelCase_:	Any,				**lowerCamelCase_:	List[str] ):
									return model(pixel_values=lowerCamelCase_,				**lowerCamelCase_ )

							with self.subTest('JIT Enabled' ):
									lowercase__				:			Optional[int]            =		model_jitted(**lowerCamelCase_ ).to_tuple()

							with self.subTest('JIT Disabled' ):
									with jax.disable_jit():
											lowercase__				:			int            =		model_jitted(**lowerCamelCase_ ).to_tuple()

							self.assertEqual(len(lowerCamelCase_ ),				len(lowerCamelCase_ ) )
							for jitted_output, output in zip(lowerCamelCase_,				lowerCamelCase_ ):
									self.assertEqual(jitted_output.shape,				output.shape )


def 			SCREAMING_SNAKE_CASE__     (					)      ->       int:




		'''simple docstring'''
		lowercase__				:			Tuple            =		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
		return image





@require_flax
class 			__lowerCAmelCase				(					unittest.TestCase			):


	'''simple docstring'''





	@cached_property
	def       snake_case__(	self:	List[Any] ):
			return AutoImageProcessor.from_pretrained('microsoft/resnet-50' ) if is_vision_available() else None





	@slow
	def       snake_case__(	self:	List[str] ):
			lowercase__				:			Any            =		FlaxResNetForImageClassification.from_pretrained('microsoft/resnet-50' )

			lowercase__				:			Optional[Any]            =		self.default_image_processor
			lowercase__				:			Tuple            =		prepare_img()
			lowercase__				:			Dict            =		image_processor(images=lowerCamelCase_,				return_tensors='np' )

			lowercase__				:			Dict            =		model(**lowerCamelCase_ )

			# verify the logits
			lowercase__				:			List[Any]            =		(1, 1000)
			self.assertEqual(outputs.logits.shape,				lowerCamelCase_ )

			lowercase__				:			Dict            =		jnp.array([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7] )

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









import enum
import inspect
from typing import Iterable, List, Optional, Tuple, Union


class 			__lowerCAmelCase				(					enum.Enum			):


	'''simple docstring'''





	_A       	=							"timm"
	_A       	=							"transformers"


def 			SCREAMING_SNAKE_CASE__     (					_lowercase    :   Optional[Iterable[str]]      ,						_lowercase    :   Optional[Iterable[int]]      ,						_lowercase    :   Optional[Iterable[str]] )      ->       Optional[int]:




		'''simple docstring'''
		if stage_names is None:
				raise ValueError('Stage_names must be set for transformers backbones' )

		if out_features is not None:
				if not isinstance(_lowercase      ,						(list,) ):
						raise ValueError(f"""out_features must be a list {type(_lowercase )}""" )
				if any(feat not in stage_names for feat in out_features ):
						raise ValueError(f"""out_features must be a subset of stage_names: {stage_names} got {out_features}""" )

		if out_indices is not None:
				if not isinstance(_lowercase      ,						(list, tuple) ):
						raise ValueError(f"""out_indices must be a list or tuple, got {type(_lowercase )}""" )
				if any(idx >= len(_lowercase ) for idx in out_indices ):
						raise ValueError('out_indices must be valid indices for stage_names {stage_names}, got {out_indices}' )

		if out_features is not None and out_indices is not None:
				if len(_lowercase ) != len(_lowercase ):
						raise ValueError('out_features and out_indices should have the same length if both are set' )
				if out_features != [stage_names[idx] for idx in out_indices]:
						raise ValueError('out_features and out_indices should correspond to the same stages if both are set' )


def 			SCREAMING_SNAKE_CASE__     (					_lowercase    :   Optional[List[str]]      ,						_lowercase    :   Optional[Union[List[int], Tuple[int]]]      ,						_lowercase    :   List[str]      ,						)      ->       Dict:




		'''simple docstring'''
		if out_indices is None and out_features is None:
				lowercase__				:			str            =		[len(_lowercase ) - 1]
				lowercase__				:			Union[str, Any]            =		[stage_names[-1]]
		elif out_indices is None and out_features is not None:
				lowercase__				:			Optional[int]            =		[stage_names.index(_lowercase ) for layer in out_features]
		elif out_features is None and out_indices is not None:
				lowercase__				:			str            =		[stage_names[idx] for idx in out_indices]
		return out_features, out_indices


def 			SCREAMING_SNAKE_CASE__     (					_lowercase    :   Optional[List[str]]      ,						_lowercase    :   Optional[Union[List[int], Tuple[int]]]      ,						_lowercase    :   List[str]      ,						)      ->       Tuple[List[str], List[int]]:




		'''simple docstring'''
		verify_out_features_out_indices(out_features=_lowercase      ,						out_indices=_lowercase      ,						stage_names=_lowercase )
		lowercase__      ,							lowercase__				:			List[str]            =		_align_output_features_output_indices(
		    out_features=_lowercase      ,						out_indices=_lowercase      ,						stage_names=_lowercase )
		# Verify that the aligned out_features and out_indices are valid
		verify_out_features_out_indices(out_features=_lowercase      ,						out_indices=_lowercase      ,						stage_names=_lowercase )
		return output_features, output_indices


class 			__lowerCAmelCase				:


	'''simple docstring'''





	_A       	=							None

	def       snake_case__(	self:	Dict,				lowerCamelCase_:	Optional[Any] ):
			if getattr(self,				'_backbone',				lowerCamelCase_ ) is None:
					raise ValueError('self._backbone must be set before calling _init_timm_backbone' )

			# These will diagree with the defaults for the transformers models e.g. for resnet50
			# the transformer model has out_features = ['stem', 'stage1', 'stage2', 'stage3', 'stage4']
			# the timm model has out_features = ['act', 'layer1', 'layer2', 'layer3', 'layer4']
			lowercase__				:			Tuple            =		[stage['module'] for stage in self._backbone.feature_info.info]
			lowercase__				:			Union[str, Any]            =		[stage['num_chs'] for stage in self._backbone.feature_info.info]
			lowercase__				:			Dict            =		self._backbone.feature_info.out_indices
			lowercase__				:			Tuple            =		self._backbone.feature_info.module_name()

			# We verify the out indices and out features are valid
			verify_out_features_out_indices(
			    out_features=lowerCamelCase_,				out_indices=lowerCamelCase_,				stage_names=self.stage_names )
			lowercase__      ,							lowercase__				:			List[Any]            =		out_features, out_indices

	def       snake_case__(	self:	Any,				lowerCamelCase_:	List[str] ):
			lowercase__				:			Dict            =		getattr(lowerCamelCase_,				'stage_names' )
			lowercase__				:			List[str]            =		getattr(lowerCamelCase_,				'out_features',				lowerCamelCase_ )
			lowercase__				:			Optional[int]            =		getattr(lowerCamelCase_,				'out_indices',				lowerCamelCase_ )

			lowercase__				:			Optional[int]            =		stage_names
			lowercase__      ,							lowercase__				:			Union[str, Any]            =		get_aligned_output_features_output_indices(
			    out_features=lowerCamelCase_,				out_indices=lowerCamelCase_,				stage_names=lowerCamelCase_ )
			# Number of channels for each stage. This is set in the transformer backbone model init
			lowercase__				:			Dict            =		None

	def       snake_case__(	self:	List[Any],				lowerCamelCase_:	List[str] ):
			lowercase__				:			List[Any]            =		config

			lowercase__				:			Optional[int]            =		getattr(lowerCamelCase_,				'use_timm_backbone',				lowerCamelCase_ )
			lowercase__				:			List[Any]            =		BackboneType.TIMM if self.use_timm_backbone else BackboneType.TRANSFORMERS

			if self.backbone_type == BackboneType.TIMM:
					self._init_timm_backbone(lowerCamelCase_ )
			elif self.backbone_type == BackboneType.TRANSFORMERS:
					self._init_transformers_backbone(lowerCamelCase_ )
			else:
					raise ValueError(F"""backbone_type {self.backbone_type} not supported.""" )

	@property
	def       snake_case__(	self:	List[str] ):
			return self._out_features

	@out_features.setter
	def       snake_case__(	self:	Union[str, Any],				lowerCamelCase_:	List[str] ):
			lowercase__      ,							lowercase__				:			Optional[int]            =		get_aligned_output_features_output_indices(
			    out_features=lowerCamelCase_,				out_indices=lowerCamelCase_,				stage_names=self.stage_names )

	@property
	def       snake_case__(	self:	List[Any] ):
			return self._out_indices

	@out_indices.setter
	def       snake_case__(	self:	Tuple,				lowerCamelCase_:	Union[Tuple[int], List[int]] ):
			lowercase__      ,							lowercase__				:			List[str]            =		get_aligned_output_features_output_indices(
			    out_features=lowerCamelCase_,				out_indices=lowerCamelCase_,				stage_names=self.stage_names )

	@property
	def       snake_case__(	self:	str ):
			# the current backbones will output the number of channels for each stage
			# even if that stage is not in the out_features list.
			return {stage: self.num_features[i] for i, stage in enumerate(self.stage_names )}

	@property
	def       snake_case__(	self:	Optional[int] ):
			return [self.out_feature_channels[name] for name in self.out_features]

	def       snake_case__(	self:	List[Any],				*lowerCamelCase_:	List[Any],				**lowerCamelCase_:	Optional[Any] ):
			lowercase__				:			Any            =		dict(inspect.signature(self.forward ).parameters )
			lowercase__				:			List[Any]            =		{k: v for k, v in kwargs.items() if k in signature}
			return self(*lowerCamelCase_,				**lowerCamelCase_ )

	def       snake_case__(	self:	int,				lowerCamelCase_:	str,				lowerCamelCase_:	Optional[bool] = None,				lowerCamelCase_:	Optional[bool] = None,				lowerCamelCase_:	Optional[bool] = None,				):
			raise NotImplementedError('This method should be implemented by the derived class.' )





	def       snake_case__(	self:	Dict ):
			lowercase__				:			List[Any]            =		super().to_dict()
			lowercase__				:			Union[str, Any]            =		output.pop('_out_features' )
			lowercase__				:			Any            =		output.pop('_out_indices' )
			return output


class 			__lowerCAmelCase				:


	'''simple docstring'''





	@property
	def       snake_case__(	self:	Optional[int] ):
			return self._out_features

	@out_features.setter
	def       snake_case__(	self:	List[Any],				lowerCamelCase_:	List[str] ):
			lowercase__      ,							lowercase__				:			List[Any]            =		get_aligned_output_features_output_indices(
			    out_features=lowerCamelCase_,				out_indices=lowerCamelCase_,				stage_names=self.stage_names )

	@property
	def       snake_case__(	self:	Dict ):
			return self._out_indices

	@out_indices.setter
	def       snake_case__(	self:	Optional[int],				lowerCamelCase_:	Union[Tuple[int], List[int]] ):
			lowercase__      ,							lowercase__				:			Any            =		get_aligned_output_features_output_indices(
			    out_features=lowerCamelCase_,				out_indices=lowerCamelCase_,				stage_names=self.stage_names )





	def       snake_case__(	self:	Union[str, Any] ):
			lowercase__				:			List[str]            =		super().to_dict()
			lowercase__				:			str            =		output.pop('_out_features' )
			lowercase__				:			str            =		output.pop('_out_indices' )
			return output


