






"""simple docstring"""




from __future__ import annotations

import math

_snake_case          =   "2020.9.26"
_snake_case          =   "xcodz-dot, cclaus, dhruvmanila"

def 			lowerCAmelCase__     (     UpperCamelCase__     ,   UpperCamelCase__     ,   UpperCamelCase__     ,   UpperCamelCase__     ,   UpperCamelCase__				):



  '''simple docstring'''




  if not all(isinstance(_UpperCamelCase     ,   (float, int)				) for val in locals().values()				):
    _a  :       Optional[Any]             =	F"""Input values must either be float or int: {list(locals().values()				)}"""
    raise TypeError(_UpperCamelCase				)
  _a  :       Union[str, Any]             =	((x * distance) / (z + distance)) * scale
  _a  :       List[Any]             =	((y * distance) / (z + distance)) * scale
  return projected_x, projected_y

def 			lowerCAmelCase__     (     UpperCamelCase__     ,   UpperCamelCase__     ,   UpperCamelCase__     ,   UpperCamelCase__     ,   UpperCamelCase__				):



  '''simple docstring'''




  if not isinstance(_UpperCamelCase     ,   _UpperCamelCase				):
    raise TypeError("""Axis must be a str"""				)
  _a  :       Tuple             =	locals()
  del input_variables["axis"]
  if not all(isinstance(_UpperCamelCase     ,   (float, int)				) for val in input_variables.values()				):
    _a  :       Tuple             =	(
        """Input values except axis must either be float or int: """
        F"""{list(input_variables.values()				)}"""
    )
    raise TypeError(_UpperCamelCase				)
  _a  :       Optional[int]             =	(angle % 3_6_0) / 4_5_0 * 1_8_0 / math.pi
  if axis == "z":
    _a  :       int             =	x * math.cos(_UpperCamelCase				) - y * math.sin(_UpperCamelCase				)
    _a  :       Union[str, Any]             =	y * math.cos(_UpperCamelCase				) + x * math.sin(_UpperCamelCase				)
    _a  :       str             =	z
  elif axis == "x":
    _a  :       Optional[int]             =	y * math.cos(_UpperCamelCase				) - z * math.sin(_UpperCamelCase				)
    _a  :       Union[str, Any]             =	z * math.cos(_UpperCamelCase				) + y * math.sin(_UpperCamelCase				)
    _a  :       Optional[int]             =	x
  elif axis == "y":
    _a  :       Union[str, Any]             =	x * math.cos(_UpperCamelCase				) - z * math.sin(_UpperCamelCase				)
    _a  :       Tuple             =	z * math.cos(_UpperCamelCase				) + x * math.sin(_UpperCamelCase				)
    _a  :       int             =	y
  else:
    raise ValueError("""not a valid axis, choose one of 'x', 'y', 'z'"""				)

  return new_x, new_y, new_z


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 print(F'''{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }''')
 print(F'''{rotate(1.0, 2.0, 3.0, 'y', 90.0) = }''')





"""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     :   Tuple			    =			logging.get_logger(__name__)

A     :   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"),
]

A     :   Optional[Any]			    =			[
    "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	(		_UpperCamelCase      ):

			'''simple docstring'''




			__lowerCAmelCase				    =			torch.load(_UpperCamelCase    , map_location="cpu"      )
			return sd


def _lowerCamelCase	(		_UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase=rename_keys_prefix      ):

			'''simple docstring'''




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


@torch.no_grad()
def _lowerCamelCase	(		_UpperCamelCase    , _UpperCamelCase      ):

			'''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				    =			"pretraining"
						if "vcr" in checkpoint_path:
									__lowerCAmelCase				    =			{"visual_embedding_dim": 512}
						elif "vqa_advanced" in checkpoint_path:
									__lowerCAmelCase				    =			{"visual_embedding_dim": 2048}
						elif "vqa" in checkpoint_path:
									__lowerCAmelCase				    =			{"visual_embedding_dim": 2048}
						elif "nlvr" in checkpoint_path:
									__lowerCAmelCase				    =			{"visual_embedding_dim": 1024}
						else:
									raise NotImplementedError(f"No implementation found for `{checkpoint_path}`."      )
			else:
						if "vcr" in checkpoint_path:
									__lowerCAmelCase				    =			{"visual_embedding_dim": 512}
									__lowerCAmelCase				    =			"multichoice"
						elif "vqa_advanced" in checkpoint_path:
									__lowerCAmelCase				    =			{"visual_embedding_dim": 2048}
									__lowerCAmelCase				    =			"vqa_advanced"
						elif "vqa" in checkpoint_path:
									__lowerCAmelCase				    =			{"visual_embedding_dim": 2048, "num_labels": 3129}
									__lowerCAmelCase				    =			"vqa"
						elif "nlvr" in checkpoint_path:
									__lowerCAmelCase				    =			{
									    "visual_embedding_dim": 1024,
									    "num_labels": 2,
									}
									__lowerCAmelCase				    =			"nlvr"

			__lowerCAmelCase				    =			VisualBertConfig(**_UpperCamelCase      )

			# Load State Dict
			__lowerCAmelCase				    =			load_state_dict(_UpperCamelCase      )

			__lowerCAmelCase				    =			get_new_dict(_UpperCamelCase    , _UpperCamelCase      )

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

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


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




