




import math
import unittest

from transformers import BioGptConfig, 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 (
      BioGptForCausalLM,
      BioGptForSequenceClassification,
      BioGptForTokenClassification,
      BioGptModel,
      BioGptTokenizer,
  )
  from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST


class 							UpperCamelCase_       :

    '''simple docstring'''






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





           '''simple docstring'''

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


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





           '''simple docstring'''

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

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

           A__ 					=       None
           if self.use_token_type_ids:
                  A__ 					=       ids_tensor([self.batch_size, self.seq_length]   ,					self.type_vocab_size)

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

           A__ 					=       self.get_config()

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


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





           '''simple docstring'''

           return BioGptConfig(
               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   ,					)


    def 			SCREAMING_SNAKE_CASE				(     self :      Optional[int]   ,					UpperCAmelCase__ :      Any   ,					UpperCAmelCase__ :      int   ,					UpperCAmelCase__ :      Optional[int]   ,					UpperCAmelCase__ :      List[str]   ,					UpperCAmelCase__ :      str   ,					UpperCAmelCase__ :      List[str]   ,					UpperCAmelCase__ :      List[str])		->Union[str, Any]:





           '''simple docstring'''

           A__ 					=       BioGptModel(config=lowerCamelCase_)
           model.to(lowerCamelCase_)
           model.eval()
           A__ 					=       model(lowerCamelCase_   ,					attention_mask=lowerCamelCase_)
           A__ 					=       model(lowerCamelCase_)
           self.parent.assertEqual(result.last_hidden_state.shape   ,					(self.batch_size, self.seq_length, self.hidden_size))


    def 			SCREAMING_SNAKE_CASE				(     self :      str   ,					UpperCAmelCase__ :      Dict   ,					UpperCAmelCase__ :      Union[str, Any]   ,					UpperCAmelCase__ :      Optional[int]   ,					UpperCAmelCase__ :      Dict   ,					UpperCAmelCase__ :      List[str]   ,					UpperCAmelCase__ :      int   ,					UpperCAmelCase__ :      int   ,					UpperCAmelCase__ :      int   ,					UpperCAmelCase__ :      Optional[Any]   ,					)		->Optional[Any]:





           '''simple docstring'''

           A__ 					=       BioGptForCausalLM(config=lowerCamelCase_)
           model.to(lowerCamelCase_)
           model.eval()
           A__ 					=       model(lowerCamelCase_   ,					attention_mask=lowerCamelCase_   ,					token_type_ids=lowerCamelCase_   ,					labels=lowerCamelCase_)
           self.parent.assertEqual(result.logits.shape   ,					(self.batch_size, self.seq_length, self.vocab_size))


    def 			SCREAMING_SNAKE_CASE				(     self :      Optional[Any]   ,					UpperCAmelCase__ :      Dict   ,					UpperCAmelCase__ :      Union[str, Any]   ,					UpperCAmelCase__ :      str   ,					UpperCAmelCase__ :      Dict   ,					UpperCAmelCase__ :      List[Any]   ,					*UpperCAmelCase__ :      int)		->int:





           '''simple docstring'''

           A__ 					=       BioGptModel(config=lowerCamelCase_)
           model.to(lowerCamelCase_)
           model.eval()

           # create attention mask
           A__ 					=       torch.ones(input_ids.shape   ,					dtype=torch.long   ,					device=lowerCamelCase_)
           A__ 					=       self.seq_length // 2
           A__ 					=       0

           # first forward pass
           A__ 					=       model(lowerCamelCase_   ,					attention_mask=lowerCamelCase_).to_tuple()

           # create hypothetical next token and extent to next_input_ids
           A__ 					=       ids_tensor((self.batch_size, 1)   ,					config.vocab_size)

           # change a random masked slice from input_ids
           A__ 					=       ids_tensor((1,)   ,					lowerCamelCase_).item() + 1
           A__ 					=       ids_tensor((self.batch_size, 1)   ,					config.vocab_size).squeeze(-1)
           A__ 					=       random_other_next_tokens

           # append to next input_ids and attn_mask
           A__ 					=       torch.cat([input_ids, next_tokens]   ,					dim=-1)
           A__ 					=       torch.cat(
               [attn_mask, torch.ones((attn_mask.shape[0], 1)   ,					dtype=torch.long   ,					device=lowerCamelCase_)]   ,					dim=1   ,					)

           # get two different outputs
           A__ 					=       model(lowerCamelCase_   ,					attention_mask=lowerCamelCase_)["""last_hidden_state"""]
           A__ 					=       model(lowerCamelCase_   ,					past_key_values=lowerCamelCase_   ,					attention_mask=lowerCamelCase_)["""last_hidden_state"""]

           # select random slice
           A__ 					=       ids_tensor((1,)   ,					output_from_past.shape[-1]).item()
           A__ 					=       output_from_no_past[:, -1, random_slice_idx].detach()
           A__ 					=       output_from_past[:, 0, random_slice_idx].detach()

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


    def 			SCREAMING_SNAKE_CASE				(     self :      Any   ,					UpperCAmelCase__ :      Optional[int]   ,					UpperCAmelCase__ :      Dict   ,					UpperCAmelCase__ :      Optional[Any]   ,					UpperCAmelCase__ :      List[Any]   ,					UpperCAmelCase__ :      int   ,					*UpperCAmelCase__ :      Optional[Any])		->str:





           '''simple docstring'''

           A__ 					=       BioGptModel(config=lowerCamelCase_).to(lowerCamelCase_).eval()

           A__ 					=       torch.ones(input_ids.shape   ,					dtype=torch.long   ,					device=lowerCamelCase_)

           # first forward pass
           A__ 					=       model(lowerCamelCase_   ,					attention_mask=lowerCamelCase_   ,					use_cache=lowerCamelCase_)

           A__ 					=       outputs.to_tuple()

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

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

           A__ 					=       model(lowerCamelCase_   ,					attention_mask=lowerCamelCase_)["""last_hidden_state"""]
           A__ 					=       model(lowerCamelCase_   ,					attention_mask=lowerCamelCase_   ,					past_key_values=lowerCamelCase_)[
               """last_hidden_state"""
           ]

           # select random slice
           A__ 					=       ids_tensor((1,)   ,					output_from_past.shape[-1]).item()
           A__ 					=       output_from_no_past[:, -3:, random_slice_idx].detach()
           A__ 					=       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 :      str   ,					UpperCAmelCase__ :      Optional[Any]   ,					UpperCAmelCase__ :      List[str]   ,					UpperCAmelCase__ :      Tuple   ,					UpperCAmelCase__ :      Optional[Any]   ,					UpperCAmelCase__ :      List[str]   ,					*UpperCAmelCase__ :      List[Any]   ,					UpperCAmelCase__ :      Optional[int]=False)		->List[str]:





           '''simple docstring'''

           A__ 					=       BioGptForCausalLM(lowerCamelCase_)
           model.to(lowerCamelCase_)
           if gradient_checkpointing:
                  model.gradient_checkpointing_enable()

           A__ 					=       model(lowerCamelCase_   ,					labels=lowerCamelCase_)
           self.parent.assertEqual(result.loss.shape   ,					())
           self.parent.assertEqual(result.logits.shape   ,					(self.batch_size, self.seq_length, self.vocab_size))
           result.loss.backward()


    def 			SCREAMING_SNAKE_CASE				(     self :      List[Any]   ,					UpperCAmelCase__ :      Dict   ,					*UpperCAmelCase__ :      List[str])		->str:





           '''simple docstring'''

           A__ 					=       BioGptModel(lowerCamelCase_)
           A__ 					=       model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers)
           for key in model.state_dict().keys():
                  if "c_proj" in key and "weight" in key:
                         self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key]) - model_std)   ,					0.001)
                         self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]) - 0.0)   ,					0.01)


    def 			SCREAMING_SNAKE_CASE				(     self :      Tuple   ,					UpperCAmelCase__ :      Dict   ,					UpperCAmelCase__ :      Optional[Any]   ,					UpperCAmelCase__ :      Any   ,					UpperCAmelCase__ :      Optional[int]   ,					UpperCAmelCase__ :      Union[str, Any]   ,					*UpperCAmelCase__ :      List[str])		->Any:





           '''simple docstring'''

           A__ 					=       self.num_labels
           A__ 					=       BioGptForTokenClassification(lowerCamelCase_)
           model.to(lowerCamelCase_)
           model.eval()
           A__ 					=       model(lowerCamelCase_   ,					attention_mask=lowerCamelCase_   ,					token_type_ids=lowerCamelCase_)
           self.parent.assertEqual(result.logits.shape   ,					(self.batch_size, self.seq_length, self.num_labels))





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





           '''simple docstring'''

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


@require_torch
class 							UpperCamelCase_       (					lowercase_						,   lowercase_						,   lowercase_						,   unittest.TestCase	):

    '''simple docstring'''






    UpperCAmelCase__				    = (
        (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification)
        if is_torch_available()
        else ()
    )
    UpperCAmelCase__				    = (BioGptForCausalLM,) if is_torch_available() else ()
    UpperCAmelCase__				    = (
        {
            '''feature-extraction''': BioGptModel,
            '''text-classification''': BioGptForSequenceClassification,
            '''text-generation''': BioGptForCausalLM,
            '''token-classification''': BioGptForTokenClassification,
            '''zero-shot''': BioGptForSequenceClassification,
        }
        if is_torch_available()
        else {}
    )
    UpperCAmelCase__				    = False


    def 			SCREAMING_SNAKE_CASE				(     self :      List[str])		->List[Any]:





           '''simple docstring'''

           A__ 					=       BioGptModelTester(self)
           A__ 					=       ConfigTester(self   ,					config_class=lowerCamelCase_   ,					hidden_size=37)


    def 			SCREAMING_SNAKE_CASE				(     self :      str)		->Any:





           '''simple docstring'''

           self.config_tester.run_common_tests()


    def 			SCREAMING_SNAKE_CASE				(     self :      str)		->Tuple:





           '''simple docstring'''

           A__ 					=       self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowerCamelCase_)


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





           '''simple docstring'''

           A__ 					=       self.model_tester.prepare_config_and_inputs()
           for type in ["absolute", "relative_key", "relative_key_query"]:
                  A__ 					=       type
                  self.model_tester.create_and_check_model(*lowerCamelCase_)


    def 			SCREAMING_SNAKE_CASE				(     self :      Union[str, Any])		->Optional[int]:





           '''simple docstring'''

           A__ 					=       self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_biogpt_model_attention_mask_past(*lowerCamelCase_)


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





           '''simple docstring'''

           A__ 					=       self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_forward_and_backwards(*lowerCamelCase_   ,					gradient_checkpointing=lowerCamelCase_)


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





           '''simple docstring'''

           A__ 					=       self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_biogpt_model_past_large_inputs(*lowerCamelCase_)


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





           '''simple docstring'''

           A__ 					=       self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_biogpt_weight_initialization(*lowerCamelCase_)


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





           '''simple docstring'''

           A__ 					=       self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_biogpt_for_token_classification(*lowerCamelCase_)


    @slow
    def 			SCREAMING_SNAKE_CASE				(     self :      List[str])		->Tuple:





           '''simple docstring'''

           A__ 					=       BioGptForCausalLM.from_pretrained('''microsoft/biogpt''')
           model.to(lowerCamelCase_)
           A__ 					=       BioGptTokenizer.from_pretrained('''microsoft/biogpt''')

           A__ 					=       """left"""

           # Define PAD Token = EOS Token = 50256
           A__ 					=       tokenizer.eos_token
           A__ 					=       model.config.eos_token_id

           # use different length sentences to test batching
           A__ 					=       [
               """Hello, my dog is a little""",
               """Today, I""",
           ]

           A__ 					=       tokenizer(lowerCamelCase_   ,					return_tensors='''pt'''   ,					padding=lowerCamelCase_)
           A__ 					=       inputs["""input_ids"""].to(lowerCamelCase_)

           A__ 					=       model.generate(
               input_ids=lowerCamelCase_   ,					attention_mask=inputs['''attention_mask'''].to(lowerCamelCase_)   ,					)

           A__ 					=       tokenizer(sentences[0]   ,					return_tensors='''pt''').input_ids.to(lowerCamelCase_)
           A__ 					=       model.generate(input_ids=lowerCamelCase_)

           A__ 					=       inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item()
           A__ 					=       tokenizer(sentences[1]   ,					return_tensors='''pt''').input_ids.to(lowerCamelCase_)
           A__ 					=       model.generate(input_ids=lowerCamelCase_   ,					max_length=model.config.max_length - num_paddings)

           A__ 					=       tokenizer.batch_decode(lowerCamelCase_   ,					skip_special_tokens=lowerCamelCase_)
           A__ 					=       tokenizer.decode(output_non_padded[0]   ,					skip_special_tokens=lowerCamelCase_)
           A__ 					=       tokenizer.decode(output_padded[0]   ,					skip_special_tokens=lowerCamelCase_)

           A__ 					=       [
               """Hello, my dog is a little bit bigger than a little bit.""",
               """Today, I have a good idea of how to use the information""",
           ]
           self.assertListEqual(lowerCamelCase_   ,					lowerCamelCase_)
           self.assertListEqual(lowerCamelCase_   ,					[non_padded_sentence, padded_sentence])


    @slow
    def 			SCREAMING_SNAKE_CASE				(     self :      Tuple)		->Optional[int]:





           '''simple docstring'''

           for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  A__ 					=       BioGptModel.from_pretrained(lowerCamelCase_)
                  self.assertIsNotNone(lowerCamelCase_)


    def 			SCREAMING_SNAKE_CASE				(     self :      Optional[int])		->Union[str, Any]:





           '''simple docstring'''

           A__ 					=       self.model_tester.prepare_config_and_inputs_for_common()
           A__ 					=       3
           A__ 					=       input_dict["""input_ids"""]
           A__ 					=       input_ids.ne(1).to(lowerCamelCase_)
           A__ 					=       ids_tensor([self.model_tester.batch_size]   ,					self.model_tester.type_sequence_label_size)
           A__ 					=       BioGptForSequenceClassification(lowerCamelCase_)
           model.to(lowerCamelCase_)
           model.eval()
           A__ 					=       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 :      Optional[Any])		->List[Any]:





           '''simple docstring'''

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


@require_torch
class 							UpperCamelCase_       (					unittest.TestCase	):

    '''simple docstring'''






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





           '''simple docstring'''

           A__ 					=       BioGptForCausalLM.from_pretrained('''microsoft/biogpt''')
           A__ 					=       torch.tensor([[2, 4_805, 9, 656, 21]])
           A__ 					=       model(lowerCamelCase_)[0]

           A__ 					=       42_384

           A__ 					=       torch.Size((1, 5, vocab_size))
           self.assertEqual(output.shape   ,					lowerCamelCase_)

           A__ 					=       torch.tensor(
               [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]])

           self.assertTrue(torch.allclose(output[:, :3, :3]   ,					lowerCamelCase_   ,					atol=1e-4))





    @slow
    def 			SCREAMING_SNAKE_CASE				(     self :      Optional[int])		->Any:





           '''simple docstring'''

           A__ 					=       BioGptTokenizer.from_pretrained('''microsoft/biogpt''')
           A__ 					=       BioGptForCausalLM.from_pretrained('''microsoft/biogpt''')
           model.to(lowerCamelCase_)

           torch.manual_seed(0)
           A__ 					=       tokenizer('''COVID-19 is'''   ,					return_tensors='''pt''').to(lowerCamelCase_)
           A__ 					=       model.generate(
               **lowerCamelCase_   ,					min_length=100   ,					max_length=1_024   ,					num_beams=5   ,					early_stopping=lowerCamelCase_   ,					)
           A__ 					=       tokenizer.decode(output_ids[0]   ,					skip_special_tokens=lowerCamelCase_)

           A__ 					=       (
               """COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the"""
               """ causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and"""
               """ territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),"""
               """ and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and"""
               """ more than 800,000 deaths."""
           )
           self.assertEqual(lowerCamelCase_   ,					lowerCamelCase_)









'''simple docstring'''




from typing import Any, Callable, Dict, List, Optional, Union

import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker


__UpperCAmelCase            =       """CompVis/stable-diffusion-v1-1"""
__UpperCAmelCase            =       """CompVis/stable-diffusion-v1-2"""
__UpperCAmelCase            =       """CompVis/stable-diffusion-v1-3"""
__UpperCAmelCase            =       """CompVis/stable-diffusion-v1-4"""




class      UpperCamelCase__					(					lowercase_			):




					"""simple docstring"""


					def __init__(						self				:			List[str]      ,						lowerCamelCase_				:			AutoencoderKL      ,						lowerCamelCase_				:			CLIPTextModel      ,						lowerCamelCase_				:			CLIPTokenizer      ,						lowerCamelCase_				:			UNetaDConditionModel      ,						lowerCamelCase_				:			Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]      ,						lowerCamelCase_				:			StableDiffusionSafetyChecker      ,						lowerCamelCase_				:			CLIPImageProcessor      ,						lowerCamelCase_				:			bool = True      ,						):

							'''simple docstring'''



							super()._init_()

							SCREAMING_SNAKE_CASE :				Tuple		=			StableDiffusionPipeline.from_pretrained(lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				List[Any]		=			StableDiffusionPipeline.from_pretrained(lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				List[Any]		=			StableDiffusionPipeline.from_pretrained(lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				Optional[int]		=			StableDiffusionPipeline(
							    vae=lowerCamelCase_      ,						text_encoder=lowerCamelCase_      ,						tokenizer=lowerCamelCase_      ,						unet=lowerCamelCase_      ,						scheduler=lowerCamelCase_      ,						safety_checker=lowerCamelCase_      ,						feature_extractor=lowerCamelCase_      ,						requires_safety_checker=lowerCamelCase_      ,						)

							self.register_modules(pipelinea=self.pipea      ,						pipelinea=self.pipea      ,						pipelinea=self.pipea      ,						pipelinea=self.pipea						)


					@property
					def lowerCamelCase_			(						self				:			int						):

							'''simple docstring'''



							return {k: getattr(self      ,						lowerCamelCase_						) for k in self.config.keys() if not k.startswith("""_"""						)}


					def lowerCamelCase_			(						self				:			Any      ,						lowerCamelCase_				:			Optional[Union[str, int]] = "auto"						):

							'''simple docstring'''



							if slice_size == "auto":
									# half the attention head size is usually a good trade-off between
									# speed and memory
									SCREAMING_SNAKE_CASE :				Optional[int]		=			self.unet.config.attention_head_dim // 2
							self.unet.set_attention_slice(lowerCamelCase_						)


					def lowerCamelCase_			(						self				:			Dict						):

							'''simple docstring'''



							self.enable_attention_slicing(lowerCamelCase_						)


					@torch.no_grad()
					def lowerCamelCase_			(						self				:			Optional[Any]      ,						lowerCamelCase_				:			Union[str, List[str]]      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 50      ,						lowerCamelCase_				:			float = 7.5      ,						lowerCamelCase_				:			Optional[Union[str, List[str]]] = None      ,						lowerCamelCase_				:			Optional[int] = 1      ,						lowerCamelCase_				:			float = 0.0      ,						lowerCamelCase_				:			Optional[torch.Generator] = None      ,						lowerCamelCase_				:			Optional[torch.FloatTensor] = None      ,						lowerCamelCase_				:			Optional[str] = "pil"      ,						lowerCamelCase_				:			bool = True      ,						lowerCamelCase_				:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,						lowerCamelCase_				:			int = 1      ,						**lowerCamelCase_				:			Union[str, Any]      ,						):

							'''simple docstring'''



							return self.pipea(
							    prompt=lowerCamelCase_      ,						height=lowerCamelCase_      ,						width=lowerCamelCase_      ,						num_inference_steps=lowerCamelCase_      ,						guidance_scale=lowerCamelCase_      ,						negative_prompt=lowerCamelCase_      ,						num_images_per_prompt=lowerCamelCase_      ,						eta=lowerCamelCase_      ,						generator=lowerCamelCase_      ,						latents=lowerCamelCase_      ,						output_type=lowerCamelCase_      ,						return_dict=lowerCamelCase_      ,						callback=lowerCamelCase_      ,						callback_steps=lowerCamelCase_      ,						**lowerCamelCase_      ,						)


					@torch.no_grad()
					def lowerCamelCase_			(						self				:			Optional[int]      ,						lowerCamelCase_				:			Union[str, List[str]]      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 50      ,						lowerCamelCase_				:			float = 7.5      ,						lowerCamelCase_				:			Optional[Union[str, List[str]]] = None      ,						lowerCamelCase_				:			Optional[int] = 1      ,						lowerCamelCase_				:			float = 0.0      ,						lowerCamelCase_				:			Optional[torch.Generator] = None      ,						lowerCamelCase_				:			Optional[torch.FloatTensor] = None      ,						lowerCamelCase_				:			Optional[str] = "pil"      ,						lowerCamelCase_				:			bool = True      ,						lowerCamelCase_				:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,						lowerCamelCase_				:			int = 1      ,						**lowerCamelCase_				:			Union[str, Any]      ,						):

							'''simple docstring'''



							return self.pipea(
							    prompt=lowerCamelCase_      ,						height=lowerCamelCase_      ,						width=lowerCamelCase_      ,						num_inference_steps=lowerCamelCase_      ,						guidance_scale=lowerCamelCase_      ,						negative_prompt=lowerCamelCase_      ,						num_images_per_prompt=lowerCamelCase_      ,						eta=lowerCamelCase_      ,						generator=lowerCamelCase_      ,						latents=lowerCamelCase_      ,						output_type=lowerCamelCase_      ,						return_dict=lowerCamelCase_      ,						callback=lowerCamelCase_      ,						callback_steps=lowerCamelCase_      ,						**lowerCamelCase_      ,						)


					@torch.no_grad()
					def lowerCamelCase_			(						self				:			Optional[Any]      ,						lowerCamelCase_				:			Union[str, List[str]]      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 50      ,						lowerCamelCase_				:			float = 7.5      ,						lowerCamelCase_				:			Optional[Union[str, List[str]]] = None      ,						lowerCamelCase_				:			Optional[int] = 1      ,						lowerCamelCase_				:			float = 0.0      ,						lowerCamelCase_				:			Optional[torch.Generator] = None      ,						lowerCamelCase_				:			Optional[torch.FloatTensor] = None      ,						lowerCamelCase_				:			Optional[str] = "pil"      ,						lowerCamelCase_				:			bool = True      ,						lowerCamelCase_				:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,						lowerCamelCase_				:			int = 1      ,						**lowerCamelCase_				:			str      ,						):

							'''simple docstring'''



							return self.pipea(
							    prompt=lowerCamelCase_      ,						height=lowerCamelCase_      ,						width=lowerCamelCase_      ,						num_inference_steps=lowerCamelCase_      ,						guidance_scale=lowerCamelCase_      ,						negative_prompt=lowerCamelCase_      ,						num_images_per_prompt=lowerCamelCase_      ,						eta=lowerCamelCase_      ,						generator=lowerCamelCase_      ,						latents=lowerCamelCase_      ,						output_type=lowerCamelCase_      ,						return_dict=lowerCamelCase_      ,						callback=lowerCamelCase_      ,						callback_steps=lowerCamelCase_      ,						**lowerCamelCase_      ,						)


					@torch.no_grad()
					def lowerCamelCase_			(						self				:			Tuple      ,						lowerCamelCase_				:			Union[str, List[str]]      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 50      ,						lowerCamelCase_				:			float = 7.5      ,						lowerCamelCase_				:			Optional[Union[str, List[str]]] = None      ,						lowerCamelCase_				:			Optional[int] = 1      ,						lowerCamelCase_				:			float = 0.0      ,						lowerCamelCase_				:			Optional[torch.Generator] = None      ,						lowerCamelCase_				:			Optional[torch.FloatTensor] = None      ,						lowerCamelCase_				:			Optional[str] = "pil"      ,						lowerCamelCase_				:			bool = True      ,						lowerCamelCase_				:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,						lowerCamelCase_				:			int = 1      ,						**lowerCamelCase_				:			Dict      ,						):

							'''simple docstring'''



							return self.pipea(
							    prompt=lowerCamelCase_      ,						height=lowerCamelCase_      ,						width=lowerCamelCase_      ,						num_inference_steps=lowerCamelCase_      ,						guidance_scale=lowerCamelCase_      ,						negative_prompt=lowerCamelCase_      ,						num_images_per_prompt=lowerCamelCase_      ,						eta=lowerCamelCase_      ,						generator=lowerCamelCase_      ,						latents=lowerCamelCase_      ,						output_type=lowerCamelCase_      ,						return_dict=lowerCamelCase_      ,						callback=lowerCamelCase_      ,						callback_steps=lowerCamelCase_      ,						**lowerCamelCase_      ,						)



					@torch.no_grad()
					def lowerCamelCase_			(						self				:			Dict      ,						lowerCamelCase_				:			Union[str, List[str]]      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 50      ,						lowerCamelCase_				:			float = 7.5      ,						lowerCamelCase_				:			Optional[Union[str, List[str]]] = None      ,						lowerCamelCase_				:			Optional[int] = 1      ,						lowerCamelCase_				:			float = 0.0      ,						lowerCamelCase_				:			Optional[torch.Generator] = None      ,						lowerCamelCase_				:			Optional[torch.FloatTensor] = None      ,						lowerCamelCase_				:			Optional[str] = "pil"      ,						lowerCamelCase_				:			bool = True      ,						lowerCamelCase_				:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,						lowerCamelCase_				:			int = 1      ,						**lowerCamelCase_				:			Any      ,						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				int		=			"""cuda""" if torch.cuda.is_available() else """cpu"""
							self.to(lowerCamelCase_						)

							# Checks if the height and width are divisible by 8 or not
							if height % 8 != 0 or width % 8 != 0:
									raise ValueError(f'''`height` and `width` must be divisible by 8 but are {height} and {width}.'''						)

							# Get first result from Stable Diffusion Checkpoint v1.1
							SCREAMING_SNAKE_CASE :				List[str]		=			self.textaimg_sda_a(
							    prompt=lowerCamelCase_      ,						height=lowerCamelCase_      ,						width=lowerCamelCase_      ,						num_inference_steps=lowerCamelCase_      ,						guidance_scale=lowerCamelCase_      ,						negative_prompt=lowerCamelCase_      ,						num_images_per_prompt=lowerCamelCase_      ,						eta=lowerCamelCase_      ,						generator=lowerCamelCase_      ,						latents=lowerCamelCase_      ,						output_type=lowerCamelCase_      ,						return_dict=lowerCamelCase_      ,						callback=lowerCamelCase_      ,						callback_steps=lowerCamelCase_      ,						**lowerCamelCase_      ,						)

							# Get first result from Stable Diffusion Checkpoint v1.2
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			self.textaimg_sda_a(
							    prompt=lowerCamelCase_      ,						height=lowerCamelCase_      ,						width=lowerCamelCase_      ,						num_inference_steps=lowerCamelCase_      ,						guidance_scale=lowerCamelCase_      ,						negative_prompt=lowerCamelCase_      ,						num_images_per_prompt=lowerCamelCase_      ,						eta=lowerCamelCase_      ,						generator=lowerCamelCase_      ,						latents=lowerCamelCase_      ,						output_type=lowerCamelCase_      ,						return_dict=lowerCamelCase_      ,						callback=lowerCamelCase_      ,						callback_steps=lowerCamelCase_      ,						**lowerCamelCase_      ,						)

							# Get first result from Stable Diffusion Checkpoint v1.3
							SCREAMING_SNAKE_CASE :				int		=			self.textaimg_sda_a(
							    prompt=lowerCamelCase_      ,						height=lowerCamelCase_      ,						width=lowerCamelCase_      ,						num_inference_steps=lowerCamelCase_      ,						guidance_scale=lowerCamelCase_      ,						negative_prompt=lowerCamelCase_      ,						num_images_per_prompt=lowerCamelCase_      ,						eta=lowerCamelCase_      ,						generator=lowerCamelCase_      ,						latents=lowerCamelCase_      ,						output_type=lowerCamelCase_      ,						return_dict=lowerCamelCase_      ,						callback=lowerCamelCase_      ,						callback_steps=lowerCamelCase_      ,						**lowerCamelCase_      ,						)

							# Get first result from Stable Diffusion Checkpoint v1.4
							SCREAMING_SNAKE_CASE :				Optional[int]		=			self.textaimg_sda_a(
							    prompt=lowerCamelCase_      ,						height=lowerCamelCase_      ,						width=lowerCamelCase_      ,						num_inference_steps=lowerCamelCase_      ,						guidance_scale=lowerCamelCase_      ,						negative_prompt=lowerCamelCase_      ,						num_images_per_prompt=lowerCamelCase_      ,						eta=lowerCamelCase_      ,						generator=lowerCamelCase_      ,						latents=lowerCamelCase_      ,						output_type=lowerCamelCase_      ,						return_dict=lowerCamelCase_      ,						callback=lowerCamelCase_      ,						callback_steps=lowerCamelCase_      ,						**lowerCamelCase_      ,						)

							# Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
							return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]]						)



