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

UpperCAmelCase_							: Dict =							[
    ('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'),
]

UpperCAmelCase_							: 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 		A_							(						_lowerCAmelCase :     Optional[Any]				):



      """simple docstring"""




      _lowerCamelCase					: Optional[int]		    = torch.load(_lowerCAmelCase					,						map_location="cpu"				)
      return sd







def 		A_							(						_lowerCAmelCase :     List[Any]					,						_lowerCAmelCase :     Dict					,						_lowerCAmelCase :     Tuple=rename_keys_prefix				):



      """simple docstring"""




      _lowerCamelCase					: Any		    = OrderedDict()
      _lowerCamelCase					: str		    = 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
            _lowerCamelCase					: Any		    = key
            for name_pair in rename_keys_prefix:
                  _lowerCamelCase					: Dict		    = new_key.replace(name_pair[0]					,						name_pair[1]				)
            _lowerCamelCase					: Any		    = d[key]
            if key == "bert.cls.predictions.decoder.weight":
                  # Old bert code didn't have `decoder.bias`, but was added separately
                  _lowerCamelCase					: List[str]		    = new_d["cls.predictions.bias"]
      return new_d







@torch.no_grad()
def 		A_							(						_lowerCAmelCase :     str					,						_lowerCAmelCase :     Dict				):



      """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:
            _lowerCamelCase					: Optional[int]		    = "pretraining"
            if "vcr" in checkpoint_path:
                  _lowerCamelCase					: Union[str, Any]		    = {"visual_embedding_dim": 512}
            elif "vqa_advanced" in checkpoint_path:
                  _lowerCamelCase					: List[str]		    = {"visual_embedding_dim": 2048}
            elif "vqa" in checkpoint_path:
                  _lowerCamelCase					: int		    = {"visual_embedding_dim": 2048}
            elif "nlvr" in checkpoint_path:
                  _lowerCamelCase					: List[str]		    = {"visual_embedding_dim": 1024}
            else:
                  raise NotImplementedError(F'No implementation found for `{checkpoint_path}`.'				)
      else:
            if "vcr" in checkpoint_path:
                  _lowerCamelCase					: Any		    = {"visual_embedding_dim": 512}
                  _lowerCamelCase					: List[Any]		    = "multichoice"
            elif "vqa_advanced" in checkpoint_path:
                  _lowerCamelCase					: Tuple		    = {"visual_embedding_dim": 2048}
                  _lowerCamelCase					: Dict		    = "vqa_advanced"
            elif "vqa" in checkpoint_path:
                  _lowerCamelCase					: Union[str, Any]		    = {"visual_embedding_dim": 2048, "num_labels": 3129}
                  _lowerCamelCase					: Optional[int]		    = "vqa"
            elif "nlvr" in checkpoint_path:
                  _lowerCamelCase					: Tuple		    = {
                      "visual_embedding_dim": 1024,
                      "num_labels": 2,
                  }
                  _lowerCamelCase					: Optional[Any]		    = "nlvr"

      _lowerCamelCase					: str		    = VisualBertConfig(**_lowerCAmelCase				)

      # Load State Dict
      _lowerCamelCase					: str		    = load_state_dict(_lowerCAmelCase				)

      _lowerCamelCase					: List[str]		    = get_new_dict(_lowerCAmelCase					,						_lowerCAmelCase				)

      if model_type == "pretraining":
            _lowerCamelCase					: List[Any]		    = VisualBertForPreTraining(_lowerCAmelCase				)
      elif model_type == "vqa":
            _lowerCamelCase					: Dict		    = VisualBertForQuestionAnswering(_lowerCAmelCase				)
      elif model_type == "nlvr":
            _lowerCamelCase					: Tuple		    = VisualBertForVisualReasoning(_lowerCAmelCase				)
      elif model_type == "multichoice":
            _lowerCamelCase					: str		    = VisualBertForMultipleChoice(_lowerCAmelCase				)

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


if __name__ == "__main__":
 UpperCAmelCase_							: List[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.')
 UpperCAmelCase_							: Tuple =							parser.parse_args()
 convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)


'''simple docstring'''







import os
import sys
import unittest


__lowerCamelCase									=     os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
__lowerCamelCase									=     os.path.join(git_repo_path, '''src''', '''transformers''')

__lowerCamelCase									=     '''
{0} = None
'''

__lowerCamelCase									=     '''
class {0}(metaclass=DummyObject):
    _backends = {1}

    def __init__(self, *args, **kwargs):
        requires_backends(self, {1})
'''


__lowerCamelCase									=     '''
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
'''


class        A__   (   unittest.TestCase      ):



    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           A_						       =   find_backend("""    _import_structure[\"models.albert\"].append(\"AlbertTokenizerFast\")"""							)
           self.assertIsNone(UpperCamelCase__							)

           A_						       =   find_backend("""    if not is_tokenizers_available():"""							)
           self.assertEqual(UpperCamelCase__		,					"""tokenizers"""							)

           A_						       =   find_backend("""    if not is_tensorflow_text_available():"""							)
           self.assertEqual(UpperCamelCase__		,					"""tensorflow_text"""							)

           A_						       =   find_backend("""    if not (is_sentencepiece_available() and is_tokenizers_available()):"""							)
           self.assertEqual(UpperCamelCase__		,					"""sentencepiece_and_tokenizers"""							)

           A_						       =   find_backend(
               """    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"""							)
           self.assertEqual(UpperCamelCase__		,					"""sentencepiece_and_tensorflow_text"""							)

           A_						       =   find_backend(
               """    if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):"""							)
           self.assertEqual(UpperCamelCase__		,					"""sentencepiece_and_tokenizers_and_vision"""							)



    def        snake_case_      (       self							)    ->   int:





           '''simple docstring'''
           A_						       =   read_init()
           # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
           self.assertIn("""torch"""		,					UpperCamelCase__							)
           self.assertIn("""tensorflow_text"""		,					UpperCamelCase__							)
           self.assertIn("""sentencepiece_and_tokenizers"""		,					UpperCamelCase__							)

           # Likewise, we can't assert on the exact content of a key
           self.assertIn("""BertModel"""		,					objects["""torch"""]							)
           self.assertIn("""TFBertModel"""		,					objects["""tf"""]							)
           self.assertIn("""FlaxBertModel"""		,					objects["""flax"""]							)
           self.assertIn("""BertModel"""		,					objects["""torch"""]							)
           self.assertIn("""TFBertTokenizer"""		,					objects["""tensorflow_text"""]							)
           self.assertIn("""convert_slow_tokenizer"""		,					objects["""sentencepiece_and_tokenizers"""]							)



    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   create_dummy_object("""CONSTANT"""		,					"""'torch'"""							)
           self.assertEqual(UpperCamelCase__		,					"""\nCONSTANT = None\n"""							)

           A_						       =   create_dummy_object("""function"""		,					"""'torch'"""							)
           self.assertEqual(
               UpperCamelCase__		,					"""\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n"""							)

           A_						       =   """
class FakeClass(metaclass=DummyObject):
    _backends = 'torch'

    def __init__(self, *args, **kwargs):
        requires_backends(self, 'torch')
"""
           A_						       =   create_dummy_object("""FakeClass"""		,					"""'torch'"""							)
           self.assertEqual(UpperCamelCase__		,					UpperCamelCase__							)







    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   """# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends


CONSTANT = None


def function(*args, **kwargs):
    requires_backends(function, [\"torch\"])


class FakeClass(metaclass=DummyObject):
    _backends = [\"torch\"]

    def __init__(self, *args, **kwargs):
        requires_backends(self, [\"torch\"])
"""
           A_						       =   create_dummy_files({"""torch""": ["""CONSTANT""", """function""", """FakeClass"""]}							)
           self.assertEqual(dummy_files["""torch"""]		,					UpperCamelCase__							)
