




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







						'''simple docstring'''





						def 	snake_case__						(						self							:					Any						):






							"""simple docstring"""






							snake_case_		   =					self.config_class(**self.inputs_dict						)
							self.parent.assertTrue(hasattr(__lowercase	,     "hidden_sizes"						)						)
							self.parent.assertTrue(hasattr(__lowercase	,     "num_encoder_blocks"						)						)







class 		UpperCAmelCase       :







						'''simple docstring'''





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






							"""simple docstring"""






							snake_case_		   =					parent
							snake_case_		   =					batch_size
							snake_case_		   =					image_size
							snake_case_		   =					num_channels
							snake_case_		   =					num_encoder_blocks
							snake_case_		   =					sr_ratios
							snake_case_		   =					depths
							snake_case_		   =					hidden_sizes
							snake_case_		   =					downsampling_rates
							snake_case_		   =					is_training
							snake_case_		   =					use_labels
							snake_case_		   =					hidden_act
							snake_case_		   =					hidden_dropout_prob
							snake_case_		   =					initializer_range
							snake_case_		   =					num_labels
							snake_case_		   =					scope






						def 	snake_case__						(						self							:					Optional[Any]						):






							"""simple docstring"""






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

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

							snake_case_		   =					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 	snake_case__						(						self							:					Optional[int]	,     __lowercase							:					Optional[Any]	,     __lowercase							:					Any	,     __lowercase							:					Optional[int]						):






							"""simple docstring"""






							snake_case_		   =					PoolFormerModel(config=__lowercase						)
							model.to(__lowercase						)
							model.eval()
							snake_case_		   =					model(__lowercase						)
							snake_case_		   =					snake_case_		   =					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 	snake_case__						(						self							:					Dict						):






							"""simple docstring"""






							snake_case_		   =					self.prepare_config_and_inputs()
							snake_case_   ,				snake_case_   ,				snake_case_		   =					config_and_inputs
							snake_case_		   =					{"pixel_values": pixel_values}
							return config, inputs_dict







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







						'''simple docstring'''





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

						lowerCAmelCase_							=       False
						lowerCAmelCase_							=       False
						lowerCAmelCase_							=       False
						lowerCAmelCase_							=       False
						lowerCAmelCase_							=       False






						def 	snake_case__						(						self							:					List[Any]						):






							"""simple docstring"""






							snake_case_		   =					PoolFormerModelTester(self						)
							snake_case_		   =					PoolFormerConfigTester(self	,     config_class=__lowercase						)






						def 	snake_case__						(						self							:					Union[str, Any]						):






							"""simple docstring"""






							self.config_tester.run_common_tests()






						def 	snake_case__						(						self							:					str						):






							"""simple docstring"""






							snake_case_		   =					self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__lowercase						)






						@unittest.skip("PoolFormer does not use inputs_embeds"						)
						def 	snake_case__						(						self							:					Any						):






							"""simple docstring"""






							pass






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






							"""simple docstring"""






							pass






						def 	snake_case__						(						self							:					List[str]						):






							"""simple docstring"""






							def check_hidden_states_output(__lowercase							:					str	,     __lowercase							:					Tuple	,     __lowercase							:					List[str]						):
								snake_case_		   =					model_class(__lowercase						)
								model.to(__lowercase						)
								model.eval()

								with torch.no_grad():
									snake_case_		   =					model(**self._prepare_for_class(__lowercase	,     __lowercase						)						)

								snake_case_		   =					outputs.hidden_states

								snake_case_		   =					self.model_tester.num_encoder_blocks
								self.assertEqual(len(__lowercase						)	,     __lowercase						)

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

							snake_case_   ,				snake_case_		   =					self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								snake_case_		   =					True
								check_hidden_states_output(__lowercase	,     __lowercase	,     __lowercase						)

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

								check_hidden_states_output(__lowercase	,     __lowercase	,     __lowercase						)






						def 	snake_case__						(						self							:					int						):






							"""simple docstring"""






							if not self.model_tester.is_training:
								return

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

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






						def 	snake_case__						(						self							:					Optional[Any]						):






							"""simple docstring"""






							snake_case_   ,				snake_case_		   =					self.model_tester.prepare_config_and_inputs_for_common()

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

								snake_case_		   =					["pixel_values"]
								self.assertListEqual(arg_names[:1]	,     __lowercase						)






						@slow
						def 	snake_case__						(						self							:					Any						):






							"""simple docstring"""






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







def 						lowerCamelCase__   (		):







	'''simple docstring'''





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






@require_torch
class 		UpperCAmelCase       (    unittest.TestCase      ):







						'''simple docstring'''





						@slow
						def 	snake_case__						(						self							:					List[str]						):






							"""simple docstring"""






							snake_case_		   =					PoolFormerImageProcessor()
							snake_case_		   =					PoolFormerForImageClassification.from_pretrained("sail/poolformer_s12"						).to(__lowercase						)

							snake_case_		   =					image_processor(images=prepare_img()	,     return_tensors="pt"						).to(__lowercase						)

							# forward pass
							with torch.no_grad():
								snake_case_		   =					model(**__lowercase						)

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

							snake_case_		   =					torch.tensor([-0.6113, 0.1685, -0.0492]						).to(__lowercase						)
							self.assertTrue(torch.allclose(outputs.logits[0, :3]	,     __lowercase	,     atol=1E-4						)						)






import argparse
import pathlib

import fairseq
import torch
from fairseq.models.roberta import RobertaModel as FairseqRobertaModel
from fairseq.modules import TransformerSentenceEncoderLayer
from packaging import version

from transformers import RobertaConfig, RobertaForMaskedLM, RobertaForSequenceClassification
from transformers.models.bert.modeling_bert import (
    BertIntermediate,
    BertLayer,
    BertOutput,
    BertSelfAttention,
    BertSelfOutput,
)
from transformers.utils import logging


if version.parse(fairseq.__version__) < version.parse("0.9.0"):
		raise Exception("requires fairseq >= 0.9.0")


logging.set_verbosity_info()
lowercase__    :					Dict					=						logging.get_logger(__name__)

lowercase__    :					Any					=						"Hello world! cécé herlolip"


def 						lowerCamelCase__   (		_A					,     _A					,     _A							):







	'''simple docstring'''





	snake_case_		   =					FairseqRobertaModel.from_pretrained(_A							)
	roberta.eval()  # disable dropout
	snake_case_		   =					roberta.model.encoder.sentence_encoder
	snake_case_		   =					RobertaConfig(
	    vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings					,     hidden_size=roberta.args.encoder_embed_dim					,     num_hidden_layers=roberta.args.encoder_layers					,     num_attention_heads=roberta.args.encoder_attention_heads					,     intermediate_size=roberta.args.encoder_ffn_embed_dim					,     max_position_embeddings=514					,     type_vocab_size=1					,     layer_norm_eps=1E-5					,     )
	if classification_head:
		snake_case_		   =					roberta.model.classification_heads["mnli"].out_proj.weight.shape[0]
	print("Our BERT config:"					,     _A							)

	snake_case_		   =					RobertaForSequenceClassification(_A							) if classification_head else RobertaForMaskedLM(_A							)
	model.eval()

	# Now let's copy all the weights.
	# Embeddings
	snake_case_		   =					roberta_sent_encoder.embed_tokens.weight
	snake_case_		   =					roberta_sent_encoder.embed_positions.weight
	snake_case_		   =					torch.zeros_like(
	    model.roberta.embeddings.token_type_embeddings.weight							)  # just zero them out b/c RoBERTa doesn't use them.
	snake_case_		   =					roberta_sent_encoder.emb_layer_norm.weight
	snake_case_		   =					roberta_sent_encoder.emb_layer_norm.bias

	for i in range(config.num_hidden_layers							):
		# Encoder: start of layer
		snake_case_		   =					model.roberta.encoder.layer[i]
		snake_case_		   =					roberta_sent_encoder.layers[i]

		# self attention
		snake_case_		   =					layer.attention.self
		assert (
		    roberta_layer.self_attn.k_proj.weight.data.shape
		    == roberta_layer.self_attn.q_proj.weight.data.shape
		    == roberta_layer.self_attn.v_proj.weight.data.shape
		    == torch.Size((config.hidden_size, config.hidden_size)							)
		)

		snake_case_		   =					roberta_layer.self_attn.q_proj.weight
		snake_case_		   =					roberta_layer.self_attn.q_proj.bias
		snake_case_		   =					roberta_layer.self_attn.k_proj.weight
		snake_case_		   =					roberta_layer.self_attn.k_proj.bias
		snake_case_		   =					roberta_layer.self_attn.v_proj.weight
		snake_case_		   =					roberta_layer.self_attn.v_proj.bias

		# self-attention output
		snake_case_		   =					layer.attention.output
		assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape
		snake_case_		   =					roberta_layer.self_attn.out_proj.weight
		snake_case_		   =					roberta_layer.self_attn.out_proj.bias
		snake_case_		   =					roberta_layer.self_attn_layer_norm.weight
		snake_case_		   =					roberta_layer.self_attn_layer_norm.bias

		# intermediate
		snake_case_		   =					layer.intermediate
		assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape
		snake_case_		   =					roberta_layer.fca.weight
		snake_case_		   =					roberta_layer.fca.bias

		# output
		snake_case_		   =					layer.output
		assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape
		snake_case_		   =					roberta_layer.fca.weight
		snake_case_		   =					roberta_layer.fca.bias
		snake_case_		   =					roberta_layer.final_layer_norm.weight
		snake_case_		   =					roberta_layer.final_layer_norm.bias
		# end of layer

	if classification_head:
		snake_case_		   =					roberta.model.classification_heads["mnli"].dense.weight
		snake_case_		   =					roberta.model.classification_heads["mnli"].dense.bias
		snake_case_		   =					roberta.model.classification_heads["mnli"].out_proj.weight
		snake_case_		   =					roberta.model.classification_heads["mnli"].out_proj.bias
	else:
		# LM Head
		snake_case_		   =					roberta.model.encoder.lm_head.dense.weight
		snake_case_		   =					roberta.model.encoder.lm_head.dense.bias
		snake_case_		   =					roberta.model.encoder.lm_head.layer_norm.weight
		snake_case_		   =					roberta.model.encoder.lm_head.layer_norm.bias
		snake_case_		   =					roberta.model.encoder.lm_head.weight
		snake_case_		   =					roberta.model.encoder.lm_head.bias

	# Let's check that we get the same results.
	snake_case_		   =					roberta.encode(_A							).unsqueeze(0							)  # batch of size 1

	snake_case_		   =					model(_A							)[0]
	if classification_head:
		snake_case_		   =					roberta.model.classification_heads["mnli"](roberta.extract_features(_A							)							)
	else:
		snake_case_		   =					roberta.model(_A							)[0]
	print(our_output.shape					,     their_output.shape							)
	snake_case_		   =					torch.max(torch.abs(our_output - their_output							)							).item()
	print(f"max_absolute_diff = {max_absolute_diff}"							)  # ~ 1e-7
	snake_case_		   =					torch.allclose(_A					,     _A					,     atol=1E-3							)
	print("Do both models output the same tensors?"					,     "🔥" if success else "💩"							)
	if not success:
		raise Exception("Something went wRoNg"							)

	pathlib.Path(_A							).mkdir(parents=_A					,     exist_ok=_A							)
	print(f"Saving model to {pytorch_dump_folder_path}"							)
	model.save_pretrained(_A							)


if __name__ == "__main__":
		lowercase__    :					int					=						argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    "--roberta_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump."
		)
		parser.add_argument(
		    "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
		)
		parser.add_argument(
		    "--classification_head", action="store_true", help="Whether to convert a final classification head."
		)
		lowercase__    :					Optional[Any]					=						parser.parse_args()
		convert_roberta_checkpoint_to_pytorch(
		    args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
		)
