




"""simple docstring"""

from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import TensorType, logging


if TYPE_CHECKING:
		from ...onnx.config import PatchingSpec
		from ...tokenization_utils_base import PreTrainedTokenizerBase


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

_lowerCamelCase  :			Optional[Any]        =       {
    'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json',
    'allenai/longformer-large-4096': 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json',
    'allenai/longformer-large-4096-finetuned-triviaqa': (
        'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json'
    ),
    'allenai/longformer-base-4096-extra.pos.embd.only': (
        'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json'
    ),
    'allenai/longformer-large-4096-extra.pos.embd.only': (
        'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json'
    ),
}

class        lowercase      (    __UpperCAmelCase):
				__lowerCAmelCase    :    Optional[Any]         =   """longformer"""







				def __init__(							self   :					int      ,     _lowerCamelCase   :					Union[List[int], int] = 5_12      ,     _lowerCamelCase   :					int = 2      ,     _lowerCamelCase   :					int = 1      ,     _lowerCamelCase   :					int = 0      ,     _lowerCamelCase   :					int = 2      ,     _lowerCamelCase   :					int = 3_05_22      ,     _lowerCamelCase   :					int = 7_68      ,     _lowerCamelCase   :					int = 12      ,     _lowerCamelCase   :					int = 12      ,     _lowerCamelCase   :					int = 30_72      ,     _lowerCamelCase   :					str = "gelu"      ,     _lowerCamelCase   :					float = 0.1      ,     _lowerCamelCase   :					float = 0.1      ,     _lowerCamelCase   :					int = 5_12      ,     _lowerCamelCase   :					int = 2      ,     _lowerCamelCase   :					float = 0.02      ,     _lowerCamelCase   :					float = 1E-12      ,     _lowerCamelCase   :					bool = False      ,     **_lowerCamelCase   :					Any      ,     ):



					"""simple docstring"""

					super().__init__(pad_token_id=_lowerCamelCase      ,     **_lowerCamelCase       )

					A_  :				List[str]	   =		attention_window
					A_  :				int	   =		sep_token_id
					A_  :				str	   =		bos_token_id
					A_  :				List[Any]	   =		eos_token_id
					A_  :				int	   =		vocab_size
					A_  :				List[str]	   =		hidden_size
					A_  :				Dict	   =		num_hidden_layers
					A_  :				int	   =		num_attention_heads
					A_  :				Optional[Any]	   =		hidden_act
					A_  :				Tuple	   =		intermediate_size
					A_  :				str	   =		hidden_dropout_prob
					A_  :				Tuple	   =		attention_probs_dropout_prob
					A_  :				Optional[Any]	   =		max_position_embeddings
					A_  :				int	   =		type_vocab_size
					A_  :				str	   =		initializer_range
					A_  :				Optional[int]	   =		layer_norm_eps
					A_  :				Dict	   =		onnx_export

class        lowercase      (    __UpperCAmelCase):







				def __init__(							self   :					List[Any]      ,     _lowerCamelCase   :					"PretrainedConfig"      ,     _lowerCamelCase   :					str = "default"      ,     _lowerCamelCase   :					"List[PatchingSpec]" = None       ):



					"""simple docstring"""

					super().__init__(_lowerCamelCase      ,     _lowerCamelCase      ,     _lowerCamelCase       )
					A_  :				Any	   =		True







				@property
				def 					a_  (							self   :					Optional[int]       ):



					"""simple docstring"""

					if self.task == "multiple-choice":
						A_  :				Optional[int]	   =		{0: '''batch''', 1: '''choice''', 2: '''sequence'''}
					else:
						A_  :				int	   =		{0: '''batch''', 1: '''sequence'''}
					return OrderedDict(
					    [
					        ('''input_ids''', dynamic_axis),
					        ('''attention_mask''', dynamic_axis),
					        ('''global_attention_mask''', dynamic_axis),
					    ]       )







				@property
				def 					a_  (							self   :					Dict       ):



					"""simple docstring"""

					A_  :				Optional[int]	   =		super().outputs
					if self.task == "default":
						A_  :				Optional[int]	   =		{0: '''batch'''}
					return outputs







				@property
				def 					a_  (							self   :					Tuple       ):



					"""simple docstring"""

					return 1E-4







				@property
				def 					a_  (							self   :					int       ):



					"""simple docstring"""

					return max(super().default_onnx_opset      ,     14       )







				def 					a_  (							self   :					str      ,     _lowerCamelCase   :					"PreTrainedTokenizerBase"      ,     _lowerCamelCase   :					int = -1      ,     _lowerCamelCase   :					int = -1      ,     _lowerCamelCase   :					bool = False      ,     _lowerCamelCase   :					Optional[TensorType] = None      ,     ):



					"""simple docstring"""

					A_  :				int	   =		super().generate_dummy_inputs(
					    preprocessor=_lowerCamelCase      ,     batch_size=_lowerCamelCase      ,     seq_length=_lowerCamelCase      ,     is_pair=_lowerCamelCase      ,     framework=_lowerCamelCase       )
					import torch

					# for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64)
					# makes the export fail randomly
					A_  :				Dict	   =		torch.zeros_like(inputs['''input_ids''']       )
					# make every second token global
					A_  :				Union[str, Any]	   =		1

					return inputs











"""simple docstring"""

# 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


_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}"""	)





