






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.
_a      	=  {'''LayoutLMv2Config''', '''LayoutLMv3Config'''}





@is_pipeline_test
class __lowerCamelCase (      unittest.TestCase):





	"""simple docstring"""






	UpperCamelCase__								=      MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
	UpperCamelCase__								=      TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

	if model_mapping is not None:
		UpperCamelCase__								=      {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
	if tf_model_mapping is not None:
		UpperCamelCase__								=      {
		    config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
		}

	def        UpperCamelCase    (							self       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    ):
							"""simple docstring"""







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

	def        UpperCamelCase    (							self       ,    UpperCAmelCase       ,    UpperCAmelCase    ):
							"""simple docstring"""







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

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

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

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

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

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

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

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

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

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

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

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

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

							self.run_entailment_id(UpperCAmelCase    )

	def        UpperCamelCase    (							self       ,    UpperCAmelCase    ):
							"""simple docstring"""







							_UpperCAmelCase									=			zero_shot_classifier.model.config
							_UpperCAmelCase									=			config.labelaid
							_UpperCAmelCase									=			zero_shot_classifier.entailment_id

							_UpperCAmelCase									=			{'LABEL_0': 0, 'LABEL_1': 1, 'LABEL_2': 2}
							self.assertEqual(zero_shot_classifier.entailment_id       ,    -1    )

							_UpperCAmelCase									=			{'entailment': 0, 'neutral': 1, 'contradiction': 2}
							self.assertEqual(zero_shot_classifier.entailment_id       ,    0    )

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

							_UpperCAmelCase									=			{'ENTAIL': 2, 'NEUTRAL': 1, 'CONTR': 0}
							self.assertEqual(zero_shot_classifier.entailment_id       ,    2    )

							_UpperCAmelCase									=			original_labelaid
							self.assertEqual(UpperCAmelCase       ,    zero_shot_classifier.entailment_id    )

	@require_torch
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			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?' * 100       ,    candidate_labels=['politics', 'public health', 'science']    )

	@require_torch
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







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

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

	@require_tf
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







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

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

	@slow
	@require_torch
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







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

							self.assertEqual(
							    nested_simplify(UpperCAmelCase    )       ,    {
							        'sequence': 'Who are you voting for in 2020?',
							        'labels': ['politics', 'public health', 'science'],
							        'scores': [0.9_76, 0.0_15, 0.0_09],
							    }       ,    )
							_UpperCAmelCase									=			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=UpperCAmelCase       ,    )
							self.assertEqual(
							    nested_simplify(UpperCAmelCase    )       ,    {
							        '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.8_17, 0.7_13, 0.0_18, 0.0_18],
							    }       ,    )

	@slow
	@require_tf
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







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

							self.assertEqual(
							    nested_simplify(UpperCAmelCase    )       ,    {
							        'sequence': 'Who are you voting for in 2020?',
							        'labels': ['politics', 'public health', 'science'],
							        'scores': [0.9_76, 0.0_15, 0.0_09],
							    }       ,    )
							_UpperCAmelCase									=			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=UpperCAmelCase       ,    )
							self.assertEqual(
							    nested_simplify(UpperCAmelCase    )       ,    {
							        '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.8_17, 0.7_13, 0.0_18, 0.0_18],
							    }       ,    )







'''simple docstring'''







import torch
from torch import nn

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin
class 				__SCREAMING_SNAKE_CASE  (lowerCamelCase_       ,							lowerCamelCase_      ):






				"""simple docstring"""







				@register_to_config
				def __init__(  self     :					Dict					,				*,
				    __a     :					int = 4					,				__a     :					int = 7_68					,				__a     :					int					,				__a     :					int					,				):
								super().__init__()

								_a								= nn.Parameter(torch.zeros(__a					)					)

								# parameters for additional clip time embeddings
								_a								= nn.Linear(__a					,				__a					)
								_a								= nn.Linear(__a					,				__a					)

								# parameters for encoder hidden states
								_a								= clip_extra_context_tokens
								_a								= nn.Linear(
								    __a					,				self.clip_extra_context_tokens * cross_attention_dim					)
								_a								= nn.Linear(__a					,				__a					)
								_a								= nn.LayerNorm(__a					)




				def   UpperCamelCase__   (  self     :					Optional[Any]					,				*, __a     :					Tuple					,				__a     :					Union[str, Any]					,				__a     :					Any					,				__a     :					List[Any]					):
								if do_classifier_free_guidance:
												# Add the classifier free guidance embeddings to the image embeddings
												_a								= image_embeddings.shape[0]
												_a								= self.learned_classifier_free_guidance_embeddings.unsqueeze(0					)
												_a								= classifier_free_guidance_embeddings.expand(
												    __a					,				-1					)
												_a								= torch.cat([classifier_free_guidance_embeddings, image_embeddings]					,				dim=0					)

								# The image embeddings batch size and the text embeddings batch size are equal
								assert image_embeddings.shape[0] == prompt_embeds.shape[0]

								_a								= prompt_embeds.shape[0]

								# "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and
								# adding CLIP embeddings to the existing timestep embedding, ...
								_a								= self.embedding_proj(__a					)
								_a								= self.clip_image_embeddings_project_to_time_embeddings(__a					)
								_a								= time_projected_image_embeddings + time_projected_prompt_embeds

								# ... and by projecting CLIP embeddings into four
								# extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder"
								_a								= self.clip_extra_context_tokens_proj(__a					)
								_a								= clip_extra_context_tokens.reshape(__a					,				-1					,				self.clip_extra_context_tokens					)
								_a								= clip_extra_context_tokens.permute(0					,				2					,				1					)

								_a								= self.encoder_hidden_states_proj(__a					)
								_a								= self.text_encoder_hidden_states_norm(__a					)
								_a								= torch.cat([clip_extra_context_tokens, text_encoder_hidden_states]					,				dim=1					)

								return text_encoder_hidden_states, additive_clip_time_embeddings
