


import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase__  :Union[str, Any]             =							logging.get_logger(__name__)

lowerCAmelCase__  :str             =							{
    '''BAAI/AltCLIP''': '''https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json''',
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}

class 		__a				(    UpperCAmelCase      ):
		_a     :  int           =     'altclip_text_model'
		def __init__(      self      ,   _SCREAMING_SNAKE_CASE=250002      ,   _SCREAMING_SNAKE_CASE=1024      ,   _SCREAMING_SNAKE_CASE=24      ,   _SCREAMING_SNAKE_CASE=16      ,   _SCREAMING_SNAKE_CASE=4096      ,   _SCREAMING_SNAKE_CASE="gelu"      ,   _SCREAMING_SNAKE_CASE=0.1      ,   _SCREAMING_SNAKE_CASE=0.1      ,   _SCREAMING_SNAKE_CASE=514      ,   _SCREAMING_SNAKE_CASE=1      ,   _SCREAMING_SNAKE_CASE=0.02      ,   _SCREAMING_SNAKE_CASE=0.02      ,   _SCREAMING_SNAKE_CASE=1e-0_5      ,   _SCREAMING_SNAKE_CASE=1      ,   _SCREAMING_SNAKE_CASE=0      ,   _SCREAMING_SNAKE_CASE=2      ,   _SCREAMING_SNAKE_CASE="absolute"      ,   _SCREAMING_SNAKE_CASE=True      ,   _SCREAMING_SNAKE_CASE=768      ,   **_SCREAMING_SNAKE_CASE      ,   )			->	Optional[Any]:




									"""simple docstring"""





									super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE      ,   bos_token_id=_SCREAMING_SNAKE_CASE      ,   eos_token_id=_SCREAMING_SNAKE_CASE      ,   **_SCREAMING_SNAKE_CASE						)

									_UpperCAmelCase					=      vocab_size
									_UpperCAmelCase					=      hidden_size
									_UpperCAmelCase					=      num_hidden_layers
									_UpperCAmelCase					=      num_attention_heads
									_UpperCAmelCase					=      hidden_act
									_UpperCAmelCase					=      intermediate_size
									_UpperCAmelCase					=      hidden_dropout_prob
									_UpperCAmelCase					=      attention_probs_dropout_prob
									_UpperCAmelCase					=      max_position_embeddings
									_UpperCAmelCase					=      type_vocab_size
									_UpperCAmelCase					=      initializer_range
									_UpperCAmelCase					=      initializer_factor
									_UpperCAmelCase					=      layer_norm_eps
									_UpperCAmelCase					=      position_embedding_type
									_UpperCAmelCase					=      use_cache
									_UpperCAmelCase					=      project_dim



class 		__a				(    UpperCAmelCase      ):
		_a     :  Optional[Any]           =     'altclip_vision_model'
		def __init__(      self      ,   _SCREAMING_SNAKE_CASE=768      ,   _SCREAMING_SNAKE_CASE=3072      ,   _SCREAMING_SNAKE_CASE=512      ,   _SCREAMING_SNAKE_CASE=12      ,   _SCREAMING_SNAKE_CASE=12      ,   _SCREAMING_SNAKE_CASE=3      ,   _SCREAMING_SNAKE_CASE=224      ,   _SCREAMING_SNAKE_CASE=32      ,   _SCREAMING_SNAKE_CASE="quick_gelu"      ,   _SCREAMING_SNAKE_CASE=1e-5      ,   _SCREAMING_SNAKE_CASE=0.0      ,   _SCREAMING_SNAKE_CASE=0.02      ,   _SCREAMING_SNAKE_CASE=1.0      ,   **_SCREAMING_SNAKE_CASE      ,   )			->	Optional[Any]:




									"""simple docstring"""





									super().__init__(**_SCREAMING_SNAKE_CASE						)

									_UpperCAmelCase					=      hidden_size
									_UpperCAmelCase					=      intermediate_size
									_UpperCAmelCase					=      projection_dim
									_UpperCAmelCase					=      num_hidden_layers
									_UpperCAmelCase					=      num_attention_heads
									_UpperCAmelCase					=      num_channels
									_UpperCAmelCase					=      patch_size
									_UpperCAmelCase					=      image_size
									_UpperCAmelCase					=      initializer_range
									_UpperCAmelCase					=      initializer_factor
									_UpperCAmelCase					=      attention_dropout
									_UpperCAmelCase					=      layer_norm_eps
									_UpperCAmelCase					=      hidden_act






		@classmethod
		def      UpperCAmelCase__    (      cls      ,   _SCREAMING_SNAKE_CASE      ,   **_SCREAMING_SNAKE_CASE						)			->	"PretrainedConfig":




									"""simple docstring"""





									cls._set_token_in_kwargs(_SCREAMING_SNAKE_CASE						)

									_UpperCAmelCase		,	_UpperCAmelCase					=      cls.get_config_dict(_SCREAMING_SNAKE_CASE      ,   **_SCREAMING_SNAKE_CASE						)

									# get the vision config dict if we are loading from AltCLIPConfig
									if config_dict.get('model_type'						) == "altclip":
																_UpperCAmelCase					=      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(_SCREAMING_SNAKE_CASE      ,   **_SCREAMING_SNAKE_CASE						)



class 		__a				(    UpperCAmelCase      ):
		_a     :  int           =     'altclip'
		_a     :  Optional[int]           =     True
		def __init__(      self      ,   _SCREAMING_SNAKE_CASE=None      ,   _SCREAMING_SNAKE_CASE=None      ,   _SCREAMING_SNAKE_CASE=768      ,   _SCREAMING_SNAKE_CASE=2.6592      ,   **_SCREAMING_SNAKE_CASE						)			->	Optional[Any]:




									"""simple docstring"""





									_UpperCAmelCase					=      kwargs.pop('text_config_dict'      ,   _SCREAMING_SNAKE_CASE						)
									_UpperCAmelCase					=      kwargs.pop('vision_config_dict'      ,   _SCREAMING_SNAKE_CASE						)

									super().__init__(**_SCREAMING_SNAKE_CASE						)

									# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
									# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
									# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
									if text_config_dict is not None:
																if text_config is None:
																							_UpperCAmelCase					=      {}

																# This is the complete result when using `text_config_dict`.
																_UpperCAmelCase					=      AltCLIPTextConfig(**_SCREAMING_SNAKE_CASE						).to_dict()

																# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
																for key, value in _text_config_dict.items():
																							if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
																														# If specified in `text_config_dict`
																														if key in text_config_dict:
																																					_UpperCAmelCase					=      (
																																					    f'''`{key}` is found in both `text_config_dict` and `text_config` but with different values. '''
																																					    f'''The value `text_config_dict["{key}"]` will be used instead.'''
																																					)
																														# If inferred from default argument values (just to be super careful)
																														else:
																																					_UpperCAmelCase					=      (
																																					    f'''`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The '''
																																					    f'''value `text_config["{key}"]` will be overriden.'''
																																					)
																														logger.warning(_SCREAMING_SNAKE_CASE						)

            # Update all values in `text_config` with the ones in `_text_config_dict`.
																text_config.update(_text_config_dict						)

									if vision_config_dict is not None:
																if vision_config is None:
																							_UpperCAmelCase					=      {}

																# This is the complete result when using `vision_config_dict`.
																_UpperCAmelCase					=      AltCLIPVisionConfig(**_SCREAMING_SNAKE_CASE						).to_dict()
																# convert keys to string instead of integer
																if "id2label" in _vision_config_dict:
																							_UpperCAmelCase					=      {
																							    str(_SCREAMING_SNAKE_CASE						): value for key, value in _vision_config_dict['id2label'].items()
																							}

																# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
																for key, value in _vision_config_dict.items():
																							if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
																														# If specified in `vision_config_dict`
																														if key in vision_config_dict:
																																					_UpperCAmelCase					=      (
																																					    f'''`{key}` is found in both `vision_config_dict` and `vision_config` but with different '''
																																					    f'''values. The value `vision_config_dict["{key}"]` will be used instead.'''
																																					)
																														# If inferred from default argument values (just to be super careful)
																														else:
																																					_UpperCAmelCase					=      (
																																					    f'''`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. '''
																																					    f'''The value `vision_config["{key}"]` will be overriden.'''
																																					)
																														logger.warning(_SCREAMING_SNAKE_CASE						)

            # Update all values in `vision_config` with the ones in `_vision_config_dict`.
																vision_config.update(_vision_config_dict						)

									if text_config is None:
																_UpperCAmelCase					=      {}
																logger.info('`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.'						)

									if vision_config is None:
																_UpperCAmelCase					=      {}
																logger.info('`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.'						)

									_UpperCAmelCase					=      AltCLIPTextConfig(**_SCREAMING_SNAKE_CASE						)
									_UpperCAmelCase					=      AltCLIPVisionConfig(**_SCREAMING_SNAKE_CASE						)

									_UpperCAmelCase					=      projection_dim
									_UpperCAmelCase					=      logit_scale_init_value
									_UpperCAmelCase					=      1.0
		@classmethod
		def      UpperCAmelCase__    (      cls      ,   _SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE      ,   **_SCREAMING_SNAKE_CASE						)			->	Any:




									"""simple docstring"""





									return cls(text_config=text_config.to_dict()      ,   vision_config=vision_config.to_dict()      ,   **_SCREAMING_SNAKE_CASE						)






		def      UpperCAmelCase__    (      self						)			->	Dict:




									"""simple docstring"""





									_UpperCAmelCase					=      copy.deepcopy(self.__dict__						)
									_UpperCAmelCase					=      self.text_config.to_dict()
									_UpperCAmelCase					=      self.vision_config.to_dict()
									_UpperCAmelCase					=      self.__class__.model_type
									return output




# Copyright 2022 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.

import argparse
import os
import subprocess

from packaging.version import Version, parse

from accelerate.commands.config.config_args import default_config_file, load_config_from_file


lowerCAmelCase__  :Dict             =							'''Run commands across TPU VMs for initial setup before running `accelerate launch`.'''

def 	lowerCAmelCase__			(      a__:		Optional[Any]=None	)  ->		List[Any]:


							'''simple docstring'''





							if subparsers is not None:
														_UpperCAmelCase					=      subparsers.add_parser('tpu-config'      ,  description=_description	)
							else:
														_UpperCAmelCase					=      argparse.ArgumentParser('Accelerate tpu-config command'      ,  description=_description	)
							# Core arguments
							_UpperCAmelCase					=      parser.add_argument_group(
							    'Config Arguments'      ,  'Arguments that can be configured through `accelerate config`.'	)
							config_args.add_argument(
							    '--config_file'      ,  type=a__      ,  default=a__      ,  help='Path to the config file to use for accelerate.'      ,  )
							config_args.add_argument(
							    '--tpu_name'      ,  default=a__      ,  help='The name of the TPU to use. If not specified, will use the TPU specified in the config file.'      ,  )
							config_args.add_argument(
							    '--tpu_zone'      ,  default=a__      ,  help='The zone of the TPU to use. If not specified, will use the zone specified in the config file.'      ,  )
							_UpperCAmelCase					=      parser.add_argument_group('TPU Arguments'      ,  'Arguments for options ran inside the TPU.'	)
							pod_args.add_argument(
							    '--use_alpha'      ,  action='store_true'      ,  help='Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.'      ,  )
							pod_args.add_argument(
							    '--command_file'      ,  default=a__      ,  help='The path to the file containing the commands to run on the pod on startup.'      ,  )
							pod_args.add_argument(
							    '--command'      ,  action='append'      ,  nargs='+'      ,  help='A command to run on the pod. Can be passed multiple times.'      ,  )
							pod_args.add_argument(
							    '--install_accelerate'      ,  action='store_true'      ,  help='Whether to install accelerate on the pod. Defaults to False.'      ,  )
							pod_args.add_argument(
							    '--accelerate_version'      ,  default='latest'      ,  help='The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.'      ,  )
							pod_args.add_argument(
							    '--debug'      ,  action='store_true'      ,  help='If set, will print the command that would be run instead of running it.'	)

							if subparsers is not None:
														parser.set_defaults(func=a__	)
							return parser

def 	lowerCAmelCase__			(      a__:		str	)  ->		Any:


							'''simple docstring'''





							_UpperCAmelCase					=      None

							# Get the default from the config file if it exists.
							if args.config_file is not None or os.path.isfile(a__	):
														_UpperCAmelCase					=      load_config_from_file(args.config_file	)
														if not args.command_file and defaults.command_file is not None and not args.command:
																					_UpperCAmelCase					=      defaults.command_file
														if not args.command and defaults.commands is not None:
																					_UpperCAmelCase					=      defaults.commands
														if not args.tpu_name:
																					_UpperCAmelCase					=      defaults.tpu_name
														if not args.tpu_zone:
																					_UpperCAmelCase					=      defaults.tpu_zone
							if args.accelerate_version == "dev":
														_UpperCAmelCase					=      'git+https://github.com/huggingface/accelerate.git'
							elif args.accelerate_version == "latest":
														_UpperCAmelCase					=      'accelerate -U'
							elif isinstance(parse(args.accelerate_version	)      ,  a__	):
														_UpperCAmelCase					=      F'''accelerate=={args.accelerate_version}'''

							if not args.command_file and not args.command:
														raise ValueError('You must specify either a command file or a command to run on the pod.'	)

							if args.command_file:
														with open(args.command_file      ,  'r'	) as f:
																					_UpperCAmelCase					=      [f.read().splitlines()]

    # To turn list of lists into list of strings
							if isinstance(args.command[0]      ,  a__	):
														_UpperCAmelCase					=      [line for cmd in args.command for line in cmd]
							# Default to the shared folder and install accelerate
							_UpperCAmelCase					=      ['cd /usr/share']
							if args.install_accelerate:
														new_cmd += [F'''pip install {args.accelerate_version}''']
							new_cmd += args.command
							_UpperCAmelCase					=      '; '.join(a__	)

							# Then send it to gcloud
							# Eventually try to use google-api-core to do this instead of subprocess
							_UpperCAmelCase					=      ['gcloud']
							if args.use_alpha:
														cmd += ["alpha"]
							cmd += [
							    "compute",
							    "tpus",
							    "tpu-vm",
							    "ssh",
							    args.tpu_name,
							    "--zone",
							    args.tpu_zone,
							    "--command",
							    args.command,
							    "--worker",
							    "all",
							]
							if args.debug:
														print(F'''Running {" ".join(a__	)}'''	)
														return
							subprocess.run(a__	)
							print('Successfully setup pod.'	)







def 	lowerCAmelCase__			(      )  ->		Optional[Any]:


							'''simple docstring'''





							_UpperCAmelCase					=      tpu_command_parser()
							_UpperCAmelCase					=      parser.parse_args()

							tpu_command_launcher(a__	)
