






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       ,    UpperCAmelCase       ,    UpperCAmelCase=None       ,    UpperCAmelCase=None       ,    UpperCAmelCase=None       ,    UpperCAmelCase="resnet50"       ,    UpperCAmelCase=3       ,    UpperCAmelCase=32       ,    UpperCAmelCase=3       ,    UpperCAmelCase=True       ,    UpperCAmelCase=True       ,    ):
							"""simple docstring"""







							_UpperCAmelCase									=			parent
							_UpperCAmelCase									=			out_indices if out_indices is not None else [4]
							_UpperCAmelCase									=			stage_names
							_UpperCAmelCase									=			out_features
							_UpperCAmelCase									=			backbone
							_UpperCAmelCase									=			batch_size
							_UpperCAmelCase									=			image_size
							_UpperCAmelCase									=			num_channels
							_UpperCAmelCase									=			use_pretrained_backbone
							_UpperCAmelCase									=			is_training

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )
							_UpperCAmelCase									=			self.get_config()

							return config, pixel_values

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							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        UpperCamelCase    (							self       ,    UpperCAmelCase       ,    UpperCAmelCase    ):
							"""simple docstring"""







							_UpperCAmelCase									=			TimmBackbone(config=UpperCAmelCase    )
							model.to(UpperCAmelCase    )
							model.eval()
							with torch.no_grad():
													_UpperCAmelCase									=			model(UpperCAmelCase    )
							self.parent.assertEqual(
							    result.feature_map[-1].shape       ,    (self.batch_size, model.channels[-1], 14, 14)       ,    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			self.prepare_config_and_inputs()
							_UpperCAmelCase					, _UpperCAmelCase									=			config_and_inputs
							_UpperCAmelCase									=			{'pixel_values': pixel_values}
							return config, inputs_dict





@require_torch
@require_timm
class __lowerCamelCase (      __a     ,       __a     ,       __a     ,       unittest.TestCase):





	"""simple docstring"""






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

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			TimmBackboneModelTester(self    )
							_UpperCAmelCase									=			ConfigTester(self       ,    config_class=UpperCAmelCase       ,    has_text_modality=UpperCAmelCase    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							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        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			'resnet18'
							_UpperCAmelCase									=			'microsoft/resnet-18'

							_UpperCAmelCase									=			AutoBackbone.from_pretrained(UpperCAmelCase       ,    use_timm_backbone=UpperCAmelCase    )
							_UpperCAmelCase									=			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]    )

							_UpperCAmelCase									=			AutoBackbone.from_pretrained(UpperCAmelCase       ,    use_timm_backbone=UpperCAmelCase       ,    out_indices=[1, 2, 3]    )
							_UpperCAmelCase									=			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        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip('TimmBackbone doesn\'t have num_hidden_layers attribute'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip('TimmBackbone initialization is managed on the timm side'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip('TimmBackbone models doesn\'t have inputs_embeds'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip('TimmBackbone models doesn\'t have inputs_embeds'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip('TimmBackbone model cannot be created without specifying a backbone checkpoint'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip('model weights aren\'t tied in TimmBackbone.'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip('model weights aren\'t tied in TimmBackbone.'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip('TimmBackbone doesn\'t have hidden size info in its configuration.'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip('TimmBackbone doesn\'t support output_attentions.'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip('Safetensors is not supported by timm.'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase					, _UpperCAmelCase									=			self.model_tester.prepare_config_and_inputs_for_common()

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

													_UpperCAmelCase									=			['pixel_values']
													self.assertListEqual(arg_names[:1]       ,    UpperCAmelCase    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase					, _UpperCAmelCase									=			self.model_tester.prepare_config_and_inputs_for_common()
							_UpperCAmelCase									=			True
							_UpperCAmelCase									=			self.has_attentions

							# no need to test all models as different heads yield the same functionality
							_UpperCAmelCase									=			self.all_model_classes[0]
							_UpperCAmelCase									=			model_class(UpperCAmelCase    )
							model.to(UpperCAmelCase    )

							_UpperCAmelCase									=			self._prepare_for_class(UpperCAmelCase       ,    UpperCAmelCase    )
							_UpperCAmelCase									=			model(**UpperCAmelCase    )
							_UpperCAmelCase									=			outputs[0][-1]

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

							if self.has_attentions:
													_UpperCAmelCase									=			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        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase					, _UpperCAmelCase									=			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													_UpperCAmelCase									=			model_class(UpperCAmelCase    )
													model.to(UpperCAmelCase    )
													model.eval()
													_UpperCAmelCase									=			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
													_UpperCAmelCase									=			copy.deepcopy(UpperCAmelCase    )
													_UpperCAmelCase									=			None
													_UpperCAmelCase									=			model_class(UpperCAmelCase    )
													model.to(UpperCAmelCase    )
													model.eval()
													_UpperCAmelCase									=			model(**UpperCAmelCase    )

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

													# Check backbone can be initialized with fresh weights
													_UpperCAmelCase									=			copy.deepcopy(UpperCAmelCase    )
													_UpperCAmelCase									=			False
													_UpperCAmelCase									=			model_class(UpperCAmelCase    )
													model.to(UpperCAmelCase    )
													model.eval()
													_UpperCAmelCase									=			model(**UpperCAmelCase    )






'''simple docstring'''







from typing import Dict, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, logging


if is_torch_available():
   import torch


A     =logging.get_logger(__name__)


class 			_a  (	__a ):
       __a				:     str   				=					["""pixel_values"""]
       def __init__(	self						:	Optional[int]   ,				lowercase						:	bool = True   ,				lowercase						:	Optional[Dict[str, int]] = None   ,				lowercase						:	PILImageResampling = PILImageResampling.BILINEAR   ,				lowercase						:	bool = True   ,				lowercase						:	Dict[str, int] = None   ,				lowercase						:	bool = True   ,				lowercase						:	Union[int, float] = 1 / 255   ,				lowercase						:	bool = True   ,				lowercase						:	Optional[Union[float, List[float]]] = None   ,				lowercase						:	Optional[Union[float, List[float]]] = None   ,				**lowercase						:	Union[str, Any]   ,				):



           '''simple docstring'''

           super().__init__(**lowercase				)
           UpperCAmelCase			       =		size if size is not None else {'''shortest_edge''': 256}
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				default_to_square=lowercase				)
           UpperCAmelCase			       =		crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				param_name='''crop_size'''				)
           UpperCAmelCase			       =		do_resize
           UpperCAmelCase			       =		size
           UpperCAmelCase			       =		resample
           UpperCAmelCase			       =		do_center_crop
           UpperCAmelCase			       =		crop_size
           UpperCAmelCase			       =		do_rescale
           UpperCAmelCase			       =		rescale_factor
           UpperCAmelCase			       =		do_normalize
           UpperCAmelCase			       =		image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
           UpperCAmelCase			       =		image_std if image_std is not None else IMAGENET_STANDARD_STD
       def     A      (	self						:	Union[str, Any]   ,				lowercase						:	np.ndarray   ,				lowercase						:	Dict[str, int]   ,				lowercase						:	PILImageResampling = PILImageResampling.BICUBIC   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	Any   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		get_size_dict(lowercase   ,				default_to_square=lowercase				)
           if "shortest_edge" not in size:
               raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"				)
           UpperCAmelCase			       =		get_resize_output_image_size(lowercase   ,				size=size['''shortest_edge''']   ,				default_to_square=lowercase				)
           return resize(lowercase   ,				size=lowercase   ,				resample=lowercase   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Union[str, Any]   ,				lowercase						:	np.ndarray   ,				lowercase						:	Dict[str, int]   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	int   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		get_size_dict(lowercase				)
           if "height" not in size or "width" not in size:
               raise ValueError(f"The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}"				)
           return center_crop(lowercase   ,				size=(size['''height'''], size['''width'''])   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Tuple   ,				lowercase						:	np.ndarray   ,				lowercase						:	float   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	List[str]				):



           '''simple docstring'''

           return rescale(lowercase   ,				scale=lowercase   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Optional[int]   ,				lowercase						:	np.ndarray   ,				lowercase						:	Union[float, List[float]]   ,				lowercase						:	Union[float, List[float]]   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	Union[str, Any]   ,				):



           '''simple docstring'''

           return normalize(lowercase   ,				mean=lowercase   ,				std=lowercase   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Optional[int]   ,				lowercase						:	ImageInput   ,				lowercase						:	Optional[bool] = None   ,				lowercase						:	Dict[str, int] = None   ,				lowercase						:	PILImageResampling = None   ,				lowercase						:	bool = None   ,				lowercase						:	Dict[str, int] = None   ,				lowercase						:	Optional[bool] = None   ,				lowercase						:	Optional[float] = None   ,				lowercase						:	Optional[bool] = None   ,				lowercase						:	Optional[Union[float, List[float]]] = None   ,				lowercase						:	Optional[Union[float, List[float]]] = None   ,				lowercase						:	Optional[Union[str, TensorType]] = None   ,				lowercase						:	Union[str, ChannelDimension] = ChannelDimension.FIRST   ,				**lowercase						:	Dict   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		do_resize if do_resize is not None else self.do_resize
           UpperCAmelCase			       =		size if size is not None else self.size
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				default_to_square=lowercase				)
           UpperCAmelCase			       =		resample if resample is not None else self.resample
           UpperCAmelCase			       =		do_center_crop if do_center_crop is not None else self.do_center_crop
           UpperCAmelCase			       =		crop_size if crop_size is not None else self.crop_size
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				param_name='''crop_size'''				)
           UpperCAmelCase			       =		do_rescale if do_rescale is not None else self.do_rescale
           UpperCAmelCase			       =		rescale_factor if rescale_factor is not None else self.rescale_factor
           UpperCAmelCase			       =		do_normalize if do_normalize is not None else self.do_normalize
           UpperCAmelCase			       =		image_mean if image_mean is not None else self.image_mean
           UpperCAmelCase			       =		image_std if image_std is not None else self.image_std

           UpperCAmelCase			       =		make_list_of_images(lowercase				)

           if not valid_images(lowercase				):
               raise ValueError(
                   '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
                   '''torch.Tensor, tf.Tensor or jax.ndarray.'''				)

           if do_resize and size is None:
               raise ValueError('''Size must be specified if do_resize is True.'''				)

           if do_center_crop and crop_size is None:
               raise ValueError('''Crop size must be specified if do_center_crop is True.'''				)

           if do_rescale and rescale_factor is None:
               raise ValueError('''Rescale factor must be specified if do_rescale is True.'''				)

           if do_normalize and (image_mean is None or image_std is None):
               raise ValueError('''Image mean and std must be specified if do_normalize is True.'''				)

           # All transformations expect numpy arrays.
           UpperCAmelCase			       =		[to_numpy_array(lowercase				) for image in images]

           if do_resize:
               UpperCAmelCase			       =		[self.resize(image=lowercase   ,				size=lowercase   ,				resample=lowercase				) for image in images]

           if do_center_crop:
               UpperCAmelCase			       =		[self.center_crop(image=lowercase   ,				size=lowercase				) for image in images]

           if do_rescale:
               UpperCAmelCase			       =		[self.rescale(image=lowercase   ,				scale=lowercase				) for image in images]

           if do_normalize:
               UpperCAmelCase			       =		[self.normalize(image=lowercase   ,				mean=lowercase   ,				std=lowercase				) for image in images]

           UpperCAmelCase			       =		[to_channel_dimension_format(lowercase   ,				lowercase				) for image in images]

           UpperCAmelCase			       =		{'''pixel_values''': images}
           return BatchFeature(data=lowercase   ,				tensor_type=lowercase				)







       def     A      (	self						:	Tuple   ,				lowercase						:	str   ,				lowercase						:	List[Tuple] = None				):



           '''simple docstring'''

           UpperCAmelCase			       =		outputs.logits

           # Resize logits and compute semantic segmentation maps
           if target_sizes is not None:
               if len(lowercase				) != len(lowercase				):
                   raise ValueError(
                       '''Make sure that you pass in as many target sizes as the batch dimension of the logits'''				)

               if is_torch_tensor(lowercase				):
                   UpperCAmelCase			       =		target_sizes.numpy()

               UpperCAmelCase			       =		[]

               for idx in range(len(lowercase				)				):
                   UpperCAmelCase			       =		torch.nn.functional.interpolate(
                       logits[idx].unsqueeze(dim=0				)   ,				size=target_sizes[idx]   ,				mode='''bilinear'''   ,				align_corners=lowercase				)
                   UpperCAmelCase			       =		resized_logits[0].argmax(dim=0				)
                   semantic_segmentation.append(lowercase				)
           else:
               UpperCAmelCase			       =		logits.argmax(dim=1				)
               UpperCAmelCase			       =		[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]				)]

           return semantic_segmentation




