from __future__ import annotations

import copy
import os
import tempfile
from importlib import import_module
from math import isnan

from transformers import is_tf_available
from transformers.models.auto import get_values
from transformers.testing_utils import _tf_gpu_memory_limit, require_tf, slow

from ..test_modeling_tf_common import ids_tensor


if is_tf_available():
     import numpy as np
     import tensorflow as tf

     from transformers import (
         TF_MODEL_FOR_CAUSAL_LM_MAPPING,
         TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
         TF_MODEL_FOR_MASKED_LM_MAPPING,
         TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
         TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING,
         TF_MODEL_FOR_PRETRAINING_MAPPING,
         TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
         TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
         TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
         TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
         TFSharedEmbeddings,
     )

     if _tf_gpu_memory_limit is not None:
          __snake_case			      =    tf.config.list_physical_devices('''GPU''')
          for gpu in gpus:
               # Restrict TensorFlow to only allocate x GB of memory on the GPUs
               try:
                    tf.config.set_logical_device_configuration(
                        gpu, [tf.config.LogicalDeviceConfiguration(memory_limit=_tf_gpu_memory_limit)]
                    )
                    __snake_case			      =    tf.config.list_logical_devices('''GPU''')
                    print('''Logical GPUs''', logical_gpus)
               except RuntimeError as e:
                    # Virtual devices must be set before GPUs have been initialized
                    print(e)







@require_tf
class 			__snake_case   :
 __lowerCamelCase    :   int     =      None
 __lowerCamelCase    :   Dict     =      ()
 __lowerCamelCase    :   Dict     =      ()
 __lowerCamelCase    :   Dict     =      True
 __lowerCamelCase    :   str     =      True
 __lowerCamelCase    :   Union[str, Any]     =      True
 __lowerCamelCase    :   Any     =      False
 def 	UpperCAmelCase__       (  self		,   snake_case__		,   snake_case__		,   snake_case__=False						)	->							dict:
       '''simple docstring'''





       UpperCAmelCase    : Optional[Any]      =copy.deepcopy(snake_case__						)

       if model_class in get_values(snake_case__						):
             UpperCAmelCase    : Optional[int]      ={
                 k: tf.tile(tf.expand_dims(snake_case__		,   1						)		,   (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)						)
                 if isinstance(snake_case__		,   tf.Tensor						) and v.ndim > 0
                 else v
                 for k, v in inputs_dict.items()
             }

       if return_labels:
             if model_class in get_values(snake_case__						):
                   UpperCAmelCase    : List[str]      =tf.ones(self.model_tester.batch_size		,   dtype=tf.intaa						)
             elif model_class in get_values(snake_case__						):
                   UpperCAmelCase    : List[str]      =tf.zeros(self.model_tester.batch_size		,   dtype=tf.intaa						)
                   UpperCAmelCase    : Union[str, Any]      =tf.zeros(self.model_tester.batch_size		,   dtype=tf.intaa						)
             elif model_class in [
                 *get_values(snake_case__						),
                 *get_values(snake_case__						),
             ]:
                   UpperCAmelCase    : List[Any]      =tf.zeros(self.model_tester.batch_size		,   dtype=tf.intaa						)
             elif model_class in get_values(snake_case__						):
                   UpperCAmelCase    : Tuple      =tf.zeros(self.model_tester.batch_size		,   dtype=tf.intaa						)
             elif model_class in [
                 *get_values(snake_case__						),
                 *get_values(snake_case__						),
                 *get_values(snake_case__						),
                 *get_values(snake_case__						),
                 *get_values(snake_case__						),
             ]:
                   UpperCAmelCase    : Optional[Any]      =tf.zeros(
                       (self.model_tester.batch_size, self.model_tester.seq_length)		,   dtype=tf.intaa						)
       return inputs_dict
 @slow
 def 	UpperCAmelCase__       (  self						)	->							Optional[Any]:
       '''simple docstring'''





       UpperCAmelCase  ,						UpperCAmelCase    : int      =self.model_tester.prepare_config_and_inputs_for_common()
       for model_class in self.all_model_classes[:2]:
             UpperCAmelCase    : int      =self._prepare_for_class(snake_case__		,   snake_case__						)
             UpperCAmelCase    : Tuple      =model_class(snake_case__						)

             @tf.function
             def run_in_graph_mode():
                   return model(snake_case__						)

             UpperCAmelCase    : Optional[int]      =run_in_graph_mode()
             self.assertIsNotNone(snake_case__						)
 @slow
 def 	UpperCAmelCase__       (  self						)	->							int:
       '''simple docstring'''





       UpperCAmelCase  ,						UpperCAmelCase    : List[str]      =self.model_tester.prepare_config_and_inputs_for_common()
       for model_class in self.all_model_classes[:2]:
             UpperCAmelCase    : List[Any]      =self._prepare_for_class(snake_case__		,   snake_case__						)
             UpperCAmelCase    : Optional[Any]      =model_class(snake_case__						)

             @tf.function(experimental_compile=snake_case__						)
             def run_in_graph_mode():
                   return model(snake_case__						)

             UpperCAmelCase    : Tuple      =run_in_graph_mode()
             self.assertIsNotNone(snake_case__						)
 @slow
 def 	UpperCAmelCase__       (  self						)	->							Optional[int]:
       '''simple docstring'''





       UpperCAmelCase  ,						UpperCAmelCase    : List[Any]      =self.model_tester.prepare_config_and_inputs_for_common()
       for model_class in self.all_model_classes[:2]:
             UpperCAmelCase    : str      =model_class(snake_case__						)
             if getattr(snake_case__		,   '''hf_compute_loss'''		,   snake_case__						):
                   # Test that model correctly compute the loss with kwargs
                   UpperCAmelCase    : List[str]      =self._prepare_for_class(inputs_dict.copy()		,   snake_case__		,   return_labels=snake_case__						)
                   # Is there a better way to remove these decoder inputs?
                   UpperCAmelCase    : List[str]      ={
                       key: val
                       for key, val in prepared_for_class.items()
                       if key not in ('''head_mask''', '''decoder_head_mask''', '''cross_attn_head_mask''', '''decoder_input_ids''')
                   }

                   UpperCAmelCase    : Tuple      ={
                       '''labels''',
                       '''label''',
                       '''label_ids''',
                       '''start_positions''',
                       '''start_position''',
                       '''end_positions''',
                       '''end_position''',
                       '''next_sentence_label''',
                   }
                   UpperCAmelCase    : List[Any]      =possible_label_cols.intersection(set(snake_case__						)						)
                   self.assertGreater(len(snake_case__						)		,   0		,   msg='''No matching label names found!'''						)
                   UpperCAmelCase    : int      ={key: val for key, val in prepared_for_class.items() if key in label_names}
                   UpperCAmelCase    : str      ={key: val for key, val in prepared_for_class.items() if key not in label_names}
                   self.assertGreater(len(snake_case__						)		,   0						)

                   # Make sure it works with XLA!
                   model.compile(optimizer=tf.keras.optimizers.SGD(0.0						)		,   jit_compile=snake_case__						)
                   # Make sure the model fits without crashing regardless of where we pass the labels
                   UpperCAmelCase    : Tuple      =model.fit(
                       snake_case__		,   validation_data=snake_case__		,   steps_per_epoch=1		,   validation_steps=1		,   shuffle=snake_case__		,   verbose=0		,   )
                   UpperCAmelCase    : int      =history.history['''loss'''][0]
                   self.assertTrue(not isnan(snake_case__						)						)
                   UpperCAmelCase    : int      =history.history['''val_loss'''][0]
                   self.assertTrue(not isnan(snake_case__						)						)

                   # Now test it with separate labels, to make sure that path works in XLA too.
                   UpperCAmelCase    : Tuple      =model_class(snake_case__						)
                   model.compile(optimizer=tf.keras.optimizers.SGD(0.0						)		,   jit_compile=snake_case__						)
                   UpperCAmelCase    : Tuple      =model.fit(
                       snake_case__		,   snake_case__		,   validation_data=(inputs_minus_labels, labels)		,   steps_per_epoch=1		,   validation_steps=1		,   shuffle=snake_case__		,   verbose=0		,   )

                   UpperCAmelCase    : str      =history.history['''loss'''][0]
                   self.assertTrue(not isnan(snake_case__						)						)
                   UpperCAmelCase    : List[str]      =history.history['''val_loss'''][0]
                   self.assertTrue(not isnan(snake_case__						)						)
 @slow
 def 	UpperCAmelCase__       (  self						)	->							List[str]:
       '''simple docstring'''





       UpperCAmelCase  ,						UpperCAmelCase    : List[Any]      =self.model_tester.prepare_config_and_inputs_for_common()
       UpperCAmelCase    : Any      =True
       UpperCAmelCase    : Optional[int]      =True

       if hasattr(snake_case__		,   '''use_cache'''						):
             UpperCAmelCase    : Dict      =True

       UpperCAmelCase    : Optional[Any]      =getattr(self.model_tester		,   '''encoder_seq_length'''		,   self.model_tester.seq_length						)
       UpperCAmelCase    : Optional[int]      =getattr(self.model_tester		,   '''key_length'''		,   snake_case__						)

       for model_class in self.all_model_classes[:2]:
             UpperCAmelCase    : Optional[Any]      =self._prepare_for_class(snake_case__		,   snake_case__						)
             UpperCAmelCase    : List[str]      =model_class(snake_case__						)
             model.build()
             UpperCAmelCase    : Union[str, Any]      =len(model(snake_case__						)						)

             for key in list(class_inputs_dict.keys()						):
                   # Remove keys not in the serving signature, as the SavedModel will not be compiled to deal with them
                   if key not in model.input_signature:
                         del class_inputs_dict[key]
                   # Check it's a tensor, in case the inputs dict has some bools in it too
                   elif isinstance(class_inputs_dict[key]		,   tf.Tensor						) and class_inputs_dict[key].dtype.is_integer:
                         UpperCAmelCase    : List[str]      =tf.cast(class_inputs_dict[key]		,   tf.intaa						)

             if set(class_inputs_dict.keys()						) != set(model.input_signature.keys()						):
                   continue  # Some models have inputs that the preparation functions don't create, we skip those

             with tempfile.TemporaryDirectory() as tmpdirname:
                   model.save_pretrained(snake_case__		,   saved_model=snake_case__						)
                   UpperCAmelCase    : Optional[Any]      =os.path.join(snake_case__		,   '''saved_model'''		,   '''1'''						)
                   UpperCAmelCase    : Tuple      =tf.keras.models.load_model(snake_case__						)
                   UpperCAmelCase    : List[str]      =model(snake_case__						)

                   if self.is_encoder_decoder:
                         UpperCAmelCase    : List[str]      =outputs['''encoder_hidden_states''']
                         UpperCAmelCase    : Tuple      =outputs['''encoder_attentions''']
                   else:
                         UpperCAmelCase    : List[str]      =outputs['''hidden_states''']
                         UpperCAmelCase    : Tuple      =outputs['''attentions''']

                   self.assertEqual(len(snake_case__						)		,   snake_case__						)

                   UpperCAmelCase    : List[str]      =getattr(
                       self.model_tester		,   '''expected_num_hidden_layers'''		,   self.model_tester.num_hidden_layers + 1						)

                   self.assertEqual(len(snake_case__						)		,   snake_case__						)
                   self.assertListEqual(
                       list(output_hidden_states[0].shape[-2:]						)		,   [self.model_tester.seq_length, self.model_tester.hidden_size]		,   )

                   self.assertEqual(len(snake_case__						)		,   self.model_tester.num_hidden_layers						)
                   self.assertListEqual(
                       list(output_attentions[0].shape[-3:]						)		,   [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length]		,   )
 @slow
 def 	UpperCAmelCase__       (  self						)	->							Union[str, Any]:
       '''simple docstring'''





       tf.keras.mixed_precision.set_global_policy('''mixed_float16'''						)

       # try/finally block to ensure subsequent tests run in float32
       try:
             UpperCAmelCase  ,						UpperCAmelCase    : Dict      =self.model_tester.prepare_config_and_inputs_for_common()
             for model_class in self.all_model_classes[:2]:
                   UpperCAmelCase    : Dict      =self._prepare_for_class(snake_case__		,   snake_case__						)
                   UpperCAmelCase    : Dict      =model_class(snake_case__						)
                   UpperCAmelCase    : List[Any]      =model(snake_case__						)

                   self.assertIsNotNone(snake_case__						)
       finally:
             tf.keras.mixed_precision.set_global_policy('''float32'''						)
 @slow
 def 	UpperCAmelCase__       (  self						)	->							Union[str, Any]:
       '''simple docstring'''





       UpperCAmelCase  ,						UpperCAmelCase    : Optional[Any]      =self.model_tester.prepare_config_and_inputs_for_common()
       # head_mask and decoder_head_mask has different shapes than other input args
       if "head_mask" in inputs_dict:
             del inputs_dict["head_mask"]
       if "decoder_head_mask" in inputs_dict:
             del inputs_dict["decoder_head_mask"]
       if "cross_attn_head_mask" in inputs_dict:
             del inputs_dict["cross_attn_head_mask"]
       UpperCAmelCase    : Optional[Any]      ={
           module_member
           for model_class in self.all_model_classes
           for module in (import_module(model_class.__module__						),)
           for module_member_name in dir(snake_case__						)
           if module_member_name.endswith('''MainLayer'''						)
           for module_member in (getattr(snake_case__		,   snake_case__						),)
           if isinstance(snake_case__		,   snake_case__						)
           and tf.keras.layers.Layer in module_member.__bases__
           and getattr(snake_case__		,   '''_keras_serializable'''		,   snake_case__						)
       }

       for main_layer_class in tf_main_layer_classes:
             # T5MainLayer needs an embed_tokens parameter when called without the inputs_embeds parameter
             if "T5" in main_layer_class.__name__:
                   # Take the same values than in TFT5ModelTester for this shared layer
                   UpperCAmelCase    : Dict      =TFSharedEmbeddings(self.model_tester.vocab_size		,   self.model_tester.hidden_size		,   name='''shared'''						)
                   UpperCAmelCase    : int      =False
                   UpperCAmelCase    : Optional[int]      =main_layer_class(snake_case__		,   embed_tokens=snake_case__						)
             else:
                   UpperCAmelCase    : Optional[int]      =main_layer_class(snake_case__						)

             UpperCAmelCase    : Optional[Any]      ={
                 name: tf.keras.Input(tensor.shape[1:]		,   dtype=tensor.dtype						) for name, tensor in inputs_dict.items()
             }

             if hasattr(self.model_tester		,   '''num_labels'''						):
                   UpperCAmelCase    : Tuple      =self.model_tester.num_labels
             else:
                   UpperCAmelCase    : Union[str, Any]      =2

             UpperCAmelCase    : Optional[int]      =tf.data.Dataset.from_tensor_slices(
                 (inputs_dict, np.ones((self.model_tester.batch_size, self.model_tester.seq_length, num_labels, 1)						))						).batch(1						)

             UpperCAmelCase    : str      =main_layer(snake_case__						)[0]
             UpperCAmelCase    : str      =tf.keras.layers.Dense(snake_case__		,   activation='''softmax'''		,   name='''outputs'''						)(snake_case__						)
             UpperCAmelCase    : str      =tf.keras.models.Model(inputs=snake_case__		,   outputs=[outputs]						)

             model.compile(loss='''binary_crossentropy'''		,   optimizer='''adam'''		,   metrics=['''binary_accuracy''']						)
             model.fit(snake_case__		,   epochs=1						)

             with tempfile.TemporaryDirectory() as tmpdirname:
                   UpperCAmelCase    : List[Any]      =os.path.join(snake_case__		,   '''keras_model.h5'''						)
                   model.save(snake_case__						)
                   if "T5" in main_layer_class.__name__:
                         UpperCAmelCase    : Union[str, Any]      =tf.keras.models.load_model(
                             snake_case__		,   custom_objects={
                                 main_layer_class.__name__: main_layer_class,
                                 '''TFSharedEmbeddings''': TFSharedEmbeddings,
                             }		,   )
                   else:
                         UpperCAmelCase    : Tuple      =tf.keras.models.load_model(
                             snake_case__		,   custom_objects={main_layer_class.__name__: main_layer_class}						)
                   assert isinstance(snake_case__		,   tf.keras.Model						)
                   model(snake_case__						)
 @slow
 def 	UpperCAmelCase__       (  self						)	->							Union[str, Any]:
       '''simple docstring'''





       UpperCAmelCase  ,						UpperCAmelCase    : str      =self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes[:2]:
             UpperCAmelCase    : Optional[Any]      =model_class(snake_case__						)

             UpperCAmelCase    : List[str]      =copy.deepcopy(snake_case__						)

             if not self.is_encoder_decoder:
                   UpperCAmelCase    : Union[str, Any]      =inputs['''input_ids''']
                   del inputs["input_ids"]
             else:
                   UpperCAmelCase    : List[str]      =inputs['''input_ids''']
                   UpperCAmelCase    : Dict      =inputs.get('''decoder_input_ids'''		,   snake_case__						)
                   del inputs["input_ids"]
                   inputs.pop('''decoder_input_ids'''		,   snake_case__						)

             if not self.is_encoder_decoder:
                   UpperCAmelCase    : Dict      =model.get_input_embeddings()(snake_case__						)
             else:
                   UpperCAmelCase    : List[str]      =model.get_input_embeddings()(snake_case__						)
                   UpperCAmelCase    : Union[str, Any]      =model.get_input_embeddings()(snake_case__						)

             UpperCAmelCase    : Tuple      =self._prepare_for_class(snake_case__		,   snake_case__						)

             @tf.function
             def run_in_graph_mode():
                   return model(snake_case__						)

             UpperCAmelCase    : str      =run_in_graph_mode()
             self.assertIsNotNone(snake_case__						)
 def 	UpperCAmelCase__       (  self		,   snake_case__		,   snake_case__						)	->							Union[str, Any]:
       '''simple docstring'''





       UpperCAmelCase    : List[str]      =[]
       if model.config.bos_token_id is not None:
             special_tokens.append(model.config.bos_token_id						)
       if model.config.pad_token_id is not None:
             special_tokens.append(model.config.pad_token_id						)
       if model.config.eos_token_id is not None:
             special_tokens.append(model.config.eos_token_id						)

       # create random bad tokens that are not special tokens
       UpperCAmelCase    : Optional[Any]      =[]
       while len(snake_case__						) < num_bad_tokens:
             UpperCAmelCase    : Dict      =tf.squeeze(ids_tensor((1, 1)		,   self.model_tester.vocab_size						)		,   0						).numpy()[0]
             if token not in special_tokens:
                   bad_tokens.append(snake_case__						)
       return bad_tokens
 def 	UpperCAmelCase__       (  self		,   snake_case__						)	->							List[str]:
       '''simple docstring'''





       for token_id in output_ids[0].numpy().tolist():
             self.assertGreaterEqual(snake_case__		,   0						)
             self.assertLess(snake_case__		,   self.model_tester.vocab_size						)






 def 	UpperCAmelCase__       (  self		,   snake_case__		,   snake_case__						)	->							Optional[int]:
       '''simple docstring'''





       for bad_word_ids in bad_words_ids:
             # for all slices in batch
             for generated_ids_slice in generated_ids:
                   # for all word idx
                   for i in range(len(snake_case__						)		,   len(snake_case__						)						):
                         # if tokens match
                         if generated_ids_slice[i - len(snake_case__						) : i] == bad_word_ids:
                               return True
       return False

# 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


__snake_case			      =    os.path.expanduser(
    os.getenv('''HF_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''huggingface'''))
)
__snake_case			      =    os.path.join(hf_cache_home, '''accelerate''')
__snake_case			      =    os.path.join(cache_dir, '''default_config.yaml''')
__snake_case			      =    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):
     __snake_case			      =    default_yaml_config_file
else:
     __snake_case			      =    default_json_config_file





def   lowerCAmelCase_ (				__lowerCAmelCase						)->  Tuple:






      '''simple docstring'''





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







@dataclass
class 			__snake_case   :
 __lowerCamelCase    :   ComputeEnvironment
 __lowerCamelCase    :   Union[DistributedType, SageMakerDistributedType]
 __lowerCamelCase    :   str
 __lowerCamelCase    :   bool
 def 	UpperCAmelCase__       (  self						)	->							List[Any]:
       '''simple docstring'''





       UpperCAmelCase    : Union[str, Any]      =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(snake_case__		,   snake_case__						):
                   UpperCAmelCase    : Any      =value.value
             if isinstance(snake_case__		,   snake_case__						) and not bool(snake_case__						):
                   UpperCAmelCase    : Union[str, Any]      =None
       UpperCAmelCase    : Dict      ={k: v for k, v in result.items() if v is not None}
       return result
 @classmethod
 def 	UpperCAmelCase__       (  cls		,   snake_case__=None						)	->							Optional[int]:
       '''simple docstring'''





       UpperCAmelCase    : Tuple      =default_json_config_file if json_file is None else json_file
       with open(snake_case__		,   '''r'''		,   encoding='''utf-8'''						) as f:
             UpperCAmelCase    : Optional[int]      =json.load(snake_case__						)
       if "compute_environment" not in config_dict:
             UpperCAmelCase    : Optional[int]      =ComputeEnvironment.LOCAL_MACHINE
       if "mixed_precision" not in config_dict:
             UpperCAmelCase    : Optional[int]      ='''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.
             UpperCAmelCase    : Optional[Any]      =config_dict.pop('''dynamo_backend'''						)
             UpperCAmelCase    : List[Any]      ={} if dynamo_backend == '''NO''' else {'''dynamo_backend''': dynamo_backend}
       if "use_cpu" not in config_dict:
             UpperCAmelCase    : Dict      =False
       return cls(**snake_case__						)
 def 	UpperCAmelCase__       (  self		,   snake_case__						)	->							int:
       '''simple docstring'''





       with open(snake_case__		,   '''w'''		,   encoding='''utf-8'''						) as f:
             UpperCAmelCase    : Dict      =json.dumps(self.to_dict()		,   indent=2		,   sort_keys=snake_case__						) + '''\n'''
             f.write(snake_case__						)
 @classmethod
 def 	UpperCAmelCase__       (  cls		,   snake_case__=None						)	->							Optional[Any]:
       '''simple docstring'''





       UpperCAmelCase    : List[Any]      =default_yaml_config_file if yaml_file is None else yaml_file
       with open(snake_case__		,   '''r'''		,   encoding='''utf-8'''						) as f:
             UpperCAmelCase    : List[str]      =yaml.safe_load(snake_case__						)
       if "compute_environment" not in config_dict:
             UpperCAmelCase    : str      =ComputeEnvironment.LOCAL_MACHINE

       if "mixed_precision" not in config_dict:
             UpperCAmelCase    : Optional[Any]      ='''fp16''' if ('''fp16''' in config_dict and config_dict['''fp16''']) else None
       if isinstance(config_dict['''mixed_precision''']		,   snake_case__						) and not config_dict["mixed_precision"]:
             UpperCAmelCase    : Any      ='''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.
             UpperCAmelCase    : List[str]      =config_dict.pop('''dynamo_backend'''						)
             UpperCAmelCase    : str      ={} if dynamo_backend == '''NO''' else {'''dynamo_backend''': dynamo_backend}
       if "use_cpu" not in config_dict:
             UpperCAmelCase    : Optional[int]      =False
       return cls(**snake_case__						)
 def 	UpperCAmelCase__       (  self		,   snake_case__						)	->							List[str]:
       '''simple docstring'''





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






 def 	UpperCAmelCase__       (  self						)	->							int:
       '''simple docstring'''





       if isinstance(self.compute_environment		,   snake_case__						):
             UpperCAmelCase    : Any      =ComputeEnvironment(self.compute_environment						)
       if isinstance(self.distributed_type		,   snake_case__						):
             if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
                   UpperCAmelCase    : int      =SageMakerDistributedType(self.distributed_type						)
             else:
                   UpperCAmelCase    : int      =DistributedType(self.distributed_type						)
       if self.dynamo_config is None:
             UpperCAmelCase    : Optional[int]      ={}







@dataclass
class 			__snake_case   (     lowerCamelCase__   ):
 __lowerCamelCase    :   int
 __lowerCamelCase    :   int     =      0
 __lowerCamelCase    :   int     =      1
 __lowerCamelCase    :   Optional[str]     =      None
 __lowerCamelCase    :   Optional[str]     =      None
 __lowerCamelCase    :   Optional[int]     =      None
 __lowerCamelCase    :   Optional[str]     =      "static"
 __lowerCamelCase    :   Optional[bool]     =      False
 __lowerCamelCase    :   str     =      "main"

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

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

 # args for dynamo
 __lowerCamelCase    :   dict     =      None
 def 	UpperCAmelCase__       (  self						)	->							Tuple:
       '''simple docstring'''





       if self.deepspeed_config is None:
             UpperCAmelCase    : Union[str, Any]      ={}
       if self.fsdp_config is None:
             UpperCAmelCase    : Any      ={}
       if self.megatron_lm_config is None:
             UpperCAmelCase    : List[Any]      ={}
       if self.ipex_config is None:
             UpperCAmelCase    : int      ={}
       return super().__post_init__()







@dataclass
class 			__snake_case   (     lowerCamelCase__   ):
 __lowerCamelCase    :   str
 __lowerCamelCase    :   str
 __lowerCamelCase    :   Optional[str]     =      None
 __lowerCamelCase    :   Optional[str]     =      None
 __lowerCamelCase    :   str     =      "us-east-1"
 __lowerCamelCase    :   int     =      1
 __lowerCamelCase    :   str     =      "all"
 __lowerCamelCase    :   str     =      F'accelerate-sagemaker-{num_machines}'
 __lowerCamelCase    :   str     =      SAGEMAKER_PYTORCH_VERSION
 __lowerCamelCase    :   str     =      SAGEMAKER_TRANSFORMERS_VERSION
 __lowerCamelCase    :   str     =      SAGEMAKER_PYTHON_VERSION
 __lowerCamelCase    :   str     =      None
 __lowerCamelCase    :   str     =      None
 __lowerCamelCase    :   dict     =      None
 __lowerCamelCase    :   dict     =      None
