





import copy
import inspect
import unittest

from transformers import AutoBackbone
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import require_timm, require_torch, torch_device
from transformers.utils.import_utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor


if is_torch_available():
			import torch

			from transformers import TimmBackbone, TimmBackboneConfig

from ...test_pipeline_mixin import PipelineTesterMixin


class       __lowerCAmelCase					:


	'''simple docstring'''





	def __init__(						self:						Optional[int],					lowerCamelCase_:						Tuple,					lowerCamelCase_:						Optional[int]=None,					lowerCamelCase_:						Dict=None,					lowerCamelCase_:						Optional[int]=None,					lowerCamelCase_:						Tuple="resnet50",					lowerCamelCase_:						List[Any]=3,					lowerCamelCase_:						str=32,					lowerCamelCase_:						Optional[int]=3,					lowerCamelCase_:						Optional[int]=True,					lowerCamelCase_:						Optional[int]=True,					):
			lowercase__					:      Optional[int]      =		parent
			lowercase__					:      str      =		out_indices if out_indices is not None else [4]
			lowercase__					:      int      =		stage_names
			lowercase__					:      Optional[int]      =		out_features
			lowercase__					:      int      =		backbone
			lowercase__					:      Union[str, Any]      =		batch_size
			lowercase__					:      Dict      =		image_size
			lowercase__					:      List[str]      =		num_channels
			lowercase__					:      Union[str, Any]      =		use_pretrained_backbone
			lowercase__					:      str      =		is_training

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

			return config, pixel_values

	def    snake_case__(						self:						Union[str, Any]			):
			return TimmBackboneConfig(
			    image_size=self.image_size,					num_channels=self.num_channels,					out_features=self.out_features,					out_indices=self.out_indices,					stage_names=self.stage_names,					use_pretrained_backbone=self.use_pretrained_backbone,					backbone=self.backbone,					)

	def    snake_case__(						self:						Optional[int],					lowerCamelCase_:						Dict,					lowerCamelCase_:						Optional[int]			):
			lowercase__					:      Tuple      =		TimmBackbone(config=lowerCamelCase_			)
			model.to(lowerCamelCase_			)
			model.eval()
			with torch.no_grad():
					lowercase__					:      List[str]      =		model(lowerCamelCase_			)
			self.parent.assertEqual(
			    result.feature_map[-1].shape,					(self.batch_size, model.channels[-1], 14, 14),					)





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


@require_torch
@require_timm
class       __lowerCAmelCase					(       _UpperCamelCase   ,    _UpperCamelCase   ,    _UpperCamelCase   ,    unittest.TestCase      ):


	'''simple docstring'''





	_A													=				(TimmBackbone,) if is_torch_available() else ()
	_A													=				{"feature-extraction": TimmBackbone} if is_torch_available() else {}
	_A													=				False
	_A													=				False
	_A													=				False
	_A													=				False

	def    snake_case__(						self:						Optional[Any]			):
			lowercase__					:      Union[str, Any]      =		TimmBackboneModelTester(self			)
			lowercase__					:      str      =		ConfigTester(self,					config_class=lowerCamelCase_,					has_text_modality=lowerCamelCase_			)

	def    snake_case__(						self:						List[str]			):
			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:						Tuple			):
			lowercase__					:      Optional[Any]      =		'resnet18'
			lowercase__					:      str      =		'microsoft/resnet-18'

			lowercase__					:      Optional[int]      =		AutoBackbone.from_pretrained(lowerCamelCase_,					use_timm_backbone=lowerCamelCase_			)
			lowercase__					:      Union[str, Any]      =		AutoBackbone.from_pretrained(lowerCamelCase_			)

			self.assertEqual(len(timm_model.out_features			),					len(transformers_model.out_features			)			)
			self.assertEqual(len(timm_model.stage_names			),					len(transformers_model.stage_names			)			)
			self.assertEqual(timm_model.channels,					transformers_model.channels			)
			# Out indices are set to the last layer by default. For timm models, we don't know
			# the number of layers in advance, so we set it to (-1,), whereas for transformers
			# models, we set it to [len(stage_names) - 1] (kept for backward compatibility).
			self.assertEqual(timm_model.out_indices,					(-1,)			)
			self.assertEqual(transformers_model.out_indices,					[len(timm_model.stage_names			) - 1]			)

			lowercase__					:      List[Any]      =		AutoBackbone.from_pretrained(lowerCamelCase_,					use_timm_backbone=lowerCamelCase_,					out_indices=[1, 2, 3]			)
			lowercase__					:      List[str]      =		AutoBackbone.from_pretrained(lowerCamelCase_,					out_indices=[1, 2, 3]			)

			self.assertEqual(timm_model.out_indices,					transformers_model.out_indices			)
			self.assertEqual(len(timm_model.out_features			),					len(transformers_model.out_features			)			)
			self.assertEqual(timm_model.channels,					transformers_model.channels			)

	@unittest.skip('TimmBackbone doesn\'t support feed forward chunking'			)
	def    snake_case__(						self:						Union[str, Any]			):
			pass

	@unittest.skip('TimmBackbone doesn\'t have num_hidden_layers attribute'			)
	def    snake_case__(						self:						Optional[Any]			):
			pass

	@unittest.skip('TimmBackbone initialization is managed on the timm side'			)
	def    snake_case__(						self:						Union[str, Any]			):
			pass

	@unittest.skip('TimmBackbone models doesn\'t have inputs_embeds'			)
	def    snake_case__(						self:						Any			):
			pass

	@unittest.skip('TimmBackbone models doesn\'t have inputs_embeds'			)
	def    snake_case__(						self:						Optional[Any]			):
			pass

	@unittest.skip('TimmBackbone model cannot be created without specifying a backbone checkpoint'			)
	def    snake_case__(						self:						Union[str, Any]			):
			pass

	@unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone'			)
	def    snake_case__(						self:						Dict			):
			pass

	@unittest.skip('model weights aren\'t tied in TimmBackbone.'			)
	def    snake_case__(						self:						List[Any]			):
			pass

	@unittest.skip('model weights aren\'t tied in TimmBackbone.'			)
	def    snake_case__(						self:						List[Any]			):
			pass

	@unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone'			)
	def    snake_case__(						self:						Any			):
			pass

	@unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone'			)
	def    snake_case__(						self:						Optional[Any]			):
			pass

	@unittest.skip('TimmBackbone doesn\'t have hidden size info in its configuration.'			)
	def    snake_case__(						self:						Optional[Any]			):
			pass

	@unittest.skip('TimmBackbone doesn\'t support output_attentions.'			)
	def    snake_case__(						self:						Any			):
			pass

	@unittest.skip('Safetensors is not supported by timm.'			)
	def    snake_case__(						self:						Dict			):
			pass

	@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'			)
	def    snake_case__(						self:						List[str]			):
			pass

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

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

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

	def    snake_case__(						self:						Optional[int]			):
			lowercase__   ,				lowercase__					:      Dict      =		self.model_tester.prepare_config_and_inputs_for_common()
			lowercase__					:      Tuple      =		True
			lowercase__					:      List[Any]      =		self.has_attentions

			# no need to test all models as different heads yield the same functionality
			lowercase__					:      int      =		self.all_model_classes[0]
			lowercase__					:      Tuple      =		model_class(lowerCamelCase_			)
			model.to(lowerCamelCase_			)

			lowercase__					:      Optional[int]      =		self._prepare_for_class(lowerCamelCase_,					lowerCamelCase_			)
			lowercase__					:      Tuple      =		model(**lowerCamelCase_			)
			lowercase__					:      Optional[Any]      =		outputs[0][-1]

			# Encoder-/Decoder-only models
			lowercase__					:      Optional[int]      =		outputs.hidden_states[0]
			hidden_states.retain_grad()

			if self.has_attentions:
					lowercase__					:      Tuple      =		outputs.attentions[0]
					attentions.retain_grad()

			output.flatten()[0].backward(retain_graph=lowerCamelCase_			)

			self.assertIsNotNone(hidden_states.grad			)

			if self.has_attentions:
					self.assertIsNotNone(attentions.grad			)





	def    snake_case__(						self:						Optional[int]			):
			lowercase__   ,				lowercase__					:      str      =		self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
					lowercase__					:      str      =		model_class(lowerCamelCase_			)
					model.to(lowerCamelCase_			)
					model.eval()
					lowercase__					:      Optional[int]      =		model(**lowerCamelCase_			)

					self.assertEqual(len(result.feature_maps			),					len(config.out_indices			)			)
					self.assertEqual(len(model.channels			),					len(config.out_indices			)			)

					# Check output of last stage is taken if out_features=None, out_indices=None
					lowercase__					:      List[str]      =		copy.deepcopy(lowerCamelCase_			)
					lowercase__					:      List[str]      =		None
					lowercase__					:      List[Any]      =		model_class(lowerCamelCase_			)
					model.to(lowerCamelCase_			)
					model.eval()
					lowercase__					:      Optional[Any]      =		model(**lowerCamelCase_			)

					self.assertEqual(len(result.feature_maps			),					1			)
					self.assertEqual(len(model.channels			),					1			)

					# Check backbone can be initialized with fresh weights
					lowercase__					:      List[str]      =		copy.deepcopy(lowerCamelCase_			)
					lowercase__					:      Union[str, Any]      =		False
					lowercase__					:      Tuple      =		model_class(lowerCamelCase_			)
					model.to(lowerCamelCase_			)
					model.eval()
					lowercase__					:      Tuple      =		model(**lowerCamelCase_			)









from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__UpperCamelCase:	Optional[int] = logging.get_logger(__name__)

__UpperCamelCase:	Optional[int] = {
    """google/mobilenet_v1_1.0_224""": """https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json""",
    """google/mobilenet_v1_0.75_192""": """https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json""",
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
}


class       __lowerCAmelCase					(       _UpperCamelCase      ):


	'''simple docstring'''





	_A													=				"mobilenet_v1"

	def __init__(						self:						Dict,					lowerCamelCase_:						Any=3,					lowerCamelCase_:						Dict=224,					lowerCamelCase_:						int=1.0,					lowerCamelCase_:						List[Any]=8,					lowerCamelCase_:						int="relu6",					lowerCamelCase_:						Optional[int]=True,					lowerCamelCase_:						Any=0.9_9_9,					lowerCamelCase_:						List[str]=0.0_2,					lowerCamelCase_:						Optional[int]=0.0_0_1,					**lowerCamelCase_:						Tuple,					):
			super().__init__(**lowerCamelCase_			)

			if depth_multiplier <= 0:
					raise ValueError('depth_multiplier must be greater than zero.'			)

			lowercase__					:      Optional[int]      =		num_channels
			lowercase__					:      List[Any]      =		image_size
			lowercase__					:      str      =		depth_multiplier
			lowercase__					:      Optional[Any]      =		min_depth
			lowercase__					:      int      =		hidden_act
			lowercase__					:      Dict      =		tf_padding
			lowercase__					:      Optional[Any]      =		classifier_dropout_prob
			lowercase__					:      int      =		initializer_range
			lowercase__					:      Any      =		layer_norm_eps


class       __lowerCAmelCase					(       _UpperCamelCase      ):


	'''simple docstring'''





	_A													=				version.parse("1.11"      )

	@property
	def    snake_case__(						self:						Optional[int]			):
			return OrderedDict([('pixel_values', {0: 'batch'})]			)

	@property
	def    snake_case__(						self:						Dict			):
			if self.task == "image-classification":
					return OrderedDict([('logits', {0: 'batch'})]			)
			else:
					return OrderedDict([('last_hidden_state', {0: 'batch'}), ('pooler_output', {0: 'batch'})]			)





	@property
	def    snake_case__(						self:						List[Any]			):
			return 1E-4


