





from __future__ import annotations

import unittest

from transformers import MobileBertConfig, is_tf_available
from transformers.models.auto import get_values
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 import (
		    TF_MODEL_FOR_PRETRAINING_MAPPING,
		    TFMobileBertForMaskedLM,
		    TFMobileBertForMultipleChoice,
		    TFMobileBertForNextSentencePrediction,
		    TFMobileBertForPreTraining,
		    TFMobileBertForQuestionAnswering,
		    TFMobileBertForSequenceClassification,
		    TFMobileBertForTokenClassification,
		    TFMobileBertModel,
		)

@require_tf
class        __SCREAMING_SNAKE_CASE					(     _a   ,		_a   ,		unittest.TestCase       ):
							snake_case     :      List[Any]						     =       (
							    (
							        TFMobileBertModel,
							        TFMobileBertForMaskedLM,
							        TFMobileBertForNextSentencePrediction,
							        TFMobileBertForPreTraining,
							        TFMobileBertForQuestionAnswering,
							        TFMobileBertForSequenceClassification,
							        TFMobileBertForTokenClassification,
							        TFMobileBertForMultipleChoice,
							    )
							    if is_tf_available()
							    else ()
							)
							snake_case     :      Dict						     =       (
							    {
							        """feature-extraction""": TFMobileBertModel,
							        """fill-mask""": TFMobileBertForMaskedLM,
							        """question-answering""": TFMobileBertForQuestionAnswering,
							        """text-classification""": TFMobileBertForSequenceClassification,
							        """token-classification""": TFMobileBertForTokenClassification,
							        """zero-shot""": TFMobileBertForSequenceClassification,
							    }
							    if is_tf_available()
							    else {}
							)
							snake_case     :      Any						     =       False
							snake_case     :      int						     =       False






							def 				_lowerCamelCase		(						self  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase=False  ):
														UpperCamelCase__				     =			super()._prepare_for_class(__lowerCAmelCase  , __lowerCAmelCase  , return_labels=__lowerCAmelCase  )

														if return_labels:
																					if model_class in get_values(__lowerCAmelCase  ):
																												UpperCamelCase__				     =			tf.zeros(self.model_tester.batch_size  , dtype=tf.intaa  )

														return inputs_dict

							class        __SCREAMING_SNAKE_CASE					(     _a       ):






														def __init__(						self  , __lowerCAmelCase  , __lowerCAmelCase=13  , __lowerCAmelCase=7  , __lowerCAmelCase=True  , __lowerCAmelCase=True  , __lowerCAmelCase=True  , __lowerCAmelCase=True  , __lowerCAmelCase=99  , __lowerCAmelCase=32  , __lowerCAmelCase=32  , __lowerCAmelCase=2  , __lowerCAmelCase=4  , __lowerCAmelCase=37  , __lowerCAmelCase="gelu"  , __lowerCAmelCase=0.1  , __lowerCAmelCase=0.1  , __lowerCAmelCase=512  , __lowerCAmelCase=16  , __lowerCAmelCase=2  , __lowerCAmelCase=0.02  , __lowerCAmelCase=3  , __lowerCAmelCase=4  , __lowerCAmelCase=None  , ):
																					UpperCamelCase__				     =			parent
																					UpperCamelCase__				     =			batch_size
																					UpperCamelCase__				     =			seq_length
																					UpperCamelCase__				     =			is_training
																					UpperCamelCase__				     =			use_input_mask
																					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__				     =			embedding_size






														def 				_lowerCamelCase		(						self  ):
																					UpperCamelCase__				     =			ids_tensor([self.batch_size, self.seq_length]  , self.vocab_size  )

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

																					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__				     =			MobileBertConfig(
																					    vocab_size=self.vocab_size  , hidden_size=self.hidden_size  , num_hidden_layers=self.num_hidden_layers  , num_attention_heads=self.num_attention_heads  , intermediate_size=self.intermediate_size  , hidden_act=self.hidden_act  , hidden_dropout_prob=self.hidden_dropout_prob  , attention_probs_dropout_prob=self.attention_probs_dropout_prob  , max_position_embeddings=self.max_position_embeddings  , type_vocab_size=self.type_vocab_size  , initializer_range=self.initializer_range  , embedding_size=self.embedding_size  , )

																					return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels






														def 				_lowerCamelCase		(						self  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  ):
																					UpperCamelCase__				     =			TFMobileBertModel(config=__lowerCAmelCase  )
																					UpperCamelCase__				     =			{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
																					UpperCamelCase__				     =			model(__lowerCAmelCase  )

																					UpperCamelCase__				     =			[input_ids, input_mask]
																					UpperCamelCase__				     =			model(__lowerCAmelCase  )

																					UpperCamelCase__				     =			model(__lowerCAmelCase  )

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






														def 				_lowerCamelCase		(						self  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  ):
																					UpperCamelCase__				     =			TFMobileBertForMaskedLM(config=__lowerCAmelCase  )
																					UpperCamelCase__				     =			{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
																					UpperCamelCase__				     =			model(__lowerCAmelCase  )
																					self.parent.assertEqual(result.logits.shape  , (self.batch_size, self.seq_length, self.vocab_size)  )






														def 				_lowerCamelCase		(						self  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  ):
																					UpperCamelCase__				     =			TFMobileBertForNextSentencePrediction(config=__lowerCAmelCase  )
																					UpperCamelCase__				     =			{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
																					UpperCamelCase__				     =			model(__lowerCAmelCase  )
																					self.parent.assertEqual(result.logits.shape  , (self.batch_size, 2)  )






														def 				_lowerCamelCase		(						self  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  ):
																					UpperCamelCase__				     =			TFMobileBertForPreTraining(config=__lowerCAmelCase  )
																					UpperCamelCase__				     =			{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
																					UpperCamelCase__				     =			model(__lowerCAmelCase  )
																					self.parent.assertEqual(
																					    result.prediction_logits.shape  , (self.batch_size, self.seq_length, self.vocab_size)  )
																					self.parent.assertEqual(result.seq_relationship_logits.shape  , (self.batch_size, 2)  )






														def 				_lowerCamelCase		(						self  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  ):
																					UpperCamelCase__				     =			self.num_labels
																					UpperCamelCase__				     =			TFMobileBertForSequenceClassification(config=__lowerCAmelCase  )
																					UpperCamelCase__				     =			{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
																					UpperCamelCase__				     =			model(__lowerCAmelCase  )
																					self.parent.assertEqual(result.logits.shape  , (self.batch_size, self.num_labels)  )






														def 				_lowerCamelCase		(						self  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  ):
																					UpperCamelCase__				     =			self.num_choices
																					UpperCamelCase__				     =			TFMobileBertForMultipleChoice(config=__lowerCAmelCase  )
																					UpperCamelCase__				     =			tf.tile(tf.expand_dims(__lowerCAmelCase  , 1  )  , (1, self.num_choices, 1)  )
																					UpperCamelCase__				     =			tf.tile(tf.expand_dims(__lowerCAmelCase  , 1  )  , (1, self.num_choices, 1)  )
																					UpperCamelCase__				     =			tf.tile(tf.expand_dims(__lowerCAmelCase  , 1  )  , (1, self.num_choices, 1)  )
																					UpperCamelCase__				     =			{
																					    """input_ids""": multiple_choice_inputs_ids,
																					    """attention_mask""": multiple_choice_input_mask,
																					    """token_type_ids""": multiple_choice_token_type_ids,
																					}
																					UpperCamelCase__				     =			model(__lowerCAmelCase  )
																					self.parent.assertEqual(result.logits.shape  , (self.batch_size, self.num_choices)  )






														def 				_lowerCamelCase		(						self  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  ):
																					UpperCamelCase__				     =			self.num_labels
																					UpperCamelCase__				     =			TFMobileBertForTokenClassification(config=__lowerCAmelCase  )
																					UpperCamelCase__				     =			{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
																					UpperCamelCase__				     =			model(__lowerCAmelCase  )
																					self.parent.assertEqual(result.logits.shape  , (self.batch_size, self.seq_length, self.num_labels)  )






														def 				_lowerCamelCase		(						self  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  ):
																					UpperCamelCase__				     =			TFMobileBertForQuestionAnswering(config=__lowerCAmelCase  )
																					UpperCamelCase__				     =			{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
																					UpperCamelCase__				     =			model(__lowerCAmelCase  )
																					self.parent.assertEqual(result.start_logits.shape  , (self.batch_size, self.seq_length)  )
																					self.parent.assertEqual(result.end_logits.shape  , (self.batch_size, self.seq_length)  )







														def 				_lowerCamelCase		(						self  ):
																					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, """attention_mask""": input_mask}
																					return config, inputs_dict






							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			TFMobileBertModelTest.TFMobileBertModelTester(self  )
														UpperCamelCase__				     =			ConfigTester(self  , config_class=__lowerCAmelCase  , hidden_size=37  )






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






							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_mobilebert_model(*__lowerCAmelCase  )






							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_mobilebert_for_masked_lm(*__lowerCAmelCase  )






							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__lowerCAmelCase  )






							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__lowerCAmelCase  )






							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_mobilebert_for_pretraining(*__lowerCAmelCase  )






							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_mobilebert_for_question_answering(*__lowerCAmelCase  )






							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__lowerCAmelCase  )






							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_mobilebert_for_token_classification(*__lowerCAmelCase  )







							@slow
							def 				_lowerCamelCase		(						self  ):
														# for model_name in TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														for model_name in ["google/mobilebert-uncased"]:
																					UpperCamelCase__				     =			TFMobileBertModel.from_pretrained(__lowerCAmelCase  )
																					self.assertIsNotNone(__lowerCAmelCase  )






@require_tf
class        __SCREAMING_SNAKE_CASE					(     unittest.TestCase       ):






							@slow
							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			TFMobileBertForPreTraining.from_pretrained("""google/mobilebert-uncased"""  )
														UpperCamelCase__				     =			tf.constant([[0, 1, 2, 3, 4, 5]]  )
														UpperCamelCase__				     =			model(__lowerCAmelCase  )[0]

														UpperCamelCase__				     =			[1, 6, 30522]
														self.assertEqual(output.shape  , __lowerCAmelCase  )

														UpperCamelCase__				     =			tf.constant(
														    [
														        [
														            [-4.591_9547, -9.24_8295, -9.64_5256],
														            [-6.730_6175, -6.44_0284, -6.605_2837],
														            [-7.274_3506, -6.784_7915, -6.02_4673],
														        ]
														    ]  )
														tf.debugging.assert_near(output[:, :3, :3]  , __lowerCAmelCase  , atol=1E-4  )











import unittest

from transformers import (
    MODEL_FOR_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_CAUSAL_LM_MAPPING,
    TextGenerationPipeline,
    logging,
    pipeline,
)
from transformers.testing_utils import (
    CaptureLogger,
    is_pipeline_test,
    require_accelerate,
    require_tf,
    require_torch,
    require_torch_gpu,
    require_torch_or_tf,
)

from .test_pipelines_common import ANY

@is_pipeline_test
@require_torch_or_tf
class        __SCREAMING_SNAKE_CASE					(     unittest.TestCase       ):
							snake_case     :      Union[str, Any]						     =       MODEL_FOR_CAUSAL_LM_MAPPING
							snake_case     :      List[str]						     =       TF_MODEL_FOR_CAUSAL_LM_MAPPING






							@require_torch
							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			pipeline(task="""text-generation"""  , model="""sshleifer/tiny-ctrl"""  , framework="""pt"""  )
														# Using `do_sample=False` to force deterministic output
														UpperCamelCase__				     =			text_generator("""This is a test"""  , do_sample=__lowerCAmelCase  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        {
														            """generated_text""": (
														                """This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope."""
														                """ oscope. FiliFili@@"""
														            )
														        }
														    ]  , )

														UpperCamelCase__				     =			text_generator(["""This is a test""", """This is a second test"""]  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        [
														            {
														                """generated_text""": (
														                    """This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope."""
														                    """ oscope. FiliFili@@"""
														                )
														            }
														        ],
														        [
														            {
														                """generated_text""": (
														                    """This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy"""
														                    """ oscope. oscope. FiliFili@@"""
														                )
														            }
														        ],
														    ]  , )

														UpperCamelCase__				     =			text_generator("""This is a test"""  , do_sample=__lowerCAmelCase  , num_return_sequences=2  , return_tensors=__lowerCAmelCase  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        {"""generated_token_ids""": ANY(__lowerCAmelCase  )},
														        {"""generated_token_ids""": ANY(__lowerCAmelCase  )},
														    ]  , )
														UpperCamelCase__				     =			text_generator.model.config.eos_token_id
														UpperCamelCase__				     =			"""<pad>"""
														UpperCamelCase__				     =			text_generator(
														    ["""This is a test""", """This is a second test"""]  , do_sample=__lowerCAmelCase  , num_return_sequences=2  , batch_size=2  , return_tensors=__lowerCAmelCase  , )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        [
														            {"""generated_token_ids""": ANY(__lowerCAmelCase  )},
														            {"""generated_token_ids""": ANY(__lowerCAmelCase  )},
														        ],
														        [
														            {"""generated_token_ids""": ANY(__lowerCAmelCase  )},
														            {"""generated_token_ids""": ANY(__lowerCAmelCase  )},
														        ],
														    ]  , )






							@require_tf
							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			pipeline(task="""text-generation"""  , model="""sshleifer/tiny-ctrl"""  , framework="""tf"""  )

														# Using `do_sample=False` to force deterministic output
														UpperCamelCase__				     =			text_generator("""This is a test"""  , do_sample=__lowerCAmelCase  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        {
														            """generated_text""": (
														                """This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵"""
														                """ please,"""
														            )
														        }
														    ]  , )

														UpperCamelCase__				     =			text_generator(["""This is a test""", """This is a second test"""]  , do_sample=__lowerCAmelCase  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        [
														            {
														                """generated_text""": (
														                    """This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵"""
														                    """ please,"""
														                )
														            }
														        ],
														        [
														            {
														                """generated_text""": (
														                    """This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes"""
														                    """ Cannes 閲閲Cannes Cannes Cannes 攵 please,"""
														                )
														            }
														        ],
														    ]  , )






							def 				_lowerCamelCase		(						self  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  ):
														UpperCamelCase__				     =			TextGenerationPipeline(model=__lowerCAmelCase  , tokenizer=__lowerCAmelCase  )
														return text_generator, ["This is a test", "Another test"]






							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			"""Hello I believe in"""
														UpperCamelCase__				     =			pipeline("""text-generation"""  , model="""hf-internal-testing/tiny-random-gpt2"""  )
														UpperCamelCase__				     =			text_generator(__lowerCAmelCase  )
														self.assertEqual(
														    __lowerCAmelCase  , [{"""generated_text""": """Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe"""}]  , )

														UpperCamelCase__				     =			text_generator(__lowerCAmelCase  , stop_sequence=""" fe"""  )
														self.assertEqual(__lowerCAmelCase  , [{"""generated_text""": """Hello I believe in fe"""}]  )






							def 				_lowerCamelCase		(						self  , __lowerCAmelCase  , __lowerCAmelCase  ):
														UpperCamelCase__				     =			text_generator.model
														UpperCamelCase__				     =			text_generator.tokenizer

														UpperCamelCase__				     =			text_generator("""This is a test"""  )
														self.assertEqual(__lowerCAmelCase  , [{"""generated_text""": ANY(__lowerCAmelCase  )}]  )
														self.assertTrue(outputs[0]["""generated_text"""].startswith("""This is a test"""  )  )

														UpperCamelCase__				     =			text_generator("""This is a test"""  , return_full_text=__lowerCAmelCase  )
														self.assertEqual(__lowerCAmelCase  , [{"""generated_text""": ANY(__lowerCAmelCase  )}]  )
														self.assertNotIn("""This is a test"""  , outputs[0]["""generated_text"""]  )

														UpperCamelCase__				     =			pipeline(task="""text-generation"""  , model=__lowerCAmelCase  , tokenizer=__lowerCAmelCase  , return_full_text=__lowerCAmelCase  )
														UpperCamelCase__				     =			text_generator("""This is a test"""  )
														self.assertEqual(__lowerCAmelCase  , [{"""generated_text""": ANY(__lowerCAmelCase  )}]  )
														self.assertNotIn("""This is a test"""  , outputs[0]["""generated_text"""]  )

														UpperCamelCase__				     =			text_generator("""This is a test"""  , return_full_text=__lowerCAmelCase  )
														self.assertEqual(__lowerCAmelCase  , [{"""generated_text""": ANY(__lowerCAmelCase  )}]  )
														self.assertTrue(outputs[0]["""generated_text"""].startswith("""This is a test"""  )  )

														UpperCamelCase__				     =			text_generator(["""This is great !""", """Something else"""]  , num_return_sequences=2  , do_sample=__lowerCAmelCase  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        [{"""generated_text""": ANY(__lowerCAmelCase  )}, {"""generated_text""": ANY(__lowerCAmelCase  )}],
														        [{"""generated_text""": ANY(__lowerCAmelCase  )}, {"""generated_text""": ANY(__lowerCAmelCase  )}],
														    ]  , )

														if text_generator.tokenizer.pad_token is not None:
																					UpperCamelCase__				     =			text_generator(
																					    ["""This is great !""", """Something else"""]  , num_return_sequences=2  , batch_size=2  , do_sample=__lowerCAmelCase  )
																					self.assertEqual(
																					    __lowerCAmelCase  , [
																					        [{"""generated_text""": ANY(__lowerCAmelCase  )}, {"""generated_text""": ANY(__lowerCAmelCase  )}],
																					        [{"""generated_text""": ANY(__lowerCAmelCase  )}, {"""generated_text""": ANY(__lowerCAmelCase  )}],
																					    ]  , )

														with self.assertRaises(__lowerCAmelCase  ):
																					UpperCamelCase__				     =			text_generator("""test"""  , return_full_text=__lowerCAmelCase  , return_text=__lowerCAmelCase  )
														with self.assertRaises(__lowerCAmelCase  ):
																					UpperCamelCase__				     =			text_generator("""test"""  , return_full_text=__lowerCAmelCase  , return_tensors=__lowerCAmelCase  )
														with self.assertRaises(__lowerCAmelCase  ):
																					UpperCamelCase__				     =			text_generator("""test"""  , return_text=__lowerCAmelCase  , return_tensors=__lowerCAmelCase  )

														# Empty prompt is slighly special
														# it requires BOS token to exist.
														# Special case for Pegasus which will always append EOS so will
														# work even without BOS.
														if (
														    text_generator.tokenizer.bos_token_id is not None
														    or "Pegasus" in tokenizer.__class__.__name__
														    or "Git" in model.__class__.__name__
														):
																					UpperCamelCase__				     =			text_generator(""""""  )
																					self.assertEqual(__lowerCAmelCase  , [{"""generated_text""": ANY(__lowerCAmelCase  )}]  )
														else:
																					with self.assertRaises((ValueError, AssertionError)  ):
																												UpperCamelCase__				     =			text_generator(""""""  )

														if text_generator.framework == "tf":
																					# TF generation does not support max_new_tokens, and it's impossible
																					# to control long generation with only max_length without
																					# fancy calculation, dismissing tests for now.
																					return
														# We don't care about infinite range models.
														# They already work.
														# Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly.
														UpperCamelCase__				     =			["""RwkvForCausalLM""", """XGLMForCausalLM""", """GPTNeoXForCausalLM"""]
														if (
														    tokenizer.model_max_length < 10000
														    and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS
														):
																					# Handling of large generations
																					with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError)  ):
																												text_generator("""This is a test""" * 500  , max_new_tokens=20  )

																					UpperCamelCase__				     =			text_generator("""This is a test""" * 500  , handle_long_generation="""hole"""  , max_new_tokens=20  )
																					# Hole strategy cannot work
																					with self.assertRaises(__lowerCAmelCase  ):
																												text_generator(
																												    """This is a test""" * 500  , handle_long_generation="""hole"""  , max_new_tokens=tokenizer.model_max_length + 10  , )






							@require_torch
							@require_accelerate
							@require_torch_gpu
							def 				_lowerCamelCase		(						self  ):
														import torch

														# Classic `model_kwargs`
														UpperCamelCase__				     =			pipeline(
														    model="""hf-internal-testing/tiny-random-bloom"""  , model_kwargs={"""device_map""": """auto""", """torch_dtype""": torch.bfloataa}  , )
														self.assertEqual(pipe.model.device  , torch.device(0  )  )
														self.assertEqual(pipe.model.lm_head.weight.dtype  , torch.bfloataa  )
														UpperCamelCase__				     =			pipe("""This is a test"""  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        {
														            """generated_text""": (
														                """This is a test test test test test test test test test test test test test test test test"""
														                """ test"""
														            )
														        }
														    ]  , )

														# Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.)
														UpperCamelCase__				     =			pipeline(model="""hf-internal-testing/tiny-random-bloom"""  , device_map="""auto"""  , torch_dtype=torch.bfloataa  )
														self.assertEqual(pipe.model.device  , torch.device(0  )  )
														self.assertEqual(pipe.model.lm_head.weight.dtype  , torch.bfloataa  )
														UpperCamelCase__				     =			pipe("""This is a test"""  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        {
														            """generated_text""": (
														                """This is a test test test test test test test test test test test test test test test test"""
														                """ test"""
														            )
														        }
														    ]  , )

														# torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602
														UpperCamelCase__				     =			pipeline(model="""hf-internal-testing/tiny-random-bloom"""  , device_map="""auto"""  )
														self.assertEqual(pipe.model.device  , torch.device(0  )  )
														self.assertEqual(pipe.model.lm_head.weight.dtype  , torch.floataa  )
														UpperCamelCase__				     =			pipe("""This is a test"""  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        {
														            """generated_text""": (
														                """This is a test test test test test test test test test test test test test test test test"""
														                """ test"""
														            )
														        }
														    ]  , )






							@require_torch
							@require_torch_gpu
							def 				_lowerCamelCase		(						self  ):
														import torch

														UpperCamelCase__				     =			pipeline(model="""hf-internal-testing/tiny-random-bloom"""  , device=0  , torch_dtype=torch.floataa  )
														pipe("""This is a test"""  )






							@require_torch
							@require_accelerate
							@require_torch_gpu
							def 				_lowerCamelCase		(						self  ):
														import torch

														UpperCamelCase__				     =			pipeline(model="""hf-internal-testing/tiny-random-bloom"""  , device_map="""auto"""  , torch_dtype=torch.floataa  )
														pipe("""This is a test"""  , do_sample=__lowerCAmelCase  , top_p=0.5  )







							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			"""Hello world"""
														UpperCamelCase__				     =			pipeline("""text-generation"""  , model="""hf-internal-testing/tiny-random-gpt2"""  )
														if text_generator.model.framework == "tf":
																					UpperCamelCase__				     =			logging.get_logger("""transformers.generation.tf_utils"""  )
														else:
																					UpperCamelCase__				     =			logging.get_logger("""transformers.generation.utils"""  )
														UpperCamelCase__				     =			"""Both `max_new_tokens`"""  # The beggining of the message to be checked in this test

														# Both are set by the user -> log warning
														with CaptureLogger(__lowerCAmelCase  ) as cl:
																					UpperCamelCase__				     =			text_generator(__lowerCAmelCase  , max_length=10  , max_new_tokens=1  )
														self.assertIn(__lowerCAmelCase  , cl.out  )

														# The user only sets one -> no warning
														with CaptureLogger(__lowerCAmelCase  ) as cl:
																					UpperCamelCase__				     =			text_generator(__lowerCAmelCase  , max_new_tokens=1  )
														self.assertNotIn(__lowerCAmelCase  , cl.out  )

														with CaptureLogger(__lowerCAmelCase  ) as cl:
																					UpperCamelCase__				     =			text_generator(__lowerCAmelCase  , max_length=10  )
														self.assertNotIn(__lowerCAmelCase  , cl.out  )




