
"""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    UpperCamelCase						(					UpperCAmelCase     )						->str:

   """simple docstring"""



   if config_file is not None:
      if not os.path.isfile(UpperCAmelCase     ):
         raise FileNotFoundError(
             F'''The passed configuration file `{config_file}` does not exist. '''
             "Please pass an existing file to `accelerate launch`, or use the the default one "
             "created through `accelerate config` and run `accelerate launch` "
             "without the `--config_file` argument."     )
   else:
      a_						   =     default_config_file
   with open(UpperCAmelCase ,   "r" ,   encoding="utf-8"     ) as f:
      if config_file.endswith(".json"     ):
         if (
             json.load(UpperCAmelCase     ).get("compute_environment" ,   ComputeEnvironment.LOCAL_MACHINE     )
             == ComputeEnvironment.LOCAL_MACHINE
         ):
            a_						   =     ClusterConfig
         else:
            a_						   =     SageMakerConfig
         return config_class.from_json_file(json_file=UpperCAmelCase     )
      else:
         if (
             yaml.safe_load(UpperCAmelCase     ).get("compute_environment" ,   ComputeEnvironment.LOCAL_MACHINE     )
             == ComputeEnvironment.LOCAL_MACHINE
         ):
            a_						   =     ClusterConfig
         else:
            a_						   =     SageMakerConfig
         return config_class.from_yaml_file(yaml_file=UpperCAmelCase     )





@dataclass
class 							snake_case       :
   a_					:		ComputeEnvironment
   a_					:		Union[DistributedType, SageMakerDistributedType]
   a_					:		str
   a_					:		bool







   def    UpperCAmelCase__	( self)   ->Optional[int]:
      a_						   =     self.__dict__
      # For serialization, it's best to convert Enums to strings (or their underlying value type).
      for key, value in result.items():
         if isinstance(__UpperCAmelCase       ,							__UpperCAmelCase):
            a_						   =     value.value
         if isinstance(__UpperCAmelCase       ,							__UpperCAmelCase) and not bool(__UpperCAmelCase):
            a_						   =     None
      a_						   =     {k: v for k, v in result.items() if v is not None}
      return result







   @classmethod
   def    UpperCAmelCase__	( cls       ,							__UpperCAmelCase=None)   ->Optional[Any]:
      a_						   =     default_json_config_file if json_file is None else json_file
      with open(__UpperCAmelCase       ,							"r"       ,							encoding="utf-8") as f:
         a_						   =     json.load(__UpperCAmelCase)
      if "compute_environment" not in config_dict:
         a_						   =     ComputeEnvironment.LOCAL_MACHINE
      if "mixed_precision" not in config_dict:
         a_						   =     "fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None
      if "fp16" in config_dict:  # Convert the config to the new format.
         del config_dict["fp16"]
      if "dynamo_backend" in config_dict:  # Convert the config to the new format.
         a_						   =     config_dict.pop("dynamo_backend")
         a_						   =     {} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
      if "use_cpu" not in config_dict:
         a_						   =     False
      return cls(**__UpperCAmelCase)







   def    UpperCAmelCase__	( self       ,							__UpperCAmelCase)   ->str:
      with open(__UpperCAmelCase       ,							"w"       ,							encoding="utf-8") as f:
         a_						   =     json.dumps(self.to_dict()       ,							indent=2       ,							sort_keys=__UpperCAmelCase) + "\n"
         f.write(__UpperCAmelCase)







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

      if "mixed_precision" not in config_dict:
         a_						   =     "fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None
      if isinstance(config_dict["mixed_precision"]       ,							__UpperCAmelCase) and not config_dict["mixed_precision"]:
         a_						   =     "no"
      if "fp16" in config_dict:  # Convert the config to the new format.
         del config_dict["fp16"]
      if "dynamo_backend" in config_dict:  # Convert the config to the new format.
         a_						   =     config_dict.pop("dynamo_backend")
         a_						   =     {} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
      if "use_cpu" not in config_dict:
         a_						   =     False
      return cls(**__UpperCAmelCase)







   def    UpperCAmelCase__	( self       ,							__UpperCAmelCase)   ->Optional[int]:
      with open(__UpperCAmelCase       ,							"w"       ,							encoding="utf-8") as f:
         yaml.safe_dump(self.to_dict()       ,							__UpperCAmelCase)







   def    UpperCAmelCase__	( self)   ->int:
      if isinstance(self.compute_environment       ,							__UpperCAmelCase):
         a_						   =     ComputeEnvironment(self.compute_environment)
      if isinstance(self.distributed_type       ,							__UpperCAmelCase):
         if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
            a_						   =     SageMakerDistributedType(self.distributed_type)
         else:
            a_						   =     DistributedType(self.distributed_type)
      if self.dynamo_config is None:
         a_						   =     {}






@dataclass
class 							snake_case       (     SCREAMING_SNAKE_CASE_		):
   a_					:		int
   a_					:		int     					=     0
   a_					:		int     					=     1
   a_					:		Optional[str]     					=     None
   a_					:		Optional[str]     					=     None
   a_					:		Optional[int]     					=     None
   a_					:		Optional[str]     					=     "static"
   a_					:		Optional[bool]     					=     False
   a_					:		str     					=     "main"

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

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

   # args for dynamo
   a_					:		dict     					=     None







   def    UpperCAmelCase__	( self)   ->Union[str, Any]:
      if self.deepspeed_config is None:
         a_						   =     {}
      if self.fsdp_config is None:
         a_						   =     {}
      if self.megatron_lm_config is None:
         a_						   =     {}
      if self.ipex_config is None:
         a_						   =     {}
      return super().__post_init__()






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

"""simple docstring"""






import json
import os
import unittest

from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import (
    VOCAB_FILES_NAMES,
    GPTNeoXJapaneseTokenizer,
)
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin





@require_tokenizers
class 							snake_case       (     SCREAMING_SNAKE_CASE_							,       unittest.TestCase		):
   a_					:		Optional[int]     					=     GPTNeoXJapaneseTokenizer
   a_					:		Dict     					=     False
   a_					:		Union[str, Any]     					=     {"""do_clean_text""": False, """add_prefix_space""": False}







   def    UpperCAmelCase__	( self)   ->Union[str, Any]:
      super().setUp()

      a_						   =     [
          "こん",
          "こんに",
          "にちは",
          "ばんは",
          "世界,㔺界",
          "、",
          "。",
          "<BR>",
          "<SP>",
          "<TAB>",
          "<URL>",
          "<EMAIL>",
          "<TEL>",
          "<DATE>",
          "<PRICE>",
          "<BLOCK>",
          "<KIGOU>",
          "<U2000U2BFF>",
          "<|emoji1|>",
          "<unk>",
          "<|startoftext|>",
          "<|endoftext|>",
      ]
      a_						   =     {"emoji": {"\ud83d\ude00": "<|emoji1|>"}, "emoji_inv": {"<|emoji1|>": "\ud83d\ude00"}}  # 😀
      a_						   =     {"unk_token": "<unk>"}

      a_						   =     os.path.join(self.tmpdirname       ,							VOCAB_FILES_NAMES["vocab_file"])
      a_						   =     os.path.join(self.tmpdirname       ,							VOCAB_FILES_NAMES["emoji_file"])
      with open(self.vocab_file       ,							"w"       ,							encoding="utf-8") as vocab_writer:
         vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
      with open(self.emoji_file       ,							"w") as emoji_writer:
         emoji_writer.write(json.dumps(__UpperCAmelCase))







   def    UpperCAmelCase__	( self       ,							**__UpperCAmelCase)   ->int:
      kwargs.update(self.special_tokens_map)
      return GPTNeoXJapaneseTokenizer.from_pretrained(self.tmpdirname       ,							**__UpperCAmelCase)







   def    UpperCAmelCase__	( self       ,							__UpperCAmelCase)   ->Dict:
      a_						   =     "こんにちは、世界。 \nこんばんは、㔺界。😀"
      a_						   =     "こんにちは、世界。 \nこんばんは、世界。😀"
      return input_text, output_text







   def    UpperCAmelCase__	( self       ,							__UpperCAmelCase)   ->Optional[Any]:
      a_   ,			a_						   =     self.get_input_output_texts(__UpperCAmelCase)
      a_						   =     tokenizer.encode(__UpperCAmelCase       ,							add_special_tokens=__UpperCAmelCase)
      a_						   =     tokenizer.decode(__UpperCAmelCase       ,							clean_up_tokenization_spaces=__UpperCAmelCase)
      return text, ids







   def    UpperCAmelCase__	( self)   ->Any:
      pass  # TODO add if relevant







   def    UpperCAmelCase__	( self)   ->int:
      pass  # TODO add if relevant







   def    UpperCAmelCase__	( self)   ->Optional[Any]:
      pass  # TODO add if relevant







   def    UpperCAmelCase__	( self)   ->List[str]:
      a_						   =     self.get_tokenizer()

      # Testing tokenization
      a_						   =     "こんにちは、世界。　こんばんは、㔺界。"
      a_						   =     ["こん", "にちは", "、", "世界", "。", "<SP>", "こん", "ばんは", "、", "㔺界", "。"]
      a_						   =     tokenizer.tokenize(__UpperCAmelCase)
      self.assertListEqual(__UpperCAmelCase       ,							__UpperCAmelCase)

      # Testing conversion to ids without special tokens
      a_						   =     [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6]
      a_						   =     tokenizer.convert_tokens_to_ids(__UpperCAmelCase)
      self.assertListEqual(__UpperCAmelCase       ,							__UpperCAmelCase)

      # Testing conversion to ids with special tokens
      a_						   =     tokens + [tokenizer.unk_token]
      a_						   =     [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19]
      a_						   =     tokenizer.convert_tokens_to_ids(__UpperCAmelCase)
      self.assertListEqual(__UpperCAmelCase       ,							__UpperCAmelCase)







   @slow
   def    UpperCAmelCase__	( self)   ->Tuple:
      a_						   =     self.tokenizer_class.from_pretrained("abeja/gpt-neox-japanese-2.7b")

      a_						   =     tokenizer.encode("ありがとう。"       ,							add_special_tokens=__UpperCAmelCase)
      a_						   =     tokenizer.encode("どういたしまして。"       ,							add_special_tokens=__UpperCAmelCase)

      a_						   =     tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase)
      a_						   =     tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase       ,							__UpperCAmelCase)

      assert encoded_sentence == ids_a
      assert encoded_pair == ids_a + ids_a







   def    UpperCAmelCase__	( self)   ->Tuple:
      # Intentionally convert some words to accommodate character fluctuations unique to Japanese
      pass







   def    UpperCAmelCase__	( self)   ->Union[str, Any]:
      # tokenizer has no padding token
      pass