




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  __lowerCAmelCase							(				lowerCAmelCase):






       def        SCREAMING_SNAKE_CASE     ( self:       str					):
         lowercase     :Union[str, Any]   						=    self.config_class(**self.inputs_dict					)
         self.parent.assertTrue(hasattr(_lowerCAmelCase							,       "hidden_sizes"					)					)
         self.parent.assertTrue(hasattr(_lowerCAmelCase							,       "num_encoder_blocks"					)					)







class  __lowerCAmelCase							:






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






       def        SCREAMING_SNAKE_CASE     ( self:       Optional[Any]					):
         lowercase     :List[Any]   						=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

         lowercase     :Union[str, Any]   						=    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        SCREAMING_SNAKE_CASE     ( self:       Tuple							,       _lowerCAmelCase:       str							,       _lowerCAmelCase:       int							,       _lowerCAmelCase:       Union[str, Any]					):
         lowercase     :List[Any]   						=    PoolFormerModel(config=_lowerCAmelCase					)
         model.to(_lowerCAmelCase					)
         model.eval()
         lowercase     :Optional[Any]   						=    model(_lowerCAmelCase					)
         lowercase     :Tuple   						=    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        SCREAMING_SNAKE_CASE     ( self:       List[Any]					):
         lowercase     :Any   						=    self.prepare_config_and_inputs()
         lowercase						,     lowercase						,     lowercase     :Optional[int]   						=    config_and_inputs
         lowercase     :Dict   						=    {"pixel_values": pixel_values}
         return config, inputs_dict







@require_torch
class  __lowerCAmelCase							(				lowerCAmelCase   ,			lowerCAmelCase   ,			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        SCREAMING_SNAKE_CASE     ( self:       Any					):
         lowercase     :Tuple   						=    PoolFormerModelTester(self					)
         lowercase     :int   						=    PoolFormerConfigTester(self							,       config_class=_lowerCAmelCase					)






       def        SCREAMING_SNAKE_CASE     ( self:       List[Any]					):
         self.config_tester.run_common_tests()






       def        SCREAMING_SNAKE_CASE     ( self:       Dict					):
         lowercase     :Union[str, Any]   						=    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_lowerCAmelCase					)






       @unittest.skip("PoolFormer does not use inputs_embeds"					)
       def        SCREAMING_SNAKE_CASE     ( self:       Optional[int]					):
         pass






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






       def        SCREAMING_SNAKE_CASE     ( self:       List[str]					):
         def check_hidden_states_output(_lowerCAmelCase:       Optional[Any]							,       _lowerCAmelCase:       int							,       _lowerCAmelCase:       Any					):
           lowercase     :Tuple   						=    model_class(_lowerCAmelCase					)
           model.to(_lowerCAmelCase					)
           model.eval()

           with torch.no_grad():
             lowercase     :Union[str, Any]   						=    model(**self._prepare_for_class(_lowerCAmelCase							,       _lowerCAmelCase					)					)

           lowercase     :int   						=    outputs.hidden_states

           lowercase     :List[Any]   						=    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,
               ]							,       )

         lowercase						,     lowercase     :Union[str, Any]   						=    self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
           lowercase     :List[Any]   						=    True
           check_hidden_states_output(_lowerCAmelCase							,       _lowerCAmelCase							,       _lowerCAmelCase					)

           # check that output_hidden_states also work using config
           del inputs_dict["output_hidden_states"]
           lowercase     :List[str]   						=    True

           check_hidden_states_output(_lowerCAmelCase							,       _lowerCAmelCase							,       _lowerCAmelCase					)






       def        SCREAMING_SNAKE_CASE     ( self:       Union[str, Any]					):
         if not self.model_tester.is_training:
           return

         lowercase						,     lowercase     :Union[str, Any]   						=    self.model_tester.prepare_config_and_inputs_for_common()
         lowercase     :Optional[int]   						=    True

         for model_class in self.all_model_classes:
           if model_class in get_values(_lowerCAmelCase					):
             continue
           lowercase     :Any   						=    model_class(_lowerCAmelCase					)
           model.to(_lowerCAmelCase					)
           model.train()
           lowercase     :Union[str, Any]   						=    self._prepare_for_class(_lowerCAmelCase							,       _lowerCAmelCase							,       return_labels=_lowerCAmelCase					)
           lowercase     :Union[str, Any]   						=    model(**_lowerCAmelCase					).loss
           loss.backward()






       def        SCREAMING_SNAKE_CASE     ( self:       Optional[Any]					):
         lowercase						,     lowercase     :int   						=    self.model_tester.prepare_config_and_inputs_for_common()

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

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






       @slow
       def        SCREAMING_SNAKE_CASE     ( self:       str					):
         for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowercase     :Any   						=    PoolFormerModel.from_pretrained(_lowerCAmelCase					)
           self.assertIsNotNone(_lowerCAmelCase					)







def    UpperCAmelCase__	(  ):
  lowercase     :Union[str, Any]   						=    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
  return image







@require_torch
class  __lowerCAmelCase							(				unittest.TestCase):






       @slow
       def        SCREAMING_SNAKE_CASE     ( self:       List[str]					):
         lowercase     :Union[str, Any]   						=    PoolFormerImageProcessor()
         lowercase     :Tuple   						=    PoolFormerForImageClassification.from_pretrained("sail/poolformer_s12"					).to(_lowerCAmelCase					)

         lowercase     :Optional[Any]   						=    image_processor(images=prepare_img()							,       return_tensors="pt"					).to(_lowerCAmelCase					)

         # forward pass
         with torch.no_grad():
           lowercase     :Optional[int]   						=    model(**_lowerCAmelCase					)

         # verify the logits
         lowercase     :List[str]   						=    torch.Size((1, 10_00)					)
         self.assertEqual(outputs.logits.shape							,       _lowerCAmelCase					)

         lowercase     :Tuple   						=    torch.tensor([-0.61_13, 0.16_85, -0.04_92]					).to(_lowerCAmelCase					)
         self.assertTrue(torch.allclose(outputs.logits[0, :3]							,       _lowerCAmelCase							,       atol=1e-4					)					)









import unittest
from pathlib import Path

from transformers import is_vision_available, load_tool
from transformers.testing_utils import get_tests_dir

from .test_tools_common import ToolTesterMixin


if is_vision_available():
     from PIL import Image




class  __lowerCAmelCase							(				unittest.TestCase   ,			lowerCAmelCase):






       def        SCREAMING_SNAKE_CASE     ( self:       Dict					):
         lowercase     :Any   						=    load_tool("image-segmentation"					)
         self.tool.setup()
         lowercase     :int   						=    load_tool("image-segmentation"							,       remote=_lowerCAmelCase					)






       def        SCREAMING_SNAKE_CASE     ( self:       str					):
         lowercase     :Any   						=    Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO"					)					) / "000000039769.png"					)
         lowercase     :Dict   						=    self.tool(_lowerCAmelCase							,       "cat"					)
         self.assertTrue(isinstance(_lowerCAmelCase							,       Image.Image					)					)






       def        SCREAMING_SNAKE_CASE     ( self:       Union[str, Any]					):
         lowercase     :Dict   						=    Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO"					)					) / "000000039769.png"					)
         lowercase     :List[Any]   						=    self.remote_tool(_lowerCAmelCase							,       "cat"					)
         self.assertTrue(isinstance(_lowerCAmelCase							,       Image.Image					)					)






       def        SCREAMING_SNAKE_CASE     ( self:       List[Any]					):
         lowercase     :Optional[Any]   						=    Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO"					)					) / "000000039769.png"					)
         lowercase     :Dict   						=    self.tool(image=_lowerCAmelCase							,       label="cat"					)
         self.assertTrue(isinstance(_lowerCAmelCase							,       Image.Image					)					)






       def        SCREAMING_SNAKE_CASE     ( self:       Tuple					):
         lowercase     :int   						=    Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO"					)					) / "000000039769.png"					)
         lowercase     :List[str]   						=    self.remote_tool(image=_lowerCAmelCase							,       label="cat"					)
         self.assertTrue(isinstance(_lowerCAmelCase							,       Image.Image					)					)



