





import logging
import math
import os
from dataclasses import dataclass, field
from glob import glob
from typing import Optional

from torch.utils.data import ConcatDataset

import transformers
from transformers import (
    CONFIG_MAPPING,
    MODEL_WITH_LM_HEAD_MAPPING,
    AutoConfig,
    AutoModelWithLMHead,
    AutoTokenizer,
    DataCollatorForLanguageModeling,
    DataCollatorForPermutationLanguageModeling,
    DataCollatorForWholeWordMask,
    HfArgumentParser,
    LineByLineTextDataset,
    LineByLineWithRefDataset,
    PreTrainedTokenizer,
    TextDataset,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


UpperCAmelCase_  							=				logging.getLogger(__name__)


UpperCAmelCase_  							=				list(MODEL_WITH_LM_HEAD_MAPPING.keys())
UpperCAmelCase_  							=				tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)






@dataclass
class 					lowercase__ :

   '''simple docstring'''


   a		:							Optional[str]     	=	field(
       default=__lowerCamelCase    ,       metadata={
           "help": (
               "The model checkpoint for weights initialization. Leave None if you want to train a model from"
               " scratch."
           )
       }    ,       )
   a		:							Optional[str]     	=	field(
       default=__lowerCamelCase    ,       metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(__lowerCamelCase       )}    ,       )
   a		:							Optional[str]     	=	field(
       default=__lowerCamelCase    ,       metadata={"help": "Pretrained config name or path if not the same as model_name"}       )
   a		:							Optional[str]     	=	field(
       default=__lowerCamelCase    ,       metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}       )
   a		:							Optional[str]     	=	field(
       default=__lowerCamelCase    ,       metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}    ,       )






@dataclass
class 					lowercase__ :

   '''simple docstring'''


   a		:							Optional[str]     	=	field(
       default=__lowerCamelCase    ,       metadata={"help": "The input training data file (a text file)."}       )
   a		:							Optional[str]     	=	field(
       default=__lowerCamelCase    ,       metadata={
           "help": (
               "The input training data files (multiple files in glob format). "
               "Very often splitting large files to smaller files can prevent tokenizer going out of memory"
           )
       }    ,       )
   a		:							Optional[str]     	=	field(
       default=__lowerCamelCase    ,       metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."}    ,       )
   a		:							Optional[str]     	=	field(
       default=__lowerCamelCase    ,       metadata={"help": "An optional input train ref data file for whole word mask in Chinese."}    ,       )
   a		:							Optional[str]     	=	field(
       default=__lowerCamelCase    ,       metadata={"help": "An optional input eval ref data file for whole word mask in Chinese."}    ,       )
   a		:							bool     	=	field(
       default=__lowerCamelCase    ,       metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."}    ,       )

   a		:							bool     	=	field(
       default=__lowerCamelCase    ,       metadata={"help": "Train with masked-language modeling loss instead of language modeling."}       )
   a		:							bool     	=	field(default=__lowerCamelCase    ,       metadata={"help": "Whether ot not to use whole word mask."}       )
   a		:							float     	=	field(
       default=0.1_5    ,       metadata={"help": "Ratio of tokens to mask for masked language modeling loss"}       )
   a		:							float     	=	field(
       default=1 / 6    ,       metadata={
           "help": (
               "Ratio of length of a span of masked tokens to surrounding context length for permutation language"
               " modeling."
           )
       }    ,       )
   a		:							int     	=	field(
       default=5    ,       metadata={"help": "Maximum length of a span of masked tokens for permutation language modeling."}       )

   a		:							int     	=	field(
       default=-1    ,       metadata={
           "help": (
               "Optional input sequence length after tokenization."
               "The training dataset will be truncated in block of this size for training."
               "Default to the model max input length for single sentence inputs (take into account special tokens)."
           )
       }    ,       )
   a		:							bool     	=	field(
       default=__lowerCamelCase    ,       metadata={"help": "Overwrite the cached training and evaluation sets"}       )




def 	lowerCAmelCase_					(						__UpperCAmelCase:    DataTrainingArguments	,     __UpperCAmelCase:    PreTrainedTokenizer	,     __UpperCAmelCase:    bool = False	,     __UpperCAmelCase:    Optional[str] = None	,     )   ->			Tuple:
    def _dataset(__UpperCAmelCase:    Union[str, Any]	,     __UpperCAmelCase:    Any=None   ):
        if args.line_by_line:
            if ref_path is not None:
                if not args.whole_word_mask or not args.mlm:
                    raise ValueError('''You need to set world whole masking and mlm to True for Chinese Whole Word Mask'''   )
                return LineByLineWithRefDataset(
                    tokenizer=__UpperCAmelCase	,     file_path=__UpperCAmelCase	,     block_size=args.block_size	,     ref_path=__UpperCAmelCase	,     )

            return LineByLineTextDataset(tokenizer=__UpperCAmelCase	,     file_path=__UpperCAmelCase	,     block_size=args.block_size   )
        else:
            return TextDataset(
                tokenizer=__UpperCAmelCase	,     file_path=__UpperCAmelCase	,     block_size=args.block_size	,     overwrite_cache=args.overwrite_cache	,     cache_dir=__UpperCAmelCase	,     )

    if evaluate:
        return _dataset(args.eval_data_file	,     args.eval_ref_file   )
    elif args.train_data_files:
        return ConcatDataset([_dataset(__UpperCAmelCase   ) for f in glob(args.train_data_files   )]   )
    else:
        return _dataset(args.train_data_file	,     args.train_ref_file   )




def 	lowerCAmelCase_					(						)   ->			Union[str, Any]:
    # See all possible arguments in src/transformers/training_args.py
    # or by passing the --help flag to this script.
    # We now keep distinct sets of args, for a cleaner separation of concerns.

    UpperCamelCase__							:       int      =   HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)   )
    UpperCamelCase__     ,UpperCamelCase__     ,UpperCamelCase__							:       Tuple      =   parser.parse_args_into_dataclasses()

    if data_args.eval_data_file is None and training_args.do_eval:
        raise ValueError(
            '''Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file '''
            '''or remove the --do_eval argument.'''   )
    if (
        os.path.exists(training_args.output_dir   )
        and os.listdir(training_args.output_dir   )
        and training_args.do_train
        and not training_args.overwrite_output_dir
    ):
        raise ValueError(
            f"Output directory ({training_args.output_dir}) already exists and is not empty. Use"
            ''' --overwrite_output_dir to overcome.'''   )

    # Setup logging
    logging.basicConfig(
        format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''	,     datefmt='''%m/%d/%Y %H:%M:%S'''	,     level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN	,     )
    logger.warning(
        '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s'''	,     training_args.local_rank	,     training_args.device	,     training_args.n_gpu	,     bool(training_args.local_rank != -1   )	,     training_args.fpaa	,     )
    # Set the verbosity to info of the Transformers logger (on main process only):
    if is_main_process(training_args.local_rank   ):
        transformers.utils.logging.set_verbosity_info()
        transformers.utils.logging.enable_default_handler()
        transformers.utils.logging.enable_explicit_format()
    logger.info('''Training/evaluation parameters %s'''	,     __UpperCAmelCase   )

    # Set seed
    set_seed(training_args.seed   )

    # Load pretrained model and tokenizer
    #
    # Distributed training:
    # The .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.

    if model_args.config_name:
        UpperCamelCase__							:       Dict      =   AutoConfig.from_pretrained(model_args.config_name	,     cache_dir=model_args.cache_dir   )
    elif model_args.model_name_or_path:
        UpperCamelCase__							:       List[str]      =   AutoConfig.from_pretrained(model_args.model_name_or_path	,     cache_dir=model_args.cache_dir   )
    else:
        UpperCamelCase__							:       str      =   CONFIG_MAPPING[model_args.model_type]()
        logger.warning('''You are instantiating a new config instance from scratch.'''   )

    if model_args.tokenizer_name:
        UpperCamelCase__							:       List[Any]      =   AutoTokenizer.from_pretrained(model_args.tokenizer_name	,     cache_dir=model_args.cache_dir   )
    elif model_args.model_name_or_path:
        UpperCamelCase__							:       Any      =   AutoTokenizer.from_pretrained(model_args.model_name_or_path	,     cache_dir=model_args.cache_dir   )
    else:
        raise ValueError(
            '''You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another'''
            ''' script, save it,and load it from here, using --tokenizer_name'''   )

    if model_args.model_name_or_path:
        UpperCamelCase__							:       Optional[int]      =   AutoModelWithLMHead.from_pretrained(
            model_args.model_name_or_path	,     from_tf=bool('''.ckpt''' in model_args.model_name_or_path   )	,     config=__UpperCAmelCase	,     cache_dir=model_args.cache_dir	,     )
    else:
        logger.info('''Training new model from scratch'''   )
        UpperCamelCase__							:       str      =   AutoModelWithLMHead.from_config(__UpperCAmelCase   )

    model.resize_token_embeddings(len(__UpperCAmelCase   )   )

    if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm:
        raise ValueError(
            '''BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the'''
            '''--mlm flag (masked language modeling).'''   )

    if data_args.block_size <= 0:
        UpperCamelCase__							:       str      =   tokenizer.max_len
        # Our input block size will be the max possible for the model
    else:
        UpperCamelCase__							:       List[Any]      =   min(data_args.block_size	,     tokenizer.max_len   )

    # Get datasets

    UpperCamelCase__							:       List[str]      =   (
        get_dataset(__UpperCAmelCase	,     tokenizer=__UpperCAmelCase	,     cache_dir=model_args.cache_dir   ) if training_args.do_train else None
    )
    UpperCamelCase__							:       Tuple      =   (
        get_dataset(__UpperCAmelCase	,     tokenizer=__UpperCAmelCase	,     evaluate=__UpperCAmelCase	,     cache_dir=model_args.cache_dir   )
        if training_args.do_eval
        else None
    )
    if config.model_type == "xlnet":
        UpperCamelCase__							:       Any      =   DataCollatorForPermutationLanguageModeling(
            tokenizer=__UpperCAmelCase	,     plm_probability=data_args.plm_probability	,     max_span_length=data_args.max_span_length	,     )
    else:
        if data_args.mlm and data_args.whole_word_mask:
            UpperCamelCase__							:       int      =   DataCollatorForWholeWordMask(
                tokenizer=__UpperCAmelCase	,     mlm_probability=data_args.mlm_probability   )
        else:
            UpperCamelCase__							:       Optional[int]      =   DataCollatorForLanguageModeling(
                tokenizer=__UpperCAmelCase	,     mlm=data_args.mlm	,     mlm_probability=data_args.mlm_probability   )

    # Initialize our Trainer
    UpperCamelCase__							:       List[str]      =   Trainer(
        model=__UpperCAmelCase	,     args=__UpperCAmelCase	,     data_collator=__UpperCAmelCase	,     train_dataset=__UpperCAmelCase	,     eval_dataset=__UpperCAmelCase	,     prediction_loss_only=__UpperCAmelCase	,     )

    # Training
    if training_args.do_train:
        UpperCamelCase__							:       Optional[Any]      =   (
            model_args.model_name_or_path
            if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path   )
            else None
        )
        trainer.train(model_path=__UpperCAmelCase   )
        trainer.save_model()
        # For convenience, we also re-save the tokenizer to the same directory,
        # so that you can share your model easily on huggingface.co/models =)
        if trainer.is_world_master():
            tokenizer.save_pretrained(training_args.output_dir   )

    # Evaluation
    UpperCamelCase__							:       Optional[int]      =   {}
    if training_args.do_eval:
        logger.info('''*** Evaluate ***'''   )

        UpperCamelCase__							:       List[Any]      =   trainer.evaluate()

        UpperCamelCase__							:       int      =   math.exp(eval_output['''eval_loss''']   )
        UpperCamelCase__							:       Tuple      =   {'''perplexity''': perplexity}

        UpperCamelCase__							:       Dict      =   os.path.join(training_args.output_dir	,     '''eval_results_lm.txt'''   )
        if trainer.is_world_master():
            with open(__UpperCAmelCase	,     '''w'''   ) as writer:
                logger.info('''***** Eval results *****'''   )
                for key in sorted(result.keys()   ):
                    logger.info('''  %s = %s'''	,     __UpperCAmelCase	,     str(result[key]   )   )
                    writer.write('''%s = %s\n''' % (key, str(result[key]   ))   )

        results.update(__UpperCAmelCase   )

    return results




def 	lowerCAmelCase_					(						__UpperCAmelCase:    Dict   )   ->			Optional[Any]:
    # For xla_spawn (TPUs)
    main()


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()
UpperCAmelCase_  							=				logging.get_logger(__name__)




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




def 	lowerCAmelCase_					(						__UpperCAmelCase:    List[Any]   )   ->			Any:
    UpperCamelCase__							:       int      =   ['''head.weight''', '''head.bias''']
    for k in ignore_keys:
        state_dict.pop(__UpperCAmelCase	,     __UpperCAmelCase   )




def 	lowerCAmelCase_					(						__UpperCAmelCase:    Any	,     __UpperCAmelCase:    Dict	,     __UpperCAmelCase:    int   )   ->			List[str]:
    UpperCamelCase__							:       str      =   dct.pop(__UpperCAmelCase   )
    UpperCamelCase__							:       Optional[int]      =   val




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

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

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

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

    # Forward pass on example inputs (image + text)
    if nlvr_model:
        UpperCamelCase__							:       Optional[int]      =   Image.open(requests.get('''https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg'''	,     stream=__UpperCAmelCase   ).raw   )
        UpperCamelCase__							:       Union[str, Any]      =   Image.open(requests.get('''https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg'''	,     stream=__UpperCAmelCase   ).raw   )
        UpperCamelCase__							:       Dict      =   (
            '''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(__UpperCAmelCase	,     __UpperCAmelCase	,     return_tensors='''pt'''   )
        UpperCamelCase__							:       Optional[Any]      =   processor(__UpperCAmelCase	,     __UpperCAmelCase	,     return_tensors='''pt'''   )
        UpperCamelCase__							:       Union[str, Any]      =   model(
            input_ids=encoding_a.input_ids	,     pixel_values=encoding_a.pixel_values	,     pixel_values_a=encoding_a.pixel_values	,     )
    else:
        UpperCamelCase__							:       Union[str, Any]      =   Image.open(requests.get('''http://images.cocodataset.org/val2017/000000039769.jpg'''	,     stream=__UpperCAmelCase   ).raw   )
        if mlm_model:
            UpperCamelCase__							:       int      =   '''a bunch of [MASK] laying on a [MASK].'''
        else:
            UpperCamelCase__							:       Optional[Any]      =   '''How many cats are there?'''
        UpperCamelCase__							:       List[Any]      =   processor(__UpperCAmelCase	,     __UpperCAmelCase	,     return_tensors='''pt'''   )
        UpperCamelCase__							:       Union[str, Any]      =   model(**__UpperCAmelCase   )

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

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

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

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


if __name__ == "__main__":
  UpperCAmelCase_  							=				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_  							=				parser.parse_args()
  convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)

