



'''simple docstring'''





import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)





def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase=False		)		-> List[str]:
      try:
            snake_case__  :    Optional[int]    						=      os.environ[key]
      except KeyError:
            # KEY isn't set, default to `default`.
            snake_case__  :    Dict    						=      default
      else:
            # KEY is set, convert it to True or False.
            try:
                  snake_case__  :    List[str]    						=      strtobool(_lowerCAmelCase		)
            except ValueError:
                  # More values are supported, but let's keep the message simple.
                  raise ValueError(f"If set, {key} must be yes or no."		)
      return _value


__a          =		parse_flag_from_env("RUN_SLOW", default=False)





def 						__snake_case(				_lowerCAmelCase		)		-> List[Any]:
      return unittest.skip("""Test was skipped"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Union[str, Any]:
      return unittest.skipUnless(_run_slow_tests     ,   """test is slow"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> List[str]:
      return unittest.skipUnless(not torch.cuda.is_available()     ,   """test requires only a CPU"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Any:
      return unittest.skipUnless(torch.cuda.is_available()     ,   """test requires a GPU"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> int:
      return unittest.skipUnless(is_xpu_available()     ,   """test requires a XPU"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Union[str, Any]:
      return unittest.skipUnless(is_mps_available()     ,   """test requires a `mps` backend support in `torch`"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> List[str]:
      return unittest.skipUnless(
          is_transformers_available() and is_datasets_available()     ,   """test requires the Hugging Face suite"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> List[Any]:
      return unittest.skipUnless(is_bnb_available()     ,   """test requires the bitsandbytes library"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Any:
      return unittest.skipUnless(is_tpu_available()     ,   """test requires TPU"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Union[str, Any]:
      return unittest.skipUnless(torch.cuda.device_count() == 1     ,   """test requires a GPU"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> List[str]:
      return unittest.skipUnless(torch.xpu.device_count() == 1     ,   """test requires a XPU"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Dict:
      return unittest.skipUnless(torch.cuda.device_count() > 1     ,   """test requires multiple GPUs"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> List[str]:
      return unittest.skipUnless(torch.xpu.device_count() > 1     ,   """test requires multiple XPUs"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> List[Any]:
      return unittest.skipUnless(is_safetensors_available()     ,   """test requires safetensors"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Union[str, Any]:
      return unittest.skipUnless(is_deepspeed_available()     ,   """test requires DeepSpeed"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Optional[int]:
      return unittest.skipUnless(is_torch_version(""">="""     ,   """1.12.0"""		)     ,   """test requires torch version >= 1.12.0"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase=None     ,   _lowerCAmelCase=None		)		-> Any:
      if test_case is None:
            return partial(_lowerCAmelCase     ,   version=_lowerCAmelCase		)
      return unittest.skipUnless(is_torch_version(""">="""     ,   _lowerCAmelCase		)     ,   f"test requires torch version >= {version}"		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> int:
      return unittest.skipUnless(is_tensorboard_available()     ,   """test requires Tensorboard"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Any:
      return unittest.skipUnless(is_wandb_available()     ,   """test requires wandb"""		)(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> Optional[Any]:
      return unittest.skipUnless(is_comet_ml_available()     ,   """test requires comet_ml"""		)(_lowerCAmelCase		)


__a          =		(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)





def 						__snake_case(				_lowerCAmelCase		)		-> int:
      return unittest.skipUnless(
          _atleast_one_tracker_available     ,   """test requires at least one tracker to be available and for `comet_ml` to not be installed"""     ,   )(_lowerCAmelCase		)







class     UpperCAmelCase_       (       unittest.TestCase	):
    """simple docstring"""







    lowercase					=		True




    @classmethod
    def lowerCamelCase       (    cls					:     Any						):
          snake_case__  :    Union[str, Any]    						=      tempfile.mkdtemp()




    @classmethod
    def lowerCamelCase       (    cls					:     int						):
          if os.path.exists(cls.tmpdir						):
                shutil.rmtree(cls.tmpdir						)




    def lowerCamelCase       (    self					:     Tuple						):
          if self.clear_on_setup:
                for path in Path(self.tmpdir						).glob("""**/*"""						):
                      if path.is_file():
                            path.unlink()
                      elif path.is_dir():
                            shutil.rmtree(snake_case_						)







class     UpperCAmelCase_       (       unittest.TestCase	):
    """simple docstring"""







    def lowerCamelCase       (    self					:     Any						):
          super().tearDown()
          # Reset the state of the AcceleratorState singleton.
          AcceleratorState._reset_state()
          PartialState._reset_state()







class     UpperCAmelCase_       (       unittest.TestCase	):
    """simple docstring"""







    def lowerCamelCase       (    self					:     Optional[int] ,     snake_case_					:     Union[mock.Mock, List[mock.Mock]]						):
          snake_case__  :    Dict    						=      mocks if isinstance(snake_case_ ,     (tuple, list)						) else [mocks]
          for m in self.mocks:
                m.start()
                self.addCleanup(m.stop						)





def 						__snake_case(				_lowerCAmelCase		)		-> int:
      snake_case__  :    Union[str, Any]    						=      AcceleratorState()
      snake_case__  :    int    						=      tensor[None].clone().to(state.device		)
      snake_case__  :    Optional[Any]    						=      gather(_lowerCAmelCase		).cpu()
      snake_case__  :    str    						=      tensor[0].cpu()
      for i in range(tensors.shape[0]		):
            if not torch.equal(tensors[i]     ,   _lowerCAmelCase		):
                  return False
      return True







class     UpperCAmelCase_       :
    """simple docstring"""







    def __init__(    self					:     List[Any] ,     snake_case_					:     Tuple ,     snake_case_					:     Union[str, Any] ,     snake_case_					:     List[Any]						):
          snake_case__  :    List[Any]    						=      returncode
          snake_case__  :    List[Any]    						=      stdout
          snake_case__  :    List[Any]    						=      stderr





async def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase		)		-> Optional[int]:
      while True:
            snake_case__  :    Optional[int]    						=      await stream.readline()
            if line:
                  callback(_lowerCAmelCase		)
            else:
                  break





async def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase=None     ,   _lowerCAmelCase=None     ,   _lowerCAmelCase=None     ,   _lowerCAmelCase=False     ,   _lowerCAmelCase=False		)		-> _RunOutput:
      if echo:
            print("""\nRunning: """     ,   """ """.join(_lowerCAmelCase		)		)

      snake_case__  :    Any    						=      await asyncio.create_subprocess_exec(
          cmd[0]     ,   *cmd[1:]     ,   stdin=_lowerCAmelCase     ,   stdout=asyncio.subprocess.PIPE     ,   stderr=asyncio.subprocess.PIPE     ,   env=_lowerCAmelCase     ,   )

      # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
      # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
      #
      # If it starts hanging, will need to switch to the following code. The problem is that no data
      # will be seen until it's done and if it hangs for example there will be no debug info.
      # out, err = await p.communicate()
      # return _RunOutput(p.returncode, out, err)

      snake_case__  :    List[Any]    						=      []
      snake_case__  :    Any    						=      []

      def tee(_lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase=""		):
            snake_case__  :    str    						=      line.decode("""utf-8"""		).rstrip()
            sink.append(_lowerCAmelCase		)
            if not quiet:
                  print(_lowerCAmelCase     ,   _lowerCAmelCase     ,   file=_lowerCAmelCase		)

    # XXX: the timeout doesn't seem to make any difference here
      await asyncio.wait(
          [
              asyncio.create_task(_read_stream(p.stdout     ,   lambda _lowerCAmelCase		: tee(_lowerCAmelCase     ,   _lowerCAmelCase     ,   sys.stdout     ,   label="""stdout:"""		)		)		),
              asyncio.create_task(_read_stream(p.stderr     ,   lambda _lowerCAmelCase		: tee(_lowerCAmelCase     ,   _lowerCAmelCase     ,   sys.stderr     ,   label="""stderr:"""		)		)		),
          ]     ,   timeout=_lowerCAmelCase     ,   )
      return _RunOutput(await p.wait()     ,   _lowerCAmelCase     ,   _lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase=None     ,   _lowerCAmelCase=None     ,   _lowerCAmelCase=180     ,   _lowerCAmelCase=False     ,   _lowerCAmelCase=True		)		-> _RunOutput:
      snake_case__  :    Optional[Any]    						=      asyncio.get_event_loop()
      snake_case__  :    List[Any]    						=      loop.run_until_complete(
          _stream_subprocess(_lowerCAmelCase     ,   env=_lowerCAmelCase     ,   stdin=_lowerCAmelCase     ,   timeout=_lowerCAmelCase     ,   quiet=_lowerCAmelCase     ,   echo=_lowerCAmelCase		)		)

      snake_case__  :    List[Any]    						=      """ """.join(_lowerCAmelCase		)
      if result.returncode > 0:
            snake_case__  :    List[str]    						=      """\n""".join(result.stderr		)
            raise RuntimeError(
                f"'{cmd_str}' failed with returncode {result.returncode}\n\n"
                f"The combined stderr from workers follows:\n{stderr}"		)

      return result







class     UpperCAmelCase_       (       _a	):
    """simple docstring"""







    pass





def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase=False		)		-> List[Any]:
      try:
            snake_case__  :    List[Any]    						=      subprocess.check_output(_lowerCAmelCase     ,   stderr=subprocess.STDOUT		)
            if return_stdout:
                  if hasattr(_lowerCAmelCase     ,   """decode"""		):
                        snake_case__  :    str    						=      output.decode("""utf-8"""		)
                  return output
      except subprocess.CalledProcessError as e:
            raise SubprocessCallException(
                f"Command `{' '.join(_lowerCAmelCase		)}` failed with the following error:\n\n{e.output.decode()}"		) from e





'''simple docstring'''





import json
import os
import unittest

from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import (
    VOCAB_FILES_NAMES,
    GPTSanJapaneseTokenizer,
)
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin







@require_tokenizers
class     UpperCAmelCase_       (       _a		,		unittest.TestCase	):
    """simple docstring"""







    lowercase					=		GPTSanJapaneseTokenizer
    lowercase					=		False
    lowercase					=		{"do_clean_text": False, "add_prefix_space": False}




    def lowerCamelCase       (    self					:     str						):
          super().setUp()

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

          snake_case__  :    Optional[Any]    						=      os.path.join(self.tmpdirname ,     VOCAB_FILES_NAMES["""vocab_file"""]						)
          snake_case__  :    Dict    						=      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(snake_case_						)						)




    def lowerCamelCase       (    self					:     Any ,     **snake_case_					:     Union[str, Any]						):
          kwargs.update(self.special_tokens_map						)
          return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname ,     **snake_case_						)




    def lowerCamelCase       (    self					:     Any ,     snake_case_					:     str						):
          snake_case__  :    Union[str, Any]    						=      """こんにちは、世界。 \nこんばんは、㔺界。😀"""
          snake_case__  :    List[str]    						=      """こんにちは、世界。 \nこんばんは、世界。😀"""
          return input_text, output_text




    def lowerCamelCase       (    self					:     Any ,     snake_case_					:     Dict						):
          snake_case__						,				snake_case__  :    int    						=      self.get_input_output_texts(snake_case_						)
          snake_case__  :    int    						=      tokenizer.encode(snake_case_ ,     add_special_tokens=snake_case_						)
          snake_case__  :    List[str]    						=      tokenizer.decode(snake_case_ ,     clean_up_tokenization_spaces=snake_case_						)
          return text, ids




    def lowerCamelCase       (    self					:     Optional[Any]						):
          pass  # TODO add if relevant




    def lowerCamelCase       (    self					:     Union[str, Any]						):
          pass  # TODO add if relevant




    def lowerCamelCase       (    self					:     List[str]						):
          pass  # TODO add if relevant




    def lowerCamelCase       (    self					:     Dict						):
          snake_case__  :    Optional[Any]    						=      self.get_tokenizer()

          # Testing tokenization
          snake_case__  :    int    						=      """こんにちは、世界。　こんばんは、㔺界。"""
          snake_case__  :    Optional[int]    						=      ["""こん""", """にちは""", """、""", """世界""", """。""", """<SP>""", """こん""", """ばんは""", """、""", """㔺界""", """。"""]
          snake_case__  :    Dict    						=      tokenizer.tokenize(snake_case_						)
          self.assertListEqual(snake_case_ ,     snake_case_						)

          # Testing conversion to ids without special tokens
          snake_case__  :    Union[str, Any]    						=      [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6]
          snake_case__  :    List[Any]    						=      tokenizer.convert_tokens_to_ids(snake_case_						)
          self.assertListEqual(snake_case_ ,     snake_case_						)

          # Testing conversion to ids with special tokens
          snake_case__  :    Union[str, Any]    						=      tokens + [tokenizer.unk_token]
          snake_case__  :    Dict    						=      [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19]
          snake_case__  :    Any    						=      tokenizer.convert_tokens_to_ids(snake_case_						)
          self.assertListEqual(snake_case_ ,     snake_case_						)




    def lowerCamelCase       (    self					:     Optional[Any]						):
          snake_case__  :    Union[str, Any]    						=      self.get_tokenizer()

          # Testing tokenization
          snake_case__  :    Union[str, Any]    						=      """こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。"""
          snake_case__  :    Optional[int]    						=      """こんにちは、、、、世界。こんばんは、、、、世界。"""
          snake_case__  :    Any    						=      tokenizer.encode(snake_case_						)
          snake_case__  :    int    						=      tokenizer.decode(snake_case_						)
          self.assertEqual(snake_case_ ,     snake_case_						)




    @slow
    def lowerCamelCase       (    self					:     Union[str, Any]						):
          snake_case__  :    Optional[Any]    						=      self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese"""						)

          # Testing tokenization
          snake_case__  :    Tuple    						=      """こんにちは、世界。"""
          snake_case__  :    Optional[Any]    						=      """こんばんは、㔺界。😀"""
          snake_case__  :    List[str]    						=      """こんにちは、世界。こんばんは、世界。😀"""
          snake_case__  :    Dict    						=      tokenizer.encode(prefix_text + input_text						)
          snake_case__  :    Dict    						=      tokenizer.encode("""""" ,     prefix_text=prefix_text + input_text						)
          snake_case__  :    int    						=      tokenizer.encode(snake_case_ ,     prefix_text=snake_case_						)
          snake_case__  :    Optional[Any]    						=      tokenizer.decode(snake_case_						)
          snake_case__  :    Union[str, Any]    						=      tokenizer.decode(snake_case_						)
          snake_case__  :    str    						=      tokenizer.decode(snake_case_						)
          self.assertEqual(snake_case_ ,     snake_case_						)
          self.assertEqual(snake_case_ ,     snake_case_						)
          self.assertEqual(snake_case_ ,     snake_case_						)




    @slow
    def lowerCamelCase       (    self					:     Union[str, Any]						):
          snake_case__  :    Optional[Any]    						=      self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese"""						)

          # Testing tokenization
          snake_case__  :    Dict    						=      """こんにちは、世界。"""
          snake_case__  :    Optional[int]    						=      """こんばんは、㔺界。😀"""

          snake_case__  :    Any    						=      len(tokenizer.encode(snake_case_						)						) - 2
          snake_case__  :    Optional[int]    						=      len(tokenizer.encode(snake_case_						)						) - 2

          snake_case__  :    List[str]    						=      [1] + [0] * (len_prefix + len_text + 1)
          snake_case__  :    Optional[int]    						=      [1] * (len_prefix + len_text + 1) + [0]
          snake_case__  :    int    						=      [1] + [1] * (len_prefix) + [0] * (len_text + 1)

          snake_case__  :    Any    						=      tokenizer(prefix_text + input_text						).token_type_ids
          snake_case__  :    str    						=      tokenizer("""""" ,     prefix_text=prefix_text + input_text						).token_type_ids
          snake_case__  :    Optional[Any]    						=      tokenizer(snake_case_ ,     prefix_text=snake_case_						).token_type_ids
          self.assertListEqual(snake_case_ ,     snake_case_						)
          self.assertListEqual(snake_case_ ,     snake_case_						)
          self.assertListEqual(snake_case_ ,     snake_case_						)




    @slow
    def lowerCamelCase       (    self					:     Optional[int]						):
          snake_case__  :    Optional[Any]    						=      self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese"""						)

          snake_case__  :    Union[str, Any]    						=      tokenizer.encode("""あンいワ"""						)
          snake_case__  :    int    						=      tokenizer.encode("""""" ,     prefix_text="""あンいワ"""						)
          snake_case__  :    Dict    						=      tokenizer.encode("""いワ""" ,     prefix_text="""あン"""						)

          self.assertEqual(tokenizer.decode(snake_case_						) ,     tokenizer.decode(snake_case_						)						)
          self.assertEqual(tokenizer.decode(snake_case_						) ,     tokenizer.decode(snake_case_						)						)
          self.assertNotEqual(snake_case_ ,     snake_case_						)
          self.assertNotEqual(snake_case_ ,     snake_case_						)
          self.assertEqual(x_token_a[1] ,     x_token_a[-1]						)  # SEG token
          self.assertEqual(x_token_a[1] ,     x_token_a[3]						)  # SEG token




    @slow
    def lowerCamelCase       (    self					:     Any						):
          snake_case__  :    Optional[int]    						=      self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese"""						)

          snake_case__  :    int    						=      [["""武田信玄""", """は、"""], ["""織田信長""", """の配下の、"""]]
          snake_case__  :    Optional[Any]    						=      tokenizer(snake_case_ ,     padding=snake_case_						)
          snake_case__  :    Tuple    						=      tokenizer.batch_encode_plus(snake_case_ ,     padding=snake_case_						)

          # fmt: off
          snake_case__  :    Optional[Any]    						=      [[35_993, 8_640, 25_948, 35_998, 30_647, 35_675, 35_999, 35_999], [35_993, 10_382, 9_868, 35_998, 30_646, 9_459, 30_646, 35_675]]
          snake_case__  :    Optional[Any]    						=      [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]]
          snake_case__  :    Optional[Any]    						=      [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]]
          # fmt: on
          self.assertListEqual(x_token.input_ids ,     snake_case_						)
          self.assertListEqual(x_token.token_type_ids ,     snake_case_						)
          self.assertListEqual(x_token.attention_mask ,     snake_case_						)
          self.assertListEqual(x_token_a.input_ids ,     snake_case_						)
          self.assertListEqual(x_token_a.token_type_ids ,     snake_case_						)
          self.assertListEqual(x_token_a.attention_mask ,     snake_case_						)




    def lowerCamelCase       (    self					:     Any						):
          # Intentionally convert some words to accommodate character fluctuations unique to Japanese
          pass




    def lowerCamelCase       (    self					:     List[str]						):
          # tokenizer has no padding token
          pass
