




import argparse

import intel_extension_for_pytorch as ipex
import torch

from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline


UpperCamelCase__					    =    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""")
UpperCamelCase__					    =    parser.parse_args()


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

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

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

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

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

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

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










import unittest

from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
					from PIL import Image
else:
					class     a__					:






											@staticmethod
											def        __SCREAMING_SNAKE_CASE(     *_A	,    **_A    ):




																"""simple docstring"""



																pass
@is_pipeline_test
@require_torch
@require_vision
class     a__					(      unittest.TestCase   ):
						_a							:					Any      =					MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING






						def        __SCREAMING_SNAKE_CASE(     self	,    _A	,    _A	,    _A    ):




											"""simple docstring"""



											__lowerCAmelCase            = pipeline("visual-question-answering"	,    model="hf-internal-testing/tiny-vilt-random-vqa"    )
											__lowerCAmelCase            = [
											    {
											        "image": Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    ),
											        "question": "How many cats are there?",
											    },
											    {
											        "image": "./tests/fixtures/tests_samples/COCO/000000039769.png",
											        "question": "How many cats are there?",
											    },
											]
											return vqa_pipeline, examples






						def        __SCREAMING_SNAKE_CASE(     self	,    _A	,    _A    ):




											"""simple docstring"""



											__lowerCAmelCase            = vqa_pipeline(_A	,    top_k=1    )
											self.assertEqual(
											    _A	,    [
											        [{"score": ANY(_A    ), "answer": ANY(_A    )}],
											        [{"score": ANY(_A    ), "answer": ANY(_A    )}],
											    ]	,    )






						@require_torch
						def        __SCREAMING_SNAKE_CASE(     self    ):




											"""simple docstring"""



											__lowerCAmelCase            = pipeline("visual-question-answering"	,    model="hf-internal-testing/tiny-vilt-random-vqa"    )
											__lowerCAmelCase            = "./tests/fixtures/tests_samples/COCO/000000039769.png"
											__lowerCAmelCase            = "How many cats are there?"

											__lowerCAmelCase            = vqa_pipeline(image=_A	,    question="How many cats are there?"	,    top_k=2    )
											self.assertEqual(
											    _A	,    [{"score": ANY(_A    ), "answer": ANY(_A    )}, {"score": ANY(_A    ), "answer": ANY(_A    )}]    )

											__lowerCAmelCase            = vqa_pipeline({"image": image, "question": question}	,    top_k=2    )
											self.assertEqual(
											    _A	,    [{"score": ANY(_A    ), "answer": ANY(_A    )}, {"score": ANY(_A    ), "answer": ANY(_A    )}]    )






						@slow
						@require_torch
						def        __SCREAMING_SNAKE_CASE(     self    ):




											"""simple docstring"""



											__lowerCAmelCase            = pipeline("visual-question-answering"	,    model="dandelin/vilt-b32-finetuned-vqa"    )
											__lowerCAmelCase            = "./tests/fixtures/tests_samples/COCO/000000039769.png"
											__lowerCAmelCase            = "How many cats are there?"

											__lowerCAmelCase            = vqa_pipeline(image=_A	,    question=_A	,    top_k=2    )
											self.assertEqual(
											    nested_simplify(_A	,    decimals=4    )	,    [{"score": 0.87_99, "answer": "2"}, {"score": 0.2_96, "answer": "1"}]    )

											__lowerCAmelCase            = vqa_pipeline({"image": image, "question": question}	,    top_k=2    )
											self.assertEqual(
											    nested_simplify(_A	,    decimals=4    )	,    [{"score": 0.87_99, "answer": "2"}, {"score": 0.2_96, "answer": "1"}]    )

											__lowerCAmelCase            = vqa_pipeline(
											    [{"image": image, "question": question}, {"image": image, "question": question}]	,    top_k=2    )
											self.assertEqual(
											    nested_simplify(_A	,    decimals=4    )	,    [[{"score": 0.87_99, "answer": "2"}, {"score": 0.2_96, "answer": "1"}]] * 2	,    )






						@require_tf
						@unittest.skip("Visual question answering not implemented in TF"    )
						def        __SCREAMING_SNAKE_CASE(     self    ):




											"""simple docstring"""



											pass




