



'''simple docstring'''






from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
   import tensorflow as tf

   from ..tf_utils import stable_softmax


if is_torch_available():
   import torch


A_							: Optional[Any]						 =	logging.get_logger(__name__)



@add_end_docstrings(
    _lowerCamelCase					,					R"""
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    """					,					)
class 							lowercase       (  _lowerCamelCase				):


 """simple docstring"""


 def _snake_case (							self  ,a_							)		->   np.ndarray:
        if self.framework == "tf":
               _UpperCAmelCase  :						str			     = tf.where(input_ids == self.tokenizer.mask_token_id							).numpy()
        elif self.framework == "pt":
               _UpperCAmelCase  :						List[str]			     = torch.nonzero(input_ids == self.tokenizer.mask_token_id  ,as_tuple=a_							)
        else:
               raise ValueError("""Unsupported framework"""							)
        return masked_index







 def _snake_case (							self  ,a_							)		->   np.ndarray:
        _UpperCAmelCase  :						Dict			     = self.get_masked_index(a_							)
        _UpperCAmelCase  :						Any			     = np.prod(masked_index.shape							)
        if numel < 1:
               raise PipelineException(
                   """fill-mask"""  ,self.model.base_model_prefix  ,f'''No mask_token ({self.tokenizer.mask_token}) found on the input'''  ,)







 def _snake_case (							self  ,a_							)		->   List[str]:
        if isinstance(a_  ,a_							):
               for model_input in model_inputs:
                      self._ensure_exactly_one_mask_token(model_input["""input_ids"""][0]							)
        else:
               for input_ids in model_inputs["input_ids"]:
                      self._ensure_exactly_one_mask_token(a_							)







 def _snake_case (							self  ,a_  ,a_=None  ,**a_							)		->   Dict[str, GenericTensor]:
        if return_tensors is None:
               _UpperCAmelCase  :						List[str]			     = self.framework
        _UpperCAmelCase  :						Any			     = self.tokenizer(a_  ,return_tensors=a_							)
        self.ensure_exactly_one_mask_token(a_							)
        return model_inputs







 def _snake_case (							self  ,a_							)		->   Union[str, Any]:
        _UpperCAmelCase  :						int			     = self.model(**a_							)
        _UpperCAmelCase  :						Any			     = model_inputs["""input_ids"""]
        return model_outputs







 def _snake_case (							self  ,a_  ,a_=5  ,a_=None							)		->   Union[str, Any]:
        # Cap top_k if there are targets
        if target_ids is not None and target_ids.shape[0] < top_k:
               _UpperCAmelCase  :						Any			     = target_ids.shape[0]
        _UpperCAmelCase  :						str			     = model_outputs["""input_ids"""][0]
        _UpperCAmelCase  :						Dict			     = model_outputs["""logits"""]

        if self.framework == "tf":
               _UpperCAmelCase  :						str			     = tf.where(input_ids == self.tokenizer.mask_token_id							).numpy()[:, 0]

               _UpperCAmelCase  :						Tuple			     = outputs.numpy()

               _UpperCAmelCase  :						List[Any]			     = outputs[0, masked_index, :]
               _UpperCAmelCase  :						Union[str, Any]			     = stable_softmax(a_  ,axis=-1							)
               if target_ids is not None:
                      _UpperCAmelCase  :						List[str]			     = tf.gather_nd(tf.squeeze(a_  ,0							)  ,target_ids.reshape(-1  ,1							)							)
                      _UpperCAmelCase  :						List[str]			     = tf.expand_dims(a_  ,0							)

               _UpperCAmelCase  :						Any			     = tf.math.top_k(a_  ,k=a_							)
               _UpperCAmelCase     ,_UpperCAmelCase  :						Dict			     = topk.values.numpy(), topk.indices.numpy()
        else:
               _UpperCAmelCase  :						Optional[int]			     = torch.nonzero(input_ids == self.tokenizer.mask_token_id  ,as_tuple=a_							).squeeze(-1							)
               # Fill mask pipeline supports only one ${mask_token} per sample

               _UpperCAmelCase  :						Optional[Any]			     = outputs[0, masked_index, :]
               _UpperCAmelCase  :						List[Any]			     = logits.softmax(dim=-1							)
               if target_ids is not None:
                      _UpperCAmelCase  :						Tuple			     = probs[..., target_ids]

               _UpperCAmelCase     ,_UpperCAmelCase  :						int			     = probs.topk(a_							)

        _UpperCAmelCase  :						Union[str, Any]			     = []
        _UpperCAmelCase  :						Dict			     = values.shape[0] == 1
        for i, (_values, _predictions) in enumerate(zip(values.tolist()  ,predictions.tolist()							)							):
               _UpperCAmelCase  :						Optional[int]			     = []
               for v, p in zip(_values  ,_predictions							):
                      # Copy is important since we're going to modify this array in place
                      _UpperCAmelCase  :						List[Any]			     = input_ids.numpy().copy()
                      if target_ids is not None:
                             _UpperCAmelCase  :						Union[str, Any]			     = target_ids[p].tolist()

                      _UpperCAmelCase  :						Union[str, Any]			     = p
                      # Filter padding out:
                      _UpperCAmelCase  :						Any			     = tokens[np.where(tokens != self.tokenizer.pad_token_id							)]
                      # Originally we skip special tokens to give readable output.
                      # For multi masks though, the other [MASK] would be removed otherwise
                      # making the output look odd, so we add them back
                      _UpperCAmelCase  :						str			     = self.tokenizer.decode(a_  ,skip_special_tokens=a_							)
                      _UpperCAmelCase  :						List[str]			     = {"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p]							), """sequence""": sequence}
                      row.append(a_							)
               result.append(a_							)
        if single_mask:
               return result[0]
        return result







 def _snake_case (							self  ,a_  ,a_=None							)		->   Tuple:
        if isinstance(a_  ,a_							):
               _UpperCAmelCase  :						str			     = [targets]
        try:
               _UpperCAmelCase  :						List[str]			     = self.tokenizer.get_vocab()
        except Exception:
               _UpperCAmelCase  :						Union[str, Any]			     = {}
        _UpperCAmelCase  :						Any			     = []
        for target in targets:
               _UpperCAmelCase  :						Optional[Any]			     = vocab.get(a_  ,a_							)
               if id_ is None:
                      _UpperCAmelCase  :						Any			     = self.tokenizer(
                          a_  ,add_special_tokens=a_  ,return_attention_mask=a_  ,return_token_type_ids=a_  ,max_length=1  ,truncation=a_  ,)["""input_ids"""]
                      if len(a_							) == 0:
                             logger.warning(
                                 f'''The specified target token `{target}` does not exist in the model vocabulary. '''
                                 """We cannot replace it with anything meaningful, ignoring it"""							)
                             continue
                      _UpperCAmelCase  :						Dict			     = input_ids[0]
                      # XXX: If users encounter this pass
                      # it becomes pretty slow, so let's make sure
                      # The warning enables them to fix the input to
                      # get faster performance.
                      logger.warning(
                          f'''The specified target token `{target}` does not exist in the model vocabulary. '''
                          f'''Replacing with `{self.tokenizer.convert_ids_to_tokens(id_							)}`.'''							)
               target_ids.append(id_							)
        _UpperCAmelCase  :						str			     = list(set(a_							)							)
        if len(a_							) == 0:
               raise ValueError("""At least one target must be provided when passed."""							)
        _UpperCAmelCase  :						List[Any]			     = np.array(a_							)
        return target_ids







 def _snake_case (							self  ,a_=None  ,a_=None							)		->   Dict:
        _UpperCAmelCase  :						int			     = {}

        if targets is not None:
               _UpperCAmelCase  :						str			     = self.get_target_ids(a_  ,a_							)
               _UpperCAmelCase  :						Optional[Any]			     = target_ids

        if top_k is not None:
               _UpperCAmelCase  :						str			     = top_k

        if self.tokenizer.mask_token_id is None:
               raise PipelineException(
                   """fill-mask"""  ,self.model.base_model_prefix  ,"""The tokenizer does not define a `mask_token`."""							)
        return {}, {}, postprocess_params







 def __call__(							self  ,a_  ,*a_  ,**a_							)		->   Union[str, Any]:
        _UpperCAmelCase  :						Tuple			     = super().__call__(a_  ,**a_							)
        if isinstance(a_  ,a_							) and len(a_							) == 1:
               return outputs[0]
        return outputs








'''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)



