


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.
_snake_case             =     {'''LayoutLMv2Config''', '''LayoutLMv3Config'''}
@is_pipeline_test
class 	UpperCAmelCase_					(					unittest.TestCase    ):

   '''simple docstring'''




   __A :      Optional[int]     		=		MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
   __A :      Optional[int]     		=		TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

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






   def _snake_case    (		self						,				__A						,				__A						,				__A ):






     """simple docstring"""





     lowerCamelCase :					List[str]    =				ZeroShotClassificationPipeline(
         model=__A						,				tokenizer=__A						,				candidate_labels=["polics", "health"] )
     return classifier, ["Who are you voting for in 2020?", "My stomach hurts."]






   def _snake_case    (		self						,				__A						,				__A ):






     """simple docstring"""





     lowerCamelCase :					str    =				classifier("Who are you voting for in 2020?"						,				candidate_labels="politics" )
     self.assertEqual(__A						,				{"sequence": ANY(__A ), "labels": [ANY(__A )], "scores": [ANY(__A )]} )

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

     lowerCamelCase :					Optional[int]    =				classifier("Who are you voting for in 2020?"						,				candidate_labels=["politics"] )
     self.assertEqual(__A						,				{"sequence": ANY(__A ), "labels": [ANY(__A )], "scores": [ANY(__A )]} )

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

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

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

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

     with self.assertRaises(__A ):
       classifier(""						,				candidate_labels="politics" )

     with self.assertRaises(__A ):
       classifier(__A						,				candidate_labels="politics" )

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

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

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

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

     self.run_entailment_id(__A )






   def _snake_case    (		self						,				__A ):






     """simple docstring"""





     lowerCamelCase :					Tuple    =				zero_shot_classifier.model.config
     lowerCamelCase :					List[Any]    =				config.labelaid
     lowerCamelCase :					Optional[int]    =				zero_shot_classifier.entailment_id

     lowerCamelCase :					Union[str, Any]    =				{"LABEL_0": 0, "LABEL_1": 1, "LABEL_2": 2}
     self.assertEqual(zero_shot_classifier.entailment_id						,				-1 )

     lowerCamelCase :					List[Any]    =				{"entailment": 0, "neutral": 1, "contradiction": 2}
     self.assertEqual(zero_shot_classifier.entailment_id						,				0 )

     lowerCamelCase :					Dict    =				{"ENTAIL": 0, "NON-ENTAIL": 1}
     self.assertEqual(zero_shot_classifier.entailment_id						,				0 )

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

     lowerCamelCase :					Optional[Any]    =				original_labelaid
     self.assertEqual(__A						,				zero_shot_classifier.entailment_id )






   @require_torch
   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					Union[str, Any]    =				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 _snake_case    (		self ):






     """simple docstring"""





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

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






   @require_tf
   def _snake_case    (		self ):






     """simple docstring"""





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

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






   @slow
   @require_torch
   def _snake_case    (		self ):






     """simple docstring"""





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

     self.assertEqual(
         nested_simplify(__A )						,				{
             "sequence": "Who are you voting for in 2020?",
             "labels": ["politics", "public health", "science"],
             "scores": [0.976, 0.015, 0.009],
         }						,				)
     lowerCamelCase :					int    =				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=__A						,				)
     self.assertEqual(
         nested_simplify(__A )						,				{
             "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 _snake_case    (		self ):






     """simple docstring"""





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

     self.assertEqual(
         nested_simplify(__A )						,				{
             "sequence": "Who are you voting for in 2020?",
             "labels": ["politics", "public health", "science"],
             "scores": [0.976, 0.015, 0.009],
         }						,				)
     lowerCamelCase :					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=__A						,				)
     self.assertEqual(
         nested_simplify(__A )						,				{
             "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],
         }						,				)







import argparse

import intel_extension_for_pytorch as ipex
import torch

from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline


_snake_case             =     argparse.ArgumentParser('''Stable Diffusion script with intel optimization''', add_help=False)
parser.add_argument('''--dpm''', action='''store_true''', help='''Enable DPMSolver or not''')
parser.add_argument('''--steps''', default=None, type=int, help='''Num inference steps''')
_snake_case             =     parser.parse_args()


_snake_case             =     '''cpu'''
_snake_case             =     '''a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings'''

_snake_case             =     '''path-to-your-trained-model'''
_snake_case             =     StableDiffusionPipeline.from_pretrained(model_id)
if args.dpm:
   _snake_case             =     DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
_snake_case             =     pipe.to(device)

# to channels last
_snake_case             =     pipe.unet.to(memory_format=torch.channels_last)
_snake_case             =     pipe.vae.to(memory_format=torch.channels_last)
_snake_case             =     pipe.text_encoder.to(memory_format=torch.channels_last)
if pipe.requires_safety_checker:
   _snake_case             =     pipe.safety_checker.to(memory_format=torch.channels_last)

# optimize with ipex
_snake_case             =     torch.randn(2, 4, 64, 64)
_snake_case             =     torch.rand(1) * 9_99
_snake_case             =     torch.randn(2, 77, 7_68)
_snake_case             =     (sample, timestep, encoder_hidden_status)
try:
   _snake_case             =     ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example)
except Exception:
   _snake_case             =     ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True)
_snake_case             =     ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True)
_snake_case             =     ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True)
if pipe.requires_safety_checker:
   _snake_case             =     ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True)

# compute
_snake_case             =     6_66
_snake_case             =     torch.Generator(device).manual_seed(seed)
_snake_case             =     {'''generator''': generator}
if args.steps is not None:
   _snake_case             =     args.steps

with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa):
   _snake_case             =     pipe(prompt, **generate_kwargs).images[0]

# save image
image.save('''generated.png''')



