
'''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     (    _UpperCAmelCase					:       Optional[Any],      _UpperCAmelCase					:       List[Any]=False):
   try:
      UpperCamelCase       =  os.environ[key]
   except KeyError:
      # KEY isn't set, default to `default`.
      UpperCamelCase       =  default
   else:
      # KEY is set, convert it to True or False.
      try:
         UpperCamelCase       =  strtobool(_UpperCAmelCase)
      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


snake_case_ :  Tuple     =					parse_flag_from_env('RUN_SLOW', default=False)



def  __snake_case     (    _UpperCAmelCase					:       Dict):
   return unittest.skip('''Test was skipped''')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       int):
   return unittest.skipUnless(_run_slow_tests,      '''test is slow''')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       int):
   return unittest.skipUnless(not torch.cuda.is_available(),      '''test requires only a CPU''')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       str):
   return unittest.skipUnless(torch.cuda.is_available(),      '''test requires a GPU''')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       Dict):
   return unittest.skipUnless(is_xpu_available(),      '''test requires a XPU''')(_UpperCAmelCase)



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



def  __snake_case     (    _UpperCAmelCase					:       List[Any]):
   return unittest.skipUnless(
       is_transformers_available() and is_datasets_available(),      '''test requires the Hugging Face suite''')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       int):
   return unittest.skipUnless(is_bnb_available(),      '''test requires the bitsandbytes library''')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       Union[str, Any]):
   return unittest.skipUnless(is_tpu_available(),      '''test requires TPU''')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       Dict):
   return unittest.skipUnless(torch.cuda.device_count() == 1,      '''test requires a GPU''')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       str):
   return unittest.skipUnless(torch.xpu.device_count() == 1,      '''test requires a XPU''')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       Optional[int]):
   return unittest.skipUnless(torch.cuda.device_count() > 1,      '''test requires multiple GPUs''')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       str):
   return unittest.skipUnless(torch.xpu.device_count() > 1,      '''test requires multiple XPUs''')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       int):
   return unittest.skipUnless(is_safetensors_available(),      '''test requires safetensors''')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       Optional[int]):
   return unittest.skipUnless(is_deepspeed_available(),      '''test requires DeepSpeed''')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       Any):
   return unittest.skipUnless(is_torch_version('''>=''',      '''1.12.0'''),      '''test requires torch version >= 1.12.0''')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       Optional[Any]=None,      _UpperCAmelCase					:       List[Any]=None):
   if test_case is None:
      return partial(_UpperCAmelCase,      version=_UpperCAmelCase)
   return unittest.skipUnless(is_torch_version('''>=''',      _UpperCAmelCase),      f'test requires torch version >= {version}')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       Optional[Any]):
   return unittest.skipUnless(is_tensorboard_available(),      '''test requires Tensorboard''')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       Any):
   return unittest.skipUnless(is_wandb_available(),      '''test requires wandb''')(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       int):
   return unittest.skipUnless(is_comet_ml_available(),      '''test requires comet_ml''')(_UpperCAmelCase)


snake_case_ :  Dict     =					(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)



def  __snake_case     (    _UpperCAmelCase					:       Tuple):
   return unittest.skipUnless(
       _atleast_one_tracker_available,      '''test requires at least one tracker to be available and for `comet_ml` to not be installed''',      )(_UpperCAmelCase)


class 						lowercase__	(  unittest.TestCase   ):






   '''simple docstring'''







   _snake_case		   =							True







   @classmethod
   def       UpperCAmelCase				(			cls   ):

      '''simple docstring'''







      UpperCamelCase       =  tempfile.mkdtemp()







   @classmethod
   def       UpperCAmelCase				(			cls   ):

      '''simple docstring'''







      if os.path.exists(cls.tmpdir   ):
         shutil.rmtree(cls.tmpdir   )







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      if self.clear_on_setup:
         for path in Path(self.tmpdir   ).glob('''**/*'''   ):
            if path.is_file():
               path.unlink()
            elif path.is_dir():
               shutil.rmtree(lowerCamelCase__   )




class 						lowercase__	(  unittest.TestCase   ):






   '''simple docstring'''







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      super().tearDown()
      # Reset the state of the AcceleratorState singleton.
      AcceleratorState._reset_state()
      PartialState._reset_state()




class 						lowercase__	(  unittest.TestCase   ):






   '''simple docstring'''







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      UpperCamelCase       =  mocks if isinstance(lowerCamelCase__ ,   (tuple, list)   ) else [mocks]
      for m in self.mocks:
         m.start()
         self.addCleanup(m.stop   )




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


class 						lowercase__	:






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__   ):

      '''simple docstring'''







      UpperCamelCase       =  returncode
      UpperCamelCase       =  stdout
      UpperCamelCase       =  stderr




async def  __snake_case     (    _UpperCAmelCase					:       int,      _UpperCAmelCase					:       Tuple):
   while True:
      UpperCamelCase       =  await stream.readline()
      if line:
         callback(_UpperCAmelCase)
      else:
         break



async def  __snake_case     (    _UpperCAmelCase					:       str,      _UpperCAmelCase					:       Union[str, Any]=None,      _UpperCAmelCase					:       Tuple=None,      _UpperCAmelCase					:       Any=None,      _UpperCAmelCase					:       Optional[Any]=False,      _UpperCAmelCase					:       List[Any]=False):
   if echo:
      print('''\nRunning: ''',      ''' '''.join(_UpperCAmelCase))

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

   # 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)

   UpperCamelCase       =  []
   UpperCamelCase       =  []

   def tee(_UpperCAmelCase					:       Dict,      _UpperCAmelCase					:       int,      _UpperCAmelCase					:       str,      _UpperCAmelCase					:       str=""):
      UpperCamelCase       =  line.decode('''utf-8''').rstrip()
      sink.append(_UpperCAmelCase)
      if not quiet:
         print(_UpperCAmelCase,      _UpperCAmelCase,      file=_UpperCAmelCase)

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



def  __snake_case     (    _UpperCAmelCase					:       Optional[int],      _UpperCAmelCase					:       List[str]=None,      _UpperCAmelCase					:       int=None,      _UpperCAmelCase					:       int=180,      _UpperCAmelCase					:       int=False,      _UpperCAmelCase					:       str=True):
   UpperCamelCase       =  asyncio.get_event_loop()
   UpperCamelCase       =  loop.run_until_complete(
       _stream_subprocess(_UpperCAmelCase,      env=_UpperCAmelCase,      stdin=_UpperCAmelCase,      timeout=_UpperCAmelCase,      quiet=_UpperCAmelCase,      echo=_UpperCAmelCase))

   UpperCamelCase       =  ''' '''.join(_UpperCAmelCase)
   if result.returncode > 0:
      UpperCamelCase       =  '''\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 						lowercase__	(  snake_case_   ):






   '''simple docstring'''







   pass




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







'''simple docstring'''


from queue import Queue
from typing import TYPE_CHECKING, Optional


if TYPE_CHECKING:
   from ..models.auto import AutoTokenizer


class 						lowercase__	:






   '''simple docstring'''







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      raise NotImplementedError()







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      raise NotImplementedError()




class 						lowercase__	(  snake_case_   ):






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__ ,   lowerCamelCase__ = False ,   **lowerCamelCase__   ):

      '''simple docstring'''







      UpperCamelCase       =  tokenizer
      UpperCamelCase       =  skip_prompt
      UpperCamelCase       =  decode_kwargs

      # variables used in the streaming process
      UpperCamelCase       =  []
      UpperCamelCase       =  0
      UpperCamelCase       =  True







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      if len(value.shape   ) > 1 and value.shape[0] > 1:
         raise ValueError('''TextStreamer only supports batch size 1'''   )
      elif len(value.shape   ) > 1:
         UpperCamelCase       =  value[0]

      if self.skip_prompt and self.next_tokens_are_prompt:
         UpperCamelCase       =  False
         return

      # Add the new token to the cache and decodes the entire thing.
      self.token_cache.extend(value.tolist()   )
      UpperCamelCase       =  self.tokenizer.decode(self.token_cache ,   **self.decode_kwargs   )

      # After the symbol for a new line, we flush the cache.
      if text.endswith('''\n'''   ):
         UpperCamelCase       =  text[self.print_len :]
         UpperCamelCase       =  []
         UpperCamelCase       =  0
      # If the last token is a CJK character, we print the characters.
      elif len(lowerCamelCase__   ) > 0 and self._is_chinese_char(ord(text[-1]   )   ):
         UpperCamelCase       =  text[self.print_len :]
         self.print_len += len(lowerCamelCase__   )
      # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words,
      # which may change with the subsequent token -- there are probably smarter ways to do this!)
      else:
         UpperCamelCase       =  text[self.print_len : text.rfind(''' '''   ) + 1]
         self.print_len += len(lowerCamelCase__   )

      self.on_finalized_text(lowerCamelCase__   )







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      if len(self.token_cache   ) > 0:
         UpperCamelCase       =  self.tokenizer.decode(self.token_cache ,   **self.decode_kwargs   )
         UpperCamelCase       =  text[self.print_len :]
         UpperCamelCase       =  []
         UpperCamelCase       =  0
      else:
         UpperCamelCase       =  ''''''

      UpperCamelCase       =  True
      self.on_finalized_text(lowerCamelCase__ ,   stream_end=lowerCamelCase__   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__ = False   ):

      '''simple docstring'''







      print(lowerCamelCase__ ,   flush=lowerCamelCase__ ,   end='''''' if not stream_end else None   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      if (
          (cp >= 0x4_E_0_0 and cp <= 0x9_F_F_F)
          or (cp >= 0x3_4_0_0 and cp <= 0x4_D_B_F)  #
          or (cp >= 0x2_0_0_0_0 and cp <= 0x2_A_6_D_F)  #
          or (cp >= 0x2_A_7_0_0 and cp <= 0x2_B_7_3_F)  #
          or (cp >= 0x2_B_7_4_0 and cp <= 0x2_B_8_1_F)  #
          or (cp >= 0x2_B_8_2_0 and cp <= 0x2_C_E_A_F)  #
          or (cp >= 0xF_9_0_0 and cp <= 0xF_A_F_F)
          or (cp >= 0x2_F_8_0_0 and cp <= 0x2_F_A_1_F)  #
      ):  #
         return True

      return False




class 						lowercase__	(  snake_case_   ):






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__ ,   lowerCamelCase__ = False ,   lowerCamelCase__ = None ,   **lowerCamelCase__   ):

      '''simple docstring'''







      super().__init__(lowerCamelCase__ ,   lowerCamelCase__ ,   **lowerCamelCase__   )
      UpperCamelCase       =  Queue()
      UpperCamelCase       =  None
      UpperCamelCase       =  timeout







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__ = False   ):

      '''simple docstring'''







      self.text_queue.put(lowerCamelCase__ ,   timeout=self.timeout   )
      if stream_end:
         self.text_queue.put(self.stop_signal ,   timeout=self.timeout   )







   def __iter__(			self   ):

      '''simple docstring'''







      return self







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      UpperCamelCase       =  self.text_queue.get(timeout=self.timeout   )
      if value == self.stop_signal:
         raise StopIteration()
      else:
         return value





