




"""simple docstring"""







import inspect
import unittest

from transformers import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

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


if is_torch_available():
		import torch

		from transformers import MODEL_MAPPING, PoolFormerConfig, PoolFormerForImageClassification, PoolFormerModel
		from transformers.models.poolformer.modeling_poolformer import POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import PoolFormerImageProcessor






class  SCREAMING_SNAKE_CASE__   (   _a   ):


						def 					__lowercase	(							self			:     int   ):
										lowerCAmelCase		=			self.config_class(**self.inputs_dict   )
										self.parent.assertTrue(hasattr(lowerCAmelCase  ,  """hidden_sizes"""   )   )
										self.parent.assertTrue(hasattr(lowerCAmelCase  ,  """num_encoder_blocks"""   )   )






class  SCREAMING_SNAKE_CASE__   :


						def __init__(							self			:     Tuple  ,  lowerCAmelCase			:     Union[str, Any]  ,  lowerCAmelCase			:     int=13  ,  lowerCAmelCase			:     Optional[int]=64  ,  lowerCAmelCase			:     Union[str, Any]=3  ,  lowerCAmelCase			:     Tuple=4  ,  lowerCAmelCase			:     str=[2, 2, 2, 2]  ,  lowerCAmelCase			:     Tuple=[8, 4, 2, 1]  ,  lowerCAmelCase			:     Dict=[16, 32, 64, 128]  ,  lowerCAmelCase			:     int=[1, 4, 8, 16]  ,  lowerCAmelCase			:     Tuple=False  ,  lowerCAmelCase			:     Optional[int]=True  ,  lowerCAmelCase			:     str="gelu"  ,  lowerCAmelCase			:     Tuple=0.1  ,  lowerCAmelCase			:     Optional[Any]=0.02  ,  lowerCAmelCase			:     Optional[int]=3  ,  lowerCAmelCase			:     str=None  ,  ):
										lowerCAmelCase		=			parent
										lowerCAmelCase		=			batch_size
										lowerCAmelCase		=			image_size
										lowerCAmelCase		=			num_channels
										lowerCAmelCase		=			num_encoder_blocks
										lowerCAmelCase		=			sr_ratios
										lowerCAmelCase		=			depths
										lowerCAmelCase		=			hidden_sizes
										lowerCAmelCase		=			downsampling_rates
										lowerCAmelCase		=			is_training
										lowerCAmelCase		=			use_labels
										lowerCAmelCase		=			hidden_act
										lowerCAmelCase		=			hidden_dropout_prob
										lowerCAmelCase		=			initializer_range
										lowerCAmelCase		=			num_labels
										lowerCAmelCase		=			scope


						def 					__lowercase	(							self			:     Tuple   ):
										lowerCAmelCase		=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

										lowerCAmelCase		=			None
										if self.use_labels:
														lowerCAmelCase		=			ids_tensor([self.batch_size, self.image_size, self.image_size]  ,  self.num_labels   )

										lowerCAmelCase		=			PoolFormerConfig(
										    image_size=self.image_size  ,  num_channels=self.num_channels  ,  num_encoder_blocks=self.num_encoder_blocks  ,  depths=self.depths  ,  hidden_sizes=self.hidden_sizes  ,  hidden_act=self.hidden_act  ,  hidden_dropout_prob=self.hidden_dropout_prob  ,  initializer_range=self.initializer_range  ,  )

										return config, pixel_values, labels


						def 					__lowercase	(							self			:     Any  ,  lowerCAmelCase			:     Optional[int]  ,  lowerCAmelCase			:     Tuple  ,  lowerCAmelCase			:     Union[str, Any]   ):
										lowerCAmelCase		=			PoolFormerModel(config=lowerCAmelCase   )
										model.to(lowerCAmelCase   )
										model.eval()
										lowerCAmelCase		=			model(lowerCAmelCase   )
										lowerCAmelCase		=			lowerCAmelCase		=			self.image_size // 32.0
										self.parent.assertEqual(
										    result.last_hidden_state.shape  ,  (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)   )




						def 					__lowercase	(							self			:     Optional[Any]   ):
										lowerCAmelCase		=			self.prepare_config_and_inputs()
										lowerCAmelCase	,  lowerCAmelCase	,  lowerCAmelCase		=			config_and_inputs
										lowerCAmelCase		=			{"""pixel_values""": pixel_values}
										return config, inputs_dict






@require_torch
class  SCREAMING_SNAKE_CASE__   (   _a  ,			_a  ,			unittest.TestCase   ):
						_a        =  (PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
						_a        =  (
						    {'feature-extraction': PoolFormerModel, 'image-classification': PoolFormerForImageClassification}
						    if is_torch_available()
						    else {}
						)

						_a        =  False
						_a        =  False
						_a        =  False
						_a        =  False
						_a        =  False


						def 					__lowercase	(							self			:     List[str]   ):
										lowerCAmelCase		=			PoolFormerModelTester(self   )
										lowerCAmelCase		=			PoolFormerConfigTester(self  ,  config_class=lowerCAmelCase   )


						def 					__lowercase	(							self			:     Optional[Any]   ):
										self.config_tester.run_common_tests()


						def 					__lowercase	(							self			:     Union[str, Any]   ):
										lowerCAmelCase		=			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase   )


						@unittest.skip("""PoolFormer does not use inputs_embeds"""   )
						def 					__lowercase	(							self			:     List[Any]   ):
										pass


						@unittest.skip("""PoolFormer does not have get_input_embeddings method and get_output_embeddings methods"""   )
						def 					__lowercase	(							self			:     str   ):
										pass


						def 					__lowercase	(							self			:     Optional[int]   ):
										def check_hidden_states_output(lowerCAmelCase			:     List[str]  ,  lowerCAmelCase			:     Any  ,  lowerCAmelCase			:     Any   ):
														lowerCAmelCase		=			model_class(lowerCAmelCase   )
														model.to(lowerCAmelCase   )
														model.eval()

														with torch.no_grad():
																		lowerCAmelCase		=			model(**self._prepare_for_class(lowerCAmelCase  ,  lowerCAmelCase   )   )

														lowerCAmelCase		=			outputs.hidden_states

														lowerCAmelCase		=			self.model_tester.num_encoder_blocks
														self.assertEqual(len(lowerCAmelCase   )  ,  lowerCAmelCase   )

														# verify the first hidden states (first block)
														self.assertListEqual(
														    list(hidden_states[0].shape[-3:]   )  ,  [
														        self.model_tester.hidden_sizes[0],
														        self.model_tester.image_size // 4,
														        self.model_tester.image_size // 4,
														    ]  ,  )

										lowerCAmelCase	,  lowerCAmelCase		=			self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														lowerCAmelCase		=			True
														check_hidden_states_output(lowerCAmelCase  ,  lowerCAmelCase  ,  lowerCAmelCase   )

														# check that output_hidden_states also work using config
														del inputs_dict["output_hidden_states"]
														lowerCAmelCase		=			True

														check_hidden_states_output(lowerCAmelCase  ,  lowerCAmelCase  ,  lowerCAmelCase   )


						def 					__lowercase	(							self			:     Tuple   ):
										if not self.model_tester.is_training:
														return

										lowerCAmelCase	,  lowerCAmelCase		=			self.model_tester.prepare_config_and_inputs_for_common()
										lowerCAmelCase		=			True

										for model_class in self.all_model_classes:
														if model_class in get_values(lowerCAmelCase   ):
																		continue
														lowerCAmelCase		=			model_class(lowerCAmelCase   )
														model.to(lowerCAmelCase   )
														model.train()
														lowerCAmelCase		=			self._prepare_for_class(lowerCAmelCase  ,  lowerCAmelCase  ,  return_labels=lowerCAmelCase   )
														lowerCAmelCase		=			model(**lowerCAmelCase   ).loss
														loss.backward()


						def 					__lowercase	(							self			:     Optional[int]   ):
										lowerCAmelCase	,  lowerCAmelCase		=			self.model_tester.prepare_config_and_inputs_for_common()

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

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




						@slow
						def 					__lowercase	(							self			:     str   ):
										for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														lowerCAmelCase		=			PoolFormerModel.from_pretrained(lowerCAmelCase   )
														self.assertIsNotNone(lowerCAmelCase   )





def 							lowercase   ()       ->					Any:


				'''simple docstring'''






				lowerCAmelCase		=			Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
				return image






@require_torch
class  SCREAMING_SNAKE_CASE__   (   unittest.TestCase   ):


						@slow
						def 					__lowercase	(							self			:     str   ):
										lowerCAmelCase		=			PoolFormerImageProcessor()
										lowerCAmelCase		=			PoolFormerForImageClassification.from_pretrained("""sail/poolformer_s12"""   ).to(lowerCAmelCase   )

										lowerCAmelCase		=			image_processor(images=prepare_img()  ,  return_tensors="""pt"""   ).to(lowerCAmelCase   )

										# forward pass
										with torch.no_grad():
														lowerCAmelCase		=			model(**lowerCAmelCase   )

										# verify the logits
										lowerCAmelCase		=			torch.Size((1, 1000)   )
										self.assertEqual(outputs.logits.shape  ,  lowerCAmelCase   )

										lowerCAmelCase		=			torch.tensor([-0.6113, 0.1685, -0.0492]   ).to(lowerCAmelCase   )
										self.assertTrue(torch.allclose(outputs.logits[0, :3]  ,  lowerCAmelCase  ,  atol=1e-4   )   )











"""simple docstring"""







import unittest

import numpy as np

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 OwlViTImageProcessor






class  SCREAMING_SNAKE_CASE__   (   unittest.TestCase   ):


						def __init__(							self			:     int  ,  lowerCAmelCase			:     Optional[int]  ,  lowerCAmelCase			:     Optional[Any]=7  ,  lowerCAmelCase			:     str=3  ,  lowerCAmelCase			:     str=18  ,  lowerCAmelCase			:     Tuple=30  ,  lowerCAmelCase			:     Union[str, Any]=400  ,  lowerCAmelCase			:     List[str]=True  ,  lowerCAmelCase			:     List[str]=None  ,  lowerCAmelCase			:     int=True  ,  lowerCAmelCase			:     int=None  ,  lowerCAmelCase			:     Optional[int]=True  ,  lowerCAmelCase			:     Dict=[0.4814_5466, 0.457_8275, 0.4082_1073]  ,  lowerCAmelCase			:     str=[0.2686_2954, 0.2613_0258, 0.2757_7711]  ,  lowerCAmelCase			:     Any=True  ,  ):
										lowerCAmelCase		=			parent
										lowerCAmelCase		=			batch_size
										lowerCAmelCase		=			num_channels
										lowerCAmelCase		=			image_size
										lowerCAmelCase		=			min_resolution
										lowerCAmelCase		=			max_resolution
										lowerCAmelCase		=			do_resize
										lowerCAmelCase		=			size if size is not None else {"""height""": 18, """width""": 18}
										lowerCAmelCase		=			do_center_crop
										lowerCAmelCase		=			crop_size if crop_size is not None else {"""height""": 18, """width""": 18}
										lowerCAmelCase		=			do_normalize
										lowerCAmelCase		=			image_mean
										lowerCAmelCase		=			image_std
										lowerCAmelCase		=			do_convert_rgb




						def 					__lowercase	(							self			:     Tuple   ):
										return {
										    "do_resize": self.do_resize,
										    "size": self.size,
										    "do_center_crop": self.do_center_crop,
										    "crop_size": self.crop_size,
										    "do_normalize": self.do_normalize,
										    "image_mean": self.image_mean,
										    "image_std": self.image_std,
										    "do_convert_rgb": self.do_convert_rgb,
										}






@require_torch
@require_vision
class  SCREAMING_SNAKE_CASE__   (   _a  ,			unittest.TestCase   ):
						_a        =  OwlViTImageProcessor if is_vision_available() else None


						def 					__lowercase	(							self			:     Union[str, Any]   ):
										lowerCAmelCase		=			OwlViTImageProcessingTester(self   )


						@property
						def 					__lowercase	(							self			:     List[Any]   ):
										return self.image_processor_tester.prepare_image_processor_dict()


						def 					__lowercase	(							self			:     List[str]   ):
										lowerCAmelCase		=			self.image_processing_class(**self.image_processor_dict   )
										self.assertTrue(hasattr(lowerCAmelCase  ,  """do_resize"""   )   )
										self.assertTrue(hasattr(lowerCAmelCase  ,  """size"""   )   )
										self.assertTrue(hasattr(lowerCAmelCase  ,  """do_center_crop"""   )   )
										self.assertTrue(hasattr(lowerCAmelCase  ,  """center_crop"""   )   )
										self.assertTrue(hasattr(lowerCAmelCase  ,  """do_normalize"""   )   )
										self.assertTrue(hasattr(lowerCAmelCase  ,  """image_mean"""   )   )
										self.assertTrue(hasattr(lowerCAmelCase  ,  """image_std"""   )   )
										self.assertTrue(hasattr(lowerCAmelCase  ,  """do_convert_rgb"""   )   )


						def 					__lowercase	(							self			:     List[Any]   ):
										lowerCAmelCase		=			self.image_processing_class.from_dict(self.image_processor_dict   )
										self.assertEqual(image_processor.size  ,  {"""height""": 18, """width""": 18}   )
										self.assertEqual(image_processor.crop_size  ,  {"""height""": 18, """width""": 18}   )

										lowerCAmelCase		=			self.image_processing_class.from_dict(self.image_processor_dict  ,  size=42  ,  crop_size=84   )
										self.assertEqual(image_processor.size  ,  {"""height""": 42, """width""": 42}   )
										self.assertEqual(image_processor.crop_size  ,  {"""height""": 84, """width""": 84}   )


						def 					__lowercase	(							self			:     str   ):
										# Initialize image_processing
										lowerCAmelCase		=			self.image_processing_class(**self.image_processor_dict   )
										# create random PIL images
										lowerCAmelCase		=			prepare_image_inputs(self.image_processor_tester  ,  equal_resolution=lowerCAmelCase   )

										for image in image_inputs:
														self.assertIsInstance(lowerCAmelCase  ,  Image.Image   )

										# Test not batched input
										lowerCAmelCase		=			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.crop_size["""height"""],
										        self.image_processor_tester.crop_size["""width"""],
										    )  ,  )

										# Test batched
										lowerCAmelCase		=			image_processing(lowerCAmelCase  ,  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.crop_size["""height"""],
										        self.image_processor_tester.crop_size["""width"""],
										    )  ,  )


						def 					__lowercase	(							self			:     Tuple   ):
										# Initialize image_processing
										lowerCAmelCase		=			self.image_processing_class(**self.image_processor_dict   )
										# create random numpy tensors
										lowerCAmelCase		=			prepare_image_inputs(self.image_processor_tester  ,  equal_resolution=lowerCAmelCase  ,  numpify=lowerCAmelCase   )
										for image in image_inputs:
														self.assertIsInstance(lowerCAmelCase  ,  np.ndarray   )

										# Test not batched input
										lowerCAmelCase		=			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.crop_size["""height"""],
										        self.image_processor_tester.crop_size["""width"""],
										    )  ,  )

										# Test batched
										lowerCAmelCase		=			image_processing(lowerCAmelCase  ,  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.crop_size["""height"""],
										        self.image_processor_tester.crop_size["""width"""],
										    )  ,  )




						def 					__lowercase	(							self			:     Optional[int]   ):
										# Initialize image_processing
										lowerCAmelCase		=			self.image_processing_class(**self.image_processor_dict   )
										# create random PyTorch tensors
										lowerCAmelCase		=			prepare_image_inputs(self.image_processor_tester  ,  equal_resolution=lowerCAmelCase  ,  torchify=lowerCAmelCase   )
										for image in image_inputs:
														self.assertIsInstance(lowerCAmelCase  ,  torch.Tensor   )

										# Test not batched input
										lowerCAmelCase		=			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.crop_size["""height"""],
										        self.image_processor_tester.crop_size["""width"""],
										    )  ,  )

										# Test batched
										lowerCAmelCase		=			image_processing(lowerCAmelCase  ,  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.crop_size["""height"""],
										        self.image_processor_tester.crop_size["""width"""],
										    )  ,  )





