




"""simple docstring"""

import unittest

from parameterized import parameterized

from transformers import OpenLlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel

class        lowercase      :







				def __init__(							self   :					Dict      ,     _lowerCamelCase   :					List[str]      ,     _lowerCamelCase   :					Optional[int]=13      ,     _lowerCamelCase   :					Union[str, Any]=7      ,     _lowerCamelCase   :					Any=True      ,     _lowerCamelCase   :					str=True      ,     _lowerCamelCase   :					Optional[int]=False      ,     _lowerCamelCase   :					Dict=True      ,     _lowerCamelCase   :					Any=99      ,     _lowerCamelCase   :					Tuple=32      ,     _lowerCamelCase   :					str=5      ,     _lowerCamelCase   :					Tuple=4      ,     _lowerCamelCase   :					Optional[int]=37      ,     _lowerCamelCase   :					List[str]="gelu"      ,     _lowerCamelCase   :					int=0.1      ,     _lowerCamelCase   :					Dict=0.1      ,     _lowerCamelCase   :					List[str]=5_12      ,     _lowerCamelCase   :					Tuple=16      ,     _lowerCamelCase   :					List[Any]=2      ,     _lowerCamelCase   :					Optional[Any]=0.02      ,     _lowerCamelCase   :					str=3      ,     _lowerCamelCase   :					List[str]=4      ,     _lowerCamelCase   :					str=None      ,     ):



					"""simple docstring"""

					A_  :				Any	   =		parent
					A_  :				int	   =		batch_size
					A_  :				List[str]	   =		seq_length
					A_  :				Union[str, Any]	   =		is_training
					A_  :				Tuple	   =		use_input_mask
					A_  :				Dict	   =		use_token_type_ids
					A_  :				Tuple	   =		use_labels
					A_  :				Optional[Any]	   =		vocab_size
					A_  :				Optional[Any]	   =		hidden_size
					A_  :				List[Any]	   =		num_hidden_layers
					A_  :				int	   =		num_attention_heads
					A_  :				List[Any]	   =		intermediate_size
					A_  :				Union[str, Any]	   =		hidden_act
					A_  :				Optional[int]	   =		hidden_dropout_prob
					A_  :				Tuple	   =		attention_probs_dropout_prob
					A_  :				List[Any]	   =		max_position_embeddings
					A_  :				Dict	   =		type_vocab_size
					A_  :				List[Any]	   =		type_sequence_label_size
					A_  :				Dict	   =		initializer_range
					A_  :				Dict	   =		num_labels
					A_  :				List[Any]	   =		num_choices
					A_  :				Any	   =		scope







				def 					a_  (							self   :					Tuple       ):



					"""simple docstring"""

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

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

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

					A_  :				List[Any]	   =		None
					A_  :				List[str]	   =		None
					A_  :				Optional[Any]	   =		None
					if self.use_labels:
						A_  :				Tuple	   =		ids_tensor([self.batch_size]      ,     self.type_sequence_label_size       )
						A_  :				Optional[Any]	   =		ids_tensor([self.batch_size, self.seq_length]      ,     self.num_labels       )
						A_  :				List[str]	   =		ids_tensor([self.batch_size]      ,     self.num_choices       )

					A_  :				List[Any]	   =		self.get_config()

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







				def 					a_  (							self   :					Optional[Any]       ):



					"""simple docstring"""

					return OpenLlamaConfig(
					    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      ,     is_decoder=_lowerCamelCase      ,     initializer_range=self.initializer_range      ,     use_stable_embedding=_lowerCamelCase      ,     )







				def 					a_  (							self   :					str      ,     _lowerCamelCase   :					int      ,     _lowerCamelCase   :					Any      ,     _lowerCamelCase   :					Optional[int]      ,     _lowerCamelCase   :					List[Any]      ,     _lowerCamelCase   :					List[Any]      ,     _lowerCamelCase   :					Tuple      ,     _lowerCamelCase   :					int       ):



					"""simple docstring"""

					A_  :				Dict	   =		OpenLlamaModel(config=_lowerCamelCase       )
					model.to(_lowerCamelCase       )
					model.eval()
					A_  :				Union[str, Any]	   =		model(_lowerCamelCase      ,     attention_mask=_lowerCamelCase       )
					A_  :				Optional[Any]	   =		model(_lowerCamelCase       )
					self.parent.assertEqual(result.last_hidden_state.shape      ,     (self.batch_size, self.seq_length, self.hidden_size)       )







				def 					a_  (							self   :					List[str]      ,     _lowerCamelCase   :					int      ,     _lowerCamelCase   :					str      ,     _lowerCamelCase   :					Tuple      ,     _lowerCamelCase   :					int      ,     _lowerCamelCase   :					int      ,     _lowerCamelCase   :					Any      ,     _lowerCamelCase   :					List[str]      ,     _lowerCamelCase   :					Dict      ,     _lowerCamelCase   :					Optional[Any]      ,     ):



					"""simple docstring"""

					A_  :				Optional[int]	   =		True
					A_  :				Any	   =		OpenLlamaModel(_lowerCamelCase       )
					model.to(_lowerCamelCase       )
					model.eval()
					A_  :				Tuple	   =		model(
					    _lowerCamelCase      ,     attention_mask=_lowerCamelCase      ,     encoder_hidden_states=_lowerCamelCase      ,     encoder_attention_mask=_lowerCamelCase      ,     )
					A_  :				List[Any]	   =		model(
					    _lowerCamelCase      ,     attention_mask=_lowerCamelCase      ,     encoder_hidden_states=_lowerCamelCase      ,     )
					A_  :				Dict	   =		model(_lowerCamelCase      ,     attention_mask=_lowerCamelCase       )
					self.parent.assertEqual(result.last_hidden_state.shape      ,     (self.batch_size, self.seq_length, self.hidden_size)       )







				def 					a_  (							self   :					int      ,     _lowerCamelCase   :					str      ,     _lowerCamelCase   :					List[str]      ,     _lowerCamelCase   :					int      ,     _lowerCamelCase   :					str      ,     _lowerCamelCase   :					Union[str, Any]      ,     _lowerCamelCase   :					Tuple      ,     _lowerCamelCase   :					str      ,     _lowerCamelCase   :					Union[str, Any]      ,     _lowerCamelCase   :					Dict      ,     ):



					"""simple docstring"""

					A_  :				Union[str, Any]	   =		OpenLlamaForCausalLM(config=_lowerCamelCase       )
					model.to(_lowerCamelCase       )
					model.eval()
					A_  :				List[Any]	   =		model(_lowerCamelCase      ,     attention_mask=_lowerCamelCase      ,     labels=_lowerCamelCase       )
					self.parent.assertEqual(result.logits.shape      ,     (self.batch_size, self.seq_length, self.vocab_size)       )







				def 					a_  (							self   :					List[Any]      ,     _lowerCamelCase   :					Any      ,     _lowerCamelCase   :					int      ,     _lowerCamelCase   :					Optional[Any]      ,     _lowerCamelCase   :					Any      ,     _lowerCamelCase   :					List[str]      ,     _lowerCamelCase   :					Optional[int]      ,     _lowerCamelCase   :					Any      ,     _lowerCamelCase   :					Optional[Any]      ,     _lowerCamelCase   :					str      ,     ):



					"""simple docstring"""

					A_  :				str	   =		True
					A_  :				List[str]	   =		True
					A_  :				Union[str, Any]	   =		OpenLlamaForCausalLM(config=_lowerCamelCase       )
					model.to(_lowerCamelCase       )
					model.eval()

					# first forward pass
					A_  :				Dict	   =		model(
					    _lowerCamelCase      ,     attention_mask=_lowerCamelCase      ,     encoder_hidden_states=_lowerCamelCase      ,     encoder_attention_mask=_lowerCamelCase      ,     use_cache=_lowerCamelCase      ,     )
					A_  :				Dict	   =		outputs.past_key_values

					# create hypothetical multiple next token and extent to next_input_ids
					A_  :				Optional[Any]	   =		ids_tensor((self.batch_size, 3)      ,     config.vocab_size       )
					A_  :				int	   =		ids_tensor((self.batch_size, 3)      ,     vocab_size=2       )

					# append to next input_ids and
					A_  :				Dict	   =		torch.cat([input_ids, next_tokens]      ,     dim=-1       )
					A_  :				List[str]	   =		torch.cat([input_mask, next_mask]      ,     dim=-1       )

					A_  :				str	   =		model(
					    _lowerCamelCase      ,     attention_mask=_lowerCamelCase      ,     encoder_hidden_states=_lowerCamelCase      ,     encoder_attention_mask=_lowerCamelCase      ,     output_hidden_states=_lowerCamelCase      ,     )['''hidden_states'''][0]
					A_  :				Any	   =		model(
					    _lowerCamelCase      ,     attention_mask=_lowerCamelCase      ,     encoder_hidden_states=_lowerCamelCase      ,     encoder_attention_mask=_lowerCamelCase      ,     past_key_values=_lowerCamelCase      ,     output_hidden_states=_lowerCamelCase      ,     )['''hidden_states'''][0]

					# select random slice
					A_  :				List[str]	   =		ids_tensor((1,)      ,     output_from_past.shape[-1]       ).item()
					A_  :				Union[str, Any]	   =		output_from_no_past[:, -3:, random_slice_idx].detach()
					A_  :				Union[str, Any]	   =		output_from_past[:, :, random_slice_idx].detach()

					self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]       )

					# test that outputs are equal for slice
					self.parent.assertTrue(torch.allclose(_lowerCamelCase      ,     _lowerCamelCase      ,     atol=1E-3       )       )







				def 					a_  (							self   :					Optional[Any]       ):



					"""simple docstring"""

					A_  :				List[str]	   =		self.prepare_config_and_inputs()
					(
					    (
					    A_
					)   , (
					    A_
					)   , (
					    A_
					)   , (
					    A_
					)   , (
					    A_
					)   , (
					    A_
					)   , (
					    A_
					)   , 
					)  :				Any	   =		config_and_inputs
					A_  :				List[Any]	   =		{'''input_ids''': input_ids, '''attention_mask''': input_mask}
					return config, inputs_dict

@require_torch
class        lowercase      (    __UpperCAmelCase     ,	__UpperCAmelCase     ,	__UpperCAmelCase     ,	unittest.TestCase):
				__lowerCAmelCase    :    Optional[int]         =   (
				    (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
				)
				__lowerCAmelCase    :    Any         =   (OpenLlamaForCausalLM,) if is_torch_available() else ()
				__lowerCAmelCase    :    str         =   (
				    {
				        """feature-extraction""": OpenLlamaModel,
				        """text-classification""": OpenLlamaForSequenceClassification,
				        """text-generation""": OpenLlamaForCausalLM,
				        """zero-shot""": OpenLlamaForSequenceClassification,
				    }
				    if is_torch_available()
				    else {}
				)
				__lowerCAmelCase    :    List[str]         =   False
				__lowerCAmelCase    :    Optional[Any]         =   False







				def 					a_  (							self   :					Any       ):



					"""simple docstring"""

					A_  :				List[Any]	   =		OpenLlamaModelTester(self       )
					A_  :				int	   =		ConfigTester(self      ,     config_class=_lowerCamelCase      ,     hidden_size=37       )







				def 					a_  (							self   :					Union[str, Any]       ):



					"""simple docstring"""

					self.config_tester.run_common_tests()







				def 					a_  (							self   :					Union[str, Any]       ):



					"""simple docstring"""

					A_  :				Union[str, Any]	   =		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*_lowerCamelCase       )







				def 					a_  (							self   :					List[str]       ):



					"""simple docstring"""

					A_  :				str	   =		self.model_tester.prepare_config_and_inputs()
					for type in ["absolute", "relative_key", "relative_key_query"]:
						A_  :				Optional[int]	   =		type
						self.model_tester.create_and_check_model(*_lowerCamelCase       )







				def 					a_  (							self   :					int       ):



					"""simple docstring"""

					A_   , A_  :				List[str]	   =		self.model_tester.prepare_config_and_inputs_for_common()
					A_  :				List[Any]	   =		3
					A_  :				str	   =		input_dict['''input_ids''']
					A_  :				str	   =		input_ids.ne(1       ).to(_lowerCamelCase       )
					A_  :				Dict	   =		ids_tensor([self.model_tester.batch_size]      ,     self.model_tester.type_sequence_label_size       )
					A_  :				List[str]	   =		OpenLlamaForSequenceClassification(_lowerCamelCase       )
					model.to(_lowerCamelCase       )
					model.eval()
					A_  :				Union[str, Any]	   =		model(_lowerCamelCase      ,     attention_mask=_lowerCamelCase      ,     labels=_lowerCamelCase       )
					self.assertEqual(result.logits.shape      ,     (self.model_tester.batch_size, self.model_tester.num_labels)       )







				def 					a_  (							self   :					Optional[Any]       ):



					"""simple docstring"""

					A_   , A_  :				Any	   =		self.model_tester.prepare_config_and_inputs_for_common()
					A_  :				Union[str, Any]	   =		3
					A_  :				List[str]	   =		'''single_label_classification'''
					A_  :				Any	   =		input_dict['''input_ids''']
					A_  :				str	   =		input_ids.ne(1       ).to(_lowerCamelCase       )
					A_  :				str	   =		ids_tensor([self.model_tester.batch_size]      ,     self.model_tester.type_sequence_label_size       )
					A_  :				int	   =		OpenLlamaForSequenceClassification(_lowerCamelCase       )
					model.to(_lowerCamelCase       )
					model.eval()
					A_  :				Union[str, Any]	   =		model(_lowerCamelCase      ,     attention_mask=_lowerCamelCase      ,     labels=_lowerCamelCase       )
					self.assertEqual(result.logits.shape      ,     (self.model_tester.batch_size, self.model_tester.num_labels)       )







				def 					a_  (							self   :					Dict       ):



					"""simple docstring"""

					A_   , A_  :				Optional[int]	   =		self.model_tester.prepare_config_and_inputs_for_common()
					A_  :				Dict	   =		3
					A_  :				Union[str, Any]	   =		'''multi_label_classification'''
					A_  :				Optional[int]	   =		input_dict['''input_ids''']
					A_  :				Union[str, Any]	   =		input_ids.ne(1       ).to(_lowerCamelCase       )
					A_  :				Tuple	   =		ids_tensor(
					    [self.model_tester.batch_size, config.num_labels]      ,     self.model_tester.type_sequence_label_size       ).to(torch.float       )
					A_  :				List[Any]	   =		OpenLlamaForSequenceClassification(_lowerCamelCase       )
					model.to(_lowerCamelCase       )
					model.eval()
					A_  :				List[str]	   =		model(_lowerCamelCase      ,     attention_mask=_lowerCamelCase      ,     labels=_lowerCamelCase       )
					self.assertEqual(result.logits.shape      ,     (self.model_tester.batch_size, self.model_tester.num_labels)       )







				@unittest.skip('''Open-Llama buffers include complex numbers, which breaks this test'''       )
				def 					a_  (							self   :					List[Any]       ):



					"""simple docstring"""

					pass







				@parameterized.expand([('''linear''',), ('''dynamic''',)]       )
				def 					a_  (							self   :					str      ,     _lowerCamelCase   :					List[Any]       ):



					"""simple docstring"""

					A_   , A_  :				int	   =		self.model_tester.prepare_config_and_inputs_for_common()
					A_  :				List[str]	   =		ids_tensor([1, 10]      ,     config.vocab_size       )
					A_  :				List[Any]	   =		ids_tensor([1, int(config.max_position_embeddings * 1.5       )]      ,     config.vocab_size       )

					set_seed(42       )  # Fixed seed at init time so the two models get the same random weights
					A_  :				Dict	   =		OpenLlamaModel(_lowerCamelCase       )
					original_model.to(_lowerCamelCase       )
					original_model.eval()
					A_  :				Dict	   =		original_model(_lowerCamelCase       ).last_hidden_state
					A_  :				List[Any]	   =		original_model(_lowerCamelCase       ).last_hidden_state

					set_seed(42       )  # Fixed seed at init time so the two models get the same random weights
					A_  :				List[str]	   =		{'''type''': scaling_type, '''factor''': 10.0}
					A_  :				str	   =		OpenLlamaModel(_lowerCamelCase       )
					scaled_model.to(_lowerCamelCase       )
					scaled_model.eval()
					A_  :				int	   =		scaled_model(_lowerCamelCase       ).last_hidden_state
					A_  :				List[Any]	   =		scaled_model(_lowerCamelCase       ).last_hidden_state

					# Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
					# maximum sequence length, so the outputs for the short input should match.
					if scaling_type == "dynamic":
						self.assertTrue(torch.allclose(_lowerCamelCase      ,     _lowerCamelCase      ,     atol=1E-5       )       )
					else:
						self.assertFalse(torch.allclose(_lowerCamelCase      ,     _lowerCamelCase      ,     atol=1E-5       )       )

					# The output should be different for long inputs
					self.assertFalse(torch.allclose(_lowerCamelCase      ,     _lowerCamelCase      ,     atol=1E-5       )       )











"""simple docstring"""

import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    Pipeline,
    ZeroShotClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
_lowerCamelCase  :			Optional[Any]        =       {'LayoutLMv2Config', 'LayoutLMv3Config'}

@is_pipeline_test
class        lowercase      (    unittest.TestCase):
				__lowerCAmelCase    :    Optional[Any]         =   MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
				__lowerCAmelCase    :    str         =   TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

				if model_mapping is not None:
								__lowerCAmelCase    :    int         =   {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
				if tf_model_mapping is not None:
								__lowerCAmelCase    :    List[Any]         =   {
								    config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
								}







				def 					a_  (							self   :					Optional[Any]      ,     _lowerCamelCase   :					Any      ,     _lowerCamelCase   :					List[Any]      ,     _lowerCamelCase   :					Any       ):



					"""simple docstring"""

					A_  :				int	   =		ZeroShotClassificationPipeline(
					    model=_lowerCamelCase      ,     tokenizer=_lowerCamelCase      ,     candidate_labels=['''polics''', '''health''']       )
					return classifier, ["Who are you voting for in 2020?", "My stomach hurts."]







				def 					a_  (							self   :					List[str]      ,     _lowerCamelCase   :					Any      ,     _lowerCamelCase   :					Union[str, Any]       ):



					"""simple docstring"""

					A_  :				List[Any]	   =		classifier('''Who are you voting for in 2020?'''      ,     candidate_labels='''politics'''       )
					self.assertEqual(_lowerCamelCase      ,     {'''sequence''': ANY(_lowerCamelCase       ), '''labels''': [ANY(_lowerCamelCase       )], '''scores''': [ANY(_lowerCamelCase       )]}       )

					# No kwarg
					A_  :				Tuple	   =		classifier('''Who are you voting for in 2020?'''      ,     ['''politics''']       )
					self.assertEqual(_lowerCamelCase      ,     {'''sequence''': ANY(_lowerCamelCase       ), '''labels''': [ANY(_lowerCamelCase       )], '''scores''': [ANY(_lowerCamelCase       )]}       )

					A_  :				List[Any]	   =		classifier('''Who are you voting for in 2020?'''      ,     candidate_labels=['''politics''']       )
					self.assertEqual(_lowerCamelCase      ,     {'''sequence''': ANY(_lowerCamelCase       ), '''labels''': [ANY(_lowerCamelCase       )], '''scores''': [ANY(_lowerCamelCase       )]}       )

					A_  :				Union[str, Any]	   =		classifier('''Who are you voting for in 2020?'''      ,     candidate_labels='''politics, public health'''       )
					self.assertEqual(
					    _lowerCamelCase      ,     {'''sequence''': ANY(_lowerCamelCase       ), '''labels''': [ANY(_lowerCamelCase       ), ANY(_lowerCamelCase       )], '''scores''': [ANY(_lowerCamelCase       ), ANY(_lowerCamelCase       )]}       )
					self.assertAlmostEqual(sum(nested_simplify(outputs['''scores''']       )       )      ,     1.0       )

					A_  :				Tuple	   =		classifier('''Who are you voting for in 2020?'''      ,     candidate_labels=['''politics''', '''public health''']       )
					self.assertEqual(
					    _lowerCamelCase      ,     {'''sequence''': ANY(_lowerCamelCase       ), '''labels''': [ANY(_lowerCamelCase       ), ANY(_lowerCamelCase       )], '''scores''': [ANY(_lowerCamelCase       ), ANY(_lowerCamelCase       )]}       )
					self.assertAlmostEqual(sum(nested_simplify(outputs['''scores''']       )       )      ,     1.0       )

					A_  :				List[str]	   =		classifier(
					    '''Who are you voting for in 2020?'''      ,     candidate_labels='''politics'''      ,     hypothesis_template='''This text is about {}'''       )
					self.assertEqual(_lowerCamelCase      ,     {'''sequence''': ANY(_lowerCamelCase       ), '''labels''': [ANY(_lowerCamelCase       )], '''scores''': [ANY(_lowerCamelCase       )]}       )

					# https://github.com/huggingface/transformers/issues/13846
					A_  :				str	   =		classifier(['''I am happy''']      ,     ['''positive''', '''negative''']       )
					self.assertEqual(
					    _lowerCamelCase      ,     [
					        {'''sequence''': ANY(_lowerCamelCase       ), '''labels''': [ANY(_lowerCamelCase       ), ANY(_lowerCamelCase       )], '''scores''': [ANY(_lowerCamelCase       ), ANY(_lowerCamelCase       )]}
					        for i in range(1       )
					    ]      ,     )
					A_  :				str	   =		classifier(['''I am happy''', '''I am sad''']      ,     ['''positive''', '''negative''']       )
					self.assertEqual(
					    _lowerCamelCase      ,     [
					        {'''sequence''': ANY(_lowerCamelCase       ), '''labels''': [ANY(_lowerCamelCase       ), ANY(_lowerCamelCase       )], '''scores''': [ANY(_lowerCamelCase       ), ANY(_lowerCamelCase       )]}
					        for i in range(2       )
					    ]      ,     )

					with self.assertRaises(_lowerCamelCase       ):
						classifier(''''''      ,     candidate_labels='''politics'''       )

					with self.assertRaises(_lowerCamelCase       ):
						classifier(_lowerCamelCase      ,     candidate_labels='''politics'''       )

					with self.assertRaises(_lowerCamelCase       ):
						classifier('''Who are you voting for in 2020?'''      ,     candidate_labels=''''''       )

					with self.assertRaises(_lowerCamelCase       ):
						classifier('''Who are you voting for in 2020?'''      ,     candidate_labels=_lowerCamelCase       )

					with self.assertRaises(_lowerCamelCase       ):
						classifier(
						    '''Who are you voting for in 2020?'''      ,     candidate_labels='''politics'''      ,     hypothesis_template='''Not formatting template'''      ,     )

					with self.assertRaises(_lowerCamelCase       ):
						classifier(
						    '''Who are you voting for in 2020?'''      ,     candidate_labels='''politics'''      ,     hypothesis_template=_lowerCamelCase      ,     )

					self.run_entailment_id(_lowerCamelCase       )







				def 					a_  (							self   :					Any      ,     _lowerCamelCase   :					Pipeline       ):



					"""simple docstring"""

					A_  :				int	   =		zero_shot_classifier.model.config
					A_  :				Dict	   =		config.labelaid
					A_  :				Optional[int]	   =		zero_shot_classifier.entailment_id

					A_  :				Optional[Any]	   =		{'''LABEL_0''': 0, '''LABEL_1''': 1, '''LABEL_2''': 2}
					self.assertEqual(zero_shot_classifier.entailment_id      ,     -1       )

					A_  :				Union[str, Any]	   =		{'''entailment''': 0, '''neutral''': 1, '''contradiction''': 2}
					self.assertEqual(zero_shot_classifier.entailment_id      ,     0       )

					A_  :				int	   =		{'''ENTAIL''': 0, '''NON-ENTAIL''': 1}
					self.assertEqual(zero_shot_classifier.entailment_id      ,     0       )

					A_  :				Optional[Any]	   =		{'''ENTAIL''': 2, '''NEUTRAL''': 1, '''CONTR''': 0}
					self.assertEqual(zero_shot_classifier.entailment_id      ,     2       )

					A_  :				List[Any]	   =		original_labelaid
					self.assertEqual(_lowerCamelCase      ,     zero_shot_classifier.entailment_id       )







				@require_torch
				def 					a_  (							self   :					List[Any]       ):



					"""simple docstring"""

					A_  :				List[str]	   =		pipeline(
					    '''zero-shot-classification'''      ,     model='''sshleifer/tiny-distilbert-base-cased-distilled-squad'''      ,     framework='''pt'''      ,     )
					# There was a regression in 4.10 for this
					# Adding a test so we don't make the mistake again.
					# https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499
					zero_shot_classifier(
					    '''Who are you voting for in 2020?''' * 1_00      ,     candidate_labels=['''politics''', '''public health''', '''science''']       )







				@require_torch
				def 					a_  (							self   :					Dict       ):



					"""simple docstring"""

					A_  :				Optional[Any]	   =		pipeline(
					    '''zero-shot-classification'''      ,     model='''sshleifer/tiny-distilbert-base-cased-distilled-squad'''      ,     framework='''pt'''      ,     )
					A_  :				Optional[Any]	   =		zero_shot_classifier(
					    '''Who are you voting for in 2020?'''      ,     candidate_labels=['''politics''', '''public health''', '''science''']       )

					self.assertEqual(
					    nested_simplify(_lowerCamelCase       )      ,     {
					        '''sequence''': '''Who are you voting for in 2020?''',
					        '''labels''': ['''science''', '''public health''', '''politics'''],
					        '''scores''': [0.333, 0.333, 0.333],
					    }      ,     )







				@require_tf
				def 					a_  (							self   :					Dict       ):



					"""simple docstring"""

					A_  :				List[str]	   =		pipeline(
					    '''zero-shot-classification'''      ,     model='''sshleifer/tiny-distilbert-base-cased-distilled-squad'''      ,     framework='''tf'''      ,     )
					A_  :				List[str]	   =		zero_shot_classifier(
					    '''Who are you voting for in 2020?'''      ,     candidate_labels=['''politics''', '''public health''', '''science''']       )

					self.assertEqual(
					    nested_simplify(_lowerCamelCase       )      ,     {
					        '''sequence''': '''Who are you voting for in 2020?''',
					        '''labels''': ['''science''', '''public health''', '''politics'''],
					        '''scores''': [0.333, 0.333, 0.333],
					    }      ,     )







				@slow
				@require_torch
				def 					a_  (							self   :					int       ):



					"""simple docstring"""

					A_  :				Union[str, Any]	   =		pipeline('''zero-shot-classification'''      ,     model='''roberta-large-mnli'''      ,     framework='''pt'''       )
					A_  :				str	   =		zero_shot_classifier(
					    '''Who are you voting for in 2020?'''      ,     candidate_labels=['''politics''', '''public health''', '''science''']       )

					self.assertEqual(
					    nested_simplify(_lowerCamelCase       )      ,     {
					        '''sequence''': '''Who are you voting for in 2020?''',
					        '''labels''': ['''politics''', '''public health''', '''science'''],
					        '''scores''': [0.976, 0.015, 0.009],
					    }      ,     )
					A_  :				str	   =		zero_shot_classifier(
					    '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks'''
					    ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder'''
					    ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based'''
					    ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two'''
					    ''' machine translation tasks show these models to be superior in quality while being more parallelizable'''
					    ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014'''
					    ''' English-to-German translation task, improving over the existing best results, including ensembles by'''
					    ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new'''
					    ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small'''
					    ''' fraction of the training costs of the best models from the literature. We show that the Transformer'''
					    ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with'''
					    ''' large and limited training data.'''      ,     candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision''']      ,     multi_label=_lowerCamelCase      ,     )
					self.assertEqual(
					    nested_simplify(_lowerCamelCase       )      ,     {
					        '''sequence''': (
					            '''The dominant sequence transduction models are based on complex recurrent or convolutional neural'''
					            ''' networks in an encoder-decoder configuration. The best performing models also connect the'''
					            ''' encoder and decoder through an attention mechanism. We propose a new simple network'''
					            ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence'''
					            ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be'''
					            ''' superior in quality while being more parallelizable and requiring significantly less time to'''
					            ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,'''
					            ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014'''
					            ''' English-to-French translation task, our model establishes a new single-model state-of-the-art'''
					            ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training'''
					            ''' costs of the best models from the literature. We show that the Transformer generalizes well to'''
					            ''' other tasks by applying it successfully to English constituency parsing both with large and'''
					            ''' limited training data.'''
					        ),
					        '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''],
					        '''scores''': [0.817, 0.713, 0.018, 0.018],
					    }      ,     )







				@slow
				@require_tf
				def 					a_  (							self   :					Union[str, Any]       ):



					"""simple docstring"""

					A_  :				Tuple	   =		pipeline('''zero-shot-classification'''      ,     model='''roberta-large-mnli'''      ,     framework='''tf'''       )
					A_  :				str	   =		zero_shot_classifier(
					    '''Who are you voting for in 2020?'''      ,     candidate_labels=['''politics''', '''public health''', '''science''']       )

					self.assertEqual(
					    nested_simplify(_lowerCamelCase       )      ,     {
					        '''sequence''': '''Who are you voting for in 2020?''',
					        '''labels''': ['''politics''', '''public health''', '''science'''],
					        '''scores''': [0.976, 0.015, 0.009],
					    }      ,     )
					A_  :				Tuple	   =		zero_shot_classifier(
					    '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks'''
					    ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder'''
					    ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based'''
					    ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two'''
					    ''' machine translation tasks show these models to be superior in quality while being more parallelizable'''
					    ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014'''
					    ''' English-to-German translation task, improving over the existing best results, including ensembles by'''
					    ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new'''
					    ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small'''
					    ''' fraction of the training costs of the best models from the literature. We show that the Transformer'''
					    ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with'''
					    ''' large and limited training data.'''      ,     candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision''']      ,     multi_label=_lowerCamelCase      ,     )
					self.assertEqual(
					    nested_simplify(_lowerCamelCase       )      ,     {
					        '''sequence''': (
					            '''The dominant sequence transduction models are based on complex recurrent or convolutional neural'''
					            ''' networks in an encoder-decoder configuration. The best performing models also connect the'''
					            ''' encoder and decoder through an attention mechanism. We propose a new simple network'''
					            ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence'''
					            ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be'''
					            ''' superior in quality while being more parallelizable and requiring significantly less time to'''
					            ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,'''
					            ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014'''
					            ''' English-to-French translation task, our model establishes a new single-model state-of-the-art'''
					            ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training'''
					            ''' costs of the best models from the literature. We show that the Transformer generalizes well to'''
					            ''' other tasks by applying it successfully to English constituency parsing both with large and'''
					            ''' limited training data.'''
					        ),
					        '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''],
					        '''scores''': [0.817, 0.713, 0.018, 0.018],
					    }      ,     )





