


'''simple docstring'''




import unittest

from transformers import AutoTokenizer, FalconConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

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


if is_torch_available():
       import torch

       from transformers import (
           FalconForCausalLM,
           FalconForQuestionAnswering,
           FalconForSequenceClassification,
           FalconForTokenClassification,
           FalconModel,
       )

class 		UpperCAmelCase_      :





     def __init__( self       :      Union[str, Any]    ,      UpperCAmelCase__       :      Union[str, Any]    ,      UpperCAmelCase__       :      List[Any]=3    ,      UpperCAmelCase__       :      Optional[int]=7    ,      UpperCAmelCase__       :      int=True    ,      UpperCAmelCase__       :      Union[str, Any]=True    ,      UpperCAmelCase__       :      str=False    ,      UpperCAmelCase__       :      List[Any]=True    ,      UpperCAmelCase__       :      List[str]=9_9    ,      UpperCAmelCase__       :      Union[str, Any]=3_2    ,      UpperCAmelCase__       :      Optional[Any]=5    ,      UpperCAmelCase__       :      List[Any]=4    ,      UpperCAmelCase__       :      str=3_7    ,      UpperCAmelCase__       :      Optional[int]="gelu"    ,      UpperCAmelCase__       :      str=0.1    ,      UpperCAmelCase__       :      Optional[int]=0.1    ,      UpperCAmelCase__       :      Dict=5_1_2    ,      UpperCAmelCase__       :      int=1_6    ,      UpperCAmelCase__       :      str=2    ,      UpperCAmelCase__       :      Dict=0.02    ,      UpperCAmelCase__       :      int=3    ,      UpperCAmelCase__       :      int=4    ,      UpperCAmelCase__       :      Any=None    ,      )				->  Dict:
        lowerCAmelCase     =			parent
        lowerCAmelCase     =			batch_size
        lowerCAmelCase     =			seq_length
        lowerCAmelCase     =			is_training
        lowerCAmelCase     =			use_input_mask
        lowerCAmelCase     =			use_token_type_ids
        lowerCAmelCase     =			use_labels
        lowerCAmelCase     =			vocab_size
        lowerCAmelCase     =			hidden_size
        lowerCAmelCase     =			num_hidden_layers
        lowerCAmelCase     =			num_attention_heads
        lowerCAmelCase     =			intermediate_size
        lowerCAmelCase     =			hidden_act
        lowerCAmelCase     =			hidden_dropout_prob
        lowerCAmelCase     =			attention_probs_dropout_prob
        lowerCAmelCase     =			max_position_embeddings
        lowerCAmelCase     =			type_vocab_size
        lowerCAmelCase     =			type_sequence_label_size
        lowerCAmelCase     =			initializer_range
        lowerCAmelCase     =			num_labels
        lowerCAmelCase     =			num_choices
        lowerCAmelCase     =			scope





     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  Union[str, Any]:
        lowerCAmelCase     =			ids_tensor([self.batch_size, self.seq_length]    ,      self.vocab_size    )

        lowerCAmelCase     =			None
        if self.use_input_mask:
           lowerCAmelCase     =			random_attention_mask([self.batch_size, self.seq_length]    )

        lowerCAmelCase     =			None

        lowerCAmelCase     =			None
        lowerCAmelCase     =			None
        lowerCAmelCase     =			None
        if self.use_labels:
           lowerCAmelCase     =			ids_tensor([self.batch_size]    ,      self.type_sequence_label_size    )
           lowerCAmelCase     =			ids_tensor([self.batch_size, self.seq_length]    ,      self.num_labels    )
           lowerCAmelCase     =			ids_tensor([self.batch_size]    ,      self.num_choices    )

        lowerCAmelCase     =			self.get_config()

        return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels





     def 							__UpperCAmelCase      ( self       :      Dict    )				->  str:
        return FalconConfig(
            vocab_size=self.vocab_size    ,      hidden_size=self.hidden_size    ,      num_hidden_layers=self.num_hidden_layers    ,      num_attention_heads=self.num_attention_heads    ,      intermediate_size=self.intermediate_size    ,      hidden_act=self.hidden_act    ,      hidden_dropout_prob=self.hidden_dropout_prob    ,      attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,      max_position_embeddings=self.max_position_embeddings    ,      type_vocab_size=self.type_vocab_size    ,      is_decoder=UpperCAmelCase__    ,      initializer_range=self.initializer_range    ,      pad_token_id=1    ,      new_decoder_architecture=UpperCAmelCase__    ,      )





     def 							__UpperCAmelCase      ( self       :      Tuple    ,      UpperCAmelCase__       :      List[Any]    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      int    ,      UpperCAmelCase__       :      Tuple    ,      UpperCAmelCase__       :      Optional[int]    ,      UpperCAmelCase__       :      Union[str, Any]    ,      UpperCAmelCase__       :      Optional[int]    )				->  Dict:
        lowerCAmelCase     =			FalconModel(config=UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    )
        lowerCAmelCase     =			model(UpperCAmelCase__    )
        self.parent.assertEqual(result.last_hidden_state.shape    ,      (self.batch_size, self.seq_length, self.hidden_size)    )





     def 							__UpperCAmelCase      ( self       :      Optional[Any]    ,      UpperCAmelCase__       :      Optional[int]    ,      UpperCAmelCase__       :      Optional[Any]    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      Union[str, Any]    ,      UpperCAmelCase__       :      Optional[Any]    ,      UpperCAmelCase__       :      Union[str, Any]    ,      UpperCAmelCase__       :      str    ,      UpperCAmelCase__       :      Union[str, Any]    ,      UpperCAmelCase__       :      Tuple    ,      )				->  Optional[int]:
        lowerCAmelCase     =			True
        lowerCAmelCase     =			FalconModel(UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(
            UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      encoder_hidden_states=UpperCAmelCase__    ,      encoder_attention_mask=UpperCAmelCase__    ,      )
        lowerCAmelCase     =			model(
            UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      encoder_hidden_states=UpperCAmelCase__    ,      )
        lowerCAmelCase     =			model(UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    )
        self.parent.assertEqual(result.last_hidden_state.shape    ,      (self.batch_size, self.seq_length, self.hidden_size)    )





     def 							__UpperCAmelCase      ( self       :      Any    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      Any    ,      UpperCAmelCase__       :      List[Any]    ,      UpperCAmelCase__       :      str    ,      UpperCAmelCase__       :      str    ,      UpperCAmelCase__       :      int    ,      UpperCAmelCase__       :      Tuple    ,      UpperCAmelCase__       :      str    ,      UpperCAmelCase__       :      Tuple    ,      )				->  Tuple:
        lowerCAmelCase     =			FalconForCausalLM(config=UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      labels=UpperCAmelCase__    )
        self.parent.assertEqual(result.logits.shape    ,      (self.batch_size, self.seq_length, self.vocab_size)    )





     def 							__UpperCAmelCase      ( self       :      Dict    ,      UpperCAmelCase__       :      List[Any]    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      Optional[Any]    ,      UpperCAmelCase__       :      Any    ,      UpperCAmelCase__       :      Dict    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      Optional[Any]    ,      UpperCAmelCase__       :      Union[str, Any]    ,      UpperCAmelCase__       :      Any    ,      )				->  Optional[int]:
        lowerCAmelCase     =			True
        lowerCAmelCase     =			True
        lowerCAmelCase     =			FalconForCausalLM(config=UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()

        # first forward pass
        lowerCAmelCase     =			model(
            UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      encoder_hidden_states=UpperCAmelCase__    ,      encoder_attention_mask=UpperCAmelCase__    ,      use_cache=UpperCAmelCase__    ,      )
        lowerCAmelCase     =			outputs.past_key_values

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

        # append to next input_ids and
        lowerCAmelCase     =			torch.cat([input_ids, next_tokens]    ,      dim=-1    )
        lowerCAmelCase     =			torch.cat([input_mask, next_mask]    ,      dim=-1    )

        lowerCAmelCase     =			model(
            UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      encoder_hidden_states=UpperCAmelCase__    ,      encoder_attention_mask=UpperCAmelCase__    ,      output_hidden_states=UpperCAmelCase__    ,      )['hidden_states'][0]
        lowerCAmelCase     =			model(
            UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      encoder_hidden_states=UpperCAmelCase__    ,      encoder_attention_mask=UpperCAmelCase__    ,      past_key_values=UpperCAmelCase__    ,      output_hidden_states=UpperCAmelCase__    ,      )['hidden_states'][0]

        # select random slice
        lowerCAmelCase     =			ids_tensor((1,)    ,      output_from_past.shape[-1]    ).item()
        lowerCAmelCase     =			output_from_no_past[:, -3:, random_slice_idx].detach()
        lowerCAmelCase     =			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(UpperCAmelCase__    ,      UpperCAmelCase__    ,      atol=1E-3    )    )





     def 							__UpperCAmelCase      ( self       :      Dict    )				->  List[Any]:
        lowerCAmelCase     =			self.prepare_config_and_inputs()
        (
            (
            lowerCAmelCase
        )     ,  (
            lowerCAmelCase
        )     ,  (
            lowerCAmelCase
        )     ,  (
            lowerCAmelCase
        )     ,  (
            lowerCAmelCase
        )     ,  (
            lowerCAmelCase
        )     ,  (
            lowerCAmelCase
        )     ,  
        )     =			config_and_inputs
        lowerCAmelCase     =			{'input_ids': input_ids, 'attention_mask': input_mask}
        return config, inputs_dict




@require_torch
class 		UpperCAmelCase_      (  __lowercase       ,	__lowercase       ,	__lowercase       ,	unittest.TestCase		):
     lowerCamelCase				:	List[Any]		=     (
         (
             FalconModel,
             FalconForCausalLM,
             FalconForSequenceClassification,
             FalconForTokenClassification,
             FalconForQuestionAnswering,
         )
         if is_torch_available()
         else ()
     )
     lowerCamelCase				:	List[Any]		=     (FalconForCausalLM,) if is_torch_available() else ()
     lowerCamelCase				:	Tuple		=     (
         {
             '''feature-extraction''': FalconModel,
             '''text-classification''': FalconForSequenceClassification,
             '''text-generation''': FalconForCausalLM,
             '''question-answering''': FalconForQuestionAnswering,
             '''token-classification''': FalconForTokenClassification,
             '''zero-shot''': FalconForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )
     lowerCamelCase				:	str		=     False
     lowerCamelCase				:	Tuple		=     False





     def 							__UpperCAmelCase      ( self       :      Optional[int]    )				->  Dict:
        lowerCAmelCase     =			FalconModelTester(self    )
        lowerCAmelCase     =			ConfigTester(self    ,      config_class=UpperCAmelCase__    ,      hidden_size=3_7    )





     def 							__UpperCAmelCase      ( self       :      List[str]    )				->  Tuple:
        self.config_tester.run_common_tests()





     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  Union[str, Any]:
        lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*UpperCAmelCase__    )





     def 							__UpperCAmelCase      ( self       :      List[Any]    )				->  Any:
        lowerCAmelCase     ,  *lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs()
        for alibi in [True, False]:
           lowerCAmelCase     =			alibi
           self.model_tester.create_and_check_model(UpperCAmelCase__    ,      *UpperCAmelCase__    )





     def 							__UpperCAmelCase      ( self       :      Optional[Any]    )				->  List[str]:
        lowerCAmelCase     ,  lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs_for_common()
        lowerCAmelCase     =			3
        lowerCAmelCase     =			input_dict['input_ids']
        lowerCAmelCase     =			input_ids.ne(1    ).to(UpperCAmelCase__    )
        lowerCAmelCase     =			ids_tensor([self.model_tester.batch_size]    ,      self.model_tester.type_sequence_label_size    )
        lowerCAmelCase     =			FalconForSequenceClassification(UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      labels=UpperCAmelCase__    )
        self.assertEqual(result.logits.shape    ,      (self.model_tester.batch_size, self.model_tester.num_labels)    )





     def 							__UpperCAmelCase      ( self       :      List[Any]    )				->  Dict:
        lowerCAmelCase     ,  lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs_for_common()
        lowerCAmelCase     =			3
        lowerCAmelCase     =			'single_label_classification'
        lowerCAmelCase     =			input_dict['input_ids']
        lowerCAmelCase     =			input_ids.ne(1    ).to(UpperCAmelCase__    )
        lowerCAmelCase     =			ids_tensor([self.model_tester.batch_size]    ,      self.model_tester.type_sequence_label_size    )
        lowerCAmelCase     =			FalconForSequenceClassification(UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      labels=UpperCAmelCase__    )
        self.assertEqual(result.logits.shape    ,      (self.model_tester.batch_size, self.model_tester.num_labels)    )





     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  int:
        lowerCAmelCase     ,  lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs_for_common()
        lowerCAmelCase     =			input_dict['input_ids']
        lowerCAmelCase     =			FalconForCausalLM(UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCAmelCase__    ,      use_cache=UpperCAmelCase__    )
        lowerCAmelCase     =			input_ids.shape[0]
        lowerCAmelCase     =			model._convert_to_rw_cache(result.past_key_values    )
        lowerCAmelCase     =			model._convert_cache_to_standard_format(UpperCAmelCase__    ,      UpperCAmelCase__    )
        for layer in range(len(UpperCAmelCase__    )    ):
           for tensor_idx in range(2    ):
              self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3    )
              self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4    )
              self.assertTrue(
                  torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx]    )    )





     def 							__UpperCAmelCase      ( self       :      int    )				->  Dict:
        lowerCAmelCase     ,  lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs_for_common()
        lowerCAmelCase     =			3
        lowerCAmelCase     =			'multi_label_classification'
        lowerCAmelCase     =			input_dict['input_ids']
        lowerCAmelCase     =			input_ids.ne(1    ).to(UpperCAmelCase__    )
        lowerCAmelCase     =			ids_tensor(
            [self.model_tester.batch_size, config.num_labels]    ,      self.model_tester.type_sequence_label_size    ).to(torch.float    )
        lowerCAmelCase     =			FalconForSequenceClassification(UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      labels=UpperCAmelCase__    )
        self.assertEqual(result.logits.shape    ,      (self.model_tester.batch_size, self.model_tester.num_labels)    )





     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  Optional[Any]:
        # Falcon can have different numbers of KV-heads than the number of query heads, so we need
        # to override this test to use the right head counts.
        for model_class in self.all_generative_model_classes:
           lowerCAmelCase     ,  lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs_for_common()

           # If it doesn't support cache, pass the test
           if not hasattr(UpperCAmelCase__    ,      'use_cache'    ):
              return

           lowerCAmelCase     =			model_class(UpperCAmelCase__    ).to(UpperCAmelCase__    )
           if "use_cache" not in inputs:
              lowerCAmelCase     =			True
           lowerCAmelCase     =			model(**UpperCAmelCase__    )

           # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
           if "past_key_values" not in outputs:
              return

           lowerCAmelCase     =			(
               getattr(UpperCAmelCase__    ,      'decoder_layers'    ,      UpperCAmelCase__    )
               or getattr(UpperCAmelCase__    ,      'num_decoder_layers'    ,      UpperCAmelCase__    )
               or config.num_hidden_layers
           )
           lowerCAmelCase     =			getattr(UpperCAmelCase__    ,      'num_kv_heads'    ,      config.num_attention_heads    )
           lowerCAmelCase     =			getattr(UpperCAmelCase__    ,      'd_model'    ,      config.hidden_size    )
           lowerCAmelCase     =			embed_dim // num_attention_heads

           lowerCAmelCase     =			outputs['past_key_values']
           self.assertEqual(len(UpperCAmelCase__    )    ,      UpperCAmelCase__    )

           lowerCAmelCase     ,  lowerCAmelCase     =			inputs['input_ids'].shape
           for i in range(UpperCAmelCase__    ):
              if config.new_decoder_architecture:
                 lowerCAmelCase     =			config.num_attention_heads
              elif config.multi_query:
                 lowerCAmelCase     =			1
              self.assertEqual(len(past_kv[0]    )    ,      2    )  # K V for the decoder = 2
              self.assertEqual(
                  past_kv[i][0].shape    ,      (batch_size, num_attention_heads, seq_length, per_head_embed_dim)    )
              self.assertEqual(
                  past_kv[i][1].shape    ,      (batch_size, num_attention_heads, seq_length, per_head_embed_dim)    )




@require_torch
class 		UpperCAmelCase_      (  unittest.TestCase		):





     @slow
     def 							__UpperCAmelCase      ( self       :      Optional[int]    )				->  List[str]:
        lowerCAmelCase     =			AutoTokenizer.from_pretrained('Rocketknight1/falcon-rw-1b'    )
        lowerCAmelCase     =			FalconForCausalLM.from_pretrained('Rocketknight1/falcon-rw-1b'    )
        model.eval()
        model.to(UpperCAmelCase__    )
        lowerCAmelCase     =			tokenizer('My favorite food is'    ,      return_tensors='pt'    ).to(UpperCAmelCase__    )

        lowerCAmelCase     =			(
            'My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.'
        )

        lowerCAmelCase     =			model.generate(**UpperCAmelCase__    ,      do_sample=UpperCAmelCase__    ,      max_new_tokens=1_9    )
        lowerCAmelCase     =			tokenizer.batch_decode(UpperCAmelCase__    )[0]

        self.assertEqual(UpperCAmelCase__    ,      UpperCAmelCase__    )





     @slow
     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  List[Any]:
        # The big models are way too big for the CI, so we use tiny random models that resemble their
        # architectures but with much smaller and fewer layers
        for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
           lowerCAmelCase     =			AutoTokenizer.from_pretrained(UpperCAmelCase__    )
           lowerCAmelCase     =			FalconForCausalLM.from_pretrained(UpperCAmelCase__    )
           model.eval()
           model.to(UpperCAmelCase__    )
           lowerCAmelCase     =			tokenizer('My favorite food is'    ,      return_tensors='pt'    ).to(UpperCAmelCase__    )

           # We just test that these run without errors - the models are randomly initialized
           # and so the actual text outputs will be garbage
           model.generate(**UpperCAmelCase__    ,      do_sample=UpperCAmelCase__    ,      max_new_tokens=4    )
           model.generate(**UpperCAmelCase__    ,      do_sample=UpperCAmelCase__    ,      max_new_tokens=4    )
           model.generate(**UpperCAmelCase__    ,      num_beams=2    ,      max_new_tokens=4    )





     @slow
     def 							__UpperCAmelCase      ( self       :      Dict    )				->  Any:
        # The big models are way too big for the CI, so we use tiny random models that resemble their
        # architectures but with much smaller and fewer layers
        with torch.no_grad():
           for repo in [
               "Rocketknight1/falcon-rw-1b",
               "Rocketknight1/tiny-random-falcon-7b",
               "Rocketknight1/tiny-random-falcon-40b",
           ]:
              lowerCAmelCase     =			AutoTokenizer.from_pretrained(UpperCAmelCase__    )
              lowerCAmelCase     =			FalconForCausalLM.from_pretrained(UpperCAmelCase__    )
              model.eval()
              model.to(device=UpperCAmelCase__    )
              lowerCAmelCase     =			tokenizer('My favorite food is'    ,      return_tensors='pt'    ).to(UpperCAmelCase__    )

              # Test results are the same with and without cache
              lowerCAmelCase     =			model.generate(**UpperCAmelCase__    ,      do_sample=UpperCAmelCase__    ,      max_new_tokens=2_0    ,      use_cache=UpperCAmelCase__    )
              lowerCAmelCase     =			model.generate(**UpperCAmelCase__    ,      do_sample=UpperCAmelCase__    ,      max_new_tokens=2_0    ,      use_cache=UpperCAmelCase__    )
              self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0    )









import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionAttendAndExcitePipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_numpy, skip_mps, slow
from diffusers.utils.testing_utils import 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 PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


snake_case							:       int     			=      False







@skip_mps
class        snake_case_   (lowerCamelCase_	,						lowerCamelCase_	,						lowerCamelCase_	,						unittest.TestCase      ):
					UpperCAmelCase__					:    Union[str, Any]          =			StableDiffusionAttendAndExcitePipeline
					UpperCAmelCase__					:    List[str]          =			False
					UpperCAmelCase__					:    int          =			TEXT_TO_IMAGE_PARAMS
					UpperCAmelCase__					:    List[Any]          =			TEXT_TO_IMAGE_BATCH_PARAMS.union({'''token_indices'''}      )
					UpperCAmelCase__					:    List[str]          =			TEXT_TO_IMAGE_IMAGE_PARAMS
					UpperCAmelCase__					:    str          =			TEXT_TO_IMAGE_IMAGE_PARAMS
					@classmethod
					def  lowerCamelCase__(      cls   :int      )					->    int:
												super().setUpClass()
												torch.use_deterministic_algorithms(__snake_case      )
					@classmethod
					def  lowerCamelCase__(      cls   :Optional[Any]      )					->    int:
												super().tearDownClass()
												torch.use_deterministic_algorithms(__snake_case      )
					def  lowerCamelCase__(      self   :Dict      )					->    Optional[Any]:
												torch.manual_seed(0      )
												a__             =     UNetaDConditionModel(
												    block_out_channels=(32, 64)			,layers_per_block=1			,sample_size=32			,in_channels=4			,out_channels=4			,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')			,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')			,cross_attention_dim=32			,attention_head_dim=(2, 4)			,use_linear_projection=__snake_case			,)
												a__             =     DDIMScheduler(
												    beta_start=0.0_00_85			,beta_end=0.0_12			,beta_schedule='scaled_linear'			,clip_sample=__snake_case			,set_alpha_to_one=__snake_case			,)
												torch.manual_seed(0      )
												a__             =     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__             =     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=5_12			,)
												a__             =     CLIPTextModel(__snake_case      )
												a__             =     CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'      )

												a__             =     {
												    'unet': unet,
												    'scheduler': scheduler,
												    'vae': vae,
												    'text_encoder': text_encoder,
												    'tokenizer': tokenizer,
												    'safety_checker': None,
												    'feature_extractor': None,
												}

												return components
					def  lowerCamelCase__(      self   :Any			,__snake_case   :Union[str, Any]			,__snake_case   :Tuple=0      )					->    Any:
												if str(__snake_case      ).startswith('mps'      ):
																			a__             =     torch.manual_seed(__snake_case      )
												else:
																			a__             =     torch.Generator(device=__snake_case      ).manual_seed(__snake_case      )
												a__             =     a__             =     {
												    'prompt': 'a cat and a frog',
												    'token_indices': [2, 5],
												    'generator': generator,
												    'num_inference_steps': 1,
												    'guidance_scale': 6.0,
												    'output_type': 'numpy',
												    'max_iter_to_alter': 2,
												    'thresholds': {0: 0.7},
												}
												return inputs
					def  lowerCamelCase__(      self   :Optional[int]      )					->    Any:
												a__             =     'cpu'

												a__             =     self.get_dummy_components()
												a__             =     self.pipeline_class(**__snake_case      )
												pipe.to(__snake_case      )
												pipe.set_progress_bar_config(disable=__snake_case      )

												a__             =     self.get_dummy_inputs(__snake_case      )
												a__             =     pipe(**__snake_case      ).images
												a__             =     image[0, -3:, -3:, -1]

												self.assertEqual(image.shape			,(1, 64, 64, 3)      )
												a__             =     np.array(
												    [0.63_90_53_64, 0.62_89_73_07, 0.48_59_90_17, 0.5_13_36_24, 0.5_55_00_48, 0.45_76_95_16, 0.50_32_69_73, 0.5_02_31_39, 0.45_38_44_96]      )
												a__             =     np.abs(image_slice.flatten() - expected_slice      ).max()
												self.assertLessEqual(__snake_case			,1E-3      )
					def  lowerCamelCase__(      self   :Optional[Any]      )					->    List[str]:
												super().test_cpu_offload_forward_pass(expected_max_diff=5E-4      )
					def  lowerCamelCase__(      self   :Dict      )					->    List[str]:
												# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
												self._test_inference_batch_consistent(batch_sizes=[1, 2]      )
					def  lowerCamelCase__(      self   :List[str]      )					->    Optional[int]:
												self._test_inference_batch_single_identical(batch_size=2			,expected_max_diff=7E-4      )
					def  lowerCamelCase__(      self   :Dict      )					->    Dict:
												super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3      )
					def  lowerCamelCase__(      self   :Dict      )					->    Union[str, Any]:
												super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4      )
					def  lowerCamelCase__(      self   :Optional[Any]      )					->    Dict:
												super().test_save_load_local(expected_max_difference=5E-4      )



					def  lowerCamelCase__(      self   :List[Any]      )					->    List[Any]:
												super().test_save_load_optional_components(expected_max_difference=4E-4      )







@require_torch_gpu
@slow
class        snake_case_   (unittest.TestCase      ):
					@classmethod
					def  lowerCamelCase__(      cls   :Optional[Any]      )					->    Tuple:
												super().setUpClass()
												torch.use_deterministic_algorithms(__snake_case      )
					@classmethod
					def  lowerCamelCase__(      cls   :Optional[int]      )					->    Tuple:
												super().tearDownClass()
												torch.use_deterministic_algorithms(__snake_case      )
					def  lowerCamelCase__(      self   :Tuple      )					->    Union[str, Any]:
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()



					def  lowerCamelCase__(      self   :Optional[Any]      )					->    Tuple:
												a__             =     torch.manual_seed(51      )

												a__             =     StableDiffusionAttendAndExcitePipeline.from_pretrained(
												    'CompVis/stable-diffusion-v1-4'			,safety_checker=__snake_case			,torch_dtype=torch.floataa      )
												pipe.to('cuda'      )

												a__             =     'a painting of an elephant with glasses'
												a__             =     [5, 7]

												a__             =     pipe(
												    prompt=__snake_case			,token_indices=__snake_case			,guidance_scale=7.5			,generator=__snake_case			,num_inference_steps=5			,max_iter_to_alter=5			,output_type='numpy'			,).images[0]

												a__             =     load_numpy(
												    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy'      )
												assert np.abs((expected_image - image).max()      ) < 5E-1




