
"""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       A_  (				__lowercase						,	__lowercase=False	):
 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_     :					Tuple   	=strtobool(__lowercase	)
  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


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




def       A_  (				__lowercase	):
 return unittest.skip('Test was skipped'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(_run_slow_tests						,	'test is slow'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(not torch.cuda.is_available()						,	'test requires only a CPU'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(torch.cuda.is_available()						,	'test requires a GPU'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(is_xpu_available()						,	'test requires a XPU'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(is_mps_available()						,	'test requires a `mps` backend support in `torch`'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(
     is_transformers_available() and is_datasets_available()						,	'test requires the Hugging Face suite'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(is_bnb_available()						,	'test requires the bitsandbytes library'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(is_tpu_available()						,	'test requires TPU'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(torch.cuda.device_count() == 1						,	'test requires a GPU'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(torch.xpu.device_count() == 1						,	'test requires a XPU'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(torch.cuda.device_count() > 1						,	'test requires multiple GPUs'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(torch.xpu.device_count() > 1						,	'test requires multiple XPUs'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(is_safetensors_available()						,	'test requires safetensors'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(is_deepspeed_available()						,	'test requires DeepSpeed'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(is_torch_version('>='						,	'1.12.0'	)						,	'test requires torch version >= 1.12.0'	)(__lowercase	)




def       A_  (				__lowercase=None						,	__lowercase=None	):
 if test_case is None:
  return partial(__lowercase						,	version=__lowercase	)
 return unittest.skipUnless(is_torch_version('>='						,	__lowercase	)						,	F'''test requires torch version >= {version}'''	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(is_tensorboard_available()						,	'test requires Tensorboard'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(is_wandb_available()						,	'test requires wandb'	)(__lowercase	)




def       A_  (				__lowercase	):
 return unittest.skipUnless(is_comet_ml_available()						,	'test requires comet_ml'	)(__lowercase	)


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




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





class 				a__					(						unittest.TestCase       ):
     UpperCAmelCase__         =      True



     @classmethod
     def  lowerCamelCase_						(							cls :int   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[Any]   	=tempfile.mkdtemp()



     @classmethod
     def  lowerCamelCase_						(							cls :Any   ):







      '''simple docstring'''



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




     def  lowerCamelCase_						(							self :List[str]   ):







      '''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 				a__					(						unittest.TestCase       ):



     def  lowerCamelCase_						(							self :Union[str, Any]   ):







      '''simple docstring'''



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





class 				a__					(						unittest.TestCase       ):



     def  lowerCamelCase_						(							self :Optional[Any]      ,  _lowerCamelCase :Union[mock.Mock, List[mock.Mock]]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[Any]   	=mocks if isinstance(_lowerCamelCase      ,  (tuple, list)   ) else [mocks]
      for m in self.mocks:
       m.start()
       self.addCleanup(m.stop   )




def       A_  (				__lowercase	):
 UpperCamelCase_     :					Tuple   	=AcceleratorState()
 UpperCamelCase_     :					Tuple   	=tensor[None].clone().to(state.device	)
 UpperCamelCase_     :					Optional[Any]   	=gather(__lowercase	).cpu()
 UpperCamelCase_     :					Any   	=tensor[0].cpu()
 for i in range(tensors.shape[0]	):
  if not torch.equal(tensors[i]						,	__lowercase	):
   return False
 return True





class 				a__					:



     def __init__(							self :Optional[Any]      ,  _lowerCamelCase :List[Any]      ,  _lowerCamelCase :Optional[int]      ,  _lowerCamelCase :Optional[int]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[int]   	=returncode
      UpperCamelCase_     :					Optional[Any]   	=stdout
      UpperCamelCase_     :					int   	=stderr




async def       A_  (				__lowercase						,	__lowercase	):
 while True:
  UpperCamelCase_     :					str   	=await stream.readline()
  if line:
   callback(__lowercase	)
  else:
   break




async def       A_  (				__lowercase						,	__lowercase=None						,	__lowercase=None						,	__lowercase=None						,	__lowercase=False						,	__lowercase=False	):
 if echo:
  print('\nRunning: '						,	' '.join(__lowercase	)	)

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

 # 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_     :					Tuple   	=[]
 UpperCamelCase_     :					Union[str, Any]   	=[]

 def tee(__lowercase						,	__lowercase						,	__lowercase						,	__lowercase=""	):
  UpperCamelCase_     :					Any   	=line.decode('utf-8'	).rstrip()
  sink.append(__lowercase	)
  if not quiet:
   print(__lowercase						,	__lowercase						,	file=__lowercase	)

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




def       A_  (				__lowercase						,	__lowercase=None						,	__lowercase=None						,	__lowercase=1_80						,	__lowercase=False						,	__lowercase=True	):
 UpperCamelCase_     :					Optional[Any]   	=asyncio.get_event_loop()
 UpperCamelCase_     :					List[Any]   	=loop.run_until_complete(
     _stream_subprocess(__lowercase						,	env=__lowercase						,	stdin=__lowercase						,	timeout=__lowercase						,	quiet=__lowercase						,	echo=__lowercase	)	)

 UpperCamelCase_     :					Tuple   	=' '.join(__lowercase	)
 if result.returncode > 0:
  UpperCamelCase_     :					Any   	='\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 				a__					(						A__       ):
     pass




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


"""simple docstring"""






import copy
import tempfile
import unittest

from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError

from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test





class 				a__					(						unittest.TestCase       ):



     @parameterized.expand([(None,), ('foo.json',)]   )
     def  lowerCamelCase_						(							self :Union[str, Any]      ,  _lowerCamelCase :Any   ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=GenerationConfig(
          do_sample=_lowerCamelCase      ,  temperature=0.7      ,  length_penalty=1.0      ,  bad_words_ids=[[1, 2, 3], [4, 5]]      ,  )
      with tempfile.TemporaryDirectory() as tmp_dir:
       config.save_pretrained(_lowerCamelCase      ,  config_name=_lowerCamelCase   )
       UpperCamelCase_     :					Union[str, Any]   	=GenerationConfig.from_pretrained(_lowerCamelCase      ,  config_name=_lowerCamelCase   )

      # Checks parameters that were specified
      self.assertEqual(loaded_config.do_sample      ,  _lowerCamelCase   )
      self.assertEqual(loaded_config.temperature      ,  0.7   )
      self.assertEqual(loaded_config.length_penalty      ,  1.0   )
      self.assertEqual(loaded_config.bad_words_ids      ,  [[1, 2, 3], [4, 5]]   )

      # Checks parameters that were not specified (defaults)
      self.assertEqual(loaded_config.top_k      ,  50   )
      self.assertEqual(loaded_config.max_length      ,  20   )
      self.assertEqual(loaded_config.max_time      ,  _lowerCamelCase   )



     def  lowerCamelCase_						(							self :Optional[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[int]   	=AutoConfig.from_pretrained('gpt2'   )
      UpperCamelCase_     :					Tuple   	=GenerationConfig.from_model_config(_lowerCamelCase   )
      UpperCamelCase_     :					Optional[int]   	=GenerationConfig()

      # The generation config has loaded a few non-default parameters from the model config
      self.assertNotEqual(_lowerCamelCase      ,  _lowerCamelCase   )

      # One of those parameters is eos_token_id -- check if it matches
      self.assertNotEqual(generation_config_from_model.eos_token_id      ,  default_generation_config.eos_token_id   )
      self.assertEqual(generation_config_from_model.eos_token_id      ,  model_config.eos_token_id   )



     def  lowerCamelCase_						(							self :Tuple   ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=GenerationConfig()
      UpperCamelCase_     :					Optional[Any]   	={
          'max_new_tokens': 1_024,
          'foo': 'bar',
      }
      UpperCamelCase_     :					Optional[Any]   	=copy.deepcopy(_lowerCamelCase   )
      UpperCamelCase_     :					Optional[int]   	=generation_config.update(**_lowerCamelCase   )

      # update_kwargs was not modified (no side effects)
      self.assertEqual(_lowerCamelCase      ,  _lowerCamelCase   )

      # update_kwargs was used to update the config on valid attributes
      self.assertEqual(generation_config.max_new_tokens      ,  1_024   )

      # `.update()` returns a dictionary of unused kwargs
      self.assertEqual(_lowerCamelCase      ,  {'foo': 'bar'}   )



     def  lowerCamelCase_						(							self :Union[str, Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Union[str, Any]   	=GenerationConfig()
      UpperCamelCase_     :					Union[str, Any]   	='bar'

      with tempfile.TemporaryDirectory('test-generation-config'   ) as tmp_dir:
       generation_config.save_pretrained(_lowerCamelCase   )

       UpperCamelCase_     :					Dict   	=GenerationConfig.from_pretrained(_lowerCamelCase   )
      # update_kwargs was used to update the config on valid attributes
      self.assertEqual(new_config.foo      ,  'bar'   )

      UpperCamelCase_     :					List[str]   	=GenerationConfig.from_model_config(_lowerCamelCase   )
      assert not hasattr(_lowerCamelCase      ,  'foo'   )  # no new kwargs should be initialized if from config




     def  lowerCamelCase_						(							self :Optional[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[str]   	=GenerationConfig()
      self.assertEqual(default_config.temperature      ,  1.0   )
      self.assertEqual(default_config.do_sample      ,  _lowerCamelCase   )
      self.assertEqual(default_config.num_beams      ,  1   )

      UpperCamelCase_     :					Tuple   	=GenerationConfig(
          do_sample=_lowerCamelCase      ,  temperature=0.7      ,  length_penalty=1.0      ,  bad_words_ids=[[1, 2, 3], [4, 5]]      ,  )
      self.assertEqual(config.temperature      ,  0.7   )
      self.assertEqual(config.do_sample      ,  _lowerCamelCase   )
      self.assertEqual(config.num_beams      ,  1   )

      with tempfile.TemporaryDirectory() as tmp_dir:
       config.save_pretrained(_lowerCamelCase   )
       UpperCamelCase_     :					str   	=GenerationConfig.from_pretrained(_lowerCamelCase      ,  temperature=1.0   )

      self.assertEqual(loaded_config.temperature      ,  1.0   )
      self.assertEqual(loaded_config.do_sample      ,  _lowerCamelCase   )
      self.assertEqual(loaded_config.num_beams      ,  1   )  # default value





@is_staging_test
class 				a__					(						unittest.TestCase       ):



     @classmethod
     def  lowerCamelCase_						(							cls :Optional[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Dict   	=TOKEN
      HfFolder.save_token(_lowerCamelCase   )



     @classmethod
     def  lowerCamelCase_						(							cls :List[Any]   ):







      '''simple docstring'''



      try:
       delete_repo(token=cls._token      ,  repo_id='test-generation-config'   )
      except HTTPError:
       pass

      try:
       delete_repo(token=cls._token      ,  repo_id='valid_org/test-generation-config-org'   )
      except HTTPError:
       pass



     def  lowerCamelCase_						(							self :List[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[str]   	=GenerationConfig(
          do_sample=_lowerCamelCase      ,  temperature=0.7      ,  length_penalty=1.0      ,  )
      config.push_to_hub('test-generation-config'      ,  use_auth_token=self._token   )

      UpperCamelCase_     :					List[Any]   	=GenerationConfig.from_pretrained(f'''{USER}/test-generation-config'''   )
      for k, v in config.to_dict().items():
       if k != "transformers_version":
        self.assertEqual(_lowerCamelCase      ,  getattr(_lowerCamelCase      ,  _lowerCamelCase   )   )

        # Reset repo
      delete_repo(token=self._token      ,  repo_id='test-generation-config'   )

      # Push to hub via save_pretrained
      with tempfile.TemporaryDirectory() as tmp_dir:
       config.save_pretrained(
           _lowerCamelCase      ,  repo_id='test-generation-config'      ,  push_to_hub=_lowerCamelCase      ,  use_auth_token=self._token   )

      UpperCamelCase_     :					Any   	=GenerationConfig.from_pretrained(f'''{USER}/test-generation-config'''   )
      for k, v in config.to_dict().items():
       if k != "transformers_version":
        self.assertEqual(_lowerCamelCase      ,  getattr(_lowerCamelCase      ,  _lowerCamelCase   )   )




     def  lowerCamelCase_						(							self :Union[str, Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Union[str, Any]   	=GenerationConfig(
          do_sample=_lowerCamelCase      ,  temperature=0.7      ,  length_penalty=1.0      ,  )
      config.push_to_hub('valid_org/test-generation-config-org'      ,  use_auth_token=self._token   )

      UpperCamelCase_     :					int   	=GenerationConfig.from_pretrained('valid_org/test-generation-config-org'   )
      for k, v in config.to_dict().items():
       if k != "transformers_version":
        self.assertEqual(_lowerCamelCase      ,  getattr(_lowerCamelCase      ,  _lowerCamelCase   )   )

        # Reset repo
      delete_repo(token=self._token      ,  repo_id='valid_org/test-generation-config-org'   )

      # Push to hub via save_pretrained
      with tempfile.TemporaryDirectory() as tmp_dir:
       config.save_pretrained(
           _lowerCamelCase      ,  repo_id='valid_org/test-generation-config-org'      ,  push_to_hub=_lowerCamelCase      ,  use_auth_token=self._token   )

      UpperCamelCase_     :					Optional[Any]   	=GenerationConfig.from_pretrained('valid_org/test-generation-config-org'   )
      for k, v in config.to_dict().items():
       if k != "transformers_version":
        self.assertEqual(_lowerCamelCase      ,  getattr(_lowerCamelCase      ,  _lowerCamelCase   )   )
