





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__ :



     '''simple docstring'''

     def __init__(							self						:    int						,lowerCamelCase__						:    List[str]						,lowerCamelCase__						:    Optional[Any]=3						,lowerCamelCase__						:    List[str]=7						,lowerCamelCase__						:    int=True						,lowerCamelCase__						:    Union[str, Any]=True						,lowerCamelCase__						:    Optional[Any]=False						,lowerCamelCase__						:    Dict=True						,lowerCamelCase__						:    Dict=99						,lowerCamelCase__						:    Dict=32						,lowerCamelCase__						:    Tuple=5						,lowerCamelCase__						:    Optional[int]=4						,lowerCamelCase__						:    List[str]=37						,lowerCamelCase__						:    str="gelu"						,lowerCamelCase__						:    List[str]=0.1						,lowerCamelCase__						:    List[Any]=0.1						,lowerCamelCase__						:    int=512						,lowerCamelCase__						:    int=16						,lowerCamelCase__						:    Dict=2						,lowerCamelCase__						:    Any=0.02						,lowerCamelCase__						:    Tuple=3						,lowerCamelCase__						:    str=4						,lowerCamelCase__						:    str=None						,)     ->		int:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						parent
           SCREAMING_SNAKE_CASE		=						batch_size
           SCREAMING_SNAKE_CASE		=						seq_length
           SCREAMING_SNAKE_CASE		=						is_training
           SCREAMING_SNAKE_CASE		=						use_input_mask
           SCREAMING_SNAKE_CASE		=						use_token_type_ids
           SCREAMING_SNAKE_CASE		=						use_labels
           SCREAMING_SNAKE_CASE		=						vocab_size
           SCREAMING_SNAKE_CASE		=						hidden_size
           SCREAMING_SNAKE_CASE		=						num_hidden_layers
           SCREAMING_SNAKE_CASE		=						num_attention_heads
           SCREAMING_SNAKE_CASE		=						intermediate_size
           SCREAMING_SNAKE_CASE		=						hidden_act
           SCREAMING_SNAKE_CASE		=						hidden_dropout_prob
           SCREAMING_SNAKE_CASE		=						attention_probs_dropout_prob
           SCREAMING_SNAKE_CASE		=						max_position_embeddings
           SCREAMING_SNAKE_CASE		=						type_vocab_size
           SCREAMING_SNAKE_CASE		=						type_sequence_label_size
           SCREAMING_SNAKE_CASE		=						initializer_range
           SCREAMING_SNAKE_CASE		=						num_labels
           SCREAMING_SNAKE_CASE		=						num_choices
           SCREAMING_SNAKE_CASE		=						scope






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Tuple       )     ->		int:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						ids_tensor([self.batch_size, self.seq_length]						,self.vocab_size       )

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

           SCREAMING_SNAKE_CASE		=						None

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

           SCREAMING_SNAKE_CASE		=						self.get_config()

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






     def 				SCREAMING_SNAKE_CASE__  (							self						:    str       )     ->		Any:




           '''simple docstring'''


           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=lowerCamelCase__						,initializer_range=self.initializer_range						,pad_token_id=1						,new_decoder_architecture=lowerCamelCase__						,)






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Dict						,lowerCamelCase__						:    Any						,lowerCamelCase__						:    int						,lowerCamelCase__						:    Dict						,lowerCamelCase__						:    Tuple						,lowerCamelCase__						:    Optional[int]						,lowerCamelCase__						:    List[str]						,lowerCamelCase__						:    Union[str, Any]       )     ->		int:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						FalconModel(config=lowerCamelCase__       )
           model.to(lowerCamelCase__       )
           model.eval()
           SCREAMING_SNAKE_CASE		=						model(lowerCamelCase__						,attention_mask=lowerCamelCase__       )
           SCREAMING_SNAKE_CASE		=						model(lowerCamelCase__       )
           self.parent.assertEqual(result.last_hidden_state.shape						,(self.batch_size, self.seq_length, self.hidden_size)       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    List[str]						,lowerCamelCase__						:    Dict						,lowerCamelCase__						:    List[str]						,lowerCamelCase__						:    Optional[Any]						,lowerCamelCase__						:    str						,lowerCamelCase__						:    List[Any]						,lowerCamelCase__						:    Union[str, Any]						,lowerCamelCase__						:    List[Any]						,lowerCamelCase__						:    List[Any]						,lowerCamelCase__						:    Tuple						,)     ->		int:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						True
           SCREAMING_SNAKE_CASE		=						FalconModel(lowerCamelCase__       )
           model.to(lowerCamelCase__       )
           model.eval()
           SCREAMING_SNAKE_CASE		=						model(
               lowerCamelCase__						,attention_mask=lowerCamelCase__						,encoder_hidden_states=lowerCamelCase__						,encoder_attention_mask=lowerCamelCase__						,)
           SCREAMING_SNAKE_CASE		=						model(
               lowerCamelCase__						,attention_mask=lowerCamelCase__						,encoder_hidden_states=lowerCamelCase__						,)
           SCREAMING_SNAKE_CASE		=						model(lowerCamelCase__						,attention_mask=lowerCamelCase__       )
           self.parent.assertEqual(result.last_hidden_state.shape						,(self.batch_size, self.seq_length, self.hidden_size)       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Optional[Any]						,lowerCamelCase__						:    str						,lowerCamelCase__						:    str						,lowerCamelCase__						:    str						,lowerCamelCase__						:    List[Any]						,lowerCamelCase__						:    List[str]						,lowerCamelCase__						:    Optional[int]						,lowerCamelCase__						:    Optional[Any]						,lowerCamelCase__						:    List[Any]						,lowerCamelCase__						:    Optional[int]						,)     ->		Any:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						FalconForCausalLM(config=lowerCamelCase__       )
           model.to(lowerCamelCase__       )
           model.eval()
           SCREAMING_SNAKE_CASE		=						model(lowerCamelCase__						,attention_mask=lowerCamelCase__						,labels=lowerCamelCase__       )
           self.parent.assertEqual(result.logits.shape						,(self.batch_size, self.seq_length, self.vocab_size)       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    List[str]						,lowerCamelCase__						:    List[Any]						,lowerCamelCase__						:    List[str]						,lowerCamelCase__						:    Tuple						,lowerCamelCase__						:    List[Any]						,lowerCamelCase__						:    List[str]						,lowerCamelCase__						:    int						,lowerCamelCase__						:    Optional[Any]						,lowerCamelCase__						:    Tuple						,lowerCamelCase__						:    Dict						,)     ->		List[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						True
           SCREAMING_SNAKE_CASE		=						True
           SCREAMING_SNAKE_CASE		=						FalconForCausalLM(config=lowerCamelCase__       )
           model.to(lowerCamelCase__       )
           model.eval()

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

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

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

           SCREAMING_SNAKE_CASE		=						model(
               lowerCamelCase__						,attention_mask=lowerCamelCase__						,encoder_hidden_states=lowerCamelCase__						,encoder_attention_mask=lowerCamelCase__						,output_hidden_states=lowerCamelCase__						,)["""hidden_states"""][0]
           SCREAMING_SNAKE_CASE		=						model(
               lowerCamelCase__						,attention_mask=lowerCamelCase__						,encoder_hidden_states=lowerCamelCase__						,encoder_attention_mask=lowerCamelCase__						,past_key_values=lowerCamelCase__						,output_hidden_states=lowerCamelCase__						,)["""hidden_states"""][0]

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






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Any       )     ->		str:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						self.prepare_config_and_inputs()
           (
               (
               SCREAMING_SNAKE_CASE
           ),					(
               SCREAMING_SNAKE_CASE
           ),					(
               SCREAMING_SNAKE_CASE
           ),					(
               SCREAMING_SNAKE_CASE
           ),					(
               SCREAMING_SNAKE_CASE
           ),					(
               SCREAMING_SNAKE_CASE
           ),					(
               SCREAMING_SNAKE_CASE
           ),					
           )		=						config_and_inputs
           SCREAMING_SNAKE_CASE		=						{"""input_ids""": input_ids, """attention_mask""": input_mask}
           return config, inputs_dict

@require_torch
class 		UpperCamelCase__ (      lowerCAmelCase_							,      lowerCAmelCase_							,      lowerCAmelCase_							,      unittest.TestCase   ):



     '''simple docstring'''

     __snake_case    :	Union[str, Any]			=			(
         (
             FalconModel,
             FalconForCausalLM,
             FalconForSequenceClassification,
             FalconForTokenClassification,
             FalconForQuestionAnswering,
         )
         if is_torch_available()
         else ()
     )
     __snake_case    :	str			=			(FalconForCausalLM,) if is_torch_available() else ()
     __snake_case    :	Optional[Any]			=			(
         {
             "feature-extraction": FalconModel,
             "text-classification": FalconForSequenceClassification,
             "text-generation": FalconForCausalLM,
             "question-answering": FalconForQuestionAnswering,
             "token-classification": FalconForTokenClassification,
             "zero-shot": FalconForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )
     __snake_case    :	Optional[int]			=			False
     __snake_case    :	Optional[int]			=			False






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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						FalconModelTester(self       )
           SCREAMING_SNAKE_CASE		=						ConfigTester(self						,config_class=lowerCamelCase__						,hidden_size=37       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    str       )     ->		Tuple:




           '''simple docstring'''


           self.config_tester.run_common_tests()






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Tuple       )     ->		List[str]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowerCamelCase__       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    List[Any]       )     ->		Dict:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE,					*SCREAMING_SNAKE_CASE		=						self.model_tester.prepare_config_and_inputs()
           for alibi in [True, False]:
                 SCREAMING_SNAKE_CASE		=						alibi
                 self.model_tester.create_and_check_model(lowerCamelCase__						,*lowerCamelCase__       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Tuple       )     ->		int:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE,					SCREAMING_SNAKE_CASE		=						self.model_tester.prepare_config_and_inputs_for_common()
           SCREAMING_SNAKE_CASE		=						3
           SCREAMING_SNAKE_CASE		=						input_dict["""input_ids"""]
           SCREAMING_SNAKE_CASE		=						input_ids.ne(1       ).to(lowerCamelCase__       )
           SCREAMING_SNAKE_CASE		=						ids_tensor([self.model_tester.batch_size]						,self.model_tester.type_sequence_label_size       )
           SCREAMING_SNAKE_CASE		=						FalconForSequenceClassification(lowerCamelCase__       )
           model.to(lowerCamelCase__       )
           model.eval()
           SCREAMING_SNAKE_CASE		=						model(lowerCamelCase__						,attention_mask=lowerCamelCase__						,labels=lowerCamelCase__       )
           self.assertEqual(result.logits.shape						,(self.model_tester.batch_size, self.model_tester.num_labels)       )






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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE,					SCREAMING_SNAKE_CASE		=						self.model_tester.prepare_config_and_inputs_for_common()
           SCREAMING_SNAKE_CASE		=						3
           SCREAMING_SNAKE_CASE		=						"""single_label_classification"""
           SCREAMING_SNAKE_CASE		=						input_dict["""input_ids"""]
           SCREAMING_SNAKE_CASE		=						input_ids.ne(1       ).to(lowerCamelCase__       )
           SCREAMING_SNAKE_CASE		=						ids_tensor([self.model_tester.batch_size]						,self.model_tester.type_sequence_label_size       )
           SCREAMING_SNAKE_CASE		=						FalconForSequenceClassification(lowerCamelCase__       )
           model.to(lowerCamelCase__       )
           model.eval()
           SCREAMING_SNAKE_CASE		=						model(lowerCamelCase__						,attention_mask=lowerCamelCase__						,labels=lowerCamelCase__       )
           self.assertEqual(result.logits.shape						,(self.model_tester.batch_size, self.model_tester.num_labels)       )






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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE,					SCREAMING_SNAKE_CASE		=						self.model_tester.prepare_config_and_inputs_for_common()
           SCREAMING_SNAKE_CASE		=						input_dict["""input_ids"""]
           SCREAMING_SNAKE_CASE		=						FalconForCausalLM(lowerCamelCase__       )
           model.to(lowerCamelCase__       )
           model.eval()
           SCREAMING_SNAKE_CASE		=						model(lowerCamelCase__						,use_cache=lowerCamelCase__       )
           SCREAMING_SNAKE_CASE		=						input_ids.shape[0]
           SCREAMING_SNAKE_CASE		=						model._convert_to_rw_cache(result.past_key_values       )
           SCREAMING_SNAKE_CASE		=						model._convert_cache_to_standard_format(lowerCamelCase__						,lowerCamelCase__       )
           for layer in range(len(lowerCamelCase__       )       ):
                 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 				SCREAMING_SNAKE_CASE__  (							self						:    int       )     ->		List[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE,					SCREAMING_SNAKE_CASE		=						self.model_tester.prepare_config_and_inputs_for_common()
           SCREAMING_SNAKE_CASE		=						3
           SCREAMING_SNAKE_CASE		=						"""multi_label_classification"""
           SCREAMING_SNAKE_CASE		=						input_dict["""input_ids"""]
           SCREAMING_SNAKE_CASE		=						input_ids.ne(1       ).to(lowerCamelCase__       )
           SCREAMING_SNAKE_CASE		=						ids_tensor(
               [self.model_tester.batch_size, config.num_labels]						,self.model_tester.type_sequence_label_size       ).to(torch.float       )
           SCREAMING_SNAKE_CASE		=						FalconForSequenceClassification(lowerCamelCase__       )
           model.to(lowerCamelCase__       )
           model.eval()
           SCREAMING_SNAKE_CASE		=						model(lowerCamelCase__						,attention_mask=lowerCamelCase__						,labels=lowerCamelCase__       )
           self.assertEqual(result.logits.shape						,(self.model_tester.batch_size, self.model_tester.num_labels)       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Tuple       )     ->		Optional[Any]:




           '''simple docstring'''


           for model_class in self.all_generative_model_classes:
                 SCREAMING_SNAKE_CASE,					SCREAMING_SNAKE_CASE		=						self.model_tester.prepare_config_and_inputs_for_common()

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

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

                 # 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

                 SCREAMING_SNAKE_CASE		=						(
                     getattr(lowerCamelCase__						,"""decoder_layers"""						,lowerCamelCase__       )
                     or getattr(lowerCamelCase__						,"""num_decoder_layers"""						,lowerCamelCase__       )
                     or config.num_hidden_layers
                 )
                 SCREAMING_SNAKE_CASE		=						getattr(lowerCamelCase__						,"""num_kv_heads"""						,config.num_attention_heads       )
                 SCREAMING_SNAKE_CASE		=						getattr(lowerCamelCase__						,"""d_model"""						,config.hidden_size       )
                 SCREAMING_SNAKE_CASE		=						embed_dim // num_attention_heads

                 SCREAMING_SNAKE_CASE		=						outputs["""past_key_values"""]
                 self.assertEqual(len(lowerCamelCase__       )						,lowerCamelCase__       )

                 SCREAMING_SNAKE_CASE,					SCREAMING_SNAKE_CASE		=						inputs["""input_ids"""].shape
                 for i in range(lowerCamelCase__       ):
                       if config.new_decoder_architecture:
                             SCREAMING_SNAKE_CASE		=						config.num_attention_heads
                       elif config.multi_query:
                             SCREAMING_SNAKE_CASE		=						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   ):



     '''simple docstring'''

     @slow
     def 				SCREAMING_SNAKE_CASE__  (							self						:    List[str]       )     ->		Union[str, Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						AutoTokenizer.from_pretrained("""Rocketknight1/falcon-rw-1b"""       )
           SCREAMING_SNAKE_CASE		=						FalconForCausalLM.from_pretrained("""Rocketknight1/falcon-rw-1b"""       )
           model.eval()
           model.to(lowerCamelCase__       )
           SCREAMING_SNAKE_CASE		=						tokenizer("""My favorite food is"""						,return_tensors="""pt"""       ).to(lowerCamelCase__       )

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

           SCREAMING_SNAKE_CASE		=						model.generate(**lowerCamelCase__						,do_sample=lowerCamelCase__						,max_new_tokens=19       )
           SCREAMING_SNAKE_CASE		=						tokenizer.batch_decode(lowerCamelCase__       )[0]

           self.assertEqual(lowerCamelCase__						,lowerCamelCase__       )






     @slow
     def 				SCREAMING_SNAKE_CASE__  (							self						:    Optional[int]       )     ->		str:




           '''simple docstring'''


           for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
                 SCREAMING_SNAKE_CASE		=						AutoTokenizer.from_pretrained(lowerCamelCase__       )
                 SCREAMING_SNAKE_CASE		=						FalconForCausalLM.from_pretrained(lowerCamelCase__       )
                 model.eval()
                 model.to(lowerCamelCase__       )
                 SCREAMING_SNAKE_CASE		=						tokenizer("""My favorite food is"""						,return_tensors="""pt"""       ).to(lowerCamelCase__       )

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






     @slow
     def 				SCREAMING_SNAKE_CASE__  (							self						:    Union[str, Any]       )     ->		Union[str, Any]:




           '''simple docstring'''


           with torch.no_grad():
                 for repo in [
                     "Rocketknight1/falcon-rw-1b",
                     "Rocketknight1/tiny-random-falcon-7b",
                     "Rocketknight1/tiny-random-falcon-40b",
                 ]:
                       SCREAMING_SNAKE_CASE		=						AutoTokenizer.from_pretrained(lowerCamelCase__       )
                       SCREAMING_SNAKE_CASE		=						FalconForCausalLM.from_pretrained(lowerCamelCase__       )
                       model.eval()
                       model.to(device=lowerCamelCase__       )
                       SCREAMING_SNAKE_CASE		=						tokenizer("""My favorite food is"""						,return_tensors="""pt"""       ).to(lowerCamelCase__       )

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






'''simple docstring'''

import gc
import unittest

import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DDPMScheduler,
    PriorTransformer,
    StableUnCLIPPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device

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,
    assert_mean_pixel_difference,
)


enable_full_determinism()





class      snake_case    (    lowercase			,						lowercase			,						lowercase			,						unittest.TestCase			):





  """simple docstring"""




  _lowerCamelCase		    =  StableUnCLIPPipeline
  _lowerCamelCase		    =  TEXT_TO_IMAGE_PARAMS
  _lowerCamelCase		    =  TEXT_TO_IMAGE_BATCH_PARAMS
  _lowerCamelCase		    =  TEXT_TO_IMAGE_IMAGE_PARAMS
  _lowerCamelCase		    =  TEXT_TO_IMAGE_IMAGE_PARAMS

  # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false
  _lowerCamelCase		    =  False






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  32
   lowerCamelCase_      =  embedder_hidden_size

   # prior components

   torch.manual_seed(0     )
   lowerCamelCase_      =  CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

   torch.manual_seed(0     )
   lowerCamelCase_      =  CLIPTextModelWithProjection(
       CLIPTextConfig(
           bos_token_id=0			,  eos_token_id=2			,  hidden_size=UpperCamelCase			,  projection_dim=UpperCamelCase			,  intermediate_size=37			,  layer_norm_eps=1e-05			,  num_attention_heads=4			,  num_hidden_layers=5			,  pad_token_id=1			,  vocab_size=1000			,  )     )

   torch.manual_seed(0     )
   lowerCamelCase_      =  PriorTransformer(
       num_attention_heads=2			,  attention_head_dim=12			,  embedding_dim=UpperCamelCase			,  num_layers=1			,  )

   torch.manual_seed(0     )
   lowerCamelCase_      =  DDPMScheduler(
       variance_type="fixed_small_log"			,  prediction_type="sample"			,  num_train_timesteps=1000			,  clip_sample=UpperCamelCase			,  clip_sample_range=5.0			,  beta_schedule="squaredcos_cap_v2"			,  )

   # regular denoising components

   torch.manual_seed(0     )
   lowerCamelCase_      =  StableUnCLIPImageNormalizer(embedding_dim=UpperCamelCase     )
   lowerCamelCase_      =  DDPMScheduler(beta_schedule="squaredcos_cap_v2"     )

   torch.manual_seed(0     )
   lowerCamelCase_      =  CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

   torch.manual_seed(0     )
   lowerCamelCase_      =  CLIPTextModel(
       CLIPTextConfig(
           bos_token_id=0			,  eos_token_id=2			,  hidden_size=UpperCamelCase			,  projection_dim=32			,  intermediate_size=37			,  layer_norm_eps=1e-05			,  num_attention_heads=4			,  num_hidden_layers=5			,  pad_token_id=1			,  vocab_size=1000			,  )     )

   torch.manual_seed(0     )
   lowerCamelCase_      =  UNetaDConditionModel(
       sample_size=32			,  in_channels=4			,  out_channels=4			,  down_block_types=("CrossAttnDownBlock2D", "DownBlock2D")			,  up_block_types=("UpBlock2D", "CrossAttnUpBlock2D")			,  block_out_channels=(32, 64)			,  attention_head_dim=(2, 4)			,  class_embed_type="projection"			,  projection_class_embeddings_input_dim=embedder_projection_dim * 2			,  cross_attention_dim=UpperCamelCase			,  layers_per_block=1			,  upcast_attention=UpperCamelCase			,  use_linear_projection=UpperCamelCase			,  )

   torch.manual_seed(0     )
   lowerCamelCase_      =  DDIMScheduler(
       beta_schedule="scaled_linear"			,  beta_start=0.00_085			,  beta_end=0.012			,  prediction_type="v_prediction"			,  set_alpha_to_one=UpperCamelCase			,  steps_offset=1			,  )

   torch.manual_seed(0     )
   lowerCamelCase_      =  AutoencoderKL()

   lowerCamelCase_      =  {
       # prior components
       "prior_tokenizer": prior_tokenizer,
       "prior_text_encoder": prior_text_encoder,
       "prior": prior,
       "prior_scheduler": prior_scheduler,
       # image noising components
       "image_normalizer": image_normalizer,
       "image_noising_scheduler": image_noising_scheduler,
       # regular denoising components
       "tokenizer": tokenizer,
       "text_encoder": text_encoder,
       "unet": unet,
       "scheduler": scheduler,
       "vae": vae,
   }

   return components






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase=0     ):







   """simple docstring"""
   if str(UpperCamelCase     ).startswith("mps"     ):
    lowerCamelCase_      =  torch.manual_seed(UpperCamelCase     )
   else:
    lowerCamelCase_      =  torch.Generator(device=UpperCamelCase     ).manual_seed(UpperCamelCase     )
   lowerCamelCase_      =  {
       "prompt": "A painting of a squirrel eating a burger",
       "generator": generator,
       "num_inference_steps": 2,
       "prior_num_inference_steps": 2,
       "output_type": "numpy",
   }
   return inputs






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  torch_device == "cpu"

   self._test_attention_slicing_forward_pass(test_max_difference=UpperCamelCase     )







  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  torch_device in ["cpu", "mps"]

   self._test_inference_batch_single_identical(test_max_difference=UpperCamelCase     )





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





  """simple docstring"""




  def   snake_case		(    self     ):







   """simple docstring"""
   # clean up the VRAM after each test
   super().tearDown()
   gc.collect()
   torch.cuda.empty_cache()






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  load_numpy(
       "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy"     )

   lowerCamelCase_      =  StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l"			,  torch_dtype=torch.floataa     )
   pipe.to(UpperCamelCase     )
   pipe.set_progress_bar_config(disable=UpperCamelCase     )
   # 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()

   lowerCamelCase_      =  torch.Generator(device="cpu"     ).manual_seed(0     )
   lowerCamelCase_      =  pipe("anime turle"			,  generator=UpperCamelCase			,  output_type="np"     )

   lowerCamelCase_      =  output.images[0]

   assert image.shape == (768, 768, 3)

   assert_mean_pixel_difference(UpperCamelCase			,  UpperCamelCase     )







  def   snake_case		(    self     ):







   """simple docstring"""
   torch.cuda.empty_cache()
   torch.cuda.reset_max_memory_allocated()
   torch.cuda.reset_peak_memory_stats()

   lowerCamelCase_      =  StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l"			,  torch_dtype=torch.floataa     )
   lowerCamelCase_      =  pipe.to(UpperCamelCase     )
   pipe.set_progress_bar_config(disable=UpperCamelCase     )
   pipe.enable_attention_slicing()
   pipe.enable_sequential_cpu_offload()

   lowerCamelCase_      =  pipe(
       "anime turtle"			,  prior_num_inference_steps=2			,  num_inference_steps=2			,  output_type="np"			,  )

   lowerCamelCase_      =  torch.cuda.max_memory_allocated()
   # make sure that less than 7 GB is allocated
   assert mem_bytes < 7 * 10**9



