



'''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			,					_lowerCAmelCase			,					_lowerCAmelCase=None			,					_lowerCAmelCase=None			,					_lowerCAmelCase=None			,					_lowerCAmelCase="resnet50"			,					_lowerCAmelCase=3			,					_lowerCAmelCase=32			,					_lowerCAmelCase=3			,					_lowerCAmelCase=True			,					_lowerCAmelCase=True			,					)     ->     Union[str, Any]:
							'''simple docstring'''






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







	def 	_a (     self    )     ->     Optional[Any]:
							'''simple docstring'''






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

							return config, pixel_values







	def 	_a (     self    )     ->     Tuple:
							'''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 	_a (     self			,					_lowerCAmelCase			,					_lowerCAmelCase    )     ->     str:
							'''simple docstring'''






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







	def 	_a (     self    )     ->     str:
							'''simple docstring'''






							lowercase   =				self.prepare_config_and_inputs()
							lowercase  , lowercase   =				config_and_inputs
							lowercase   =				{"""pixel_values""": pixel_values}
							return config, inputs_dict




@require_torch
@require_timm
class   __UpperCamelCase							(lowercase__      , lowercase__      , lowercase__      , unittest.TestCase      ):
	__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 	_a (     self    )     ->     Optional[Any]:
							'''simple docstring'''






							lowercase   =				TimmBackboneModelTester(self    )
							lowercase   =				ConfigTester(self			,					config_class=lowercase_			,					has_text_modality=lowercase_    )







	def 	_a (     self    )     ->     Dict:
							'''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 	_a (     self    )     ->     str:
							'''simple docstring'''






							lowercase   =				"""resnet18"""
							lowercase   =				"""microsoft/resnet-18"""

							lowercase   =				AutoBackbone.from_pretrained(lowercase_			,					use_timm_backbone=lowercase_    )
							lowercase   =				AutoBackbone.from_pretrained(lowercase_    )

							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   =				AutoBackbone.from_pretrained(lowercase_			,					use_timm_backbone=lowercase_			,					out_indices=[1, 2, 3]    )
							lowercase   =				AutoBackbone.from_pretrained(lowercase_			,					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 	_a (     self    )     ->     int:
							'''simple docstring'''






							pass







	@unittest.skip("""TimmBackbone doesn\'t have num_hidden_layers attribute"""    )
	def 	_a (     self    )     ->     List[str]:
							'''simple docstring'''






							pass







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






							pass







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






							pass







	@unittest.skip("""TimmBackbone models doesn\'t have inputs_embeds"""    )
	def 	_a (     self    )     ->     List[str]:
							'''simple docstring'''






							pass







	@unittest.skip("""TimmBackbone model cannot be created without specifying a backbone checkpoint"""    )
	def 	_a (     self    )     ->     Optional[int]:
							'''simple docstring'''






							pass







	@unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone"""    )
	def 	_a (     self    )     ->     Union[str, Any]:
							'''simple docstring'''






							pass







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






							pass







	@unittest.skip("""model weights aren\'t tied in TimmBackbone."""    )
	def 	_a (     self    )     ->     List[Any]:
							'''simple docstring'''






							pass







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






							pass







	@unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone"""    )
	def 	_a (     self    )     ->     Union[str, Any]:
							'''simple docstring'''






							pass







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






							pass







	@unittest.skip("""TimmBackbone doesn\'t support output_attentions."""    )
	def 	_a (     self    )     ->     str:
							'''simple docstring'''






							pass







	@unittest.skip("""Safetensors is not supported by timm."""    )
	def 	_a (     self    )     ->     Optional[int]:
							'''simple docstring'''






							pass







	@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""    )
	def 	_a (     self    )     ->     Optional[Any]:
							'''simple docstring'''






							pass







	def 	_a (     self    )     ->     Any:
							'''simple docstring'''






							lowercase  , lowercase   =				self.model_tester.prepare_config_and_inputs_for_common()

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

													lowercase   =				["""pixel_values"""]
													self.assertListEqual(arg_names[:1]			,					lowercase_    )







	def 	_a (     self    )     ->     Any:
							'''simple docstring'''






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

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

							lowercase   =				self._prepare_for_class(lowercase_			,					lowercase_    )
							lowercase   =				model(**lowercase_    )
							lowercase   =				outputs[0][-1]

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

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

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

							self.assertIsNotNone(hidden_states.grad    )

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







	def 	_a (     self    )     ->     List[str]:
							'''simple docstring'''






							lowercase  , lowercase   =				self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													lowercase   =				model_class(lowercase_    )
													model.to(lowercase_    )
													model.eval()
													lowercase   =				model(**lowercase_    )

													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   =				copy.deepcopy(lowercase_    )
													lowercase   =				None
													lowercase   =				model_class(lowercase_    )
													model.to(lowercase_    )
													model.eval()
													lowercase   =				model(**lowercase_    )

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

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






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


_lowerCAmelCase:						List[Any]   				=       logging.get_logger(__name__)




class       lowercase_					(lowercase__   ):
				snake_case	    =['pixel_values']





				def __init__(				self       ,  lowercase_ = True       ,  lowercase_ = None       ,  lowercase_ = PILImageResampling.BILINEAR       ,  lowercase_ = True       ,  lowercase_ = None       ,  lowercase_ = True       ,  lowercase_ = 1 / 255       ,  lowercase_ = True       ,  lowercase_ = None       ,  lowercase_ = None       ,  **lowercase_       ,  )  -> None:
											super().__init__(**lowercase_)
											a__      =size if size is not None else {'shortest_edge': 256}
											a__      =get_size_dict(lowercase_       ,  default_to_square=lowercase_)
											a__      =crop_size if crop_size is not None else {'height': 224, 'width': 224}
											a__      =get_size_dict(lowercase_       ,  param_name='crop_size')
											a__      =do_resize
											a__      =size
											a__      =resample
											a__      =do_center_crop
											a__      =crop_size
											a__      =do_rescale
											a__      =rescale_factor
											a__      =do_normalize
											a__      =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
											a__      =image_std if image_std is not None else IMAGENET_STANDARD_STD





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_       ,  lowercase_ = PILImageResampling.BICUBIC       ,  lowercase_ = None       ,  **lowercase_       ,  )  -> np.ndarray:
											a__      =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()}""")
											a__      =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 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_       ,  lowercase_ = None       ,  **lowercase_       ,  )  -> np.ndarray:
											a__      =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 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_       ,  lowercase_ = None       ,  **lowercase_)  -> np.ndarray:
											return rescale(lowercase_       ,  scale=lowercase_       ,  data_format=lowercase_       ,  **lowercase_)





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_ = None       ,  **lowercase_       ,  )  -> np.ndarray:
											return normalize(lowercase_       ,  mean=lowercase_       ,  std=lowercase_       ,  data_format=lowercase_       ,  **lowercase_)





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_ = None       ,  lowercase_ = None       ,  lowercase_ = None       ,  lowercase_ = None       ,  lowercase_ = None       ,  lowercase_ = None       ,  lowercase_ = None       ,  lowercase_ = None       ,  lowercase_ = None       ,  lowercase_ = None       ,  lowercase_ = None       ,  lowercase_ = ChannelDimension.FIRST       ,  **lowercase_       ,  )  -> Tuple:
											a__      =do_resize if do_resize is not None else self.do_resize
											a__      =size if size is not None else self.size
											a__      =get_size_dict(lowercase_       ,  default_to_square=lowercase_)
											a__      =resample if resample is not None else self.resample
											a__      =do_center_crop if do_center_crop is not None else self.do_center_crop
											a__      =crop_size if crop_size is not None else self.crop_size
											a__      =get_size_dict(lowercase_       ,  param_name='crop_size')
											a__      =do_rescale if do_rescale is not None else self.do_rescale
											a__      =rescale_factor if rescale_factor is not None else self.rescale_factor
											a__      =do_normalize if do_normalize is not None else self.do_normalize
											a__      =image_mean if image_mean is not None else self.image_mean
											a__      =image_std if image_std is not None else self.image_std

											a__      =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.
											a__      =[to_numpy_array(lowercase_) for image in images]

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

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

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

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

											a__      =[to_channel_dimension_format(lowercase_       ,  lowercase_) for image in images]

											a__      ={'pixel_values': images}
											return BatchFeature(data=lowercase_       ,  tensor_type=lowercase_)





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_ = None)  -> str:
											a__      =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_):
																									a__      =target_sizes.numpy()

																		a__      =[]

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

											return semantic_segmentation

