





"""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 		lowercase ( _UpperCAmelCase ):





      def    _snake_case      (	self			)		->					Any:
            lowerCAmelCase  						=	self.config_class(**self.inputs_dict			)
            self.parent.assertTrue(hasattr(lowercase				,						"""hidden_sizes"""			)			)
            self.parent.assertTrue(hasattr(lowercase				,						"""num_encoder_blocks"""			)			)







class 		lowercase :





      def __init__(	self				,						lowercase				,						lowercase=13				,						lowercase=64				,						lowercase=3				,						lowercase=4				,						lowercase=[2, 2, 2, 2]				,						lowercase=[8, 4, 2, 1]				,						lowercase=[16, 32, 64, 128]				,						lowercase=[1, 4, 8, 16]				,						lowercase=False				,						lowercase=True				,						lowercase="gelu"				,						lowercase=0.1				,						lowercase=0.02				,						lowercase=3				,						lowercase=None				,						)		->					Tuple:
            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    _snake_case      (	self			)		->					Any:
            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    _snake_case      (	self				,						lowercase				,						lowercase				,						lowercase			)		->					int:
            lowerCAmelCase  						=	PoolFormerModel(config=lowercase			)
            model.to(lowercase			)
            model.eval()
            lowerCAmelCase  						=	model(lowercase			)
            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    _snake_case      (	self			)		->					Dict:
            lowerCAmelCase  						=	self.prepare_config_and_inputs()
            lowerCAmelCase						,		lowerCAmelCase						,		lowerCAmelCase  						=	config_and_inputs
            lowerCAmelCase  						=	{"""pixel_values""": pixel_values}
            return config, inputs_dict







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

      _SCREAMING_SNAKE_CASE         =				False
      _SCREAMING_SNAKE_CASE         =				False
      _SCREAMING_SNAKE_CASE         =				False
      _SCREAMING_SNAKE_CASE         =				False
      _SCREAMING_SNAKE_CASE         =				False





      def    _snake_case      (	self			)		->					str:
            lowerCAmelCase  						=	PoolFormerModelTester(self			)
            lowerCAmelCase  						=	PoolFormerConfigTester(self				,						config_class=lowercase			)





      def    _snake_case      (	self			)		->					Union[str, Any]:
            self.config_tester.run_common_tests()





      def    _snake_case      (	self			)		->					Optional[int]:
            lowerCAmelCase  						=	self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*lowercase			)





      @unittest.skip("""PoolFormer does not use inputs_embeds"""			)
      def    _snake_case      (	self			)		->					str:
            pass





      @unittest.skip("""PoolFormer does not have get_input_embeddings method and get_output_embeddings methods"""			)
      def    _snake_case      (	self			)		->					Optional[int]:
            pass





      def    _snake_case      (	self			)		->					int:
            def check_hidden_states_output(lowercase				,						lowercase				,						lowercase			):
                  lowerCAmelCase  						=	model_class(lowercase			)
                  model.to(lowercase			)
                  model.eval()

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

                  lowerCAmelCase  						=	outputs.hidden_states

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

                  # 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(lowercase				,						lowercase				,						lowercase			)

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

                  check_hidden_states_output(lowercase				,						lowercase				,						lowercase			)





      def    _snake_case      (	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(lowercase			):
                        continue
                  lowerCAmelCase  						=	model_class(lowercase			)
                  model.to(lowercase			)
                  model.train()
                  lowerCAmelCase  						=	self._prepare_for_class(lowercase				,						lowercase				,						return_labels=lowercase			)
                  lowerCAmelCase  						=	model(**lowercase			).loss
                  loss.backward()





      def    _snake_case      (	self			)		->					Union[str, Any]:
            lowerCAmelCase						,		lowerCAmelCase  						=	self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                  lowerCAmelCase  						=	model_class(lowercase			)
                  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]				,						lowercase			)





      @slow
      def    _snake_case      (	self			)		->					Optional[int]:
            for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  lowerCAmelCase  						=	PoolFormerModel.from_pretrained(lowercase			)
                  self.assertIsNotNone(lowercase			)







def       UpperCAmelCase__							(  ):







      '''simple docstring'''




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






@require_torch
class 		lowercase ( unittest.TestCase ):





      @slow
      def    _snake_case      (	self			)		->					Union[str, Any]:
            lowerCAmelCase  						=	PoolFormerImageProcessor()
            lowerCAmelCase  						=	PoolFormerForImageClassification.from_pretrained("""sail/poolformer_s12"""			).to(lowercase			)

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

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

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

            lowerCAmelCase  						=	torch.tensor([-0.6_113, 0.1_685, -0.0_492]			).to(lowercase			)
            self.assertTrue(torch.allclose(outputs.logits[0, :3]				,						lowercase				,						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 ConvNextImageProcessor

class 		lowercase ( unittest.TestCase ):





      def __init__(	self				,						lowercase				,						lowercase=7				,						lowercase=3				,						lowercase=18				,						lowercase=30				,						lowercase=400				,						lowercase=True				,						lowercase=None				,						lowercase=0.875				,						lowercase=True				,						lowercase=[0.5, 0.5, 0.5]				,						lowercase=[0.5, 0.5, 0.5]				,						)		->					List[Any]:
            lowerCAmelCase  						=	size if size is not None else {"""shortest_edge""": 20}
            lowerCAmelCase  						=	parent
            lowerCAmelCase  						=	batch_size
            lowerCAmelCase  						=	num_channels
            lowerCAmelCase  						=	image_size
            lowerCAmelCase  						=	min_resolution
            lowerCAmelCase  						=	max_resolution
            lowerCAmelCase  						=	do_resize
            lowerCAmelCase  						=	size
            lowerCAmelCase  						=	crop_pct
            lowerCAmelCase  						=	do_normalize
            lowerCAmelCase  						=	image_mean
            lowerCAmelCase  						=	image_std





      def    _snake_case      (	self			)		->					Optional[Any]:
            return {
                "image_mean": self.image_mean,
                "image_std": self.image_std,
                "do_normalize": self.do_normalize,
                "do_resize": self.do_resize,
                "size": self.size,
                "crop_pct": self.crop_pct,
            }







@require_torch
@require_vision
class 		lowercase ( _UpperCAmelCase					,  unittest.TestCase ):
      _SCREAMING_SNAKE_CASE         =				ConvNextImageProcessor if is_vision_available() else None





      def    _snake_case      (	self			)		->					List[str]:
            lowerCAmelCase  						=	ConvNextImageProcessingTester(self			)





      @property
      def    _snake_case      (	self			)		->					List[str]:
            return self.image_processor_tester.prepare_image_processor_dict()





      def    _snake_case      (	self			)		->					int:
            lowerCAmelCase  						=	self.image_processing_class(**self.image_processor_dict			)
            self.assertTrue(hasattr(lowercase				,						"""do_resize"""			)			)
            self.assertTrue(hasattr(lowercase				,						"""size"""			)			)
            self.assertTrue(hasattr(lowercase				,						"""crop_pct"""			)			)
            self.assertTrue(hasattr(lowercase				,						"""do_normalize"""			)			)
            self.assertTrue(hasattr(lowercase				,						"""image_mean"""			)			)
            self.assertTrue(hasattr(lowercase				,						"""image_std"""			)			)





      def    _snake_case      (	self			)		->					int:
            lowerCAmelCase  						=	self.image_processing_class.from_dict(self.image_processor_dict			)
            self.assertEqual(image_processor.size				,						{"""shortest_edge""": 20}			)

            lowerCAmelCase  						=	self.image_processing_class.from_dict(self.image_processor_dict				,						size=42			)
            self.assertEqual(image_processor.size				,						{"""shortest_edge""": 42}			)





      def    _snake_case      (	self			)		->					Optional[int]:
            pass





      def    _snake_case      (	self			)		->					Optional[int]:
            # 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=lowercase			)
            for image in image_inputs:
                  self.assertIsInstance(lowercase				,						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.size["""shortest_edge"""],
                    self.image_processor_tester.size["""shortest_edge"""],
                )				,						)

            # Test batched
            lowerCAmelCase  						=	image_processing(lowercase				,						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["""shortest_edge"""],
                    self.image_processor_tester.size["""shortest_edge"""],
                )				,						)





      def    _snake_case      (	self			)		->					str:
            # 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=lowercase				,						numpify=lowercase			)
            for image in image_inputs:
                  self.assertIsInstance(lowercase				,						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.size["""shortest_edge"""],
                    self.image_processor_tester.size["""shortest_edge"""],
                )				,						)

            # Test batched
            lowerCAmelCase  						=	image_processing(lowercase				,						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["""shortest_edge"""],
                    self.image_processor_tester.size["""shortest_edge"""],
                )				,						)





      def    _snake_case      (	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=lowercase				,						torchify=lowercase			)
            for image in image_inputs:
                  self.assertIsInstance(lowercase				,						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.size["""shortest_edge"""],
                    self.image_processor_tester.size["""shortest_edge"""],
                )				,						)

            # Test batched
            lowerCAmelCase  						=	image_processing(lowercase				,						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["""shortest_edge"""],
                    self.image_processor_tester.size["""shortest_edge"""],
                )				,						)






