






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

snake_case     					=		[
    ("""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"""),
]

snake_case     					=		[
    """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 	lowerCamelCase__      (  lowercase					):

  """simple docstring"""






  SCREAMING_SNAKE_CASE							:   int						    =     torch.load(lowercase    ,  map_location="cpu"					)
  return sd


def 	lowerCamelCase__      (  lowercase    ,  lowercase    ,  lowercase=rename_keys_prefix					):

  """simple docstring"""






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


@torch.no_grad()
def 	lowerCamelCase__      (  lowercase    ,  lowercase					):

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

  SCREAMING_SNAKE_CASE							:   List[Any]						    =     VisualBertConfig(**lowercase					)

  # Load State Dict
  SCREAMING_SNAKE_CASE							:   List[str]						    =     load_state_dict(lowercase					)

  SCREAMING_SNAKE_CASE							:   Any						    =     get_new_dict(lowercase    ,  lowercase					)

  if model_type == "pretraining":
    SCREAMING_SNAKE_CASE							:   int						    =     VisualBertForPreTraining(lowercase					)
  elif model_type == "vqa":
    SCREAMING_SNAKE_CASE							:   Tuple						    =     VisualBertForQuestionAnswering(lowercase					)
  elif model_type == "nlvr":
    SCREAMING_SNAKE_CASE							:   List[Any]						    =     VisualBertForVisualReasoning(lowercase					)
  elif model_type == "multichoice":
    SCREAMING_SNAKE_CASE							:   Optional[Any]						    =     VisualBertForMultipleChoice(lowercase					)

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


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









import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase_							:					List[str]		 =   logging.get_logger(__name__)

UpperCAmelCase_							:					str		 =   {
    '''microsoft/unispeech-large-1500h-cv''': (
        '''https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json'''
    ),
    # See all UniSpeech models at https://huggingface.co/models?filter=unispeech
}






class      lowerCamelCase_      (	_lowercase	):
	_lowercase		:   Dict     					=				'''unispeech'''




	def __init__(     self						:     str					,      __A						:     Tuple=32					,      __A						:     List[str]=768					,      __A						:     Dict=12					,      __A						:     Union[str, Any]=12					,      __A						:     Tuple=3072					,      __A						:     Any="gelu"					,      __A						:     int=0.1					,      __A						:     Optional[int]=0.1					,      __A						:     List[Any]=0.1					,      __A						:     Any=0.0					,      __A						:     List[str]=0.0					,      __A						:     int=0.1					,      __A						:     List[Any]=0.1					,      __A						:     List[str]=0.0_2					,      __A						:     List[str]=1e-5					,      __A						:     List[Any]="group"					,      __A						:     int="gelu"					,      __A						:     Any=(512, 512, 512, 512, 512, 512, 512)					,      __A						:     Union[str, Any]=(5, 2, 2, 2, 2, 2, 2)					,      __A						:     Tuple=(10, 3, 3, 3, 3, 2, 2)					,      __A						:     Optional[int]=False					,      __A						:     Any=128					,      __A						:     Union[str, Any]=16					,      __A						:     Optional[Any]=False					,      __A						:     str=True					,      __A						:     Dict=0.0_5					,      __A						:     Optional[Any]=10					,      __A						:     Dict=2					,      __A						:     int=0.0					,      __A						:     List[str]=10					,      __A						:     str=0					,      __A						:     List[str]=320					,      __A						:     List[Any]=2					,      __A						:     Tuple=0.1					,      __A						:     Optional[int]=100					,      __A						:     Any=256					,      __A						:     Dict=256					,      __A						:     Tuple=0.1					,      __A						:     List[str]="mean"					,      __A						:     int=False					,      __A						:     List[str]=False					,      __A						:     List[Any]=256					,      __A						:     str=80					,      __A						:     Tuple=0					,      __A						:     Tuple=1					,      __A						:     int=2					,      __A						:     Dict=0.5					,      **__A						:     List[Any]					,      ):
		super().__init__(**__A					,      pad_token_id=__A					,      bos_token_id=__A					,      eos_token_id=__A							)
		__A :			Dict		    =			hidden_size
		__A :			Optional[Any]		    =			feat_extract_norm
		__A :			List[Any]		    =			feat_extract_activation
		__A :			str		    =			list(__A							)
		__A :			Optional[Any]		    =			list(__A							)
		__A :			Optional[int]		    =			list(__A							)
		__A :			List[Any]		    =			conv_bias
		__A :			Optional[int]		    =			num_conv_pos_embeddings
		__A :			List[Any]		    =			num_conv_pos_embedding_groups
		__A :			int		    =			len(self.conv_dim							)
		__A :			Optional[Any]		    =			num_hidden_layers
		__A :			List[str]		    =			intermediate_size
		__A :			Union[str, Any]		    =			hidden_act
		__A :			Optional[int]		    =			num_attention_heads
		__A :			Tuple		    =			hidden_dropout
		__A :			Optional[Any]		    =			attention_dropout
		__A :			Union[str, Any]		    =			activation_dropout
		__A :			Dict		    =			feat_proj_dropout
		__A :			Optional[int]		    =			final_dropout
		__A :			Dict		    =			layerdrop
		__A :			Optional[int]		    =			layer_norm_eps
		__A :			Optional[Any]		    =			initializer_range
		__A :			Optional[int]		    =			num_ctc_classes
		__A :			Dict		    =			vocab_size
		__A :			List[str]		    =			do_stable_layer_norm
		__A :			Tuple		    =			use_weighted_layer_sum
		__A :			Any		    =			classifier_proj_size

		if (
		    (len(self.conv_stride							) != self.num_feat_extract_layers)
		    or (len(self.conv_kernel							) != self.num_feat_extract_layers)
		    or (len(self.conv_dim							) != self.num_feat_extract_layers)
		):
			raise ValueError(
			    """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="""
			    """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="""
			    F""" {len(self.conv_dim							)}`, `len(config.conv_stride) = {len(self.conv_stride							)}`,"""
			    F""" `len(config.conv_kernel) = {len(self.conv_kernel							)}`."""							)

		# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
		__A :			Tuple		    =			apply_spec_augment
		__A :			Union[str, Any]		    =			mask_time_prob
		__A :			Optional[Any]		    =			mask_time_length
		__A :			List[Any]		    =			mask_time_min_masks
		__A :			List[Any]		    =			mask_feature_prob
		__A :			Any		    =			mask_feature_length
		__A :			List[Any]		    =			mask_feature_min_masks

		# parameters for pretraining with codevector quantized representations
		__A :			Any		    =			num_codevectors_per_group
		__A :			Tuple		    =			num_codevector_groups
		__A :			List[str]		    =			contrastive_logits_temperature
		__A :			Optional[int]		    =			feat_quantizer_dropout
		__A :			int		    =			num_negatives
		__A :			List[str]		    =			codevector_dim
		__A :			int		    =			proj_codevector_dim
		__A :			Union[str, Any]		    =			diversity_loss_weight

		# ctc loss
		__A :			List[str]		    =			ctc_loss_reduction
		__A :			Any		    =			ctc_zero_infinity

		# pretraining loss
		__A :			Union[str, Any]		    =			replace_prob




	@property
	def        lowerCAmelCase_       (     self						:     int							):
		return functools.reduce(operator.mul					,      self.conv_stride					,      1							)





