
'''simple docstring'''







import enum
import warnings

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
					import tensorflow as tf

					from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

if is_torch_available():
					from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

lowercase					:							Tuple   =      logging.get_logger(__name__)


class 		__UpperCAmelCase   (      enum.Enum		):
							__lowercase   	= 0
							__lowercase   	= 1


@add_end_docstrings(_lowerCamelCase		)
class 		__UpperCAmelCase   (      _lowerCamelCase		):
							__lowercase   	= """generated"""


							def __init__( self					,     *lowerCAmelCase_					,     **lowerCAmelCase_						):





								"""simple docstring"""






								super().__init__(*lowerCAmelCase_					,     **lowerCAmelCase_						)

								self.check_model_type(
								    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
								    if self.framework == 'tf'
								    else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING						)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_=None					,     lowerCAmelCase_=None					,     lowerCAmelCase_=None					,     lowerCAmelCase_=None					,     lowerCAmelCase_=None					,     lowerCAmelCase_=None					,     **lowerCAmelCase_					,     ):





								"""simple docstring"""






								_snake_case     		=	{}
								if truncation is not None:
									_snake_case     		=	truncation

								_snake_case     		=	generate_kwargs

								_snake_case     		=	{}
								if return_tensors is not None and return_type is None:
									_snake_case     		=	ReturnType.TENSORS if return_tensors else ReturnType.TEXT
								if return_type is not None:
									_snake_case     		=	return_type

								if clean_up_tokenization_spaces is not None:
									_snake_case     		=	clean_up_tokenization_spaces

								if stop_sequence is not None:
									_snake_case     		=	self.tokenizer.encode(lowerCAmelCase_					,     add_special_tokens=lowerCAmelCase_						)
									if len(lowerCAmelCase_						) > 1:
										warnings.warn(
										    'Stopping on a multiple token sequence is not yet supported on transformers. The first token of'
										    ' the stop sequence will be used as the stop sequence string in the interim.'						)
									_snake_case     		=	stop_sequence_ids[0]

								return preprocess_params, forward_params, postprocess_params


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_						):





								"""simple docstring"""






								return True


							def 				lowerCamelCase       ( self					,     *lowerCAmelCase_					,     lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	self.model.config.prefix if self.model.config.prefix is not None else ''
								if isinstance(args[0]					,     lowerCAmelCase_						):
									if self.tokenizer.pad_token_id is None:
										raise ValueError('Please make sure that the tokenizer has a pad_token_id when using a batch input'						)
									_snake_case     		=	([prefix + arg for arg in args[0]],)
									_snake_case     		=	True

								elif isinstance(args[0]					,     lowerCAmelCase_						):
									_snake_case     		=	(prefix + args[0],)
									_snake_case     		=	False
								else:
									raise ValueError(
									    F' `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`'						)
								_snake_case     		=	self.tokenizer(*lowerCAmelCase_					,     padding=lowerCAmelCase_					,     truncation=lowerCAmelCase_					,     return_tensors=self.framework						)
								# This is produced by tokenizers but is an invalid generate kwargs
								if "token_type_ids" in inputs:
									del inputs["token_type_ids"]
								return inputs


							def __call__( self					,     *lowerCAmelCase_					,     **lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	super().__call__(*lowerCAmelCase_					,     **lowerCAmelCase_						)
								if (
								    isinstance(args[0]					,     lowerCAmelCase_						)
								    and all(isinstance(lowerCAmelCase_					,     lowerCAmelCase_						) for el in args[0]						)
								    and all(len(lowerCAmelCase_						) == 1 for res in result						)
								):
									return [res[0] for res in result]
								return result


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_=TruncationStrategy.DO_NOT_TRUNCATE					,     **lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	self._parse_and_tokenize(lowerCAmelCase_					,     truncation=lowerCAmelCase_					,     **lowerCAmelCase_						)
								return inputs


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     **lowerCAmelCase_						):





								"""simple docstring"""






								if self.framework == "pt":
									_snake_case		,				_snake_case     		=	model_inputs['input_ids'].shape
								elif self.framework == "tf":
									_snake_case		,				_snake_case     		=	tf.shape(model_inputs['input_ids']						).numpy()

								_snake_case     		=	generate_kwargs.get('min_length'					,     self.model.config.min_length						)
								_snake_case     		=	generate_kwargs.get('max_length'					,     self.model.config.max_length						)
								self.check_inputs(lowerCAmelCase_					,     generate_kwargs['min_length']					,     generate_kwargs['max_length']						)
								_snake_case     		=	self.model.generate(**lowerCAmelCase_					,     **lowerCAmelCase_						)
								_snake_case     		=	output_ids.shape[0]
								if self.framework == "pt":
									_snake_case     		=	output_ids.reshape(lowerCAmelCase_					,     out_b // in_b					,     *output_ids.shape[1:]						)
								elif self.framework == "tf":
									_snake_case     		=	tf.reshape(lowerCAmelCase_					,     (in_b, out_b // in_b, *output_ids.shape[1:])						)
								return {"output_ids": output_ids}




							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_=ReturnType.TEXT					,     lowerCAmelCase_=False						):





								"""simple docstring"""






								_snake_case     		=	[]
								for output_ids in model_outputs["output_ids"][0]:
									if return_type == ReturnType.TENSORS:
										_snake_case     		=	{F'{self.return_name}_token_ids': output_ids}
									elif return_type == ReturnType.TEXT:
										_snake_case     		=	{
										    F'{self.return_name}_text': self.tokenizer.decode(
										        lowerCAmelCase_					,     skip_special_tokens=lowerCAmelCase_					,     clean_up_tokenization_spaces=lowerCAmelCase_					,     )
										}
									records.append(lowerCAmelCase_						)
								return records


@add_end_docstrings(_lowerCamelCase		)
class 		__UpperCAmelCase   (      _lowerCamelCase		):
							__lowercase   	= """summary"""


							def __call__( self					,     *lowerCAmelCase_					,     **lowerCAmelCase_						):





								"""simple docstring"""






								return super().__call__(*lowerCAmelCase_					,     **lowerCAmelCase_						)




							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_						):





								"""simple docstring"""






								if max_length < min_length:
									logger.warning(F'Your min_length={min_length} must be inferior than your max_length={max_length}.'						)

								if input_length < max_length:
									logger.warning(
									    F'Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is '
									    'a summarization task, where outputs shorter than the input are typically wanted, you might '
									    F'consider decreasing max_length manually, e.g. summarizer(\'...\', max_length={input_length//2})'						)


@add_end_docstrings(_lowerCamelCase		)
class 		__UpperCAmelCase   (      _lowerCamelCase		):
							__lowercase   	= """translation"""


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_						):





								"""simple docstring"""






								if input_length > 0.9 * max_length:
									logger.warning(
									    F'Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider '
									    'increasing your max_length manually, e.g. translator(\'...\', max_length=400)'						)
								return True


							def 				lowerCamelCase       ( self					,     *lowerCAmelCase_					,     lowerCAmelCase_=TruncationStrategy.DO_NOT_TRUNCATE					,     lowerCAmelCase_=None					,     lowerCAmelCase_=None						):





								"""simple docstring"""






								if getattr(self.tokenizer					,     '_build_translation_inputs'					,     lowerCAmelCase_						):
									return self.tokenizer._build_translation_inputs(
									    *lowerCAmelCase_					,     return_tensors=self.framework					,     truncation=lowerCAmelCase_					,     src_lang=lowerCAmelCase_					,     tgt_lang=lowerCAmelCase_						)
								else:
									return super()._parse_and_tokenize(*lowerCAmelCase_					,     truncation=lowerCAmelCase_						)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_=None					,     lowerCAmelCase_=None					,     **lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case		,				_snake_case		,				_snake_case     		=	super()._sanitize_parameters(**lowerCAmelCase_						)
								if src_lang is not None:
									_snake_case     		=	src_lang
								if tgt_lang is not None:
									_snake_case     		=	tgt_lang
								if src_lang is None and tgt_lang is None:
									# Backward compatibility, direct arguments use is preferred.
									_snake_case     		=	kwargs.get('task'					,     self.task						)
									_snake_case     		=	task.split('_'						)
									if task and len(lowerCAmelCase_						) == 4:
										# translation, XX, to YY
										_snake_case     		=	items[1]
										_snake_case     		=	items[3]
								return preprocess_params, forward_params, postprocess_params




							def __call__( self					,     *lowerCAmelCase_					,     **lowerCAmelCase_						):





								"""simple docstring"""






								return super().__call__(*lowerCAmelCase_					,     **lowerCAmelCase_						)



'''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 		__UpperCAmelCase   :


							def __init__( self					,     lowerCAmelCase_					,     lowerCAmelCase_=13					,     lowerCAmelCase_=7					,     lowerCAmelCase_=True					,     lowerCAmelCase_=True					,     lowerCAmelCase_=True					,     lowerCAmelCase_=99					,     lowerCAmelCase_=32					,     lowerCAmelCase_=5					,     lowerCAmelCase_=4					,     lowerCAmelCase_=37					,     lowerCAmelCase_="gelu"					,     lowerCAmelCase_=0.1					,     lowerCAmelCase_=0.1					,     lowerCAmelCase_=5_12					,     lowerCAmelCase_=16					,     lowerCAmelCase_=2					,     lowerCAmelCase_=0.02					,     lowerCAmelCase_=3					,     lowerCAmelCase_=4					,     lowerCAmelCase_=None					,     ):





								"""simple docstring"""






								_snake_case     		=	parent
								_snake_case     		=	batch_size
								_snake_case     		=	seq_length
								_snake_case     		=	is_training
								_snake_case     		=	use_token_type_ids
								_snake_case     		=	use_labels
								_snake_case     		=	vocab_size
								_snake_case     		=	hidden_size
								_snake_case     		=	num_hidden_layers
								_snake_case     		=	num_attention_heads
								_snake_case     		=	intermediate_size
								_snake_case     		=	hidden_act
								_snake_case     		=	hidden_dropout_prob
								_snake_case     		=	attention_probs_dropout_prob
								_snake_case     		=	max_position_embeddings
								_snake_case     		=	type_vocab_size
								_snake_case     		=	type_sequence_label_size
								_snake_case     		=	initializer_range
								_snake_case     		=	num_labels
								_snake_case     		=	num_choices
								_snake_case     		=	scope
								_snake_case     		=	self.vocab_size - 1


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






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

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

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

								_snake_case     		=	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					,     )

								_snake_case     		=	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 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     *lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTModel(config=lowerCAmelCase_						)
								model.to(lowerCAmelCase_						)
								model.eval()

								_snake_case     		=	model(lowerCAmelCase_					,     token_type_ids=lowerCAmelCase_					,     head_mask=lowerCAmelCase_						)
								_snake_case     		=	model(lowerCAmelCase_					,     token_type_ids=lowerCAmelCase_						)
								_snake_case     		=	model(lowerCAmelCase_						)

								self.parent.assertEqual(result.last_hidden_state.shape					,     (self.batch_size, self.seq_length, self.hidden_size)						)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     *lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTLMHeadModel(lowerCAmelCase_						)
								model.to(lowerCAmelCase_						)
								model.eval()

								_snake_case     		=	model(lowerCAmelCase_					,     token_type_ids=lowerCAmelCase_					,     labels=lowerCAmelCase_						)
								self.parent.assertEqual(result.loss.shape					,     ()						)
								self.parent.assertEqual(result.logits.shape					,     (self.batch_size, self.seq_length, self.vocab_size)						)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     *lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTDoubleHeadsModel(lowerCAmelCase_						)
								model.to(lowerCAmelCase_						)
								model.eval()

								_snake_case     		=	model(lowerCAmelCase_					,     token_type_ids=lowerCAmelCase_					,     labels=lowerCAmelCase_						)
								self.parent.assertEqual(result.loss.shape					,     ()						)
								self.parent.assertEqual(result.logits.shape					,     (self.batch_size, self.seq_length, self.vocab_size)						)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     *lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	self.num_labels
								_snake_case     		=	OpenAIGPTForSequenceClassification(lowerCAmelCase_						)
								model.to(lowerCAmelCase_						)
								model.eval()

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




							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






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

								return config, inputs_dict


@require_torch
class 		__UpperCAmelCase   (      _lowerCamelCase		,     _lowerCamelCase		,     _lowerCamelCase		,     unittest.TestCase		):
							__lowercase   	= (
							    (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
							    if is_torch_available()
							    else ()
							)
							__lowercase   	= (
							    (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
							)  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
							__lowercase   	= (
							    {
							        """feature-extraction""": OpenAIGPTModel,
							        """text-classification""": OpenAIGPTForSequenceClassification,
							        """text-generation""": OpenAIGPTLMHeadModel,
							        """zero-shot""": OpenAIGPTForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_						):





								"""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 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_=False						):





								"""simple docstring"""






								_snake_case     		=	super()._prepare_for_class(lowerCAmelCase_					,     lowerCAmelCase_					,     return_labels=lowerCAmelCase_						)

								if return_labels:
									if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
										_snake_case     		=	torch.zeros(
										    (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)					,     dtype=torch.long					,     device=lowerCAmelCase_					,     )
										_snake_case     		=	inputs_dict['labels']
										_snake_case     		=	inputs_dict['labels']
										_snake_case     		=	torch.zeros(
										    (self.model_tester.batch_size, self.model_tester.num_choices)					,     dtype=torch.long					,     device=lowerCAmelCase_					,     )
										_snake_case     		=	torch.zeros(
										    self.model_tester.batch_size					,     dtype=torch.long					,     device=lowerCAmelCase_						)
								return inputs_dict


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTModelTester(self						)
								_snake_case     		=	ConfigTester(self					,     config_class=lowerCAmelCase_					,     n_embd=37						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								self.config_tester.run_common_tests()


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_openai_gpt_model(*lowerCAmelCase_						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_lm_head_model(*lowerCAmelCase_						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_double_lm_head_model(*lowerCAmelCase_						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*lowerCAmelCase_						)




							@slow
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






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


@require_torch
class 		__UpperCAmelCase   (      unittest.TestCase		):


							@slow
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTLMHeadModel.from_pretrained('openai-gpt'						)
								model.to(lowerCAmelCase_						)
								_snake_case     		=	torch.tensor([[4_81, 47_35, 5_44]]					,     dtype=torch.long					,     device=lowerCAmelCase_						)  # the president is
								_snake_case     		=	[
								    4_81,
								    47_35,
								    5_44,
								    2_46,
								    9_63,
								    8_70,
								    7_62,
								    2_39,
								    2_44,
								    4_04_77,
								    2_44,
								    2_49,
								    7_19,
								    8_81,
								    4_87,
								    5_44,
								    2_40,
								    2_44,
								    6_03,
								    4_81,
								]  # the president is a very good man. " \n " i\'m sure he is, " said the

								_snake_case     		=	model.generate(lowerCAmelCase_					,     do_sample=lowerCAmelCase_						)
								self.assertListEqual(output_ids[0].tolist()					,     lowerCAmelCase_						)

