




import functools
import math

import flax.linen as nn
import jax
import jax.numpy as jnp


def   A		(__A  :       Union[str, Any]  ,							__A  :       List[str]  ,							__A  :       Optional[Any]  ,							__A  :       Dict  ,							__A  :       int = 4096			)  -> Dict:







     """simple docstring"""


     UpperCAmelCase_	,			UpperCAmelCase_	,			UpperCAmelCase_		=				key.shape[-3:]
     UpperCAmelCase_		=				value.shape[-1]
     UpperCAmelCase_		=				min(__A  ,							__A			)
     UpperCAmelCase_		=				query / jnp.sqrt(__A			)

     @functools.partial(jax.checkpoint  ,							prevent_cse=__A			)
     def summarize_chunk(__A  :       Any  ,							__A  :       str  ,							__A  :       Any			):
          UpperCAmelCase_		=				jnp.einsum('''...qhd,...khd->...qhk'''  ,							__A  ,							__A  ,							precision=__A			)

          UpperCAmelCase_		=				jnp.max(__A  ,							axis=-1  ,							keepdims=__A			)
          UpperCAmelCase_		=				jax.lax.stop_gradient(__A			)
          UpperCAmelCase_		=				jnp.exp(attn_weights - max_score			)

          UpperCAmelCase_		=				jnp.einsum('''...vhf,...qhv->...qhf'''  ,							__A  ,							__A  ,							precision=__A			)
          UpperCAmelCase_		=				jnp.einsum('''...qhk->...qh'''  ,							__A			)

          return (exp_values, exp_weights.sum(axis=-1			), max_score)

     def chunk_scanner(__A  :       List[str]			):
          # julienne key array
          UpperCAmelCase_		=				jax.lax.dynamic_slice(
              operand=__A  ,							start_indices=[0] * (key.ndim - 3) + [chunk_idx, 0, 0]  ,							slice_sizes=list(key.shape[:-3]			) + [key_chunk_size, num_heads, k_features]  ,							)

          # julienne value array
          UpperCAmelCase_		=				jax.lax.dynamic_slice(
              operand=__A  ,							start_indices=[0] * (value.ndim - 3) + [chunk_idx, 0, 0]  ,							slice_sizes=list(value.shape[:-3]			) + [key_chunk_size, num_heads, v_features]  ,							)

          return summarize_chunk(__A  ,							__A  ,							__A			)

     UpperCAmelCase_	,			UpperCAmelCase_	,			UpperCAmelCase_		=				jax.lax.map(f=__A  ,							xs=jnp.arange(0  ,							__A  ,							__A			)			)

     UpperCAmelCase_		=				jnp.max(__A  ,							axis=0  ,							keepdims=__A			)
     UpperCAmelCase_		=				jnp.exp(chunk_max - global_max			)

     chunk_values *= jnp.expand_dims(__A  ,							axis=-1			)
     chunk_weights *= max_diffs

     UpperCAmelCase_		=				chunk_values.sum(axis=0			)
     UpperCAmelCase_		=				jnp.expand_dims(__A  ,							-1			).sum(axis=0			)

     return all_values / all_weights


def   A		(__A  :       int  ,							__A  :       Tuple  ,							__A  :       Any  ,							__A  :       Any=jax.lax.Precision.HIGHEST  ,							__A  :       int = 1024  ,							__A  :       int = 4096			)  -> List[Any]:







     """simple docstring"""


     UpperCAmelCase_	,			UpperCAmelCase_	,			UpperCAmelCase_		=				query.shape[-3:]

     def chunk_scanner(__A  :       Optional[Any]  ,							__A  :       Union[str, Any]			):
          # julienne query array
          UpperCAmelCase_		=				jax.lax.dynamic_slice(
              operand=__A  ,							start_indices=([0] * (query.ndim - 3)) + [chunk_idx, 0, 0]  ,							slice_sizes=list(query.shape[:-3]			) + [min(__A  ,							__A			), num_heads, q_features]  ,							)

          return (
              chunk_idx + query_chunk_size,  # unused ignore it
              _query_chunk_attention(
                  query=__A  ,							key=__A  ,							value=__A  ,							precision=__A  ,							key_chunk_size=__A			),
          )

     UpperCAmelCase_	,			UpperCAmelCase_		=				jax.lax.scan(
         f=__A  ,							init=0  ,							xs=__A  ,							length=math.ceil(num_q / query_chunk_size			)			)

     return jnp.concatenate(__A  ,							axis=-3			)  # fuse the chunked result back







class __snake_case     (     nn.Module						):
   UpperCAmelCase__    :       int
   UpperCAmelCase__    :       int		=    8
   UpperCAmelCase__    :       int		=    6_4
   UpperCAmelCase__    :       float		=    0.0
   UpperCAmelCase__    :       bool		=    False
   UpperCAmelCase__    :       jnp.dtype		=    jnp.floataa







   def lowerCamelCase		( self						:		int):

        """simple docstring"""


        UpperCAmelCase_		=				self.dim_head * self.heads
        UpperCAmelCase_		=				self.dim_head**-0.5

        # Weights were exported with old names {to_q, to_k, to_v, to_out}
        UpperCAmelCase_		=				nn.Dense(_snake_case   ,		use_bias=_snake_case   ,		dtype=self.dtype   ,		name='''to_q''')
        UpperCAmelCase_		=				nn.Dense(_snake_case   ,		use_bias=_snake_case   ,		dtype=self.dtype   ,		name='''to_k''')
        UpperCAmelCase_		=				nn.Dense(_snake_case   ,		use_bias=_snake_case   ,		dtype=self.dtype   ,		name='''to_v''')

        UpperCAmelCase_		=				nn.Dense(self.query_dim   ,		dtype=self.dtype   ,		name='''to_out_0''')
        UpperCAmelCase_		=				nn.Dropout(rate=self.dropout)







   def lowerCamelCase		( self						:		Dict   ,		_snake_case						:		int):

        """simple docstring"""


        UpperCAmelCase_	,			UpperCAmelCase_	,			UpperCAmelCase_		=				tensor.shape
        UpperCAmelCase_		=				self.heads
        UpperCAmelCase_		=				tensor.reshape(_snake_case   ,		_snake_case   ,		_snake_case   ,		dim // head_size)
        UpperCAmelCase_		=				jnp.transpose(_snake_case   ,		(0, 2, 1, 3))
        UpperCAmelCase_		=				tensor.reshape(batch_size * head_size   ,		_snake_case   ,		dim // head_size)
        return tensor







   def lowerCamelCase		( self						:		int   ,		_snake_case						:		Optional[Any]):

        """simple docstring"""


        UpperCAmelCase_	,			UpperCAmelCase_	,			UpperCAmelCase_		=				tensor.shape
        UpperCAmelCase_		=				self.heads
        UpperCAmelCase_		=				tensor.reshape(batch_size // head_size   ,		_snake_case   ,		_snake_case   ,		_snake_case)
        UpperCAmelCase_		=				jnp.transpose(_snake_case   ,		(0, 2, 1, 3))
        UpperCAmelCase_		=				tensor.reshape(batch_size // head_size   ,		_snake_case   ,		dim * head_size)
        return tensor







   def __call__( self						:		List[Any]   ,		_snake_case						:		str   ,		_snake_case						:		Optional[int]=None   ,		_snake_case						:		Optional[int]=True):

        """simple docstring"""


        UpperCAmelCase_		=				hidden_states if context is None else context

        UpperCAmelCase_		=				self.query(_snake_case)
        UpperCAmelCase_		=				self.key(_snake_case)
        UpperCAmelCase_		=				self.value(_snake_case)

        UpperCAmelCase_		=				self.reshape_heads_to_batch_dim(_snake_case)
        UpperCAmelCase_		=				self.reshape_heads_to_batch_dim(_snake_case)
        UpperCAmelCase_		=				self.reshape_heads_to_batch_dim(_snake_case)

        if self.use_memory_efficient_attention:
             UpperCAmelCase_		=				query_states.transpose(1   ,		0   ,		2)
             UpperCAmelCase_		=				key_states.transpose(1   ,		0   ,		2)
             UpperCAmelCase_		=				value_states.transpose(1   ,		0   ,		2)

             # this if statement create a chunk size for each layer of the unet
             # the chunk size is equal to the query_length dimension of the deepest layer of the unet

             UpperCAmelCase_		=				query_states.shape[-3]
             if flatten_latent_dim % 64 == 0:
                  UpperCAmelCase_		=				int(flatten_latent_dim / 64)
             elif flatten_latent_dim % 16 == 0:
                  UpperCAmelCase_		=				int(flatten_latent_dim / 16)
             elif flatten_latent_dim % 4 == 0:
                  UpperCAmelCase_		=				int(flatten_latent_dim / 4)
             else:
                  UpperCAmelCase_		=				int(_snake_case)

             UpperCAmelCase_		=				jax_memory_efficient_attention(
                 _snake_case   ,		_snake_case   ,		_snake_case   ,		query_chunk_size=_snake_case   ,		key_chunk_size=4096 * 4)

             UpperCAmelCase_		=				hidden_states.transpose(1   ,		0   ,		2)
        else:
             # compute attentions
             UpperCAmelCase_		=				jnp.einsum('''b i d, b j d->b i j'''   ,		_snake_case   ,		_snake_case)
             UpperCAmelCase_		=				attention_scores * self.scale
             UpperCAmelCase_		=				nn.softmax(_snake_case   ,		axis=2)

             # attend to values
             UpperCAmelCase_		=				jnp.einsum('''b i j, b j d -> b i d'''   ,		_snake_case   ,		_snake_case)

        UpperCAmelCase_		=				self.reshape_batch_dim_to_heads(_snake_case)
        UpperCAmelCase_		=				self.proj_attn(_snake_case)
        return self.dropout_layer(_snake_case   ,		deterministic=_snake_case)







class __snake_case     (     nn.Module						):
   UpperCAmelCase__    :       int
   UpperCAmelCase__    :       int
   UpperCAmelCase__    :       int
   UpperCAmelCase__    :       float		=    0.0
   UpperCAmelCase__    :       bool		=    False
   UpperCAmelCase__    :       jnp.dtype		=    jnp.floataa
   UpperCAmelCase__    :       bool		=    False







   def lowerCamelCase		( self						:		Tuple):

        """simple docstring"""


        UpperCAmelCase_		=				FlaxAttention(
            self.dim   ,		self.n_heads   ,		self.d_head   ,		self.dropout   ,		self.use_memory_efficient_attention   ,		dtype=self.dtype)
        # cross attention
        UpperCAmelCase_		=				FlaxAttention(
            self.dim   ,		self.n_heads   ,		self.d_head   ,		self.dropout   ,		self.use_memory_efficient_attention   ,		dtype=self.dtype)
        UpperCAmelCase_		=				FlaxFeedForward(dim=self.dim   ,		dropout=self.dropout   ,		dtype=self.dtype)
        UpperCAmelCase_		=				nn.LayerNorm(epsilon=1e-5   ,		dtype=self.dtype)
        UpperCAmelCase_		=				nn.LayerNorm(epsilon=1e-5   ,		dtype=self.dtype)
        UpperCAmelCase_		=				nn.LayerNorm(epsilon=1e-5   ,		dtype=self.dtype)
        UpperCAmelCase_		=				nn.Dropout(rate=self.dropout)







   def __call__( self						:		Dict   ,		_snake_case						:		int   ,		_snake_case						:		Optional[int]   ,		_snake_case						:		List[str]=True):

        """simple docstring"""


        UpperCAmelCase_		=				hidden_states
        if self.only_cross_attention:
             UpperCAmelCase_		=				self.attna(self.norma(_snake_case)   ,		_snake_case   ,		deterministic=_snake_case)
        else:
             UpperCAmelCase_		=				self.attna(self.norma(_snake_case)   ,		deterministic=_snake_case)
        UpperCAmelCase_		=				hidden_states + residual

        # cross attention
        UpperCAmelCase_		=				hidden_states
        UpperCAmelCase_		=				self.attna(self.norma(_snake_case)   ,		_snake_case   ,		deterministic=_snake_case)
        UpperCAmelCase_		=				hidden_states + residual

        # feed forward
        UpperCAmelCase_		=				hidden_states
        UpperCAmelCase_		=				self.ff(self.norma(_snake_case)   ,		deterministic=_snake_case)
        UpperCAmelCase_		=				hidden_states + residual

        return self.dropout_layer(_snake_case   ,		deterministic=_snake_case)







class __snake_case     (     nn.Module						):
   UpperCAmelCase__    :       int
   UpperCAmelCase__    :       int
   UpperCAmelCase__    :       int
   UpperCAmelCase__    :       int		=    1
   UpperCAmelCase__    :       float		=    0.0
   UpperCAmelCase__    :       bool		=    False
   UpperCAmelCase__    :       bool		=    False
   UpperCAmelCase__    :       jnp.dtype		=    jnp.floataa
   UpperCAmelCase__    :       bool		=    False







   def lowerCamelCase		( self						:		int):

        """simple docstring"""


        UpperCAmelCase_		=				nn.GroupNorm(num_groups=32   ,		epsilon=1e-5)

        UpperCAmelCase_		=				self.n_heads * self.d_head
        if self.use_linear_projection:
             UpperCAmelCase_		=				nn.Dense(_snake_case   ,		dtype=self.dtype)
        else:
             UpperCAmelCase_		=				nn.Conv(
                 _snake_case   ,		kernel_size=(1, 1)   ,		strides=(1, 1)   ,		padding='''VALID'''   ,		dtype=self.dtype   ,		)

        UpperCAmelCase_		=				[
            FlaxBasicTransformerBlock(
                _snake_case   ,		self.n_heads   ,		self.d_head   ,		dropout=self.dropout   ,		only_cross_attention=self.only_cross_attention   ,		dtype=self.dtype   ,		use_memory_efficient_attention=self.use_memory_efficient_attention   ,		)
            for _ in range(self.depth)
        ]

        if self.use_linear_projection:
             UpperCAmelCase_		=				nn.Dense(_snake_case   ,		dtype=self.dtype)
        else:
             UpperCAmelCase_		=				nn.Conv(
                 _snake_case   ,		kernel_size=(1, 1)   ,		strides=(1, 1)   ,		padding='''VALID'''   ,		dtype=self.dtype   ,		)

        UpperCAmelCase_		=				nn.Dropout(rate=self.dropout)







   def __call__( self						:		Optional[int]   ,		_snake_case						:		List[Any]   ,		_snake_case						:		Union[str, Any]   ,		_snake_case						:		List[str]=True):

        """simple docstring"""


        UpperCAmelCase_	,			UpperCAmelCase_	,			UpperCAmelCase_	,			UpperCAmelCase_		=				hidden_states.shape
        UpperCAmelCase_		=				hidden_states
        UpperCAmelCase_		=				self.norm(_snake_case)
        if self.use_linear_projection:
             UpperCAmelCase_		=				hidden_states.reshape(_snake_case   ,		height * width   ,		_snake_case)
             UpperCAmelCase_		=				self.proj_in(_snake_case)
        else:
             UpperCAmelCase_		=				self.proj_in(_snake_case)
             UpperCAmelCase_		=				hidden_states.reshape(_snake_case   ,		height * width   ,		_snake_case)

        for transformer_block in self.transformer_blocks:
             UpperCAmelCase_		=				transformer_block(_snake_case   ,		_snake_case   ,		deterministic=_snake_case)

        if self.use_linear_projection:
             UpperCAmelCase_		=				self.proj_out(_snake_case)
             UpperCAmelCase_		=				hidden_states.reshape(_snake_case   ,		_snake_case   ,		_snake_case   ,		_snake_case)
        else:
             UpperCAmelCase_		=				hidden_states.reshape(_snake_case   ,		_snake_case   ,		_snake_case   ,		_snake_case)
             UpperCAmelCase_		=				self.proj_out(_snake_case)

        UpperCAmelCase_		=				hidden_states + residual
        return self.dropout_layer(_snake_case   ,		deterministic=_snake_case)







class __snake_case     (     nn.Module						):
   UpperCAmelCase__    :       int
   UpperCAmelCase__    :       float		=    0.0
   UpperCAmelCase__    :       jnp.dtype		=    jnp.floataa







   def lowerCamelCase		( self						:		List[Any]):

        """simple docstring"""


        UpperCAmelCase_		=				FlaxGEGLU(self.dim   ,		self.dropout   ,		self.dtype)
        UpperCAmelCase_		=				nn.Dense(self.dim   ,		dtype=self.dtype)







   def __call__( self						:		List[str]   ,		_snake_case						:		Optional[Any]   ,		_snake_case						:		int=True):

        """simple docstring"""


        UpperCAmelCase_		=				self.net_a(_snake_case   ,		deterministic=_snake_case)
        UpperCAmelCase_		=				self.net_a(_snake_case)
        return hidden_states







class __snake_case     (     nn.Module						):
   UpperCAmelCase__    :       int
   UpperCAmelCase__    :       float		=    0.0
   UpperCAmelCase__    :       jnp.dtype		=    jnp.floataa







   def lowerCamelCase		( self						:		str):

        """simple docstring"""


        UpperCAmelCase_		=				self.dim * 4
        UpperCAmelCase_		=				nn.Dense(inner_dim * 2   ,		dtype=self.dtype)
        UpperCAmelCase_		=				nn.Dropout(rate=self.dropout)







   def __call__( self						:		Union[str, Any]   ,		_snake_case						:		str   ,		_snake_case						:		str=True):

        """simple docstring"""


        UpperCAmelCase_		=				self.proj(_snake_case)
        UpperCAmelCase_	,			UpperCAmelCase_		=				jnp.split(_snake_case   ,		2   ,		axis=2)
        return self.dropout_layer(hidden_linear * nn.gelu(_snake_case)   ,		deterministic=_snake_case)












import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPImageProcessor, CLIPVisionConfig

from diffusers import AutoencoderKL, PaintByExamplePipeline, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.paint_by_example import PaintByExampleImageEncoder
from diffusers.utils import floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import IMAGE_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, IMAGE_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class __snake_case     (     a					,    unittest.TestCase						):
   UpperCAmelCase__    :       str		=    PaintByExamplePipeline
   UpperCAmelCase__    :       Tuple		=    IMAGE_GUIDED_IMAGE_INPAINTING_PARAMS
   UpperCAmelCase__    :       Any		=    IMAGE_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
   UpperCAmelCase__    :       Union[str, Any]		=    frozenset([]						)  # TO_DO: update the image_prams once refactored VaeImageProcessor.preprocess







   def lowerCamelCase		( self						:		Optional[Any]):

        """simple docstring"""


        torch.manual_seed(0)
        UpperCAmelCase_		=				UNetaDConditionModel(
            block_out_channels=(32, 64)   ,		layers_per_block=2   ,		sample_size=32   ,		in_channels=9   ,		out_channels=4   ,		down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')   ,		up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')   ,		cross_attention_dim=32   ,		)
        UpperCAmelCase_		=				PNDMScheduler(skip_prk_steps=_snake_case)
        torch.manual_seed(0)
        UpperCAmelCase_		=				AutoencoderKL(
            block_out_channels=[32, 64]   ,		in_channels=3   ,		out_channels=3   ,		down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']   ,		up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']   ,		latent_channels=4   ,		)
        torch.manual_seed(0)
        UpperCAmelCase_		=				CLIPVisionConfig(
            hidden_size=32   ,		projection_dim=32   ,		intermediate_size=37   ,		layer_norm_eps=1e-05   ,		num_attention_heads=4   ,		num_hidden_layers=5   ,		image_size=32   ,		patch_size=4   ,		)
        UpperCAmelCase_		=				PaintByExampleImageEncoder(_snake_case   ,		proj_size=32)
        UpperCAmelCase_		=				CLIPImageProcessor(crop_size=32   ,		size=32)

        UpperCAmelCase_		=				{
            '''unet''': unet,
            '''scheduler''': scheduler,
            '''vae''': vae,
            '''image_encoder''': image_encoder,
            '''safety_checker''': None,
            '''feature_extractor''': feature_extractor,
        }
        return components







   def lowerCamelCase		( self						:		Optional[Any]   ,		_snake_case						:		List[str]):

        """simple docstring"""


        UpperCAmelCase_		=				np.array(image.convert('''RGB'''))
        UpperCAmelCase_		=				image[None].transpose(0   ,		3   ,		1   ,		2)
        UpperCAmelCase_		=				torch.from_numpy(_snake_case).to(dtype=torch.floataa) / 1_2_7.5 - 1.0
        return image







   def lowerCamelCase		( self						:		Tuple   ,		_snake_case						:		Dict="cpu"   ,		_snake_case						:		int=0):

        """simple docstring"""


        UpperCAmelCase_		=				floats_tensor((1, 3, 32, 32)   ,		rng=random.Random(_snake_case)).to(_snake_case)
        UpperCAmelCase_		=				image.cpu().permute(0   ,		2   ,		3   ,		1)[0]
        UpperCAmelCase_		=				Image.fromarray(np.uinta(_snake_case)).convert('''RGB''').resize((64, 64))
        UpperCAmelCase_		=				Image.fromarray(np.uinta(image + 4)).convert('''RGB''').resize((64, 64))
        UpperCAmelCase_		=				Image.fromarray(np.uinta(_snake_case)).convert('''RGB''').resize((32, 32))

        if str(_snake_case).startswith('''mps'''):
             UpperCAmelCase_		=				torch.manual_seed(_snake_case)
        else:
             UpperCAmelCase_		=				torch.Generator(device=_snake_case).manual_seed(_snake_case)
        UpperCAmelCase_		=				{
            '''example_image''': example_image,
            '''image''': init_image,
            '''mask_image''': mask_image,
            '''generator''': generator,
            '''num_inference_steps''': 2,
            '''guidance_scale''': 6.0,
            '''output_type''': '''numpy''',
        }
        return inputs







   def lowerCamelCase		( self						:		Any):

        """simple docstring"""


        UpperCAmelCase_		=				self.get_dummy_components()

        # make sure here that pndm scheduler skips prk
        UpperCAmelCase_		=				PaintByExamplePipeline(**_snake_case)
        UpperCAmelCase_		=				pipe.to('''cpu''')
        pipe.set_progress_bar_config(disable=_snake_case)

        UpperCAmelCase_		=				self.get_dummy_inputs()
        UpperCAmelCase_		=				pipe(**_snake_case)
        UpperCAmelCase_		=				output.images

        UpperCAmelCase_		=				image[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
        UpperCAmelCase_		=				np.array([0.4_6_8_6, 0.5_6_8_7, 0.4_0_0_7, 0.5_2_1_8, 0.5_7_4_1, 0.4_4_8_2, 0.4_9_4_0, 0.4_6_2_9, 0.4_5_0_3])

        assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2







   def lowerCamelCase		( self						:		Optional[Any]):

        """simple docstring"""


        UpperCAmelCase_		=				'''cpu'''
        UpperCAmelCase_		=				self.get_dummy_inputs()
        inputs.pop('''mask_image''')
        UpperCAmelCase_		=				self.convert_to_pt(inputs.pop('''image'''))
        UpperCAmelCase_		=				image.clamp(0   ,		1) / 2

        # make sure here that pndm scheduler skips prk
        UpperCAmelCase_		=				PaintByExamplePipeline(**self.get_dummy_components())
        UpperCAmelCase_		=				pipe.to(_snake_case)
        pipe.set_progress_bar_config(disable=_snake_case)

        UpperCAmelCase_		=				pipe(image=_snake_case   ,		mask_image=mask_image[:, 0]   ,		**_snake_case)
        UpperCAmelCase_		=				output.images

        UpperCAmelCase_		=				image.cpu().permute(0   ,		2   ,		3   ,		1)[0]
        UpperCAmelCase_		=				mask_image.cpu().permute(0   ,		2   ,		3   ,		1)[0]

        UpperCAmelCase_		=				Image.fromarray(np.uinta(_snake_case)).convert('''RGB''')
        UpperCAmelCase_		=				Image.fromarray(np.uinta(_snake_case)).convert('''RGB''')

        UpperCAmelCase_		=				pipe(**self.get_dummy_inputs())
        UpperCAmelCase_		=				output.images

        assert out_a.shape == (1, 64, 64, 3)
        assert np.abs(out_a.flatten() - out_a.flatten()).max() < 5e-2







   def lowerCamelCase		( self						:		Any):

        """simple docstring"""


        super().test_inference_batch_single_identical(expected_max_diff=3e-3)







@slow
@require_torch_gpu
class __snake_case     (     unittest.TestCase						):







   def lowerCamelCase		( self						:		Union[str, Any]):

        """simple docstring"""


        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()







   def lowerCamelCase		( self						:		Tuple):

        """simple docstring"""


        UpperCAmelCase_		=				load_image(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
            '''/paint_by_example/dog_in_bucket.png''')
        UpperCAmelCase_		=				load_image(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
            '''/paint_by_example/mask.png''')
        UpperCAmelCase_		=				load_image(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
            '''/paint_by_example/panda.jpg''')

        UpperCAmelCase_		=				PaintByExamplePipeline.from_pretrained('''Fantasy-Studio/Paint-by-Example''')
        UpperCAmelCase_		=				pipe.to(_snake_case)
        pipe.set_progress_bar_config(disable=_snake_case)

        UpperCAmelCase_		=				torch.manual_seed(321)
        UpperCAmelCase_		=				pipe(
            image=_snake_case   ,		mask_image=_snake_case   ,		example_image=_snake_case   ,		generator=_snake_case   ,		guidance_scale=5.0   ,		num_inference_steps=50   ,		output_type='''np'''   ,		)

        UpperCAmelCase_		=				output.images

        UpperCAmelCase_		=				image[0, -3:, -3:, -1]

        assert image.shape == (1, 512, 512, 3)
        UpperCAmelCase_		=				np.array([0.4_8_3_4, 0.4_8_1_1, 0.4_8_7_4, 0.5_1_2_2, 0.5_0_8_1, 0.5_1_4_4, 0.5_2_9_1, 0.5_2_9_0, 0.5_3_7_4])

        assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2






