



"""simple docstring"""




# Copyright (c) 2021-, NVIDIA CORPORATION.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

####################################################################################################

#
# Note: If when running this conversion script you're getting an exception:
#     ModuleNotFoundError: No module named 'megatron.model.enums'
# you need to tell python where to find the clone of Megatron-LM, e.g.:
#
# cd /tmp
# git clone https://github.com/NVIDIA/Megatron-LM
# PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py ...
#
# if you already have it cloned elsewhere, simply adjust the path to the existing path
#
# If the training was done using a Megatron-LM fork, e.g.,
# https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one
# in your path, i.e., /path/to/Megatron-DeepSpeed/
#

import argparse
import os
import re
import zipfile

import torch

from transformers import AutoTokenizer, GPTaConfig






def      lowerCAmelCase__		(   lowerCamelCase_		:		Any	,lowerCamelCase_		:		List[Any]	,lowerCamelCase_		:		Dict=0):





				'''simple docstring'''

				if name is None:
								lowerCAmelCase__					:    Optional[int]												=					None
				else:
								lowerCAmelCase__					:    str												=					"." * max(0	,spaces - 2) + "# {:" + str(50 - spaces) + "s}"
								lowerCAmelCase__					:    Optional[int]												=					fmt.format(lowerCamelCase_)

				# Print and recurse (if needed).
				if isinstance(lowerCamelCase_	,lowerCamelCase_):
								if msg is not None:
												print(lowerCamelCase_)
								for k in val.keys():
												recursive_print(lowerCamelCase_	,val[k]	,spaces + 2)
				elif isinstance(lowerCamelCase_	,torch.Tensor):
								print(lowerCamelCase_	,''':'''	,val.size())
				else:
								print(lowerCamelCase_	,''':'''	,lowerCamelCase_)






def      lowerCAmelCase__		(   lowerCamelCase_		:		Optional[Any]	,lowerCamelCase_		:		Tuple	,lowerCamelCase_		:		int	,lowerCamelCase_		:		List[Any]	,lowerCamelCase_		:		Dict):





				'''simple docstring'''

				lowerCAmelCase__					:    Union[str, Any]												=					param.size()
				if checkpoint_version == 1.0:
								# version 1.0 stores [num_heads * hidden_size * num_splits, :]
								lowerCAmelCase__					:    List[str]												=					(num_heads, hidden_size, num_splits) + input_shape[1:]
								lowerCAmelCase__					:    int												=					param.view(*lowerCamelCase_)
								lowerCAmelCase__					:    str												=					param.transpose(0	,2)
								lowerCAmelCase__					:    Tuple												=					param.transpose(1	,2).contiguous()
				elif checkpoint_version >= 2.0:
								# other versions store [num_heads * num_splits * hidden_size, :]
								lowerCAmelCase__					:    Dict												=					(num_heads, num_splits, hidden_size) + input_shape[1:]
								lowerCAmelCase__					:    Any												=					param.view(*lowerCamelCase_)
								lowerCAmelCase__					:    int												=					param.transpose(0	,1).contiguous()
				lowerCAmelCase__					:    Optional[int]												=					param.view(*lowerCamelCase_)
				return param






def      lowerCAmelCase__		(   lowerCamelCase_		:		int	,lowerCamelCase_		:		str	,lowerCamelCase_		:		Dict):





				'''simple docstring'''

				lowerCAmelCase__					:    Tuple												=					{}

				# old versions did not store training args
				lowerCAmelCase__					:    Tuple												=					input_state_dict.get('''args'''	,lowerCamelCase_)
				if ds_args is not None:
								# do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint
								# from pprint import pprint
								# pprint(vars(ds_args))

								lowerCAmelCase__					:    List[Any]												=					ds_args.padded_vocab_size
								lowerCAmelCase__					:    List[Any]												=					ds_args.max_position_embeddings
								lowerCAmelCase__					:    Optional[int]												=					ds_args.hidden_size
								lowerCAmelCase__					:    Tuple												=					ds_args.num_layers
								lowerCAmelCase__					:    Any												=					ds_args.num_attention_heads
								lowerCAmelCase__					:    Union[str, Any]												=					ds_args.ffn_hidden_size
								# pprint(config)

				# The number of heads.
				lowerCAmelCase__					:    int												=					config.n_head
				# The hidden_size per head.
				lowerCAmelCase__					:    int												=					config.n_embd // config.n_head
				# Megatron-LM checkpoint version
				if "checkpoint_version" in input_state_dict.keys():
								lowerCAmelCase__					:    Optional[Any]												=					input_state_dict["checkpoint_version"]
				else:
								lowerCAmelCase__					:    Dict												=					0.0

				# The model.
				lowerCAmelCase__					:    Any												=					input_state_dict["model"]
				# The language model.
				lowerCAmelCase__					:    Union[str, Any]												=					model["language_model"]
				# The embeddings.
				lowerCAmelCase__					:    Dict												=					lm["embedding"]

				# The word embeddings.
				lowerCAmelCase__					:    List[Any]												=					embeddings["word_embeddings"]["weight"]
				# Truncate the embedding table to vocab_size rows.
				lowerCAmelCase__					:    str												=					word_embeddings[: config.vocab_size, :]
				lowerCAmelCase__					:    Union[str, Any]												=					word_embeddings

				# The position embeddings.
				lowerCAmelCase__					:    Optional[int]												=					embeddings["position_embeddings"]["weight"]
				# Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size]
				lowerCAmelCase__					:    Optional[int]												=					pos_embeddings.size(0)
				if n_positions != config.n_positions:
								raise ValueError(
								    f"""pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don't match""")
				# Store the position embeddings.
				lowerCAmelCase__					:    List[str]												=					pos_embeddings

				# The transformer.
				lowerCAmelCase__					:    Tuple												=					lm["transformer"] if "transformer" in lm.keys() else lm["encoder"]

				# The regex to extract layer names.
				lowerCAmelCase__					:    Tuple												=					re.compile(r'''layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)''')

				# The simple map of names for "automated" rules.
				lowerCAmelCase__					:    Dict												=					{
				    "attention.dense": ".attn.c_proj.",
				    "self_attention.dense": ".attn.c_proj.",
				    "mlp.dense_h_to_4h": ".mlp.c_fc.",
				    "mlp.dense_4h_to_h": ".mlp.c_proj.",
				}

				# Extract the layers.
				for key, val in transformer.items():
								# Match the name.
								lowerCAmelCase__					:    str												=					layer_re.match(lowerCamelCase_)

								# Stop if that's not a layer
								if m is None:
												break

								# The index of the layer.
								lowerCAmelCase__					:    Any												=					int(m.group(1))
								# The name of the operation.
								lowerCAmelCase__					:    Tuple												=					m.group(2)
								# Is it a weight or a bias?
								lowerCAmelCase__					:    List[str]												=					m.group(3)

								# The name of the layer.
								lowerCAmelCase__					:    Dict												=					f"""transformer.h.{layer_idx}"""

								# For layernorm(s), simply store the layer norm.
								if op_name.endswith('''layernorm'''):
												lowerCAmelCase__					:    Tuple												=					"ln_1" if op_name.startswith('''input''') else "ln_2"
												lowerCAmelCase__					:    Dict												=					val

								# Transpose the QKV matrix.
								elif (
								    op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
								) and weight_or_bias == "weight":
												# Insert a tensor of 1x1xDxD bias.
												lowerCAmelCase__					:    Dict												=					torch.tril(torch.ones((n_positions, n_positions)	,dtype=torch.floataa)).view(
												    1	,1	,lowerCamelCase_	,lowerCamelCase_)
												lowerCAmelCase__					:    int												=					causal_mask

												# Insert a "dummy" tensor for masked_bias.
												lowerCAmelCase__					:    Any												=					torch.tensor(-1E4	,dtype=torch.floataa)
												lowerCAmelCase__					:    Any												=					masked_bias

												lowerCAmelCase__					:    Union[str, Any]												=					fix_query_key_value_ordering(lowerCamelCase_	,lowerCamelCase_	,3	,lowerCamelCase_	,lowerCamelCase_)
												# Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D.
												lowerCAmelCase__					:    List[str]												=					out_val.transpose(0	,1).contiguous()
												# Store.
												lowerCAmelCase__					:    Optional[int]												=					out_val

								# Transpose the bias.
								elif (
								    op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
								) and weight_or_bias == "bias":
												lowerCAmelCase__					:    List[str]												=					fix_query_key_value_ordering(lowerCamelCase_	,lowerCamelCase_	,3	,lowerCamelCase_	,lowerCamelCase_)
												# Store. No change of shape.
												lowerCAmelCase__					:    int												=					out_val

								# Transpose the weights.
								elif weight_or_bias == "weight":
												lowerCAmelCase__					:    str												=					megatron_to_transformers[op_name]
												lowerCAmelCase__					:    Optional[Any]												=					val.transpose(0	,1)

								# Copy the bias.
								elif weight_or_bias == "bias":
												lowerCAmelCase__					:    Dict												=					megatron_to_transformers[op_name]
												lowerCAmelCase__					:    str												=					val

    # DEBUG.
				assert config.n_layer == layer_idx + 1

				# The final layernorm.
				lowerCAmelCase__					:    List[Any]												=					transformer["final_layernorm.weight"]
				lowerCAmelCase__					:    List[str]												=					transformer["final_layernorm.bias"]

				# For LM head, transformers' wants the matrix to weight embeddings.
				lowerCAmelCase__					:    int												=					word_embeddings

				# It should be done!
				return output_state_dict






def      lowerCAmelCase__		(   ):





				'''simple docstring'''

				lowerCAmelCase__					:    Dict												=					argparse.ArgumentParser()
				parser.add_argument('''--print-checkpoint-structure'''	,action='''store_true''')
				parser.add_argument(
				    '''path_to_checkpoint'''	,type=lowerCamelCase_	,help='''Path to the checkpoint file (.zip archive or direct .pt file)'''	,)
				parser.add_argument(
				    '''--config_file'''	,default=''''''	,type=lowerCamelCase_	,help='''An optional config json file describing the pre-trained model.'''	,)
				lowerCAmelCase__					:    Optional[Any]												=					parser.parse_args()

				# Extract the basename.
				lowerCAmelCase__					:    Any												=					os.path.dirname(args.path_to_checkpoint)

				# Load the model.
				# the .zip is very optional, let's keep it for backward compatibility
				print(f"""Extracting PyTorch state dictionary from {args.path_to_checkpoint}""")
				if args.path_to_checkpoint.endswith('''.zip'''):
								with zipfile.ZipFile(args.path_to_checkpoint	,'''r''') as checkpoint:
												with checkpoint.open('''release/mp_rank_00/model_optim_rng.pt''') as pytorch_dict:
																lowerCAmelCase__					:    Any												=					torch.load(lowerCamelCase_	,map_location='''cpu''')
				else:
								lowerCAmelCase__					:    List[Any]												=					torch.load(args.path_to_checkpoint	,map_location='''cpu''')

				lowerCAmelCase__					:    Any												=					input_state_dict.get('''args'''	,lowerCamelCase_)

				# Read the config, or default to the model released by NVIDIA.
				if args.config_file == "":
								if ds_args is not None:
												if ds_args.bias_gelu_fusion:
																lowerCAmelCase__					:    int												=					"gelu_fast"
												elif ds_args.openai_gelu:
																lowerCAmelCase__					:    Optional[int]												=					"gelu_new"
												else:
																lowerCAmelCase__					:    List[str]												=					"gelu"
								else:
												# in the very early days this used to be "gelu_new"
												lowerCAmelCase__					:    Optional[Any]												=					"gelu_new"

								# Spell out all parameters in case the defaults change.
								lowerCAmelCase__					:    Union[str, Any]												=					GPTaConfig(
								    vocab_size=50257	,n_positions=1024	,n_embd=1024	,n_layer=24	,n_head=16	,n_inner=4096	,activation_function=lowerCamelCase_	,resid_pdrop=0.1	,embd_pdrop=0.1	,attn_pdrop=0.1	,layer_norm_epsilon=1E-5	,initializer_range=0.02	,summary_type='''cls_index'''	,summary_use_proj=lowerCamelCase_	,summary_activation=lowerCamelCase_	,summary_proj_to_labels=lowerCamelCase_	,summary_first_dropout=0.1	,scale_attn_weights=lowerCamelCase_	,use_cache=lowerCamelCase_	,bos_token_id=50256	,eos_token_id=50256	,)
				else:
								lowerCAmelCase__					:    List[Any]												=					GPTaConfig.from_json_file(args.config_file)

				lowerCAmelCase__					:    str												=					["GPT2LMHeadModel"]

				# Convert.
				print('''Converting''')
				lowerCAmelCase__					:    List[str]												=					convert_megatron_checkpoint(lowerCamelCase_	,lowerCamelCase_	,lowerCamelCase_)

				# Print the structure of converted state dict.
				if args.print_checkpoint_structure:
								recursive_print(lowerCamelCase_	,lowerCamelCase_)

				# Add tokenizer class info to config
				# see https://github.com/huggingface/transformers/issues/13906)
				if ds_args is not None:
								lowerCAmelCase__					:    Any												=					ds_args.tokenizer_type
								if tokenizer_type == "GPT2BPETokenizer":
												lowerCAmelCase__					:    List[Any]												=					"gpt2"
								elif tokenizer_type == "PretrainedFromHF":
												lowerCAmelCase__					:    str												=					ds_args.tokenizer_name_or_path
								else:
												raise ValueError(f"""Unrecognized tokenizer_type {tokenizer_type}""")
				else:
								lowerCAmelCase__					:    Optional[int]												=					"gpt2"

				lowerCAmelCase__					:    Optional[int]												=					AutoTokenizer.from_pretrained(lowerCamelCase_)
				lowerCAmelCase__					:    Dict												=					type(lowerCamelCase_).__name__
				lowerCAmelCase__					:    Optional[Any]												=					tokenizer_class

				# Store the config to file.
				print('''Saving config''')
				config.save_pretrained(lowerCamelCase_)

				# Save tokenizer based on args
				print(f"""Adding {tokenizer_class} tokenizer files""")
				tokenizer.save_pretrained(lowerCamelCase_)

				# Store the state_dict to file.
				lowerCAmelCase__					:    List[Any]												=					os.path.join(lowerCamelCase_	,'''pytorch_model.bin''')
				print(f"""Saving checkpoint to \"{output_checkpoint_file}\"""")
				torch.save(lowerCamelCase_	,lowerCamelCase_)


####################################################################################################

if __name__ == "__main__":
							main()

####################################################################################################






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 (
    BertTokenizer,
    ViltConfig,
    ViltForImageAndTextRetrieval,
    ViltForImagesAndTextClassification,
    ViltForMaskedLM,
    ViltForQuestionAnswering,
    ViltImageProcessor,
    ViltProcessor,
)
from transformers.utils import logging


logging.set_verbosity_info()
__snake_case    :		Tuple  =logging.get_logger(__name__)






def      lowerCAmelCase__		(   lowerCamelCase_		:		Tuple	,lowerCamelCase_		:		Dict=False	,lowerCamelCase_		:		List[Any]=False	,lowerCamelCase_		:		int=False):





				'''simple docstring'''

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

				# embeddings
				rename_keys.extend(
				    [
				        # text embeddings
				        ('''text_embeddings.word_embeddings.weight''', '''vilt.embeddings.text_embeddings.word_embeddings.weight'''),
				        (
				            '''text_embeddings.position_embeddings.weight''',
				            '''vilt.embeddings.text_embeddings.position_embeddings.weight''',
				        ),
				        ('''text_embeddings.position_ids''', '''vilt.embeddings.text_embeddings.position_ids'''),
				        (
				            '''text_embeddings.token_type_embeddings.weight''',
				            '''vilt.embeddings.text_embeddings.token_type_embeddings.weight''',
				        ),
				        ('''text_embeddings.LayerNorm.weight''', '''vilt.embeddings.text_embeddings.LayerNorm.weight'''),
				        ('''text_embeddings.LayerNorm.bias''', '''vilt.embeddings.text_embeddings.LayerNorm.bias'''),
				        # patch embeddings
				        ('''transformer.cls_token''', '''vilt.embeddings.cls_token'''),
				        ('''transformer.patch_embed.proj.weight''', '''vilt.embeddings.patch_embeddings.projection.weight'''),
				        ('''transformer.patch_embed.proj.bias''', '''vilt.embeddings.patch_embeddings.projection.bias'''),
				        ('''transformer.pos_embed''', '''vilt.embeddings.position_embeddings'''),
				        # token type embeddings
				        ('''token_type_embeddings.weight''', '''vilt.embeddings.token_type_embeddings.weight'''),
				    ])

				# final layernorm + pooler
				rename_keys.extend(
				    [
				        ('''transformer.norm.weight''', '''vilt.layernorm.weight'''),
				        ('''transformer.norm.bias''', '''vilt.layernorm.bias'''),
				        ('''pooler.dense.weight''', '''vilt.pooler.dense.weight'''),
				        ('''pooler.dense.bias''', '''vilt.pooler.dense.bias'''),
				    ])

				# classifier head(s)
				if vqa_model:
								# classification head
								rename_keys.extend(
								    [
								        ('''vqa_classifier.0.weight''', '''classifier.0.weight'''),
								        ('''vqa_classifier.0.bias''', '''classifier.0.bias'''),
								        ('''vqa_classifier.1.weight''', '''classifier.1.weight'''),
								        ('''vqa_classifier.1.bias''', '''classifier.1.bias'''),
								        ('''vqa_classifier.3.weight''', '''classifier.3.weight'''),
								        ('''vqa_classifier.3.bias''', '''classifier.3.bias'''),
								    ])
				elif nlvr_model:
								# classification head
								rename_keys.extend(
								    [
								        ('''nlvr2_classifier.0.weight''', '''classifier.0.weight'''),
								        ('''nlvr2_classifier.0.bias''', '''classifier.0.bias'''),
								        ('''nlvr2_classifier.1.weight''', '''classifier.1.weight'''),
								        ('''nlvr2_classifier.1.bias''', '''classifier.1.bias'''),
								        ('''nlvr2_classifier.3.weight''', '''classifier.3.weight'''),
								        ('''nlvr2_classifier.3.bias''', '''classifier.3.bias'''),
								    ])
				else:
								pass

				return rename_keys






def      lowerCAmelCase__		(   lowerCamelCase_		:		Dict	,lowerCamelCase_		:		Optional[Any]):





				'''simple docstring'''

				for i in range(config.num_hidden_layers):
								lowerCAmelCase__					:    Optional[Any]												=					'''vilt.'''
								# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
								lowerCAmelCase__					:    Dict												=					state_dict.pop(f"""transformer.blocks.{i}.attn.qkv.weight""")
								lowerCAmelCase__					:    Tuple												=					state_dict.pop(f"""transformer.blocks.{i}.attn.qkv.bias""")
								# next, add query, keys and values (in that order) to the state dict
								lowerCAmelCase__					:    Dict												=					in_proj_weight[
								    : config.hidden_size, :
								]
								lowerCAmelCase__					:    Tuple												=					in_proj_bias[: config.hidden_size]
								lowerCAmelCase__					:    Union[str, Any]												=					in_proj_weight[
								    config.hidden_size : config.hidden_size * 2, :
								]
								lowerCAmelCase__					:    Optional[Any]												=					in_proj_bias[
								    config.hidden_size : config.hidden_size * 2
								]
								lowerCAmelCase__					:    str												=					in_proj_weight[
								    -config.hidden_size :, :
								]
								lowerCAmelCase__					:    Union[str, Any]												=					in_proj_bias[-config.hidden_size :]






def      lowerCAmelCase__		(   lowerCamelCase_		:		List[str]):





				'''simple docstring'''

				lowerCAmelCase__					:    List[Any]												=					['''head.weight''', '''head.bias''']
				for k in ignore_keys:
								state_dict.pop(lowerCamelCase_	,lowerCamelCase_)






def      lowerCAmelCase__		(   lowerCamelCase_		:		Optional[Any]	,lowerCamelCase_		:		Optional[int]	,lowerCamelCase_		:		int):





				'''simple docstring'''

				lowerCAmelCase__					:    int												=					dct.pop(lowerCamelCase_)
				lowerCAmelCase__					:    List[Any]												=					val






@torch.no_grad()
def      lowerCAmelCase__		(   lowerCamelCase_		:		int	,lowerCamelCase_		:		Union[str, Any]):





				'''simple docstring'''

				lowerCAmelCase__					:    Optional[int]												=					ViltConfig(image_size=384	,patch_size=32	,tie_word_embeddings=lowerCamelCase_)
				lowerCAmelCase__					:    Optional[Any]												=					False
				lowerCAmelCase__					:    Union[str, Any]												=					False
				lowerCAmelCase__					:    Dict												=					False
				lowerCAmelCase__					:    Any												=					False
				if "vqa" in checkpoint_url:
								lowerCAmelCase__					:    List[Any]												=					True
								lowerCAmelCase__					:    List[Any]												=					3129
								lowerCAmelCase__					:    List[Any]												=					'''huggingface/label-files'''
								lowerCAmelCase__					:    Union[str, Any]												=					'''vqa2-id2label.json'''
								lowerCAmelCase__					:    Optional[int]												=					json.load(open(hf_hub_download(lowerCamelCase_	,lowerCamelCase_	,repo_type='''dataset''')	,'''r'''))
								lowerCAmelCase__					:    Optional[Any]												=					{int(lowerCamelCase_): v for k, v in idalabel.items()}
								lowerCAmelCase__					:    Dict												=					idalabel
								lowerCAmelCase__					:    List[Any]												=					{v: k for k, v in idalabel.items()}
								lowerCAmelCase__					:    Optional[int]												=					ViltForQuestionAnswering(lowerCamelCase_)
				elif "nlvr" in checkpoint_url:
								lowerCAmelCase__					:    str												=					True
								lowerCAmelCase__					:    Optional[Any]												=					2
								lowerCAmelCase__					:    Optional[Any]												=					{0: '''False''', 1: '''True'''}
								lowerCAmelCase__					:    Union[str, Any]												=					{v: k for k, v in config.idalabel.items()}
								lowerCAmelCase__					:    int												=					3
								lowerCAmelCase__					:    int												=					ViltForImagesAndTextClassification(lowerCamelCase_)
				elif "irtr" in checkpoint_url:
								lowerCAmelCase__					:    str												=					True
								lowerCAmelCase__					:    List[str]												=					ViltForImageAndTextRetrieval(lowerCamelCase_)
				elif "mlm_itm" in checkpoint_url:
								lowerCAmelCase__					:    Any												=					True
								lowerCAmelCase__					:    int												=					ViltForMaskedLM(lowerCamelCase_)
				else:
								raise ValueError('''Unknown model type''')

				# load state_dict of original model, remove and rename some keys
				lowerCAmelCase__					:    Tuple												=					torch.hub.load_state_dict_from_url(lowerCamelCase_	,map_location='''cpu''')['''state_dict''']
				lowerCAmelCase__					:    Tuple												=					create_rename_keys(lowerCamelCase_	,lowerCamelCase_	,lowerCamelCase_	,lowerCamelCase_)
				for src, dest in rename_keys:
								rename_key(lowerCamelCase_	,lowerCamelCase_	,lowerCamelCase_)
				read_in_q_k_v(lowerCamelCase_	,lowerCamelCase_)
				if mlm_model or irtr_model:
								lowerCAmelCase__					:    int												=					['''itm_score.fc.weight''', '''itm_score.fc.bias''']
								for k in ignore_keys:
												state_dict.pop(lowerCamelCase_	,lowerCamelCase_)

    # load state dict into HuggingFace model
				model.eval()
				if mlm_model:
								lowerCAmelCase__						,		lowerCAmelCase__					:    str												=					model.load_state_dict(lowerCamelCase_	,strict=lowerCamelCase_)
								assert missing_keys == ["mlm_score.decoder.bias"]
				else:
								model.load_state_dict(lowerCamelCase_)

				# Define processor
				lowerCAmelCase__					:    List[str]												=					ViltImageProcessor(size=384)
				lowerCAmelCase__					:    Tuple												=					BertTokenizer.from_pretrained('''bert-base-uncased''')
				lowerCAmelCase__					:    Union[str, Any]												=					ViltProcessor(lowerCamelCase_	,lowerCamelCase_)

				# Forward pass on example inputs (image + text)
				if nlvr_model:
								lowerCAmelCase__					:    int												=					Image.open(requests.get('''https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg'''	,stream=lowerCamelCase_).raw)
								lowerCAmelCase__					:    Union[str, Any]												=					Image.open(requests.get('''https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg'''	,stream=lowerCamelCase_).raw)
								lowerCAmelCase__					:    Union[str, Any]												=					(
								    '''The left image contains twice the number of dogs as the right image, and at least two dogs in total are'''
								    ''' standing.'''
								)
								lowerCAmelCase__					:    Optional[int]												=					processor(lowerCamelCase_	,lowerCamelCase_	,return_tensors='''pt''')
								lowerCAmelCase__					:    Tuple												=					processor(lowerCamelCase_	,lowerCamelCase_	,return_tensors='''pt''')
								lowerCAmelCase__					:    Union[str, Any]												=					model(
								    input_ids=encoding_a.input_ids	,pixel_values=encoding_a.pixel_values	,pixel_values_a=encoding_a.pixel_values	,)
				else:
								lowerCAmelCase__					:    Dict												=					Image.open(requests.get('''http://images.cocodataset.org/val2017/000000039769.jpg'''	,stream=lowerCamelCase_).raw)
								if mlm_model:
												lowerCAmelCase__					:    int												=					'''a bunch of [MASK] laying on a [MASK].'''
								else:
												lowerCAmelCase__					:    Optional[int]												=					'''How many cats are there?'''
								lowerCAmelCase__					:    Optional[int]												=					processor(lowerCamelCase_	,lowerCamelCase_	,return_tensors='''pt''')
								lowerCAmelCase__					:    Any												=					model(**lowerCamelCase_)

				# Verify outputs
				if mlm_model:
								lowerCAmelCase__					:    Dict												=					torch.Size([1, 11, 30522])
								lowerCAmelCase__					:    int												=					torch.tensor([-12.5061, -12.5123, -12.5174])
								assert outputs.logits.shape == expected_shape
								assert torch.allclose(outputs.logits[0, 0, :3]	,lowerCamelCase_	,atol=1E-4)

								# verify masked token prediction equals "cats"
								lowerCAmelCase__					:    Optional[Any]												=					outputs.logits[0, 4, :].argmax(-1).item()
								assert tokenizer.decode([predicted_id]) == "cats"
				elif vqa_model:
								lowerCAmelCase__					:    List[Any]												=					torch.Size([1, 3129])
								lowerCAmelCase__					:    str												=					torch.tensor([-15.9495, -18.1472, -10.3041])
								assert torch.allclose(outputs.logits[0, :3]	,lowerCamelCase_	,atol=1E-4)
								assert outputs.logits.shape == expected_shape
								assert torch.allclose(outputs.logits[0, 0, :3]	,lowerCamelCase_	,atol=1E-4)

								# verify vqa prediction equals "2"
								lowerCAmelCase__					:    List[Any]												=					outputs.logits.argmax(-1).item()
								assert model.config.idalabel[predicted_idx] == "2"
				elif nlvr_model:
								lowerCAmelCase__					:    Union[str, Any]												=					torch.Size([1, 2])
								lowerCAmelCase__					:    Dict												=					torch.tensor([-2.8721, 2.1291])
								assert torch.allclose(outputs.logits[0, :3]	,lowerCamelCase_	,atol=1E-4)
								assert outputs.logits.shape == expected_shape

				Path(lowerCamelCase_).mkdir(exist_ok=lowerCamelCase_)
				print(f"""Saving model and processor to {pytorch_dump_folder_path}""")
				model.save_pretrained(lowerCamelCase_)
				processor.save_pretrained(lowerCamelCase_)


if __name__ == "__main__":
							__snake_case    :		Dict  =argparse.ArgumentParser()
							# Required parameters
							parser.add_argument(
							    '--checkpoint_url',
							    default='https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt',
							    type=str,
							    help='URL of the checkpoint you\'d like to convert.',
							)
							parser.add_argument(
							    '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
							)

							__snake_case    :		Union[str, Any]  =parser.parse_args()
							convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)

