



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_	:	Union[str, Any] ,lowerCamelCase_	:	Dict=False ,lowerCamelCase_	:	Optional[Any]=False ,lowerCamelCase_	:	Tuple=False):





				'''simple docstring'''

				lowerCAmelCase__  :       int				=  []
				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_	:	Optional[int] ,lowerCamelCase_	:	Dict):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Union[str, Any]):





				'''simple docstring'''

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






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





				'''simple docstring'''

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






@torch.no_grad()
def 			lowerCAmelCase__	(					lowerCamelCase_	:	Tuple ,lowerCamelCase_	:	int):





				'''simple docstring'''

				lowerCAmelCase__  :       List[str]				=  ViltConfig(image_size=384 ,patch_size=32 ,tie_word_embeddings=lowerCamelCase_)
				lowerCAmelCase__  :       Dict				=  False
				lowerCAmelCase__  :       Tuple				=  False
				lowerCAmelCase__  :       Union[str, Any]				=  False
				lowerCAmelCase__  :       int				=  False
				if "vqa" in checkpoint_url:
								lowerCAmelCase__  :       Tuple				=  True
								lowerCAmelCase__  :       Any				=  3129
								lowerCAmelCase__  :       Optional[Any]				=  '''huggingface/label-files'''
								lowerCAmelCase__  :       List[str]				=  '''vqa2-id2label.json'''
								lowerCAmelCase__  :       Union[str, Any]				=  json.load(open(hf_hub_download(lowerCamelCase_ ,lowerCamelCase_ ,repo_type='''dataset''') ,'''r'''))
								lowerCAmelCase__  :       Any				=  {int(lowerCamelCase_): v for k, v in idalabel.items()}
								lowerCAmelCase__  :       Dict				=  idalabel
								lowerCAmelCase__  :       int				=  {v: k for k, v in idalabel.items()}
								lowerCAmelCase__  :       str				=  ViltForQuestionAnswering(lowerCamelCase_)
				elif "nlvr" in checkpoint_url:
								lowerCAmelCase__  :       int				=  True
								lowerCAmelCase__  :       Dict				=  2
								lowerCAmelCase__  :       List[str]				=  {0: '''False''', 1: '''True'''}
								lowerCAmelCase__  :       Optional[Any]				=  {v: k for k, v in config.idalabel.items()}
								lowerCAmelCase__  :       int				=  3
								lowerCAmelCase__  :       List[Any]				=  ViltForImagesAndTextClassification(lowerCamelCase_)
				elif "irtr" in checkpoint_url:
								lowerCAmelCase__  :       Optional[Any]				=  True
								lowerCAmelCase__  :       int				=  ViltForImageAndTextRetrieval(lowerCamelCase_)
				elif "mlm_itm" in checkpoint_url:
								lowerCAmelCase__  :       int				=  True
								lowerCAmelCase__  :       str				=  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__  :       Any				=  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__  :       Optional[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__  :       Dict				=  model.load_state_dict(lowerCamelCase_ ,strict=lowerCamelCase_)
								assert missing_keys == ["mlm_score.decoder.bias"]
				else:
								model.load_state_dict(lowerCamelCase_)

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

				# Forward pass on example inputs (image + text)
				if nlvr_model:
								lowerCAmelCase__  :       List[Any]				=  Image.open(requests.get('''https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg''' ,stream=lowerCamelCase_).raw)
								lowerCAmelCase__  :       Dict				=  Image.open(requests.get('''https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg''' ,stream=lowerCamelCase_).raw)
								lowerCAmelCase__  :       Dict				=  (
								    '''The left image contains twice the number of dogs as the right image, and at least two dogs in total are'''
								    ''' standing.'''
								)
								lowerCAmelCase__  :       List[Any]				=  processor(lowerCamelCase_ ,lowerCamelCase_ ,return_tensors='''pt''')
								lowerCAmelCase__  :       str				=  processor(lowerCamelCase_ ,lowerCamelCase_ ,return_tensors='''pt''')
								lowerCAmelCase__  :       Optional[int]				=  model(
								    input_ids=encoding_a.input_ids ,pixel_values=encoding_a.pixel_values ,pixel_values_a=encoding_a.pixel_values ,)
				else:
								lowerCAmelCase__  :       List[str]				=  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__  :       Dict				=  '''How many cats are there?'''
								lowerCAmelCase__  :       List[Any]				=  processor(lowerCamelCase_ ,lowerCamelCase_ ,return_tensors='''pt''')
								lowerCAmelCase__  :       Tuple				=  model(**lowerCamelCase_)

				# Verify outputs
				if mlm_model:
								lowerCAmelCase__  :       Union[str, Any]				=  torch.Size([1, 11, 30522])
								lowerCAmelCase__  :       Dict				=  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[int]				=  outputs.logits[0, 4, :].argmax(-1).item()
								assert tokenizer.decode([predicted_id]) == "cats"
				elif vqa_model:
								lowerCAmelCase__  :       Any				=  torch.Size([1, 3129])
								lowerCAmelCase__  :       int				=  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__  :       Dict				=  outputs.logits.argmax(-1).item()
								assert model.config.idalabel[predicted_idx] == "2"
				elif nlvr_model:
								lowerCAmelCase__  :       Dict				=  torch.Size([1, 2])
								lowerCAmelCase__  :       List[str]				=  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       :	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.'
							)

							__snake_case       :	Tuple            =parser.parse_args()
							convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)






import io
import json
import unittest

from parameterized import parameterized

from transformers import FSMTForConditionalGeneration, FSMTTokenizer
from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device
from utils import calculate_bleu


__snake_case       :	Optional[int]            =get_tests_dir() + '/test_data/fsmt/fsmt_val_data.json'
with io.open(filename, 'r', encoding='utf-8') as f:
							__snake_case       :	Optional[Any]            =json.load(f)



@require_torch
class  lowerCamelCase__    (							unittest.TestCase):




		'''simple docstring'''



		def 	lowerCAmelCase__   (self	,__lowerCamelCase				)  ->    Dict:

						"""simple docstring"""






						return FSMTTokenizer.from_pretrained(__lowerCamelCase				)



		def 	lowerCAmelCase__   (self	,__lowerCamelCase				)  ->    Optional[int]:

						"""simple docstring"""






						lowerCAmelCase__  :       Optional[Any]				=  FSMTForConditionalGeneration.from_pretrained(__lowerCamelCase				).to(__lowerCamelCase				)
						if torch_device == "cuda":
										model.half()
						return model



		@parameterized.expand(
		    [
		        ['''en-ru''', 26.0],
		        ['''ru-en''', 22.0],
		        ['''en-de''', 22.0],
		        ['''de-en''', 29.0],
		    ]				)
		@slow
		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase				)  ->    Any:

						"""simple docstring"""






						lowerCAmelCase__  :       List[str]				=  f"""facebook/wmt19-{pair}"""
						lowerCAmelCase__  :       int				=  self.get_tokenizer(__lowerCamelCase				)
						lowerCAmelCase__  :       Optional[int]				=  self.get_model(__lowerCamelCase				)

						lowerCAmelCase__  :       List[Any]				=  bleu_data[pair]['''src''']
						lowerCAmelCase__  :       List[Any]				=  bleu_data[pair]['''tgt''']

						lowerCAmelCase__  :       List[str]				=  tokenizer(__lowerCamelCase	,return_tensors='''pt'''	,truncation=__lowerCamelCase	,padding='''longest'''				).to(__lowerCamelCase				)
						lowerCAmelCase__  :       List[str]				=  model.generate(
						    input_ids=batch.input_ids	,num_beams=8	,)
						lowerCAmelCase__  :       Tuple				=  tokenizer.batch_decode(
						    __lowerCamelCase	,skip_special_tokens=__lowerCamelCase	,clean_up_tokenization_spaces=__lowerCamelCase				)
						lowerCAmelCase__  :       Union[str, Any]				=  calculate_bleu(__lowerCamelCase	,__lowerCamelCase				)
						print(__lowerCamelCase				)
						self.assertGreaterEqual(scores['''bleu''']	,__lowerCamelCase				)

