






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_     (	a_     ):
							def  SCREAMING_SNAKE_CASE_ (						self		:					int					):





								'''simple docstring'''



								a		=			self.config_class(**self.inputs_dict					)
								self.parent.assertTrue(hasattr(__lowerCamelCase							,'''hidden_sizes'''					)					)
								self.parent.assertTrue(hasattr(__lowerCamelCase							,'''num_encoder_blocks'''					)					)







class 				lowerCamelCase_     :
							def __init__(						self		:					int							,__lowerCamelCase		:					Optional[Any]							,__lowerCamelCase		:					List[Any]=13							,__lowerCamelCase		:					List[str]=64							,__lowerCamelCase		:					str=3							,__lowerCamelCase		:					Tuple=4							,__lowerCamelCase		:					int=[2, 2, 2, 2]							,__lowerCamelCase		:					Dict=[8, 4, 2, 1]							,__lowerCamelCase		:					str=[16, 32, 64, 1_28]							,__lowerCamelCase		:					Optional[Any]=[1, 4, 8, 16]							,__lowerCamelCase		:					Any=False							,__lowerCamelCase		:					List[Any]=True							,__lowerCamelCase		:					Any="gelu"							,__lowerCamelCase		:					Union[str, Any]=0.1							,__lowerCamelCase		:					Dict=0.02							,__lowerCamelCase		:					Dict=3							,__lowerCamelCase		:					Dict=None							,):





								'''simple docstring'''



								a		=			parent
								a		=			batch_size
								a		=			image_size
								a		=			num_channels
								a		=			num_encoder_blocks
								a		=			sr_ratios
								a		=			depths
								a		=			hidden_sizes
								a		=			downsampling_rates
								a		=			is_training
								a		=			use_labels
								a		=			hidden_act
								a		=			hidden_dropout_prob
								a		=			initializer_range
								a		=			num_labels
								a		=			scope
							def  SCREAMING_SNAKE_CASE_ (						self		:					List[Any]					):





								'''simple docstring'''



								a		=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

								a		=			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  SCREAMING_SNAKE_CASE_ (						self		:					Tuple							,__lowerCamelCase		:					Union[str, Any]							,__lowerCamelCase		:					Dict							,__lowerCamelCase		:					List[str]					):





								'''simple docstring'''



								a		=			PoolFormerModel(config=__lowerCamelCase					)
								model.to(__lowerCamelCase					)
								model.eval()
								a		=			model(__lowerCamelCase					)
								a		=			a		=			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  SCREAMING_SNAKE_CASE_ (						self		:					Tuple					):





								'''simple docstring'''



								a		=			self.prepare_config_and_inputs()
								a	, a	, a		=			config_and_inputs
								a		=			{'''pixel_values''': pixel_values}
								return config, inputs_dict







@require_torch
class 				lowerCamelCase_     (	a_ ,						a_ ,						unittest.TestCase     ):
							SCREAMING_SNAKE_CASE_						     =			(PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
							SCREAMING_SNAKE_CASE_						     =			(
							    {'feature-extraction': PoolFormerModel, 'image-classification': PoolFormerForImageClassification}
							    if is_torch_available()
							    else {}
							)

							SCREAMING_SNAKE_CASE_						     =			False
							SCREAMING_SNAKE_CASE_						     =			False
							SCREAMING_SNAKE_CASE_						     =			False
							SCREAMING_SNAKE_CASE_						     =			False
							SCREAMING_SNAKE_CASE_						     =			False
							def  SCREAMING_SNAKE_CASE_ (						self		:					Any					):





								'''simple docstring'''



								a		=			PoolFormerModelTester(self					)
								a		=			PoolFormerConfigTester(self							,config_class=__lowerCamelCase					)
							def  SCREAMING_SNAKE_CASE_ (						self		:					Optional[int]					):





								'''simple docstring'''



								self.config_tester.run_common_tests()
							def  SCREAMING_SNAKE_CASE_ (						self		:					Any					):





								'''simple docstring'''



								a		=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*__lowerCamelCase					)
							@unittest.skip('''PoolFormer does not use inputs_embeds'''					)
							def  SCREAMING_SNAKE_CASE_ (						self		:					int					):





								'''simple docstring'''



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





								'''simple docstring'''



								pass
							def  SCREAMING_SNAKE_CASE_ (						self		:					str					):





								'''simple docstring'''



								def check_hidden_states_output(__lowerCamelCase		:					Optional[int]							,__lowerCamelCase		:					Union[str, Any]							,__lowerCamelCase		:					int					):
									a		=			model_class(__lowerCamelCase					)
									model.to(__lowerCamelCase					)
									model.eval()

									with torch.no_grad():
										a		=			model(**self._prepare_for_class(__lowerCamelCase							,__lowerCamelCase					)					)

									a		=			outputs.hidden_states

									a		=			self.model_tester.num_encoder_blocks
									self.assertEqual(len(__lowerCamelCase					)							,__lowerCamelCase					)

									# 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		=			self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									a		=			True
									check_hidden_states_output(__lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase					)

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

									check_hidden_states_output(__lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase					)
							def  SCREAMING_SNAKE_CASE_ (						self		:					Optional[Any]					):





								'''simple docstring'''



								if not self.model_tester.is_training:
									return

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

								for model_class in self.all_model_classes:
									if model_class in get_values(__lowerCamelCase					):
										continue
									a		=			model_class(__lowerCamelCase					)
									model.to(__lowerCamelCase					)
									model.train()
									a		=			self._prepare_for_class(__lowerCamelCase							,__lowerCamelCase							,return_labels=__lowerCamelCase					)
									a		=			model(**__lowerCamelCase					).loss
									loss.backward()
							def  SCREAMING_SNAKE_CASE_ (						self		:					Any					):





								'''simple docstring'''



								a	, a		=			self.model_tester.prepare_config_and_inputs_for_common()

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

									a		=			['''pixel_values''']
									self.assertListEqual(arg_names[:1]							,__lowerCamelCase					)




							@slow
							def  SCREAMING_SNAKE_CASE_ (						self		:					int					):





								'''simple docstring'''



								for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									a		=			PoolFormerModel.from_pretrained(__lowerCamelCase					)
									self.assertIsNotNone(__lowerCamelCase					)





def   SCREAMING_SNAKE_CASE__						(   )   ->  int:


	"""simple docstring"""



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







@require_torch
class 				lowerCamelCase_     (	unittest.TestCase     ):
							@slow
							def  SCREAMING_SNAKE_CASE_ (						self		:					Any					):





								'''simple docstring'''



								a		=			PoolFormerImageProcessor()
								a		=			PoolFormerForImageClassification.from_pretrained('''sail/poolformer_s12'''					).to(__lowerCamelCase					)

								a		=			image_processor(images=prepare_img()							,return_tensors='''pt'''					).to(__lowerCamelCase					)

								# forward pass
								with torch.no_grad():
									a		=			model(**__lowerCamelCase					)

								# verify the logits
								a		=			torch.Size((1, 10_00)					)
								self.assertEqual(outputs.logits.shape							,__lowerCamelCase					)

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













import numpy as np





def   SCREAMING_SNAKE_CASE__						(   snake_case_,  snake_case_="utf-8",  snake_case_="surrogatepass"  )   ->  List[str]:


	"""simple docstring"""



	a		=			bin(int.from_bytes(text.encode(snake_case_,  snake_case_  ),  '''big'''  )  )[2:]
	return bits.zfill(8 * ((len(snake_case_  ) + 7) // 8)  )





def   SCREAMING_SNAKE_CASE__						(   snake_case_,  snake_case_="utf-8",  snake_case_="surrogatepass"  )   ->  int:


	"""simple docstring"""



	a		=			int(snake_case_,  2  )
	return n.to_bytes((n.bit_length() + 7) // 8,  '''big'''  ).decode(snake_case_,  snake_case_  ) or "\0"





def   SCREAMING_SNAKE_CASE__						(   snake_case_,  snake_case_  )   ->  List[Any]:


	"""simple docstring"""



	if size_par + len(snake_case_  ) <= 2**size_par - (len(snake_case_  ) - 1):
		raise ValueError('''size of parity don\'t match with size of data'''  )

	a		=			[]
	a		=			[]
	a		=			[bin(snake_case_  )[2:] for x in range(1,  size_par + len(snake_case_  ) + 1  )]

	# sorted information data for the size of the output data
	a		=			[]
	# data position template + parity
	a		=			[]
	# parity bit counter
	a		=			0
	# counter position of data bits
	a		=			0

	for x in range(1,  size_par + len(snake_case_  ) + 1  ):
		# Performs a template of bit positions - who should be given,
		# and who should be parity
		if qtd_bp < size_par:
			if (np.log(snake_case_  ) / np.log(2  )).is_integer():
				data_out_gab.append('''P'''  )
				a		=			qtd_bp + 1
			else:
				data_out_gab.append('''D'''  )
		else:
			data_out_gab.append('''D'''  )

		# Sorts the data to the new output size
		if data_out_gab[-1] == "D":
			data_ord.append(data[cont_data]  )
			cont_data += 1
		else:
			data_ord.append(snake_case_  )

    # Calculates parity
	a		=			0  # parity bit counter
	for bp in range(1,  size_par + 1  ):
		# Bit counter one for a given parity
		a		=			0
		# counter to control the loop reading
		a		=			0
		for x in data_ord:
			if x is not None:
				try:
					a		=			(bin_pos[cont_loop])[-1 * (bp)]
				except IndexError:
					a		=			'''0'''
				if aux == "1" and x == "1":
					cont_bo += 1
			cont_loop += 1
		parity.append(cont_bo % 2  )

		qtd_bp += 1

	# Mount the message
	a		=			0  # parity bit counter
	for x in range(0,  size_par + len(snake_case_  )  ):
		if data_ord[x] is None:
			data_out.append(str(parity[cont_bp]  )  )
			cont_bp += 1
		else:
			data_out.append(data_ord[x]  )

	return data_out





def   SCREAMING_SNAKE_CASE__						(   snake_case_,  snake_case_  )   ->  str:


	"""simple docstring"""



	a		=			[]
	# Parity bit counter
	a		=			0
	# Counter p data bit reading
	a		=			0
	# list of parity received
	a		=			[]
	a		=			[]

	for x in range(1,  len(snake_case_  ) + 1  ):
		# Performs a template of bit positions - who should be given,
		#  and who should be parity
		if qtd_bp < size_par and (np.log(snake_case_  ) / np.log(2  )).is_integer():
			data_out_gab.append('''P'''  )
			a		=			qtd_bp + 1
		else:
			data_out_gab.append('''D'''  )

		# Sorts the data to the new output size
		if data_out_gab[-1] == "D":
			data_output.append(data[cont_data]  )
		else:
			parity_received.append(data[cont_data]  )
		cont_data += 1

	# -----------calculates the parity with the data
	a		=			[]
	a		=			[]
	a		=			[bin(snake_case_  )[2:] for x in range(1,  size_par + len(snake_case_  ) + 1  )]

	#  sorted information data for the size of the output data
	a		=			[]
	# Data position feedback + parity
	a		=			[]
	# Parity bit counter
	a		=			0
	# Counter p data bit reading
	a		=			0

	for x in range(1,  size_par + len(snake_case_  ) + 1  ):
		# Performs a template position of bits - who should be given,
		# and who should be parity
		if qtd_bp < size_par and (np.log(snake_case_  ) / np.log(2  )).is_integer():
			data_out_gab.append('''P'''  )
			a		=			qtd_bp + 1
		else:
			data_out_gab.append('''D'''  )

		# Sorts the data to the new output size
		if data_out_gab[-1] == "D":
			data_ord.append(data_output[cont_data]  )
			cont_data += 1
		else:
			data_ord.append(snake_case_  )

    # Calculates parity
	a		=			0  # parity bit counter
	for bp in range(1,  size_par + 1  ):
		# Bit counter one for a certain parity
		a		=			0
		# Counter to control loop reading
		a		=			0
		for x in data_ord:
			if x is not None:
				try:
					a		=			(bin_pos[cont_loop])[-1 * (bp)]
				except IndexError:
					a		=			'''0'''
				if aux == "1" and x == "1":
					cont_bo += 1
			cont_loop += 1
		parity.append(str(cont_bo % 2  )  )

		qtd_bp += 1

	# Mount the message
	a		=			0  # Parity bit counter
	for x in range(0,  size_par + len(snake_case_  )  ):
		if data_ord[x] is None:
			data_out.append(str(parity[cont_bp]  )  )
			cont_bp += 1
		else:
			data_out.append(data_ord[x]  )

	a		=			parity_received == parity
	return data_output, ack





