





"""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 					_UpperCamelCase  (		self							)    ->   int:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :int	       =						self.config_class(**self.inputs_dict							)
             self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE__	,'''hidden_sizes'''							)							)
             self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE__	,'''num_encoder_blocks'''							)							)






class       _SCREAMING_SNAKE_CASE:




       def __init__(		self	,SCREAMING_SNAKE_CASE__	,SCREAMING_SNAKE_CASE__=13	,SCREAMING_SNAKE_CASE__=64	,SCREAMING_SNAKE_CASE__=3	,SCREAMING_SNAKE_CASE__=4	,SCREAMING_SNAKE_CASE__=[2, 2, 2, 2]	,SCREAMING_SNAKE_CASE__=[8, 4, 2, 1]	,SCREAMING_SNAKE_CASE__=[16, 32, 64, 1_28]	,SCREAMING_SNAKE_CASE__=[1, 4, 8, 16]	,SCREAMING_SNAKE_CASE__=False	,SCREAMING_SNAKE_CASE__=True	,SCREAMING_SNAKE_CASE__="gelu"	,SCREAMING_SNAKE_CASE__=0.1	,SCREAMING_SNAKE_CASE__=0.0_2	,SCREAMING_SNAKE_CASE__=3	,SCREAMING_SNAKE_CASE__=None	,)    ->   Optional[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :List[Any]	       =						parent
             __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						batch_size
             __SCREAMING_SNAKE_CASE     :Dict	       =						image_size
             __SCREAMING_SNAKE_CASE     :Tuple	       =						num_channels
             __SCREAMING_SNAKE_CASE     :List[str]	       =						num_encoder_blocks
             __SCREAMING_SNAKE_CASE     :Any	       =						sr_ratios
             __SCREAMING_SNAKE_CASE     :Dict	       =						depths
             __SCREAMING_SNAKE_CASE     :List[Any]	       =						hidden_sizes
             __SCREAMING_SNAKE_CASE     :Dict	       =						downsampling_rates
             __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						is_training
             __SCREAMING_SNAKE_CASE     :str	       =						use_labels
             __SCREAMING_SNAKE_CASE     :Any	       =						hidden_act
             __SCREAMING_SNAKE_CASE     :Dict	       =						hidden_dropout_prob
             __SCREAMING_SNAKE_CASE     :Optional[int]	       =						initializer_range
             __SCREAMING_SNAKE_CASE     :Optional[int]	       =						num_labels
             __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						scope




       def 					_UpperCamelCase  (		self							)    ->   str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :Dict	       =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

             __SCREAMING_SNAKE_CASE     :List[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 					_UpperCamelCase  (		self	,SCREAMING_SNAKE_CASE__	,SCREAMING_SNAKE_CASE__	,SCREAMING_SNAKE_CASE__							)    ->   Optional[int]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						PoolFormerModel(config=SCREAMING_SNAKE_CASE__							)
             model.to(SCREAMING_SNAKE_CASE__							)
             model.eval()
             __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						model(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE     :List[Any]	       =						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							)    ->   Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :Tuple	       =						self.prepare_config_and_inputs()
             __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						config_and_inputs
             __SCREAMING_SNAKE_CASE     :Any	       =						{'''pixel_values''': pixel_values}
             return config, inputs_dict






@require_torch
class       _SCREAMING_SNAKE_CASE(     A					,			A					,			unittest.TestCase						):
       SCREAMING_SNAKE_CASE_     :   Union[str, Any]					=						(PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
       SCREAMING_SNAKE_CASE_     :   Dict					=						(
           {'''feature-extraction''': PoolFormerModel, '''image-classification''': PoolFormerForImageClassification}
           if is_torch_available()
           else {}
       )

       SCREAMING_SNAKE_CASE_     :   Union[str, Any]					=						False
       SCREAMING_SNAKE_CASE_     :   List[str]					=						False
       SCREAMING_SNAKE_CASE_     :   Tuple					=						False
       SCREAMING_SNAKE_CASE_     :   Optional[int]					=						False
       SCREAMING_SNAKE_CASE_     :   List[Any]					=						False




       def 					_UpperCamelCase  (		self							)    ->   Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :Optional[int]	       =						PoolFormerModelTester(self							)
             __SCREAMING_SNAKE_CASE     :Any	       =						PoolFormerConfigTester(self	,config_class=SCREAMING_SNAKE_CASE__							)




       def 					_UpperCamelCase  (		self							)    ->   Any:





             """simple docstring"""






             self.config_tester.run_common_tests()




       def 					_UpperCamelCase  (		self							)    ->   Dict:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__							)




       @unittest.skip('''PoolFormer does not use inputs_embeds'''							)
       def 					_UpperCamelCase  (		self							)    ->   List[str]:





             """simple docstring"""






             pass




       @unittest.skip('''PoolFormer does not have get_input_embeddings method and get_output_embeddings methods'''							)
       def 					_UpperCamelCase  (		self							)    ->   Union[str, Any]:





             """simple docstring"""






             pass




       def 					_UpperCamelCase  (		self							)    ->   List[Any]:





             """simple docstring"""






             def check_hidden_states_output(SCREAMING_SNAKE_CASE__	,SCREAMING_SNAKE_CASE__	,SCREAMING_SNAKE_CASE__							):
                   __SCREAMING_SNAKE_CASE     :List[str]	       =						model_class(SCREAMING_SNAKE_CASE__							)
                   model.to(SCREAMING_SNAKE_CASE__							)
                   model.eval()

                   with torch.no_grad():
                         __SCREAMING_SNAKE_CASE     :Optional[int]	       =						model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__	,SCREAMING_SNAKE_CASE__							)							)

                   __SCREAMING_SNAKE_CASE     :List[str]	       =						outputs.hidden_states

                   __SCREAMING_SNAKE_CASE     :str	       =						self.model_tester.num_encoder_blocks
                   self.assertEqual(len(SCREAMING_SNAKE_CASE__							)	,SCREAMING_SNAKE_CASE__							)

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

             __SCREAMING_SNAKE_CASE     :Optional[int]	       =						self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   __SCREAMING_SNAKE_CASE     :List[str]	       =						True
                   check_hidden_states_output(SCREAMING_SNAKE_CASE__	,SCREAMING_SNAKE_CASE__	,SCREAMING_SNAKE_CASE__							)

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

                   check_hidden_states_output(SCREAMING_SNAKE_CASE__	,SCREAMING_SNAKE_CASE__	,SCREAMING_SNAKE_CASE__							)




       def 					_UpperCamelCase  (		self							)    ->   List[Any]:





             """simple docstring"""






             if not self.model_tester.is_training:
                   return

             __SCREAMING_SNAKE_CASE     :Any	       =						self.model_tester.prepare_config_and_inputs_for_common()
             __SCREAMING_SNAKE_CASE     :Dict	       =						True

             for model_class in self.all_model_classes:
                   if model_class in get_values(SCREAMING_SNAKE_CASE__							):
                         continue
                   __SCREAMING_SNAKE_CASE     :int	       =						model_class(SCREAMING_SNAKE_CASE__							)
                   model.to(SCREAMING_SNAKE_CASE__							)
                   model.train()
                   __SCREAMING_SNAKE_CASE     :Tuple	       =						self._prepare_for_class(SCREAMING_SNAKE_CASE__	,SCREAMING_SNAKE_CASE__	,return_labels=SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE     :List[Any]	       =						model(**SCREAMING_SNAKE_CASE__							).loss
                   loss.backward()




       def 					_UpperCamelCase  (		self							)    ->   Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :Optional[int]	       =						self.model_tester.prepare_config_and_inputs_for_common()

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

                   __SCREAMING_SNAKE_CASE     :int	       =						['''pixel_values''']
                   self.assertListEqual(arg_names[:1]	,SCREAMING_SNAKE_CASE__							)




       @slow
       def 					_UpperCamelCase  (		self							)    ->   Optional[int]:





             """simple docstring"""






             for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   __SCREAMING_SNAKE_CASE     :str	       =						PoolFormerModel.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)




def   __lowerCamelCase     (							)    ->   Union[str, Any]:
      __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''  )
      return image







@require_torch
class       _SCREAMING_SNAKE_CASE(     unittest.TestCase						):




       @slow
       def 					_UpperCamelCase  (		self							)    ->   Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						PoolFormerImageProcessor()
             __SCREAMING_SNAKE_CASE     :Optional[int]	       =						PoolFormerForImageClassification.from_pretrained('''sail/poolformer_s12'''							).to(SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE     :Any	       =						image_processor(images=prepare_img()	,return_tensors='''pt'''							).to(SCREAMING_SNAKE_CASE__							)

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

             # verify the logits
             __SCREAMING_SNAKE_CASE     :Tuple	       =						torch.Size((1, 10_00)							)
             self.assertEqual(outputs.logits.shape	,SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE     :Any	       =						torch.tensor([-0.6_1_1_3, 0.1_6_8_5, -0.0_4_9_2]							).to(SCREAMING_SNAKE_CASE__							)
             self.assertTrue(torch.allclose(outputs.logits[0, :3]	,SCREAMING_SNAKE_CASE__	,atol=1E-4							)							)






"""simple docstring"""
import json
import os
import tempfile

import datasets
from datasets.arrow_writer import ArrowWriter
from datasets.features import ArrayaD
from utils import generate_examples, get_duration


lowerCamelCase_          =	(3_0, 4_8_7)
lowerCamelCase_          =	(3_6, 1_0_2_4)
lowerCamelCase_          =	(1_0_0, 1_0_0)
lowerCamelCase_          =	1_0_0

lowerCamelCase_          =	datasets.Features(
    {"text": ArrayaD(SHAPE_TEST_1, dtype="float32"), "image": ArrayaD(SHAPE_TEST_2, dtype="float32")}
)

lowerCamelCase_    ,  lowerCamelCase_          =	os.path.split(__file__)
lowerCamelCase_          =	os.path.join(RESULTS_BASEPATH, "results", RESULTS_FILENAME.replace(".py", ".json"))



@get_duration
def   __lowerCamelCase     (							a_  :	Optional[Any]				,     a_  :	List[str]				,     a_  :	List[str]							)    ->   List[str]:
      with ArrowWriter(features=a_				,     path=os.path.join(a_				,     '''beta.arrow'''							)							) as writer:
            for key, record in dummy_data:
                  __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						my_features.encode_example(a_							)
                  writer.write(a_							)
            __SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE     :Optional[Any]	       =						writer.finalize()



@get_duration
def   __lowerCamelCase     (							a_  :	Tuple				,     a_  :	Optional[Any]							)    ->   Dict:
      __SCREAMING_SNAKE_CASE     :Tuple	       =						datasets.Dataset.from_file(
          filename=os.path.join(a_				,     '''beta.arrow'''							)				,     info=datasets.DatasetInfo(features=a_							)							)
      for _ in dataset:
            pass



@get_duration
def   __lowerCamelCase     (							a_  :	List[str]				,     a_  :	List[str]							)    ->   List[Any]:
      __SCREAMING_SNAKE_CASE     :Optional[int]	       =						datasets.Dataset.from_file(
          filename=os.path.join(a_				,     '''beta.arrow'''							)				,     info=datasets.DatasetInfo(features=a_							)							)
      dataset.set_format('''numpy'''							)
      for _ in dataset:
            pass



@get_duration
def   __lowerCamelCase     (							a_  :	Tuple				,     a_  :	Optional[int]							)    ->   Optional[int]:
      __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						10
      __SCREAMING_SNAKE_CASE     :Dict	       =						datasets.Dataset.from_file(
          filename=os.path.join(a_				,     '''beta.arrow'''							)				,     info=datasets.DatasetInfo(features=a_							)							)
      for i in range(0				,     len(a_							)				,     a_							):
            __SCREAMING_SNAKE_CASE     :Dict	       =						dataset[i : i + batch_size]



@get_duration
def   __lowerCamelCase     (							a_  :	Any				,     a_  :	Optional[Any]							)    ->   Optional[Any]:
      __SCREAMING_SNAKE_CASE     :List[Any]	       =						10
      __SCREAMING_SNAKE_CASE     :List[str]	       =						datasets.Dataset.from_file(
          filename=os.path.join(a_				,     '''beta.arrow'''							)				,     info=datasets.DatasetInfo(features=a_							)							)
      dataset.set_format('''numpy'''							)
      for i in range(0				,     len(a_							)				,     a_							):
            __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						dataset[i : i + batch_size]



@get_duration
def   __lowerCamelCase     (							a_  :	List[Any]				,     a_  :	Optional[Any]							)    ->   List[Any]:
      __SCREAMING_SNAKE_CASE     :Optional[int]	       =						datasets.Dataset.from_file(
          filename=os.path.join(a_				,     '''beta.arrow'''							)				,     info=datasets.DatasetInfo(features=a_							)							)
      for col in feats:
            __SCREAMING_SNAKE_CASE     :Tuple	       =						dataset[col]



@get_duration
def   __lowerCamelCase     (							a_  :	int				,     a_  :	List[str]							)    ->   str:
      __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						datasets.Dataset.from_file(
          filename=os.path.join(a_				,     '''beta.arrow'''							)				,     info=datasets.DatasetInfo(features=a_							)							)
      dataset.set_format('''numpy'''							)
      for col in feats:
            __SCREAMING_SNAKE_CASE     :List[Any]	       =						dataset[col]



def   __lowerCamelCase     (							)    ->   Union[str, Any]:
      __SCREAMING_SNAKE_CASE     :Tuple	       =						{}
      __SCREAMING_SNAKE_CASE     :int	       =						(
          read_unformated,
          read_formatted_as_numpy,
          read_batch_unformated,
          read_batch_formatted_as_numpy,
          read_col_unformated,
          read_col_formatted_as_numpy,
      )
      with tempfile.TemporaryDirectory() as tmp_dir:
            __SCREAMING_SNAKE_CASE     :Dict	       =						datasets.Features({'''image''': ArrayaD(a_				,     dtype='''float32'''							)}							)
            __SCREAMING_SNAKE_CASE     :Any	       =						generate_examples(features=a_				,     num_examples=a_							)
            __SCREAMING_SNAKE_CASE     :Dict	       =						write(a_				,     a_				,     a_							)
            for read_func in read_functions:
                  __SCREAMING_SNAKE_CASE     :str	       =						read_func(a_				,     a_							)

      with tempfile.TemporaryDirectory() as tmp_dir:
            # don't use fixed length for fair comparison
            # feats = datasets.Features(
            #     {"image": datasets.Sequence(datasets.Sequence(datasets.Value("float32"), SPEED_TEST_SHAPE[1]), SPEED_TEST_SHAPE[0])}
            # )
            __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						datasets.Features({'''image''': datasets.Sequence(datasets.Sequence(datasets.Value('''float32'''							)							)							)}							)
            __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						generate_examples(
                features=a_				,     num_examples=a_				,     seq_shapes={'''image''': SPEED_TEST_SHAPE}							)
            __SCREAMING_SNAKE_CASE     :Tuple	       =						write(a_				,     a_				,     a_							)
            for read_func in read_functions:
                  __SCREAMING_SNAKE_CASE     :Tuple	       =						read_func(a_				,     a_							)

      with tempfile.TemporaryDirectory() as tmp_dir:
            # don't use fixed length for fair comparison
            # feats = datasets.Features(
            #     {"image": datasets.Sequence(datasets.Value("float32"), SPEED_TEST_SHAPE[0] * SPEED_TEST_SHAPE[1])}
            # )
            __SCREAMING_SNAKE_CASE     :Dict	       =						datasets.Features({'''image''': datasets.Sequence(datasets.Value('''float32'''							)							)}							)
            __SCREAMING_SNAKE_CASE     :Dict	       =						generate_examples(
                features=a_				,     num_examples=a_				,     seq_shapes={'''image''': [SPEED_TEST_SHAPE[0] * SPEED_TEST_SHAPE[1]]}				,     )
            __SCREAMING_SNAKE_CASE     :Any	       =						write(a_				,     a_				,     a_							)
            for read_func in read_functions:
                  __SCREAMING_SNAKE_CASE     :str	       =						read_func(a_				,     a_							)

      with open(a_				,     '''wb'''							) as f:
            f.write(json.dumps(a_							).encode('''utf-8'''							)							)


if __name__ == "__main__":  # useful to run the profiler
  benchmark_array_xd()