
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 __snake_case		:
    def __init__(  self		,snake_case		,snake_case=13		,snake_case=7		,snake_case=True		,snake_case=True		,snake_case=True		,snake_case=99		,snake_case=32		,snake_case=5		,snake_case=4		,snake_case=37		,snake_case="gelu"		,snake_case=0.1		,snake_case=0.1		,snake_case=512		,snake_case=16		,snake_case=2		,snake_case=0.02		,snake_case=3		,snake_case=4		,snake_case=None		,):



           '''simple docstring'''







           lowercase							:     str       	=      parent
           lowercase							:     List[str]       	=      batch_size
           lowercase							:     Dict       	=      seq_length
           lowercase							:     Tuple       	=      is_training
           lowercase							:     Any       	=      use_token_type_ids
           lowercase							:     str       	=      use_labels
           lowercase							:     List[str]       	=      vocab_size
           lowercase							:     Union[str, Any]       	=      hidden_size
           lowercase							:     Union[str, Any]       	=      num_hidden_layers
           lowercase							:     Optional[Any]       	=      num_attention_heads
           lowercase							:     Tuple       	=      intermediate_size
           lowercase							:     Any       	=      hidden_act
           lowercase							:     Any       	=      hidden_dropout_prob
           lowercase							:     Optional[int]       	=      attention_probs_dropout_prob
           lowercase							:     Optional[int]       	=      max_position_embeddings
           lowercase							:     str       	=      type_vocab_size
           lowercase							:     Tuple       	=      type_sequence_label_size
           lowercase							:     Union[str, Any]       	=      initializer_range
           lowercase							:     List[str]       	=      num_labels
           lowercase							:     Any       	=      num_choices
           lowercase							:     Optional[int]       	=      scope
           lowercase							:     Dict       	=      self.vocab_size - 1
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     int       	=      ids_tensor([self.batch_size, self.seq_length]		,self.vocab_size      )

           lowercase							:     Optional[Any]       	=      None
           if self.use_token_type_ids:
                  lowercase							:     int       	=      ids_tensor([self.batch_size, self.seq_length]		,self.type_vocab_size      )

           lowercase							:     Any       	=      None
           lowercase							:     Dict       	=      None
           lowercase							:     Any       	=      None
           if self.use_labels:
                  lowercase							:     Optional[int]       	=      ids_tensor([self.batch_size]		,self.type_sequence_label_size      )
                  lowercase							:     List[str]       	=      ids_tensor([self.batch_size, self.seq_length]		,self.num_labels      )
                  lowercase							:     Union[str, Any]       	=      ids_tensor([self.batch_size]		,self.num_choices      )

           lowercase							:     List[str]       	=      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		,)

           lowercase							:     str       	=      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       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case		,snake_case		,snake_case		,*snake_case      ):



           '''simple docstring'''







           lowercase							:     int       	=      OpenAIGPTModel(config=snake_case      )
           model.to(snake_case      )
           model.eval()

           lowercase							:     Dict       	=      model(snake_case		,token_type_ids=snake_case		,head_mask=snake_case      )
           lowercase							:     Union[str, Any]       	=      model(snake_case		,token_type_ids=snake_case      )
           lowercase							:     int       	=      model(snake_case      )

           self.parent.assertEqual(result.last_hidden_state.shape		,(self.batch_size, self.seq_length, self.hidden_size)      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case		,snake_case		,snake_case		,*snake_case      ):



           '''simple docstring'''







           lowercase							:     List[Any]       	=      OpenAIGPTLMHeadModel(snake_case      )
           model.to(snake_case      )
           model.eval()

           lowercase							:     Dict       	=      model(snake_case		,token_type_ids=snake_case		,labels=snake_case      )
           self.parent.assertEqual(result.loss.shape		,()      )
           self.parent.assertEqual(result.logits.shape		,(self.batch_size, self.seq_length, self.vocab_size)      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case		,snake_case		,snake_case		,*snake_case      ):



           '''simple docstring'''







           lowercase							:     List[Any]       	=      OpenAIGPTDoubleHeadsModel(snake_case      )
           model.to(snake_case      )
           model.eval()

           lowercase							:     int       	=      model(snake_case		,token_type_ids=snake_case		,labels=snake_case      )
           self.parent.assertEqual(result.loss.shape		,()      )
           self.parent.assertEqual(result.logits.shape		,(self.batch_size, self.seq_length, self.vocab_size)      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case		,snake_case		,snake_case		,*snake_case      ):



           '''simple docstring'''







           lowercase							:     List[Any]       	=      self.num_labels
           lowercase							:     Any       	=      OpenAIGPTForSequenceClassification(snake_case      )
           model.to(snake_case      )
           model.eval()

           lowercase							:     int       	=      ids_tensor([self.batch_size]		,self.type_sequence_label_size      )
           lowercase							:     List[str]       	=      model(snake_case		,token_type_ids=snake_case		,labels=snake_case      )
           self.parent.assertEqual(result.logits.shape		,(self.batch_size, self.num_labels)      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     List[Any]       	=      self.prepare_config_and_inputs()
           (
               (
               lowercase
           )	,			(
               lowercase
           )	,			(
               lowercase
           )	,			(
               lowercase
           )	,			(
               lowercase
           )	,			(
               lowercase
           )	,			(
               lowercase
           )	,			
           )							:     Any       	=      config_and_inputs
           lowercase							:     int       	=      {
               """input_ids""": input_ids,
               """token_type_ids""": token_type_ids,
               """head_mask""": head_mask,
           }

           return config, inputs_dict






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



           '''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       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case		,snake_case=False      ):



           '''simple docstring'''







           lowercase							:     Tuple       	=      super()._prepare_for_class(snake_case		,snake_case		,return_labels=snake_case      )

           if return_labels:
                  if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
                         lowercase							:     List[str]       	=      torch.zeros(
                             (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)		,dtype=torch.long		,device=snake_case		,)
                         lowercase							:     Tuple       	=      inputs_dict["""labels"""]
                         lowercase							:     Dict       	=      inputs_dict["""labels"""]
                         lowercase							:     List[Any]       	=      torch.zeros(
                             (self.model_tester.batch_size, self.model_tester.num_choices)		,dtype=torch.long		,device=snake_case		,)
                         lowercase							:     List[str]       	=      torch.zeros(
                             self.model_tester.batch_size		,dtype=torch.long		,device=snake_case      )
           return inputs_dict
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Dict       	=      OpenAIGPTModelTester(self      )
           lowercase							:     str       	=      ConfigTester(self		,config_class=snake_case		,n_embd=37      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           self.config_tester.run_common_tests()
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     int       	=      self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_openai_gpt_model(*snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Tuple       	=      self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_lm_head_model(*snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     str       	=      self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_double_lm_head_model(*snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     str       	=      self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*snake_case      )
    @slow
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







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






@require_torch
class __snake_case		(      unittest.TestCase     ):
    @slow
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     int       	=      OpenAIGPTLMHeadModel.from_pretrained("""openai-gpt"""      )
           model.to(snake_case      )
           lowercase							:     List[Any]       	=      torch.tensor([[481, 4735, 544]]		,dtype=torch.long		,device=snake_case      )  # the president is
           lowercase							:     str       	=      [
               481,
               4735,
               544,
               246,
               963,
               870,
               762,
               239,
               244,
               40477,
               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

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




'''simple docstring'''



import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
__lowercase	:						Tuple       =	pytest.mark.integration


__lowercase	:						Optional[int]       =	{'comet'}
__lowercase	:						List[str]       =	importlib.util.find_spec('fairseq') is not None

__lowercase	:						str       =	{'code_eval'}
__lowercase	:						List[Any]       =	os.name == 'nt'

__lowercase	:						Optional[Any]       =	{'bertscore', 'frugalscore', 'perplexity'}
__lowercase	:						Optional[Any]       =	importlib.util.find_spec('transformers') is not None






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Dict   ):
					@wraps(_SCREAMING_SNAKE_CASE   )
					def wrapper(self      :   int						,      _SCREAMING_SNAKE_CASE      :   List[Any]   ):
										if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
															self.skipTest('"test requires Fairseq"'   )
										else:
															test_case(self						,      _SCREAMING_SNAKE_CASE   )

					return wrapper






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Union[str, Any]   ):
					@wraps(_SCREAMING_SNAKE_CASE   )
					def wrapper(self      :   Dict						,      _SCREAMING_SNAKE_CASE      :   Union[str, Any]   ):
										if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
															self.skipTest('"test requires transformers"'   )
										else:
															test_case(self						,      _SCREAMING_SNAKE_CASE   )

					return wrapper






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Dict   ):
					@wraps(_SCREAMING_SNAKE_CASE   )
					def wrapper(self      :   Optional[int]						,      _SCREAMING_SNAKE_CASE      :   Optional[Any]   ):
										if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
															self.skipTest('"test not supported on Windows"'   )
										else:
															test_case(self						,      _SCREAMING_SNAKE_CASE   )

					return wrapper






def   lowerCamelCase							():
					__a			:       List[Any]					    =  [metric_dir.split(os.sep   )[-2] for metric_dir in glob.glob('./metrics/*/'   )]
					return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished





@parameterized.named_parameters(get_local_metric_names()					)
@for_all_test_methods(
    lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_					)
@local
class 							__UpperCamelCase				(		parameterized.TestCase					):
	A_				=    {}
	A_				=    None




	@pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning'							)
	@pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning'							)
	def       __UpperCAmelCase							(   self						,				__a							):

						'''simple docstring'''





						__a			:       int					    =  '[...]'
						__a			:       Tuple					    =  importlib.import_module(
						    datasets.load.metric_module_factory(os.path.join('metrics'						,				__a							)							).module_path							)
						__a			:       Optional[Any]					    =  datasets.load.import_main_class(metric_module.__name__						,				dataset=__a							)
						# check parameters
						__a			:       Dict					    =  inspect.signature(metric._compute							).parameters
						self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()							)							)  # no **kwargs
						# run doctest
						with self.patch_intensive_calls(__a						,				metric_module.__name__							):
											with self.use_local_metrics():
																try:
																					__a			:       str					    =  doctest.testmod(__a						,				verbose=__a						,				raise_on_error=__a							)
																except doctest.UnexpectedException as e:
																					raise e.exc_info[1]  # raise the exception that doctest caught
						self.assertEqual(results.failed						,				0							)
						self.assertGreater(results.attempted						,				1							)




	@slow
	def       __UpperCAmelCase							(   self						,				__a							):

						'''simple docstring'''





						__a			:       Tuple					    =  '[...]'
						__a			:       Optional[Any]					    =  importlib.import_module(
						    datasets.load.metric_module_factory(os.path.join('metrics'						,				__a							)							).module_path							)
						# run doctest
						with self.use_local_metrics():
											__a			:       List[Any]					    =  doctest.testmod(__a						,				verbose=__a						,				raise_on_error=__a							)
						self.assertEqual(results.failed						,				0							)
						self.assertGreater(results.attempted						,				1							)




	@contextmanager
	def       __UpperCAmelCase							(   self						,				__a						,				__a							):

						'''simple docstring'''





						if metric_name in self.INTENSIVE_CALLS_PATCHER:
											with self.INTENSIVE_CALLS_PATCHER[metric_name](__a							):
																yield
						else:
											yield




	@contextmanager
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						def load_local_metric(__a						,				*__a						,				**__a							):
											return load_metric(os.path.join('metrics'						,				__a							)						,				*__a						,				**__a							)

						with patch('datasets.load_metric'							) as mock_load_metric:
											__a			:       Dict					    =  load_local_metric
											yield





	@classmethod
	def       __UpperCAmelCase							(   cls						,				__a							):

						'''simple docstring'''





						def wrapper(__a							):
											__a			:       Optional[Any]					    =  contextmanager(__a							)
											__a			:       str					    =  patcher
											return patcher

						return wrapper






@LocalMetricTest.register_intensive_calls_patcher('bleurt'   )
def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Dict   ):
					import tensorflow.compat.va as tf
					from bleurt.score import Predictor

					tf.flags.DEFINE_string('sv'						,      ''						,      ''   )  # handle pytest cli flags





					class 							__UpperCamelCase				(		lowerCAmelCase_					):




						def       __UpperCAmelCase							(   self						,				__a							):

											'''simple docstring'''





											assert len(input_dict['input_ids']							) == 2
											return np.array([1.03, 1.04]							)

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
					with patch('bleurt.score._create_predictor'   ) as mock_create_predictor:
										__a			:       Dict					    =  MockedPredictor()
										yield






@LocalMetricTest.register_intensive_calls_patcher('bertscore'   )
def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   str   ):
					import torch

					def bert_cos_score_idf(_SCREAMING_SNAKE_CASE      :   List[str]						,      _SCREAMING_SNAKE_CASE      :   str						,      *_SCREAMING_SNAKE_CASE      :   int						,      **_SCREAMING_SNAKE_CASE      :   Optional[int]   ):
										return torch.tensor([[1.0, 1.0, 1.0]] * len(_SCREAMING_SNAKE_CASE   )   )

					# mock get_model which is supposed to do download a bert model
					# mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
					with patch('bert_score.scorer.get_model'   ), patch(
					    'bert_score.scorer.bert_cos_score_idf'   ) as mock_bert_cos_score_idf:
										__a			:       str					    =  bert_cos_score_idf
										yield






@LocalMetricTest.register_intensive_calls_patcher('comet'   )
def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Dict   ):
					def load_from_checkpoint(_SCREAMING_SNAKE_CASE      :   Optional[int]   ):





										class 							__UpperCamelCase				:




											def       __UpperCAmelCase							(   self						,				__a						,				*__a						,				**__a							):

																'''simple docstring'''





																assert len(__a							) == 2
																__a			:       Dict					    =  [0.19, 0.92]
																return scores, sum(__a							) / len(__a							)



										return Model()

					# mock load_from_checkpoint which is supposed to do download a bert model
					# mock load_from_checkpoint which is supposed to do download a bert model
					with patch('comet.download_model'   ) as mock_download_model:
										__a			:       str					    =  None
										with patch('comet.load_from_checkpoint'   ) as mock_load_from_checkpoint:
															__a			:       int					    =  load_from_checkpoint
															yield






def   lowerCamelCase							():
					__a			:       Optional[Any]					    =  load_metric(os.path.join('metrics'						,      'seqeval'   )   )
					__a			:       List[str]					    =  'ERROR'
					__a			:       List[str]					    =  F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"""
					with pytest.raises(_SCREAMING_SNAKE_CASE						,      match=re.escape(_SCREAMING_SNAKE_CASE   )   ):
										metric.compute(predictions=[]						,      references=[]						,      scheme=_SCREAMING_SNAKE_CASE   )



