




"""simple docstring"""

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


_lowerCamelCase  :			List[Any]        =       'Create a default config file for Accelerate with only a few flags set.'

def 		lowercase_      (		_UpperCAmelCase="no"  ,      _UpperCAmelCase = default_json_config_file  ,      _UpperCAmelCase = False	):




	"""simple docstring"""






	A_  :				int	   =		Path(_UpperCAmelCase	)
	path.parent.mkdir(parents=_UpperCAmelCase  ,      exist_ok=_UpperCAmelCase	)
	if path.exists():
		print(
		    f"""Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`."""	)
		return False
	A_  :				List[Any]	   =		mixed_precision.lower()
	if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
		raise ValueError(
		    f"""`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}"""	)
	A_  :				Tuple	   =		{
	    '''compute_environment''': '''LOCAL_MACHINE''',
	    '''mixed_precision''': mixed_precision,
	}
	if torch.cuda.is_available():
		A_  :				Optional[Any]	   =		torch.cuda.device_count()
		A_  :				Optional[Any]	   =		num_gpus
		A_  :				int	   =		False
		if num_gpus > 1:
			A_  :				List[str]	   =		'''MULTI_GPU'''
		else:
			A_  :				Optional[int]	   =		'''NO'''
	elif is_xpu_available() and use_xpu:
		A_  :				Union[str, Any]	   =		torch.xpu.device_count()
		A_  :				Dict	   =		num_xpus
		A_  :				List[str]	   =		False
		if num_xpus > 1:
			A_  :				str	   =		'''MULTI_XPU'''
		else:
			A_  :				str	   =		'''NO'''
	elif is_npu_available():
		A_  :				Tuple	   =		torch.npu.device_count()
		A_  :				Tuple	   =		num_npus
		A_  :				List[str]	   =		False
		if num_npus > 1:
			A_  :				Any	   =		'''MULTI_NPU'''
		else:
			A_  :				List[Any]	   =		'''NO'''
	else:
		A_  :				List[Any]	   =		0
		A_  :				Dict	   =		True
		A_  :				Tuple	   =		1
		A_  :				int	   =		'''NO'''
	A_  :				Union[str, Any]	   =		ClusterConfig(**_UpperCAmelCase	)
	config.to_json_file(_UpperCAmelCase	)
	return path

def 		lowercase_      (		_UpperCAmelCase  ,      _UpperCAmelCase	):




	"""simple docstring"""






	A_  :				Union[str, Any]	   =		parser.add_parser('''default'''  ,      parents=_UpperCAmelCase  ,      help=_UpperCAmelCase  ,      formatter_class=_UpperCAmelCase	)
	parser.add_argument(
	    '''--config_file'''  ,      default=_UpperCAmelCase  ,      help=(
	        '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache '''
	        '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '''
	        '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '''
	        '''with \'huggingface\'.'''
	    )  ,      dest='''save_location'''  ,      )

	parser.add_argument(
	    '''--mixed_precision'''  ,      choices=['''no''', '''fp16''', '''bf16''']  ,      type=_UpperCAmelCase  ,      help='''Whether or not to use mixed precision training. '''
	    '''Choose between FP16 and BF16 (bfloat16) training. '''
	    '''BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.'''  ,      default='''no'''  ,      )
	parser.set_defaults(func=_UpperCAmelCase	)
	return parser

def 		lowercase_      (		_UpperCAmelCase	):




	"""simple docstring"""






	A_  :				Dict	   =		write_basic_config(args.mixed_precision  ,      args.save_location	)
	if config_file:
		print(f"""accelerate configuration saved at {config_file}"""	)









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

_lowerCamelCase  :			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'),
]

_lowerCamelCase  :			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 		lowercase_      (		_UpperCAmelCase	):




	"""simple docstring"""






	A_  :				Union[str, Any]	   =		torch.load(_UpperCAmelCase  ,      map_location='''cpu'''	)
	return sd

def 		lowercase_      (		_UpperCAmelCase  ,      _UpperCAmelCase  ,      _UpperCAmelCase=rename_keys_prefix	):




	"""simple docstring"""






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

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

	A_  :				Dict	   =		VisualBertConfig(**_UpperCAmelCase	)

	# Load State Dict
	A_  :				List[str]	   =		load_state_dict(_UpperCAmelCase	)

	A_  :				List[str]	   =		get_new_dict(_UpperCAmelCase  ,      _UpperCAmelCase	)

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

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


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





