'''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      (    __lowercase):







		"""simple docstring"""






		def 		UpperCamelCase__							( self					)			->  Optional[int]:
								_lowerCAmelCase					    =self.config_class(**self.inputs_dict					)
								self.parent.assertTrue(hasattr(__A		,    'hidden_sizes'					)					)
								self.parent.assertTrue(hasattr(__A		,    'num_encoder_blocks'					)					)

class 	SCREAMING_SNAKE_CASE      :







		"""simple docstring"""






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






		def 		UpperCamelCase__							( self					)			->  List[str]:
								_lowerCAmelCase					    =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

								_lowerCAmelCase					    =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		,    __A		,    __A		,    __A					)			->  Union[str, Any]:
								_lowerCAmelCase					    =PoolFormerModel(config=__A					)
								model.to(__A					)
								model.eval()
								_lowerCAmelCase					    =model(__A					)
								_lowerCAmelCase					    =_lowerCAmelCase					    =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					)			->  Union[str, Any]:
								_lowerCAmelCase					    =self.prepare_config_and_inputs()
								_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase					    =config_and_inputs
								_lowerCAmelCase					    ={'pixel_values': pixel_values}
								return config, inputs_dict

@require_torch
class 	SCREAMING_SNAKE_CASE      (    __lowercase     ,      __lowercase     ,      unittest.TestCase):







		"""simple docstring"""
		lowercase :   Tuple							=				(PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
		lowercase :   List[str]							=				(
		    {'feature-extraction': PoolFormerModel, 'image-classification': PoolFormerForImageClassification}
		    if is_torch_available()
		    else {}
		)

		lowercase :   Optional[Any]							=				False
		lowercase :   List[str]							=				False
		lowercase :   int							=				False
		lowercase :   Dict							=				False
		lowercase :   int							=				False






		def 		UpperCamelCase__							( self					)			->  List[str]:
								_lowerCAmelCase					    =PoolFormerModelTester(self					)
								_lowerCAmelCase					    =PoolFormerConfigTester(self		,    config_class=__A					)






		def 		UpperCamelCase__							( self					)			->  int:
								self.config_tester.run_common_tests()






		def 		UpperCamelCase__							( self					)			->  Union[str, Any]:
								_lowerCAmelCase					    =self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*__A					)






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






		@unittest.skip('PoolFormer does not have get_input_embeddings method and get_output_embeddings methods'					)
		def 		UpperCamelCase__							( self					)			->  List[Any]:
								pass






		def 		UpperCamelCase__							( self					)			->  Optional[Any]:
								def check_hidden_states_output(__A		,    __A		,    __A					):
														_lowerCAmelCase					    =model_class(__A					)
														model.to(__A					)
														model.eval()

														with torch.no_grad():
																				_lowerCAmelCase					    =model(**self._prepare_for_class(__A		,    __A					)					)

														_lowerCAmelCase					    =outputs.hidden_states

														_lowerCAmelCase					    =self.model_tester.num_encoder_blocks
														self.assertEqual(len(__A					)		,    __A					)

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

								_lowerCAmelCase    ,					_lowerCAmelCase					    =self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
														_lowerCAmelCase					    =True
														check_hidden_states_output(__A		,    __A		,    __A					)

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

														check_hidden_states_output(__A		,    __A		,    __A					)






		def 		UpperCamelCase__							( self					)			->  Any:
								if not self.model_tester.is_training:
														return

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

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






		def 		UpperCamelCase__							( self					)			->  Dict:
								_lowerCAmelCase    ,					_lowerCAmelCase					    =self.model_tester.prepare_config_and_inputs_for_common()

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

														_lowerCAmelCase					    =['pixel_values']
														self.assertListEqual(arg_names[:1]		,    __A					)






		@slow
		def 		UpperCamelCase__							( self					)			->  Union[str, Any]:
								for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														_lowerCAmelCase					    =PoolFormerModel.from_pretrained(__A					)
														self.assertIsNotNone(__A					)



def 				UpperCamelCase__      (      ):


						'''simple docstring'''






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


@require_torch
class 	SCREAMING_SNAKE_CASE      (    unittest.TestCase):







		"""simple docstring"""






		@slow
		def 		UpperCamelCase__							( self					)			->  Any:
								_lowerCAmelCase					    =PoolFormerImageProcessor()
								_lowerCAmelCase					    =PoolFormerForImageClassification.from_pretrained('sail/poolformer_s12'					).to(__A					)

								_lowerCAmelCase					    =image_processor(images=prepare_img()		,    return_tensors='pt'					).to(__A					)

								# forward pass
								with torch.no_grad():
														_lowerCAmelCase					    =model(**__A					)

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

								_lowerCAmelCase					    =torch.tensor([-0.6_113, 0.1_685, -0.0_492]					).to(__A					)
								self.assertTrue(torch.allclose(outputs.logits[0, :3]		,    __A		,    atol=1E-4					)					)






'''simple docstring'''

from itertools import compress, repeat
from math import ceil, sqrt



def 				UpperCamelCase__      (      a__   ):


						'''simple docstring'''






						if num <= 2:
												return []
						if num == 3:
												return [2]

						# Odd sieve for numbers in range [3, num - 1]
						_lowerCAmelCase					    =bytearray(B'\x01'   ) * ((num >> 1) - 1)

						for i in range(3      ,   int(sqrt(a__   )   ) + 1      ,   2   ):
												if sieve[(i >> 1) - 1]:
																		_lowerCAmelCase					    =i**2
																		_lowerCAmelCase					    =repeat(
																		    0      ,   ceil((num - i_squared) / (i << 1)   )   )

						return [2] + list(compress(range(3      ,   a__      ,   2   )      ,   a__   )   )


if __name__ == "__main__":
							import doctest

							doctest.testmod()





