





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  __UpperCamelCase						(       A__						):





     def 		UpperCamelCase(    self				):
        _UpperCAmelCase											=      self.config_class(**self.inputs_dict				)
        self.parent.assertTrue(hasattr(_UpperCamelCase							,       '''hidden_sizes'''				)				)
        self.parent.assertTrue(hasattr(_UpperCamelCase							,       '''num_encoder_blocks'''				)				)




class  __UpperCamelCase						:





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





     def 		UpperCamelCase(    self				):
        _UpperCAmelCase											=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

        _UpperCAmelCase											=      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 		UpperCamelCase(    self							,       _UpperCamelCase							,       _UpperCamelCase							,       _UpperCamelCase				):
        _UpperCAmelCase											=      PoolFormerModel(config=_UpperCamelCase				)
        model.to(_UpperCamelCase				)
        model.eval()
        _UpperCAmelCase											=      model(_UpperCamelCase				)
        _UpperCAmelCase											=      _UpperCAmelCase											=      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 		UpperCamelCase(    self				):
        _UpperCAmelCase											=      self.prepare_config_and_inputs()
        _UpperCAmelCase					,			_UpperCAmelCase					,			_UpperCAmelCase											=      config_and_inputs
        _UpperCAmelCase											=      {'''pixel_values''': pixel_values}
        return config, inputs_dict




@require_torch
class  __UpperCamelCase						(       A__  ,   A__  ,   unittest.TestCase						):
     __A  :     Union[str, Any]            =      (PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
     __A  :     str            =      (
         {"""feature-extraction""": PoolFormerModel, """image-classification""": PoolFormerForImageClassification}
         if is_torch_available()
         else {}
     )

     __A  :     Union[str, Any]            =      False
     __A  :     Tuple            =      False
     __A  :     Union[str, Any]            =      False
     __A  :     str            =      False
     __A  :     List[str]            =      False





     def 		UpperCamelCase(    self				):
        _UpperCAmelCase											=      PoolFormerModelTester(self				)
        _UpperCAmelCase											=      PoolFormerConfigTester(self							,       config_class=_UpperCamelCase				)





     def 		UpperCamelCase(    self				):
        self.config_tester.run_common_tests()





     def 		UpperCamelCase(    self				):
        _UpperCAmelCase											=      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*_UpperCamelCase				)





     @unittest.skip('''PoolFormer does not use inputs_embeds'''				)
     def 		UpperCamelCase(    self				):
        pass





     @unittest.skip('''PoolFormer does not have get_input_embeddings method and get_output_embeddings methods'''				)
     def 		UpperCamelCase(    self				):
        pass





     def 		UpperCamelCase(    self				):
        def check_hidden_states_output(_UpperCamelCase							,       _UpperCamelCase							,       _UpperCamelCase				):
           _UpperCAmelCase											=      model_class(_UpperCamelCase				)
           model.to(_UpperCamelCase				)
           model.eval()

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

           _UpperCAmelCase											=      outputs.hidden_states

           _UpperCAmelCase											=      self.model_tester.num_encoder_blocks
           self.assertEqual(len(_UpperCamelCase				)							,       _UpperCamelCase				)

           # 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,
               ]							,       )

        _UpperCAmelCase					,			_UpperCAmelCase											=      self.model_tester.prepare_config_and_inputs_for_common()

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

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

           check_hidden_states_output(_UpperCamelCase							,       _UpperCamelCase							,       _UpperCamelCase				)





     def 		UpperCamelCase(    self				):
        if not self.model_tester.is_training:
           return

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

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





     def 		UpperCamelCase(    self				):
        _UpperCAmelCase					,			_UpperCAmelCase											=      self.model_tester.prepare_config_and_inputs_for_common()

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

           _UpperCAmelCase											=      ['''pixel_values''']
           self.assertListEqual(arg_names[:1]							,       _UpperCamelCase				)





     @slow
     def 		UpperCamelCase(    self				):
        for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           _UpperCAmelCase											=      PoolFormerModel.from_pretrained(_UpperCamelCase				)
           self.assertIsNotNone(_UpperCamelCase				)




def     A__					(						)     ->     Optional[Any]:






   """simple docstring"""







   _UpperCAmelCase											=      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
   return image




@require_torch
class  __UpperCamelCase						(       unittest.TestCase						):





     @slow
     def 		UpperCamelCase(    self				):
        _UpperCAmelCase											=      PoolFormerImageProcessor()
        _UpperCAmelCase											=      PoolFormerForImageClassification.from_pretrained('''sail/poolformer_s12'''				).to(_UpperCamelCase				)

        _UpperCAmelCase											=      image_processor(images=prepare_img()							,       return_tensors='''pt'''				).to(_UpperCamelCase				)

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

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

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






def     A__					(						SCREAMING_SNAKE_CASE_      :			list	)     ->     bool:






   """simple docstring"""







   if not isinstance(SCREAMING_SNAKE_CASE_							,  SCREAMING_SNAKE_CASE_	):
      raise ValueError('''Input series is not valid, valid series - [1, 2/3, 2]'''	)
   if len(SCREAMING_SNAKE_CASE_	) == 0:
      raise ValueError('''Input list must be a non empty list'''	)
   if len(SCREAMING_SNAKE_CASE_	) == 1 and series[0] != 0:
      return True
   _UpperCAmelCase											=      []
   _UpperCAmelCase											=      len(SCREAMING_SNAKE_CASE_	)
   for i in range(0							,  SCREAMING_SNAKE_CASE_	):
      if series[i] == 0:
         raise ValueError('''Input series cannot have 0 as an element'''	)
      rec_series.append(1 / series[i]	)
   _UpperCAmelCase											=      rec_series[1] - rec_series[0]
   for index in range(2							,  SCREAMING_SNAKE_CASE_	):
      if rec_series[index] - rec_series[index - 1] != common_diff:
         return False
   return True
def     A__					(						SCREAMING_SNAKE_CASE_      :			list	)     ->     float:






   """simple docstring"""







   if not isinstance(SCREAMING_SNAKE_CASE_							,  SCREAMING_SNAKE_CASE_	):
      raise ValueError('''Input series is not valid, valid series - [2, 4, 6]'''	)
   if len(SCREAMING_SNAKE_CASE_	) == 0:
      raise ValueError('''Input list must be a non empty list'''	)
   _UpperCAmelCase											=      0
   for val in series:
      answer += 1 / val
   return len(SCREAMING_SNAKE_CASE_	) / answer


if __name__ == "__main__":
   import doctest

   doctest.testmod()