




'''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_							(_a			:							Tuple					,     _a			:							Dict=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(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_							(_a			:							Tuple  ):
				return unittest.skip('''Test was skipped'''  )(lowerCamelCase_  )





def 		snake_case_							(_a			:							Union[str, Any]  ):
				return unittest.skipUnless(_run_slow_tests					,     '''test is slow'''  )(lowerCamelCase_  )





def 		snake_case_							(_a			:							Dict  ):
				return unittest.skipUnless(not torch.cuda.is_available()					,     '''test requires only a CPU'''  )(lowerCamelCase_  )





def 		snake_case_							(_a			:							Union[str, Any]  ):
				return unittest.skipUnless(torch.cuda.is_available()					,     '''test requires a GPU'''  )(lowerCamelCase_  )





def 		snake_case_							(_a			:							str  ):
				return unittest.skipUnless(is_xpu_available()					,     '''test requires a XPU'''  )(lowerCamelCase_  )





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





def 		snake_case_							(_a			:							int  ):
				return unittest.skipUnless(
				    is_transformers_available() and is_datasets_available()					,     '''test requires the Hugging Face suite'''  )(lowerCamelCase_  )





def 		snake_case_							(_a			:							Any  ):
				return unittest.skipUnless(is_bnb_available()					,     '''test requires the bitsandbytes library'''  )(lowerCamelCase_  )





def 		snake_case_							(_a			:							Tuple  ):
				return unittest.skipUnless(is_tpu_available()					,     '''test requires TPU'''  )(lowerCamelCase_  )





def 		snake_case_							(_a			:							Union[str, Any]  ):
				return unittest.skipUnless(torch.cuda.device_count() == 1					,     '''test requires a GPU'''  )(lowerCamelCase_  )





def 		snake_case_							(_a			:							Tuple  ):
				return unittest.skipUnless(torch.xpu.device_count() == 1					,     '''test requires a XPU'''  )(lowerCamelCase_  )





def 		snake_case_							(_a			:							List[str]  ):
				return unittest.skipUnless(torch.cuda.device_count() > 1					,     '''test requires multiple GPUs'''  )(lowerCamelCase_  )





def 		snake_case_							(_a			:							Union[str, Any]  ):
				return unittest.skipUnless(torch.xpu.device_count() > 1					,     '''test requires multiple XPUs'''  )(lowerCamelCase_  )





def 		snake_case_							(_a			:							Optional[Any]  ):
				return unittest.skipUnless(is_safetensors_available()					,     '''test requires safetensors'''  )(lowerCamelCase_  )





def 		snake_case_							(_a			:							str  ):
				return unittest.skipUnless(is_deepspeed_available()					,     '''test requires DeepSpeed'''  )(lowerCamelCase_  )





def 		snake_case_							(_a			:							Optional[int]  ):
				return unittest.skipUnless(is_torch_version('''>='''					,     '''1.12.0'''  )					,     '''test requires torch version >= 1.12.0'''  )(lowerCamelCase_  )





def 		snake_case_							(_a			:							int=None					,     _a			:							Tuple=None  ):

				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_							(_a			:							str  ):
				return unittest.skipUnless(is_tensorboard_available()					,     '''test requires Tensorboard'''  )(lowerCamelCase_  )





def 		snake_case_							(_a			:							int  ):
				return unittest.skipUnless(is_wandb_available()					,     '''test requires wandb'''  )(lowerCamelCase_  )





def 		snake_case_							(_a			:							Optional[int]  ):
				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_							(_a			:							Union[str, Any]  ):
				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     _a						(			unittest.TestCase				):
							__a       :  List[str]            =      True
							@classmethod
							def 					A   (			cls		:			str       ):



											'''simple docstring'''

											UpperCAmelCase     =	tempfile.mkdtemp()
							@classmethod
							def 					A   (			cls		:			Dict       ):



											'''simple docstring'''

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







							def 					A   (			self		:			Tuple       ):



											'''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 					A   (			self		:			Optional[Any]       ):



											'''simple docstring'''

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






class     _a						(			unittest.TestCase				):
							def 					A   (			self		:			List[Any]     ,       lowercase		:			Optional[Any]       ):



											'''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_							(_a			:							Any  ):
				UpperCAmelCase     =	AcceleratorState()
				UpperCAmelCase     =	tensor[None].clone().to(state.device  )
				UpperCAmelCase     =	gather(lowerCamelCase_  ).cpu()
				UpperCAmelCase     =	tensor[0].cpu()
				for i in range(tensors.shape[0]  ):
								if not torch.equal(tensors[i]					,     lowerCamelCase_  ):
												return False
				return True


class     _a						:
							def __init__(			self		:			Dict     ,       lowercase		:			Dict     ,       lowercase		:			List[Any]     ,       lowercase		:			Union[str, Any]       ):



											'''simple docstring'''

											UpperCAmelCase     =	returncode
											UpperCAmelCase     =	stdout
											UpperCAmelCase     =	stderr






async def 		snake_case_							(_a			:							Any					,     _a			:							Any  ):

				while True:
								UpperCAmelCase     =	await stream.readline()
								if line:
												callback(lowerCamelCase_  )
								else:
												break





async def 		snake_case_							(_a			:							Any					,     _a			:							Union[str, Any]=None					,     _a			:							Dict=None					,     _a			:							Any=None					,     _a			:							str=False					,     _a			:							List[str]=False  ):

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

				UpperCAmelCase     =	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)

				UpperCAmelCase     =	[]
				UpperCAmelCase     =	[]

				def tee(_a			:							int					,     _a			:							List[Any]					,     _a			:							List[Any]					,     _a			:							int=""  ):
								UpperCAmelCase     =	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 _a  : tee(lowerCamelCase_					,     lowerCamelCase_					,     sys.stdout					,     label='''stdout:'''  )  )  ),
				        asyncio.create_task(_read_stream(p.stderr					,     lambda _a  : tee(lowerCamelCase_					,     lowerCamelCase_					,     sys.stderr					,     label='''stderr:'''  )  )  ),
				    ]					,     timeout=lowerCamelCase_					,     )
				return _RunOutput(await p.wait()					,     lowerCamelCase_					,     lowerCamelCase_  )





def 		snake_case_							(_a			:							str					,     _a			:							Optional[Any]=None					,     _a			:							int=None					,     _a			:							str=1_8_0					,     _a			:							Optional[Any]=False					,     _a			:							Optional[int]=True  ):
				UpperCAmelCase     =	asyncio.get_event_loop()
				UpperCAmelCase     =	loop.run_until_complete(
				    _stream_subprocess(lowerCamelCase_					,     env=lowerCamelCase_					,     stdin=lowerCamelCase_					,     timeout=lowerCamelCase_					,     quiet=lowerCamelCase_					,     echo=lowerCamelCase_  )  )

				UpperCAmelCase     =	''' '''.join(lowerCamelCase_  )
				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     _a						(			lowerCamelCase__				):
							pass






def 		snake_case_							(_a			:							List[str]					,     _a			:							int=False  ):

				try:
								UpperCAmelCase     =	subprocess.check_output(lowerCamelCase_					,     stderr=subprocess.STDOUT  )
								if return_stdout:
												if hasattr(lowerCamelCase_					,     '''decode'''  ):
																UpperCAmelCase     =	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 unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import (
       OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
       OpenAIGPTConfig,
       OpenAIGPTDoubleHeadsModel,
       OpenAIGPTForSequenceClassification,
       OpenAIGPTLMHeadModel,
       OpenAIGPTModel,
   )


class     _a						:
       def __init__(			self		:			Optional[Any]     ,       lowercase		:			int     ,       lowercase		:			str=13     ,       lowercase		:			int=7     ,       lowercase		:			Optional[int]=True     ,       lowercase		:			Dict=True     ,       lowercase		:			Union[str, Any]=True     ,       lowercase		:			Union[str, Any]=99     ,       lowercase		:			Optional[Any]=32     ,       lowercase		:			List[Any]=5     ,       lowercase		:			List[Any]=4     ,       lowercase		:			int=37     ,       lowercase		:			int="gelu"     ,       lowercase		:			Tuple=0.1     ,       lowercase		:			Dict=0.1     ,       lowercase		:			Tuple=512     ,       lowercase		:			List[str]=16     ,       lowercase		:			Optional[int]=2     ,       lowercase		:			int=0.02     ,       lowercase		:			str=3     ,       lowercase		:			List[Any]=4     ,       lowercase		:			List[str]=None     ,       ):



           '''simple docstring'''

           UpperCAmelCase     =	parent
           UpperCAmelCase     =	batch_size
           UpperCAmelCase     =	seq_length
           UpperCAmelCase     =	is_training
           UpperCAmelCase     =	use_token_type_ids
           UpperCAmelCase     =	use_labels
           UpperCAmelCase     =	vocab_size
           UpperCAmelCase     =	hidden_size
           UpperCAmelCase     =	num_hidden_layers
           UpperCAmelCase     =	num_attention_heads
           UpperCAmelCase     =	intermediate_size
           UpperCAmelCase     =	hidden_act
           UpperCAmelCase     =	hidden_dropout_prob
           UpperCAmelCase     =	attention_probs_dropout_prob
           UpperCAmelCase     =	max_position_embeddings
           UpperCAmelCase     =	type_vocab_size
           UpperCAmelCase     =	type_sequence_label_size
           UpperCAmelCase     =	initializer_range
           UpperCAmelCase     =	num_labels
           UpperCAmelCase     =	num_choices
           UpperCAmelCase     =	scope
           UpperCAmelCase     =	self.vocab_size - 1
       def 					A   (			self		:			List[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	ids_tensor([self.batch_size, self.seq_length]     ,       self.vocab_size       )

           UpperCAmelCase     =	None
           if self.use_token_type_ids:
               UpperCAmelCase     =	ids_tensor([self.batch_size, self.seq_length]     ,       self.type_vocab_size       )

           UpperCAmelCase     =	None
           UpperCAmelCase     =	None
           UpperCAmelCase     =	None
           if self.use_labels:
               UpperCAmelCase     =	ids_tensor([self.batch_size]     ,       self.type_sequence_label_size       )
               UpperCAmelCase     =	ids_tensor([self.batch_size, self.seq_length]     ,       self.num_labels       )
               UpperCAmelCase     =	ids_tensor([self.batch_size]     ,       self.num_choices       )

           UpperCAmelCase     =	OpenAIGPTConfig(
               vocab_size=self.vocab_size     ,       n_embd=self.hidden_size     ,       n_layer=self.num_hidden_layers     ,       n_head=self.num_attention_heads     ,       n_positions=self.max_position_embeddings     ,       pad_token_id=self.pad_token_id     ,       )

           UpperCAmelCase     =	ids_tensor([self.num_hidden_layers, self.num_attention_heads]     ,       2       )

           return (
               config,
               input_ids,
               head_mask,
               token_type_ids,
               sequence_labels,
               token_labels,
               choice_labels,
           )
       def 					A   (			self		:			Any     ,       lowercase		:			Tuple     ,       lowercase		:			List[Any]     ,       lowercase		:			Optional[Any]     ,       lowercase		:			List[str]     ,       *lowercase		:			Optional[int]       ):



           '''simple docstring'''

           UpperCAmelCase     =	OpenAIGPTModel(config=lowercase       )
           model.to(lowercase       )
           model.eval()

           UpperCAmelCase     =	model(lowercase     ,       token_type_ids=lowercase     ,       head_mask=lowercase       )
           UpperCAmelCase     =	model(lowercase     ,       token_type_ids=lowercase       )
           UpperCAmelCase     =	model(lowercase       )

           self.parent.assertEqual(result.last_hidden_state.shape     ,       (self.batch_size, self.seq_length, self.hidden_size)       )
       def 					A   (			self		:			List[str]     ,       lowercase		:			Optional[int]     ,       lowercase		:			List[Any]     ,       lowercase		:			str     ,       lowercase		:			Optional[int]     ,       *lowercase		:			List[str]       ):



           '''simple docstring'''

           UpperCAmelCase     =	OpenAIGPTLMHeadModel(lowercase       )
           model.to(lowercase       )
           model.eval()

           UpperCAmelCase     =	model(lowercase     ,       token_type_ids=lowercase     ,       labels=lowercase       )
           self.parent.assertEqual(result.loss.shape     ,       ()       )
           self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.seq_length, self.vocab_size)       )
       def 					A   (			self		:			Optional[int]     ,       lowercase		:			Tuple     ,       lowercase		:			Tuple     ,       lowercase		:			Optional[int]     ,       lowercase		:			Optional[int]     ,       *lowercase		:			Optional[int]       ):



           '''simple docstring'''

           UpperCAmelCase     =	OpenAIGPTDoubleHeadsModel(lowercase       )
           model.to(lowercase       )
           model.eval()

           UpperCAmelCase     =	model(lowercase     ,       token_type_ids=lowercase     ,       labels=lowercase       )
           self.parent.assertEqual(result.loss.shape     ,       ()       )
           self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.seq_length, self.vocab_size)       )
       def 					A   (			self		:			Tuple     ,       lowercase		:			Dict     ,       lowercase		:			Any     ,       lowercase		:			Any     ,       lowercase		:			Optional[int]     ,       *lowercase		:			int       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.num_labels
           UpperCAmelCase     =	OpenAIGPTForSequenceClassification(lowercase       )
           model.to(lowercase       )
           model.eval()

           UpperCAmelCase     =	ids_tensor([self.batch_size]     ,       self.type_sequence_label_size       )
           UpperCAmelCase     =	model(lowercase     ,       token_type_ids=lowercase     ,       labels=lowercase       )
           self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.num_labels)       )







       def 					A   (			self		:			List[str]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.prepare_config_and_inputs()
           (
               (
               UpperCAmelCase
           ) ,  (
               UpperCAmelCase
           ) ,  (
               UpperCAmelCase
           ) ,  (
               UpperCAmelCase
           ) ,  (
               UpperCAmelCase
           ) ,  (
               UpperCAmelCase
           ) ,  (
               UpperCAmelCase
           ) ,  
           )     =	config_and_inputs
           UpperCAmelCase     =	{
               '''input_ids''': input_ids,
               '''token_type_ids''': token_type_ids,
               '''head_mask''': head_mask,
           }

           return config, inputs_dict






@require_torch
class     _a						(			__a							,							__a							,							__a							,							unittest.TestCase				):
       __a       :  List[str]            =      (
           (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
           if is_torch_available()
           else ()
       )
       __a       :  List[Any]            =      (
           (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
       )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
       __a       :  Dict            =      (
           {
               """feature-extraction""": OpenAIGPTModel,
               """text-classification""": OpenAIGPTForSequenceClassification,
               """text-generation""": OpenAIGPTLMHeadModel,
               """zero-shot""": OpenAIGPTForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       def 					A   (			self		:			Optional[Any]     ,       lowercase		:			Union[str, Any]     ,       lowercase		:			Tuple     ,       lowercase		:			int     ,       lowercase		:			List[Any]     ,       lowercase		:			Optional[Any]       ):



           '''simple docstring'''

           if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
               # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
               # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
               # tiny config could not be created.
               return True

           return False
       def 					A   (			self		:			List[Any]     ,       lowercase		:			int     ,       lowercase		:			List[Any]     ,       lowercase		:			Optional[Any]=False       ):



           '''simple docstring'''

           UpperCAmelCase     =	super()._prepare_for_class(lowercase     ,       lowercase     ,       return_labels=lowercase       )

           if return_labels:
               if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
                   UpperCAmelCase     =	torch.zeros(
                       (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)     ,       dtype=torch.long     ,       device=lowercase     ,       )
                   UpperCAmelCase     =	inputs_dict['''labels''']
                   UpperCAmelCase     =	inputs_dict['''labels''']
                   UpperCAmelCase     =	torch.zeros(
                       (self.model_tester.batch_size, self.model_tester.num_choices)     ,       dtype=torch.long     ,       device=lowercase     ,       )
                   UpperCAmelCase     =	torch.zeros(
                       self.model_tester.batch_size     ,       dtype=torch.long     ,       device=lowercase       )
           return inputs_dict
       def 					A   (			self		:			List[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	OpenAIGPTModelTester(self       )
           UpperCAmelCase     =	ConfigTester(self     ,       config_class=lowercase     ,       n_embd=37       )
       def 					A   (			self		:			str       ):



           '''simple docstring'''

           self.config_tester.run_common_tests()
       def 					A   (			self		:			Tuple       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_openai_gpt_model(*lowercase       )
       def 					A   (			self		:			Optional[int]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_lm_head_model(*lowercase       )
       def 					A   (			self		:			List[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_double_lm_head_model(*lowercase       )
       def 					A   (			self		:			Optional[int]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*lowercase       )







       @slow
       def 					A   (			self		:			List[Any]       ):



           '''simple docstring'''

           for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               UpperCAmelCase     =	OpenAIGPTModel.from_pretrained(lowercase       )
               self.assertIsNotNone(lowercase       )






@require_torch
class     _a						(			unittest.TestCase				):
       @slow
       def 					A   (			self		:			Any       ):



           '''simple docstring'''

           UpperCAmelCase     =	OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt'''       )
           model.to(lowercase       )
           UpperCAmelCase     =	torch.tensor([[481, 4_735, 544]]     ,       dtype=torch.long     ,       device=lowercase       )  # the president is
           UpperCAmelCase     =	[
               481,
               4_735,
               544,
               246,
               963,
               870,
               762,
               239,
               244,
               40_477,
               244,
               249,
               719,
               881,
               487,
               544,
               240,
               244,
               603,
               481,
           ]  # the president is a very good man. " \n " i\'m sure he is, " said the

           UpperCAmelCase     =	model.generate(lowercase     ,       do_sample=lowercase       )
           self.assertListEqual(output_ids[0].tolist()     ,       lowercase       )




