






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()
UpperCAmelCase_ :						List[Any]      =      logging.get_logger(__name__)

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  str	,			__magic_name__					:  Dict=False	,			__magic_name__					:  Any=False	,			__magic_name__					:  Optional[int]=False					)		->			Optional[Any]:






	"""simple docstring"""



	UpperCamelCase     :Union[str, Any]          =	[]
	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    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  str	,			__magic_name__					:  List[str]					)		->			Optional[int]:






	"""simple docstring"""



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

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Union[str, Any]					)		->			Any:






	"""simple docstring"""



	UpperCamelCase     :Dict          =	["""head.weight""", """head.bias"""]
	for k in ignore_keys:
		state_dict.pop(__magic_name__	,			__magic_name__					)

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  List[str]	,			__magic_name__					:  Optional[int]	,			__magic_name__					:  List[str]					)		->			List[Any]:






	"""simple docstring"""



	UpperCamelCase     :Dict          =	dct.pop(__magic_name__					)
	UpperCamelCase     :Tuple          =	val

@torch.no_grad()
def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Dict	,			__magic_name__					:  Any					)		->			List[Any]:






	"""simple docstring"""



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

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

    # load state dict into HuggingFace model
	model.eval()
	if mlm_model:
		UpperCamelCase     ,      UpperCamelCase     :Optional[Any]          =	model.load_state_dict(__magic_name__	,			strict=__magic_name__					)
		assert missing_keys == ["mlm_score.decoder.bias"]
	else:
		model.load_state_dict(__magic_name__					)

	# Define processor
	UpperCamelCase     :List[str]          =	ViltImageProcessor(size=384					)
	UpperCamelCase     :int          =	BertTokenizer.from_pretrained("""bert-base-uncased"""					)
	UpperCamelCase     :Dict          =	ViltProcessor(__magic_name__	,			__magic_name__					)

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

	# Verify outputs
	if mlm_model:
		UpperCamelCase     :str          =	torch.Size([1, 11, 3_0522]					)
		UpperCamelCase     :List[Any]          =	torch.tensor([-12.5061, -12.5123, -12.5174]					)
		assert outputs.logits.shape == expected_shape
		assert torch.allclose(outputs.logits[0, 0, :3]	,			__magic_name__	,			atol=1E-4					)

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

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

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


if __name__ == "__main__":
	UpperCAmelCase_ :						Optional[Any]      =      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.'''
	)

	UpperCAmelCase_ :						Any      =      parser.parse_args()
	convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)








# Copyright 2021 The HuggingFace Team. 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.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


UpperCAmelCase_ :						Any      =      '''Create a default config file for Accelerate with only a few flags set.'''

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Optional[int]="no"	,			__magic_name__					:  str = default_json_config_file	,			__magic_name__					:  bool = False					)		->			str:






	"""simple docstring"""



	UpperCamelCase     :Any          =	Path(__magic_name__					)
	path.parent.mkdir(parents=__magic_name__	,			exist_ok=__magic_name__					)
	if path.exists():
		print(
		    f"""Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`."""					)
		return False
	UpperCamelCase     :Dict          =	mixed_precision.lower()
	if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
		raise ValueError(
		    f"""`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}"""					)
	UpperCamelCase     :Optional[Any]          =	{
	    """compute_environment""": """LOCAL_MACHINE""",
	    """mixed_precision""": mixed_precision,
	}
	if torch.cuda.is_available():
		UpperCamelCase     :Union[str, Any]          =	torch.cuda.device_count()
		UpperCamelCase     :List[Any]          =	num_gpus
		UpperCamelCase     :Dict          =	False
		if num_gpus > 1:
			UpperCamelCase     :Any          =	"""MULTI_GPU"""
		else:
			UpperCamelCase     :Any          =	"""NO"""
	elif is_xpu_available() and use_xpu:
		UpperCamelCase     :Optional[Any]          =	torch.xpu.device_count()
		UpperCamelCase     :Optional[int]          =	num_xpus
		UpperCamelCase     :int          =	False
		if num_xpus > 1:
			UpperCamelCase     :Union[str, Any]          =	"""MULTI_XPU"""
		else:
			UpperCamelCase     :Union[str, Any]          =	"""NO"""
	elif is_npu_available():
		UpperCamelCase     :List[Any]          =	torch.npu.device_count()
		UpperCamelCase     :Optional[Any]          =	num_npus
		UpperCamelCase     :Tuple          =	False
		if num_npus > 1:
			UpperCamelCase     :Optional[Any]          =	"""MULTI_NPU"""
		else:
			UpperCamelCase     :List[Any]          =	"""NO"""
	else:
		UpperCamelCase     :Any          =	0
		UpperCamelCase     :Optional[Any]          =	True
		UpperCamelCase     :Optional[Any]          =	1
		UpperCamelCase     :List[str]          =	"""NO"""
	UpperCamelCase     :int          =	ClusterConfig(**__magic_name__					)
	config.to_json_file(__magic_name__					)
	return path

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Dict	,			__magic_name__					:  Tuple					)		->			List[str]:






	"""simple docstring"""



	UpperCamelCase     :Dict          =	parser.add_parser("""default"""	,			parents=__magic_name__	,			help=__magic_name__	,			formatter_class=__magic_name__					)
	parser.add_argument(
	    """--config_file"""	,			default=__magic_name__	,			help=(
	        """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """
	        """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """
	        """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """
	        """with 'huggingface'."""
	    )	,			dest="""save_location"""	,			)

	parser.add_argument(
	    """--mixed_precision"""	,			choices=["""no""", """fp16""", """bf16"""]	,			type=__magic_name__	,			help="""Whether or not to use mixed precision training. """
	    """Choose between FP16 and BF16 (bfloat16) training. """
	    """BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later."""	,			default="""no"""	,			)
	parser.set_defaults(func=__magic_name__					)
	return parser

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  List[Any]					)		->			List[str]:






	"""simple docstring"""



	UpperCamelCase     :Optional[Any]          =	write_basic_config(args.mixed_precision	,			args.save_location					)
	if config_file:
		print(f"""accelerate configuration saved at {config_file}"""					)
