

import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import BlenderbotSmallConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
  import os

  # The slow tests are often failing with OOM error on GPU
  # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
  # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
  SCREAMING_SNAKE_CASE 							=						'platform'

  import jax
  import jax.numpy as jnp

  from transformers.models.blenderbot_small.modeling_flax_blenderbot_small import (
      FlaxBlenderbotSmallForConditionalGeneration,
      FlaxBlenderbotSmallModel,
      shift_tokens_right,
  )

def      _lowerCamelCase	(						__A    :							int		,		__A    :							List[str]		,		__A    :							int=None		,		__A    :							List[str]=None		,		__A    :							Optional[int]=None		,		__A    :							int=None		,		__A    :							Optional[Any]=None		,		__A    :							Dict=None		,		)      ->					Any:
    if attention_mask is None:
        _UpperCAmelCase				:      str			  =				np.where(input_ids != config.pad_token_id		,		1		,		0 )
    if decoder_attention_mask is None:
        _UpperCAmelCase				:      Optional[Any]			  =				np.where(decoder_input_ids != config.pad_token_id		,		1		,		0 )
    if head_mask is None:
        _UpperCAmelCase				:      Dict			  =				np.ones((config.encoder_layers, config.encoder_attention_heads) )
    if decoder_head_mask is None:
        _UpperCAmelCase				:      int			  =				np.ones((config.decoder_layers, config.decoder_attention_heads) )
    if cross_attn_head_mask is None:
        _UpperCAmelCase				:      Any			  =				np.ones((config.decoder_layers, config.decoder_attention_heads) )
    return {
        "input_ids": input_ids,
        "decoder_input_ids": decoder_input_ids,
        "attention_mask": attention_mask,
        "decoder_attention_mask": attention_mask,
    }
class 							A_    :






 '''simple docstring'''




 def __init__(	self							,  _A							,  _A=13							,  _A=7							,  _A=True							,  _A=False							,  _A=99							,  _A=16							,  _A=2							,  _A=4							,  _A=4							,  _A="gelu"							,  _A=0.1							,  _A=0.1							,  _A=32							,  _A=2							,  _A=1							,  _A=0							,  _A=0.02							,  ) ->		Any:

     """simple docstring"""



     _UpperCAmelCase				:      List[str]			  =				parent
     _UpperCAmelCase				:      List[str]			  =				batch_size
     _UpperCAmelCase				:      Tuple			  =				seq_length
     _UpperCAmelCase				:      Any			  =				is_training
     _UpperCAmelCase				:      Dict			  =				use_labels
     _UpperCAmelCase				:      int			  =				vocab_size
     _UpperCAmelCase				:      List[Any]			  =				hidden_size
     _UpperCAmelCase				:      Any			  =				num_hidden_layers
     _UpperCAmelCase				:      List[Any]			  =				num_attention_heads
     _UpperCAmelCase				:      str			  =				intermediate_size
     _UpperCAmelCase				:      str			  =				hidden_act
     _UpperCAmelCase				:      Optional[Any]			  =				hidden_dropout_prob
     _UpperCAmelCase				:      Any			  =				attention_probs_dropout_prob
     _UpperCAmelCase				:      Optional[Any]			  =				max_position_embeddings
     _UpperCAmelCase				:      str			  =				eos_token_id
     _UpperCAmelCase				:      List[str]			  =				pad_token_id
     _UpperCAmelCase				:      str			  =				bos_token_id
     _UpperCAmelCase				:      Optional[int]			  =				initializer_range


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

     """simple docstring"""



     _UpperCAmelCase				:      Tuple			  =				np.clip(ids_tensor([self.batch_size, self.seq_length - 1]							,  self.vocab_size)							,  3							,  self.vocab_size)
     _UpperCAmelCase				:      List[str]			  =				np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)							,  dtype=np.intaa))							,  -1)

     _UpperCAmelCase				:      List[str]			  =				shift_tokens_right(_snake_case							,  1							,  2)

     _UpperCAmelCase				:      List[Any]			  =				BlenderbotSmallConfig(
         vocab_size=self.vocab_size							,  d_model=self.hidden_size							,  encoder_layers=self.num_hidden_layers							,  decoder_layers=self.num_hidden_layers							,  encoder_attention_heads=self.num_attention_heads							,  decoder_attention_heads=self.num_attention_heads							,  encoder_ffn_dim=self.intermediate_size							,  decoder_ffn_dim=self.intermediate_size							,  dropout=self.hidden_dropout_prob							,  attention_dropout=self.attention_probs_dropout_prob							,  max_position_embeddings=self.max_position_embeddings							,  eos_token_id=self.eos_token_id							,  bos_token_id=self.bos_token_id							,  pad_token_id=self.pad_token_id							,  initializer_range=self.initializer_range							,  use_cache=_snake_case							,  )
     _UpperCAmelCase				:      List[Any]			  =				prepare_blenderbot_inputs_dict(_snake_case							,  _snake_case							,  _snake_case)
     return config, inputs_dict


 def  snake_case__				(	self) ->		Any:

     """simple docstring"""



     _UpperCAmelCase  , _UpperCAmelCase				:      str			  =				self.prepare_config_and_inputs()
     return config, inputs_dict


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

     """simple docstring"""



     _UpperCAmelCase				:      str			  =				20
     _UpperCAmelCase				:      Any			  =				model_class_name(_snake_case)

     _UpperCAmelCase				:      Any			  =				model.encode(inputs_dict['''input_ids'''])

     _UpperCAmelCase  , _UpperCAmelCase				:      str			  =				(
         inputs_dict['''decoder_input_ids'''],
         inputs_dict['''decoder_attention_mask'''],
     )

     _UpperCAmelCase				:      Union[str, Any]			  =				model.init_cache(decoder_input_ids.shape[0]							,  _snake_case							,  _snake_case)
     _UpperCAmelCase				:      int			  =				jnp.ones((decoder_input_ids.shape[0], max_decoder_length)							,  dtype='''i4''')

     _UpperCAmelCase				:      int			  =				jnp.broadcast_to(
         jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :]							,  (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)							,  )
     _UpperCAmelCase				:      Tuple			  =				model.decode(
         decoder_input_ids[:, :-1]							,  _snake_case							,  decoder_attention_mask=_snake_case							,  past_key_values=_snake_case							,  decoder_position_ids=_snake_case							,  )

     _UpperCAmelCase				:      List[Any]			  =				jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]							,  dtype='''i4''')
     _UpperCAmelCase				:      List[Any]			  =				model.decode(
         decoder_input_ids[:, -1:]							,  _snake_case							,  decoder_attention_mask=_snake_case							,  past_key_values=outputs_cache.past_key_values							,  decoder_position_ids=_snake_case							,  )

     _UpperCAmelCase				:      Optional[int]			  =				model.decode(_snake_case							,  _snake_case)

     _UpperCAmelCase				:      int			  =				np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
     self.parent.assertTrue(diff < 1e-3							,  msg=f'''Max diff is {diff}''')


 def  snake_case__				(	self							,  _A							,  _A							,  _A) ->		Any:

     """simple docstring"""



     _UpperCAmelCase				:      str			  =				20
     _UpperCAmelCase				:      Union[str, Any]			  =				model_class_name(_snake_case)

     _UpperCAmelCase				:      int			  =				model.encode(inputs_dict['''input_ids'''])

     _UpperCAmelCase  , _UpperCAmelCase				:      Optional[Any]			  =				(
         inputs_dict['''decoder_input_ids'''],
         inputs_dict['''decoder_attention_mask'''],
     )

     _UpperCAmelCase				:      List[Any]			  =				jnp.concatenate(
         [
             decoder_attention_mask,
             jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])),
         ]							,  axis=-1							,  )

     _UpperCAmelCase				:      Any			  =				model.init_cache(decoder_input_ids.shape[0]							,  _snake_case							,  _snake_case)
     _UpperCAmelCase				:      Optional[Any]			  =				jnp.broadcast_to(
         jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :]							,  (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)							,  )

     _UpperCAmelCase				:      str			  =				model.decode(
         decoder_input_ids[:, :-1]							,  _snake_case							,  decoder_attention_mask=_snake_case							,  past_key_values=_snake_case							,  decoder_position_ids=_snake_case							,  )
     _UpperCAmelCase				:      Optional[Any]			  =				jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]							,  dtype='''i4''')
     _UpperCAmelCase				:      Tuple			  =				model.decode(
         decoder_input_ids[:, -1:]							,  _snake_case							,  past_key_values=outputs_cache.past_key_values							,  decoder_attention_mask=_snake_case							,  decoder_position_ids=_snake_case							,  )

     _UpperCAmelCase				:      Any			  =				model.decode(_snake_case							,  _snake_case							,  decoder_attention_mask=_snake_case)

     _UpperCAmelCase				:      Optional[Any]			  =				np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
     self.parent.assertTrue(diff < 1e-3							,  msg=f'''Max diff is {diff}''')



@require_flax
class 							A_    (						unittest.TestCase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			Any =					9_9


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

     """simple docstring"""



     _UpperCAmelCase				:      Optional[int]			  =				np.array(
         [
             [71, 82, 18, 33, 46, 91, 2],
             [68, 34, 26, 58, 30, 82, 2],
             [5, 97, 17, 39, 94, 40, 2],
             [76, 83, 94, 25, 70, 78, 2],
             [87, 59, 41, 35, 48, 66, 2],
             [55, 13, 16, 58, 5, 2, 1],  # note padding
             [64, 27, 31, 51, 12, 75, 2],
             [52, 64, 86, 17, 83, 39, 2],
             [48, 61, 9, 24, 71, 82, 2],
             [26, 1, 60, 48, 22, 13, 2],
             [21, 5, 62, 28, 14, 76, 2],
             [45, 98, 37, 86, 59, 48, 2],
             [70, 70, 50, 9, 28, 0, 2],
         ]							,  dtype=np.intaa							,  )

     _UpperCAmelCase				:      int			  =				input_ids.shape[0]
     _UpperCAmelCase				:      List[str]			  =				BlenderbotSmallConfig(
         vocab_size=self.vocab_size							,  d_model=24							,  encoder_layers=2							,  decoder_layers=2							,  encoder_attention_heads=2							,  decoder_attention_heads=2							,  encoder_ffn_dim=32							,  decoder_ffn_dim=32							,  max_position_embeddings=48							,  eos_token_id=2							,  pad_token_id=1							,  bos_token_id=0							,  )
     return config, input_ids, batch_size


 def  snake_case__				(	self) ->		List[str]:

     """simple docstring"""



     _UpperCAmelCase  , _UpperCAmelCase  , _UpperCAmelCase				:      List[str]			  =				self._get_config_and_data()
     _UpperCAmelCase				:      Optional[Any]			  =				FlaxBlenderbotSmallForConditionalGeneration(_snake_case)
     _UpperCAmelCase				:      Union[str, Any]			  =				lm_model(input_ids=_snake_case)
     _UpperCAmelCase				:      str			  =				(batch_size, input_ids.shape[1], config.vocab_size)
     self.assertEqual(outputs['''logits'''].shape							,  _snake_case)


 def  snake_case__				(	self) ->		Dict:

     """simple docstring"""



     _UpperCAmelCase				:      Union[str, Any]			  =				BlenderbotSmallConfig(
         vocab_size=self.vocab_size							,  d_model=14							,  encoder_layers=2							,  decoder_layers=2							,  encoder_attention_heads=2							,  decoder_attention_heads=2							,  encoder_ffn_dim=8							,  decoder_ffn_dim=8							,  max_position_embeddings=48							,  )
     _UpperCAmelCase				:      Union[str, Any]			  =				FlaxBlenderbotSmallForConditionalGeneration(_snake_case)
     _UpperCAmelCase				:      Tuple			  =				np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]]							,  dtype=np.intaa)
     _UpperCAmelCase				:      List[Any]			  =				np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]]							,  dtype=np.intaa)
     _UpperCAmelCase				:      int			  =				lm_model(input_ids=_snake_case							,  decoder_input_ids=_snake_case)
     _UpperCAmelCase				:      Any			  =				(*summary.shape, config.vocab_size)
     self.assertEqual(outputs['''logits'''].shape							,  _snake_case)


 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     _UpperCAmelCase				:      Union[str, Any]			  =				np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]]							,  dtype=np.intaa)
     _UpperCAmelCase				:      Tuple			  =				shift_tokens_right(_snake_case							,  1							,  2)
     _UpperCAmelCase				:      List[str]			  =				np.equal(_snake_case							,  1).astype(np.floataa).sum()
     _UpperCAmelCase				:      Tuple			  =				np.equal(_snake_case							,  1).astype(np.floataa).sum()
     self.assertEqual(shifted.shape							,  input_ids.shape)
     self.assertEqual(_snake_case							,  n_pad_before - 1)
     self.assertTrue(np.equal(shifted[:, 0]							,  2).all())



@require_flax
class 							A_    (						UpperCAmelCase_ ,   unittest.TestCase ,   UpperCAmelCase_			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			List[str] =					True
 _SCREAMING_SNAKE_CASE							:			Union[str, Any] =					(
     (
         FlaxBlenderbotSmallModel,
         FlaxBlenderbotSmallForConditionalGeneration,
     )
     if is_flax_available()
     else ()
 )
 _SCREAMING_SNAKE_CASE							:			int =					(FlaxBlenderbotSmallForConditionalGeneration,) if is_flax_available() else ()


 def  snake_case__				(	self) ->		Tuple:

     """simple docstring"""



     _UpperCAmelCase				:      Union[str, Any]			  =				FlaxBlenderbotSmallModelTester(self)


 def  snake_case__				(	self) ->		str:

     """simple docstring"""



     _UpperCAmelCase  , _UpperCAmelCase				:      List[str]			  =				self.model_tester.prepare_config_and_inputs()
     for model_class in self.all_model_classes:
         self.model_tester.check_use_cache_forward(_snake_case							,  _snake_case							,  _snake_case)


 def  snake_case__				(	self) ->		str:

     """simple docstring"""



     _UpperCAmelCase  , _UpperCAmelCase				:      Union[str, Any]			  =				self.model_tester.prepare_config_and_inputs()
     for model_class in self.all_model_classes:
         self.model_tester.check_use_cache_forward_with_attn_mask(_snake_case							,  _snake_case							,  _snake_case)


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

     """simple docstring"""



     _UpperCAmelCase  , _UpperCAmelCase				:      str			  =				self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         with self.subTest(model_class.__name__):
             _UpperCAmelCase				:      Tuple			  =				self._prepare_for_class(_snake_case							,  _snake_case)
             _UpperCAmelCase				:      Optional[Any]			  =				model_class(_snake_case)

             @jax.jit
             def encode_jitted(_A							,  _A=None							,  **_A):
                 return model.encode(input_ids=_snake_case							,  attention_mask=_snake_case)

             with self.subTest('''JIT Enabled'''):
                 _UpperCAmelCase				:      Optional[int]			  =				encode_jitted(**_snake_case).to_tuple()

             with self.subTest('''JIT Disabled'''):
                 with jax.disable_jit():
                     _UpperCAmelCase				:      Any			  =				encode_jitted(**_snake_case).to_tuple()

             self.assertEqual(len(_snake_case)							,  len(_snake_case))
             for jitted_output, output in zip(_snake_case							,  _snake_case):
                 self.assertEqual(jitted_output.shape							,  output.shape)


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

     """simple docstring"""



     _UpperCAmelCase  , _UpperCAmelCase				:      int			  =				self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         with self.subTest(model_class.__name__):
             _UpperCAmelCase				:      Tuple			  =				model_class(_snake_case)
             _UpperCAmelCase				:      Tuple			  =				model.encode(inputs_dict['''input_ids''']							,  inputs_dict['''attention_mask'''])

             _UpperCAmelCase				:      Any			  =				{
                 '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''],
                 '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''],
                 '''encoder_outputs''': encoder_outputs,
             }

             @jax.jit
             def decode_jitted(_A							,  _A							,  _A):
                 return model.decode(
                     decoder_input_ids=_snake_case							,  decoder_attention_mask=_snake_case							,  encoder_outputs=_snake_case							,  )

             with self.subTest('''JIT Enabled'''):
                 _UpperCAmelCase				:      Any			  =				decode_jitted(**_snake_case).to_tuple()

             with self.subTest('''JIT Disabled'''):
                 with jax.disable_jit():
                     _UpperCAmelCase				:      Union[str, Any]			  =				decode_jitted(**_snake_case).to_tuple()

             self.assertEqual(len(_snake_case)							,  len(_snake_case))
             for jitted_output, output in zip(_snake_case							,  _snake_case):
                 self.assertEqual(jitted_output.shape							,  output.shape)


 @slow
 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     for model_class_name in self.all_model_classes:
         _UpperCAmelCase				:      str			  =				model_class_name.from_pretrained('''facebook/blenderbot_small-90M''')
         # FlaxBlenderbotForSequenceClassification expects eos token in input_ids
         _UpperCAmelCase				:      Union[str, Any]			  =				np.ones((1, 1)) * model.config.eos_token_id
         _UpperCAmelCase				:      Optional[int]			  =				model(_snake_case)
         self.assertIsNotNone(_snake_case)












import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()
class 							A_    (						__lowercase ,   __lowercase ,   unittest.TestCase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			Dict =					StableDiffusionXLImgaImgPipeline
 _SCREAMING_SNAKE_CASE							:			Any =					TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
 _SCREAMING_SNAKE_CASE							:			List[Any] =					PipelineTesterMixin.required_optional_params - {"latents"}
 _SCREAMING_SNAKE_CASE							:			Dict =					TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
 _SCREAMING_SNAKE_CASE							:			List[Any] =					IMAGE_TO_IMAGE_IMAGE_PARAMS
 _SCREAMING_SNAKE_CASE							:			Dict =					IMAGE_TO_IMAGE_IMAGE_PARAMS


 def  snake_case__				(	self) ->		Tuple:

     """simple docstring"""



     torch.manual_seed(0)
     _UpperCAmelCase				:      Tuple			  =				UNetaDConditionModel(
         block_out_channels=(32, 64)							,  layers_per_block=2							,  sample_size=32							,  in_channels=4							,  out_channels=4							,  down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')							,  up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')							,  attention_head_dim=(2, 4)							,  use_linear_projection=_A							,  addition_embed_type='''text_time'''							,  addition_time_embed_dim=8							,  transformer_layers_per_block=(1, 2)							,  projection_class_embeddings_input_dim=80							,  cross_attention_dim=64							,  )
     _UpperCAmelCase				:      int			  =				EulerDiscreteScheduler(
         beta_start=0.00085							,  beta_end=0.012							,  steps_offset=1							,  beta_schedule='''scaled_linear'''							,  timestep_spacing='''leading'''							,  )
     torch.manual_seed(0)
     _UpperCAmelCase				:      Optional[int]			  =				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							,  sample_size=128							,  )
     torch.manual_seed(0)
     _UpperCAmelCase				:      Tuple			  =				CLIPTextConfig(
         bos_token_id=0							,  eos_token_id=2							,  hidden_size=32							,  intermediate_size=37							,  layer_norm_eps=1e-05							,  num_attention_heads=4							,  num_hidden_layers=5							,  pad_token_id=1							,  vocab_size=1000							,  hidden_act='''gelu'''							,  projection_dim=32							,  )
     _UpperCAmelCase				:      int			  =				CLIPTextModel(_A)
     _UpperCAmelCase				:      Tuple			  =				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''							,  local_files_only=_A)

     _UpperCAmelCase				:      int			  =				CLIPTextModelWithProjection(_A)
     _UpperCAmelCase				:      Optional[int]			  =				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''							,  local_files_only=_A)

     _UpperCAmelCase				:      Any			  =				{
         '''unet''': unet,
         '''scheduler''': scheduler,
         '''vae''': vae,
         '''text_encoder''': text_encoder,
         '''tokenizer''': tokenizer,
         '''text_encoder_2''': text_encoder_a,
         '''tokenizer_2''': tokenizer_a,
         # "safety_checker": None,
         # "feature_extractor": None,
     }
     return components


 def  snake_case__				(	self							,  _A							,  _A=0) ->		List[Any]:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[int]			  =				floats_tensor((1, 3, 32, 32)							,  rng=random.Random(_A)).to(_A)
     _UpperCAmelCase				:      List[Any]			  =				image / 2 + 0.5
     if str(_A).startswith('''mps'''):
         _UpperCAmelCase				:      Union[str, Any]			  =				torch.manual_seed(_A)
     else:
         _UpperCAmelCase				:      List[str]			  =				torch.Generator(device=_A).manual_seed(_A)
     _UpperCAmelCase				:      Tuple			  =				{
         '''prompt''': '''A painting of a squirrel eating a burger''',
         '''image''': image,
         '''generator''': generator,
         '''num_inference_steps''': 2,
         '''guidance_scale''': 5.0,
         '''output_type''': '''numpy''',
         '''strength''': 0.75,
     }
     return inputs


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

     """simple docstring"""



     _UpperCAmelCase				:      Any			  =				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
     _UpperCAmelCase				:      Optional[Any]			  =				self.get_dummy_components()
     _UpperCAmelCase				:      Any			  =				StableDiffusionXLImgaImgPipeline(**_A)
     _UpperCAmelCase				:      List[str]			  =				sd_pipe.to(_A)
     sd_pipe.set_progress_bar_config(disable=_A)

     _UpperCAmelCase				:      Tuple			  =				self.get_dummy_inputs(_A)
     _UpperCAmelCase				:      Any			  =				sd_pipe(**_A).images
     _UpperCAmelCase				:      Any			  =				image[0, -3:, -3:, -1]

     assert image.shape == (1, 32, 32, 3)

     _UpperCAmelCase				:      Optional[Any]			  =				np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165])

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


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

     """simple docstring"""



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


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

     """simple docstring"""



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


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

     """simple docstring"""



     pass


 def  snake_case__				(	self) ->		Union[str, Any]:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[Any]			  =				self.get_dummy_components()
     _UpperCAmelCase				:      str			  =				StableDiffusionXLImgaImgPipeline(**_A)
     _UpperCAmelCase				:      Any			  =				sd_pipe.to(_A)
     _UpperCAmelCase				:      Tuple			  =				sd_pipe.to(_A)
     sd_pipe.set_progress_bar_config(disable=_A)

     # forward without prompt embeds
     _UpperCAmelCase				:      str			  =				self.get_dummy_inputs(_A)
     _UpperCAmelCase				:      Optional[Any]			  =				3 * ['''this is a negative prompt''']
     _UpperCAmelCase				:      Optional[int]			  =				negative_prompt
     _UpperCAmelCase				:      Optional[int]			  =				3 * [inputs['''prompt''']]

     _UpperCAmelCase				:      Optional[Any]			  =				sd_pipe(**_A)
     _UpperCAmelCase				:      Any			  =				output.images[0, -3:, -3:, -1]

     # forward with prompt embeds
     _UpperCAmelCase				:      Dict			  =				self.get_dummy_inputs(_A)
     _UpperCAmelCase				:      Optional[Any]			  =				3 * ['''this is a negative prompt''']
     _UpperCAmelCase				:      Dict			  =				3 * [inputs.pop('''prompt''')]

     (
         (
         _UpperCAmelCase
     )  , (
         _UpperCAmelCase
     )  , (
         _UpperCAmelCase
     )  , (
         _UpperCAmelCase
     )  , 
     )				:      str			  =				sd_pipe.encode_prompt(_A							,  negative_prompt=_A)

     _UpperCAmelCase				:      str			  =				sd_pipe(
         **_A							,  prompt_embeds=_A							,  negative_prompt_embeds=_A							,  pooled_prompt_embeds=_A							,  negative_pooled_prompt_embeds=_A							,  )
     _UpperCAmelCase				:      List[str]			  =				output.images[0, -3:, -3:, -1]

     # make sure that it's equal
     assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()).max() < 1e-4



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






 '''simple docstring'''




 def  snake_case__				(	self) ->		List[str]:

     """simple docstring"""



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


 def  snake_case__				(	self							,  _A							,  _A="cpu"							,  _A=torch.floataa							,  _A=0) ->		int:

     """simple docstring"""



     _UpperCAmelCase				:      Tuple			  =				torch.Generator(device=_A).manual_seed(_A)
     _UpperCAmelCase				:      Any			  =				np.random.RandomState(_A).standard_normal((1, 4, 64, 64))
     _UpperCAmelCase				:      Dict			  =				torch.from_numpy(_A).to(device=_A							,  dtype=_A)
     _UpperCAmelCase				:      str			  =				{
         '''prompt''': '''a photograph of an astronaut riding a horse''',
         '''latents''': latents,
         '''generator''': generator,
         '''num_inference_steps''': 3,
         '''guidance_scale''': 7.5,
         '''output_type''': '''numpy''',
     }
     return inputs


 def  snake_case__				(	self) ->		Union[str, Any]:

     """simple docstring"""



     _UpperCAmelCase				:      List[str]			  =				DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base''')
     pipe.to(_A)
     pipe.set_progress_bar_config(disable=_A)

     _UpperCAmelCase				:      str			  =				self.get_inputs(_A)
     _UpperCAmelCase				:      Union[str, Any]			  =				pipe(**_A).images
     _UpperCAmelCase				:      Optional[int]			  =				image[0, -3:, -3:, -1].flatten()

     assert image.shape == (1, 512, 512, 3)
     _UpperCAmelCase				:      int			  =				np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506])
     assert np.abs(image_slice - expected_slice).max() < 7e-3




