import collections
import inspect
import unittest

from transformers import NatConfig
from transformers.testing_utils import require_natten, require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch
      from torch import nn

      from transformers import NatBackbone, NatForImageClassification, NatModel
      from transformers.models.nat.modeling_nat import NAT_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor



class     snake_case_			:






   def __init__( self							:	Union[str, Any]      ,		lowercase_							:	Optional[int]      ,		lowercase_							:	Union[str, Any]=13      ,		lowercase_							:	str=64      ,		lowercase_							:	str=4      ,		lowercase_							:	Optional[int]=3      ,		lowercase_							:	Any=16      ,		lowercase_							:	Optional[Any]=[1, 2, 1]      ,		lowercase_							:	str=[2, 4, 8]      ,		lowercase_							:	Tuple=3      ,		lowercase_							:	str=2.0      ,		lowercase_							:	Any=True      ,		lowercase_							:	Optional[int]=0.0      ,		lowercase_							:	Optional[int]=0.0      ,		lowercase_							:	int=0.1      ,		lowercase_							:	List[str]="gelu"      ,		lowercase_							:	Dict=True      ,		lowercase_							:	Dict=0.02      ,		lowercase_							:	Union[str, Any]=1E-5      ,		lowercase_							:	Tuple=True      ,		lowercase_							:	Union[str, Any]=None      ,		lowercase_							:	Union[str, Any]=True      ,		lowercase_							:	Optional[int]=10      ,		lowercase_							:	str=["stage1", "stage2"]      ,		lowercase_							:	List[Any]=[1, 2]      ,		)   ->		List[str]:
       lowercase__					:  str          =							parent
       lowercase__					:  Union[str, Any]          =							batch_size
       lowercase__					:  int          =							image_size
       lowercase__					:  Union[str, Any]          =							patch_size
       lowercase__					:  Union[str, Any]          =							num_channels
       lowercase__					:  int          =							embed_dim
       lowercase__					:  Dict          =							depths
       lowercase__					:  Tuple          =							num_heads
       lowercase__					:  List[Any]          =							kernel_size
       lowercase__					:  List[str]          =							mlp_ratio
       lowercase__					:  Tuple          =							qkv_bias
       lowercase__					:  Tuple          =							hidden_dropout_prob
       lowercase__					:  Dict          =							attention_probs_dropout_prob
       lowercase__					:  Dict          =							drop_path_rate
       lowercase__					:  int          =							hidden_act
       lowercase__					:  int          =							patch_norm
       lowercase__					:  Optional[int]          =							layer_norm_eps
       lowercase__					:  List[Any]          =							initializer_range
       lowercase__					:  Union[str, Any]          =							is_training
       lowercase__					:  Dict          =							scope
       lowercase__					:  str          =							use_labels
       lowercase__					:  Optional[Any]          =							num_labels
       lowercase__					:  List[str]          =							out_features
       lowercase__					:  str          =							out_indices






   def  __UpperCamelCase	( self							:	Optional[Any]    )   ->		Tuple:
       lowercase__					:  Optional[Any]          =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

       lowercase__					:  str          =							None
       if self.use_labels:
           lowercase__					:  Any          =							ids_tensor([self.batch_size]      ,		self.num_labels    )

       lowercase__					:  Dict          =							self.get_config()

       return config, pixel_values, labels






   def  __UpperCamelCase	( self							:	Optional[Any]    )   ->		Union[str, Any]:
       return NatConfig(
           num_labels=self.num_labels      ,		image_size=self.image_size      ,		patch_size=self.patch_size      ,		num_channels=self.num_channels      ,		embed_dim=self.embed_dim      ,		depths=self.depths      ,		num_heads=self.num_heads      ,		kernel_size=self.kernel_size      ,		mlp_ratio=self.mlp_ratio      ,		qkv_bias=self.qkv_bias      ,		hidden_dropout_prob=self.hidden_dropout_prob      ,		attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,		drop_path_rate=self.drop_path_rate      ,		hidden_act=self.hidden_act      ,		patch_norm=self.patch_norm      ,		layer_norm_eps=self.layer_norm_eps      ,		initializer_range=self.initializer_range      ,		out_features=self.out_features      ,		out_indices=self.out_indices      ,		)






   def  __UpperCamelCase	( self							:	Optional[int]      ,		lowercase_							:	Tuple      ,		lowercase_							:	Dict      ,		lowercase_							:	List[Any]    )   ->		Optional[int]:
       lowercase__					:  Dict          =							NatModel(config=UpperCamelCase_    )
       model.to(UpperCamelCase_    )
       model.eval()
       lowercase__					:  Tuple          =							model(UpperCamelCase_    )

       lowercase__					:  List[str]          =							(config.image_size // config.patch_size) // (2 ** (len(config.depths    ) - 1))
       lowercase__					:  List[str]          =							int(config.embed_dim * 2 ** (len(config.depths    ) - 1)    )

       self.parent.assertEqual(
           result.last_hidden_state.shape      ,		(self.batch_size, expected_height, expected_width, expected_dim)    )






   def  __UpperCamelCase	( self							:	Tuple      ,		lowercase_							:	Any      ,		lowercase_							:	Dict      ,		lowercase_							:	Union[str, Any]    )   ->		Tuple:
       lowercase__					:  Tuple          =							NatForImageClassification(UpperCamelCase_    )
       model.to(UpperCamelCase_    )
       model.eval()
       lowercase__					:  Dict          =							model(UpperCamelCase_      ,		labels=UpperCamelCase_    )
       self.parent.assertEqual(result.logits.shape      ,		(self.batch_size, self.num_labels)    )

       # test greyscale images
       lowercase__					:  Tuple          =							1
       lowercase__					:  Optional[Any]          =							NatForImageClassification(UpperCamelCase_    )
       model.to(UpperCamelCase_    )
       model.eval()

       lowercase__					:  Dict          =							floats_tensor([self.batch_size, 1, self.image_size, self.image_size]    )
       lowercase__					:  Union[str, Any]          =							model(UpperCamelCase_    )
       self.parent.assertEqual(result.logits.shape      ,		(self.batch_size, self.num_labels)    )






   def  __UpperCamelCase	( self							:	Optional[Any]      ,		lowercase_							:	Any      ,		lowercase_							:	Optional[Any]      ,		lowercase_							:	List[Any]    )   ->		List[str]:
       lowercase__					:  Tuple          =							NatBackbone(config=UpperCamelCase_    )
       model.to(UpperCamelCase_    )
       model.eval()
       lowercase__					:  List[str]          =							model(UpperCamelCase_    )

       # verify hidden states
       self.parent.assertEqual(len(result.feature_maps    )      ,		len(config.out_features    )    )
       self.parent.assertListEqual(list(result.feature_maps[0].shape    )      ,		[self.batch_size, model.channels[0], 16, 16]    )

       # verify channels
       self.parent.assertEqual(len(model.channels    )      ,		len(config.out_features    )    )

       # verify backbone works with out_features=None
       lowercase__					:  Tuple          =							None
       lowercase__					:  Union[str, Any]          =							NatBackbone(config=UpperCamelCase_    )
       model.to(UpperCamelCase_    )
       model.eval()
       lowercase__					:  Optional[int]          =							model(UpperCamelCase_    )

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps    )      ,		1    )
       self.parent.assertListEqual(list(result.feature_maps[0].shape    )      ,		[self.batch_size, model.channels[-1], 4, 4]    )

       # verify channels
       self.parent.assertEqual(len(model.channels    )      ,		1    )







   def  __UpperCamelCase	( self							:	Dict    )   ->		Optional[Any]:
       lowercase__					:  Any          =							self.prepare_config_and_inputs()
       lowercase__					:  Optional[int]          =							config_and_inputs
       lowercase__					:  Any          =							{'''pixel_values''': pixel_values}
       return config, inputs_dict



@require_natten
@require_torch
class     snake_case_			(						lowerCAmelCase_    ,lowerCAmelCase_    ,unittest.TestCase			):
   __A      :						Tuple   =							(
       (
           NatModel,
           NatForImageClassification,
           NatBackbone,
       )
       if is_torch_available()
       else ()
   )
   __A      :						List[Any]   =							(
       {'''feature-extraction''': NatModel, '''image-classification''': NatForImageClassification}
       if is_torch_available()
       else {}
   )
   __A      :						int   =							False

   __A      :						Optional[int]   =							False
   __A      :						List[Any]   =							False
   __A      :						Dict   =							False
   __A      :						Dict   =							False






   def  __UpperCamelCase	( self							:	Optional[Any]    )   ->		List[str]:
       lowercase__					:  Tuple          =							NatModelTester(self    )
       lowercase__					:  Optional[Any]          =							ConfigTester(self      ,		config_class=UpperCamelCase_      ,		embed_dim=37    )






   def  __UpperCamelCase	( self							:	Dict    )   ->		List[Any]:
       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  __UpperCamelCase	( self							:	Dict    )   ->		Optional[int]:
       return






   def  __UpperCamelCase	( self							:	Optional[Any]    )   ->		Optional[int]:
       lowercase__					:  Any          =							self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase_    )






   def  __UpperCamelCase	( self							:	int    )   ->		Any:
       lowercase__					:  Any          =							self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*UpperCamelCase_    )






   def  __UpperCamelCase	( self							:	Optional[Any]    )   ->		str:
       lowercase__					:  Dict          =							self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*UpperCamelCase_    )






   @unittest.skip(reason="Nat does not use inputs_embeds"    )
   def  __UpperCamelCase	( self							:	Any    )   ->		Optional[int]:
       pass






   @unittest.skip(reason="Nat does not use feedforward chunking"    )
   def  __UpperCamelCase	( self							:	Any    )   ->		str:
       pass






   def  __UpperCamelCase	( self							:	Dict    )   ->		Optional[Any]:
       lowercase__					:  List[str]          =							self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           lowercase__					:  Any          =							model_class(UpperCamelCase_    )
           self.assertIsInstance(model.get_input_embeddings()      ,		(nn.Module)    )
           lowercase__					:  List[Any]          =							model.get_output_embeddings()
           self.assertTrue(x is None or isinstance(UpperCamelCase_      ,		nn.Linear    )    )






   def  __UpperCamelCase	( self							:	int    )   ->		Optional[Any]:
       lowercase__					:  int          =							self.model_tester.prepare_config_and_inputs_for_common()

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

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






   def  __UpperCamelCase	( self							:	Optional[Any]    )   ->		List[Any]:
       self.skipTest("Nat\'s attention operation is handled entirely by NATTEN."    )






   def  __UpperCamelCase	( self							:	Any      ,		lowercase_							:	str      ,		lowercase_							:	List[str]      ,		lowercase_							:	int      ,		lowercase_							:	List[str]    )   ->		Optional[int]:
       lowercase__					:  int          =							model_class(UpperCamelCase_    )
       model.to(UpperCamelCase_    )
       model.eval()

       with torch.no_grad():
           lowercase__					:  Tuple          =							model(**self._prepare_for_class(UpperCamelCase_      ,		UpperCamelCase_    )    )

       lowercase__					:  Any          =							outputs.hidden_states

       lowercase__					:  str          =							getattr(
           self.model_tester      ,		"expected_num_hidden_layers"      ,		len(self.model_tester.depths    ) + 1    )
       self.assertEqual(len(UpperCamelCase_    )      ,		UpperCamelCase_    )

       # Nat has a different seq_length
       lowercase__					:  Optional[int]          =							(
           config.patch_size
           if isinstance(config.patch_size      ,		collections.abc.Iterable    )
           else (config.patch_size, config.patch_size)
       )

       lowercase__					:  Optional[Any]          =							image_size[0] // patch_size[0]
       lowercase__					:  List[Any]          =							image_size[1] // patch_size[1]

       self.assertListEqual(
           list(hidden_states[0].shape[-3:]    )      ,		[height, width, self.model_tester.embed_dim]      ,		)

       if model_class.__name__ != "NatBackbone":
           lowercase__					:  str          =							outputs.reshaped_hidden_states
           self.assertEqual(len(UpperCamelCase_    )      ,		UpperCamelCase_    )

           lowercase__					:  Optional[Any]          =							reshaped_hidden_states[0].shape
           lowercase__					:  List[Any]          =							(
               reshaped_hidden_states[0].view(UpperCamelCase_      ,		UpperCamelCase_      ,		UpperCamelCase_      ,		UpperCamelCase_    ).permute(0      ,		2      ,		3      ,		1    )
           )
           self.assertListEqual(
               list(reshaped_hidden_states.shape[-3:]    )      ,		[height, width, self.model_tester.embed_dim]      ,		)






   def  __UpperCamelCase	( self							:	int    )   ->		Tuple:
       lowercase__					:  Optional[Any]          =							self.model_tester.prepare_config_and_inputs_for_common()

       lowercase__					:  int          =							(
           self.model_tester.image_size
           if isinstance(self.model_tester.image_size      ,		collections.abc.Iterable    )
           else (self.model_tester.image_size, self.model_tester.image_size)
       )

       for model_class in self.all_model_classes:
           lowercase__					:  Union[str, Any]          =							True
           self.check_hidden_states_output(UpperCamelCase_      ,		UpperCamelCase_      ,		UpperCamelCase_      ,		UpperCamelCase_    )

           # check that output_hidden_states also work using config
           del inputs_dict["output_hidden_states"]
           lowercase__					:  int          =							True

           self.check_hidden_states_output(UpperCamelCase_      ,		UpperCamelCase_      ,		UpperCamelCase_      ,		UpperCamelCase_    )






   @slow
   def  __UpperCamelCase	( self							:	Union[str, Any]    )   ->		Union[str, Any]:
       for model_name in NAT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowercase__					:  Tuple          =							NatModel.from_pretrained(UpperCamelCase_    )
           self.assertIsNotNone(UpperCamelCase_    )







   def  __UpperCamelCase	( self							:	Any    )   ->		Tuple:
       lowercase__					:  str          =							self.model_tester.prepare_config_and_inputs_for_common()

       lowercase__					:  Optional[int]          =							_config_zero_init(UpperCamelCase_    )
       for model_class in self.all_model_classes:
           lowercase__					:  Union[str, Any]          =							model_class(config=UpperCamelCase_    )
           for name, param in model.named_parameters():
               if "embeddings" not in name and param.requires_grad:
                   self.assertIn(
                       ((param.data.mean() * 1E9).round() / 1E9).item()      ,		[0.0, 1.0]      ,		msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''      ,		)



@require_natten
@require_vision
@require_torch
class     snake_case_			(						unittest.TestCase			):






   @cached_property
   def  __UpperCamelCase	( self							:	Tuple    )   ->		Optional[Any]:
       return AutoImageProcessor.from_pretrained("shi-labs/nat-mini-in1k-224"    ) if is_vision_available() else None







   @slow
   def  __UpperCamelCase	( self							:	int    )   ->		Optional[int]:
       lowercase__					:  Dict          =							NatForImageClassification.from_pretrained("shi-labs/nat-mini-in1k-224"    ).to(UpperCamelCase_    )
       lowercase__					:  Optional[int]          =							self.default_image_processor

       lowercase__					:  List[Any]          =							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
       lowercase__					:  List[str]          =							image_processor(images=UpperCamelCase_      ,		return_tensors="pt"    ).to(UpperCamelCase_    )

       # forward pass
       with torch.no_grad():
           lowercase__					:  Optional[Any]          =							model(**UpperCamelCase_    )

       # verify the logits
       lowercase__					:  Any          =							torch.Size((1, 10_00)    )
       self.assertEqual(outputs.logits.shape      ,		UpperCamelCase_    )
       lowercase__					:  List[Any]          =							torch.tensor([0.38_05, -0.86_76, -0.39_12]    ).to(UpperCamelCase_    )
       self.assertTrue(torch.allclose(outputs.logits[0, :3]      ,		UpperCamelCase_      ,		atol=1E-4    )    )



@require_torch
@require_natten
class     snake_case_			(						unittest.TestCase    ,lowerCAmelCase_			):
   __A      :						Tuple   =							(NatBackbone,) if is_torch_available() else ()
   __A      :						Optional[Any]   =							NatConfig






   def  __UpperCamelCase	( self							:	int    )   ->		Union[str, Any]:
       lowercase__					:  Dict          =							NatModelTester(self    )





'''simple docstring'''






import unittest

import numpy as np
from datasets import load_dataset

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
							import torch

if is_vision_available():
							from PIL import Image

							from transformers import SegformerImageProcessor

class 							_snake_case     (  unittest.TestCase ):
	"""simple docstring"""





	def __init__(						self				: int					,						UpperCamelCase_				: Any					,						UpperCamelCase_				: Any=7					,						UpperCamelCase_				: Optional[Any]=3					,						UpperCamelCase_				: Optional[Any]=30					,						UpperCamelCase_				: List[Any]=400					,						UpperCamelCase_				: Tuple=True					,						UpperCamelCase_				: List[str]=None					,						UpperCamelCase_				: str=True					,						UpperCamelCase_				: Tuple=[0.5, 0.5, 0.5]					,						UpperCamelCase_				: int=[0.5, 0.5, 0.5]					,						UpperCamelCase_				: str=False					,						):
			lowerCAmelCase_   :       Tuple    							=size if size is not None else {'''height''': 30, '''width''': 30}
			lowerCAmelCase_   :       List[Any]    							=parent
			lowerCAmelCase_   :       int    							=batch_size
			lowerCAmelCase_   :       int    							=num_channels
			lowerCAmelCase_   :       Union[str, Any]    							=min_resolution
			lowerCAmelCase_   :       Tuple    							=max_resolution
			lowerCAmelCase_   :       Tuple    							=do_resize
			lowerCAmelCase_   :       List[str]    							=size
			lowerCAmelCase_   :       int    							=do_normalize
			lowerCAmelCase_   :       int    							=image_mean
			lowerCAmelCase_   :       str    							=image_std
			lowerCAmelCase_   :       List[Any]    							=do_reduce_labels





	def 	__A      (						self				: Optional[Any]      ):
			return {
			    "do_resize": self.do_resize,
			    "size": self.size,
			    "do_normalize": self.do_normalize,
			    "image_mean": self.image_mean,
			    "image_std": self.image_std,
			    "do_reduce_labels": self.do_reduce_labels,
			}







def 		SCREAMING_SNAKE_CASE__					(							):
		lowerCAmelCase_   :       Optional[int]    							=load_dataset('''hf-internal-testing/fixtures_ade20k'''  ,					split='''test'''  )

		lowerCAmelCase_   :       Optional[Any]    							=Image.open(dataset[0]['''file''']  )
		lowerCAmelCase_   :       Tuple    							=Image.open(dataset[1]['''file''']  )

		return image, map







def 		SCREAMING_SNAKE_CASE__					(							):
		lowerCAmelCase_   :       Tuple    							=load_dataset('''hf-internal-testing/fixtures_ade20k'''  ,					split='''test'''  )

		lowerCAmelCase_   :       Tuple    							=Image.open(dataset[0]['''file''']  )
		lowerCAmelCase_   :       Tuple    							=Image.open(dataset[1]['''file''']  )
		lowerCAmelCase_   :       Optional[int]    							=Image.open(dataset[2]['''file''']  )
		lowerCAmelCase_   :       Union[str, Any]    							=Image.open(dataset[3]['''file''']  )

		return [imagea, imagea], [mapa, mapa]






@require_torch
@require_vision
class 							_snake_case     (  lowerCAmelCase_						,    unittest.TestCase ):
	"""simple docstring"""





	_UpperCamelCase							:  List[Any]								=		SegformerImageProcessor if is_vision_available() else None




	def 	__A      (						self				: Optional[int]      ):
			lowerCAmelCase_   :       List[str]    							=SegformerImageProcessingTester(self      )




	@property
	def 	__A      (						self				: str      ):
			return self.image_processor_tester.prepare_image_processor_dict()




	def 	__A      (						self				: Tuple      ):
			lowerCAmelCase_   :       Optional[Any]    							=self.image_processing_class(**self.image_processor_dict      )
			self.assertTrue(hasattr(UpperCamelCase_					,						'''do_resize'''      )      )
			self.assertTrue(hasattr(UpperCamelCase_					,						'''size'''      )      )
			self.assertTrue(hasattr(UpperCamelCase_					,						'''do_normalize'''      )      )
			self.assertTrue(hasattr(UpperCamelCase_					,						'''image_mean'''      )      )
			self.assertTrue(hasattr(UpperCamelCase_					,						'''image_std'''      )      )
			self.assertTrue(hasattr(UpperCamelCase_					,						'''do_reduce_labels'''      )      )




	def 	__A      (						self				: Optional[Any]      ):
			lowerCAmelCase_   :       str    							=self.image_processing_class.from_dict(self.image_processor_dict      )
			self.assertEqual(image_processor.size					,						{'''height''': 30, '''width''': 30}      )
			self.assertEqual(image_processor.do_reduce_labels					,						UpperCamelCase_      )

			lowerCAmelCase_   :       Tuple    							=self.image_processing_class.from_dict(self.image_processor_dict					,						size=42					,						reduce_labels=UpperCamelCase_      )
			self.assertEqual(image_processor.size					,						{'''height''': 42, '''width''': 42}      )
			self.assertEqual(image_processor.do_reduce_labels					,						UpperCamelCase_      )




	def 	__A      (						self				: Dict      ):
			pass




	def 	__A      (						self				: Any      ):
			# Initialize image_processing
			lowerCAmelCase_   :       List[Any]    							=self.image_processing_class(**self.image_processor_dict      )
			# create random PIL images
			lowerCAmelCase_   :       Dict    							=prepare_image_inputs(self.image_processor_tester					,						equal_resolution=UpperCamelCase_      )
			for image in image_inputs:
					self.assertIsInstance(UpperCamelCase_					,						Image.Image      )

			# Test not batched input
			lowerCAmelCase_   :       int    							=image_processing(image_inputs[0]					,						return_tensors='''pt'''      ).pixel_values
			self.assertEqual(
			    encoded_images.shape					,						(
			        1,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.size['''height'''],
			        self.image_processor_tester.size['''width'''],
			    )					,						)

			# Test batched
			lowerCAmelCase_   :       Optional[Any]    							=image_processing(UpperCamelCase_					,						return_tensors='''pt'''      ).pixel_values
			self.assertEqual(
			    encoded_images.shape					,						(
			        self.image_processor_tester.batch_size,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.size['''height'''],
			        self.image_processor_tester.size['''width'''],
			    )					,						)




	def 	__A      (						self				: str      ):
			# Initialize image_processing
			lowerCAmelCase_   :       Union[str, Any]    							=self.image_processing_class(**self.image_processor_dict      )
			# create random numpy tensors
			lowerCAmelCase_   :       List[str]    							=prepare_image_inputs(self.image_processor_tester					,						equal_resolution=UpperCamelCase_					,						numpify=UpperCamelCase_      )
			for image in image_inputs:
					self.assertIsInstance(UpperCamelCase_					,						np.ndarray      )

			# Test not batched input
			lowerCAmelCase_   :       Any    							=image_processing(image_inputs[0]					,						return_tensors='''pt'''      ).pixel_values
			self.assertEqual(
			    encoded_images.shape					,						(
			        1,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.size['''height'''],
			        self.image_processor_tester.size['''width'''],
			    )					,						)

			# Test batched
			lowerCAmelCase_   :       Optional[Any]    							=image_processing(UpperCamelCase_					,						return_tensors='''pt'''      ).pixel_values
			self.assertEqual(
			    encoded_images.shape					,						(
			        self.image_processor_tester.batch_size,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.size['''height'''],
			        self.image_processor_tester.size['''width'''],
			    )					,						)




	def 	__A      (						self				: List[str]      ):
			# Initialize image_processing
			lowerCAmelCase_   :       List[Any]    							=self.image_processing_class(**self.image_processor_dict      )
			# create random PyTorch tensors
			lowerCAmelCase_   :       str    							=prepare_image_inputs(self.image_processor_tester					,						equal_resolution=UpperCamelCase_					,						torchify=UpperCamelCase_      )
			for image in image_inputs:
					self.assertIsInstance(UpperCamelCase_					,						torch.Tensor      )

			# Test not batched input
			lowerCAmelCase_   :       Optional[int]    							=image_processing(image_inputs[0]					,						return_tensors='''pt'''      ).pixel_values
			self.assertEqual(
			    encoded_images.shape					,						(
			        1,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.size['''height'''],
			        self.image_processor_tester.size['''width'''],
			    )					,						)

			# Test batched
			lowerCAmelCase_   :       str    							=image_processing(UpperCamelCase_					,						return_tensors='''pt'''      ).pixel_values
			self.assertEqual(
			    encoded_images.shape					,						(
			        self.image_processor_tester.batch_size,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.size['''height'''],
			        self.image_processor_tester.size['''width'''],
			    )					,						)




	def 	__A      (						self				: str      ):
			# Initialize image_processing
			lowerCAmelCase_   :       Any    							=self.image_processing_class(**self.image_processor_dict      )
			# create random PyTorch tensors
			lowerCAmelCase_   :       Optional[Any]    							=prepare_image_inputs(self.image_processor_tester					,						equal_resolution=UpperCamelCase_					,						torchify=UpperCamelCase_      )
			lowerCAmelCase_   :       Tuple    							=[]
			for image in image_inputs:
					self.assertIsInstance(UpperCamelCase_					,						torch.Tensor      )
					maps.append(torch.zeros(image.shape[-2:]      ).long()      )

			# Test not batched input
			lowerCAmelCase_   :       Optional[Any]    							=image_processing(image_inputs[0]					,						maps[0]					,						return_tensors='''pt'''      )
			self.assertEqual(
			    encoding['''pixel_values'''].shape					,						(
			        1,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.size['''height'''],
			        self.image_processor_tester.size['''width'''],
			    )					,						)
			self.assertEqual(
			    encoding['''labels'''].shape					,						(
			        1,
			        self.image_processor_tester.size['''height'''],
			        self.image_processor_tester.size['''width'''],
			    )					,						)
			self.assertEqual(encoding['''labels'''].dtype					,						torch.long      )
			self.assertTrue(encoding['''labels'''].min().item() >= 0      )
			self.assertTrue(encoding['''labels'''].max().item() <= 255      )

			# Test batched
			lowerCAmelCase_   :       Union[str, Any]    							=image_processing(UpperCamelCase_					,						UpperCamelCase_					,						return_tensors='''pt'''      )
			self.assertEqual(
			    encoding['''pixel_values'''].shape					,						(
			        self.image_processor_tester.batch_size,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.size['''height'''],
			        self.image_processor_tester.size['''width'''],
			    )					,						)
			self.assertEqual(
			    encoding['''labels'''].shape					,						(
			        self.image_processor_tester.batch_size,
			        self.image_processor_tester.size['''height'''],
			        self.image_processor_tester.size['''width'''],
			    )					,						)
			self.assertEqual(encoding['''labels'''].dtype					,						torch.long      )
			self.assertTrue(encoding['''labels'''].min().item() >= 0      )
			self.assertTrue(encoding['''labels'''].max().item() <= 255      )

			# Test not batched input (PIL images)
			lowerCAmelCase_							,		lowerCAmelCase_   :       int    							=prepare_semantic_single_inputs()

			lowerCAmelCase_   :       Union[str, Any]    							=image_processing(UpperCamelCase_					,						UpperCamelCase_					,						return_tensors='''pt'''      )
			self.assertEqual(
			    encoding['''pixel_values'''].shape					,						(
			        1,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.size['''height'''],
			        self.image_processor_tester.size['''width'''],
			    )					,						)
			self.assertEqual(
			    encoding['''labels'''].shape					,						(
			        1,
			        self.image_processor_tester.size['''height'''],
			        self.image_processor_tester.size['''width'''],
			    )					,						)
			self.assertEqual(encoding['''labels'''].dtype					,						torch.long      )
			self.assertTrue(encoding['''labels'''].min().item() >= 0      )
			self.assertTrue(encoding['''labels'''].max().item() <= 255      )

			# Test batched input (PIL images)
			lowerCAmelCase_							,		lowerCAmelCase_   :       Any    							=prepare_semantic_batch_inputs()

			lowerCAmelCase_   :       Union[str, Any]    							=image_processing(UpperCamelCase_					,						UpperCamelCase_					,						return_tensors='''pt'''      )
			self.assertEqual(
			    encoding['''pixel_values'''].shape					,						(
			        2,
			        self.image_processor_tester.num_channels,
			        self.image_processor_tester.size['''height'''],
			        self.image_processor_tester.size['''width'''],
			    )					,						)
			self.assertEqual(
			    encoding['''labels'''].shape					,						(
			        2,
			        self.image_processor_tester.size['''height'''],
			        self.image_processor_tester.size['''width'''],
			    )					,						)
			self.assertEqual(encoding['''labels'''].dtype					,						torch.long      )
			self.assertTrue(encoding['''labels'''].min().item() >= 0      )
			self.assertTrue(encoding['''labels'''].max().item() <= 255      )





	def 	__A      (						self				: List[str]      ):
			# Initialize image_processing
			lowerCAmelCase_   :       Any    							=self.image_processing_class(**self.image_processor_dict      )

			# ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
			lowerCAmelCase_							,		lowerCAmelCase_   :       int    							=prepare_semantic_single_inputs()
			lowerCAmelCase_   :       Dict    							=image_processing(UpperCamelCase_					,						UpperCamelCase_					,						return_tensors='''pt'''      )
			self.assertTrue(encoding['''labels'''].min().item() >= 0      )
			self.assertTrue(encoding['''labels'''].max().item() <= 150      )

			lowerCAmelCase_   :       Optional[Any]    							=True
			lowerCAmelCase_   :       Optional[Any]    							=image_processing(UpperCamelCase_					,						UpperCamelCase_					,						return_tensors='''pt'''      )
			self.assertTrue(encoding['''labels'''].min().item() >= 0      )
			self.assertTrue(encoding['''labels'''].max().item() <= 255      )






