





'''simple docstring'''

import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image

   from transformers import ViTImageProcessor
class 							__lowerCAmelCase	(       unittest.TestCase					):






       """simple docstring"""





       def __init__(				self  :						str			,					lowerCAmelCase__  :						Optional[int]			,					lowerCAmelCase__  :						int=13			,					lowerCAmelCase__  :						Any=3			,					lowerCAmelCase__  :						Optional[Any]=224			,					lowerCAmelCase__  :						str=30			,					lowerCAmelCase__  :						int=400			,					lowerCAmelCase__  :						Union[str, Any]=True			,					lowerCAmelCase__  :						Union[str, Any]=None			,					lowerCAmelCase__  :						List[str]=True			,					lowerCAmelCase__  :						int=[0.5, 0.5, 0.5]			,					lowerCAmelCase__  :						Optional[Any]=[0.5, 0.5, 0.5]			,					)       ->	str:

            '''simple docstring'''




            _UpperCamelCase							       =			size if size is not None else {'''height''': 18, '''width''': 18}
            _UpperCamelCase							       =			parent
            _UpperCamelCase							       =			batch_size
            _UpperCamelCase							       =			num_channels
            _UpperCamelCase							       =			image_size
            _UpperCamelCase							       =			min_resolution
            _UpperCamelCase							       =			max_resolution
            _UpperCamelCase							       =			do_resize
            _UpperCamelCase							       =			size
            _UpperCamelCase							       =			do_normalize
            _UpperCamelCase							       =			image_mean
            _UpperCamelCase							       =			image_std







       def snake_case__		(				self  :						Any	)       ->	str:

            '''simple docstring'''




            return {
                "image_mean": self.image_mean,
                "image_std": self.image_std,
                "do_normalize": self.do_normalize,
                "do_resize": self.do_resize,
                "size": self.size,
            }

@require_torch
@require_vision
class 							__lowerCAmelCase	(       __magic_name__		,		unittest.TestCase					):






       """simple docstring"""
       _snake_case      :	Union[str, Any]									=       ViTImageProcessor if is_vision_available() else None





       def snake_case__		(				self  :						Optional[int]	)       ->	int:

            '''simple docstring'''




            _UpperCamelCase							       =			EfficientFormerImageProcessorTester(self	)





       @property
       def snake_case__		(				self  :						Dict	)       ->	Any:

            '''simple docstring'''




            return self.image_proc_tester.prepare_image_processor_dict()





       def snake_case__		(				self  :						Dict	)       ->	Tuple:

            '''simple docstring'''




            _UpperCamelCase							       =			self.image_processing_class(**self.image_processor_dict	)
            self.assertTrue(hasattr(lowerCAmelCase__			,					'''image_mean'''	)	)
            self.assertTrue(hasattr(lowerCAmelCase__			,					'''image_std'''	)	)
            self.assertTrue(hasattr(lowerCAmelCase__			,					'''do_normalize'''	)	)
            self.assertTrue(hasattr(lowerCAmelCase__			,					'''do_resize'''	)	)
            self.assertTrue(hasattr(lowerCAmelCase__			,					'''size'''	)	)





       def snake_case__		(				self  :						Tuple	)       ->	List[Any]:

            '''simple docstring'''




            pass





       def snake_case__		(				self  :						Optional[Any]	)       ->	Optional[int]:

            '''simple docstring'''




            _UpperCamelCase							       =			self.image_processing_class(**self.image_processor_dict	)
            # create random PIL images
            _UpperCamelCase							       =			prepare_image_inputs(self.image_proc_tester			,					equal_resolution=lowerCAmelCase__	)
            for image in image_inputs:
                 self.assertIsInstance(lowerCAmelCase__			,					Image.Image	)

            # Test not batched input
            _UpperCamelCase							       =			image_processor(image_inputs[0]			,					return_tensors='''pt'''	).pixel_values
            self.assertEqual(
                encoded_images.shape			,					(
                    1,
                    self.image_proc_tester.num_channels,
                    self.image_proc_tester.size['''height'''],
                    self.image_proc_tester.size['''width'''],
                )			,					)

            # Test batched
            _UpperCamelCase							       =			image_processor(lowerCAmelCase__			,					return_tensors='''pt'''	).pixel_values
            self.assertEqual(
                encoded_images.shape			,					(
                    self.image_proc_tester.batch_size,
                    self.image_proc_tester.num_channels,
                    self.image_proc_tester.size['''height'''],
                    self.image_proc_tester.size['''width'''],
                )			,					)





       def snake_case__		(				self  :						str	)       ->	str:

            '''simple docstring'''




            _UpperCamelCase							       =			self.image_processing_class(**self.image_processor_dict	)
            # create random numpy tensors
            _UpperCamelCase							       =			prepare_image_inputs(self.image_proc_tester			,					equal_resolution=lowerCAmelCase__			,					numpify=lowerCAmelCase__	)
            for image in image_inputs:
                 self.assertIsInstance(lowerCAmelCase__			,					np.ndarray	)

            # Test not batched input
            _UpperCamelCase							       =			image_processor(image_inputs[0]			,					return_tensors='''pt'''	).pixel_values
            self.assertEqual(
                encoded_images.shape			,					(
                    1,
                    self.image_proc_tester.num_channels,
                    self.image_proc_tester.size['''height'''],
                    self.image_proc_tester.size['''width'''],
                )			,					)

            # Test batched
            _UpperCamelCase							       =			image_processor(lowerCAmelCase__			,					return_tensors='''pt'''	).pixel_values
            self.assertEqual(
                encoded_images.shape			,					(
                    self.image_proc_tester.batch_size,
                    self.image_proc_tester.num_channels,
                    self.image_proc_tester.size['''height'''],
                    self.image_proc_tester.size['''width'''],
                )			,					)







       def snake_case__		(				self  :						int	)       ->	Dict:

            '''simple docstring'''




            _UpperCamelCase							       =			self.image_processing_class(**self.image_processor_dict	)
            # create random PyTorch tensors
            _UpperCamelCase							       =			prepare_image_inputs(self.image_proc_tester			,					equal_resolution=lowerCAmelCase__			,					torchify=lowerCAmelCase__	)
            for image in image_inputs:
                 self.assertIsInstance(lowerCAmelCase__			,					torch.Tensor	)

            # Test not batched input
            _UpperCamelCase							       =			image_processor(image_inputs[0]			,					return_tensors='''pt'''	).pixel_values
            self.assertEqual(
                encoded_images.shape			,					(
                    1,
                    self.image_proc_tester.num_channels,
                    self.image_proc_tester.size['''height'''],
                    self.image_proc_tester.size['''width'''],
                )			,					)

            # Test batched
            _UpperCamelCase							       =			image_processor(lowerCAmelCase__			,					return_tensors='''pt'''	).pixel_values
            self.assertEqual(
                encoded_images.shape			,					(
                    self.image_proc_tester.batch_size,
                    self.image_proc_tester.num_channels,
                    self.image_proc_tester.size['''height'''],
                    self.image_proc_tester.size['''width'''],
                )			,					)










'''simple docstring'''

import argparse

import intel_extension_for_pytorch as ipex
import torch

from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline


lowercase__		:     int			=							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')
lowercase__		:     Union[str, Any]			=							parser.parse_args()


lowercase__		:     Union[str, Any]			=							'cpu'
lowercase__		:     Tuple			=							'a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings'

lowercase__		:     List[Any]			=							'path-to-your-trained-model'
lowercase__		:     Optional[Any]			=							StableDiffusionPipeline.from_pretrained(model_id)
if args.dpm:
   lowercase__		:     Union[str, Any]			=							DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
lowercase__		:     Dict			=							pipe.to(device)

# to channels last
lowercase__		:     Any			=							pipe.unet.to(memory_format=torch.channels_last)
lowercase__		:     Dict			=							pipe.vae.to(memory_format=torch.channels_last)
lowercase__		:     Any			=							pipe.text_encoder.to(memory_format=torch.channels_last)
if pipe.requires_safety_checker:
   lowercase__		:     Union[str, Any]			=							pipe.safety_checker.to(memory_format=torch.channels_last)

# optimize with ipex
lowercase__		:     List[str]			=							torch.randn(2, 4, 64, 64)
lowercase__		:     int			=							torch.rand(1) * 9_99
lowercase__		:     Optional[int]			=							torch.randn(2, 77, 7_68)
lowercase__		:     List[str]			=							(sample, timestep, encoder_hidden_status)
try:
   lowercase__		:     Optional[Any]			=							ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example)
except Exception:
   lowercase__		:     Any			=							ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True)
lowercase__		:     Tuple			=							ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True)
lowercase__		:     Any			=							ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True)
if pipe.requires_safety_checker:
   lowercase__		:     Union[str, Any]			=							ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True)

# compute
lowercase__		:     Optional[Any]			=							6_66
lowercase__		:     Tuple			=							torch.Generator(device).manual_seed(seed)
lowercase__		:     Dict			=							{'generator': generator}
if args.steps is not None:
   lowercase__		:     int			=							args.steps

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

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



