





'''simple docstring'''


import math

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


_SCREAMING_SNAKE_CASE									=				logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE									=				{
    "facebook/data2vec-base-960h": "https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json",
    # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio
}

class  lowerCAmelCase_		(		__magic_name__		):
 __lowerCamelCase    :				List[Any]								=       "data2vec-audio"




 def __init__(						self      ,  _lowerCAmelCase=32      ,  _lowerCAmelCase=768      ,  _lowerCAmelCase=12      ,  _lowerCAmelCase=12      ,  _lowerCAmelCase=3072      ,  _lowerCAmelCase="gelu"      ,  _lowerCAmelCase=0.1      ,  _lowerCAmelCase=0.1      ,  _lowerCAmelCase=0.1      ,  _lowerCAmelCase=0.0      ,  _lowerCAmelCase=0.1      ,  _lowerCAmelCase=0.1      ,  _lowerCAmelCase=0.02      ,  _lowerCAmelCase=1E-5      ,  _lowerCAmelCase="gelu"      ,  _lowerCAmelCase=(512, 512, 512, 512, 512, 512, 512)      ,  _lowerCAmelCase=(5, 2, 2, 2, 2, 2, 2)      ,  _lowerCAmelCase=(10, 3, 3, 3, 3, 2, 2)      ,  _lowerCAmelCase=False      ,  _lowerCAmelCase=16      ,  _lowerCAmelCase=19      ,  _lowerCAmelCase=5      ,  _lowerCAmelCase=0.05      ,  _lowerCAmelCase=10      ,  _lowerCAmelCase=2      ,  _lowerCAmelCase=0.0      ,  _lowerCAmelCase=10      ,  _lowerCAmelCase=0      ,  _lowerCAmelCase="sum"      ,  _lowerCAmelCase=False      ,  _lowerCAmelCase=False      ,  _lowerCAmelCase=256      ,  _lowerCAmelCase=(512, 512, 512, 512, 1500)      ,  _lowerCAmelCase=(5, 3, 3, 1, 1)      ,  _lowerCAmelCase=(1, 2, 3, 1, 1)      ,  _lowerCAmelCase=512      ,  _lowerCAmelCase=0      ,  _lowerCAmelCase=1      ,  _lowerCAmelCase=2      ,  _lowerCAmelCase=False      ,  _lowerCAmelCase=3      ,  _lowerCAmelCase=2      ,  _lowerCAmelCase=3      ,  _lowerCAmelCase=None      ,  **_lowerCAmelCase      ,  )     ->				Dict:
     super().__init__(**_lowerCAmelCase      ,  pad_token_id=_lowerCAmelCase      ,  bos_token_id=_lowerCAmelCase      ,  eos_token_id=_lowerCAmelCase		)
     _lowerCAmelCase						      =   hidden_size
     _lowerCAmelCase						      =   feat_extract_activation
     _lowerCAmelCase						      =   list(_lowerCAmelCase		)
     _lowerCAmelCase						      =   list(_lowerCAmelCase		)
     _lowerCAmelCase						      =   list(_lowerCAmelCase		)
     _lowerCAmelCase						      =   conv_bias
     _lowerCAmelCase						      =   num_conv_pos_embeddings
     _lowerCAmelCase						      =   num_conv_pos_embedding_groups
     _lowerCAmelCase						      =   conv_pos_kernel_size
     _lowerCAmelCase						      =   len(self.conv_dim		)
     _lowerCAmelCase						      =   num_hidden_layers
     _lowerCAmelCase						      =   intermediate_size
     _lowerCAmelCase						      =   hidden_act
     _lowerCAmelCase						      =   num_attention_heads
     _lowerCAmelCase						      =   hidden_dropout
     _lowerCAmelCase						      =   attention_dropout
     _lowerCAmelCase						      =   activation_dropout
     _lowerCAmelCase						      =   feat_proj_dropout
     _lowerCAmelCase						      =   final_dropout
     _lowerCAmelCase						      =   layerdrop
     _lowerCAmelCase						      =   layer_norm_eps
     _lowerCAmelCase						      =   initializer_range
     _lowerCAmelCase						      =   vocab_size
     _lowerCAmelCase						      =   use_weighted_layer_sum

     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
     _lowerCAmelCase						      =   mask_time_prob
     _lowerCAmelCase						      =   mask_time_length
     _lowerCAmelCase						      =   mask_time_min_masks
     _lowerCAmelCase						      =   mask_feature_prob
     _lowerCAmelCase						      =   mask_feature_length
     _lowerCAmelCase						      =   mask_feature_min_masks

     # ctc loss
     _lowerCAmelCase						      =   ctc_loss_reduction
     _lowerCAmelCase						      =   ctc_zero_infinity

     # adapter
     _lowerCAmelCase						      =   add_adapter
     _lowerCAmelCase						      =   adapter_kernel_size
     _lowerCAmelCase						      =   adapter_stride
     _lowerCAmelCase						      =   num_adapter_layers
     _lowerCAmelCase						      =   output_hidden_size or hidden_size

     # SequenceClassification-specific parameter. Feel free to ignore for other classes.
     _lowerCAmelCase						      =   classifier_proj_size

     # XVector-specific parameters. Feel free to ignore for other classes.
     _lowerCAmelCase						      =   list(_lowerCAmelCase		)
     _lowerCAmelCase						      =   list(_lowerCAmelCase		)
     _lowerCAmelCase						      =   list(_lowerCAmelCase		)
     _lowerCAmelCase						      =   xvector_output_dim





 @property
 def 				_snake_case (						self		)     ->				str:
     return math.prod(self.conv_stride		)




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

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

__lowerCamelCase				=			[
    """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      UpperCamelCase   (       __lowerCamelCase	:					int       ):
       snake_case			:  List[Any]     							= torch.load(__lowerCamelCase							,   map_location="cpu"       )
       return sd


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


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

       snake_case			:  int     							= VisualBertConfig(**__lowerCamelCase       )

       # Load State Dict
       snake_case			:  Any     							= load_state_dict(__lowerCamelCase       )

       snake_case			:  List[Any]     							= get_new_dict(__lowerCamelCase							,   __lowerCamelCase       )

       if model_type == "pretraining":
              snake_case			:  str     							= VisualBertForPreTraining(__lowerCamelCase       )
       elif model_type == "vqa":
              snake_case			:  Any     							= VisualBertForQuestionAnswering(__lowerCamelCase       )
       elif model_type == "nlvr":
              snake_case			:  Optional[Any]     							= VisualBertForVisualReasoning(__lowerCamelCase       )
       elif model_type == "multichoice":
              snake_case			:  Optional[int]     							= VisualBertForMultipleChoice(__lowerCamelCase       )

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


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





