






"""simple docstring"""




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        UpperCamelCase			:


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


 def _lowercase	(     self		:						Union[str, Any]							)					->       Optional[Any]:
   _a  :       Tuple             =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)
   _a  :       int             =	self.get_config()

   return config, pixel_values


 def _lowercase	(     self		:						List[Any]							)					->       Optional[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 _lowercase	(     self		:						Tuple							,						UpperCAmelCase__		:						int							,						UpperCAmelCase__		:						Optional[int]							)					->       List[str]:
   _a  :       List[str]             =	TimmBackbone(config=UpperCAmelCase__							)
   model.to(UpperCAmelCase__							)
   model.eval()
   with torch.no_grad():
     _a  :       str             =	model(UpperCAmelCase__							)
   self.parent.assertEqual(
       result.feature_map[-1].shape							,						(self.batch_size, model.channels[-1], 14, 14)							,						)







 def _lowercase	(     self		:						List[Any]							)					->       Optional[int]:
   _a  :       Dict             =	self.prepare_config_and_inputs()
   _a      ,  _a  :       Tuple             =	config_and_inputs
   _a  :       Any             =	{"""pixel_values""": pixel_values}
   return config, inputs_dict







@require_torch
@require_timm
class        UpperCamelCase			(	snake_case_		,     snake_case_		,     snake_case_		,     unittest.TestCase      ):
 UpperCamelCase					:       Any			=					(TimmBackbone,) if is_torch_available() else ()
 UpperCamelCase					:       int			=					{'''feature-extraction''': TimmBackbone} if is_torch_available() else {}
 UpperCamelCase					:       List[Any]			=					False
 UpperCamelCase					:       Tuple			=					False
 UpperCamelCase					:       Union[str, Any]			=					False
 UpperCamelCase					:       Tuple			=					False


 def _lowercase	(     self		:						Optional[Any]							)					->       List[Any]:
   _a  :       str             =	TimmBackboneModelTester(self							)
   _a  :       Optional[int]             =	ConfigTester(self							,						config_class=UpperCAmelCase__							,						has_text_modality=UpperCAmelCase__							)


 def _lowercase	(     self		:						List[str]							)					->       Optional[Any]:
   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 _lowercase	(     self		:						Any							)					->       Tuple:
   _a  :       Optional[Any]             =	"""resnet18"""
   _a  :       Union[str, Any]             =	"""microsoft/resnet-18"""

   _a  :       int             =	AutoBackbone.from_pretrained(UpperCAmelCase__							,						use_timm_backbone=UpperCAmelCase__							)
   _a  :       Union[str, Any]             =	AutoBackbone.from_pretrained(UpperCAmelCase__							)

   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]							)

   _a  :       int             =	AutoBackbone.from_pretrained(UpperCAmelCase__							,						use_timm_backbone=UpperCAmelCase__							,						out_indices=[1, 2, 3]							)
   _a  :       Optional[Any]             =	AutoBackbone.from_pretrained(UpperCAmelCase__							,						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 _lowercase	(     self		:						List[Any]							)					->       int:
   pass


 @unittest.skip("""TimmBackbone doesn't have num_hidden_layers attribute"""							)
 def _lowercase	(     self		:						Optional[int]							)					->       int:
   pass


 @unittest.skip("""TimmBackbone initialization is managed on the timm side"""							)
 def _lowercase	(     self		:						Optional[int]							)					->       List[Any]:
   pass


 @unittest.skip("""TimmBackbone models doesn't have inputs_embeds"""							)
 def _lowercase	(     self		:						Optional[int]							)					->       Any:
   pass


 @unittest.skip("""TimmBackbone models doesn't have inputs_embeds"""							)
 def _lowercase	(     self		:						Tuple							)					->       Tuple:
   pass


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


 @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone"""							)
 def _lowercase	(     self		:						Dict							)					->       str:
   pass


 @unittest.skip("""model weights aren't tied in TimmBackbone."""							)
 def _lowercase	(     self		:						Dict							)					->       Tuple:
   pass


 @unittest.skip("""model weights aren't tied in TimmBackbone."""							)
 def _lowercase	(     self		:						Dict							)					->       Tuple:
   pass


 @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone"""							)
 def _lowercase	(     self		:						Union[str, Any]							)					->       Optional[Any]:
   pass


 @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone"""							)
 def _lowercase	(     self		:						str							)					->       List[str]:
   pass


 @unittest.skip("""TimmBackbone doesn't have hidden size info in its configuration."""							)
 def _lowercase	(     self		:						List[Any]							)					->       Dict:
   pass


 @unittest.skip("""TimmBackbone doesn't support output_attentions."""							)
 def _lowercase	(     self		:						Union[str, Any]							)					->       Tuple:
   pass


 @unittest.skip("""Safetensors is not supported by timm."""							)
 def _lowercase	(     self		:						List[Any]							)					->       Dict:
   pass


 @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""							)
 def _lowercase	(     self		:						Tuple							)					->       Dict:
   pass


 def _lowercase	(     self		:						List[str]							)					->       Optional[int]:
   _a      ,  _a  :       Any             =	self.model_tester.prepare_config_and_inputs_for_common()

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

     _a  :       str             =	["""pixel_values"""]
     self.assertListEqual(arg_names[:1]							,						UpperCAmelCase__							)


 def _lowercase	(     self		:						int							)					->       Dict:
   _a      ,  _a  :       Optional[Any]             =	self.model_tester.prepare_config_and_inputs_for_common()
   _a  :       str             =	True
   _a  :       Union[str, Any]             =	self.has_attentions

   # no need to test all models as different heads yield the same functionality
   _a  :       Optional[Any]             =	self.all_model_classes[0]
   _a  :       Tuple             =	model_class(UpperCAmelCase__							)
   model.to(UpperCAmelCase__							)

   _a  :       List[str]             =	self._prepare_for_class(UpperCAmelCase__							,						UpperCAmelCase__							)
   _a  :       Optional[int]             =	model(**UpperCAmelCase__							)
   _a  :       Any             =	outputs[0][-1]

   # Encoder-/Decoder-only models
   _a  :       str             =	outputs.hidden_states[0]
   hidden_states.retain_grad()

   if self.has_attentions:
     _a  :       List[str]             =	outputs.attentions[0]
     attentions.retain_grad()

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

   self.assertIsNotNone(hidden_states.grad							)

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







 def _lowercase	(     self		:						str							)					->       Tuple:
   _a      ,  _a  :       List[Any]             =	self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     _a  :       int             =	model_class(UpperCAmelCase__							)
     model.to(UpperCAmelCase__							)
     model.eval()
     _a  :       Optional[int]             =	model(**UpperCAmelCase__							)

     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
     _a  :       Dict             =	copy.deepcopy(UpperCAmelCase__							)
     _a  :       Dict             =	None
     _a  :       Optional[Any]             =	model_class(UpperCAmelCase__							)
     model.to(UpperCAmelCase__							)
     model.eval()
     _a  :       List[Any]             =	model(**UpperCAmelCase__							)

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

     # Check backbone can be initialized with fresh weights
     _a  :       Any             =	copy.deepcopy(UpperCAmelCase__							)
     _a  :       Tuple             =	False
     _a  :       Optional[Any]             =	model_class(UpperCAmelCase__							)
     model.to(UpperCAmelCase__							)
     model.eval()
     _a  :       Any             =	model(**UpperCAmelCase__							)









"""simple docstring"""




import warnings

from ...utils import logging
from .image_processing_clip import CLIPImageProcessor


_snake_case          =   logging.get_logger(__name__)






class        UpperCamelCase			(	snake_case_      ):


 def __init__(     self		:						Any							,						*UpperCAmelCase__		:						Optional[Any]							,						**UpperCAmelCase__		:						Tuple							)					->       None:
   warnings.warn(
       """The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"""
       """ use CLIPImageProcessor instead."""							,						UpperCAmelCase__							,						)
   super().__init__(*UpperCAmelCase__							,						**UpperCAmelCase__							)

