






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],
							    }       ,    )





# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion
# and https://github.com/hojonathanho/diffusion
import math
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.schedulers.scheduling_utils import SchedulerMixin
from diffusers.utils import BaseOutput, deprecate



@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM
class 	_lowercase							(   lowerCAmelCase	):





	"""simple docstring"""
	__A							=							42
	__A							=							None






def     a(      A       :    Optional[Any] ,     A       :    Any=0.999 ,     A       :    Dict="cosine" ,     )		->       Optional[int]:
					"""simple docstring"""





					if alpha_transform_type == "cosine":

										def alpha_bar_fn(A       :    Optional[int]       ):
															return math.cos((t + 0.008) / 1.008 * math.pi / 2       ) ** 2

					elif alpha_transform_type == "exp":

										def alpha_bar_fn(A       :    Any       ):
															return math.exp(t * -12.0       )

					else:
										raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}'''       )

					a					     =   []
					for i in range(A       ):
										a					     =   i / num_diffusion_timesteps
										a					     =   (i + 1) / num_diffusion_timesteps
										betas.append(min(1 - alpha_bar_fn(A       ) / alpha_bar_fn(A       ) ,     A       )       )
					return torch.tensor(A ,     dtype=torch.floataa       )







class 	_lowercase							(   lowerCAmelCase,      lowerCAmelCase	):





	"""simple docstring"""
	__A							=							1




	@register_to_config
	def __init__(self		,       lowerCamelCase_ = 1000		,       lowerCamelCase_ = 0.0001		,       lowerCamelCase_ = 0.02		,       lowerCamelCase_ = "linear"		,       lowerCamelCase_ = None		,       lowerCamelCase_ = True		,       lowerCamelCase_ = True		,       lowerCamelCase_ = 0		,       lowerCamelCase_ = "epsilon"		,       lowerCamelCase_ = 1.0		,       **lowerCamelCase_		,       ):
						"""simple docstring"""

						if kwargs.get("set_alpha_to_one"		,       lowerCamelCase_		) is not None:
											a					     =   (
											    "The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead."
											)
											deprecate("set_alpha_to_one"		,       "1.0.0"		,       lowerCamelCase_		,       standard_warn=lowerCamelCase_		)
											a					     =   kwargs["set_alpha_to_one"]
						if trained_betas is not None:
											a					     =   torch.tensor(lowerCamelCase_		,       dtype=torch.floataa		)
						elif beta_schedule == "linear":
											a					     =   torch.linspace(lowerCamelCase_		,       lowerCamelCase_		,       lowerCamelCase_		,       dtype=torch.floataa		)
						elif beta_schedule == "scaled_linear":
											# this schedule is very specific to the latent diffusion model.
											a					     =   (
											    torch.linspace(beta_start**0.5		,       beta_end**0.5		,       lowerCamelCase_		,       dtype=torch.floataa		) ** 2
											)
						elif beta_schedule == "squaredcos_cap_v2":
											# Glide cosine schedule
											a					     =   betas_for_alpha_bar(lowerCamelCase_		)
						else:
											raise NotImplementedError(F'''{beta_schedule} does is not implemented for {self.__class__}'''		)

						a					     =   1.0 - self.betas
						a					     =   torch.cumprod(self.alphas		,       dim=0		)

						# At every step in inverted ddim, we are looking into the next alphas_cumprod
						# For the final step, there is no next alphas_cumprod, and the index is out of bounds
						# `set_alpha_to_zero` decides whether we set this parameter simply to zero
						# in this case, self.step() just output the predicted noise
						# or whether we use the final alpha of the "non-previous" one.
						a					     =   torch.tensor(0.0		) if set_alpha_to_zero else self.alphas_cumprod[-1]

						# standard deviation of the initial noise distribution
						a					     =   1.0

						# setable values
						a					     =   None
						a					     =   torch.from_numpy(np.arange(0		,       lowerCamelCase_		).copy().astype(np.intaa		)		)




	def      UpperCamelCase_       (self		,       lowerCamelCase_		,       lowerCamelCase_ = None		):
						"""simple docstring"""

						return sample




	def      UpperCamelCase_       (self		,       lowerCamelCase_		,       lowerCamelCase_ = None		):
						"""simple docstring"""

						if num_inference_steps > self.config.num_train_timesteps:
											raise ValueError(
											    F'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:'''
											    F''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle'''
											    F''' maximal {self.config.num_train_timesteps} timesteps.'''		)

						a					     =   num_inference_steps
						a					     =   self.config.num_train_timesteps // self.num_inference_steps
						# creates integer timesteps by multiplying by ratio
						# casting to int to avoid issues when num_inference_step is power of 3
						a					     =   (np.arange(0		,       lowerCamelCase_		) * step_ratio).round().copy().astype(np.intaa		)
						a					     =   torch.from_numpy(lowerCamelCase_		).to(lowerCamelCase_		)
						self.timesteps += self.config.steps_offset




	def      UpperCamelCase_       (self		,       lowerCamelCase_		,       lowerCamelCase_		,       lowerCamelCase_		,       lowerCamelCase_ = 0.0		,       lowerCamelCase_ = False		,       lowerCamelCase_ = None		,       lowerCamelCase_ = True		,       ):
						"""simple docstring"""

						a					     =   timestep + self.config.num_train_timesteps // self.num_inference_steps

						# 2. compute alphas, betas
						# change original implementation to exactly match noise levels for analogous forward process
						a					     =   self.alphas_cumprod[timestep]
						a					     =   (
						    self.alphas_cumprod[prev_timestep]
						    if prev_timestep < self.config.num_train_timesteps
						    else self.final_alpha_cumprod
						)

						a					     =   1 - alpha_prod_t

						# 3. compute predicted original sample from predicted noise also called
						# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
						if self.config.prediction_type == "epsilon":
											a					     =   (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
											a					     =   model_output
						elif self.config.prediction_type == "sample":
											a					     =   model_output
											a					     =   (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5
						elif self.config.prediction_type == "v_prediction":
											a					     =   (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
											a					     =   (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
						else:
											raise ValueError(
											    F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or'''
											    " `v_prediction`"		)

						# 4. Clip or threshold "predicted x_0"
						if self.config.clip_sample:
											a					     =   pred_original_sample.clamp(
											    -self.config.clip_sample_range		,       self.config.clip_sample_range		)

						# 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
						a					     =   (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon

						# 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
						a					     =   alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction

						if not return_dict:
											return (prev_sample, pred_original_sample)
						return DDIMSchedulerOutput(prev_sample=lowerCamelCase_		,       pred_original_sample=lowerCamelCase_		)




	def __len__(self		):
						"""simple docstring"""

						return self.config.num_train_timesteps
