



# 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


A_		:  Dict										=  os.path.expanduser(
    os.getenv('''HF_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''huggingface'''))
)
A_		:  List[Any]										=  os.path.join(hf_cache_home, '''accelerate''')
A_		:  Any										=  os.path.join(cache_dir, '''default_config.yaml''')
A_		:  Optional[Any]										=  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):
     A_		:  str										=  default_yaml_config_file
else:
     A_		:  List[str]										=  default_json_config_file


def 						UpperCAmelCase__   (   UpperCAmelCase__			:Dict       ):






 '''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:
  a							=		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
   ):
    a							=		ClusterConfig
   else:
    a							=		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
   ):
    a							=		ClusterConfig
   else:
    a							=		SageMakerConfig
   return config_class.from_yaml_file(yaml_file=UpperCAmelCase__       )



@dataclass
class 		_lowercase		:
   _UpperCAmelCase  						=      42
   _UpperCAmelCase  						=      42
   _UpperCAmelCase  						=      42
   _UpperCAmelCase  						=      42

   def 		A				(   self      :							int				)							->					str:


    """simple docstring"""






    a							=		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				):
      a							=		value.value
     if isinstance(__lowerCAmelCase				, __lowerCAmelCase				) and not bool(__lowerCAmelCase				):
      a							=		None
    a							=		{k: v for k, v in result.items() if v is not None}
    return result

   @classmethod
   def 		A				(   cls      :							Optional[int]				, __lowerCAmelCase      :							Tuple=None				)							->					Union[str, Any]:


    """simple docstring"""






    a							=		default_json_config_file if json_file is None else json_file
    with open(__lowerCAmelCase				, "r"				, encoding="utf-8"				) as f:
     a							=		json.load(__lowerCAmelCase				)
    if "compute_environment" not in config_dict:
     a							=		ComputeEnvironment.LOCAL_MACHINE
    if "mixed_precision" not in config_dict:
     a							=		"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.
     a							=		config_dict.pop("dynamo_backend"				)
     a							=		{} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
    if "use_cpu" not in config_dict:
     a							=		False
    return cls(**__lowerCAmelCase				)

   def 		A				(   self      :							Optional[int]				, __lowerCAmelCase      :							List[str]				)							->					Any:


    """simple docstring"""






    with open(__lowerCAmelCase				, "w"				, encoding="utf-8"				) as f:
     a							=		json.dumps(self.to_dict()				, indent=2				, sort_keys=__lowerCAmelCase				) + "\n"
     f.write(__lowerCAmelCase				)

   @classmethod
   def 		A				(   cls      :							Optional[int]				, __lowerCAmelCase      :							List[str]=None				)							->					Optional[int]:


    """simple docstring"""






    a							=		default_yaml_config_file if yaml_file is None else yaml_file
    with open(__lowerCAmelCase				, "r"				, encoding="utf-8"				) as f:
     a							=		yaml.safe_load(__lowerCAmelCase				)
    if "compute_environment" not in config_dict:
     a							=		ComputeEnvironment.LOCAL_MACHINE

    if "mixed_precision" not in config_dict:
     a							=		"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"]:
     a							=		"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.
     a							=		config_dict.pop("dynamo_backend"				)
     a							=		{} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
    if "use_cpu" not in config_dict:
     a							=		False
    return cls(**__lowerCAmelCase				)

   def 		A				(   self      :							int				, __lowerCAmelCase      :							List[str]				)							->					Optional[int]:


    """simple docstring"""






    with open(__lowerCAmelCase				, "w"				, encoding="utf-8"				) as f:
     yaml.safe_dump(self.to_dict()				, __lowerCAmelCase				)




   def 		A				(   self      :							int				)							->					int:


    """simple docstring"""






    if isinstance(self.compute_environment				, __lowerCAmelCase				):
     a							=		ComputeEnvironment(self.compute_environment				)
    if isinstance(self.distributed_type				, __lowerCAmelCase				):
     if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
      a							=		SageMakerDistributedType(self.distributed_type				)
     else:
      a							=		DistributedType(self.distributed_type				)
    if self.dynamo_config is None:
     a							=		{}



@dataclass
class 		_lowercase		(							UpperCAmelCase__						):
   _UpperCAmelCase  						=      42
   _UpperCAmelCase  						=      0
   _UpperCAmelCase  						=      1
   _UpperCAmelCase  						=      None
   _UpperCAmelCase  						=      None
   _UpperCAmelCase  						=      None
   _UpperCAmelCase  						=      "static"
   _UpperCAmelCase  						=      False
   _UpperCAmelCase  						=      "main"

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

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

   # args for dynamo
   _UpperCAmelCase  						=      None

   def 		A				(   self      :							Dict				)							->					Optional[int]:


    """simple docstring"""






    if self.deepspeed_config is None:
     a							=		{}
    if self.fsdp_config is None:
     a							=		{}
    if self.megatron_lm_config is None:
     a							=		{}
    if self.ipex_config is None:
     a							=		{}
    return super().__post_init__()



@dataclass
class 		_lowercase		(							UpperCAmelCase__						):
   _UpperCAmelCase  						=      42
   _UpperCAmelCase  						=      42
   _UpperCAmelCase  						=      None
   _UpperCAmelCase  						=      None
   _UpperCAmelCase  						=      "us-east-1"
   _UpperCAmelCase  						=      1
   _UpperCAmelCase  						=      "all"
   _UpperCAmelCase  						=      F"""accelerate-sagemaker-{num_machines}"""
   _UpperCAmelCase  						=      SAGEMAKER_PYTORCH_VERSION
   _UpperCAmelCase  						=      SAGEMAKER_TRANSFORMERS_VERSION
   _UpperCAmelCase  						=      SAGEMAKER_PYTHON_VERSION
   _UpperCAmelCase  						=      None
   _UpperCAmelCase  						=      None
   _UpperCAmelCase  						=      None
   _UpperCAmelCase  						=      None






from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_speech_available,
    is_torch_available,
)


__A       ={
    "configuration_speech_to_text_2": ["SPEECH_TO_TEXT_2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Speech2Text2Config"],
    "processing_speech_to_text_2": ["Speech2Text2Processor"],
    "tokenization_speech_to_text_2": ["Speech2Text2Tokenizer"],
}


try:
				if not is_torch_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				__A       =[
				    "SPEECH_TO_TEXT_2_PRETRAINED_MODEL_ARCHIVE_LIST",
				    "Speech2Text2ForCausalLM",
				    "Speech2Text2PreTrainedModel",
				]


if TYPE_CHECKING:
				from .configuration_speech_to_text_a import SPEECH_TO_TEXT_2_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextaConfig
				from .processing_speech_to_text_a import SpeechaTextaProcessor
				from .tokenization_speech_to_text_a import SpeechaTextaTokenizer

				try:
								if not is_torch_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_speech_to_text_a import (
								    SPEECH_TO_TEXT_2_PRETRAINED_MODEL_ARCHIVE_LIST,
								    SpeechaTextaForCausalLM,
								    SpeechaTextaPreTrainedModel,
								)

else:
				import sys

				__A       =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)





