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







def 				UpperCAmelCase_(    a__   ):



    """simple docstring"""



    if config_file is not None:
        if not os.path.isfile(a__   ):
            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:
        SCREAMING_SNAKE_CASE				:				Any				      = default_config_file
    with open(a__ ,						'''r''' ,						encoding='''utf-8'''   ) as f:
        if config_file.endswith('''.json'''   ):
            if (
                json.load(a__   ).get('''compute_environment''' ,						ComputeEnvironment.LOCAL_MACHINE   )
                == ComputeEnvironment.LOCAL_MACHINE
            ):
                SCREAMING_SNAKE_CASE				:				Optional[Any]				      = ClusterConfig
            else:
                SCREAMING_SNAKE_CASE				:				Optional[Any]				      = SageMakerConfig
            return config_class.from_json_file(json_file=a__   )
        else:
            if (
                yaml.safe_load(a__   ).get('''compute_environment''' ,						ComputeEnvironment.LOCAL_MACHINE   )
                == ComputeEnvironment.LOCAL_MACHINE
            ):
                SCREAMING_SNAKE_CASE				:				Optional[int]				      = ClusterConfig
            else:
                SCREAMING_SNAKE_CASE				:				int				      = SageMakerConfig
            return config_class.from_yaml_file(yaml_file=a__   )






@dataclass
class     a_       :



       """simple docstring"""
       __SCREAMING_SNAKE_CASE       :					ComputeEnvironment
       __SCREAMING_SNAKE_CASE       :					Union[DistributedType, SageMakerDistributedType]
       __SCREAMING_SNAKE_CASE       :					str
       __SCREAMING_SNAKE_CASE       :					bool






       def 	__lowerCAmelCase     (		self   )					->Any:
           SCREAMING_SNAKE_CASE				:				Dict				      = 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   ):
                   SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = value.value
               if isinstance(_lowerCamelCase				,       _lowerCamelCase   ) and not bool(_lowerCamelCase   ):
                   SCREAMING_SNAKE_CASE				:				Optional[Any]				      = None
           SCREAMING_SNAKE_CASE				:				str				      = {k: v for k, v in result.items() if v is not None}
           return result






       @classmethod
       def 	__lowerCAmelCase     (		cls				,       _lowerCamelCase=None   )					->Tuple:
           SCREAMING_SNAKE_CASE				:				Tuple				      = default_json_config_file if json_file is None else json_file
           with open(_lowerCamelCase				,       '''r'''				,       encoding='''utf-8'''   ) as f:
               SCREAMING_SNAKE_CASE				:				Tuple				      = json.load(_lowerCamelCase   )
           if "compute_environment" not in config_dict:
               SCREAMING_SNAKE_CASE				:				int				      = ComputeEnvironment.LOCAL_MACHINE
           if "mixed_precision" not in config_dict:
               SCREAMING_SNAKE_CASE				:				Any				      = '''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.
               SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = config_dict.pop('''dynamo_backend'''   )
               SCREAMING_SNAKE_CASE				:				List[Any]				      = {} if dynamo_backend == '''NO''' else {'''dynamo_backend''': dynamo_backend}
           if "use_cpu" not in config_dict:
               SCREAMING_SNAKE_CASE				:				str				      = False
           return cls(**_lowerCamelCase   )






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase   )					->int:
           with open(_lowerCamelCase				,       '''w'''				,       encoding='''utf-8'''   ) as f:
               SCREAMING_SNAKE_CASE				:				List[Any]				      = json.dumps(self.to_dict()				,       indent=2				,       sort_keys=_lowerCamelCase   ) + '''\n'''
               f.write(_lowerCamelCase   )






       @classmethod
       def 	__lowerCAmelCase     (		cls				,       _lowerCamelCase=None   )					->Tuple:
           SCREAMING_SNAKE_CASE				:				List[Any]				      = default_yaml_config_file if yaml_file is None else yaml_file
           with open(_lowerCamelCase				,       '''r'''				,       encoding='''utf-8'''   ) as f:
               SCREAMING_SNAKE_CASE				:				Any				      = yaml.safe_load(_lowerCamelCase   )
           if "compute_environment" not in config_dict:
               SCREAMING_SNAKE_CASE				:				Optional[Any]				      = ComputeEnvironment.LOCAL_MACHINE

           if "mixed_precision" not in config_dict:
               SCREAMING_SNAKE_CASE				:				List[Any]				      = '''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"]:
               SCREAMING_SNAKE_CASE				:				int				      = '''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.
               SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = config_dict.pop('''dynamo_backend'''   )
               SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = {} if dynamo_backend == '''NO''' else {'''dynamo_backend''': dynamo_backend}
           if "use_cpu" not in config_dict:
               SCREAMING_SNAKE_CASE				:				Optional[Any]				      = 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   ):
               SCREAMING_SNAKE_CASE				:				Tuple				      = ComputeEnvironment(self.compute_environment   )
           if isinstance(self.distributed_type				,       _lowerCamelCase   ):
               if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
                   SCREAMING_SNAKE_CASE				:				List[str]				      = SageMakerDistributedType(self.distributed_type   )
               else:
                   SCREAMING_SNAKE_CASE				:				Tuple				      = DistributedType(self.distributed_type   )
           if self.dynamo_config is None:
               SCREAMING_SNAKE_CASE				:				List[str]				      = {}






@dataclass
class     a_       (			a__							):



       """simple docstring"""
       __SCREAMING_SNAKE_CASE       :					int
       __SCREAMING_SNAKE_CASE       :					int						=  0
       __SCREAMING_SNAKE_CASE       :					int						=  1
       __SCREAMING_SNAKE_CASE       :					Optional[str]						=  None
       __SCREAMING_SNAKE_CASE       :					Optional[str]						=  None
       __SCREAMING_SNAKE_CASE       :					Optional[int]						=  None
       __SCREAMING_SNAKE_CASE       :					Optional[str]						=  "static"
       __SCREAMING_SNAKE_CASE       :					Optional[bool]						=  False
       __SCREAMING_SNAKE_CASE       :					str						=  "main"

       # args for deepspeed_plugin
       __SCREAMING_SNAKE_CASE       :					dict						=  None
       # args for fsdp
       __SCREAMING_SNAKE_CASE       :					dict						=  None
       # args for megatron_lm
       __SCREAMING_SNAKE_CASE       :					dict						=  None
       # args for ipex
       __SCREAMING_SNAKE_CASE       :					dict						=  None
       # args for TPU
       __SCREAMING_SNAKE_CASE       :					bool						=  False

       # args for TPU pods
       __SCREAMING_SNAKE_CASE       :					str						=  None
       __SCREAMING_SNAKE_CASE       :					str						=  None
       __SCREAMING_SNAKE_CASE       :					bool						=  False
       __SCREAMING_SNAKE_CASE       :					bool						=  False
       __SCREAMING_SNAKE_CASE       :					str						=  None
       __SCREAMING_SNAKE_CASE       :					List[str]						=  None
       __SCREAMING_SNAKE_CASE       :					List[str]						=  None
       __SCREAMING_SNAKE_CASE       :					List[str]						=  None

       # args for dynamo
       __SCREAMING_SNAKE_CASE       :					dict						=  None






       def 	__lowerCAmelCase     (		self   )					->Dict:
           if self.deepspeed_config is None:
               SCREAMING_SNAKE_CASE				:				Dict				      = {}
           if self.fsdp_config is None:
               SCREAMING_SNAKE_CASE				:				str				      = {}
           if self.megatron_lm_config is None:
               SCREAMING_SNAKE_CASE				:				List[str]				      = {}
           if self.ipex_config is None:
               SCREAMING_SNAKE_CASE				:				Dict				      = {}
           return super().__post_init__()






@dataclass
class     a_       (			a__							):



       """simple docstring"""
       __SCREAMING_SNAKE_CASE       :					str
       __SCREAMING_SNAKE_CASE       :					str
       __SCREAMING_SNAKE_CASE       :					Optional[str]						=  None
       __SCREAMING_SNAKE_CASE       :					Optional[str]						=  None
       __SCREAMING_SNAKE_CASE       :					str						=  "us-east-1"
       __SCREAMING_SNAKE_CASE       :					int						=  1
       __SCREAMING_SNAKE_CASE       :					str						=  "all"
       __SCREAMING_SNAKE_CASE       :					str						=  f"accelerate-sagemaker-{num_machines}"
       __SCREAMING_SNAKE_CASE       :					str						=  SAGEMAKER_PYTORCH_VERSION
       __SCREAMING_SNAKE_CASE       :					str						=  SAGEMAKER_TRANSFORMERS_VERSION
       __SCREAMING_SNAKE_CASE       :					str						=  SAGEMAKER_PYTHON_VERSION
       __SCREAMING_SNAKE_CASE       :					str						=  None
       __SCREAMING_SNAKE_CASE       :					str						=  None
       __SCREAMING_SNAKE_CASE       :					dict						=  None
       __SCREAMING_SNAKE_CASE       :					dict						=  None


# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
      import tensorflow as tf






class     a_       (			TensorFormatter[Mapping, 'tf.Tensor', Mapping]							):



       """simple docstring"""






       def __init__(		self				,       _lowerCamelCase=None				,       **_lowerCamelCase   )					->int:
           super().__init__(features=_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Any				      = tf_tensor_kwargs
           import tensorflow as tf  # noqa: import tf at initialization






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase   )					->Tuple:
           import tensorflow as tf

           if isinstance(_lowerCamelCase				,       _lowerCamelCase   ) and column:
               if all(
                   isinstance(_lowerCamelCase				,       tf.Tensor   ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column   ):
                   return tf.stack(_lowerCamelCase   )
               elif all(
                   isinstance(_lowerCamelCase				,       (tf.Tensor, tf.RaggedTensor)   ) and x.ndim == 1 and x.dtype == column[0].dtype
                   for x in column   ):
                   # only rag 1-D tensors, otherwise some dimensions become ragged even though they were consolidated
                   return tf.ragged.stack(_lowerCamelCase   )

           return column






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase   )					->Union[str, Any]:
           import tensorflow as tf

           if value is None:
               return value

           SCREAMING_SNAKE_CASE				:				int				      = {}

           if isinstance(_lowerCamelCase				,       (np.number, np.ndarray)   ) and np.issubdtype(value.dtype				,       np.integer   ):
               SCREAMING_SNAKE_CASE				:				List[Any]				      = {'''dtype''': tf.intaa}
           elif isinstance(_lowerCamelCase				,       (np.number, np.ndarray)   ) and np.issubdtype(value.dtype				,       np.floating   ):
               SCREAMING_SNAKE_CASE				:				Optional[int]				      = {'''dtype''': tf.floataa}
           elif config.PIL_AVAILABLE and "PIL" in sys.modules:
               import PIL.Image

               if isinstance(_lowerCamelCase				,       PIL.Image.Image   ):
                   SCREAMING_SNAKE_CASE				:				Any				      = np.asarray(_lowerCamelCase   )

           return tf.convert_to_tensor(_lowerCamelCase				,       **{**default_dtype, **self.tf_tensor_kwargs}   )






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase   )					->Tuple:
           import tensorflow as tf

           # support for torch, tf, jax etc.
           if config.TORCH_AVAILABLE and "torch" in sys.modules:
               import torch

               if isinstance(_lowerCamelCase				,       torch.Tensor   ):
                   return self._tensorize(data_struct.detach().cpu().numpy()[()]   )
           if hasattr(_lowerCamelCase				,       '''__array__'''   ) and not isinstance(_lowerCamelCase				,       tf.Tensor   ):
               SCREAMING_SNAKE_CASE				:				int				      = data_struct.__array__()
           # support for nested types like struct of list of struct
           if isinstance(_lowerCamelCase				,       np.ndarray   ):
               if data_struct.dtype == object:  # tf tensors cannot be instantied from an array of objects
                   return self._consolidate([self.recursive_tensorize(_lowerCamelCase   ) for substruct in data_struct]   )
           elif isinstance(_lowerCamelCase				,       (list, tuple)   ):
               return self._consolidate([self.recursive_tensorize(_lowerCamelCase   ) for substruct in data_struct]   )
           return self._tensorize(_lowerCamelCase   )






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase   )					->Optional[int]:
           return map_nested(self._recursive_tensorize				,       _lowerCamelCase				,       map_list=_lowerCamelCase   )






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase   )					->Mapping:
           SCREAMING_SNAKE_CASE				:				str				      = self.numpy_arrow_extractor().extract_row(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				List[str]				      = self.python_features_decoder.decode_row(_lowerCamelCase   )
           return self.recursive_tensorize(_lowerCamelCase   )






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase   )					->"tf.Tensor":
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = self.numpy_arrow_extractor().extract_column(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				str				      = self.python_features_decoder.decode_column(_lowerCamelCase				,       pa_table.column_names[0]   )
           SCREAMING_SNAKE_CASE				:				str				      = self.recursive_tensorize(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				int				      = self._consolidate(_lowerCamelCase   )
           return column






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase   )					->Mapping:
           SCREAMING_SNAKE_CASE				:				Tuple				      = self.numpy_arrow_extractor().extract_batch(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Dict				      = self.python_features_decoder.decode_batch(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				int				      = self.recursive_tensorize(_lowerCamelCase   )
           for column_name in batch:
               SCREAMING_SNAKE_CASE				:				Optional[Any]				      = self._consolidate(batch[column_name]   )
           return batch
