



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__:

					"""simple docstring"""






					def __init__(				self   :      Optional[int] ,  SCREAMING_SNAKE_CASE   :      Tuple ,  SCREAMING_SNAKE_CASE   :      Union[str, Any]=13 ,  SCREAMING_SNAKE_CASE   :      List[Any]=7 ,  SCREAMING_SNAKE_CASE   :      List[Any]=True ,  SCREAMING_SNAKE_CASE   :      Union[str, Any]=True ,  SCREAMING_SNAKE_CASE   :      Tuple=True ,  SCREAMING_SNAKE_CASE   :      Dict=99 ,  SCREAMING_SNAKE_CASE   :      List[Any]=32 ,  SCREAMING_SNAKE_CASE   :      List[Any]=5 ,  SCREAMING_SNAKE_CASE   :      Union[str, Any]=4 ,  SCREAMING_SNAKE_CASE   :      int=37 ,  SCREAMING_SNAKE_CASE   :      Optional[Any]="gelu" ,  SCREAMING_SNAKE_CASE   :      int=0.1 ,  SCREAMING_SNAKE_CASE   :      Tuple=0.1 ,  SCREAMING_SNAKE_CASE   :      Tuple=512 ,  SCREAMING_SNAKE_CASE   :      List[Any]=16 ,  SCREAMING_SNAKE_CASE   :      int=2 ,  SCREAMING_SNAKE_CASE   :      Any=0.02 ,  SCREAMING_SNAKE_CASE   :      Union[str, Any]=3 ,  SCREAMING_SNAKE_CASE   :      Dict=4 ,  SCREAMING_SNAKE_CASE   :      Optional[Any]=None ,  ):
									lowercase__	:       Tuple						=	parent
									lowercase__	:       Optional[int]						=	batch_size
									lowercase__	:       Any						=	seq_length
									lowercase__	:       int						=	is_training
									lowercase__	:       Optional[int]						=	use_token_type_ids
									lowercase__	:       int						=	use_labels
									lowercase__	:       Optional[Any]						=	vocab_size
									lowercase__	:       Tuple						=	hidden_size
									lowercase__	:       Union[str, Any]						=	num_hidden_layers
									lowercase__	:       List[Any]						=	num_attention_heads
									lowercase__	:       int						=	intermediate_size
									lowercase__	:       Union[str, Any]						=	hidden_act
									lowercase__	:       List[str]						=	hidden_dropout_prob
									lowercase__	:       int						=	attention_probs_dropout_prob
									lowercase__	:       int						=	max_position_embeddings
									lowercase__	:       Tuple						=	type_vocab_size
									lowercase__	:       int						=	type_sequence_label_size
									lowercase__	:       Tuple						=	initializer_range
									lowercase__	:       Optional[int]						=	num_labels
									lowercase__	:       List[Any]						=	num_choices
									lowercase__	:       Any						=	scope
									lowercase__	:       Tuple						=	self.vocab_size - 1







					def 					snake_case	(				self   :      Any	):
									lowercase__	:       Any						=	ids_tensor([self.batch_size, self.seq_length] ,  self.vocab_size	)

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

									lowercase__	:       Any						=	None
									lowercase__	:       int						=	None
									lowercase__	:       Optional[int]						=	None
									if self.use_labels:
													lowercase__	:       Optional[int]						=	ids_tensor([self.batch_size] ,  self.type_sequence_label_size	)
													lowercase__	:       Optional[int]						=	ids_tensor([self.batch_size, self.seq_length] ,  self.num_labels	)
													lowercase__	:       Optional[Any]						=	ids_tensor([self.batch_size] ,  self.num_choices	)

									lowercase__	:       Any						=	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__	:       Dict						=	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 					snake_case	(				self   :      Tuple ,  SCREAMING_SNAKE_CASE   :      Any ,  SCREAMING_SNAKE_CASE   :      int ,  SCREAMING_SNAKE_CASE   :      Union[str, Any] ,  SCREAMING_SNAKE_CASE   :      Tuple ,  *SCREAMING_SNAKE_CASE   :      Optional[int]	):
									lowercase__	:       str						=	OpenAIGPTModel(config=_lowercase	)
									model.to(_lowercase	)
									model.eval()

									lowercase__	:       Dict						=	model(_lowercase ,  token_type_ids=_lowercase ,  head_mask=_lowercase	)
									lowercase__	:       List[Any]						=	model(_lowercase ,  token_type_ids=_lowercase	)
									lowercase__	:       str						=	model(_lowercase	)

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







					def 					snake_case	(				self   :      Optional[int] ,  SCREAMING_SNAKE_CASE   :      List[str] ,  SCREAMING_SNAKE_CASE   :      List[str] ,  SCREAMING_SNAKE_CASE   :      int ,  SCREAMING_SNAKE_CASE   :      Any ,  *SCREAMING_SNAKE_CASE   :      Tuple	):
									lowercase__	:       Optional[int]						=	OpenAIGPTLMHeadModel(_lowercase	)
									model.to(_lowercase	)
									model.eval()

									lowercase__	:       Tuple						=	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 					snake_case	(				self   :      Dict ,  SCREAMING_SNAKE_CASE   :      Any ,  SCREAMING_SNAKE_CASE   :      Dict ,  SCREAMING_SNAKE_CASE   :      str ,  SCREAMING_SNAKE_CASE   :      Tuple ,  *SCREAMING_SNAKE_CASE   :      Dict	):
									lowercase__	:       int						=	OpenAIGPTDoubleHeadsModel(_lowercase	)
									model.to(_lowercase	)
									model.eval()

									lowercase__	:       str						=	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 					snake_case	(				self   :      Optional[int] ,  SCREAMING_SNAKE_CASE   :      List[Any] ,  SCREAMING_SNAKE_CASE   :      Tuple ,  SCREAMING_SNAKE_CASE   :      Any ,  SCREAMING_SNAKE_CASE   :      int ,  *SCREAMING_SNAKE_CASE   :      int	):
									lowercase__	:       Union[str, Any]						=	self.num_labels
									lowercase__	:       List[str]						=	OpenAIGPTForSequenceClassification(_lowercase	)
									model.to(_lowercase	)
									model.eval()

									lowercase__	:       List[Any]						=	ids_tensor([self.batch_size] ,  self.type_sequence_label_size	)
									lowercase__	:       Union[str, Any]						=	model(_lowercase ,  token_type_ids=_lowercase ,  labels=_lowercase	)
									self.parent.assertEqual(result.logits.shape ,  (self.batch_size, self.num_labels)	)







					def 					snake_case	(				self   :      List[Any]	):
									lowercase__	:       Dict						=	self.prepare_config_and_inputs()
									(
									    (
									    lowercase__    
									)				,				(
									    lowercase__    
									)				,				(
									    lowercase__    
									)				,				(
									    lowercase__    
									)				,				(
									    lowercase__    
									)				,				(
									    lowercase__    
									)				,				(
									    lowercase__    
									)				,				    
									)	:       List[str]						=	config_and_inputs
									lowercase__	:       Optional[Any]						=	{
									    "input_ids": input_ids,
									    "token_type_ids": token_type_ids,
									    "head_mask": head_mask,
									}

									return config, inputs_dict






@require_torch
class  snake_case__(lowercase_							,     lowercase_							,     lowercase_							,     unittest.TestCase     ):

					"""simple docstring"""






					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 					snake_case	(				self   :      Any ,  SCREAMING_SNAKE_CASE   :      Tuple ,  SCREAMING_SNAKE_CASE   :      int ,  SCREAMING_SNAKE_CASE   :      Any ,  SCREAMING_SNAKE_CASE   :      str ,  SCREAMING_SNAKE_CASE   :      Union[str, Any]	):
									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 					snake_case	(				self   :      Tuple ,  SCREAMING_SNAKE_CASE   :      Optional[Any] ,  SCREAMING_SNAKE_CASE   :      int ,  SCREAMING_SNAKE_CASE   :      List[str]=False	):
									lowercase__	:       Optional[int]						=	super()._prepare_for_class(_lowercase ,  _lowercase ,  return_labels=_lowercase	)

									if return_labels:
													if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
																	lowercase__	:       str						=	torch.zeros(
																	    (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) ,  dtype=torch.long ,  device=_lowercase ,  )
																	lowercase__	:       int						=	inputs_dict["labels"]
																	lowercase__	:       int						=	inputs_dict["labels"]
																	lowercase__	:       Optional[Any]						=	torch.zeros(
																	    (self.model_tester.batch_size, self.model_tester.num_choices) ,  dtype=torch.long ,  device=_lowercase ,  )
																	lowercase__	:       Optional[Any]						=	torch.zeros(
																	    self.model_tester.batch_size ,  dtype=torch.long ,  device=_lowercase	)
									return inputs_dict







					def 					snake_case	(				self   :      Optional[int]	):
									lowercase__	:       Tuple						=	OpenAIGPTModelTester(self	)
									lowercase__	:       Union[str, Any]						=	ConfigTester(self ,  config_class=_lowercase ,  n_embd=37	)







					def 					snake_case	(				self   :      Optional[Any]	):
									self.config_tester.run_common_tests()







					def 					snake_case	(				self   :      Tuple	):
									lowercase__	:       Tuple						=	self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_openai_gpt_model(*_lowercase	)







					def 					snake_case	(				self   :      str	):
									lowercase__	:       Tuple						=	self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_lm_head_model(*_lowercase	)







					def 					snake_case	(				self   :      Union[str, Any]	):
									lowercase__	:       List[str]						=	self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_double_lm_head_model(*_lowercase	)







					def 					snake_case	(				self   :      str	):
									lowercase__	:       Optional[int]						=	self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*_lowercase	)







					@slow
					def 					snake_case	(				self   :      str	):
									for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													lowercase__	:       str						=	OpenAIGPTModel.from_pretrained(_lowercase	)
													self.assertIsNotNone(_lowercase	)






@require_torch
class  snake_case__(unittest.TestCase     ):

					"""simple docstring"""






					@slow
					def 					snake_case	(				self   :      str	):
									lowercase__	:       Dict						=	OpenAIGPTLMHeadModel.from_pretrained("openai-gpt"	)
									model.to(_lowercase	)
									lowercase__	:       Tuple						=	torch.tensor([[481, 4_735, 544]] ,  dtype=torch.long ,  device=_lowercase	)  # the president is
									lowercase__	:       Any						=	[
									    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

									lowercase__	:       List[Any]						=	model.generate(_lowercase ,  do_sample=_lowercase	)
									self.assertListEqual(output_ids[0].tolist() ,  _lowercase	)







'''simple docstring'''

import json
from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers, processors

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bart import BartTokenizer


SCREAMING_SNAKE_CASE							:				int     	=			logging.get_logger(__name__)


SCREAMING_SNAKE_CASE							:				Dict     	=			{"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}

# See all BART models at https://huggingface.co/models?filter=bart
SCREAMING_SNAKE_CASE							:				str     	=			{
    "vocab_file": {
        "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json",
        "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json",
        "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json",
        "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json",
        "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json",
        "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json",
    },
    "merges_file": {
        "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt",
        "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt",
        "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt",
        "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt",
        "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt",
        "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt",
    },
    "tokenizer_file": {
        "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json",
        "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json",
        "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json",
        "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json",
        "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json",
        "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json",
    },
}

SCREAMING_SNAKE_CASE							:				Union[str, Any]     	=			{
    "facebook/bart-base": 1024,
    "facebook/bart-large": 1024,
    "facebook/bart-large-mnli": 1024,
    "facebook/bart-large-cnn": 1024,
    "facebook/bart-large-xsum": 1024,
    "yjernite/bart_eli5": 1024,
}






class    snake_case     (      lowercase_		):






				"""simple docstring"""
				_a    	=     VOCAB_FILES_NAMES
				_a    	=     PRETRAINED_VOCAB_FILES_MAP
				_a    	=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				_a    	=     ["""input_ids""", """attention_mask"""]
				_a    	=     BartTokenizer



				def __init__(    self,     _lowercase=None,     _lowercase=None,     _lowercase=None,     _lowercase="replace",     _lowercase="<s>",     _lowercase="</s>",     _lowercase="</s>",     _lowercase="<s>",     _lowercase="<unk>",     _lowercase="<pad>",     _lowercase="<mask>",     _lowercase=False,     _lowercase=True,     **_lowercase,     )     ->							Dict:
											super().__init__(
											    _lowercase,     _lowercase,     tokenizer_file=_lowercase,     errors=_lowercase,     bos_token=_lowercase,     eos_token=_lowercase,     sep_token=_lowercase,     cls_token=_lowercase,     unk_token=_lowercase,     pad_token=_lowercase,     mask_token=_lowercase,     add_prefix_space=_lowercase,     trim_offsets=_lowercase,     **_lowercase,     )

											SCREAMING_SNAKE_CASE_				=				json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()       )
											if pre_tok_state.get('add_prefix_space',     _lowercase       ) != add_prefix_space:
																		SCREAMING_SNAKE_CASE_				=				getattr(_lowercase,     pre_tok_state.pop('type'       )       )
																		SCREAMING_SNAKE_CASE_				=				add_prefix_space
																		SCREAMING_SNAKE_CASE_				=				pre_tok_class(**_lowercase       )

											SCREAMING_SNAKE_CASE_				=				add_prefix_space

											# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
											SCREAMING_SNAKE_CASE_				=				'post_processor'
											SCREAMING_SNAKE_CASE_				=				getattr(self.backend_tokenizer,     _lowercase,     _lowercase       )
											if tokenizer_component_instance:
																		SCREAMING_SNAKE_CASE_				=				json.loads(tokenizer_component_instance.__getstate__()       )

																		# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
																		if "sep" in state:
																									SCREAMING_SNAKE_CASE_				=				tuple(state['sep']       )
																		if "cls" in state:
																									SCREAMING_SNAKE_CASE_				=				tuple(state['cls']       )

																		SCREAMING_SNAKE_CASE_				=				False

																		if state.get('add_prefix_space',     _lowercase       ) != add_prefix_space:
																									SCREAMING_SNAKE_CASE_				=				add_prefix_space
																									SCREAMING_SNAKE_CASE_				=				True

																		if state.get('trim_offsets',     _lowercase       ) != trim_offsets:
																									SCREAMING_SNAKE_CASE_				=				trim_offsets
																									SCREAMING_SNAKE_CASE_				=				True

																		if changes_to_apply:
																									SCREAMING_SNAKE_CASE_				=				getattr(_lowercase,     state.pop('type'       )       )
																									SCREAMING_SNAKE_CASE_				=				component_class(**_lowercase       )
																									setattr(self.backend_tokenizer,     _lowercase,     _lowercase       )



				@property
				def   a__					(    self       )     ->							str:
											if self._mask_token is None:
																		if self.verbose:
																									logger.error('Using mask_token, but it is not set yet.'       )
																		return None
											return str(self._mask_token       )



				@mask_token.setter
				def   a__					(    self,     _lowercase       )     ->							Dict:
											SCREAMING_SNAKE_CASE_				=				AddedToken(_lowercase,     lstrip=_lowercase,     rstrip=_lowercase       ) if isinstance(_lowercase,     _lowercase       ) else value
											SCREAMING_SNAKE_CASE_				=				value



				def   a__					(    self,     *_lowercase,     **_lowercase       )     ->							BatchEncoding:
											SCREAMING_SNAKE_CASE_				=				kwargs.get('is_split_into_words',     _lowercase       )

											if is_split_into_words and not self.add_prefix_space:
																		raise ValueError(
																		    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
																		    'to use it with pretokenized inputs.'       )

											return super()._batch_encode_plus(*_lowercase,     **_lowercase       )



				def   a__					(    self,     *_lowercase,     **_lowercase       )     ->							BatchEncoding:
											SCREAMING_SNAKE_CASE_				=				kwargs.get('is_split_into_words',     _lowercase       )

											if is_split_into_words and not self.add_prefix_space:
																		raise ValueError(
																		    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
																		    'to use it with pretokenized inputs.'       )

											return super()._encode_plus(*_lowercase,     **_lowercase       )



				def   a__					(    self,     _lowercase,     _lowercase = None       )     ->							Tuple[str]:
											SCREAMING_SNAKE_CASE_				=				self._tokenizer.model.save(_lowercase,     name=_lowercase       )
											return tuple(_lowercase       )



				def   a__					(    self,     _lowercase,     _lowercase=None       )     ->							Optional[Any]:
											SCREAMING_SNAKE_CASE_				=				[self.bos_token_id] + token_ids_a + [self.eos_token_id]
											if token_ids_a is None:
																		return output

											return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]





				def   a__					(    self,     _lowercase,     _lowercase = None       )     ->							List[int]:
											SCREAMING_SNAKE_CASE_				=				[self.sep_token_id]
											SCREAMING_SNAKE_CASE_				=				[self.cls_token_id]

											if token_ids_a is None:
																		return len(cls + token_ids_a + sep       ) * [0]
											return len(cls + token_ids_a + sep + sep + token_ids_a + sep       ) * [0]





