






import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
       from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder







def       A__				(   _a	:       Dict		,	_a	:       Tuple		,	_a	:       Any		,	_a	:       List[Any]=None		,	_a	:       List[Any]=None		,	_a	:       List[str]=None		,	_a	:       List[str]=None		,	_a	:       Tuple=None		,	):





 '''simple docstring'''







 if attention_mask is None:
  snake_case__	:     str											=input_ids.ne(config.pad_token_id						)
 if decoder_attention_mask is None:
  snake_case__	:     Tuple											=decoder_input_ids.ne(config.pad_token_id						)
 if head_mask is None:
  snake_case__	:     Any											=torch.ones(config.encoder_layers		,	config.encoder_attention_heads		,	device=lowercase_						)
 if decoder_head_mask is None:
  snake_case__	:     List[Any]											=torch.ones(config.decoder_layers		,	config.decoder_attention_heads		,	device=lowercase_						)
 if cross_attn_head_mask is None:
  snake_case__	:     Tuple											=torch.ones(config.decoder_layers		,	config.decoder_attention_heads		,	device=lowercase_						)
 return {
     "input_ids": input_ids,
     "decoder_input_ids": decoder_input_ids,
     "attention_mask": attention_mask,
     "decoder_attention_mask": attention_mask,
     "head_mask": head_mask,
     "decoder_head_mask": decoder_head_mask,
     "cross_attn_head_mask": cross_attn_head_mask,
 }







class 			_lowercase :
      def __init__(  self					,      a					,      a=1_3					,      a=7					,      a=True					,      a=False					,      a=9_9					,      a=1_6					,      a=2					,      a=4					,      a=4					,      a="relu"					,      a=0.1					,      a=0.1					,      a=0.0					,      a=0.0					,      a=2_0					,      a=2					,      a=1					,      a=0					,      ):
       snake_case__	:     str											=parent
       snake_case__	:     int											=batch_size
       snake_case__	:     List[Any]											=seq_length
       snake_case__	:     Optional[int]											=is_training
       snake_case__	:     Union[str, Any]											=use_labels
       snake_case__	:     Union[str, Any]											=vocab_size
       snake_case__	:     Union[str, Any]											=hidden_size
       snake_case__	:     Optional[int]											=num_hidden_layers
       snake_case__	:     Optional[Any]											=num_attention_heads
       snake_case__	:     List[Any]											=intermediate_size
       snake_case__	:     Optional[int]											=hidden_act
       snake_case__	:     Optional[int]											=hidden_dropout_prob
       snake_case__	:     List[Any]											=attention_probs_dropout_prob
       snake_case__	:     List[Any]											=encoder_layerdrop
       snake_case__	:     Optional[int]											=decoder_layerdrop
       snake_case__	:     int											=max_position_embeddings
       snake_case__	:     Optional[Any]											=eos_token_id
       snake_case__	:     List[str]											=pad_token_id
       snake_case__	:     str											=bos_token_id
      def     lowercase__       (  self ):
       snake_case__	:     Union[str, Any]											=ids_tensor([self.batch_size, self.seq_length]					,      self.vocab_size )
       snake_case__	:     Any											=self.eos_token_id  # Eos Token
       snake_case__	:     Tuple											=ids_tensor([self.batch_size, self.seq_length]					,      self.vocab_size )

       # we need to clamp the input ids here to avoid having pad token in between
       # this is because for M2M100 the position_ids are prepared such that
       # all pad tokens have pos id = 2 and rest are between 2..seq_length
       # and the seq_length here is seq_length - num_pad_tokens
       # but when using past, there is no way of knowing if the past input ids had
       # pad tokens in them, which results in incorrect seq_lenth and which in turn results in
       # position_ids being off by num_pad_tokens in past input
       snake_case__	:     int											=input_ids.clamp(self.pad_token_id + 1 )
       snake_case__	:     Optional[int]											=decoder_input_ids.clamp(self.pad_token_id + 1 )

       snake_case__	:     Optional[Any]											=self.get_config()
       snake_case__	:     Optional[Any]											=prepare_mam_aaa_inputs_dict(lowercase__					,      lowercase__					,      lowercase__ )
       return config, inputs_dict
      def     lowercase__       (  self ):
       return MaMaaaConfig(
           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					,      encoder_layerdrop=self.encoder_layerdrop					,      decoder_layerdrop=self.decoder_layerdrop					,      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					,      )
      def     lowercase__       (  self ):
       snake_case__	:     Optional[int]											=self.prepare_config_and_inputs()
       return config, inputs_dict
      def     lowercase__       (  self					,      a					,      a ):
       snake_case__	:     List[str]											=MaMaaaModel(config=lowercase__ ).get_decoder().to(lowercase__ ).eval()
       snake_case__	:     List[str]											=inputs_dict['''input_ids''']
       snake_case__	:     int											=inputs_dict['''attention_mask''']
       snake_case__	:     Dict											=inputs_dict['''head_mask''']

       # first forward pass
       snake_case__	:     List[str]											=model(lowercase__					,      attention_mask=lowercase__					,      head_mask=lowercase__					,      use_cache=lowercase__ )

       snake_case__	:     int											=outputs.to_tuple()

       # create hypothetical multiple next token and extent to next_input_ids
       snake_case__	:     Dict											=ids_tensor((self.batch_size, 3)					,      config.vocab_size )
       snake_case__	:     Tuple											=ids_tensor((self.batch_size, 3)					,      2 )

       # append to next input_ids and
       snake_case__	:     List[Any]											=torch.cat([input_ids, next_tokens]					,      dim=-1 )
       snake_case__	:     List[Any]											=torch.cat([attention_mask, next_attn_mask]					,      dim=-1 )

       snake_case__	:     Optional[Any]											=model(lowercase__					,      attention_mask=lowercase__ )['''last_hidden_state''']
       snake_case__	:     Optional[Any]											=model(lowercase__					,      attention_mask=lowercase__					,      past_key_values=lowercase__ )[
           '''last_hidden_state'''
       ]

       # select random slice
       snake_case__	:     int											=ids_tensor((1,)					,      output_from_past.shape[-1] ).item()
       snake_case__	:     int											=output_from_no_past[:, -3:, random_slice_idx].detach()
       snake_case__	:     List[str]											=output_from_past[:, :, random_slice_idx].detach()

       self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] )

       # test that outputs are equal for slice
       self.parent.assertTrue(torch.allclose(lowercase__					,      lowercase__					,      atol=1e-2 ) )



      def     lowercase__       (  self					,      a					,      a ):
       snake_case__	:     int											=MaMaaaModel(config=lowercase__ ).to(lowercase__ ).eval()
       snake_case__	:     Any											=model(**lowercase__ )

       snake_case__	:     List[Any]											=outputs.encoder_last_hidden_state
       snake_case__	:     Tuple											=outputs.last_hidden_state

       with tempfile.TemporaryDirectory() as tmpdirname:
        snake_case__	:     Optional[int]											=model.get_encoder()
        encoder.save_pretrained(lowercase__ )
        snake_case__	:     Optional[int]											=MaMaaaEncoder.from_pretrained(lowercase__ ).to(lowercase__ )

       snake_case__	:     Tuple											=encoder(inputs_dict["""input_ids"""]					,      attention_mask=inputs_dict["""attention_mask"""] )[
           0
       ]

       self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3 )

       with tempfile.TemporaryDirectory() as tmpdirname:
        snake_case__	:     List[Any]											=model.get_decoder()
        decoder.save_pretrained(lowercase__ )
        snake_case__	:     Tuple											=MaMaaaDecoder.from_pretrained(lowercase__ ).to(lowercase__ )

       snake_case__	:     str											=decoder(
           input_ids=inputs_dict["""decoder_input_ids"""]					,      attention_mask=inputs_dict["""decoder_attention_mask"""]					,      encoder_hidden_states=lowercase__					,      encoder_attention_mask=inputs_dict["""attention_mask"""]					,      )[0]

       self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3 )







@require_torch
class 			_lowercase ( _UpperCamelCase    ,					_UpperCamelCase    ,					_UpperCamelCase    ,					unittest.TestCase    ):
      _a				:    Union[str, Any]				      =				(
          (
              MaMaaaModel,
              MaMaaaForConditionalGeneration,
          )
          if is_torch_available()
          else ()
      )
      _a				:    int				      =				(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
      _a				:    Optional[int]				      =				(
          {
              '''conversational''': MaMaaaForConditionalGeneration,
              '''feature-extraction''': MaMaaaModel,
              '''summarization''': MaMaaaForConditionalGeneration,
              '''text2text-generation''': MaMaaaForConditionalGeneration,
              '''translation''': MaMaaaForConditionalGeneration,
          }
          if is_torch_available()
          else {}
      )
      _a				:    int				      =				True
      _a				:    int				      =				True
      _a				:    Any				      =				False
      _a				:    List[Any]				      =				False
      def     lowercase__       (  self					,      a					,      a					,      a					,      a					,      a ):
       if pipeline_test_casse_name == "TranslationPipelineTests":
        # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
        # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
        return True

       return False
      def     lowercase__       (  self ):
       snake_case__	:     Tuple											=MaMaaaModelTester(self )
       snake_case__	:     Dict											=ConfigTester(self					,      config_class=lowercase__ )
      def     lowercase__       (  self ):
       self.config_tester.run_common_tests()
      def     lowercase__       (  self ):
       snake_case__	:     Dict											=self.model_tester.prepare_config_and_inputs()
       for model_class in self.all_model_classes:
        snake_case__	:     str											=model_class(lowercase__ )

        with tempfile.TemporaryDirectory() as tmpdirname:
         model.save_pretrained(lowercase__ )
         snake_case__	:     List[str]											=model_class.from_pretrained(lowercase__					,      output_loading_info=lowercase__ )
        self.assertEqual(info["""missing_keys"""]					,      [] )
      def     lowercase__       (  self ):
       snake_case__	:     Optional[int]											=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_decoder_model_past_large_inputs(*lowercase__ )
      def     lowercase__       (  self ):
       snake_case__	:     List[Any]											=self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.check_encoder_decoder_model_standalone(*lowercase__ )
      def     lowercase__       (  self ):
       snake_case__	:     int											=self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
        snake_case__	:     Optional[Any]											=model_class(lowercase__ )
        model.to(lowercase__ )
        model.eval()

        snake_case__	:     int											=copy.deepcopy(self._prepare_for_class(lowercase__					,      lowercase__ ) )

        if not self.is_encoder_decoder:
         snake_case__	:     Any											=inputs['''input_ids''']
         del inputs["input_ids"]
        else:
         snake_case__	:     List[str]											=inputs['''input_ids''']
         snake_case__	:     int											=inputs.get("""decoder_input_ids"""					,      lowercase__ )
         del inputs["input_ids"]
         inputs.pop("""decoder_input_ids"""					,      lowercase__ )

        snake_case__	:     Dict											=model.get_input_embeddings()
        if not self.is_encoder_decoder:
         snake_case__	:     Tuple											=wte(lowercase__ )
        else:
         snake_case__	:     int											=wte(lowercase__ )
         snake_case__	:     str											=wte(lowercase__ )

        with torch.no_grad():
         model(**lowercase__ )[0]



      def     lowercase__       (  self ):
       snake_case__	:     List[Any]											=self.model_tester.prepare_config_and_inputs()
       snake_case__	:     Optional[Any]											=input_dict['''input_ids''']
       snake_case__	:     List[str]											=input_ids.ne(1 ).to(lowercase__ )
       snake_case__	:     Optional[Any]											=MaMaaaForConditionalGeneration(lowercase__ ).eval().to(lowercase__ )
       if torch_device == "cuda":
        model.half()
       model.generate(lowercase__					,      attention_mask=lowercase__ )
       model.generate(num_beams=4					,      do_sample=lowercase__					,      early_stopping=lowercase__					,      num_return_sequences=3 )







def       A__				(   _a	:       Union[str, Any]						):





 '''simple docstring'''







 return torch.tensor(lowercase_		,	dtype=torch.long		,	device=lowercase_						)


__lowerCamelCase						:		Optional[int]				      = 1e-4







@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class 			_lowercase ( unittest.TestCase    ):
      @cached_property
      def     lowercase__       (  self ):
       return MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M""" )
      def     lowercase__       (  self ):
       snake_case__	:     Union[str, Any]											=MaMaaaModel.from_pretrained("""facebook/m2m100_418M""" ).to(lowercase__ )
       snake_case__	:     Union[str, Any]											=_long_tensor([[1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8, 2]] )
       snake_case__	:     Dict											=_long_tensor([[2, 1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8]] )
       snake_case__	:     Dict											=prepare_mam_aaa_inputs_dict(model.config					,      lowercase__					,      lowercase__ )
       with torch.no_grad():
        snake_case__	:     Any											=model(**lowercase__ )[0]
       snake_case__	:     str											=torch.Size((1, 1_1, 1_0_2_4) )
       self.assertEqual(output.shape					,      lowercase__ )
       # change to expected output here
       snake_case__	:     List[str]											=torch.tensor(
           [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]]					,      device=lowercase__ )
       self.assertTrue(torch.allclose(output[:, :3, :3]					,      lowercase__					,      atol=lowercase__ ) )
      def     lowercase__       (  self ):
       snake_case__	:     Optional[Any]											=MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M""" ).to(lowercase__ )

       # change to intended input
       snake_case__	:     int											=_long_tensor([[1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8, 2]] )
       snake_case__	:     List[Any]											=_long_tensor([[2, 1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8]] )
       snake_case__	:     str											=prepare_mam_aaa_inputs_dict(model.config					,      lowercase__					,      lowercase__ )
       with torch.no_grad():
        snake_case__	:     List[str]											=model(**lowercase__ )[0]
       snake_case__	:     str											=torch.Size((1, 1_1, model.config.vocab_size) )
       self.assertEqual(output.shape					,      lowercase__ )
       # change to expected output here
       snake_case__	:     Dict											=torch.tensor(
           [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]]					,      device=lowercase__ )
       self.assertTrue(torch.allclose(output[:, :3, :3]					,      lowercase__					,      atol=lowercase__ ) )



      def     lowercase__       (  self ):
       snake_case__	:     Optional[Any]											=MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M""" ).to(lowercase__ )
       snake_case__	:     str											=MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M"""					,      src_lang="""fr"""					,      tgt_lang="""en""" )

       snake_case__	:     Tuple											=[
           '''L\'affaire NSA souligne l\'absence totale de débat sur le renseignement''',
           '''Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.''',
           '''Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent'''
           ''' Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de'''
           ''' l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.''',
       ]

       # The below article tests that we don't add any hypotheses outside of the top n_beams
       snake_case__	:     Optional[int]											=tokenizer(lowercase__					,      padding=lowercase__					,      return_tensors="""pt""" )

       snake_case__	:     int											=model.generate(
           input_ids=dct["""input_ids"""].to(lowercase__ )					,      attention_mask=dct["""attention_mask"""].to(lowercase__ )					,      num_beams=5					,      forced_bos_token_id=tokenizer.get_lang_id("""en""" )					,      )

       snake_case__	:     Any											=[
           '''The NSA case highlights the total absence of intelligence debate''',
           '''I think there are two levels of response from the French government.''',
           '''When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.'''
           ''' Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all'''
           ''' communications in France.''',
       ]

       snake_case__	:     List[Any]											=tokenizer.batch_decode(
           hypotheses_batch.tolist()					,      clean_up_tokenization_spaces=lowercase__					,      skip_special_tokens=lowercase__ )
       assert generated == expected_en









import gc
import random
import unittest

import numpy as np
import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModel,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    floats_tensor,
    load_image,
    load_numpy,
    require_torch_gpu,
    skip_mps,
    slow,
    torch_device,
)

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


enable_full_determinism()




class 							lowerCamelCase   (  _UpperCamelCase							,						_UpperCamelCase							,						_UpperCamelCase							,						unittest.TestCase ):
	_lowerCAmelCase     :		Optional[Any]										=						StableUnCLIPImgaImgPipeline
	_lowerCAmelCase     :		Any										=						TEXT_GUIDED_IMAGE_VARIATION_PARAMS
	_lowerCAmelCase     :		List[Any]										=						TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
	_lowerCAmelCase     :		Dict										=						frozenset(
	    [] )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
	_lowerCAmelCase     :		str										=						frozenset([] )


	def  A(    self):
							__UpperCAmelCase			:							Any	    =	3_2
							__UpperCAmelCase			:							Union[str, Any]	    =	embedder_hidden_size

							# image encoding components

							__UpperCAmelCase			:							Union[str, Any]	    =	CLIPImageProcessor(crop_size=3_2				,     size=3_2)

							torch.manual_seed(0)
							__UpperCAmelCase			:							List[str]	    =	CLIPVisionModelWithProjection(
							    CLIPVisionConfig(
							        hidden_size=lowercase__				,     projection_dim=lowercase__				,     num_hidden_layers=5				,     num_attention_heads=4				,     image_size=3_2				,     intermediate_size=3_7				,     patch_size=1				,     ))

							# regular denoising components

							torch.manual_seed(0)
							__UpperCAmelCase			:							List[Any]	    =	StableUnCLIPImageNormalizer(embedding_dim=lowercase__)
							__UpperCAmelCase			:							Any	    =	DDPMScheduler(beta_schedule='''squaredcos_cap_v2''')

							torch.manual_seed(0)
							__UpperCAmelCase			:							Dict	    =	CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''')

							torch.manual_seed(0)
							__UpperCAmelCase			:							int	    =	CLIPTextModel(
							    CLIPTextConfig(
							        bos_token_id=0				,     eos_token_id=2				,     hidden_size=lowercase__				,     projection_dim=3_2				,     intermediate_size=3_7				,     layer_norm_eps=1e-05				,     num_attention_heads=4				,     num_hidden_layers=5				,     pad_token_id=1				,     vocab_size=1_0_0_0				,     ))

							torch.manual_seed(0)
							__UpperCAmelCase			:							Tuple	    =	UNetaDConditionModel(
							    sample_size=3_2				,     in_channels=4				,     out_channels=4				,     down_block_types=('''CrossAttnDownBlock2D''', '''DownBlock2D''')				,     up_block_types=('''UpBlock2D''', '''CrossAttnUpBlock2D''')				,     block_out_channels=(3_2, 6_4)				,     attention_head_dim=(2, 4)				,     class_embed_type='''projection'''				,     projection_class_embeddings_input_dim=embedder_projection_dim * 2				,     cross_attention_dim=lowercase__				,     layers_per_block=1				,     upcast_attention=lowercase__				,     use_linear_projection=lowercase__				,     )

							torch.manual_seed(0)
							__UpperCAmelCase			:							Optional[Any]	    =	DDIMScheduler(
							    beta_schedule='''scaled_linear'''				,     beta_start=0.0_0_0_8_5				,     beta_end=0.0_1_2				,     prediction_type='''v_prediction'''				,     set_alpha_to_one=lowercase__				,     steps_offset=1				,     )

							torch.manual_seed(0)
							__UpperCAmelCase			:							Optional[Any]	    =	AutoencoderKL()

							__UpperCAmelCase			:							Optional[Any]	    =	{
							    # image encoding components
							    '''feature_extractor''': feature_extractor,
							    '''image_encoder''': image_encoder.eval(),
							    # image noising components
							    '''image_normalizer''': image_normalizer.eval(),
							    '''image_noising_scheduler''': image_noising_scheduler,
							    # regular denoising components
							    '''tokenizer''': tokenizer,
							    '''text_encoder''': text_encoder.eval(),
							    '''unet''': unet.eval(),
							    '''scheduler''': scheduler,
							    '''vae''': vae.eval(),
							}

							return components


	def  A(    self				,     lowercase__				,     lowercase__=0				,     lowercase__=True):
							if str(lowercase__).startswith('''mps'''):
													__UpperCAmelCase			:							Union[str, Any]	    =	torch.manual_seed(lowercase__)
							else:
													__UpperCAmelCase			:							int	    =	torch.Generator(device=lowercase__).manual_seed(lowercase__)

							__UpperCAmelCase			:							Dict	    =	floats_tensor((1, 3, 3_2, 3_2)				,     rng=random.Random(lowercase__)).to(lowercase__)

							if pil_image:
													__UpperCAmelCase			:							int	    =	input_image * 0.5 + 0.5
													__UpperCAmelCase			:							str	    =	input_image.clamp(0				,     1)
													__UpperCAmelCase			:							Optional[int]	    =	input_image.cpu().permute(0				,     2				,     3				,     1).float().numpy()
													__UpperCAmelCase			:							Union[str, Any]	    =	DiffusionPipeline.numpy_to_pil(lowercase__)[0]

							return {
							    "prompt": "An anime racoon running a marathon",
							    "image": input_image,
							    "generator": generator,
							    "num_inference_steps": 2,
							    "output_type": "np",
							}


	@skip_mps
	def  A(    self):
							__UpperCAmelCase			:							Union[str, Any]	    =	'''cpu'''  # ensure determinism for the device-dependent torch.Generator
							__UpperCAmelCase			:							Dict	    =	self.get_dummy_components()
							__UpperCAmelCase			:							List[Any]	    =	StableUnCLIPImgaImgPipeline(**lowercase__)
							__UpperCAmelCase			:							List[str]	    =	sd_pipe.to(lowercase__)
							sd_pipe.set_progress_bar_config(disable=lowercase__)

							__UpperCAmelCase			:							Dict	    =	self.get_dummy_inputs(lowercase__)
							inputs.update({'''image_embeds''': None})
							__UpperCAmelCase			:							Any	    =	sd_pipe(**lowercase__).images
							__UpperCAmelCase			:							Union[str, Any]	    =	image[0, -3:, -3:, -1]

							assert image.shape == (1, 3_2, 3_2, 3)
							__UpperCAmelCase			:							Union[str, Any]	    =	np.array([0.3_8_7_2, 0.7_2_2_4, 0.5_6_0_1, 0.4_7_4_1, 0.6_8_7_2, 0.5_8_1_4, 0.4_6_3_6, 0.3_8_6_7, 0.5_0_7_8])

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


	def  A(    self):
							__UpperCAmelCase			:							Optional[Any]	    =	torch_device in ['''cpu''', '''mps''']

							self._test_attention_slicing_forward_pass(test_max_difference=lowercase__)


	def  A(    self):
							__UpperCAmelCase			:							str	    =	torch_device in ['''cpu''', '''mps''']

							self._test_inference_batch_single_identical(test_max_difference=lowercase__)


	@unittest.skipIf(
	    torch_device != '''cuda''' or not is_xformers_available()				,     reason='''XFormers attention is only available with CUDA and `xformers` installed'''				,     )
	def  A(    self):
							self._test_xformers_attention_forwardGenerator_pass(test_max_difference=lowercase__)






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


	def  A(    self):
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()


	def  A(    self):
							__UpperCAmelCase			:							Dict	    =	load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png''')

							__UpperCAmelCase			:							List[str]	    =	load_numpy(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy''')

							__UpperCAmelCase			:							Optional[int]	    =	StableUnCLIPImgaImgPipeline.from_pretrained(
							    '''fusing/stable-unclip-2-1-l-img2img'''				,     torch_dtype=torch.floataa)
							pipe.to(lowercase__)
							pipe.set_progress_bar_config(disable=lowercase__)
							# stable unclip will oom when integration tests are run on a V100,
							# so turn on memory savings
							pipe.enable_attention_slicing()
							pipe.enable_sequential_cpu_offload()

							__UpperCAmelCase			:							Optional[Any]	    =	torch.Generator(device='''cpu''').manual_seed(0)
							__UpperCAmelCase			:							Any	    =	pipe(lowercase__				,     '''anime turle'''				,     generator=lowercase__				,     output_type='''np''')

							__UpperCAmelCase			:							Optional[Any]	    =	output.images[0]

							assert image.shape == (7_6_8, 7_6_8, 3)

							assert_mean_pixel_difference(lowercase__				,     lowercase__)


	def  A(    self):
							__UpperCAmelCase			:							str	    =	load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png''')

							__UpperCAmelCase			:							Union[str, Any]	    =	load_numpy(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy''')

							__UpperCAmelCase			:							Union[str, Any]	    =	StableUnCLIPImgaImgPipeline.from_pretrained(
							    '''fusing/stable-unclip-2-1-h-img2img'''				,     torch_dtype=torch.floataa)
							pipe.to(lowercase__)
							pipe.set_progress_bar_config(disable=lowercase__)
							# stable unclip will oom when integration tests are run on a V100,
							# so turn on memory savings
							pipe.enable_attention_slicing()
							pipe.enable_sequential_cpu_offload()

							__UpperCAmelCase			:							Dict	    =	torch.Generator(device='''cpu''').manual_seed(0)
							__UpperCAmelCase			:							int	    =	pipe(lowercase__				,     '''anime turle'''				,     generator=lowercase__				,     output_type='''np''')

							__UpperCAmelCase			:							List[str]	    =	output.images[0]

							assert image.shape == (7_6_8, 7_6_8, 3)

							assert_mean_pixel_difference(lowercase__				,     lowercase__)


	def  A(    self):
							__UpperCAmelCase			:							str	    =	load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png''')

							torch.cuda.empty_cache()
							torch.cuda.reset_max_memory_allocated()
							torch.cuda.reset_peak_memory_stats()

							__UpperCAmelCase			:							Optional[int]	    =	StableUnCLIPImgaImgPipeline.from_pretrained(
							    '''fusing/stable-unclip-2-1-h-img2img'''				,     torch_dtype=torch.floataa)
							__UpperCAmelCase			:							Optional[int]	    =	pipe.to(lowercase__)
							pipe.set_progress_bar_config(disable=lowercase__)
							pipe.enable_attention_slicing()
							pipe.enable_sequential_cpu_offload()

							__UpperCAmelCase			:							int	    =	pipe(
							    lowercase__				,     '''anime turtle'''				,     num_inference_steps=2				,     output_type='''np'''				,     )

							__UpperCAmelCase			:							Optional[Any]	    =	torch.cuda.max_memory_allocated()
							# make sure that less than 7 GB is allocated
							assert mem_bytes < 7 * 1_0**9

