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

__lowercase		:		Tuple														=							[
    ("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"),
]

__lowercase		:		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    SCREAMING_SNAKE_CASE       (     snake_case):
     __snake_case				=							torch.load(snake_case,      map_location='''cpu''')
     return sd





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





@torch.no_grad()
def    SCREAMING_SNAKE_CASE       (     snake_case,      snake_case):
     assert (
         checkpoint_path.split('''/''')[-1] in ACCEPTABLE_CHECKPOINTS
     ), f"The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}."

     # Get Config
     if "pre" in checkpoint_path:
          __snake_case				=							'''pretraining'''
          if "vcr" in checkpoint_path:
               __snake_case				=							{'''visual_embedding_dim''': 5_12}
          elif "vqa_advanced" in checkpoint_path:
               __snake_case				=							{'''visual_embedding_dim''': 20_48}
          elif "vqa" in checkpoint_path:
               __snake_case				=							{'''visual_embedding_dim''': 20_48}
          elif "nlvr" in checkpoint_path:
               __snake_case				=							{'''visual_embedding_dim''': 10_24}
          else:
               raise NotImplementedError(f"No implementation found for `{checkpoint_path}`.")
     else:
          if "vcr" in checkpoint_path:
               __snake_case				=							{'''visual_embedding_dim''': 5_12}
               __snake_case				=							'''multichoice'''
          elif "vqa_advanced" in checkpoint_path:
               __snake_case				=							{'''visual_embedding_dim''': 20_48}
               __snake_case				=							'''vqa_advanced'''
          elif "vqa" in checkpoint_path:
               __snake_case				=							{'''visual_embedding_dim''': 20_48, '''num_labels''': 31_29}
               __snake_case				=							'''vqa'''
          elif "nlvr" in checkpoint_path:
               __snake_case				=							{
                   '''visual_embedding_dim''': 10_24,
                   '''num_labels''': 2,
               }
               __snake_case				=							'''nlvr'''

     __snake_case				=							VisualBertConfig(**snake_case)

     # Load State Dict
     __snake_case				=							load_state_dict(snake_case)

     __snake_case				=							get_new_dict(snake_case,      snake_case)

     if model_type == "pretraining":
          __snake_case				=							VisualBertForPreTraining(snake_case)
     elif model_type == "vqa":
          __snake_case				=							VisualBertForQuestionAnswering(snake_case)
     elif model_type == "nlvr":
          __snake_case				=							VisualBertForVisualReasoning(snake_case)
     elif model_type == "multichoice":
          __snake_case				=							VisualBertForMultipleChoice(snake_case)

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


if __name__ == "__main__":
       __lowercase		:		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.")
       __lowercase		:		Optional[int]														=							parser.parse_args()
       convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
"""simple docstring"""



from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
)


__lowercase		:		Dict														=							{
    "configuration_vision_text_dual_encoder": ["VisionTextDualEncoderConfig"],
    "processing_vision_text_dual_encoder": ["VisionTextDualEncoderProcessor"],
}


try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __lowercase		:		Optional[int]														=							["VisionTextDualEncoderModel"]


try:
       if not is_flax_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __lowercase		:		Optional[int]														=							["FlaxVisionTextDualEncoderModel"]

try:
       if not is_tf_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __lowercase		:		Any														=							["TFVisionTextDualEncoderModel"]


if TYPE_CHECKING:
       from .configuration_vision_text_dual_encoder import VisionTextDualEncoderConfig
       from .processing_vision_text_dual_encoder import VisionTextDualEncoderProcessor

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_vision_text_dual_encoder import VisionTextDualEncoderModel

       try:
              if not is_flax_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_flax_vision_text_dual_encoder import FlaxVisionTextDualEncoderModel

       try:
              if not is_tf_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_tf_vision_text_dual_encoder import TFVisionTextDualEncoderModel


else:
       import sys

       __lowercase		:		Tuple														=							_LazyModule(__name__, globals()["__file__"], _import_structure)