






"""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 		_a       (						lowercase_   ):





   '''simple docstring'''






   def __lowercase    (   self)	-> int:




          '''simple docstring'''




          lowercase__:    Union[str, Any]        =      self.config_class(**self.inputs_dict)
          self.parent.assertTrue(hasattr(UpperCAmelCase_			,				"hidden_sizes"))
          self.parent.assertTrue(hasattr(UpperCAmelCase_			,				"num_encoder_blocks"))







class 		_a       :





   '''simple docstring'''






   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			,				)	-> int:




          '''simple docstring'''




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





   def __lowercase    (   self)	-> int:




          '''simple docstring'''




          lowercase__:    Optional[Any]        =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

          lowercase__:    List[str]        =      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			,				UpperCAmelCase_			,				UpperCAmelCase_			,				UpperCAmelCase_)	-> List[str]:




          '''simple docstring'''




          lowercase__:    List[str]        =      PoolFormerModel(config=UpperCAmelCase_)
          model.to(UpperCAmelCase_)
          model.eval()
          lowercase__:    Optional[int]        =      model(UpperCAmelCase_)
          lowercase__:    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 __lowercase    (   self)	-> List[Any]:




          '''simple docstring'''




          lowercase__:    Any        =      self.prepare_config_and_inputs()
          lowercase__:    int        =      config_and_inputs
          lowercase__:    Union[str, Any]        =      {"pixel_values": pixel_values}
          return config, inputs_dict







@require_torch
class 		_a       (						lowercase_    ,					lowercase_    ,					unittest.TestCase   ):





   '''simple docstring'''






   UpperCamelCase__      					=    (PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
   UpperCamelCase__      					=    (
       {"""feature-extraction""": PoolFormerModel, """image-classification""": PoolFormerForImageClassification}
       if is_torch_available()
       else {}
   )

   UpperCamelCase__      					=    False
   UpperCamelCase__      					=    False
   UpperCamelCase__      					=    False
   UpperCamelCase__      					=    False
   UpperCamelCase__      					=    False





   def __lowercase    (   self)	-> Dict:




          '''simple docstring'''




          lowercase__:    Dict        =      PoolFormerModelTester(self)
          lowercase__:    List[Any]        =      PoolFormerConfigTester(self			,				config_class=UpperCAmelCase_)





   def __lowercase    (   self)	-> Dict:




          '''simple docstring'''




          self.config_tester.run_common_tests()





   def __lowercase    (   self)	-> Optional[Any]:




          '''simple docstring'''




          lowercase__:    Optional[Any]        =      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*UpperCAmelCase_)





   @unittest.skip("PoolFormer does not use inputs_embeds")
   def __lowercase    (   self)	-> Optional[Any]:




          '''simple docstring'''




          pass





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




          '''simple docstring'''




          pass





   def __lowercase    (   self)	-> str:




          '''simple docstring'''




          def check_hidden_states_output(UpperCAmelCase_			,				UpperCAmelCase_			,				UpperCAmelCase_):
                 lowercase__:    List[Any]        =      model_class(UpperCAmelCase_)
                 model.to(UpperCAmelCase_)
                 model.eval()

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

                 lowercase__:    List[str]        =      outputs.hidden_states

                 lowercase__:    Optional[Any]        =      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,
                     ]			,				)

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

          for model_class in self.all_model_classes:
                 lowercase__:    Any        =      True
                 check_hidden_states_output(UpperCAmelCase_			,				UpperCAmelCase_			,				UpperCAmelCase_)

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

                 check_hidden_states_output(UpperCAmelCase_			,				UpperCAmelCase_			,				UpperCAmelCase_)





   def __lowercase    (   self)	-> Optional[Any]:




          '''simple docstring'''




          if not self.model_tester.is_training:
                 return

          lowercase__:    List[str]        =      self.model_tester.prepare_config_and_inputs_for_common()
          lowercase__:    Tuple        =      True

          for model_class in self.all_model_classes:
                 if model_class in get_values(UpperCAmelCase_):
                        continue
                 lowercase__:    List[Any]        =      model_class(UpperCAmelCase_)
                 model.to(UpperCAmelCase_)
                 model.train()
                 lowercase__:    Dict        =      self._prepare_for_class(UpperCAmelCase_			,				UpperCAmelCase_			,				return_labels=UpperCAmelCase_)
                 lowercase__:    Optional[int]        =      model(**UpperCAmelCase_).loss
                 loss.backward()





   def __lowercase    (   self)	-> List[str]:




          '''simple docstring'''




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

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

                 lowercase__:    Optional[Any]        =      ["pixel_values"]
                 self.assertListEqual(arg_names[:1]			,				UpperCAmelCase_)





   @slow
   def __lowercase    (   self)	-> List[Any]:




          '''simple docstring'''




          for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowercase__:    List[Any]        =      PoolFormerModel.from_pretrained(UpperCAmelCase_)
                 self.assertIsNotNone(UpperCAmelCase_)







def     A(  ):
       """simple docstring"""





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







@require_torch
class 		_a       (						unittest.TestCase   ):





   '''simple docstring'''






   @slow
   def __lowercase    (   self)	-> str:




          '''simple docstring'''




          lowercase__:    Optional[int]        =      PoolFormerImageProcessor()
          lowercase__:    Optional[Any]        =      PoolFormerForImageClassification.from_pretrained("sail/poolformer_s12").to(UpperCAmelCase_)

          lowercase__:    Union[str, Any]        =      image_processor(images=prepare_img()			,				return_tensors="pt").to(UpperCAmelCase_)

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

          # verify the logits
          lowercase__:    List[Any]        =      torch.Size((1, 1_000))
          self.assertEqual(outputs.logits.shape			,				UpperCAmelCase_)

          lowercase__:    Dict        =      torch.tensor([-0.61_13, 0.16_85, -0.04_92]).to(UpperCAmelCase_)
          self.assertTrue(torch.allclose(outputs.logits[0, :3]			,				UpperCAmelCase_			,				atol=1E-4))














"""simple docstring"""





from __future__ import annotations






def     A(  snake_case_						,       snake_case_		):
       """simple docstring"""





       lowercase__  ,     lowercase__:    Optional[int]        =      0, len(snake_case_		) - 1
       while start_ind <= end_ind:
              if array[start_ind] == search_item:
                     return start_ind
              elif array[end_ind] == search_item:
                     return end_ind
              else:
                     start_ind += 1
                     end_ind -= 1
    # returns -1 if search_item is not found in array
       return -1


if __name__ == "__main__":
  print(double_linear_search(list(range(1_00)), 40))






