
"""simple docstring"""
from __future__ import annotations

import unittest

from transformers import AutoTokenizer, GPTJConfig, is_tf_available
from transformers.testing_utils import require_tf, slow, tooslow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
from ...utils.test_modeling_tf_core import TFCoreModelTesterMixin


if is_tf_available():
    import tensorflow as tf

    from transformers.models.gptj.modeling_tf_gptj import (
        TFGPTJForCausalLM,
        TFGPTJForQuestionAnswering,
        TFGPTJForSequenceClassification,
        TFGPTJModel,
        shape_list,
    )






class   _UpperCAmelCase					:
    def __init__(     self    ,     snake_case_  ):
      _snake_case  :    Any            = parent
      _snake_case  :    Optional[Any]            = 13
      _snake_case  :    Union[str, Any]            = 7
      _snake_case  :    Dict            = True
      _snake_case  :    Tuple            = True
      _snake_case  :    Optional[Any]            = True
      _snake_case  :    int            = True
      _snake_case  :    Dict            = True
      _snake_case  :    Any            = 99
      _snake_case  :    str            = 32
      _snake_case  :    str            = 4
      _snake_case  :    Any            = 2
      _snake_case  :    Tuple            = 4
      _snake_case  :    Optional[int]            = 37
      _snake_case  :    Tuple            = "gelu"
      _snake_case  :    int            = 0.1
      _snake_case  :    Union[str, Any]            = 0.1
      _snake_case  :    Tuple            = 5_12
      _snake_case  :    Optional[Any]            = 16
      _snake_case  :    Optional[int]            = 2
      _snake_case  :    Any            = 0.02
      _snake_case  :    List[Any]            = 3
      _snake_case  :    Optional[int]            = 4
      _snake_case  :    Any            = None
      _snake_case  :    Union[str, Any]            = self.vocab_size - 1
      _snake_case  :    List[Any]            = self.vocab_size - 1
      _snake_case  :    Optional[Any]            = self.vocab_size - 1
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Optional[Any]            = ids_tensor([self.batch_size, self.seq_length]    ,     self.vocab_size  )

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

      _snake_case  :    int            = None
      if self.use_token_type_ids:
        _snake_case  :    int            = ids_tensor([self.batch_size, self.seq_length]    ,     self.type_vocab_size  )

      _snake_case  :    str            = None
      if self.use_mc_token_ids:
        _snake_case  :    Tuple            = ids_tensor([self.batch_size, self.num_choices]    ,     self.seq_length  )

      _snake_case  :    List[str]            = None
      _snake_case  :    Optional[Any]            = None
      _snake_case  :    Tuple            = None
      if self.use_labels:
        _snake_case  :    Optional[Any]            = ids_tensor([self.batch_size]    ,     self.type_sequence_label_size  )
        _snake_case  :    Any            = ids_tensor([self.batch_size, self.seq_length]    ,     self.num_labels  )
        _snake_case  :    List[Any]            = ids_tensor([self.batch_size]    ,     self.num_choices  )

      _snake_case  :    Optional[Any]            = GPTJConfig(
          vocab_size=self.vocab_size    ,     n_embd=self.hidden_size    ,     n_layer=self.num_hidden_layers    ,     n_head=self.num_attention_heads    ,     intermediate_size=self.intermediate_size    ,     hidden_act=self.hidden_act    ,     hidden_dropout_prob=self.hidden_dropout_prob    ,     attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,     n_positions=self.max_position_embeddings    ,     type_vocab_size=self.type_vocab_size    ,     initializer_range=self.initializer_range    ,     bos_token_id=self.bos_token_id    ,     eos_token_id=self.eos_token_id    ,     pad_token_id=self.pad_token_id    ,     rotary_dim=self.rotary_dim    ,     return_dict=snake_case_    ,     )

      _snake_case  :    Union[str, Any]            = ids_tensor([self.num_hidden_layers, self.num_attention_heads]    ,     2  )

      return (
          config,
          input_ids,
          input_mask,
          head_mask,
          token_type_ids,
          mc_token_ids,
          sequence_labels,
          token_labels,
          choice_labels,
      )
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     *snake_case_  ):
      _snake_case  :    Optional[int]            = TFGPTJModel(config=snake_case_  )
      _snake_case  :    Tuple            = {
          "input_ids": input_ids,
          "attention_mask": input_mask,
          "token_type_ids": token_type_ids,
      }
      _snake_case  :    int            = model(snake_case_  )

      _snake_case  :    List[Any]            = [input_ids, None, input_mask]  # None is the input for 'past'
      _snake_case  :    List[Any]            = model(snake_case_  )

      _snake_case  :    Optional[Any]            = model(snake_case_  )

      self.parent.assertEqual(result.last_hidden_state.shape    ,     (self.batch_size, self.seq_length, self.hidden_size)  )
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     *snake_case_  ):
      _snake_case  :    List[str]            = TFGPTJModel(config=snake_case_  )

      # first forward pass
      _snake_case  :    Tuple            = model(snake_case_    ,     token_type_ids=snake_case_    ,     use_cache=snake_case_  )
      _snake_case  :    Dict            = model(snake_case_    ,     token_type_ids=snake_case_  )
      _snake_case  :    Optional[int]            = model(snake_case_    ,     token_type_ids=snake_case_    ,     use_cache=snake_case_  )

      self.parent.assertTrue(len(snake_case_  ) == len(snake_case_  )  )
      self.parent.assertTrue(len(snake_case_  ) == len(snake_case_  ) + 1  )

      _snake_case      ,       _snake_case  :    Any            = outputs.to_tuple()

      # create hypothetical next token and extent to next_input_ids
      _snake_case  :    int            = ids_tensor((self.batch_size, 1)    ,     config.vocab_size  )
      _snake_case  :    Optional[int]            = ids_tensor([self.batch_size, 1]    ,     self.type_vocab_size  )

      # append to next input_ids and token_type_ids
      _snake_case  :    Dict            = tf.concat([input_ids, next_tokens]    ,     axis=-1  )
      _snake_case  :    Optional[Any]            = tf.concat([token_type_ids, next_token_types]    ,     axis=-1  )

      _snake_case  :    Union[str, Any]            = model(snake_case_    ,     token_type_ids=snake_case_  )["last_hidden_state"]
      _snake_case  :    Union[str, Any]            = model(snake_case_    ,     token_type_ids=snake_case_    ,     past_key_values=snake_case_  )[
          "last_hidden_state"
      ]

      # select random slice
      _snake_case  :    Dict            = int(ids_tensor((1,)    ,     shape_list(snake_case_  )[-1]  )  )
      _snake_case  :    Any            = output_from_no_past[:, -1, random_slice_idx]
      _snake_case  :    Dict            = output_from_past[:, 0, random_slice_idx]

      # test that outputs are equal for slice
      tf.debugging.assert_near(snake_case_    ,     snake_case_    ,     rtol=1E-6  )
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     *snake_case_  ):
      _snake_case  :    Optional[int]            = TFGPTJModel(config=snake_case_  )

      # create attention mask
      _snake_case  :    Dict            = self.seq_length // 2
      _snake_case  :    Optional[int]            = tf.ones((self.batch_size, half_seq_length)    ,     dtype=tf.intaa  )
      _snake_case  :    Any            = tf.zeros((self.batch_size, self.seq_length - half_seq_length)    ,     dtype=tf.intaa  )
      _snake_case  :    Optional[Any]            = tf.concat([attn_mask_begin, attn_mask_end]    ,     axis=1  )

      # first forward pass
      _snake_case      ,       _snake_case  :    Tuple            = model(snake_case_    ,     attention_mask=snake_case_  ).to_tuple()

      # create hypothetical next token and extent to next_input_ids
      _snake_case  :    Dict            = ids_tensor((self.batch_size, 1)    ,     config.vocab_size  )

      # change a random masked slice from input_ids
      _snake_case  :    List[str]            = ids_tensor((1,)    ,     snake_case_  ).numpy() + 1
      _snake_case  :    Dict            = ids_tensor((self.batch_size, self.seq_length)    ,     config.vocab_size  )
      _snake_case  :    Union[str, Any]            = tf.range(self.seq_length  ) == (self.seq_length - random_seq_idx_to_change)
      _snake_case  :    List[str]            = tf.transpose(
          tf.broadcast_to(tf.expand_dims(snake_case_    ,     -1  )    ,     (self.seq_length, self.batch_size)  )  )
      _snake_case  :    List[Any]            = tf.where(snake_case_    ,     snake_case_    ,     snake_case_  )

      # append to next input_ids and attn_mask
      _snake_case  :    int            = tf.concat([input_ids, next_tokens]    ,     axis=-1  )
      _snake_case  :    str            = tf.concat([attn_mask, tf.ones((shape_list(snake_case_  )[0], 1)    ,     dtype=tf.intaa  )]    ,     axis=1  )

      # get two different outputs
      _snake_case  :    Tuple            = model(snake_case_    ,     attention_mask=snake_case_  )["last_hidden_state"]
      _snake_case  :    Union[str, Any]            = model(snake_case_    ,     past_key_values=snake_case_    ,     attention_mask=snake_case_  )[
          "last_hidden_state"
      ]

      # select random slice
      _snake_case  :    Optional[int]            = int(ids_tensor((1,)    ,     shape_list(snake_case_  )[-1]  )  )
      _snake_case  :    List[str]            = output_from_no_past[:, -1, random_slice_idx]
      _snake_case  :    int            = output_from_past[:, 0, random_slice_idx]

      # test that outputs are equal for slice
      tf.debugging.assert_near(snake_case_    ,     snake_case_    ,     rtol=1E-12  )
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     *snake_case_  ):
      _snake_case  :    List[str]            = TFGPTJModel(config=snake_case_  )

      _snake_case  :    Dict            = input_ids[:1, :]
      _snake_case  :    List[Any]            = input_mask[:1, :]
      _snake_case  :    Tuple            = token_type_ids[:1, :]
      _snake_case  :    Union[str, Any]            = 1

      # first forward pass
      _snake_case  :    int            = model(snake_case_    ,     attention_mask=snake_case_    ,     token_type_ids=snake_case_    ,     use_cache=snake_case_  )

      _snake_case      ,       _snake_case  :    List[str]            = outputs.to_tuple()

      # create hypothetical next token and extent to next_input_ids
      _snake_case  :    int            = ids_tensor((self.batch_size, 3)    ,     config.vocab_size  )
      _snake_case  :    Optional[int]            = ids_tensor((self.batch_size, 3)    ,     2  )
      _snake_case  :    Dict            = ids_tensor((self.batch_size, 3)    ,     self.type_vocab_size  )

      # append to next input_ids and token_type_ids
      _snake_case  :    Optional[Any]            = tf.concat([input_ids, next_tokens]    ,     axis=-1  )
      _snake_case  :    Tuple            = tf.concat([input_mask, next_attn_mask]    ,     axis=-1  )
      _snake_case  :    Optional[Any]            = tf.concat([token_type_ids, next_token_types]    ,     axis=-1  )

      _snake_case  :    str            = model(
          snake_case_    ,     token_type_ids=snake_case_    ,     attention_mask=snake_case_  )["last_hidden_state"]
      _snake_case  :    Tuple            = model(
          snake_case_    ,     token_type_ids=snake_case_    ,     attention_mask=snake_case_    ,     past_key_values=snake_case_    ,     )["last_hidden_state"]
      self.parent.assertTrue(output_from_past.shape[1] == next_tokens.shape[1]  )

      # select random slice
      _snake_case  :    Any            = int(ids_tensor((1,)    ,     shape_list(snake_case_  )[-1]  )  )
      _snake_case  :    str            = output_from_no_past[:, -3:, random_slice_idx]
      _snake_case  :    List[Any]            = output_from_past[:, :, random_slice_idx]

      # test that outputs are equal for slice
      tf.debugging.assert_near(snake_case_    ,     snake_case_    ,     rtol=1E-3  )
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     *snake_case_  ):
      _snake_case  :    Dict            = TFGPTJForCausalLM(config=snake_case_  )
      _snake_case  :    Optional[Any]            = {
          "input_ids": input_ids,
          "attention_mask": input_mask,
          "token_type_ids": token_type_ids,
      }
      _snake_case  :    List[Any]            = model(snake_case_  )
      self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.seq_length, self.vocab_size)  )


    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Tuple            = self.prepare_config_and_inputs()

      (
          (
          _snake_case
      )      ,       (
          _snake_case
      )      ,       (
          _snake_case
      )      ,       (
          _snake_case
      )      ,       (
          _snake_case
      )      ,       (
          _snake_case
      )      ,       (
          _snake_case
      )      ,       (
          _snake_case
      )      ,       (
          _snake_case
      )      ,       
      )  :    Tuple            = config_and_inputs

      _snake_case  :    Any            = {
          "input_ids": input_ids,
          "token_type_ids": token_type_ids,
          "attention_mask": input_mask,
      }
      return config, inputs_dict






@require_tf
class   _UpperCAmelCase					(       _snake_case		,       _snake_case		,       _snake_case		,       unittest.TestCase):
    __lowercase				:			Dict	=       (
        (TFGPTJForCausalLM, TFGPTJForSequenceClassification, TFGPTJForQuestionAnswering, TFGPTJModel)
        if is_tf_available()
        else ()
    )

    __lowercase				:			Optional[Any]	=       (TFGPTJForCausalLM,) if is_tf_available() else ()
    __lowercase				:			List[Any]	=       (
        {
            """feature-extraction""": TFGPTJModel,
            """question-answering""": TFGPTJForQuestionAnswering,
            """text-classification""": TFGPTJForSequenceClassification,
            """text-generation""": TFGPTJForCausalLM,
            """zero-shot""": TFGPTJForSequenceClassification,
        }
        if is_tf_available()
        else {}
    )
    __lowercase				:			Any	=       False
    __lowercase				:			str	=       False
    __lowercase				:			Optional[int]	=       False
    __lowercase				:			Optional[Any]	=       False
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_  ):
      if (
          pipeline_test_casse_name == "QAPipelineTests"
          and tokenizer_name is not None
          and not tokenizer_name.endswith("Fast"  )
      ):
        # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
        # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
        # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
        return True

      return False
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    List[Any]            = TFGPTJModelTester(self  )
      _snake_case  :    List[str]            = ConfigTester(self    ,     config_class=snake_case_    ,     n_embd=37  )
    def        lowerCamelCase__						(     self  ):
      self.config_tester.run_common_tests()
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    List[str]            = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_gptj_model(*snake_case_  )
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Tuple            = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_gptj_model_past(*snake_case_  )
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Optional[Any]            = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_gptj_model_attention_mask_past(*snake_case_  )
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Tuple            = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_gptj_model_past_large_inputs(*snake_case_  )
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Dict            = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_gptj_lm_head_model(*snake_case_  )
    @slow
    @unittest.skipIf(
        not is_tf_available() or len(tf.config.list_physical_devices("GPU"  )  ) > 0    ,     "skip testing on GPU for now to avoid GPU OOM."    ,     )
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Tuple            = TFGPTJModel.from_pretrained("EleutherAI/gpt-j-6B"    ,     from_pt=snake_case_  )
      self.assertIsNotNone(snake_case_  )


    @unittest.skip(reason="Currently, model embeddings are going to undergo a major refactor."  )
    def        lowerCamelCase__						(     self  ):
      super().test_resize_token_embeddings()






@require_tf
@tooslow
# Marked as @tooslow due to GPU OOM -- but still useful to run locally. Requires ~39GB of RAM.
class   _UpperCAmelCase					(       unittest.TestCase):
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Optional[Any]            = TFGPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B"    ,     from_pt=snake_case_  )
      _snake_case  :    int            = tf.convert_to_tensor([[4_64, 32_90]]    ,     dtype=tf.intaa  )  # The dog
      # fmt: off
      # The dog is a man's best friend. It is a loyal companion, and it is a friend
      _snake_case  :    List[Any]            = [4_64, 32_90, 3_18, 2_57, 5_82, 3_38, 12_66, 15_45, 13, 6_32, 3_18, 2_57, 91_12, 1_51_85, 11, 2_90, 3_40, 3_18, 2_57, 15_45]
      # fmt: on
      _snake_case  :    Optional[Any]            = model.generate(snake_case_    ,     do_sample=snake_case_  )
      self.assertListEqual(output_ids[0].numpy().tolist()    ,     snake_case_  )
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Dict            = AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B"    ,     revision="float16"  )
      _snake_case  :    Optional[Any]            = TFGPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B"    ,     revision="float16"    ,     from_pt=snake_case_  )

      _snake_case  :    Tuple            = tokenizer("Today is a nice day and"    ,     return_tensors="tf"  )
      # forces the generation to happen on CPU, to avoid GPU-related quirks
      with tf.device(":/CPU:0"  ):
        _snake_case  :    Any            = model.generate(**snake_case_    ,     do_sample=snake_case_    ,     seed=[42, 0]  )
      _snake_case  :    List[Any]            = tokenizer.decode(output_ids[0]    ,     skip_special_tokens=snake_case_  )

      _snake_case  :    List[str]            = "Today is a nice day and I’m going to go for a walk. I’"
      self.assertEqual(snake_case_    ,     snake_case_  )
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    int            = TFGPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B"    ,     revision="float16"    ,     from_pt=snake_case_  )
      _snake_case  :    Union[str, Any]            = AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B"    ,     revision="float16"  )

      _snake_case  :    str            = "left"

      # Define PAD Token = EOS Token = 50256
      _snake_case  :    Tuple            = tokenizer.eos_token
      _snake_case  :    Any            = model.config.eos_token_id

      # use different length sentences to test batching
      _snake_case  :    Optional[int]            = [
          "Hello, my dog is a little",
          "Today, I",
      ]
      _snake_case  :    List[Any]            = [
          "Hello, my dog is a little over a year old and has been diagnosed with hip dysplasia",
          "Today, I’m going to be talking about a topic that’",
      ]
      return model, tokenizer, sentences, expected_output_sentences
    def        lowerCamelCase__						(     self  ):
      # Confirms that we get the expected results with left-padded beam search
      _snake_case      ,       _snake_case      ,       _snake_case      ,       _snake_case  :    Optional[int]            = self._get_beam_search_test_objects()

      _snake_case  :    Tuple            = tokenizer(snake_case_    ,     return_tensors="tf"    ,     padding=snake_case_  )
      _snake_case  :    int            = model.generate(**snake_case_    ,     do_sample=snake_case_    ,     num_beams=2  )
      _snake_case  :    List[str]            = tokenizer.batch_decode(snake_case_    ,     skip_special_tokens=snake_case_  )
      self.assertListEqual(snake_case_    ,     snake_case_  )
    def        lowerCamelCase__						(     self  ):
      # Confirms that left-padding is working properly
      _snake_case      ,       _snake_case      ,       _snake_case      ,       _snake_case  :    Any            = self._get_beam_search_test_objects()

      _snake_case  :    Dict            = tokenizer(snake_case_    ,     return_tensors="tf"    ,     padding=snake_case_  )
      _snake_case  :    int            = tokenizer(sentences[0]    ,     return_tensors="tf"  )
      _snake_case  :    List[Any]            = model.generate(**snake_case_    ,     do_sample=snake_case_    ,     num_beams=2  )
      _snake_case  :    Tuple            = (
          shape_list(inputs_non_padded["input_ids"]  )[-1]
          - tf.reduce_sum(tf.cast(inputs["attention_mask"][-1]    ,     tf.intaa  )  ).numpy()
      )
      _snake_case  :    Tuple            = tokenizer(sentences[1]    ,     return_tensors="tf"  )
      _snake_case  :    List[str]            = model.generate(
          **snake_case_    ,     do_sample=snake_case_    ,     num_beams=2    ,     max_length=model.config.max_length - num_paddings  )
      _snake_case  :    Tuple            = tokenizer.decode(output_non_padded[0]    ,     skip_special_tokens=snake_case_  )
      _snake_case  :    List[str]            = tokenizer.decode(output_padded[0]    ,     skip_special_tokens=snake_case_  )
      self.assertListEqual(snake_case_    ,     [non_padded_sentence, padded_sentence]  )


    def        lowerCamelCase__						(     self  ):
      # Confirms that XLA is working properly
      _snake_case      ,       _snake_case      ,       _snake_case      ,       _snake_case  :    Optional[int]            = self._get_beam_search_test_objects()

      _snake_case  :    Union[str, Any]            = tokenizer(snake_case_    ,     return_tensors="tf"    ,     padding=snake_case_  )
      _snake_case  :    Union[str, Any]            = tf.function(model.generate    ,     jit_compile=snake_case_  )
      _snake_case  :    int            = xla_generate(**snake_case_    ,     do_sample=snake_case_    ,     num_beams=2  )
      _snake_case  :    Optional[Any]            = tokenizer.batch_decode(snake_case_    ,     skip_special_tokens=snake_case_  )
      self.assertListEqual(snake_case_    ,     snake_case_  )









'''simple docstring'''







# 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__		(					a_  :     List[Any]			)   -> Optional[Any]:
       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__	:   Dict												=	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__	:   Dict												=	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__	:   Dict												=	ClusterConfig
                     else:
                            UpperCAmelCase__	:   int												=	SageMakerConfig
                     return config_class.from_yaml_file(yaml_file=a_			)




@dataclass
class 					__UpperCAmelCase :

      '''simple docstring'''





      SCREAMING_SNAKE_CASE				:    ComputeEnvironment
      SCREAMING_SNAKE_CASE				:    Union[DistributedType, SageMakerDistributedType]
      SCREAMING_SNAKE_CASE				:    str
      SCREAMING_SNAKE_CASE				:    bool




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




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




      def 							lowerCamelCase     (					self  ,		_UpperCAmelCase						):
             with open(_UpperCAmelCase  ,		'''w'''  ,		encoding='''utf-8'''						) as f:
                    UpperCAmelCase__	:   Any												=	json.dumps(self.to_dict()  ,		indent=2  ,		sort_keys=_UpperCAmelCase						) + '''\n'''
                    f.write(_UpperCAmelCase						)




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

             if "mixed_precision" not in config_dict:
                    UpperCAmelCase__	:   Tuple												=	'''fp16''' if ('''fp16''' in config_dict and config_dict['''fp16''']) else None
             if isinstance(config_dict['''mixed_precision''']  ,		_UpperCAmelCase						) 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__	:   Optional[int]												=	config_dict.pop('''dynamo_backend'''						)
                    UpperCAmelCase__	:   Dict												=	{} if dynamo_backend == '''NO''' else {'''dynamo_backend''': dynamo_backend}
             if "use_cpu" not in config_dict:
                    UpperCAmelCase__	:   List[str]												=	False
             return cls(**_UpperCAmelCase						)




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




      def 							lowerCamelCase     (					self						):
             if isinstance(self.compute_environment  ,		_UpperCAmelCase						):
                    UpperCAmelCase__	:   Tuple												=	ComputeEnvironment(self.compute_environment						)
             if isinstance(self.distributed_type  ,		_UpperCAmelCase						):
                    if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
                           UpperCAmelCase__	:   Optional[Any]												=	SageMakerDistributedType(self.distributed_type						)
                    else:
                           UpperCAmelCase__	:   Dict												=	DistributedType(self.distributed_type						)
             if self.dynamo_config is None:
                    UpperCAmelCase__	:   Optional[Any]												=	{}




@dataclass
class 					__UpperCAmelCase (		UpperCamelCase__	):

      '''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						):
             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__	:   Tuple												=	{}
             if self.ipex_config is None:
                    UpperCAmelCase__	:   List[str]												=	{}
             return super().__post_init__()




@dataclass
class 					__UpperCAmelCase (		UpperCamelCase__	):

      '''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