




"""simple docstring"""





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 (
    MobileViTConfig,
    MobileViTForImageClassification,
    MobileViTForSemanticSegmentation,
    MobileViTImageProcessor,
)
from transformers.utils import logging


logging.set_verbosity_info()
A   =       logging.get_logger(__name__)

def 					_UpperCamelCase    (			UpperCamelCase							)			->			List[Any]:


			"""simple docstring"""
			__UpperCAmelCase	: List[str]		=					MobileViTConfig()

			# size of the architecture
			if "mobilevit_s" in mobilevit_name:
						__UpperCAmelCase	: Dict		=					[144, 192, 240]
						__UpperCAmelCase	: str		=					[16, 32, 64, 96, 128, 160, 640]
			elif "mobilevit_xs" in mobilevit_name:
						__UpperCAmelCase	: Union[str, Any]		=					[96, 120, 144]
						__UpperCAmelCase	: Optional[Any]		=					[16, 32, 48, 64, 80, 96, 384]
			elif "mobilevit_xxs" in mobilevit_name:
						__UpperCAmelCase	: Any		=					[64, 80, 96]
						__UpperCAmelCase	: Optional[int]		=					[16, 16, 24, 48, 64, 80, 320]
						__UpperCAmelCase	: Optional[Any]		=					0.05
						__UpperCAmelCase	: List[Any]		=					2.0

			if mobilevit_name.startswith("deeplabv3_"							):
						__UpperCAmelCase	: int		=					512
						__UpperCAmelCase	: Dict		=					16
						__UpperCAmelCase	: Dict		=					21
						__UpperCAmelCase	: List[str]		=					"pascal-voc-id2label.json"
			else:
						__UpperCAmelCase	: int		=					1000
						__UpperCAmelCase	: Dict		=					"imagenet-1k-id2label.json"

			__UpperCAmelCase	: Any		=					"huggingface/label-files"
			__UpperCAmelCase	: str		=					json.load(open(hf_hub_download(snake_case__				,       snake_case__				,       repo_type="dataset"							)				,       "r"							)							)
			__UpperCAmelCase	: List[str]		=					{int(snake_case__							): v for k, v in idalabel.items()}
			__UpperCAmelCase	: Dict		=					idalabel
			__UpperCAmelCase	: Union[str, Any]		=					{v: k for k, v in idalabel.items()}

			return config

def 					_UpperCamelCase    (			UpperCamelCase				,       UpperCamelCase=False							)			->			List[Any]:


			"""simple docstring"""
			for i in range(1				,       6							):
						if f"layer_{i}." in name:
									__UpperCAmelCase	: List[Any]		=					name.replace(f"layer_{i}."				,       f"encoder.layer.{i - 1}."							)

			if "conv_1." in name:
						__UpperCAmelCase	: List[str]		=					name.replace("conv_1."				,       "conv_stem."							)
			if ".block." in name:
						__UpperCAmelCase	: Optional[int]		=					name.replace(".block."				,       "."							)

			if "exp_1x1" in name:
						__UpperCAmelCase	: Any		=					name.replace("exp_1x1"				,       "expand_1x1"							)
			if "red_1x1" in name:
						__UpperCAmelCase	: List[str]		=					name.replace("red_1x1"				,       "reduce_1x1"							)
			if ".local_rep.conv_3x3." in name:
						__UpperCAmelCase	: Dict		=					name.replace(".local_rep.conv_3x3."				,       ".conv_kxk."							)
			if ".local_rep.conv_1x1." in name:
						__UpperCAmelCase	: Optional[Any]		=					name.replace(".local_rep.conv_1x1."				,       ".conv_1x1."							)
			if ".norm." in name:
						__UpperCAmelCase	: Union[str, Any]		=					name.replace(".norm."				,       ".normalization."							)
			if ".conv." in name:
						__UpperCAmelCase	: str		=					name.replace(".conv."				,       ".convolution."							)
			if ".conv_proj." in name:
						__UpperCAmelCase	: Optional[Any]		=					name.replace(".conv_proj."				,       ".conv_projection."							)

			for i in range(0				,       2							):
						for j in range(0				,       4							):
									if f".{i}.{j}." in name:
												__UpperCAmelCase	: List[str]		=					name.replace(f".{i}.{j}."				,       f".{i}.layer.{j}."							)

			for i in range(2				,       6							):
						for j in range(0				,       4							):
									if f".{i}.{j}." in name:
												__UpperCAmelCase	: List[str]		=					name.replace(f".{i}.{j}."				,       f".{i}."							)
												if "expand_1x1" in name:
															__UpperCAmelCase	: Optional[int]		=					name.replace("expand_1x1"				,       "downsampling_layer.expand_1x1"							)
												if "conv_3x3" in name:
															__UpperCAmelCase	: Union[str, Any]		=					name.replace("conv_3x3"				,       "downsampling_layer.conv_3x3"							)
												if "reduce_1x1" in name:
															__UpperCAmelCase	: Tuple		=					name.replace("reduce_1x1"				,       "downsampling_layer.reduce_1x1"							)

			for i in range(2				,       5							):
						if f".global_rep.{i}.weight" in name:
									__UpperCAmelCase	: Any		=					name.replace(f".global_rep.{i}.weight"				,       ".layernorm.weight"							)
						if f".global_rep.{i}.bias" in name:
									__UpperCAmelCase	: str		=					name.replace(f".global_rep.{i}.bias"				,       ".layernorm.bias"							)

			if ".global_rep." in name:
						__UpperCAmelCase	: int		=					name.replace(".global_rep."				,       ".transformer."							)
			if ".pre_norm_mha.0." in name:
						__UpperCAmelCase	: List[Any]		=					name.replace(".pre_norm_mha.0."				,       ".layernorm_before."							)
			if ".pre_norm_mha.1.out_proj." in name:
						__UpperCAmelCase	: Dict		=					name.replace(".pre_norm_mha.1.out_proj."				,       ".attention.output.dense."							)
			if ".pre_norm_ffn.0." in name:
						__UpperCAmelCase	: str		=					name.replace(".pre_norm_ffn.0."				,       ".layernorm_after."							)
			if ".pre_norm_ffn.1." in name:
						__UpperCAmelCase	: str		=					name.replace(".pre_norm_ffn.1."				,       ".intermediate.dense."							)
			if ".pre_norm_ffn.4." in name:
						__UpperCAmelCase	: Any		=					name.replace(".pre_norm_ffn.4."				,       ".output.dense."							)
			if ".transformer." in name:
						__UpperCAmelCase	: Dict		=					name.replace(".transformer."				,       ".transformer.layer."							)

			if ".aspp_layer." in name:
						__UpperCAmelCase	: List[str]		=					name.replace(".aspp_layer."				,       "."							)
			if ".aspp_pool." in name:
						__UpperCAmelCase	: Tuple		=					name.replace(".aspp_pool."				,       "."							)
			if "seg_head." in name:
						__UpperCAmelCase	: int		=					name.replace("seg_head."				,       "segmentation_head."							)
			if "segmentation_head.classifier.classifier." in name:
						__UpperCAmelCase	: str		=					name.replace("segmentation_head.classifier.classifier."				,       "segmentation_head.classifier."							)

			if "classifier.fc." in name:
						__UpperCAmelCase	: Dict		=					name.replace("classifier.fc."				,       "classifier."							)
			elif (not base_model) and ("segmentation_head." not in name):
						__UpperCAmelCase	: str		=					"mobilevit." + name

			return name

def 					_UpperCamelCase    (			UpperCamelCase				,       UpperCamelCase				,       UpperCamelCase=False							)			->			Optional[Any]:


			"""simple docstring"""
			if base_model:
						__UpperCAmelCase	: Optional[Any]		=					""
			else:
						__UpperCAmelCase	: Union[str, Any]		=					"mobilevit."

			for key in orig_state_dict.copy().keys():
						__UpperCAmelCase	: Optional[int]		=					orig_state_dict.pop(snake_case__							)

						if key[:8] == "encoder.":
									__UpperCAmelCase	: List[str]		=					key[8:]

						if "qkv" in key:
									__UpperCAmelCase	: Tuple		=					key.split("."							)
									__UpperCAmelCase	: Optional[int]		=					int(key_split[0][6:]							) - 1
									__UpperCAmelCase	: List[Any]		=					int(key_split[3]							)
									__UpperCAmelCase	: Dict		=					model.get_submodule(f"{model_prefix}encoder.layer.{layer_num}"							)
									__UpperCAmelCase	: int		=					layer.transformer.layer[transformer_num].attention.attention.all_head_size
									__UpperCAmelCase	: int		=					(
									    f"{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention."
									)
									if "weight" in key:
												__UpperCAmelCase	: str		=					val[:dim, :]
												__UpperCAmelCase	: Dict		=					val[dim : dim * 2, :]
												__UpperCAmelCase	: Optional[Any]		=					val[-dim:, :]
									else:
												__UpperCAmelCase	: str		=					val[:dim]
												__UpperCAmelCase	: str		=					val[dim : dim * 2]
												__UpperCAmelCase	: Optional[Any]		=					val[-dim:]
						else:
									__UpperCAmelCase	: Union[str, Any]		=					val

			return orig_state_dict

def 					_UpperCamelCase    (			)			->			Optional[Any]:


			"""simple docstring"""
			__UpperCAmelCase	: List[Any]		=					"http://images.cocodataset.org/val2017/000000039769.jpg"
			__UpperCAmelCase	: List[str]		=					Image.open(requests.get(snake_case__				,       stream=snake_case__							).raw							)
			return im

@torch.no_grad()
def 					_UpperCamelCase    (			UpperCamelCase				,       UpperCamelCase				,       UpperCamelCase				,       UpperCamelCase=False							)			->			Tuple:


			"""simple docstring"""
			__UpperCAmelCase	: Union[str, Any]		=					get_mobilevit_config(snake_case__							)

			# load original state_dict
			__UpperCAmelCase	: List[str]		=					torch.load(snake_case__				,       map_location="cpu"							)

			# load 🤗 model
			if mobilevit_name.startswith("deeplabv3_"							):
						__UpperCAmelCase	: List[Any]		=					MobileViTForSemanticSegmentation(snake_case__							).eval()
			else:
						__UpperCAmelCase	: str		=					MobileViTForImageClassification(snake_case__							).eval()

			__UpperCAmelCase	: Union[str, Any]		=					convert_state_dict(snake_case__				,       snake_case__							)
			model.load_state_dict(snake_case__							)

			# Check outputs on an image, prepared by MobileViTImageProcessor
			__UpperCAmelCase	: Any		=					MobileViTImageProcessor(crop_size=config.image_size				,       size=config.image_size + 32							)
			__UpperCAmelCase	: Optional[int]		=					image_processor(images=prepare_img()				,       return_tensors="pt"							)
			__UpperCAmelCase	: str		=					model(**snake_case__							)
			__UpperCAmelCase	: Dict		=					outputs.logits

			if mobilevit_name.startswith("deeplabv3_"							):
						assert logits.shape == (1, 21, 32, 32)

						if mobilevit_name == "deeplabv3_mobilevit_s":
									__UpperCAmelCase	: Optional[Any]		=					torch.tensor(
									    [
									        [[6.2065, 6.1292, 6.2070], [6.1079, 6.1254, 6.1747], [6.0042, 6.1071, 6.1034]],
									        [[-6.9253, -6.8653, -7.0398], [-7.3218, -7.3983, -7.3670], [-7.1961, -7.2482, -7.1569]],
									        [[-4.4723, -4.4348, -4.3769], [-5.3629, -5.4632, -5.4598], [-5.1587, -5.3402, -5.5059]],
									    ]							)
						elif mobilevit_name == "deeplabv3_mobilevit_xs":
									__UpperCAmelCase	: str		=					torch.tensor(
									    [
									        [[5.4449, 5.5733, 5.6314], [5.1815, 5.3930, 5.5963], [5.1656, 5.4333, 5.4853]],
									        [[-9.4423, -9.7766, -9.6714], [-9.1581, -9.5720, -9.5519], [-9.1006, -9.6458, -9.5703]],
									        [[-7.7721, -7.3716, -7.1583], [-8.4599, -8.0624, -7.7944], [-8.4172, -7.8366, -7.5025]],
									    ]							)
						elif mobilevit_name == "deeplabv3_mobilevit_xxs":
									__UpperCAmelCase	: List[Any]		=					torch.tensor(
									    [
									        [[6.9811, 6.9743, 7.3123], [7.1777, 7.1931, 7.3938], [7.5633, 7.8050, 7.8901]],
									        [[-10.5536, -10.2332, -10.2924], [-10.2336, -9.8624, -9.5964], [-10.8840, -10.8158, -10.6659]],
									        [[-3.4938, -3.0631, -2.8620], [-3.4205, -2.8135, -2.6875], [-3.4179, -2.7945, -2.8750]],
									    ]							)
						else:
									raise ValueError(f"Unknown mobilevit_name: {mobilevit_name}"							)

						assert torch.allclose(logits[0, :3, :3, :3]				,       snake_case__				,       atol=1e-4							)
			else:
						assert logits.shape == (1, 1000)

						if mobilevit_name == "mobilevit_s":
									__UpperCAmelCase	: Tuple		=					torch.tensor([-0.9866, 0.2392, -1.1241]							)
						elif mobilevit_name == "mobilevit_xs":
									__UpperCAmelCase	: Optional[Any]		=					torch.tensor([-2.4761, -0.9399, -1.9587]							)
						elif mobilevit_name == "mobilevit_xxs":
									__UpperCAmelCase	: Any		=					torch.tensor([-1.9364, -1.2327, -0.4653]							)
						else:
									raise ValueError(f"Unknown mobilevit_name: {mobilevit_name}"							)

						assert torch.allclose(logits[0, :3]				,       snake_case__				,       atol=1e-4							)

			Path(snake_case__							).mkdir(exist_ok=snake_case__							)
			print(f"Saving model {mobilevit_name} to {pytorch_dump_folder_path}"							)
			model.save_pretrained(snake_case__							)
			print(f"Saving image processor to {pytorch_dump_folder_path}"							)
			image_processor.save_pretrained(snake_case__							)

			if push_to_hub:
						__UpperCAmelCase	: Dict		=					{
						    "mobilevit_s": "mobilevit-small",
						    "mobilevit_xs": "mobilevit-x-small",
						    "mobilevit_xxs": "mobilevit-xx-small",
						    "deeplabv3_mobilevit_s": "deeplabv3-mobilevit-small",
						    "deeplabv3_mobilevit_xs": "deeplabv3-mobilevit-x-small",
						    "deeplabv3_mobilevit_xxs": "deeplabv3-mobilevit-xx-small",
						}

						print("Pushing to the hub..."							)
						__UpperCAmelCase	: Optional[int]		=					model_mapping[mobilevit_name]
						image_processor.push_to_hub(snake_case__				,       organization="apple"							)
						model.push_to_hub(snake_case__				,       organization="apple"							)


if __name__ == "__main__":
					A   =       argparse.ArgumentParser()
					# Required parameters
					parser.add_argument(
					    """--mobilevit_name""",
					    default="""mobilevit_s""",
					    type=str,
					    help=(
					        """Name of the MobileViT model you\'d like to convert. Should be one of \'mobilevit_s\', \'mobilevit_xs\',"""
					        """ \'mobilevit_xxs\', \'deeplabv3_mobilevit_s\', \'deeplabv3_mobilevit_xs\', \'deeplabv3_mobilevit_xxs\'."""
					    ),
					)
					parser.add_argument(
					    """--checkpoint_path""", required=True, type=str, help="""Path to the original state dict (.pt file)."""
					)
					parser.add_argument(
					    """--pytorch_dump_folder_path""", required=True, type=str, help="""Path to the output PyTorch model directory."""
					)
					parser.add_argument(
					    """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub."""
					)

					A   =       parser.parse_args()
					convert_movilevit_checkpoint(
					    args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub
					)










"""simple docstring"""





import argparse

import torch
from datasets import load_dataset
from donut import DonutModel

from transformers import (
    DonutImageProcessor,
    DonutProcessor,
    DonutSwinConfig,
    DonutSwinModel,
    MBartConfig,
    MBartForCausalLM,
    VisionEncoderDecoderModel,
    XLMRobertaTokenizerFast,
)

def 					_UpperCamelCase    (			UpperCamelCase							)			->			Tuple:


			"""simple docstring"""
			__UpperCAmelCase	: str		=					model.config

			__UpperCAmelCase	: int		=					DonutSwinConfig(
			    image_size=original_config.input_size				,       patch_size=4				,       depths=original_config.encoder_layer				,       num_heads=[4, 8, 16, 32]				,       window_size=original_config.window_size				,       embed_dim=128				,       )
			__UpperCAmelCase	: Union[str, Any]		=					MBartConfig(
			    is_decoder=UpperCamelCase				,       is_encoder_decoder=UpperCamelCase				,       add_cross_attention=UpperCamelCase				,       decoder_layers=original_config.decoder_layer				,       max_position_embeddings=original_config.max_position_embeddings				,       vocab_size=len(
			        model.decoder.tokenizer							)				,       scale_embedding=UpperCamelCase				,       add_final_layer_norm=UpperCamelCase				,       )

			return encoder_config, decoder_config

def 					_UpperCamelCase    (			UpperCamelCase							)			->			Union[str, Any]:


			"""simple docstring"""
			if "encoder.model" in name:
						__UpperCAmelCase	: Union[str, Any]		=					name.replace("encoder.model"				,       "encoder"							)
			if "decoder.model" in name:
						__UpperCAmelCase	: Dict		=					name.replace("decoder.model"				,       "decoder"							)
			if "patch_embed.proj" in name:
						__UpperCAmelCase	: Dict		=					name.replace("patch_embed.proj"				,       "embeddings.patch_embeddings.projection"							)
			if "patch_embed.norm" in name:
						__UpperCAmelCase	: str		=					name.replace("patch_embed.norm"				,       "embeddings.norm"							)
			if name.startswith("encoder"							):
						if "layers" in name:
									__UpperCAmelCase	: Dict		=					"encoder." + name
						if "attn.proj" in name:
									__UpperCAmelCase	: List[Any]		=					name.replace("attn.proj"				,       "attention.output.dense"							)
						if "attn" in name and "mask" not in name:
									__UpperCAmelCase	: int		=					name.replace("attn"				,       "attention.self"							)
						if "norm1" in name:
									__UpperCAmelCase	: Optional[Any]		=					name.replace("norm1"				,       "layernorm_before"							)
						if "norm2" in name:
									__UpperCAmelCase	: str		=					name.replace("norm2"				,       "layernorm_after"							)
						if "mlp.fc1" in name:
									__UpperCAmelCase	: str		=					name.replace("mlp.fc1"				,       "intermediate.dense"							)
						if "mlp.fc2" in name:
									__UpperCAmelCase	: Union[str, Any]		=					name.replace("mlp.fc2"				,       "output.dense"							)

						if name == "encoder.norm.weight":
									__UpperCAmelCase	: List[Any]		=					"encoder.layernorm.weight"
						if name == "encoder.norm.bias":
									__UpperCAmelCase	: Tuple		=					"encoder.layernorm.bias"

			return name

def 					_UpperCamelCase    (			UpperCamelCase				,       UpperCamelCase							)			->			List[Any]:


			"""simple docstring"""
			for key in orig_state_dict.copy().keys():
						__UpperCAmelCase	: Any		=					orig_state_dict.pop(UpperCamelCase							)

						if "qkv" in key:
									__UpperCAmelCase	: Any		=					key.split("."							)
									__UpperCAmelCase	: List[Any]		=					int(key_split[3]							)
									__UpperCAmelCase	: Any		=					int(key_split[5]							)
									__UpperCAmelCase	: str		=					model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size

									if "weight" in key:
												__UpperCAmelCase	: List[Any]		=					val[:dim, :]
												__UpperCAmelCase	: Union[str, Any]		=					val[dim : dim * 2, :]
												__UpperCAmelCase	: Any		=					val[-dim:, :]
									else:
												__UpperCAmelCase	: List[str]		=					val[:dim]
												__UpperCAmelCase	: List[Any]		=					val[dim : dim * 2]
												__UpperCAmelCase	: Tuple		=					val[-dim:]
						elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]:
									# HuggingFace implementation doesn't use attn_mask buffer
									# and model doesn't use final LayerNorms for the encoder
									pass
						else:
									__UpperCAmelCase	: Dict		=					val

			return orig_state_dict

def 					_UpperCamelCase    (			UpperCamelCase				,       UpperCamelCase=None				,       UpperCamelCase=False							)			->			List[str]:


			"""simple docstring"""
			# load original model
			__UpperCAmelCase	: Dict		=					DonutModel.from_pretrained(UpperCamelCase							).eval()

			# load HuggingFace model
			__UpperCAmelCase	,     __UpperCAmelCase	: List[str]		=					get_configs(UpperCamelCase							)
			__UpperCAmelCase	: Tuple		=					DonutSwinModel(UpperCamelCase							)
			__UpperCAmelCase	: Optional[Any]		=					MBartForCausalLM(UpperCamelCase							)
			__UpperCAmelCase	: int		=					VisionEncoderDecoderModel(encoder=UpperCamelCase				,       decoder=UpperCamelCase							)
			model.eval()

			__UpperCAmelCase	: Union[str, Any]		=					original_model.state_dict()
			__UpperCAmelCase	: List[str]		=					convert_state_dict(UpperCamelCase				,       UpperCamelCase							)
			model.load_state_dict(UpperCamelCase							)

			# verify results on scanned document
			__UpperCAmelCase	: List[Any]		=					load_dataset("hf-internal-testing/example-documents"							)
			__UpperCAmelCase	: Any		=					dataset["test"][0]["image"].convert("RGB"							)

			__UpperCAmelCase	: Union[str, Any]		=					XLMRobertaTokenizerFast.from_pretrained(UpperCamelCase				,       from_slow=UpperCamelCase							)
			__UpperCAmelCase	: str		=					DonutImageProcessor(
			    do_align_long_axis=original_model.config.align_long_axis				,       size=original_model.config.input_size[::-1]							)
			__UpperCAmelCase	: Union[str, Any]		=					DonutProcessor(UpperCamelCase				,       UpperCamelCase							)
			__UpperCAmelCase	: Union[str, Any]		=					processor(UpperCamelCase				,       return_tensors="pt"							).pixel_values

			if model_name == "naver-clova-ix/donut-base-finetuned-docvqa":
						__UpperCAmelCase	: List[Any]		=					"<s_docvqa><s_question>{user_input}</s_question><s_answer>"
						__UpperCAmelCase	: Any		=					"When is the coffee break?"
						__UpperCAmelCase	: Dict		=					task_prompt.replace("{user_input}"				,       UpperCamelCase							)
			elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip":
						__UpperCAmelCase	: int		=					"<s_rvlcdip>"
			elif model_name in [
			    "naver-clova-ix/donut-base-finetuned-cord-v1",
			    "naver-clova-ix/donut-base-finetuned-cord-v1-2560",
			]:
						__UpperCAmelCase	: Union[str, Any]		=					"<s_cord>"
			elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2":
						__UpperCAmelCase	: Dict		=					"s_cord-v2>"
			elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket":
						__UpperCAmelCase	: str		=					"<s_zhtrainticket>"
			elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]:
						# use a random prompt
						__UpperCAmelCase	: Tuple		=					"hello world"
			else:
						raise ValueError("Model name not supported"							)
			__UpperCAmelCase	: Dict		=					original_model.decoder.tokenizer(UpperCamelCase				,       add_special_tokens=UpperCamelCase				,       return_tensors="pt"							)[
			    "input_ids"
			]

			__UpperCAmelCase	: int		=					original_model.encoder.model.patch_embed(UpperCamelCase							)
			__UpperCAmelCase	,     __UpperCAmelCase	: Tuple		=					model.encoder.embeddings(UpperCamelCase							)
			assert torch.allclose(UpperCamelCase				,       UpperCamelCase				,       atol=1e-3							)

			# verify encoder hidden states
			__UpperCAmelCase	: int		=					original_model.encoder(UpperCamelCase							)
			__UpperCAmelCase	: Union[str, Any]		=					model.encoder(UpperCamelCase							).last_hidden_state
			assert torch.allclose(UpperCamelCase				,       UpperCamelCase				,       atol=1e-2							)

			# verify decoder hidden states
			__UpperCAmelCase	: int		=					original_model(UpperCamelCase				,       UpperCamelCase				,       UpperCamelCase							).logits
			__UpperCAmelCase	: List[str]		=					model(UpperCamelCase				,       decoder_input_ids=UpperCamelCase							).logits
			assert torch.allclose(UpperCamelCase				,       UpperCamelCase				,       atol=1e-3							)
			print("Looks ok!"							)

			if pytorch_dump_folder_path is not None:
						print(f"Saving model and processor to {pytorch_dump_folder_path}"							)
						model.save_pretrained(UpperCamelCase							)
						processor.save_pretrained(UpperCamelCase							)

			if push_to_hub:
						model.push_to_hub("nielsr/" + model_name.split("/"							)[-1]				,       commit_message="Update model"							)
						processor.push_to_hub("nielsr/" + model_name.split("/"							)[-1]				,       commit_message="Update model"							)


if __name__ == "__main__":
					A   =       argparse.ArgumentParser()
					# Required parameters
					parser.add_argument(
					    """--model_name""",
					    default="""naver-clova-ix/donut-base-finetuned-docvqa""",
					    required=False,
					    type=str,
					    help="""Name of the original model you'd like to convert.""",
					)
					parser.add_argument(
					    """--pytorch_dump_folder_path""",
					    default=None,
					    required=False,
					    type=str,
					    help="""Path to the output PyTorch model directory.""",
					)
					parser.add_argument(
					    """--push_to_hub""",
					    action="""store_true""",
					    help="""Whether or not to push the converted model and processor to the 🤗 hub.""",
					)

					A   =       parser.parse_args()
					convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)


