





from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...file_utils import TensorType, is_torch_available
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging


UpperCAmelCase_   				=  logging.get_logger(__name__)

UpperCAmelCase_   				=  {
    """facebook/blenderbot-3B""": """https://huggingface.co/facebook/blenderbot-3B/resolve/main/config.json""",
    # See all Blenderbot models at https://huggingface.co/models?filter=blenderbot
}
class       UpperCamelCase_		(	_lowerCamelCase       ):
					lowerCAmelCase_				=						'''blenderbot'''
					lowerCAmelCase_				=						['''past_key_values''']
					lowerCAmelCase_				=						{'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''}




					def __init__(		self					,    lowerCAmelCase_=8008					,    lowerCAmelCase_=128					,    lowerCAmelCase_=2					,    lowerCAmelCase_=1_0240					,    lowerCAmelCase_=32					,    lowerCAmelCase_=24					,    lowerCAmelCase_=1_0240					,    lowerCAmelCase_=32					,    lowerCAmelCase_=0.0					,    lowerCAmelCase_=0.0					,    lowerCAmelCase_=True					,    lowerCAmelCase_=True					,    lowerCAmelCase_="gelu"					,    lowerCAmelCase_=2560					,    lowerCAmelCase_=0.1					,    lowerCAmelCase_=0.0					,    lowerCAmelCase_=0.0					,    lowerCAmelCase_=0.02					,    lowerCAmelCase_=1					,    lowerCAmelCase_=False					,    lowerCAmelCase_=0					,    lowerCAmelCase_=1					,    lowerCAmelCase_=2					,    lowerCAmelCase_=3					,    lowerCAmelCase_=2					,    **lowerCAmelCase_					,    )		->				Optional[int]:
										_snake_case						=					vocab_size
										_snake_case						=					max_position_embeddings
										_snake_case						=					d_model
										_snake_case						=					encoder_ffn_dim
										_snake_case						=					encoder_layers
										_snake_case						=					encoder_attention_heads
										_snake_case						=					decoder_ffn_dim
										_snake_case						=					decoder_layers
										_snake_case						=					decoder_attention_heads
										_snake_case						=					dropout
										_snake_case						=					attention_dropout
										_snake_case						=					activation_dropout
										_snake_case						=					activation_function
										_snake_case						=					init_std
										_snake_case						=					encoder_layerdrop
										_snake_case						=					decoder_layerdrop
										_snake_case						=					use_cache
										_snake_case						=					encoder_layers
										_snake_case						=					scale_embedding  # scale factor will be sqrt(d_model) if True

										super().__init__(
										    pad_token_id=lowerCAmelCase_					,    bos_token_id=lowerCAmelCase_					,    eos_token_id=lowerCAmelCase_					,    is_encoder_decoder=lowerCAmelCase_					,    decoder_start_token_id=lowerCAmelCase_					,    encoder_no_repeat_ngram_size=lowerCAmelCase_					,    forced_eos_token_id=lowerCAmelCase_					,    **lowerCAmelCase_					,    )





class       UpperCamelCase_		(	_lowerCamelCase       ):




					@property
					def 						lowerCAmelCase      (		self	)		->				Mapping[str, Mapping[int, str]]:
										if self.task in ["default", "seq2seq-lm"]:
															_snake_case						=					OrderedDict(
															    [
															        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
															        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
															    ]	)
															if self.use_past:
																				_snake_case						=					{0: 'batch'}
																				_snake_case						=					{0: 'batch', 1: 'past_decoder_sequence + sequence'}
															else:
																				_snake_case						=					{0: 'batch', 1: 'decoder_sequence'}
																				_snake_case						=					{0: 'batch', 1: 'decoder_sequence'}
															if self.use_past:
																				self.fill_with_past_key_values_(lowerCAmelCase_					,    direction='inputs'	)
										elif self.task == "causal-lm":
															_snake_case						=					OrderedDict(
															    [
															        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
															        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
															    ]	)
															if self.use_past:
																				_snake_case				,  _snake_case						=					self.num_layers
																				for i in range(lowerCAmelCase_	):
																									_snake_case						=					{0: 'batch', 2: 'past_sequence + sequence'}
																									_snake_case						=					{0: 'batch', 2: 'past_sequence + sequence'}
										else:
															_snake_case						=					OrderedDict(
															    [
															        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
															        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
															        ('decoder_input_ids', {0: 'batch', 1: 'decoder_sequence'}),
															        ('decoder_attention_mask', {0: 'batch', 1: 'decoder_sequence'}),
															    ]	)

										return common_inputs




					@property
					# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
					def 						lowerCAmelCase      (		self	)		->				Mapping[str, Mapping[int, str]]:
										if self.task in ["default", "seq2seq-lm"]:
															_snake_case						=					super().outputs
										else:
															_snake_case						=					super(lowerCAmelCase_					,    self	).outputs
															if self.use_past:
																				_snake_case				,  _snake_case						=					self.num_layers
																				for i in range(lowerCAmelCase_	):
																									_snake_case						=					{0: 'batch', 2: 'past_sequence + sequence'}
																									_snake_case						=					{0: 'batch', 2: 'past_sequence + sequence'}
										return common_outputs




					def 						lowerCAmelCase      (		self					,    lowerCAmelCase_					,    lowerCAmelCase_ = -1					,    lowerCAmelCase_ = -1					,    lowerCAmelCase_ = False					,    lowerCAmelCase_ = None					,    )		->				Mapping[str, Any]:
										_snake_case						=					self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
										    lowerCAmelCase_					,    lowerCAmelCase_					,    lowerCAmelCase_					,    lowerCAmelCase_					,    lowerCAmelCase_	)
										# Generate decoder inputs
										_snake_case						=					seq_length if not self.use_past else 1
										_snake_case						=					self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
										    lowerCAmelCase_					,    lowerCAmelCase_					,    lowerCAmelCase_					,    lowerCAmelCase_					,    lowerCAmelCase_	)
										_snake_case						=					{F'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()}
										_snake_case						=					dict(**lowerCAmelCase_					,    **lowerCAmelCase_	)

										if self.use_past:
															if not is_torch_available():
																				raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'	)
															else:
																				import torch
															_snake_case				,  _snake_case						=					common_inputs['input_ids'].shape
															_snake_case						=					common_inputs['decoder_input_ids'].shape[1]
															_snake_case				,  _snake_case						=					self.num_attention_heads
															_snake_case						=					(
															    batch,
															    num_encoder_attention_heads,
															    encoder_seq_length,
															    self._config.hidden_size // num_encoder_attention_heads,
															)
															_snake_case						=					decoder_seq_length
															_snake_case						=					(
															    batch,
															    num_decoder_attention_heads,
															    decoder_past_length,
															    self._config.hidden_size // num_decoder_attention_heads,
															)
															_snake_case						=					torch.cat(
															    [common_inputs['decoder_attention_mask'], torch.ones(lowerCAmelCase_					,    lowerCAmelCase_	)]					,    dim=1	)
															_snake_case						=					[]
															_snake_case				,  _snake_case						=					self.num_layers

															for _ in range(lowerCAmelCase_	):
																				common_inputs["past_key_values"].append(
																				    (
																				        torch.zeros(lowerCAmelCase_	),
																				        torch.zeros(lowerCAmelCase_	),
																				        torch.zeros(lowerCAmelCase_	),
																				        torch.zeros(lowerCAmelCase_	),
																				    )	)
										return common_inputs




					def 						lowerCAmelCase      (		self					,    lowerCAmelCase_					,    lowerCAmelCase_ = -1					,    lowerCAmelCase_ = -1					,    lowerCAmelCase_ = False					,    lowerCAmelCase_ = None					,    )		->				Mapping[str, Any]:
										_snake_case						=					self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
										    lowerCAmelCase_					,    lowerCAmelCase_					,    lowerCAmelCase_					,    lowerCAmelCase_					,    lowerCAmelCase_	)

										if self.use_past:
															if not is_torch_available():
																				raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'	)
															else:
																				import torch
															_snake_case				,  _snake_case						=					common_inputs['input_ids'].shape
															_snake_case						=					seqlen
															_snake_case				,  _snake_case						=					self.num_layers
															_snake_case				,  _snake_case						=					self.num_attention_heads
															_snake_case						=					(
															    batch,
															    num_encoder_attention_heads,
															    past_key_values_length,
															    self._config.hidden_size // num_encoder_attention_heads,
															)
															_snake_case						=					common_inputs['attention_mask'].dtype
															_snake_case						=					torch.cat(
															    [common_inputs['attention_mask'], torch.ones(lowerCAmelCase_					,    lowerCAmelCase_					,    dtype=lowerCAmelCase_	)]					,    dim=1	)
															_snake_case						=					[
															    (torch.zeros(lowerCAmelCase_	), torch.zeros(lowerCAmelCase_	)) for _ in range(lowerCAmelCase_	)
															]
										return common_inputs




					def 						lowerCAmelCase      (		self					,    lowerCAmelCase_					,    lowerCAmelCase_ = -1					,    lowerCAmelCase_ = -1					,    lowerCAmelCase_ = False					,    lowerCAmelCase_ = None					,    )		->				Mapping[str, Any]:
										# Copied from OnnxConfig.generate_dummy_inputs
										# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
										# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
										_snake_case						=					compute_effective_axis_dimension(
										    lowerCAmelCase_					,    fixed_dimension=OnnxConfig.default_fixed_batch					,    num_token_to_add=0	)

										# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
										_snake_case						=					tokenizer.num_special_tokens_to_add(lowerCAmelCase_	)
										_snake_case						=					compute_effective_axis_dimension(
										    lowerCAmelCase_					,    fixed_dimension=OnnxConfig.default_fixed_sequence					,    num_token_to_add=lowerCAmelCase_	)

										# Generate dummy inputs according to compute batch and sequence
										_snake_case						=					[' '.join([tokenizer.unk_token]	) * seq_length] * batch_size
										_snake_case						=					dict(tokenizer(lowerCAmelCase_					,    return_tensors=lowerCAmelCase_	)	)
										return common_inputs




					def 						lowerCAmelCase      (		self					,    lowerCAmelCase_					,    lowerCAmelCase_ = -1					,    lowerCAmelCase_ = -1					,    lowerCAmelCase_ = False					,    lowerCAmelCase_ = None					,    )		->				Mapping[str, Any]:
										if self.task in ["default", "seq2seq-lm"]:
															_snake_case						=					self._generate_dummy_inputs_for_default_and_seqaseq_lm(
															    lowerCAmelCase_					,    batch_size=lowerCAmelCase_					,    seq_length=lowerCAmelCase_					,    is_pair=lowerCAmelCase_					,    framework=lowerCAmelCase_	)

										elif self.task == "causal-lm":
															_snake_case						=					self._generate_dummy_inputs_for_causal_lm(
															    lowerCAmelCase_					,    batch_size=lowerCAmelCase_					,    seq_length=lowerCAmelCase_					,    is_pair=lowerCAmelCase_					,    framework=lowerCAmelCase_	)
										else:
															_snake_case						=					self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
															    lowerCAmelCase_					,    batch_size=lowerCAmelCase_					,    seq_length=lowerCAmelCase_					,    is_pair=lowerCAmelCase_					,    framework=lowerCAmelCase_	)

										return common_inputs




					def 						lowerCAmelCase      (		self					,    lowerCAmelCase_					,    lowerCAmelCase_					,    lowerCAmelCase_					,    lowerCAmelCase_	)		->				List[Any]:
										if self.task in ["default", "seq2seq-lm"]:
															_snake_case						=					super()._flatten_past_key_values_(lowerCAmelCase_					,    lowerCAmelCase_					,    lowerCAmelCase_					,    lowerCAmelCase_	)
										else:
															_snake_case						=					super(lowerCAmelCase_					,    self	)._flatten_past_key_values_(
															    lowerCAmelCase_					,    lowerCAmelCase_					,    lowerCAmelCase_					,    lowerCAmelCase_	)






					def 						lowerCAmelCase      (		self					,    lowerCAmelCase_					,    lowerCAmelCase_	)		->				Tuple:
										if direction not in ["inputs", "outputs"]:
															raise ValueError(F'''direction must either be "inputs" or "outputs", but {direction} was given'''	)

										_snake_case						=					'past_key_values' if direction == 'inputs' else 'present'
										_snake_case				,  _snake_case						=					self.num_layers

										_snake_case						=					'past_encoder_sequence'
										_snake_case						=					'past_decoder_sequence' if direction == 'inputs' else 'past_decoder_sequence + sequence'

										for i in range(lowerCAmelCase_	):
															_snake_case						=					{0: 'batch', 2: decoder_sequence}
															_snake_case						=					{0: 'batch', 2: decoder_sequence}
															_snake_case						=					{0: 'batch', 2: encoder_sequence}
															_snake_case						=					{0: 'batch', 2: encoder_sequence}










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

import json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


UpperCAmelCase_   				=  os.path.expanduser(
    os.getenv("""HF_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """huggingface"""))
)
UpperCAmelCase_   				=  os.path.join(hf_cache_home, """accelerate""")
UpperCAmelCase_   				=  os.path.join(cache_dir, """default_config.yaml""")
UpperCAmelCase_   				=  os.path.join(cache_dir, """default_config.yaml""")

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
					UpperCAmelCase_   				=  default_yaml_config_file
else:
					UpperCAmelCase_   				=  default_json_config_file





def     lowerCamelCase__  (  UpperCamelCase__      :							List[str]    )      ->			str:



					'''simple docstring'''




					if config_file is not None:
										if not os.path.isfile(UpperCamelCase__    ):
															raise FileNotFoundError(
															    F'''The passed configuration file `{config_file}` does not exist. '''
															    'Please pass an existing file to `accelerate launch`, or use the the default one '
															    'created through `accelerate config` and run `accelerate launch` '
															    'without the `--config_file` argument.'    )
					else:
										_snake_case						=					default_config_file
					with open(UpperCamelCase__							,     'r'							,     encoding='utf-8'    ) as f:
										if config_file.endswith('.json'    ):
															if (
															    json.load(UpperCamelCase__    ).get('compute_environment'							,     ComputeEnvironment.LOCAL_MACHINE    )
															    == ComputeEnvironment.LOCAL_MACHINE
															):
																				_snake_case						=					ClusterConfig
															else:
																				_snake_case						=					SageMakerConfig
															return config_class.from_json_file(json_file=UpperCamelCase__    )
										else:
															if (
															    yaml.safe_load(UpperCamelCase__    ).get('compute_environment'							,     ComputeEnvironment.LOCAL_MACHINE    )
															    == ComputeEnvironment.LOCAL_MACHINE
															):
																				_snake_case						=					ClusterConfig
															else:
																				_snake_case						=					SageMakerConfig
															return config_class.from_yaml_file(yaml_file=UpperCamelCase__    )
@dataclass
class       UpperCamelCase_		:
					lowerCAmelCase_				=						42
					lowerCAmelCase_				=						42
					lowerCAmelCase_				=						42
					lowerCAmelCase_				=						42




					def 						lowerCAmelCase      (		self	)		->				Optional[Any]:
										_snake_case						=					self.__dict__
										# For serialization, it's best to convert Enums to strings (or their underlying value type).
										for key, value in result.items():
															if isinstance(lowerCAmelCase_					,    lowerCAmelCase_	):
																				_snake_case						=					value.value
															if isinstance(lowerCAmelCase_					,    lowerCAmelCase_	) and not bool(lowerCAmelCase_	):
																				_snake_case						=					None
										_snake_case						=					{k: v for k, v in result.items() if v is not None}
										return result




					@classmethod
					def 						lowerCAmelCase      (		cls					,    lowerCAmelCase_=None	)		->				List[Any]:
										_snake_case						=					default_json_config_file if json_file is None else json_file
										with open(lowerCAmelCase_					,    'r'					,    encoding='utf-8'	) as f:
															_snake_case						=					json.load(lowerCAmelCase_	)
										if "compute_environment" not in config_dict:
															_snake_case						=					ComputeEnvironment.LOCAL_MACHINE
										if "mixed_precision" not in config_dict:
															_snake_case						=					'fp16' if ('fp16' in config_dict and config_dict['fp16']) else None
										if "fp16" in config_dict:  # Convert the config to the new format.
															del config_dict["fp16"]
										if "dynamo_backend" in config_dict:  # Convert the config to the new format.
															_snake_case						=					config_dict.pop('dynamo_backend'	)
															_snake_case						=					{} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
										if "use_cpu" not in config_dict:
															_snake_case						=					False
										return cls(**lowerCAmelCase_	)




					def 						lowerCAmelCase      (		self					,    lowerCAmelCase_	)		->				List[str]:
										with open(lowerCAmelCase_					,    'w'					,    encoding='utf-8'	) as f:
															_snake_case						=					json.dumps(self.to_dict()					,    indent=2					,    sort_keys=lowerCAmelCase_	) + '\n'
															f.write(lowerCAmelCase_	)




					@classmethod
					def 						lowerCAmelCase      (		cls					,    lowerCAmelCase_=None	)		->				int:
										_snake_case						=					default_yaml_config_file if yaml_file is None else yaml_file
										with open(lowerCAmelCase_					,    'r'					,    encoding='utf-8'	) as f:
															_snake_case						=					yaml.safe_load(lowerCAmelCase_	)
										if "compute_environment" not in config_dict:
															_snake_case						=					ComputeEnvironment.LOCAL_MACHINE

										if "mixed_precision" not in config_dict:
															_snake_case						=					'fp16' if ('fp16' in config_dict and config_dict['fp16']) else None
										if isinstance(config_dict['mixed_precision']					,    lowerCAmelCase_	) and not config_dict["mixed_precision"]:
															_snake_case						=					'no'
										if "fp16" in config_dict:  # Convert the config to the new format.
															del config_dict["fp16"]
										if "dynamo_backend" in config_dict:  # Convert the config to the new format.
															_snake_case						=					config_dict.pop('dynamo_backend'	)
															_snake_case						=					{} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
										if "use_cpu" not in config_dict:
															_snake_case						=					False
										return cls(**lowerCAmelCase_	)




					def 						lowerCAmelCase      (		self					,    lowerCAmelCase_	)		->				List[str]:
										with open(lowerCAmelCase_					,    'w'					,    encoding='utf-8'	) as f:
															yaml.safe_dump(self.to_dict()					,    lowerCAmelCase_	)






					def 						lowerCAmelCase      (		self	)		->				Tuple:
										if isinstance(self.compute_environment					,    lowerCAmelCase_	):
															_snake_case						=					ComputeEnvironment(self.compute_environment	)
										if isinstance(self.distributed_type					,    lowerCAmelCase_	):
															if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
																				_snake_case						=					SageMakerDistributedType(self.distributed_type	)
															else:
																				_snake_case						=					DistributedType(self.distributed_type	)
										if self.dynamo_config is None:
															_snake_case						=					{}





@dataclass
class       UpperCamelCase_		(	_lowerCamelCase       ):
					lowerCAmelCase_				=						42
					lowerCAmelCase_				=						0
					lowerCAmelCase_				=						1
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						"static"
					lowerCAmelCase_				=						False
					lowerCAmelCase_				=						"main"

					# args for deepspeed_plugin
					lowerCAmelCase_				=						None
					# args for fsdp
					lowerCAmelCase_				=						None
					# args for megatron_lm
					lowerCAmelCase_				=						None
					# args for ipex
					lowerCAmelCase_				=						None
					# args for TPU
					lowerCAmelCase_				=						False

					# args for TPU pods
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						False
					lowerCAmelCase_				=						False
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None

					# args for dynamo
					lowerCAmelCase_				=						None




					def 						lowerCAmelCase      (		self	)		->				Optional[Any]:
										if self.deepspeed_config is None:
															_snake_case						=					{}
										if self.fsdp_config is None:
															_snake_case						=					{}
										if self.megatron_lm_config is None:
															_snake_case						=					{}
										if self.ipex_config is None:
															_snake_case						=					{}
										return super().__post_init__()





@dataclass
class       UpperCamelCase_		(	_lowerCamelCase       ):
					lowerCAmelCase_				=						42
					lowerCAmelCase_				=						42
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						"us-east-1"
					lowerCAmelCase_				=						1
					lowerCAmelCase_				=						"all"
					lowerCAmelCase_				=						f"accelerate-sagemaker-{num_machines}"
					lowerCAmelCase_				=						SAGEMAKER_PYTORCH_VERSION
					lowerCAmelCase_				=						SAGEMAKER_TRANSFORMERS_VERSION
					lowerCAmelCase_				=						SAGEMAKER_PYTHON_VERSION
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None
					lowerCAmelCase_				=						None



