


import tempfile
import unittest

import numpy as np

import transformers
from transformers import GPTaConfig, GPTaTokenizer, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, slow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
      import jax
      import jax.numpy as jnp

      from transformers.modeling_flax_pytorch_utils import (
          convert_pytorch_state_dict_to_flax,
          load_flax_weights_in_pytorch_model,
      )
      from transformers.models.gpta.modeling_flax_gpta import FlaxGPTaLMHeadModel, FlaxGPTaModel

if is_torch_available():
      import torch




class    A_   :
 def __init__(			self					: Tuple       ,    _a					: int       ,    _a					: int=1_4       ,    _a					: Any=7       ,    _a					: List[str]=True       ,    _a					: Union[str, Any]=True       ,    _a					: Optional[int]=False       ,    _a					: Dict=True       ,    _a					: Tuple=9_9       ,    _a					: str=3_2       ,    _a					: Any=5       ,    _a					: Optional[Any]=4       ,    _a					: str=3_7       ,    _a					: List[Any]="gelu"       ,    _a					: int=0.1       ,    _a					: int=0.1       ,    _a					: List[Any]=5_1_2       ,    _a					: List[Any]=0.0_2       ,    )    ->			List[str]:
      UpperCAmelCase						:				List[str]		  =			parent
      UpperCAmelCase						:				List[str]		  =			batch_size
      UpperCAmelCase						:				Any		  =			seq_length
      UpperCAmelCase						:				Dict		  =			is_training
      UpperCAmelCase						:				Union[str, Any]		  =			use_input_mask
      UpperCAmelCase						:				Optional[int]		  =			use_token_type_ids
      UpperCAmelCase						:				List[str]		  =			use_labels
      UpperCAmelCase						:				List[str]		  =			vocab_size
      UpperCAmelCase						:				str		  =			hidden_size
      UpperCAmelCase						:				Dict		  =			num_hidden_layers
      UpperCAmelCase						:				str		  =			num_attention_heads
      UpperCAmelCase						:				Optional[Any]		  =			intermediate_size
      UpperCAmelCase						:				Any		  =			hidden_act
      UpperCAmelCase						:				int		  =			hidden_dropout_prob
      UpperCAmelCase						:				List[str]		  =			attention_probs_dropout_prob
      UpperCAmelCase						:				List[Any]		  =			max_position_embeddings
      UpperCAmelCase						:				Optional[Any]		  =			initializer_range
      UpperCAmelCase						:				Union[str, Any]		  =			None
      UpperCAmelCase						:				Union[str, Any]		  =			vocab_size - 1
      UpperCAmelCase						:				List[str]		  =			vocab_size - 1
      UpperCAmelCase						:				Dict		  =			vocab_size - 1
 def   _UpperCamelCase    (			self					: List[str]				)    ->			int:
      UpperCAmelCase						:				Optional[int]		  =			ids_tensor([self.batch_size, self.seq_length]       ,    self.vocab_size				)

      UpperCAmelCase						:				List[str]		  =			None
      if self.use_input_mask:
           UpperCAmelCase						:				Dict		  =			random_attention_mask([self.batch_size, self.seq_length]				)

      UpperCAmelCase						:				List[str]		  =			GPTaConfig(
          vocab_size=self.vocab_size       ,    n_embd=self.hidden_size       ,    n_layer=self.num_hidden_layers       ,    n_head=self.num_attention_heads       ,    n_positions=self.max_position_embeddings       ,    use_cache=__snake_case       ,    bos_token_id=self.bos_token_id       ,    eos_token_id=self.eos_token_id       ,    pad_token_id=self.pad_token_id       ,    )

      return (config, input_ids, input_mask)
 def   _UpperCamelCase    (			self					: Dict				)    ->			int:
      UpperCAmelCase						:				Union[str, Any]		  =			self.prepare_config_and_inputs()
      UpperCAmelCase  , UpperCAmelCase  , UpperCAmelCase						:				Union[str, Any]		  =			config_and_inputs
      UpperCAmelCase						:				Any		  =			{"input_ids": input_ids, "attention_mask": attention_mask}
      return config, inputs_dict
 def   _UpperCamelCase    (			self					: Tuple				)    ->			Tuple:
      UpperCAmelCase  , UpperCAmelCase  , UpperCAmelCase						:				Optional[int]		  =			self.prepare_config_and_inputs()

      UpperCAmelCase						:				Optional[int]		  =			floats_tensor([self.batch_size, self.seq_length, self.hidden_size]				)
      UpperCAmelCase						:				Dict		  =			ids_tensor([self.batch_size, self.seq_length]       ,    vocab_size=2				)

      return (
          config,
          input_ids,
          attention_mask,
          encoder_hidden_states,
          encoder_attention_mask,
      )
 def   _UpperCamelCase    (			self					: Optional[Any]       ,    _a					: str       ,    _a					: Dict       ,    _a					: int       ,    _a					: List[Any]				)    ->			Any:
      UpperCAmelCase						:				Optional[Any]		  =			2_0
      UpperCAmelCase						:				Any		  =			model_class_name(__snake_case				)

      UpperCAmelCase						:				Tuple		  =			model.init_cache(input_ids.shape[0]       ,    __snake_case				)
      UpperCAmelCase						:				int		  =			jnp.ones((input_ids.shape[0], max_decoder_length)       ,    dtype="i4"				)

      UpperCAmelCase						:				Optional[int]		  =			jnp.broadcast_to(
          jnp.arange(input_ids.shape[-1] - 1				)[None, :]       ,    (input_ids.shape[0], input_ids.shape[-1] - 1)				)
      UpperCAmelCase						:				Optional[int]		  =			model(
          input_ids[:, :-1]       ,    attention_mask=__snake_case       ,    past_key_values=__snake_case       ,    position_ids=__snake_case       ,    )

      UpperCAmelCase						:				Any		  =			jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]       ,    dtype="i4"				)
      UpperCAmelCase						:				Optional[Any]		  =			model(
          input_ids[:, -1:]       ,    attention_mask=__snake_case       ,    past_key_values=outputs_cache.past_key_values       ,    position_ids=__snake_case       ,    )

      UpperCAmelCase						:				Any		  =			model(__snake_case				)

      UpperCAmelCase						:				Optional[Any]		  =			np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])				)				)
      self.parent.assertTrue(diff < 1E-3       ,    msg=f'Max diff is {diff}'				)

 def   _UpperCamelCase    (			self					: Any       ,    _a					: Optional[int]       ,    _a					: int       ,    _a					: str       ,    _a					: List[str]				)    ->			Union[str, Any]:
      UpperCAmelCase						:				Dict		  =			2_0
      UpperCAmelCase						:				int		  =			model_class_name(__snake_case				)

      UpperCAmelCase						:				Optional[int]		  =			jnp.concatenate(
          [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1])				)]       ,    axis=-1       ,    )

      UpperCAmelCase						:				int		  =			model.init_cache(input_ids.shape[0]       ,    __snake_case				)
      UpperCAmelCase						:				List[Any]		  =			jnp.broadcast_to(
          jnp.arange(input_ids.shape[-1] - 1				)[None, :]       ,    (input_ids.shape[0], input_ids.shape[-1] - 1)				)

      UpperCAmelCase						:				Union[str, Any]		  =			model(
          input_ids[:, :-1]       ,    attention_mask=__snake_case       ,    past_key_values=__snake_case       ,    position_ids=__snake_case       ,    )
      UpperCAmelCase						:				str		  =			jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]       ,    dtype="i4"				)
      UpperCAmelCase						:				List[str]		  =			model(
          input_ids[:, -1:]       ,    past_key_values=outputs_cache.past_key_values       ,    attention_mask=__snake_case       ,    position_ids=__snake_case       ,    )

      UpperCAmelCase						:				Any		  =			model(__snake_case       ,    attention_mask=__snake_case				)

      UpperCAmelCase						:				Optional[Any]		  =			np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])				)				)
      self.parent.assertTrue(diff < 1E-3       ,    msg=f'Max diff is {diff}'				)




@require_flax
class    A_   ( snake_case__      ,						snake_case__      ,						unittest.TestCase     ):
 _UpperCamelCase				: Optional[int]      =					(FlaxGPTaModel, FlaxGPTaLMHeadModel) if is_flax_available() else ()
 _UpperCamelCase				: Union[str, Any]      =					(FlaxGPTaLMHeadModel,) if is_flax_available() else ()
 def   _UpperCamelCase    (			self					: str				)    ->			str:
      UpperCAmelCase						:				Union[str, Any]		  =			FlaxGPTaModelTester(self				)
 def   _UpperCamelCase    (			self					: Optional[int]				)    ->			Optional[int]:
      for model_class_name in self.all_model_classes:
           UpperCAmelCase  , UpperCAmelCase  , UpperCAmelCase						:				List[Any]		  =			self.model_tester.prepare_config_and_inputs()
           self.model_tester.check_use_cache_forward(__snake_case       ,    __snake_case       ,    __snake_case       ,    __snake_case				)
 def   _UpperCamelCase    (			self					: Union[str, Any]				)    ->			Any:
      for model_class_name in self.all_model_classes:
           UpperCAmelCase  , UpperCAmelCase  , UpperCAmelCase						:				str		  =			self.model_tester.prepare_config_and_inputs()
           self.model_tester.check_use_cache_forward_with_attn_mask(
               __snake_case       ,    __snake_case       ,    __snake_case       ,    __snake_case				)
 @slow
 def   _UpperCamelCase    (			self					: List[Any]				)    ->			List[Any]:
      UpperCAmelCase						:				str		  =			GPTaTokenizer.from_pretrained("gpt2"       ,    pad_token="</s>"       ,    padding_side="left"				)
      UpperCAmelCase						:				List[Any]		  =			tokenizer(["Hello this is a long string", "Hey"]       ,    return_tensors="np"       ,    padding=__snake_case       ,    truncation=__snake_case				)

      UpperCAmelCase						:				Optional[int]		  =			FlaxGPTaLMHeadModel.from_pretrained("gpt2"				)
      UpperCAmelCase						:				Any		  =			False
      UpperCAmelCase						:				Any		  =			model.config.eos_token_id

      UpperCAmelCase						:				Union[str, Any]		  =			jax.jit(model.generate				)

      UpperCAmelCase						:				Any		  =			jit_generate(inputs["input_ids"]       ,    attention_mask=inputs["attention_mask"]				).sequences

      UpperCAmelCase						:				Optional[int]		  =			tokenizer.batch_decode(__snake_case       ,    skip_special_tokens=__snake_case				)

      UpperCAmelCase						:				Any		  =			[
          "Hello this is a long string of words. I\'m going to start with the first one.\n",
          "Hey, I\'m not sure if I\'m going to be able to do",
      ]

      self.assertListEqual(__snake_case       ,    __snake_case				)
 @is_pt_flax_cross_test
 def   _UpperCamelCase    (			self					: int				)    ->			Optional[int]:
      UpperCAmelCase  , UpperCAmelCase						:				Optional[int]		  =			self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
           with self.subTest(model_class.__name__				):
                # prepare inputs
                UpperCAmelCase						:				int		  =			self._prepare_for_class(__snake_case       ,    __snake_case				)
                UpperCAmelCase						:				Optional[Any]		  =			{k: torch.tensor(v.tolist()				) for k, v in prepared_inputs_dict.items()}

                # load corresponding PyTorch class
                UpperCAmelCase						:				Optional[Any]		  =			model_class.__name__[4:]  # Skip the "Flax" at the beginning
                UpperCAmelCase						:				Union[str, Any]		  =			getattr(__snake_case       ,    __snake_case				)

                UpperCAmelCase  , UpperCAmelCase						:				Optional[Any]		  =			pt_inputs["input_ids"].shape
                UpperCAmelCase						:				List[str]		  =			np.random.randint(0       ,    seq_length - 1       ,    size=(batch_size,)				)
                for batch_idx, start_index in enumerate(__snake_case				):
                     UpperCAmelCase						:				Optional[Any]		  =			0
                     UpperCAmelCase						:				List[Any]		  =			1
                     UpperCAmelCase						:				Dict		  =			0
                     UpperCAmelCase						:				Dict		  =			1
                UpperCAmelCase						:				Tuple		  =			pt_model_class(__snake_case				).eval()
                UpperCAmelCase						:				List[str]		  =			model_class(__snake_case       ,    dtype=jnp.floataa				)

                UpperCAmelCase						:				Any		  =			convert_pytorch_state_dict_to_flax(pt_model.state_dict()       ,    __snake_case				)
                UpperCAmelCase						:				Union[str, Any]		  =			fx_state

                with torch.no_grad():
                     UpperCAmelCase						:				Tuple		  =			pt_model(**__snake_case				).to_tuple()

                UpperCAmelCase						:				Any		  =			fx_model(**__snake_case				).to_tuple()
                self.assertEqual(len(__snake_case				)       ,    len(__snake_case				)       ,    "Output lengths differ between Flax and PyTorch"				)
                for fx_output, pt_output in zip(__snake_case       ,    __snake_case				):
                     self.assert_almost_equals(fx_output[:, -1]       ,    pt_output[:, -1].numpy()       ,    4E-2				)

                with tempfile.TemporaryDirectory() as tmpdirname:
                     pt_model.save_pretrained(__snake_case				)
                     UpperCAmelCase						:				Optional[int]		  =			model_class.from_pretrained(__snake_case       ,    from_pt=__snake_case				)

                UpperCAmelCase						:				Union[str, Any]		  =			fx_model_loaded(**__snake_case				).to_tuple()
                self.assertEqual(
                    len(__snake_case				)       ,    len(__snake_case				)       ,    "Output lengths differ between Flax and PyTorch"				)
                for fx_output_loaded, pt_output in zip(__snake_case       ,    __snake_case				):
                     self.assert_almost_equals(fx_output_loaded[:, -1]       ,    pt_output[:, -1].numpy()       ,    4E-2				)
 @is_pt_flax_cross_test
 def   _UpperCamelCase    (			self					: Any				)    ->			List[Any]:
      UpperCAmelCase  , UpperCAmelCase						:				Tuple		  =			self.model_tester.prepare_config_and_inputs_for_common()
      for model_class in self.all_model_classes:
           with self.subTest(model_class.__name__				):
                # prepare inputs
                UpperCAmelCase						:				Any		  =			self._prepare_for_class(__snake_case       ,    __snake_case				)
                UpperCAmelCase						:				Any		  =			{k: torch.tensor(v.tolist()				) for k, v in prepared_inputs_dict.items()}

                # load corresponding PyTorch class
                UpperCAmelCase						:				List[str]		  =			model_class.__name__[4:]  # Skip the "Flax" at the beginning
                UpperCAmelCase						:				str		  =			getattr(__snake_case       ,    __snake_case				)

                UpperCAmelCase						:				Union[str, Any]		  =			pt_model_class(__snake_case				).eval()
                UpperCAmelCase						:				str		  =			model_class(__snake_case       ,    dtype=jnp.floataa				)

                UpperCAmelCase						:				List[str]		  =			load_flax_weights_in_pytorch_model(__snake_case       ,    fx_model.params				)
                UpperCAmelCase  , UpperCAmelCase						:				Union[str, Any]		  =			pt_inputs["input_ids"].shape
                UpperCAmelCase						:				List[Any]		  =			np.random.randint(0       ,    seq_length - 1       ,    size=(batch_size,)				)
                for batch_idx, start_index in enumerate(__snake_case				):
                     UpperCAmelCase						:				Optional[int]		  =			0
                     UpperCAmelCase						:				Union[str, Any]		  =			1
                     UpperCAmelCase						:				int		  =			0
                     UpperCAmelCase						:				List[str]		  =			1

                # make sure weights are tied in PyTorch
                pt_model.tie_weights()

                with torch.no_grad():
                     UpperCAmelCase						:				Tuple		  =			pt_model(**__snake_case				).to_tuple()

                UpperCAmelCase						:				Dict		  =			fx_model(**__snake_case				).to_tuple()
                self.assertEqual(len(__snake_case				)       ,    len(__snake_case				)       ,    "Output lengths differ between Flax and PyTorch"				)
                for fx_output, pt_output in zip(__snake_case       ,    __snake_case				):
                     self.assert_almost_equals(fx_output[:, -1]       ,    pt_output[:, -1].numpy()       ,    4E-2				)

                with tempfile.TemporaryDirectory() as tmpdirname:
                     fx_model.save_pretrained(__snake_case				)
                     UpperCAmelCase						:				Union[str, Any]		  =			pt_model_class.from_pretrained(__snake_case       ,    from_flax=__snake_case				)

                with torch.no_grad():
                     UpperCAmelCase						:				Optional[Any]		  =			pt_model_loaded(**__snake_case				).to_tuple()

                self.assertEqual(
                    len(__snake_case				)       ,    len(__snake_case				)       ,    "Output lengths differ between Flax and PyTorch"				)
                for fx_output, pt_output in zip(__snake_case       ,    __snake_case				):
                     self.assert_almost_equals(fx_output[:, -1]       ,    pt_output[:, -1].numpy()       ,    4E-2				)

 @slow
 def   _UpperCamelCase    (			self					: str				)    ->			Optional[Any]:
      for model_class_name in self.all_model_classes:
           UpperCAmelCase						:				List[Any]		  =			model_class_name.from_pretrained("gpt2"       ,    from_pt=__snake_case				)
           UpperCAmelCase						:				Tuple		  =			model(np.ones((1, 1)				)				)
           self.assertIsNotNone(__snake_case				)







# 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   A   (		A__ ):
     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:
          UpperCAmelCase						:				Optional[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
               ):
                    UpperCAmelCase						:				Optional[Any]		  =			ClusterConfig
               else:
                    UpperCAmelCase						:				int		  =			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
               ):
                    UpperCAmelCase						:				int		  =			ClusterConfig
               else:
                    UpperCAmelCase						:				Optional[Any]		  =			SageMakerConfig
               return config_class.from_yaml_file(yaml_file=A__ )




@dataclass
class    A_   :







 """simple docstring"""





 _UpperCamelCase				: ComputeEnvironment
 _UpperCamelCase				: Union[DistributedType, SageMakerDistributedType]
 _UpperCamelCase				: str
 _UpperCamelCase				: bool
 def   _UpperCamelCase    (			self					: Tuple				)    ->			Optional[int]:
      UpperCAmelCase						:				Optional[int]		  =			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(_a       ,    _a				):
                UpperCAmelCase						:				Any		  =			value.value
           if isinstance(_a       ,    _a				) and not bool(_a				):
                UpperCAmelCase						:				Dict		  =			None
      UpperCAmelCase						:				Union[str, Any]		  =			{k: v for k, v in result.items() if v is not None}
      return result
 @classmethod
 def   _UpperCamelCase    (			cls					: Dict       ,    _a					: List[Any]=None				)    ->			Optional[int]:
      UpperCAmelCase						:				int		  =			default_json_config_file if json_file is None else json_file
      with open(_a       ,    "r"       ,    encoding="utf-8"				) as f:
           UpperCAmelCase						:				str		  =			json.load(_a				)
      if "compute_environment" not in config_dict:
           UpperCAmelCase						:				List[Any]		  =			ComputeEnvironment.LOCAL_MACHINE
      if "mixed_precision" not in config_dict:
           UpperCAmelCase						:				List[str]		  =			"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						:				Dict		  =			config_dict.pop("dynamo_backend"				)
           UpperCAmelCase						:				Optional[int]		  =			{} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
      if "use_cpu" not in config_dict:
           UpperCAmelCase						:				Dict		  =			False
      return cls(**_a				)
 def   _UpperCamelCase    (			self					: List[Any]       ,    _a					: Optional[int]				)    ->			Dict:
      with open(_a       ,    "w"       ,    encoding="utf-8"				) as f:
           UpperCAmelCase						:				Tuple		  =			json.dumps(self.to_dict()       ,    indent=2       ,    sort_keys=_a				) + "\n"
           f.write(_a				)
 @classmethod
 def   _UpperCamelCase    (			cls					: int       ,    _a					: Optional[int]=None				)    ->			Dict:
      UpperCAmelCase						:				Optional[int]		  =			default_yaml_config_file if yaml_file is None else yaml_file
      with open(_a       ,    "r"       ,    encoding="utf-8"				) as f:
           UpperCAmelCase						:				str		  =			yaml.safe_load(_a				)
      if "compute_environment" not in config_dict:
           UpperCAmelCase						:				Dict		  =			ComputeEnvironment.LOCAL_MACHINE

      if "mixed_precision" not in config_dict:
           UpperCAmelCase						:				List[str]		  =			"fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None
      if isinstance(config_dict["mixed_precision"]       ,    _a				) and not config_dict["mixed_precision"]:
           UpperCAmelCase						:				Tuple		  =			"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						:				str		  =			config_dict.pop("dynamo_backend"				)
           UpperCAmelCase						:				Tuple		  =			{} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
      if "use_cpu" not in config_dict:
           UpperCAmelCase						:				List[str]		  =			False
      return cls(**_a				)
 def   _UpperCamelCase    (			self					: Optional[Any]       ,    _a					: str				)    ->			int:
      with open(_a       ,    "w"       ,    encoding="utf-8"				) as f:
           yaml.safe_dump(self.to_dict()       ,    _a				)

 def   _UpperCamelCase    (			self					: Tuple				)    ->			List[Any]:
      if isinstance(self.compute_environment       ,    _a				):
           UpperCAmelCase						:				str		  =			ComputeEnvironment(self.compute_environment				)
      if isinstance(self.distributed_type       ,    _a				):
           if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
                UpperCAmelCase						:				Optional[int]		  =			SageMakerDistributedType(self.distributed_type				)
           else:
                UpperCAmelCase						:				str		  =			DistributedType(self.distributed_type				)
      if self.dynamo_config is None:
           UpperCAmelCase						:				List[str]		  =			{}




@dataclass
class    A_   ( a_     ):







 """simple docstring"""





 _UpperCamelCase				: int
 _UpperCamelCase				: int      =					0
 _UpperCamelCase				: int      =					1
 _UpperCamelCase				: Optional[str]      =					None
 _UpperCamelCase				: Optional[str]      =					None
 _UpperCamelCase				: Optional[int]      =					None
 _UpperCamelCase				: Optional[str]      =					"static"
 _UpperCamelCase				: Optional[bool]      =					False
 _UpperCamelCase				: str      =					"main"

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

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

 # args for dynamo
 _UpperCamelCase				: dict      =					None
 def   _UpperCamelCase    (			self					: Union[str, Any]				)    ->			Optional[int]:
      if self.deepspeed_config is None:
           UpperCAmelCase						:				int		  =			{}
      if self.fsdp_config is None:
           UpperCAmelCase						:				str		  =			{}
      if self.megatron_lm_config is None:
           UpperCAmelCase						:				Optional[int]		  =			{}
      if self.ipex_config is None:
           UpperCAmelCase						:				int		  =			{}
      return super().__post_init__()




@dataclass
class    A_   ( a_     ):







 """simple docstring"""





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



