






from __future__ import annotations

import unittest

from transformers import DistilBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
	import tensorflow as tf

	from transformers.models.distilbert.modeling_tf_distilbert import (
	    TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
	    TFDistilBertForMaskedLM,
	    TFDistilBertForMultipleChoice,
	    TFDistilBertForQuestionAnswering,
	    TFDistilBertForSequenceClassification,
	    TFDistilBertForTokenClassification,
	    TFDistilBertModel,
	)

class 		lowerCAmelCase     :

					'''simple docstring'''

					def __init__(  self				:	Optional[Any]		,     __a				:	Any		,     )			->  Union[str, Any]:


												"""simple docstring"""

												__lowercase      :							List[Any]				=     parent
												__lowercase      :							Optional[int]				=     13
												__lowercase      :							Optional[int]				=     7
												__lowercase      :							Any				=     True
												__lowercase      :							Optional[int]				=     True
												__lowercase      :							Any				=     False
												__lowercase      :							str				=     True
												__lowercase      :							Optional[Any]				=     99
												__lowercase      :							Dict				=     32
												__lowercase      :							List[Any]				=     2
												__lowercase      :							int				=     4
												__lowercase      :							List[str]				=     37
												__lowercase      :							Dict				=     """gelu"""
												__lowercase      :							Any				=     0.1
												__lowercase      :							Tuple				=     0.1
												__lowercase      :							Tuple				=     512
												__lowercase      :							Optional[int]				=     16
												__lowercase      :							Any				=     2
												__lowercase      :							Optional[int]				=     0.02
												__lowercase      :							str				=     3
												__lowercase      :							Optional[int]				=     4
												__lowercase      :							List[str]				=     None



					def       lowerCAmelCase				(  self				:	int							)			->  int:


												"""simple docstring"""

												__lowercase      :							Any				=     ids_tensor([self.batch_size, self.seq_length]		,     self.vocab_size							)

												__lowercase      :							List[str]				=     None
												if self.use_input_mask:
																			__lowercase      :							Any				=     random_attention_mask([self.batch_size, self.seq_length]							)

												__lowercase      :							str				=     None
												__lowercase      :							List[Any]				=     None
												__lowercase      :							Union[str, Any]				=     None
												if self.use_labels:
																			__lowercase      :							Optional[int]				=     ids_tensor([self.batch_size]		,     self.type_sequence_label_size							)
																			__lowercase      :							Optional[int]				=     ids_tensor([self.batch_size, self.seq_length]		,     self.num_labels							)
																			__lowercase      :							Optional[int]				=     ids_tensor([self.batch_size]		,     self.num_choices							)

												__lowercase      :							List[str]				=     DistilBertConfig(
												    vocab_size=self.vocab_size		,     dim=self.hidden_size		,     n_layers=self.num_hidden_layers		,     n_heads=self.num_attention_heads		,     hidden_dim=self.intermediate_size		,     hidden_act=self.hidden_act		,     dropout=self.hidden_dropout_prob		,     attention_dropout=self.attention_probs_dropout_prob		,     max_position_embeddings=self.max_position_embeddings		,     initializer_range=self.initializer_range		,     )

												return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels



					def       lowerCAmelCase				(  self				:	Union[str, Any]		,     __a				:	Any		,     __a				:	Tuple		,     __a				:	Dict		,     __a				:	str		,     __a				:	int		,     __a				:	Union[str, Any]							)			->  List[str]:


												"""simple docstring"""

												__lowercase      :							int				=     TFDistilBertModel(config=_lowercase							)
												__lowercase      :							Optional[Any]				=     {"""input_ids""": input_ids, """attention_mask""": input_mask}

												__lowercase      :							str				=     model(_lowercase							)

												__lowercase      :							Optional[Any]				=     [input_ids, input_mask]

												__lowercase      :							Any				=     model(_lowercase							)

												self.parent.assertEqual(result.last_hidden_state.shape		,     (self.batch_size, self.seq_length, self.hidden_size)							)



					def       lowerCAmelCase				(  self				:	Union[str, Any]		,     __a				:	List[Any]		,     __a				:	str		,     __a				:	Dict		,     __a				:	List[str]		,     __a				:	Union[str, Any]		,     __a				:	List[str]							)			->  Any:


												"""simple docstring"""

												__lowercase      :							Dict				=     TFDistilBertForMaskedLM(config=_lowercase							)
												__lowercase      :							List[str]				=     {"""input_ids""": input_ids, """attention_mask""": input_mask}
												__lowercase      :							Any				=     model(_lowercase							)
												self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.seq_length, self.vocab_size)							)



					def       lowerCAmelCase				(  self				:	Tuple		,     __a				:	Optional[int]		,     __a				:	Union[str, Any]		,     __a				:	Dict		,     __a				:	Optional[Any]		,     __a				:	Any		,     __a				:	Optional[int]							)			->  Tuple:


												"""simple docstring"""

												__lowercase      :							Optional[int]				=     TFDistilBertForQuestionAnswering(config=_lowercase							)
												__lowercase      :							str				=     {
												    """input_ids""": input_ids,
												    """attention_mask""": input_mask,
												}
												__lowercase      :							Tuple				=     model(_lowercase							)
												self.parent.assertEqual(result.start_logits.shape		,     (self.batch_size, self.seq_length)							)
												self.parent.assertEqual(result.end_logits.shape		,     (self.batch_size, self.seq_length)							)



					def       lowerCAmelCase				(  self				:	Optional[Any]		,     __a				:	Optional[int]		,     __a				:	List[str]		,     __a				:	Optional[Any]		,     __a				:	str		,     __a				:	Optional[Any]		,     __a				:	Union[str, Any]							)			->  Any:


												"""simple docstring"""

												__lowercase      :							Optional[int]				=     self.num_labels
												__lowercase      :							Union[str, Any]				=     TFDistilBertForSequenceClassification(_lowercase							)
												__lowercase      :							str				=     {"""input_ids""": input_ids, """attention_mask""": input_mask}
												__lowercase      :							Tuple				=     model(_lowercase							)
												self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.num_labels)							)



					def       lowerCAmelCase				(  self				:	str		,     __a				:	List[str]		,     __a				:	Union[str, Any]		,     __a				:	Dict		,     __a				:	Any		,     __a				:	Tuple		,     __a				:	Tuple							)			->  Dict:


												"""simple docstring"""

												__lowercase      :							Optional[int]				=     self.num_choices
												__lowercase      :							List[Any]				=     TFDistilBertForMultipleChoice(_lowercase							)
												__lowercase      :							List[str]				=     tf.tile(tf.expand_dims(_lowercase		,     1							)		,     (1, self.num_choices, 1)							)
												__lowercase      :							int				=     tf.tile(tf.expand_dims(_lowercase		,     1							)		,     (1, self.num_choices, 1)							)
												__lowercase      :							int				=     {
												    """input_ids""": multiple_choice_inputs_ids,
												    """attention_mask""": multiple_choice_input_mask,
												}
												__lowercase      :							Optional[int]				=     model(_lowercase							)
												self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.num_choices)							)



					def       lowerCAmelCase				(  self				:	Any		,     __a				:	Optional[int]		,     __a				:	Optional[int]		,     __a				:	List[str]		,     __a				:	Dict		,     __a				:	Optional[int]		,     __a				:	Dict							)			->  Dict:


												"""simple docstring"""

												__lowercase      :							List[str]				=     self.num_labels
												__lowercase      :							Tuple				=     TFDistilBertForTokenClassification(_lowercase							)
												__lowercase      :							Any				=     {"""input_ids""": input_ids, """attention_mask""": input_mask}
												__lowercase      :							List[str]				=     model(_lowercase							)
												self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.seq_length, self.num_labels)							)



					def       lowerCAmelCase				(  self				:	Dict							)			->  str:


												"""simple docstring"""

												__lowercase      :							Any				=     self.prepare_config_and_inputs()
												(__lowercase)      :							List[str]				=     config_and_inputs
												__lowercase      :							Union[str, Any]				=     {"""input_ids""": input_ids, """attention_mask""": input_mask}
												return config, inputs_dict







@require_tf
class 		lowerCAmelCase     ( __snake_case      ,       __snake_case      ,       unittest.TestCase			):

					'''simple docstring'''

					_A						:			List[str]									=      (
					    (
					        TFDistilBertModel,
					        TFDistilBertForMaskedLM,
					        TFDistilBertForQuestionAnswering,
					        TFDistilBertForSequenceClassification,
					        TFDistilBertForTokenClassification,
					        TFDistilBertForMultipleChoice,
					    )
					    if is_tf_available()
					    else None
					)
					_A						:			str									=      (
					    {
					        '''feature-extraction''': TFDistilBertModel,
					        '''fill-mask''': TFDistilBertForMaskedLM,
					        '''question-answering''': TFDistilBertForQuestionAnswering,
					        '''text-classification''': TFDistilBertForSequenceClassification,
					        '''token-classification''': TFDistilBertForTokenClassification,
					        '''zero-shot''': TFDistilBertForSequenceClassification,
					    }
					    if is_tf_available()
					    else {}
					)
					_A						:			Union[str, Any]									=      False
					_A						:			Union[str, Any]									=      False



					def       lowerCAmelCase				(  self				:	Dict							)			->  Tuple:


												"""simple docstring"""

												__lowercase      :							List[str]				=     TFDistilBertModelTester(self							)
												__lowercase      :							Optional[int]				=     ConfigTester(self		,     config_class=_lowercase		,     dim=37							)



					def       lowerCAmelCase				(  self				:	List[str]							)			->  Dict:


												"""simple docstring"""

												self.config_tester.run_common_tests()



					def       lowerCAmelCase				(  self				:	List[Any]							)			->  Tuple:


												"""simple docstring"""

												__lowercase      :							Optional[int]				=     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_distilbert_model(*_lowercase							)



					def       lowerCAmelCase				(  self				:	Union[str, Any]							)			->  Any:


												"""simple docstring"""

												__lowercase      :							List[Any]				=     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_distilbert_for_masked_lm(*_lowercase							)



					def       lowerCAmelCase				(  self				:	List[str]							)			->  int:


												"""simple docstring"""

												__lowercase      :							int				=     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_distilbert_for_question_answering(*_lowercase							)



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


												"""simple docstring"""

												__lowercase      :							Dict				=     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_distilbert_for_sequence_classification(*_lowercase							)



					def       lowerCAmelCase				(  self				:	str							)			->  Union[str, Any]:


												"""simple docstring"""

												__lowercase      :							Union[str, Any]				=     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_distilbert_for_multiple_choice(*_lowercase							)



					def       lowerCAmelCase				(  self				:	int							)			->  Union[str, Any]:


												"""simple docstring"""

												__lowercase      :							Optional[Any]				=     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_distilbert_for_token_classification(*_lowercase							)



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


												"""simple docstring"""

												for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]							):
																			__lowercase      :							Any				=     TFDistilBertModel.from_pretrained(_lowercase							)
																			self.assertIsNotNone(_lowercase							)







@require_tf
class 		lowerCAmelCase     ( unittest.TestCase			):

					'''simple docstring'''

					@slow
					def       lowerCAmelCase				(  self				:	str							)			->  Optional[int]:


												"""simple docstring"""

												__lowercase      :							Union[str, Any]				=     TFDistilBertModel.from_pretrained("""distilbert-base-uncased"""							)
												__lowercase      :							Union[str, Any]				=     tf.constant([[0, 1, 2, 3, 4, 5]]							)
												__lowercase      :							Optional[Any]				=     model(_lowercase							)[0]

												__lowercase      :							List[Any]				=     [1, 6, 768]
												self.assertEqual(output.shape		,     _lowercase							)

												__lowercase      :							int				=     tf.constant(
												    [
												        [
												            [0.19261885, -0.13732955, 0.4119799],
												            [0.22150156, -0.07422661, 0.39037204],
												            [0.22756018, -0.0896414, 0.3701467],
												        ]
												    ]							)
												tf.debugging.assert_near(output[:, :3, :3]		,     _lowercase		,     atol=1E-4							)







import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor
from transformers.image_utils import PILImageResampling
from transformers.utils import logging


logging.set_verbosity_info()
lowerCamelCase : List[Any]						   =       logging.get_logger(__name__)
def       snake_case_		(     lowerCAmelCase_       :						int       ,       lowerCAmelCase_       :						str=False       ,       lowerCAmelCase_       :						Any=False      ):
							__lowercase      :							Any				=     """backbone.""" if is_semantic else """"""

							__lowercase      :							Optional[Any]				=     []
							for i in range(config.num_hidden_layers      ):
														# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
														rename_keys.append((F"{prefix}blocks.{i}.norm1.weight", F"beit.encoder.layer.{i}.layernorm_before.weight")      )
														rename_keys.append((F"{prefix}blocks.{i}.norm1.bias", F"beit.encoder.layer.{i}.layernorm_before.bias")      )
														rename_keys.append(
														    (F"{prefix}blocks.{i}.attn.proj.weight", F"beit.encoder.layer.{i}.attention.output.dense.weight")      )
														rename_keys.append(
														    (F"{prefix}blocks.{i}.attn.proj.bias", F"beit.encoder.layer.{i}.attention.output.dense.bias")      )
														rename_keys.append((F"{prefix}blocks.{i}.norm2.weight", F"beit.encoder.layer.{i}.layernorm_after.weight")      )
														rename_keys.append((F"{prefix}blocks.{i}.norm2.bias", F"beit.encoder.layer.{i}.layernorm_after.bias")      )
														rename_keys.append((F"{prefix}blocks.{i}.mlp.fc1.weight", F"beit.encoder.layer.{i}.intermediate.dense.weight")      )
														rename_keys.append((F"{prefix}blocks.{i}.mlp.fc1.bias", F"beit.encoder.layer.{i}.intermediate.dense.bias")      )
														rename_keys.append((F"{prefix}blocks.{i}.mlp.fc2.weight", F"beit.encoder.layer.{i}.output.dense.weight")      )
														rename_keys.append((F"{prefix}blocks.{i}.mlp.fc2.bias", F"beit.encoder.layer.{i}.output.dense.bias")      )

							# projection layer + position embeddings
							rename_keys.extend(
							    [
							        (F"{prefix}cls_token", """beit.embeddings.cls_token"""),
							        (F"{prefix}patch_embed.proj.weight", """beit.embeddings.patch_embeddings.projection.weight"""),
							        (F"{prefix}patch_embed.proj.bias", """beit.embeddings.patch_embeddings.projection.bias"""),
							        (F"{prefix}pos_embed", """beit.embeddings.position_embeddings"""),
							    ]      )

							if has_lm_head:
														# mask token + layernorm
														rename_keys.extend(
														    [
														        ("""mask_token""", """beit.embeddings.mask_token"""),
														        ("""norm.weight""", """layernorm.weight"""),
														        ("""norm.bias""", """layernorm.bias"""),
														    ]      )
							else:
														# layernorm + classification head
														rename_keys.extend(
														    [
														        ("""fc_norm.weight""", """beit.pooler.layernorm.weight"""),
														        ("""fc_norm.bias""", """beit.pooler.layernorm.bias"""),
														        ("""head.weight""", """classifier.weight"""),
														        ("""head.bias""", """classifier.bias"""),
														    ]      )

							return rename_keys
def       snake_case_		(     lowerCAmelCase_       :						Optional[Any]       ,       lowerCAmelCase_       :						Tuple       ,       lowerCAmelCase_       :						Any=False       ,       lowerCAmelCase_       :						List[Any]=False      ):
							for i in range(config.num_hidden_layers      ):
														__lowercase      :							Tuple				=     """backbone.""" if is_semantic else """"""
														# queries, keys and values
														__lowercase      :							int				=     state_dict.pop(F"{prefix}blocks.{i}.attn.qkv.weight"      )
														__lowercase      :							Dict				=     state_dict.pop(F"{prefix}blocks.{i}.attn.q_bias"      )
														__lowercase      :							int				=     state_dict.pop(F"{prefix}blocks.{i}.attn.v_bias"      )

														__lowercase      :							List[str]				=     in_proj_weight[
														    : config.hidden_size, :
														]
														__lowercase      :							Union[str, Any]				=     q_bias
														__lowercase      :							Any				=     in_proj_weight[
														    config.hidden_size : config.hidden_size * 2, :
														]
														__lowercase      :							Union[str, Any]				=     in_proj_weight[
														    -config.hidden_size :, :
														]
														__lowercase      :							str				=     v_bias

														# gamma_1 and gamma_2
														# we call them lambda because otherwise they are renamed when using .from_pretrained
														__lowercase      :							int				=     state_dict.pop(F"{prefix}blocks.{i}.gamma_1"      )
														__lowercase      :							str				=     state_dict.pop(F"{prefix}blocks.{i}.gamma_2"      )

														__lowercase      :							List[str]				=     gamma_a
														__lowercase      :							Optional[int]				=     gamma_a
def       snake_case_		(     lowerCAmelCase_       :						List[str]       ,       lowerCAmelCase_       :						str       ,       lowerCAmelCase_       :						int      ):
							__lowercase      :							Tuple				=     dct.pop(lowerCAmelCase_      )
							__lowercase      :							Tuple				=     val
def       snake_case_		(     ):
							__lowercase      :							Optional[int]				=     """http://images.cocodataset.org/val2017/000000039769.jpg"""
							__lowercase      :							Any				=     Image.open(requests.get(lowerCAmelCase_       ,       stream=lowerCAmelCase_      ).raw      )
							return im
@torch.no_grad()
def       snake_case_		(     lowerCAmelCase_       :						Dict       ,       lowerCAmelCase_       :						Optional[Any]       ,       lowerCAmelCase_       :						Optional[int]=False      ):
							__lowercase      :							Dict				=     False if """rvlcdip""" in checkpoint_url else True
							__lowercase      :							Tuple				=     BeitConfig(use_absolute_position_embeddings=lowerCAmelCase_       ,       use_mask_token=lowerCAmelCase_      )

							# size of the architecture
							if "large" in checkpoint_url or "dit-l" in checkpoint_url:
														__lowercase      :							Union[str, Any]				=     1024
														__lowercase      :							Optional[int]				=     4096
														__lowercase      :							List[Any]				=     24
														__lowercase      :							Dict				=     16

							# labels
							if "rvlcdip" in checkpoint_url:
														__lowercase      :							Optional[int]				=     16
														__lowercase      :							Any				=     """huggingface/label-files"""
														__lowercase      :							Union[str, Any]				=     """rvlcdip-id2label.json"""
														__lowercase      :							List[str]				=     json.load(open(hf_hub_download(lowerCAmelCase_       ,       lowerCAmelCase_       ,       repo_type="""dataset"""      )       ,       """r"""      )      )
														__lowercase      :							Optional[int]				=     {int(lowerCAmelCase_      ): v for k, v in idalabel.items()}
														__lowercase      :							Union[str, Any]				=     idalabel
														__lowercase      :							Optional[Any]				=     {v: k for k, v in idalabel.items()}

							# load state_dict of original model, remove and rename some keys
							__lowercase      :							Optional[int]				=     torch.hub.load_state_dict_from_url(lowerCAmelCase_       ,       map_location="""cpu"""      )["""model"""]

							__lowercase      :							Union[str, Any]				=     create_rename_keys(lowerCAmelCase_       ,       has_lm_head=lowerCAmelCase_      )
							for src, dest in rename_keys:
														rename_key(lowerCAmelCase_       ,       lowerCAmelCase_       ,       lowerCAmelCase_      )
							read_in_q_k_v(lowerCAmelCase_       ,       lowerCAmelCase_       ,       has_lm_head=lowerCAmelCase_      )

							# load HuggingFace model
							__lowercase      :							Dict				=     BeitForMaskedImageModeling(lowerCAmelCase_      ) if has_lm_head else BeitForImageClassification(lowerCAmelCase_      )
							model.eval()
							model.load_state_dict(lowerCAmelCase_      )

							# Check outputs on an image
							__lowercase      :							List[str]				=     BeitImageProcessor(
							    size=config.image_size       ,       resample=PILImageResampling.BILINEAR       ,       do_center_crop=lowerCAmelCase_      )
							__lowercase      :							List[str]				=     prepare_img()

							__lowercase      :							Optional[Any]				=     image_processor(images=lowerCAmelCase_       ,       return_tensors="""pt"""      )
							__lowercase      :							Optional[int]				=     encoding["""pixel_values"""]

							__lowercase      :							str				=     model(lowerCAmelCase_      )
							__lowercase      :							Tuple				=     outputs.logits

							# verify logits
							__lowercase      :							str				=     [1, 16] if """rvlcdip""" in checkpoint_url else [1, 196, 8192]
							assert logits.shape == torch.Size(lowerCAmelCase_      ), "Shape of logits not as expected"

							Path(lowerCAmelCase_      ).mkdir(exist_ok=lowerCAmelCase_      )
							print(F"Saving model to {pytorch_dump_folder_path}"      )
							model.save_pretrained(lowerCAmelCase_      )
							print(F"Saving image processor to {pytorch_dump_folder_path}"      )
							image_processor.save_pretrained(lowerCAmelCase_      )

							if push_to_hub:
														if has_lm_head:
																					__lowercase      :							Optional[Any]				=     """dit-base""" if """base""" in checkpoint_url else """dit-large"""
														else:
																					__lowercase      :							Tuple				=     """dit-base-finetuned-rvlcdip""" if """dit-b""" in checkpoint_url else """dit-large-finetuned-rvlcdip"""
														image_processor.push_to_hub(
														    repo_path_or_name=Path(lowerCAmelCase_       ,       lowerCAmelCase_      )       ,       organization="""nielsr"""       ,       commit_message="""Add image processor"""       ,       use_temp_dir=lowerCAmelCase_       ,       )
														model.push_to_hub(
														    repo_path_or_name=Path(lowerCAmelCase_       ,       lowerCAmelCase_      )       ,       organization="""nielsr"""       ,       commit_message="""Add model"""       ,       use_temp_dir=lowerCAmelCase_       ,       )


if __name__ == "__main__":
	lowerCamelCase : List[str]						   =       argparse.ArgumentParser()

	parser.add_argument(
	    '''--checkpoint_url''',
	    default='''https://layoutlm.blob.core.windows.net/dit/dit-pts/dit-base-224-p16-500k-62d53a.pth''',
	    type=str,
	    help='''URL to the original PyTorch checkpoint (.pth file).''',
	)
	parser.add_argument(
	    '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.'''
	)
	parser.add_argument(
	    '''--push_to_hub''',
	    action='''store_true''',
	)
	lowerCamelCase : List[str]						   =       parser.parse_args()
	convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)