
'''simple docstring'''







import importlib.util
import os
import platform
from argparse import ArgumentParser

import huggingface_hub

from .. import __version__ as version
from ..utils import (
    is_accelerate_available,
    is_flax_available,
    is_safetensors_available,
    is_tf_available,
    is_torch_available,
)
from . import BaseTransformersCLICommand







def 				SCREAMING_SNAKE_CASE__	(   __A	)       ->	Union[str, Any]:
	return EnvironmentCommand()







def 				SCREAMING_SNAKE_CASE__	(   __A	)       ->	Tuple:
	return EnvironmentCommand(args.accelerate_config_file	)





class 						__UpperCAmelCase      (					__lowerCamelCase						):


							@staticmethod
							def  lowerCamelCase				(       lowerCAmelCase_  ):





								"""simple docstring"""






								_snake_case   						=		parser.add_parser('env'  )
								download_parser.set_defaults(func=lowerCAmelCase_  )
								download_parser.add_argument(
								    '--accelerate-config_file'    ,   default=lowerCAmelCase_    ,   help='The accelerate config file to use for the default values in the launching script.'    ,   )
								download_parser.set_defaults(func=lowerCAmelCase_  )


							def __init__(       self    ,   lowerCAmelCase_    ,   *lowerCAmelCase_  ):





								"""simple docstring"""






								_snake_case   						=		accelerate_config_file


							def  lowerCamelCase				(       self  ):





								"""simple docstring"""






								_snake_case   						=		'not installed'
								if is_safetensors_available():
									import safetensors

									_snake_case   						=		safetensors.__version__
								elif importlib.util.find_spec('safetensors'  ) is not None:
									import safetensors

									_snake_case   						=		F'{safetensors.__version__} but is ignored because of PyTorch version too old.'

								_snake_case   						=		'not installed'
								_snake_case   						=		_snake_case   						=		'not found'
								if is_accelerate_available():
									import accelerate
									from accelerate.commands.config import default_config_file, load_config_from_file

									_snake_case   						=		accelerate.__version__
									# Get the default from the config file.
									if self._accelerate_config_file is not None or os.path.isfile(lowerCAmelCase_  ):
										_snake_case   						=		load_config_from_file(self._accelerate_config_file  ).to_dict()

									_snake_case   						=		(
									    '\n'.join([F'\t- {prop}: {val}' for prop, val in accelerate_config.items()]  )
									    if isinstance(lowerCAmelCase_    ,   lowerCAmelCase_  )
									    else F'\t{accelerate_config}'
									)

								_snake_case   						=		'not installed'
								_snake_case   						=		'NA'
								if is_torch_available():
									import torch

									_snake_case   						=		torch.__version__
									_snake_case   						=		torch.cuda.is_available()

								_snake_case   						=		'not installed'
								_snake_case   						=		'NA'
								if is_tf_available():
									import tensorflow as tf

									_snake_case   						=		tf.__version__
									try:
										# deprecated in v2.1
										_snake_case   						=		tf.test.is_gpu_available()
									except AttributeError:
										# returns list of devices, convert to bool
										_snake_case   						=		bool(tf.config.list_physical_devices('GPU'  )  )

								_snake_case   						=		'not installed'
								_snake_case   						=		'not installed'
								_snake_case   						=		'not installed'
								_snake_case   						=		'NA'
								if is_flax_available():
									import flax
									import jax
									import jaxlib

									_snake_case   						=		flax.__version__
									_snake_case   						=		jax.__version__
									_snake_case   						=		jaxlib.__version__
									_snake_case   						=		jax.lib.xla_bridge.get_backend().platform

								_snake_case   						=		{
								    '`transformers` version': version,
								    'Platform': platform.platform(),
								    'Python version': platform.python_version(),
								    'Huggingface_hub version': huggingface_hub.__version__,
								    'Safetensors version': F'{safetensors_version}',
								    'Accelerate version': F'{accelerate_version}',
								    'Accelerate config': F'{accelerate_config_str}',
								    'PyTorch version (GPU?)': F'{pt_version} ({pt_cuda_available})',
								    'Tensorflow version (GPU?)': F'{tf_version} ({tf_cuda_available})',
								    'Flax version (CPU?/GPU?/TPU?)': F'{flax_version} ({jax_backend})',
								    'Jax version': F'{jax_version}',
								    'JaxLib version': F'{jaxlib_version}',
								    'Using GPU in script?': '<fill in>',
								    'Using distributed or parallel set-up in script?': '<fill in>',
								}

								print('\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n'  )
								print(self.format_dict(lowerCAmelCase_  )  )

								return info




							@staticmethod
							def  lowerCamelCase				(       lowerCAmelCase_  ):





								"""simple docstring"""






								return "\n".join([F'- {prop}: {val}' for prop, val in d.items()]  ) + "\n"



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

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







class        A_   (			__lowerCamelCase   ):




	'''simple docstring'''


	_UpperCamelCase     :     Optional[Any]							 =       """blip_2_vision_model"""





	def __init__(       self		,    snake_case=1408		,    snake_case=6144		,    snake_case=39		,    snake_case=16		,    snake_case=224		,    snake_case=14		,    snake_case="gelu"		,    snake_case=0.00_001		,    snake_case=0.0		,    snake_case=1E-10		,    snake_case=True		,    **snake_case		,    ):
		super().__init__(**snake_case       )

		lowercase       =    hidden_size
		lowercase       =    intermediate_size
		lowercase       =    num_hidden_layers
		lowercase       =    num_attention_heads
		lowercase       =    patch_size
		lowercase       =    image_size
		lowercase       =    initializer_range
		lowercase       =    attention_dropout
		lowercase       =    layer_norm_eps
		lowercase       =    hidden_act
		lowercase       =    qkv_bias





	@classmethod
	def 	SCREAMING_SNAKE_CASE__						(       cls		,    snake_case		,    **snake_case       ):
		cls._set_token_in_kwargs(snake_case       )

		lowercase  ,					lowercase       =    cls.get_config_dict(snake_case		,    **snake_case       )

		# get the vision config dict if we are loading from Blip2Config
		if config_dict.get('model_type'       ) == "blip-2":
			lowercase       =    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(snake_case		,    **snake_case       )







class        A_   (			__lowerCamelCase   ):




	'''simple docstring'''


	_UpperCamelCase     :     int							 =       """blip_2_qformer"""





	def __init__(       self		,    snake_case=3_0522		,    snake_case=768		,    snake_case=12		,    snake_case=12		,    snake_case=3072		,    snake_case="gelu"		,    snake_case=0.1		,    snake_case=0.1		,    snake_case=512		,    snake_case=0.02		,    snake_case=1E-12		,    snake_case=0		,    snake_case="absolute"		,    snake_case=2		,    snake_case=1408		,    **snake_case		,    ):
		super().__init__(pad_token_id=snake_case		,    **snake_case       )

		lowercase       =    vocab_size
		lowercase       =    hidden_size
		lowercase       =    num_hidden_layers
		lowercase       =    num_attention_heads
		lowercase       =    hidden_act
		lowercase       =    intermediate_size
		lowercase       =    hidden_dropout_prob
		lowercase       =    attention_probs_dropout_prob
		lowercase       =    max_position_embeddings
		lowercase       =    initializer_range
		lowercase       =    layer_norm_eps
		lowercase       =    position_embedding_type
		lowercase       =    cross_attention_frequency
		lowercase       =    encoder_hidden_size





	@classmethod
	def 	SCREAMING_SNAKE_CASE__						(       cls		,    snake_case		,    **snake_case       ):
		cls._set_token_in_kwargs(snake_case       )

		lowercase  ,					lowercase       =    cls.get_config_dict(snake_case		,    **snake_case       )

		# get the qformer config dict if we are loading from Blip2Config
		if config_dict.get('model_type'       ) == "blip-2":
			lowercase       =    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(snake_case		,    **snake_case       )







class        A_   (			__lowerCamelCase   ):




	'''simple docstring'''


	_UpperCamelCase     :     List[Any]							 =       """blip-2"""
	_UpperCamelCase     :     str							 =       True





	def __init__(       self		,    snake_case=None		,    snake_case=None		,    snake_case=None		,    snake_case=32		,    **snake_case       ):
		super().__init__(**snake_case       )

		if vision_config is None:
			lowercase       =    {}
			logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.'       )

		if qformer_config is None:
			lowercase       =    {}
			logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.'       )

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

		lowercase       =    BlipaVisionConfig(**snake_case       )
		lowercase       =    BlipaQFormerConfig(**snake_case       )
		lowercase       =    text_config['model_type'] if 'model_type' in text_config else 'opt'
		lowercase       =    CONFIG_MAPPING[text_model_type](**snake_case       )

		lowercase       =    self.text_config.tie_word_embeddings
		lowercase       =    self.text_config.is_encoder_decoder

		lowercase       =    num_query_tokens
		lowercase       =    self.vision_config.hidden_size
		lowercase       =    self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
		lowercase       =    1.0
		lowercase       =    0.02





	@classmethod
	def 	SCREAMING_SNAKE_CASE__						(       cls		,    snake_case		,    snake_case		,    snake_case		,    **snake_case		,    ):
		return cls(
		    vision_config=vision_config.to_dict()		,    qformer_config=qformer_config.to_dict()		,    text_config=text_config.to_dict()		,    **snake_case		,    )





	def 	SCREAMING_SNAKE_CASE__						(       self       ):
		lowercase       =    copy.deepcopy(self.__dict__       )
		lowercase       =    self.vision_config.to_dict()
		lowercase       =    self.qformer_config.to_dict()
		lowercase       =    self.text_config.to_dict()
		lowercase       =    self.__class__.model_type
		return output

