




'''simple docstring'''


import gc
import unittest

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

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

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class 						lowerCAmelCase_	(       lowerCAmelCase_       ,					lowerCAmelCase_       ,					unittest.TestCase							):







  '''simple docstring'''

  UpperCamelCase_			:      Tuple										=				StableDiffusionXLPipeline
  UpperCamelCase_			:      Dict										=				TEXT_TO_IMAGE_PARAMS
  UpperCamelCase_			:      str										=				TEXT_TO_IMAGE_BATCH_PARAMS
  UpperCamelCase_			:      Tuple										=				TEXT_TO_IMAGE_IMAGE_PARAMS
  UpperCamelCase_			:      Optional[Any]										=				TEXT_TO_IMAGE_IMAGE_PARAMS



  def 					_snake_case     ( self				:							Any	)			->		int:







       '''simple docstring'''



       torch.manual_seed(0	)
       A:		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=lowerCamelCase_					,  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					,  )
       A:		Optional[Any]          =		EulerDiscreteScheduler(
           beta_start=0.0_0085					,  beta_end=0.012					,  steps_offset=1					,  beta_schedule='''scaled_linear'''					,  timestep_spacing='''leading'''					,  )
       torch.manual_seed(0	)
       A:		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=1_28					,  )
       torch.manual_seed(0	)
       A:		Optional[int]          =		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=10_00					,  hidden_act='''gelu'''					,  projection_dim=32					,  )
       A:		Dict          =		CLIPTextModel(lowerCamelCase_	)
       A:		Optional[int]          =		CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''					,  local_files_only=lowerCamelCase_	)

       A:		Dict          =		CLIPTextModelWithProjection(lowerCamelCase_	)
       A:		Dict          =		CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''					,  local_files_only=lowerCamelCase_	)

       A:		Dict          =		{
           """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				:							Optional[Any]					,  SCREAMING_SNAKE_CASE_				:							Tuple					,  SCREAMING_SNAKE_CASE_				:							Optional[Any]=0	)			->		Optional[int]:







       '''simple docstring'''



       if str(lowerCamelCase_	).startswith('''mps'''	):
            A:		Dict          =		torch.manual_seed(lowerCamelCase_	)
       else:
            A:		int          =		torch.Generator(device=lowerCamelCase_	).manual_seed(lowerCamelCase_	)
       A:		Optional[Any]          =		{
           """prompt""": """A painting of a squirrel eating a burger""",
           """generator""": generator,
           """num_inference_steps""": 2,
           """guidance_scale""": 5.0,
           """output_type""": """numpy""",
       }
       return inputs



  def 					_snake_case     ( self				:							Dict	)			->		Any:







       '''simple docstring'''



       A:		Optional[Any]          =		"""cpu"""  # ensure determinism for the device-dependent torch.Generator
       A:		Union[str, Any]          =		self.get_dummy_components()
       A:		Tuple          =		StableDiffusionXLPipeline(**lowerCamelCase_	)
       A:		List[Any]          =		sd_pipe.to(lowerCamelCase_	)
       sd_pipe.set_progress_bar_config(disable=lowerCamelCase_	)

       A:		Tuple          =		self.get_dummy_inputs(lowerCamelCase_	)
       A:		Dict          =		sd_pipe(**lowerCamelCase_	).images
       A:		Dict          =		image[0, -3:, -3:, -1]

       assert image.shape == (1, 64, 64, 3)
       A:		List[Any]          =		np.array([0.5873, 0.6128, 0.4797, 0.5122, 0.5674, 0.4639, 0.5227, 0.5149, 0.4747]	)

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



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







       '''simple docstring'''



       A:		Optional[int]          =		self.get_dummy_components()
       A:		Dict          =		StableDiffusionXLPipeline(**lowerCamelCase_	)
       A:		int          =		sd_pipe.to(lowerCamelCase_	)
       A:		Dict          =		sd_pipe.to(lowerCamelCase_	)
       sd_pipe.set_progress_bar_config(disable=lowerCamelCase_	)

       # forward without prompt embeds
       A:		List[str]          =		self.get_dummy_inputs(lowerCamelCase_	)
       A:		Any          =		3 * ["""this is a negative prompt"""]
       A:		Any          =		negative_prompt
       A:		Union[str, Any]          =		3 * [inputs["""prompt"""]]

       A:		List[str]          =		sd_pipe(**lowerCamelCase_	)
       A:		Tuple          =		output.images[0, -3:, -3:, -1]

       # forward with prompt embeds
       A:		List[str]          =		self.get_dummy_inputs(lowerCamelCase_	)
       A:		Any          =		3 * ["""this is a negative prompt"""]
       A:		List[Any]          =		3 * [inputs.pop('''prompt'''	)]

       (
           A      
       ):		int          =		sd_pipe.encode_prompt(lowerCamelCase_					,  negative_prompt=lowerCamelCase_	)

       A:		Any          =		sd_pipe(
           **lowerCamelCase_					,  prompt_embeds=lowerCamelCase_					,  negative_prompt_embeds=lowerCamelCase_					,  pooled_prompt_embeds=lowerCamelCase_					,  negative_pooled_prompt_embeds=lowerCamelCase_					,  )
       A:		Dict          =		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



  def 					_snake_case     ( self				:							str	)			->		Optional[Any]:







       '''simple docstring'''



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




  def 					_snake_case     ( self				:							Tuple	)			->		int:







       '''simple docstring'''



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






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







  '''simple docstring'''

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







       '''simple docstring'''



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



  def 					_snake_case     ( self				:							int					,  SCREAMING_SNAKE_CASE_				:							List[str]					,  SCREAMING_SNAKE_CASE_				:							List[str]="cpu"					,  SCREAMING_SNAKE_CASE_				:							List[str]=torch.floataa					,  SCREAMING_SNAKE_CASE_				:							int=0	)			->		int:







       '''simple docstring'''



       A:		str          =		torch.Generator(device=lowerCamelCase_	).manual_seed(lowerCamelCase_	)
       A:		Dict          =		np.random.RandomState(lowerCamelCase_	).standard_normal((1, 4, 64, 64)	)
       A:		Dict          =		torch.from_numpy(lowerCamelCase_	).to(device=lowerCamelCase_					,  dtype=lowerCamelCase_	)
       A:		int          =		{
           """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				:							List[Any]	)			->		List[Any]:







       '''simple docstring'''



       A:		List[Any]          =		DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base'''	)
       pipe.to(lowerCamelCase_	)
       pipe.set_progress_bar_config(disable=lowerCamelCase_	)

       A:		Dict          =		self.get_inputs(lowerCamelCase_	)
       A:		Any          =		pipe(**lowerCamelCase_	).images
       A:		Any          =		image[0, -3:, -3:, -1].flatten()

       assert image.shape == (1, 5_12, 5_12, 3)
       A:		str          =		np.array([0.4_9493, 0.4_7896, 0.4_0798, 0.5_4214, 0.5_3212, 0.4_8202, 0.4_7656, 0.4_6329, 0.4_8506]	)
       assert np.abs(image_slice - expected_slice	).max() < 7E-3










import unittest

from transformers import SpeechaTextaConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device

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.models.speech_to_text_a.modeling_speech_to_text_a import (
           SpeechaTextaDecoder,
           SpeechaTextaForCausalLM,
       )


@require_torch
class 	a__						:

       def __init__( self   :  Dict   ,				lowerCamelCase_   :  Any   ,				lowerCamelCase_   :  Dict=9_9   ,				lowerCamelCase_   :  List[Any]=1_3   ,				lowerCamelCase_   :  Dict=1_6   ,				lowerCamelCase_   :  Any=7   ,				lowerCamelCase_   :  Dict=True   ,				lowerCamelCase_   :  List[str]=True   ,				lowerCamelCase_   :  Tuple=True   ,				lowerCamelCase_   :  Any=False   ,				lowerCamelCase_   :  Union[str, Any]=True   ,				lowerCamelCase_   :  int=2   ,				lowerCamelCase_   :  Tuple=3_2   ,				lowerCamelCase_   :  int=4   ,				lowerCamelCase_   :  Dict=4   ,				lowerCamelCase_   :  str=3_0   ,				lowerCamelCase_   :  Optional[int]=0   ,				lowerCamelCase_   :  Optional[Any]=1   ,				lowerCamelCase_   :  Any=2   ,				lowerCamelCase_   :  Optional[int]=None   ,				):
            a_     :  Optional[Any]				      =     parent
            a_     :  Union[str, Any]				      =     batch_size
            a_     :  Tuple				      =     decoder_seq_length
            # For common tests
            a_     :  Union[str, Any]				      =     self.decoder_seq_length
            a_     :  List[str]				      =     is_training
            a_     :  int				      =     use_attention_mask
            a_     :  Dict				      =     use_labels

            a_     :  List[str]				      =     vocab_size
            a_     :  Optional[int]				      =     d_model
            a_     :  str				      =     d_model
            a_     :  Any				      =     decoder_layers
            a_     :  Tuple				      =     decoder_layers
            a_     :  Dict				      =     decoder_ffn_dim
            a_     :  List[str]				      =     decoder_attention_heads
            a_     :  List[Any]				      =     decoder_attention_heads
            a_     :  List[str]				      =     eos_token_id
            a_     :  Any				      =     bos_token_id
            a_     :  List[Any]				      =     pad_token_id
            a_     :  Dict				      =     decoder_start_token_id
            a_     :  Tuple				      =     use_cache
            a_     :  List[Any]				      =     max_position_embeddings

            a_     :  List[str]				      =     None
            a_     :  Any				      =     decoder_seq_length
            a_     :  List[Any]				      =     2
            a_     :  Optional[Any]				      =     1

       def     UpperCAmelCase( self   :  str     ):
            a_     :  Any				      =     ids_tensor([self.batch_size, self.decoder_seq_length]   ,				self.vocab_size     )

            a_     :  Any				      =     None
            if self.use_attention_mask:
                 a_     :  Optional[Any]				      =     ids_tensor([self.batch_size, self.decoder_seq_length]   ,				vocab_size=2     )

            a_     :  Tuple				      =     None
            if self.use_labels:
                 a_     :  int				      =     ids_tensor([self.batch_size, self.decoder_seq_length]   ,				self.vocab_size     )

            a_     :  int				      =     SpeechaTextaConfig(
                vocab_size=self.vocab_size   ,				d_model=self.d_model   ,				decoder_layers=self.decoder_layers   ,				decoder_ffn_dim=self.decoder_ffn_dim   ,				decoder_attention_heads=self.decoder_attention_heads   ,				eos_token_id=self.eos_token_id   ,				bos_token_id=self.bos_token_id   ,				use_cache=self.use_cache   ,				pad_token_id=self.pad_token_id   ,				decoder_start_token_id=self.decoder_start_token_id   ,				max_position_embeddings=self.max_position_embeddings   ,				)

            return (
                config,
                input_ids,
                attention_mask,
                lm_labels,
            )

       def     UpperCAmelCase( self   :  Tuple   ,				lowerCamelCase_   :  List[str]   ,				lowerCamelCase_   :  str   ,				lowerCamelCase_   :  Optional[int]   ,				lowerCamelCase_   :  List[str]   ,				):
            a_     :  List[Any]				      =     True
            a_     :  Optional[int]				      =     SpeechaTextaDecoder(config=lowerCamelCase_     ).to(lowerCamelCase_     ).eval()
            a_     :  Optional[int]				      =     input_ids[:2]

            input_ids[input_ids == 0] += 1
            # first forward pass
            a_     :  Union[str, Any]				      =     model(lowerCamelCase_   ,				use_cache=lowerCamelCase_     )
            a_     :  Tuple				      =     model(lowerCamelCase_     )
            a_     :  str				      =     model(lowerCamelCase_   ,				use_cache=lowerCamelCase_     )

            self.parent.assertTrue(len(lowerCamelCase_     ) == len(lowerCamelCase_     )     )
            self.parent.assertTrue(len(lowerCamelCase_     ) == len(lowerCamelCase_     ) + 1     )

            a_     :  Tuple				      =     outputs["""past_key_values"""]

            # create hypothetical next token and extent to next_input_ids
            a_     :  Any				      =     ids_tensor((2, 1)   ,				config.vocab_size - 1     ) + 1

            # append to next input_ids and
            a_     :  str				      =     torch.cat([input_ids, next_tokens]   ,				dim=-1     )

            print(lowerCamelCase_     )

            a_     :  Any				      =     model(lowerCamelCase_     )["""last_hidden_state"""]
            a_     :  int				      =     model(lowerCamelCase_   ,				past_key_values=lowerCamelCase_     )["""last_hidden_state"""]

            # select random slice
            a_     :  Tuple				      =     ids_tensor((1,)   ,				output_from_past.shape[-1]     ).item()
            a_     :  List[str]				      =     output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
            a_     :  List[Any]				      =     output_from_past[:, 0, random_slice_idx].detach()

            # test that outputs are equal for slice
            assert torch.allclose(lowerCamelCase_   ,				lowerCamelCase_   ,				atol=1E-3     )

       def     UpperCAmelCase( self   :  Any     ):
            a_     :  List[Any]				      =     self.prepare_config_and_inputs()
            (
                (
                a_
            )      ,      (
                a_
            )      ,      (
                a_
            )      ,      (
                a_
            )      ,      
            )     :  Optional[int]				      =     config_and_inputs

            a_     :  Tuple				      =     {
                """input_ids""": input_ids,
                """attention_mask""": attention_mask,
            }
            return config, inputs_dict


@require_torch
class 	a__						(    lowerCAmelCase_    ,							lowerCAmelCase_    ,							lowerCAmelCase_    ,							unittest.TestCase     ):
       lowerCamelCase__:  int				     =  (SpeechaTextaDecoder, SpeechaTextaForCausalLM) if is_torch_available() else ()
       lowerCamelCase__:  int				     =  (SpeechaTextaForCausalLM,) if is_torch_available() else ()
       lowerCamelCase__:  int				     =  {"""text-generation""": SpeechaTextaForCausalLM} if is_torch_available() else {}
       lowerCamelCase__:  Dict				     =  True
       lowerCamelCase__:  List[Any]				     =  False

       def     UpperCAmelCase( self   :  List[str]   ,				):
            a_     :  Optional[int]				      =     SpeechaTextaStandaloneDecoderModelTester(self   ,				is_training=lowerCamelCase_     )
            a_     :  str				      =     ConfigTester(self   ,				config_class=lowerCamelCase_     )

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

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

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

       def     UpperCAmelCase( self   :  str     ):
            self.config_tester.run_common_tests()

       def     UpperCAmelCase( self   :  Dict     ):
            a_     :  int				      =     self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_decoder_model_past(*lowerCamelCase_     )

       def     UpperCAmelCase( self   :  int     ):
            return



