'''simple docstring'''




import json
import os
import unittest

from transformers import BartTokenizer, BartTokenizerFast, BatchEncoding
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, require_torch
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin, filter_roberta_detectors




@require_tokenizers
class       __UpperCAmelCase							(							_UpperCamelCase		, unittest.TestCase	):





       '''simple docstring'''



       __lowercase   :   Optional[Any]  					=							BartTokenizer
       __lowercase   :   Dict  					=							BartTokenizerFast
       __lowercase   :   Dict  					=							True
       __lowercase   :   Union[str, Any]  					=							filter_roberta_detectors

       def    __A			( self					)						->	Tuple:
           super().setUp()
           A_      =  [
               '''l''',
               '''o''',
               '''w''',
               '''e''',
               '''r''',
               '''s''',
               '''t''',
               '''i''',
               '''d''',
               '''n''',
               '''\u0120''',
               '''\u0120l''',
               '''\u0120n''',
               '''\u0120lo''',
               '''\u0120low''',
               '''er''',
               '''\u0120lowest''',
               '''\u0120newer''',
               '''\u0120wider''',
               '''<unk>''',
           ]
           A_      =  dict(zip(_SCREAMING_SNAKE_CASE       ,	range(len(_SCREAMING_SNAKE_CASE					)					)					)					)
           A_      =  ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', '''''']
           A_      =  {'''unk_token''': '''<unk>'''}

           A_      =  os.path.join(self.tmpdirname       ,	VOCAB_FILES_NAMES['''vocab_file''']					)
           A_      =  os.path.join(self.tmpdirname       ,	VOCAB_FILES_NAMES['''merges_file''']					)
           with open(self.vocab_file       ,	'''w'''       ,	encoding='''utf-8'''					) as fp:
               fp.write(json.dumps(_SCREAMING_SNAKE_CASE					) + '''\n'''					)
           with open(self.merges_file       ,	'''w'''       ,	encoding='''utf-8'''					) as fp:
               fp.write('''\n'''.join(_SCREAMING_SNAKE_CASE					)					)

       def    __A			( self       ,	**_SCREAMING_SNAKE_CASE					)						->	Optional[int]:
           kwargs.update(self.special_tokens_map					)
           return self.tokenizer_class.from_pretrained(self.tmpdirname       ,	**_SCREAMING_SNAKE_CASE					)

       def    __A			( self       ,	**_SCREAMING_SNAKE_CASE					)						->	Union[str, Any]:
           kwargs.update(self.special_tokens_map					)
           return self.rust_tokenizer_class.from_pretrained(self.tmpdirname       ,	**_SCREAMING_SNAKE_CASE					)

       def    __A			( self       ,	_SCREAMING_SNAKE_CASE					)						->	Optional[int]:
           return "lower newer", "lower newer"

       @cached_property
       def    __A			( self					)						->	List[Any]:
           return BartTokenizer.from_pretrained('''facebook/bart-large'''					)

       @cached_property
       def    __A			( self					)						->	Optional[int]:
           return BartTokenizerFast.from_pretrained('''facebook/bart-large'''					)

       @require_torch
       def    __A			( self					)						->	Tuple:
           A_      =  ['''A long paragraph for summarization.''', '''Another paragraph for summarization.''']
           A_      =  [0, 250, 251, 1_7818, 13, 3_9186, 1938, 4, 2]

           for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
               A_      =  tokenizer(_SCREAMING_SNAKE_CASE       ,	max_length=len(_SCREAMING_SNAKE_CASE					)       ,	padding=_SCREAMING_SNAKE_CASE       ,	return_tensors='''pt'''					)
               self.assertIsInstance(_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE					)

               self.assertEqual((2, 9)       ,	batch.input_ids.shape					)
               self.assertEqual((2, 9)       ,	batch.attention_mask.shape					)
               A_      =  batch.input_ids.tolist()[0]
               self.assertListEqual(_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE					)
               # Test that special tokens are reset

       @require_torch
       def    __A			( self					)						->	Tuple:
           A_      =  ['''A long paragraph for summarization.''', '''Another paragraph for summarization.''']
           for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
               A_      =  tokenizer(_SCREAMING_SNAKE_CASE       ,	padding=_SCREAMING_SNAKE_CASE       ,	return_tensors='''pt'''					)
               # check if input_ids are returned and no labels
               self.assertIn('''input_ids'''       ,	_SCREAMING_SNAKE_CASE					)
               self.assertIn('''attention_mask'''       ,	_SCREAMING_SNAKE_CASE					)
               self.assertNotIn('''labels'''       ,	_SCREAMING_SNAKE_CASE					)
               self.assertNotIn('''decoder_attention_mask'''       ,	_SCREAMING_SNAKE_CASE					)

       @require_torch
       def    __A			( self					)						->	str:
           A_      =  [
               '''Summary of the text.''',
               '''Another summary.''',
           ]
           for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
               A_      =  tokenizer(text_target=_SCREAMING_SNAKE_CASE       ,	max_length=32       ,	padding='''max_length'''       ,	return_tensors='''pt'''					)
               self.assertEqual(32       ,	targets['''input_ids'''].shape[1]					)

       @require_torch
       def    __A			( self					)						->	List[str]:
           for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
               A_      =  tokenizer(
                   ['''I am a small frog''' * 1024, '''I am a small frog''']       ,	padding=_SCREAMING_SNAKE_CASE       ,	truncation=_SCREAMING_SNAKE_CASE       ,	return_tensors='''pt'''					)
               self.assertIsInstance(_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE					)
               self.assertEqual(batch.input_ids.shape       ,	(2, 1024)					)

       @require_torch
       def    __A			( self					)						->	int:
           A_      =  ['''A long paragraph for summarization.''']
           A_      =  [
               '''Summary of the text.''',
           ]
           for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
               A_      =  tokenizer(_SCREAMING_SNAKE_CASE       ,	return_tensors='''pt'''					)
               A_      =  tokenizer(text_target=_SCREAMING_SNAKE_CASE       ,	return_tensors='''pt'''					)
               A_      =  inputs['''input_ids''']
               A_      =  targets['''input_ids''']
               self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item()					)
               self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item()					)
               self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item()					)
               self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item()					)

       def    __A			( self					)						->	Union[str, Any]:
           pass

       def    __A			( self					)						->	Tuple:
           for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
               with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})'''					):
                   A_      =  self.rust_tokenizer_class.from_pretrained(_SCREAMING_SNAKE_CASE       ,	**_SCREAMING_SNAKE_CASE					)
                   A_      =  self.tokenizer_class.from_pretrained(_SCREAMING_SNAKE_CASE       ,	**_SCREAMING_SNAKE_CASE					)
                   A_      =  '''A, <mask> AllenNLP sentence.'''
                   A_      =  tokenizer_r.encode_plus(_SCREAMING_SNAKE_CASE       ,	add_special_tokens=_SCREAMING_SNAKE_CASE       ,	return_token_type_ids=_SCREAMING_SNAKE_CASE					)
                   A_      =  tokenizer_p.encode_plus(_SCREAMING_SNAKE_CASE       ,	add_special_tokens=_SCREAMING_SNAKE_CASE       ,	return_token_type_ids=_SCREAMING_SNAKE_CASE					)

                   # token_type_ids should put 0 everywhere
                   self.assertEqual(sum(tokens_r['''token_type_ids''']					)       ,	sum(tokens_p['''token_type_ids''']					)					)

                   # attention_mask should put 1 everywhere, so sum over length should be 1
                   self.assertEqual(
                       sum(tokens_r['''attention_mask''']					) / len(tokens_r['''attention_mask''']					)       ,	sum(tokens_p['''attention_mask''']					) / len(tokens_p['''attention_mask''']					)       ,	)

                   A_      =  tokenizer_r.convert_ids_to_tokens(tokens_r['''input_ids''']					)
                   A_      =  tokenizer_p.convert_ids_to_tokens(tokens_p['''input_ids''']					)

                   # Rust correctly handles the space before the mask while python doesnt
                   self.assertSequenceEqual(tokens_p['''input_ids''']       ,	[0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2]					)
                   self.assertSequenceEqual(tokens_r['''input_ids''']       ,	[0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2]					)

                   self.assertSequenceEqual(
                       _SCREAMING_SNAKE_CASE       ,	['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>''']					)
                   self.assertSequenceEqual(
                       _SCREAMING_SNAKE_CASE       ,	['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>''']					)







'''simple docstring'''




from __future__ import annotations

import unittest

from transformers import OpenAIGPTConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers.models.openai.modeling_tf_openai import (
      TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFOpenAIGPTDoubleHeadsModel,
      TFOpenAIGPTForSequenceClassification,
      TFOpenAIGPTLMHeadModel,
      TFOpenAIGPTModel,
  )




class       __UpperCAmelCase							:





       '''simple docstring'''



       def __init__( self       ,	_SCREAMING_SNAKE_CASE       ,	)						->	Any:
           A_      =  parent
           A_      =  13
           A_      =  7
           A_      =  True
           A_      =  True
           A_      =  True
           A_      =  True
           A_      =  True
           A_      =  99
           A_      =  32
           A_      =  2
           A_      =  4
           A_      =  37
           A_      =  '''gelu'''
           A_      =  0.1
           A_      =  0.1
           A_      =  512
           A_      =  16
           A_      =  2
           A_      =  0.02
           A_      =  3
           A_      =  4
           A_      =  None
           A_      =  self.vocab_size - 1

       def    __A			( self					)						->	Union[str, Any]:
           A_      =  ids_tensor([self.batch_size, self.seq_length]       ,	self.vocab_size					)

           A_      =  None
           if self.use_input_mask:
               A_      =  random_attention_mask([self.batch_size, self.seq_length]					)

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

           A_      =  None
           if self.use_mc_token_ids:
               A_      =  ids_tensor([self.batch_size, self.num_choices]       ,	self.seq_length					)

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

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

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

           return (
               config,
               input_ids,
               input_mask,
               head_mask,
               token_type_ids,
               mc_token_ids,
               sequence_labels,
               token_labels,
               choice_labels,
           )

       def    __A			( self       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	*_SCREAMING_SNAKE_CASE					)						->	Optional[int]:
           A_      =  TFOpenAIGPTModel(config=_SCREAMING_SNAKE_CASE					)
           A_      =  {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
           A_      =  model(_SCREAMING_SNAKE_CASE					)

           A_      =  [input_ids, input_mask]
           A_      =  model(_SCREAMING_SNAKE_CASE					)

           A_      =  model(_SCREAMING_SNAKE_CASE					)

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

       def    __A			( self       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	*_SCREAMING_SNAKE_CASE					)						->	Dict:
           A_      =  TFOpenAIGPTLMHeadModel(config=_SCREAMING_SNAKE_CASE					)
           A_      =  {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
           A_      =  model(_SCREAMING_SNAKE_CASE					)
           self.parent.assertEqual(result.logits.shape       ,	(self.batch_size, self.seq_length, self.vocab_size)					)

       def    __A			( self       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	*_SCREAMING_SNAKE_CASE					)						->	Optional[Any]:
           A_      =  TFOpenAIGPTDoubleHeadsModel(config=_SCREAMING_SNAKE_CASE					)

           A_      =  tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE       ,	1					)       ,	(1, self.num_choices, 1)					)
           A_      =  tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE       ,	1					)       ,	(1, self.num_choices, 1)					)
           A_      =  tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE       ,	1					)       ,	(1, self.num_choices, 1)					)

           A_      =  {
               '''input_ids''': multiple_choice_inputs_ids,
               '''mc_token_ids''': mc_token_ids,
               '''attention_mask''': multiple_choice_input_mask,
               '''token_type_ids''': multiple_choice_token_type_ids,
           }
           A_      =  model(_SCREAMING_SNAKE_CASE					)
           self.parent.assertEqual(
               result.logits.shape       ,	(self.batch_size, self.num_choices, self.seq_length, self.vocab_size)					)
           self.parent.assertEqual(result.mc_logits.shape       ,	(self.batch_size, self.num_choices)					)

       def    __A			( self       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	*_SCREAMING_SNAKE_CASE					)						->	Dict:
           A_      =  self.num_labels
           A_      =  ids_tensor([self.batch_size]       ,	self.type_sequence_label_size					)
           A_      =  {
               '''input_ids''': input_ids,
               '''attention_mask''': input_mask,
               '''token_type_ids''': token_type_ids,
               '''labels''': sequence_labels,
           }
           A_      =  TFOpenAIGPTForSequenceClassification(_SCREAMING_SNAKE_CASE					)
           A_      =  model(_SCREAMING_SNAKE_CASE					)
           self.parent.assertEqual(result.logits.shape       ,	(self.batch_size, self.num_labels)					)

       def    __A			( self					)						->	Union[str, Any]:
           A_      =  self.prepare_config_and_inputs()

           (
               (
               A_
           )  ,(
               A_
           )  ,(
               A_
           )  ,(
               A_
           )  ,(
               A_
           )  ,(
               A_
           )  ,(
               A_
           )  ,(
               A_
           )  ,(
               A_
           )  ,
           )      =  config_and_inputs

           A_      =  {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
           return config, inputs_dict




@require_tf
class       __UpperCAmelCase							(							_UpperCamelCase		, _UpperCamelCase		, unittest.TestCase	):





       '''simple docstring'''



       __lowercase   :   Dict  					=							(
           (TFOpenAIGPTModel, TFOpenAIGPTLMHeadModel, TFOpenAIGPTDoubleHeadsModel, TFOpenAIGPTForSequenceClassification)
           if is_tf_available()
           else ()
       )
       __lowercase   :   List[str]  					=							(
           (TFOpenAIGPTLMHeadModel,) if is_tf_available() else ()
       )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
       __lowercase   :   List[str]  					=							(
           {
               'feature-extraction': TFOpenAIGPTModel,
               'text-classification': TFOpenAIGPTForSequenceClassification,
               'text-generation': TFOpenAIGPTLMHeadModel,
               'zero-shot': TFOpenAIGPTForSequenceClassification,
           }
           if is_tf_available()
           else {}
       )
       __lowercase   :   Dict  					=							False
       __lowercase   :   Optional[int]  					=							False

       def    __A			( self       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_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    __A			( self					)						->	Any:
           A_      =  TFOpenAIGPTModelTester(self					)
           A_      =  ConfigTester(self       ,	config_class=_SCREAMING_SNAKE_CASE       ,	n_embd=37					)

       def    __A			( self					)						->	List[Any]:
           self.config_tester.run_common_tests()

       def    __A			( self					)						->	Dict:
           A_      =  self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_openai_gpt_model(*_SCREAMING_SNAKE_CASE					)

       def    __A			( self					)						->	Any:
           A_      =  self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_openai_gpt_lm_head(*_SCREAMING_SNAKE_CASE					)

       def    __A			( self					)						->	Tuple:
           A_      =  self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_openai_gpt_double_head(*_SCREAMING_SNAKE_CASE					)

       def    __A			( self					)						->	List[str]:
           A_      =  self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*_SCREAMING_SNAKE_CASE					)

       @slow
       def    __A			( self					)						->	Union[str, Any]:
           for model_name in TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               A_      =  TFOpenAIGPTModel.from_pretrained(_SCREAMING_SNAKE_CASE					)
               self.assertIsNotNone(_SCREAMING_SNAKE_CASE					)




@require_tf
class       __UpperCAmelCase							(							unittest.TestCase	):





       '''simple docstring'''



       @slow
       def    __A			( self					)						->	List[str]:
           A_      =  TFOpenAIGPTLMHeadModel.from_pretrained('''openai-gpt'''					)
           A_      =  tf.convert_to_tensor([[481, 4735, 544]]       ,	dtype=tf.intaa					)  # the president is
           A_      =  [
               481,
               4735,
               544,
               246,
               963,
               870,
               762,
               239,
               244,
               4_0477,
               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

           A_      =  model.generate(_SCREAMING_SNAKE_CASE       ,	do_sample=_SCREAMING_SNAKE_CASE					)
           self.assertListEqual(output_ids[0].numpy().tolist()       ,	_SCREAMING_SNAKE_CASE					)






