


'''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  __lowerCamelCase (       UpperCAmelCase_       ):
    """simple docstring"""


    def    A    (  self			:							Optional[int]):
           _A     :	str      =					self.config_class(**self.inputs_dict)
           self.parent.assertTrue(hasattr(__UpperCamelCase      ,							'hidden_sizes'))
           self.parent.assertTrue(hasattr(__UpperCamelCase      ,							'num_encoder_blocks'))




class  __lowerCamelCase :
    """simple docstring"""


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


    def    A    (  self			:							Dict):
           _A     :	str      =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

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




@require_torch
class  __lowerCamelCase (       UpperCAmelCase_				,					UpperCAmelCase_				,					unittest.TestCase       ):
    """simple docstring"""
    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    A    (  self			:							Optional[Any]):
           _A     :	Optional[int]      =					PoolFormerModelTester(self)
           _A     :	Optional[Any]      =					PoolFormerConfigTester(self      ,							config_class=__UpperCamelCase)


    def    A    (  self			:							int):
           self.config_tester.run_common_tests()


    def    A    (  self			:							Tuple):
           _A     :	int      =					self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__UpperCamelCase)


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


    @unittest.skip('PoolFormer does not have get_input_embeddings method and get_output_embeddings methods')
    def    A    (  self			:							List[str]):
           pass


    def    A    (  self			:							List[Any]):
           def check_hidden_states_output(SCREAMING_SNAKE_CASE			:							int      ,							SCREAMING_SNAKE_CASE			:							Any      ,							SCREAMING_SNAKE_CASE			:							Union[str, Any]):
                  _A     :	Union[str, Any]      =					model_class(__UpperCamelCase)
                  model.to(__UpperCamelCase)
                  model.eval()

                  with torch.no_grad():
                         _A     :	Optional[Any]      =					model(**self._prepare_for_class(__UpperCamelCase      ,							__UpperCamelCase))

                  _A     :	Dict      =					outputs.hidden_states

                  _A     :	str      =					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,
                      ]      ,							)

           _A  , _A     :	Any      =					self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                  _A     :	Dict      =					True
                  check_hidden_states_output(__UpperCamelCase      ,							__UpperCamelCase      ,							__UpperCamelCase)

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

                  check_hidden_states_output(__UpperCamelCase      ,							__UpperCamelCase      ,							__UpperCamelCase)


    def    A    (  self			:							str):
           if not self.model_tester.is_training:
                  return

           _A  , _A     :	Any      =					self.model_tester.prepare_config_and_inputs_for_common()
           _A     :	Any      =					True

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


    def    A    (  self			:							Tuple):
           _A  , _A     :	List[Any]      =					self.model_tester.prepare_config_and_inputs_for_common()

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

                  _A     :	Optional[Any]      =					['pixel_values']
                  self.assertListEqual(arg_names[:1]      ,							__UpperCamelCase)


    @slow
    def    A    (  self			:							List[str]):
           for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  _A     :	List[str]      =					PoolFormerModel.from_pretrained(__UpperCamelCase)
                  self.assertIsNotNone(__UpperCamelCase)






def       lowerCAmelCase__       (				):
       _A     :	Tuple      =					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
       return image


@require_torch
class  __lowerCamelCase (       unittest.TestCase       ):
    """simple docstring"""


    @slow
    def    A    (  self			:							Tuple):
           _A     :	Dict      =					PoolFormerImageProcessor()
           _A     :	List[str]      =					PoolFormerForImageClassification.from_pretrained('sail/poolformer_s12').to(__UpperCamelCase)

           _A     :	List[Any]      =					image_processor(images=prepare_img()      ,							return_tensors='pt').to(__UpperCamelCase)

           # forward pass
           with torch.no_grad():
                  _A     :	int      =					model(**__UpperCamelCase)

           # verify the logits
           _A     :	Tuple      =					torch.Size((1, 1000))
           self.assertEqual(outputs.logits.shape      ,							__UpperCamelCase)

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












'''simple docstring'''







from functools import lru_cache






@lru_cache
def 		_lowercase		(	lowercase_  ):



		'''simple docstring'''







		if not isinstance(lowercase_						,							lowercase_  ):
				raise TypeError("k must be an integer."  )
		if k < 0:
				raise ValueError("k integer must be greater or equal to zero."  )
		if k == 0:
				return 0
		elif k == 1:
				return 1
		else:
				return fibonacci(k - 1  ) + fibonacci(k - 2  )






def 		_lowercase		(	lowercase_						,							lowercase_  ):



		'''simple docstring'''







		_snake_case	       =       len(lowercase_  )
		# Find m such that F_m >= n where F_i is the i_th fibonacci number.
		_snake_case	       =       0
		while True:
				if fibonacci(lowercase_  ) >= len_list:
						_snake_case	       =       i
						break
				i += 1
		_snake_case	       =       0
		while fibb_k > 0:
				_snake_case	       =       min(
				    offset + fibonacci(fibb_k - 1  )						,							len_list - 1  )  # Prevent out of range
				_snake_case	       =       arr[index_k]
				if item_k_1 == val:
						return index_k
				elif val < item_k_1:
						fibb_k -= 1
				elif val > item_k_1:
						offset += fibonacci(fibb_k - 1  )
						fibb_k -= 2
		else:
				return -1


if __name__ == "__main__":
						import doctest

						doctest.testmod()





