






import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING


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

UpperCAmelCase_ :						int      =      {
    '''salesforce/blip2-opt-2.7b''': '''https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json''',
}

class     _SCREAMING_SNAKE_CASE       (			_a      ):
	snake_case__							:     Union[str, Any]     	=  """blip_2_vision_model"""





	def __init__(		self				:					Any ,  __lowerCamelCase				:					Any=1_408 ,  __lowerCamelCase				:					Any=6_144 ,  __lowerCamelCase				:					Any=39 ,  __lowerCamelCase				:					List[str]=16 ,  __lowerCamelCase				:					List[Any]=224 ,  __lowerCamelCase				:					List[str]=14 ,  __lowerCamelCase				:					Any="gelu" ,  __lowerCamelCase				:					List[str]=0.00001 ,  __lowerCamelCase				:					Dict=0.0 ,  __lowerCamelCase				:					List[str]=1E-10 ,  __lowerCamelCase				:					int=True ,  **__lowerCamelCase				:					str ,  ):
		super().__init__(**__lowerCamelCase	)

		UpperCamelCase     :Optional[Any]          =	hidden_size
		UpperCamelCase     :List[str]          =	intermediate_size
		UpperCamelCase     :Optional[Any]          =	num_hidden_layers
		UpperCamelCase     :Union[str, Any]          =	num_attention_heads
		UpperCamelCase     :List[str]          =	patch_size
		UpperCamelCase     :str          =	image_size
		UpperCamelCase     :Optional[int]          =	initializer_range
		UpperCamelCase     :Optional[int]          =	attention_dropout
		UpperCamelCase     :Union[str, Any]          =	layer_norm_eps
		UpperCamelCase     :Optional[int]          =	hidden_act
		UpperCamelCase     :List[str]          =	qkv_bias





	@classmethod
	def 						_A (		cls				:					Tuple ,  __lowerCamelCase				:					Union[str, os.PathLike] ,  **__lowerCamelCase				:					List[str]	):
		cls._set_token_in_kwargs(__lowerCamelCase	)

		UpperCamelCase     ,      UpperCamelCase     :List[Any]          =	cls.get_config_dict(__lowerCamelCase ,  **__lowerCamelCase	)

		# get the vision config dict if we are loading from Blip2Config
		if config_dict.get("""model_type"""	) == "blip-2":
			UpperCamelCase     :Union[str, Any]          =	config_dict["""vision_config"""]

		if "model_type" in config_dict and hasattr(cls ,  """model_type"""	) and config_dict["model_type"] != cls.model_type:
			logger.warning(
			    F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
			    F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""	)

		return cls.from_dict(__lowerCamelCase ,  **__lowerCamelCase	)

class     _SCREAMING_SNAKE_CASE       (			_a      ):
	snake_case__							:     int     	=  """blip_2_qformer"""





	def __init__(		self				:					Optional[int] ,  __lowerCamelCase				:					Optional[Any]=30_522 ,  __lowerCamelCase				:					Any=768 ,  __lowerCamelCase				:					Union[str, Any]=12 ,  __lowerCamelCase				:					Optional[Any]=12 ,  __lowerCamelCase				:					List[str]=3_072 ,  __lowerCamelCase				:					Union[str, Any]="gelu" ,  __lowerCamelCase				:					str=0.1 ,  __lowerCamelCase				:					Any=0.1 ,  __lowerCamelCase				:					int=512 ,  __lowerCamelCase				:					Tuple=0.02 ,  __lowerCamelCase				:					Union[str, Any]=1E-12 ,  __lowerCamelCase				:					Any=0 ,  __lowerCamelCase				:					Tuple="absolute" ,  __lowerCamelCase				:					Optional[Any]=2 ,  __lowerCamelCase				:					Optional[Any]=1_408 ,  **__lowerCamelCase				:					str ,  ):
		super().__init__(pad_token_id=__lowerCamelCase ,  **__lowerCamelCase	)

		UpperCamelCase     :Tuple          =	vocab_size
		UpperCamelCase     :str          =	hidden_size
		UpperCamelCase     :Dict          =	num_hidden_layers
		UpperCamelCase     :Tuple          =	num_attention_heads
		UpperCamelCase     :Optional[Any]          =	hidden_act
		UpperCamelCase     :Any          =	intermediate_size
		UpperCamelCase     :Tuple          =	hidden_dropout_prob
		UpperCamelCase     :List[str]          =	attention_probs_dropout_prob
		UpperCamelCase     :Tuple          =	max_position_embeddings
		UpperCamelCase     :Union[str, Any]          =	initializer_range
		UpperCamelCase     :Tuple          =	layer_norm_eps
		UpperCamelCase     :Tuple          =	position_embedding_type
		UpperCamelCase     :Optional[Any]          =	cross_attention_frequency
		UpperCamelCase     :Optional[Any]          =	encoder_hidden_size





	@classmethod
	def 						_A (		cls				:					Optional[Any] ,  __lowerCamelCase				:					Union[str, os.PathLike] ,  **__lowerCamelCase				:					int	):
		cls._set_token_in_kwargs(__lowerCamelCase	)

		UpperCamelCase     ,      UpperCamelCase     :str          =	cls.get_config_dict(__lowerCamelCase ,  **__lowerCamelCase	)

		# get the qformer config dict if we are loading from Blip2Config
		if config_dict.get("""model_type"""	) == "blip-2":
			UpperCamelCase     :str          =	config_dict["""qformer_config"""]

		if "model_type" in config_dict and hasattr(cls ,  """model_type"""	) and config_dict["model_type"] != cls.model_type:
			logger.warning(
			    F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
			    F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""	)

		return cls.from_dict(__lowerCamelCase ,  **__lowerCamelCase	)

class     _SCREAMING_SNAKE_CASE       (			_a      ):
	snake_case__							:     int     	=  """blip-2"""
	snake_case__							:     Optional[Any]     	=  True





	def __init__(		self				:					int ,  __lowerCamelCase				:					Dict=None ,  __lowerCamelCase				:					Optional[Any]=None ,  __lowerCamelCase				:					List[str]=None ,  __lowerCamelCase				:					Dict=32 ,  **__lowerCamelCase				:					Dict	):
		super().__init__(**__lowerCamelCase	)

		if vision_config is None:
			UpperCamelCase     :List[str]          =	{}
			logger.info("""vision_config is None. initializing the Blip2VisionConfig with default values."""	)

		if qformer_config is None:
			UpperCamelCase     :List[Any]          =	{}
			logger.info("""qformer_config is None. Initializing the Blip2QFormerConfig with default values."""	)

		if text_config is None:
			UpperCamelCase     :int          =	{}
			logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`)."""	)

		UpperCamelCase     :Tuple          =	BlipaVisionConfig(**__lowerCamelCase	)
		UpperCamelCase     :str          =	BlipaQFormerConfig(**__lowerCamelCase	)
		UpperCamelCase     :Any          =	text_config["""model_type"""] if """model_type""" in text_config else """opt"""
		UpperCamelCase     :Union[str, Any]          =	CONFIG_MAPPING[text_model_type](**__lowerCamelCase	)

		UpperCamelCase     :List[str]          =	self.text_config.tie_word_embeddings
		UpperCamelCase     :Union[str, Any]          =	self.text_config.is_encoder_decoder

		UpperCamelCase     :Tuple          =	num_query_tokens
		UpperCamelCase     :Any          =	self.vision_config.hidden_size
		UpperCamelCase     :int          =	self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
		UpperCamelCase     :Union[str, Any]          =	1.0
		UpperCamelCase     :Union[str, Any]          =	0.02





	@classmethod
	def 						_A (		cls				:					Tuple ,  __lowerCamelCase				:					BlipaVisionConfig ,  __lowerCamelCase				:					BlipaQFormerConfig ,  __lowerCamelCase				:					PretrainedConfig ,  **__lowerCamelCase				:					List[Any] ,  ):
		return cls(
		    vision_config=vision_config.to_dict() ,  qformer_config=qformer_config.to_dict() ,  text_config=text_config.to_dict() ,  **__lowerCamelCase ,  )





	def 						_A (		self				:					Optional[int]	):
		UpperCamelCase     :Tuple          =	copy.deepcopy(self.__dict__	)
		UpperCamelCase     :Dict          =	self.vision_config.to_dict()
		UpperCamelCase     :Optional[int]          =	self.qformer_config.to_dict()
		UpperCamelCase     :Any          =	self.text_config.to_dict()
		UpperCamelCase     :Union[str, Any]          =	self.__class__.model_type
		return output








# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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


UpperCAmelCase_ :						Any      =      '''Create a default config file for Accelerate with only a few flags set.'''

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Optional[int]="no"	,			__magic_name__					:  str = default_json_config_file	,			__magic_name__					:  bool = False					)		->			str:






	"""simple docstring"""



	UpperCamelCase     :Any          =	Path(__magic_name__					)
	path.parent.mkdir(parents=__magic_name__	,			exist_ok=__magic_name__					)
	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
	UpperCamelCase     :Dict          =	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}"""					)
	UpperCamelCase     :Optional[Any]          =	{
	    """compute_environment""": """LOCAL_MACHINE""",
	    """mixed_precision""": mixed_precision,
	}
	if torch.cuda.is_available():
		UpperCamelCase     :Union[str, Any]          =	torch.cuda.device_count()
		UpperCamelCase     :List[Any]          =	num_gpus
		UpperCamelCase     :Dict          =	False
		if num_gpus > 1:
			UpperCamelCase     :Any          =	"""MULTI_GPU"""
		else:
			UpperCamelCase     :Any          =	"""NO"""
	elif is_xpu_available() and use_xpu:
		UpperCamelCase     :Optional[Any]          =	torch.xpu.device_count()
		UpperCamelCase     :Optional[int]          =	num_xpus
		UpperCamelCase     :int          =	False
		if num_xpus > 1:
			UpperCamelCase     :Union[str, Any]          =	"""MULTI_XPU"""
		else:
			UpperCamelCase     :Union[str, Any]          =	"""NO"""
	elif is_npu_available():
		UpperCamelCase     :List[Any]          =	torch.npu.device_count()
		UpperCamelCase     :Optional[Any]          =	num_npus
		UpperCamelCase     :Tuple          =	False
		if num_npus > 1:
			UpperCamelCase     :Optional[Any]          =	"""MULTI_NPU"""
		else:
			UpperCamelCase     :List[Any]          =	"""NO"""
	else:
		UpperCamelCase     :Any          =	0
		UpperCamelCase     :Optional[Any]          =	True
		UpperCamelCase     :Optional[Any]          =	1
		UpperCamelCase     :List[str]          =	"""NO"""
	UpperCamelCase     :int          =	ClusterConfig(**__magic_name__					)
	config.to_json_file(__magic_name__					)
	return path

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Dict	,			__magic_name__					:  Tuple					)		->			List[str]:






	"""simple docstring"""



	UpperCamelCase     :Dict          =	parser.add_parser("""default"""	,			parents=__magic_name__	,			help=__magic_name__	,			formatter_class=__magic_name__					)
	parser.add_argument(
	    """--config_file"""	,			default=__magic_name__	,			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=__magic_name__	,			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=__magic_name__					)
	return parser

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  List[Any]					)		->			List[str]:






	"""simple docstring"""



	UpperCamelCase     :Optional[Any]          =	write_basic_config(args.mixed_precision	,			args.save_location					)
	if config_file:
		print(f"""accelerate configuration saved at {config_file}"""					)
