




# 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


__SCREAMING_SNAKE_CASE 						="""Create a default config file for Accelerate with only a few flags set."""

def 			a   (_lowerCAmelCase="no"  ,    _lowerCAmelCase = default_json_config_file  ,    _lowerCAmelCase = False     ):
							SCREAMING_SNAKE_CASE_   	=    Path(_lowerCAmelCase     )
							path.parent.mkdir(parents=_lowerCAmelCase  ,    exist_ok=_lowerCAmelCase     )
							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
							SCREAMING_SNAKE_CASE_   	=    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}"     )
							SCREAMING_SNAKE_CASE_   	=    {
							    '''compute_environment''': '''LOCAL_MACHINE''',
							    '''mixed_precision''': mixed_precision,
							}
							if torch.cuda.is_available():
														SCREAMING_SNAKE_CASE_   	=    torch.cuda.device_count()
														SCREAMING_SNAKE_CASE_   	=    num_gpus
														SCREAMING_SNAKE_CASE_   	=    False
														if num_gpus > 1:
																					SCREAMING_SNAKE_CASE_   	=    '''MULTI_GPU'''
														else:
																					SCREAMING_SNAKE_CASE_   	=    '''NO'''
							elif is_xpu_available() and use_xpu:
														SCREAMING_SNAKE_CASE_   	=    torch.xpu.device_count()
														SCREAMING_SNAKE_CASE_   	=    num_xpus
														SCREAMING_SNAKE_CASE_   	=    False
														if num_xpus > 1:
																					SCREAMING_SNAKE_CASE_   	=    '''MULTI_XPU'''
														else:
																					SCREAMING_SNAKE_CASE_   	=    '''NO'''
							elif is_npu_available():
														SCREAMING_SNAKE_CASE_   	=    torch.npu.device_count()
														SCREAMING_SNAKE_CASE_   	=    num_npus
														SCREAMING_SNAKE_CASE_   	=    False
														if num_npus > 1:
																					SCREAMING_SNAKE_CASE_   	=    '''MULTI_NPU'''
														else:
																					SCREAMING_SNAKE_CASE_   	=    '''NO'''
							else:
														SCREAMING_SNAKE_CASE_   	=    0
														SCREAMING_SNAKE_CASE_   	=    True
														SCREAMING_SNAKE_CASE_   	=    1
														SCREAMING_SNAKE_CASE_   	=    '''NO'''
							SCREAMING_SNAKE_CASE_   	=    ClusterConfig(**_lowerCAmelCase     )
							config.to_json_file(_lowerCAmelCase     )
							return path

def 			a   (_lowerCAmelCase  ,    _lowerCAmelCase     ):
							SCREAMING_SNAKE_CASE_   	=    parser.add_parser('''default'''  ,    parents=_lowerCAmelCase  ,    help=_lowerCAmelCase  ,    formatter_class=_lowerCAmelCase     )
							parser.add_argument(
							    '''--config_file'''  ,    default=_lowerCAmelCase  ,    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=_lowerCAmelCase  ,    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=_lowerCAmelCase     )
							return parser






def 			a   (_lowerCAmelCase     ):
							SCREAMING_SNAKE_CASE_   	=    write_basic_config(args.mixed_precision  ,    args.save_location     )
							if config_file:
														print(F"accelerate configuration saved at {config_file}"     )








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


__SCREAMING_SNAKE_CASE 						=logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE 						={
    """google/realm-cc-news-pretrained-embedder""": (
        """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json"""
    ),
    """google/realm-cc-news-pretrained-encoder""": (
        """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json"""
    ),
    """google/realm-cc-news-pretrained-scorer""": (
        """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json"""
    ),
    """google/realm-cc-news-pretrained-openqa""": (
        """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json"""
    ),
    """google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json""",
    """google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json""",
    """google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json""",
    """google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json""",
    # See all REALM models at https://huggingface.co/models?filter=realm
}






class  __magic_name__						(  __UpperCAmelCase):
				'''simple docstring'''







				SCREAMING_SNAKE_CASE__					:							int	      =					"realm"


				def __init__(							self:   Tuple		,					_lowerCamelCase:   Union[str, Any]=3_05_22		,					_lowerCamelCase:   Tuple=7_68		,					_lowerCamelCase:   str=1_28		,					_lowerCamelCase:   str=12		,					_lowerCamelCase:   int=12		,					_lowerCamelCase:   Union[str, Any]=8		,					_lowerCamelCase:   Optional[Any]=30_72		,					_lowerCamelCase:   str="gelu_new"		,					_lowerCamelCase:   str=0.1		,					_lowerCamelCase:   Union[str, Any]=0.1		,					_lowerCamelCase:   Optional[int]=5_12		,					_lowerCamelCase:   Union[str, Any]=2		,					_lowerCamelCase:   int=0.02		,					_lowerCamelCase:   Tuple=1E-12		,					_lowerCamelCase:   List[Any]=2_56		,					_lowerCamelCase:   Any=10		,					_lowerCamelCase:   Optional[Any]=1E-3		,					_lowerCamelCase:   Any=5		,					_lowerCamelCase:   List[str]=3_20		,					_lowerCamelCase:   List[str]=13_35_37_18		,					_lowerCamelCase:   str=50_00		,					_lowerCamelCase:   str=1		,					_lowerCamelCase:   str=0		,					_lowerCamelCase:   Dict=2		,					**_lowerCamelCase:   Tuple		,					):
											super().__init__(pad_token_id=_lowerCamelCase		,					bos_token_id=_lowerCamelCase		,					eos_token_id=_lowerCamelCase		,					**_lowerCamelCase		)

											# Common config
											SCREAMING_SNAKE_CASE_   	=    vocab_size
											SCREAMING_SNAKE_CASE_   	=    max_position_embeddings
											SCREAMING_SNAKE_CASE_   	=    hidden_size
											SCREAMING_SNAKE_CASE_   	=    retriever_proj_size
											SCREAMING_SNAKE_CASE_   	=    num_hidden_layers
											SCREAMING_SNAKE_CASE_   	=    num_attention_heads
											SCREAMING_SNAKE_CASE_   	=    num_candidates
											SCREAMING_SNAKE_CASE_   	=    intermediate_size
											SCREAMING_SNAKE_CASE_   	=    hidden_act
											SCREAMING_SNAKE_CASE_   	=    hidden_dropout_prob
											SCREAMING_SNAKE_CASE_   	=    attention_probs_dropout_prob
											SCREAMING_SNAKE_CASE_   	=    initializer_range
											SCREAMING_SNAKE_CASE_   	=    type_vocab_size
											SCREAMING_SNAKE_CASE_   	=    layer_norm_eps

											# Reader config
											SCREAMING_SNAKE_CASE_   	=    span_hidden_size
											SCREAMING_SNAKE_CASE_   	=    max_span_width
											SCREAMING_SNAKE_CASE_   	=    reader_layer_norm_eps
											SCREAMING_SNAKE_CASE_   	=    reader_beam_size
											SCREAMING_SNAKE_CASE_   	=    reader_seq_len

											# Retrieval config
											SCREAMING_SNAKE_CASE_   	=    num_block_records
											SCREAMING_SNAKE_CASE_   	=    searcher_beam_size


