


'''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 lowerCamelCase__      (						__lowerCamelCase	:							List[str]	,   __lowerCamelCase	:							Dict=False							):







   '''simple docstring'''




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


lowercase							=parse_flag_from_env('RUN_SLOW', default=False)





def lowerCamelCase__      (						__lowerCamelCase	:							Optional[int]							):







   '''simple docstring'''




   return unittest.skip('Test was skipped'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							List[Any]							):







   '''simple docstring'''




   return unittest.skipUnless(_run_slow_tests	,   'test is slow'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							Optional[int]							):







   '''simple docstring'''




   return unittest.skipUnless(not torch.cuda.is_available()	,   'test requires only a CPU'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							Dict							):







   '''simple docstring'''




   return unittest.skipUnless(torch.cuda.is_available()	,   'test requires a GPU'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							Optional[Any]							):







   '''simple docstring'''




   return unittest.skipUnless(is_xpu_available()	,   'test requires a XPU'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							List[Any]							):







   '''simple docstring'''




   return unittest.skipUnless(is_mps_available()	,   'test requires a `mps` backend support in `torch`'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							Tuple							):







   '''simple docstring'''




   return unittest.skipUnless(
       is_transformers_available() and is_datasets_available()	,   'test requires the Hugging Face suite'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							Any							):







   '''simple docstring'''




   return unittest.skipUnless(is_bnb_available()	,   'test requires the bitsandbytes library'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							List[Any]							):







   '''simple docstring'''




   return unittest.skipUnless(is_tpu_available()	,   'test requires TPU'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							List[str]							):







   '''simple docstring'''




   return unittest.skipUnless(torch.cuda.device_count() == 1	,   'test requires a GPU'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							int							):







   '''simple docstring'''




   return unittest.skipUnless(torch.xpu.device_count() == 1	,   'test requires a XPU'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							str							):







   '''simple docstring'''




   return unittest.skipUnless(torch.cuda.device_count() > 1	,   'test requires multiple GPUs'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							List[Any]							):







   '''simple docstring'''




   return unittest.skipUnless(torch.xpu.device_count() > 1	,   'test requires multiple XPUs'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							int							):







   '''simple docstring'''




   return unittest.skipUnless(is_safetensors_available()	,   'test requires safetensors'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							List[str]							):







   '''simple docstring'''




   return unittest.skipUnless(is_deepspeed_available()	,   'test requires DeepSpeed'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							str							):







   '''simple docstring'''




   return unittest.skipUnless(is_torch_version('>='	,   '1.12.0'							)	,   'test requires torch version >= 1.12.0'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							int=None	,   __lowerCamelCase	:							Any=None							):







   '''simple docstring'''




   if test_case is None:
      return partial(__SCREAMING_SNAKE_CASE	,   version=__SCREAMING_SNAKE_CASE							)
   return unittest.skipUnless(is_torch_version('>='	,   __SCREAMING_SNAKE_CASE							)	,   f"test requires torch version >= {version}"							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							List[str]							):







   '''simple docstring'''




   return unittest.skipUnless(is_tensorboard_available()	,   'test requires Tensorboard'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							Any							):







   '''simple docstring'''




   return unittest.skipUnless(is_wandb_available()	,   'test requires wandb'							)(__SCREAMING_SNAKE_CASE							)





def lowerCamelCase__      (						__lowerCamelCase	:							Any							):







   '''simple docstring'''




   return unittest.skipUnless(is_comet_ml_available()	,   'test requires comet_ml'							)(__SCREAMING_SNAKE_CASE							)


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





def lowerCamelCase__      (						__lowerCamelCase	:							Tuple							):







   '''simple docstring'''




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






class  __magic_name__							(		unittest.TestCase    ):
       UpperCAmelCase										=True






       @classmethod
       def       lowerCAmelCase		(      cls)						->  List[Any]:




          '''simple docstring'''
          _UpperCAmelCase       :       Tuple							   =tempfile.mkdtemp()






       @classmethod
       def       lowerCAmelCase		(      cls)						->  List[str]:




          '''simple docstring'''


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






       def       lowerCAmelCase		(      self)						->  Dict:




          '''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(UpperCamelCase__)






class  __magic_name__							(		unittest.TestCase    ):






       def       lowerCAmelCase		(      self)						->  List[str]:




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






class  __magic_name__							(		unittest.TestCase    ):






       def       lowerCAmelCase		(      self  ,							snake_case)						->  Dict:




          '''simple docstring'''
          _UpperCAmelCase       :       Optional[Any]							   =mocks if isinstance(UpperCamelCase__  ,							(tuple, list)) else [mocks]
          for m in self.mocks:
             m.start()
             self.addCleanup(m.stop)






def lowerCamelCase__      (						__lowerCamelCase	:							Optional[int]							):







   '''simple docstring'''




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






class  __magic_name__							:






       def __init__(      self  ,							snake_case  ,							snake_case  ,							snake_case)						->  Dict:




          '''simple docstring'''
          _UpperCAmelCase       :       Optional[int]							   =returncode
          _UpperCAmelCase       :       List[str]							   =stdout
          _UpperCAmelCase       :       Tuple							   =stderr






async def lowerCamelCase__      (						__lowerCamelCase	:							int	,   __lowerCamelCase	:							Dict							):







   '''simple docstring'''




   while True:
      _UpperCAmelCase       :       Dict							   =await stream.readline()
      if line:
         callback(__SCREAMING_SNAKE_CASE							)
      else:
         break





async def lowerCamelCase__      (						__lowerCamelCase	:							Tuple	,   __lowerCamelCase	:							List[str]=None	,   __lowerCamelCase	:							Union[str, Any]=None	,   __lowerCamelCase	:							Optional[Any]=None	,   __lowerCamelCase	:							Dict=False	,   __lowerCamelCase	:							str=False							):







   '''simple docstring'''




   if echo:
      print('\nRunning: '	,   ' '.join(__SCREAMING_SNAKE_CASE							)							)

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

   # 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       :       int							   =[]
   _UpperCAmelCase       :       List[str]							   =[]

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

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





def lowerCamelCase__      (						__lowerCamelCase	:							List[str]	,   __lowerCamelCase	:							List[str]=None	,   __lowerCamelCase	:							List[Any]=None	,   __lowerCamelCase	:							str=1_8_0	,   __lowerCamelCase	:							Dict=False	,   __lowerCamelCase	:							Optional[int]=True							):







   '''simple docstring'''




   _UpperCAmelCase       :       Optional[int]							   =asyncio.get_event_loop()
   _UpperCAmelCase       :       int							   =loop.run_until_complete(
       _stream_subprocess(__SCREAMING_SNAKE_CASE	,   env=__SCREAMING_SNAKE_CASE	,   stdin=__SCREAMING_SNAKE_CASE	,   timeout=__SCREAMING_SNAKE_CASE	,   quiet=__SCREAMING_SNAKE_CASE	,   echo=__SCREAMING_SNAKE_CASE							)							)

   _UpperCAmelCase       :       Union[str, Any]							   =" ".join(__SCREAMING_SNAKE_CASE							)
   if result.returncode > 0:
      _UpperCAmelCase       :       Dict							   ="\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  __magic_name__							(		__snake_case    ):
       pass






def lowerCamelCase__      (						__lowerCamelCase	:							Dict	,   __lowerCamelCase	:							Union[str, Any]=False							):







   '''simple docstring'''




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






'''simple docstring'''






# Copyright 2023 The HuggingFace Inc. 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 re

from ..utils import cached_file


# docstyle-ignore
lowercase							='\nHuman: <<task>>\n\nAssistant: '


lowercase							='huggingface-tools/default-prompts'
lowercase							={'chat': 'chat_prompt_template.txt', 'run': 'run_prompt_template.txt'}





def lowerCamelCase__      (						__lowerCamelCase	:							Union[str, Any]	,   __lowerCamelCase	:							Union[str, Any]	,   __lowerCamelCase	:							int="run"							):







   '''simple docstring'''




   if prompt_or_repo_id is None:
      _UpperCAmelCase       :       List[str]							   =DEFAULT_PROMPTS_REPO

   # prompt is considered a repo ID when it does not contain any kind of space
   if re.search('\\s'	,   __lowerCamelCase							) is not None:
      return prompt_or_repo_id

   _UpperCAmelCase       :       Dict							   =cached_file(
       __lowerCamelCase	,   PROMPT_FILES[mode]	,   repo_type='dataset'	,   user_agent={'agent': agent_name}							)
   with open(__lowerCamelCase	,   'r'	,   encoding='utf-8'							) as f:
      return f.read()

