



'''simple docstring'''






import logging

from transformers.configuration_utils import PretrainedConfig


A_							: Union[str, Any]						 =	logging.getLogger(__name__)



class 							lowercase       (  _lowerCamelCase				):


 """simple docstring"""


 UpperCAmelCase							=  """masked_bert"""







 def __init__(							self  ,a_=30_522  ,a_=768  ,a_=12  ,a_=12  ,a_=3_072  ,a_="gelu"  ,a_=0.1  ,a_=0.1  ,a_=512  ,a_=2  ,a_=0.02  ,a_=1E-1_2  ,a_=0  ,a_="topK"  ,a_="constant"  ,a_=0.0  ,**a_  ,)		->   Optional[int]:
        super().__init__(pad_token_id=a_  ,**a_							)

        _UpperCAmelCase  :						Dict			     = vocab_size
        _UpperCAmelCase  :						Optional[int]			     = hidden_size
        _UpperCAmelCase  :						Any			     = num_hidden_layers
        _UpperCAmelCase  :						Optional[Any]			     = num_attention_heads
        _UpperCAmelCase  :						Tuple			     = hidden_act
        _UpperCAmelCase  :						int			     = intermediate_size
        _UpperCAmelCase  :						Optional[Any]			     = hidden_dropout_prob
        _UpperCAmelCase  :						str			     = attention_probs_dropout_prob
        _UpperCAmelCase  :						str			     = max_position_embeddings
        _UpperCAmelCase  :						Optional[Any]			     = type_vocab_size
        _UpperCAmelCase  :						str			     = initializer_range
        _UpperCAmelCase  :						Optional[int]			     = layer_norm_eps
        _UpperCAmelCase  :						int			     = pruning_method
        _UpperCAmelCase  :						str			     = mask_init
        _UpperCAmelCase  :						List[str]			     = mask_scale








'''simple docstring'''






import argparse
from collections import OrderedDict
from pathlib import Path

import torch

from transformers import (
    VisualBertConfig,
    VisualBertForMultipleChoice,
    VisualBertForPreTraining,
    VisualBertForQuestionAnswering,
    VisualBertForVisualReasoning,
)
from transformers.utils import logging


logging.set_verbosity_info()
A_							: Union[str, Any]						 =	logging.get_logger(__name__)

A_							: Union[str, Any]						 =	[
    ("""bert.bert""", """visual_bert"""),
    ("""bert.cls""", """cls"""),
    ("""bert.classifier""", """cls"""),
    ("""token_type_embeddings_visual""", """visual_token_type_embeddings"""),
    ("""position_embeddings_visual""", """visual_position_embeddings"""),
    ("""projection""", """visual_projection"""),
]

A_							: int						 =	[
    """nlvr2_coco_pre_trained.th""",
    """nlvr2_fine_tuned.th""",
    """nlvr2_pre_trained.th""",
    """vcr_coco_pre_train.th""",
    """vcr_fine_tune.th""",
    """vcr_pre_train.th""",
    """vqa_coco_pre_trained.th""",
    """vqa_fine_tuned.th""",
    """vqa_pre_trained.th""",
]




def     snake_case_					(     lowerCAmelCase_		)->		Optional[int]:





       '''simple docstring'''


       _UpperCAmelCase  :						Dict			     = torch.load(lowerCAmelCase_       ,   map_location="""cpu"""		)
       return sd




def     snake_case_					(     lowerCAmelCase_       ,   lowerCAmelCase_       ,   lowerCAmelCase_=rename_keys_prefix		)->		Optional[Any]:





       '''simple docstring'''


       _UpperCAmelCase  :						Any			     = OrderedDict()
       _UpperCAmelCase  :						Any			     = torch.arange(config.max_position_embeddings		).expand((1, -1)		)
       # detector_d = OrderedDict()
       for key in d:
              if "detector" in key:
                     # detector_d[key.replace('detector.','')] = d[key]
                     continue
              _UpperCAmelCase  :						Dict			     = key
              for name_pair in rename_keys_prefix:
                     _UpperCAmelCase  :						str			     = new_key.replace(name_pair[0]       ,   name_pair[1]		)
              _UpperCAmelCase  :						str			     = d[key]
              if key == "bert.cls.predictions.decoder.weight":
                     # Old bert code didn't have `decoder.bias`, but was added separately
                     _UpperCAmelCase  :						int			     = new_d["""cls.predictions.bias"""]
       return new_d




@torch.no_grad()
def     snake_case_					(     lowerCAmelCase_       ,   lowerCAmelCase_		)->		Any:





       '''simple docstring'''


       assert (
           checkpoint_path.split("""/"""		)[-1] in ACCEPTABLE_CHECKPOINTS
       ), F'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.'''

       # Get Config
       if "pre" in checkpoint_path:
              _UpperCAmelCase  :						Optional[int]			     = """pretraining"""
              if "vcr" in checkpoint_path:
                     _UpperCAmelCase  :						Optional[int]			     = {"""visual_embedding_dim""": 512}
              elif "vqa_advanced" in checkpoint_path:
                     _UpperCAmelCase  :						List[Any]			     = {"""visual_embedding_dim""": 2048}
              elif "vqa" in checkpoint_path:
                     _UpperCAmelCase  :						Any			     = {"""visual_embedding_dim""": 2048}
              elif "nlvr" in checkpoint_path:
                     _UpperCAmelCase  :						Any			     = {"""visual_embedding_dim""": 1024}
              else:
                     raise NotImplementedError(F'''No implementation found for `{checkpoint_path}`.'''		)
       else:
              if "vcr" in checkpoint_path:
                     _UpperCAmelCase  :						str			     = {"""visual_embedding_dim""": 512}
                     _UpperCAmelCase  :						int			     = """multichoice"""
              elif "vqa_advanced" in checkpoint_path:
                     _UpperCAmelCase  :						str			     = {"""visual_embedding_dim""": 2048}
                     _UpperCAmelCase  :						int			     = """vqa_advanced"""
              elif "vqa" in checkpoint_path:
                     _UpperCAmelCase  :						List[str]			     = {"""visual_embedding_dim""": 2048, """num_labels""": 3129}
                     _UpperCAmelCase  :						int			     = """vqa"""
              elif "nlvr" in checkpoint_path:
                     _UpperCAmelCase  :						int			     = {
                         """visual_embedding_dim""": 1024,
                         """num_labels""": 2,
                     }
                     _UpperCAmelCase  :						Optional[Any]			     = """nlvr"""

       _UpperCAmelCase  :						int			     = VisualBertConfig(**lowerCAmelCase_		)

       # Load State Dict
       _UpperCAmelCase  :						Any			     = load_state_dict(lowerCAmelCase_		)

       _UpperCAmelCase  :						Optional[int]			     = get_new_dict(lowerCAmelCase_       ,   lowerCAmelCase_		)

       if model_type == "pretraining":
              _UpperCAmelCase  :						List[str]			     = VisualBertForPreTraining(lowerCAmelCase_		)
       elif model_type == "vqa":
              _UpperCAmelCase  :						Optional[int]			     = VisualBertForQuestionAnswering(lowerCAmelCase_		)
       elif model_type == "nlvr":
              _UpperCAmelCase  :						str			     = VisualBertForVisualReasoning(lowerCAmelCase_		)
       elif model_type == "multichoice":
              _UpperCAmelCase  :						Dict			     = VisualBertForMultipleChoice(lowerCAmelCase_		)

       model.load_state_dict(lowerCAmelCase_		)
       # Save Checkpoints
       Path(lowerCAmelCase_		).mkdir(exist_ok=lowerCAmelCase_		)
       model.save_pretrained(lowerCAmelCase_		)


if __name__ == "__main__":
   A_							: Optional[Any]						 =	argparse.ArgumentParser()
   # Required parameters
   parser.add_argument("""orig_checkpoint_path""", type=str, help="""A path to .th on local filesystem.""")
   parser.add_argument("""pytorch_dump_folder_path""", type=str, help="""Path to the output PyTorch model.""")
   A_							: int						 =	parser.parse_args()
   convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)



