


import tempfile
import unittest

import numpy as np
import torch

from diffusers import DiffusionPipeline
from diffusers.models.attention_processor import Attention, AttnAddedKVProcessor



class 							a       (      unittest.TestCase ):





     def 			SCREAMING_SNAKE_CASE__							(     self       :					int     ,						SCREAMING_SNAKE_CASE_       :					bool = False				):
        __lowerCamelCase:					Dict	 =						10

        if only_cross_attention:
           __lowerCamelCase:					int	 =						12
        else:
           # when only cross attention is not set, the cross attention dim must be the same as the query dim
           __lowerCamelCase:					List[str]	 =						query_dim

        return {
            "query_dim": query_dim,
            "cross_attention_dim": cross_attention_dim,
            "heads": 2,
            "dim_head": 4,
            "added_kv_proj_dim": 6,
            "norm_num_groups": 1,
            "only_cross_attention": only_cross_attention,
            "processor": AttnAddedKVProcessor(),
        }





     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[Any]     ,						SCREAMING_SNAKE_CASE_       :					int     ,						SCREAMING_SNAKE_CASE_       :					List[str]				):
        __lowerCamelCase:					Union[str, Any]	 =						2

        __lowerCamelCase:					Optional[int]	 =						torch.rand(SCREAMING_SNAKE_CASE_     ,						SCREAMING_SNAKE_CASE_     ,						3     ,						2				)
        __lowerCamelCase:					Dict	 =						torch.rand(SCREAMING_SNAKE_CASE_     ,						4     ,						SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					Optional[int]	 =						None

        return {
            "hidden_states": hidden_states,
            "encoder_hidden_states": encoder_hidden_states,
            "attention_mask": attention_mask,
        }







     def 			SCREAMING_SNAKE_CASE__							(     self       :					Tuple				):
        # self and cross attention

        torch.manual_seed(0				)

        __lowerCamelCase:					Tuple	 =						self.get_constructor_arguments(only_cross_attention=SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					Union[str, Any]	 =						Attention(**SCREAMING_SNAKE_CASE_				)

        self.assertTrue(attn.to_k is not None				)
        self.assertTrue(attn.to_v is not None				)

        __lowerCamelCase:					Optional[Any]	 =						self.get_forward_arguments(
            query_dim=constructor_args["""query_dim"""]     ,						added_kv_proj_dim=constructor_args["""added_kv_proj_dim"""]				)

        __lowerCamelCase:					Any	 =						attn(**SCREAMING_SNAKE_CASE_				)

        # only self attention

        torch.manual_seed(0				)

        __lowerCamelCase:					Any	 =						self.get_constructor_arguments(only_cross_attention=SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					Optional[int]	 =						Attention(**SCREAMING_SNAKE_CASE_				)

        self.assertTrue(attn.to_k is None				)
        self.assertTrue(attn.to_v is None				)

        __lowerCamelCase:					Tuple	 =						self.get_forward_arguments(
            query_dim=constructor_args["""query_dim"""]     ,						added_kv_proj_dim=constructor_args["""added_kv_proj_dim"""]				)

        __lowerCamelCase:					Optional[Any]	 =						attn(**SCREAMING_SNAKE_CASE_				)

        self.assertTrue((only_cross_attn_out != self_and_cross_attn_out).all()				)



class 							a       (      unittest.TestCase ):





     def 			SCREAMING_SNAKE_CASE__							(     self       :					int				):
        __lowerCamelCase:					Any	 =						DiffusionPipeline.from_pretrained("""hf-internal-testing/tiny-stable-diffusion-pipe"""     ,						safety_checker=SCREAMING_SNAKE_CASE_				)

        __lowerCamelCase:					Optional[int]	 =						pipe(
            """foo"""     ,						num_inference_steps=2     ,						generator=torch.Generator("""cpu"""				).manual_seed(0				)     ,						output_type="""np"""     ,						).images

        # the initial conversion succeeds
        __lowerCamelCase:					Optional[int]	 =						DiffusionPipeline.from_pretrained(
            """hf-internal-testing/tiny-stable-diffusion-pipe"""     ,						device_map="""sequential"""     ,						safety_checker=SCREAMING_SNAKE_CASE_				)

        __lowerCamelCase:					str	 =						pipe(
            """foo"""     ,						num_inference_steps=2     ,						generator=torch.Generator("""cpu"""				).manual_seed(0				)     ,						output_type="""np"""     ,						).images

        with tempfile.TemporaryDirectory() as tmpdir:
           # save the converted model
           pipe.save_pretrained(SCREAMING_SNAKE_CASE_				)

           # can also load the converted weights
           __lowerCamelCase:					Tuple	 =						DiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_     ,						device_map="""sequential"""     ,						safety_checker=SCREAMING_SNAKE_CASE_				)

        __lowerCamelCase:					Dict	 =						pipe(
            """foo"""     ,						num_inference_steps=2     ,						generator=torch.Generator("""cpu"""				).manual_seed(0				)     ,						output_type="""np"""     ,						).images

        self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_     ,						SCREAMING_SNAKE_CASE_     ,						atol=1E-5				)				)
        self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_     ,						SCREAMING_SNAKE_CASE_     ,						atol=1E-5				)				)






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 MobileNetVaImageProcessor



class 							a       (      unittest.TestCase ):





     def __init__(     self       :					Optional[int]     ,						SCREAMING_SNAKE_CASE_       :					str     ,						SCREAMING_SNAKE_CASE_       :					List[str]=7     ,						SCREAMING_SNAKE_CASE_       :					Union[str, Any]=3     ,						SCREAMING_SNAKE_CASE_       :					List[Any]=18     ,						SCREAMING_SNAKE_CASE_       :					List[str]=30     ,						SCREAMING_SNAKE_CASE_       :					List[Any]=400     ,						SCREAMING_SNAKE_CASE_       :					Dict=True     ,						SCREAMING_SNAKE_CASE_       :					Any=None     ,						SCREAMING_SNAKE_CASE_       :					List[str]=True     ,						SCREAMING_SNAKE_CASE_       :					Any=None     ,						):
        __lowerCamelCase:					List[Any]	 =						size if size is not None else {"""shortest_edge""": 20}
        __lowerCamelCase:					Tuple	 =						crop_size if crop_size is not None else {"""height""": 18, """width""": 18}
        __lowerCamelCase:					List[Any]	 =						parent
        __lowerCamelCase:					Optional[int]	 =						batch_size
        __lowerCamelCase:					str	 =						num_channels
        __lowerCamelCase:					Dict	 =						image_size
        __lowerCamelCase:					Tuple	 =						min_resolution
        __lowerCamelCase:					Union[str, Any]	 =						max_resolution
        __lowerCamelCase:					Tuple	 =						do_resize
        __lowerCamelCase:					List[str]	 =						size
        __lowerCamelCase:					int	 =						do_center_crop
        __lowerCamelCase:					Tuple	 =						crop_size







     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[Any]				):
        return {
            "do_resize": self.do_resize,
            "size": self.size,
            "do_center_crop": self.do_center_crop,
            "crop_size": self.crop_size,
        }



@require_torch
@require_vision
class 							a       (      _UpperCAmelCase  ,unittest.TestCase ):
     UpperCAmelCase__			:	int       =						MobileNetVaImageProcessor if is_vision_available() else None





     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[str]				):
        __lowerCamelCase:					Tuple	 =						MobileNetVaImageProcessingTester(self				)





     @property
     def 			SCREAMING_SNAKE_CASE__							(     self       :					str				):
        return self.image_processor_tester.prepare_image_processor_dict()





     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[str]				):
        __lowerCamelCase:					List[Any]	 =						self.image_processing_class(**self.image_processor_dict				)
        self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,						"""do_resize"""				)				)
        self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,						"""size"""				)				)
        self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,						"""do_center_crop"""				)				)
        self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,						"""center_crop"""				)				)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Any				):
        __lowerCamelCase:					str	 =						self.image_processing_class.from_dict(self.image_processor_dict				)
        self.assertEqual(image_processor.size     ,						{"""shortest_edge""": 20}				)
        self.assertEqual(image_processor.crop_size     ,						{"""height""": 18, """width""": 18}				)

        __lowerCamelCase:					Optional[int]	 =						self.image_processing_class.from_dict(self.image_processor_dict     ,						size=42     ,						crop_size=84				)
        self.assertEqual(image_processor.size     ,						{"""shortest_edge""": 42}				)
        self.assertEqual(image_processor.crop_size     ,						{"""height""": 84, """width""": 84}				)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[Any]				):
        pass





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[int]				):
        # Initialize image_processing
        __lowerCamelCase:					List[str]	 =						self.image_processing_class(**self.image_processor_dict				)
        # create random PIL images
        __lowerCamelCase:					str	 =						prepare_image_inputs(self.image_processor_tester     ,						equal_resolution=SCREAMING_SNAKE_CASE_				)
        for image in image_inputs:
           self.assertIsInstance(SCREAMING_SNAKE_CASE_     ,						Image.Image				)

        # Test not batched input
        __lowerCamelCase:					Optional[Any]	 =						image_processing(image_inputs[0]     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)

        # Test batched
        __lowerCamelCase:					Tuple	 =						image_processing(SCREAMING_SNAKE_CASE_     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[int]				):
        # Initialize image_processing
        __lowerCamelCase:					Union[str, Any]	 =						self.image_processing_class(**self.image_processor_dict				)
        # create random numpy tensors
        __lowerCamelCase:					Tuple	 =						prepare_image_inputs(self.image_processor_tester     ,						equal_resolution=SCREAMING_SNAKE_CASE_     ,						numpify=SCREAMING_SNAKE_CASE_				)
        for image in image_inputs:
           self.assertIsInstance(SCREAMING_SNAKE_CASE_     ,						np.ndarray				)

        # Test not batched input
        __lowerCamelCase:					List[Any]	 =						image_processing(image_inputs[0]     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)

        # Test batched
        __lowerCamelCase:					Optional[Any]	 =						image_processing(SCREAMING_SNAKE_CASE_     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)







     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[int]				):
        # Initialize image_processing
        __lowerCamelCase:					str	 =						self.image_processing_class(**self.image_processor_dict				)
        # create random PyTorch tensors
        __lowerCamelCase:					List[str]	 =						prepare_image_inputs(self.image_processor_tester     ,						equal_resolution=SCREAMING_SNAKE_CASE_     ,						torchify=SCREAMING_SNAKE_CASE_				)
        for image in image_inputs:
           self.assertIsInstance(SCREAMING_SNAKE_CASE_     ,						torch.Tensor				)

        # Test not batched input
        __lowerCamelCase:					Union[str, Any]	 =						image_processing(image_inputs[0]     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)

        # Test batched
        __lowerCamelCase:					Optional[int]	 =						image_processing(SCREAMING_SNAKE_CASE_     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)


