





import collections
import inspect
import unittest
from typing import Dict, List, Tuple

from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import MaskFormerSwinBackbone
 from transformers.models.maskformer import MaskFormerSwinModel
class        SCREAMING_SNAKE_CASE     :


   def __init__(					self    :       List[Any]    ,  a    :       Dict    ,  a    :       Any=13    ,  a    :       Dict=32    ,  a    :       List[Any]=2    ,  a    :       Optional[int]=3    ,  a    :       Optional[int]=16    ,  a    :       Dict=[1, 2, 1]    ,  a    :       List[Any]=[2, 2, 4]    ,  a    :       str=2    ,  a    :       Dict=2.0    ,  a    :       Dict=True    ,  a    :       Tuple=0.0    ,  a    :       int=0.0    ,  a    :       List[Any]=0.1    ,  a    :       Any="gelu"    ,  a    :       int=False    ,  a    :       List[Any]=True    ,  a    :       List[str]=0.02    ,  a    :       Union[str, Any]=1E-5    ,  a    :       Union[str, Any]=True    ,  a    :       List[Any]=None    ,  a    :       Tuple=True    ,  a    :       Optional[int]=10    ,  a    :       Any=8    ,  a    :       Optional[int]=["stage1", "stage2", "stage3"]    ,  a    :       str=[1, 2, 3]    ,  )->     Dict:





     """simple docstring"""







     lowercase__			    =						parent
     lowercase__			    =						batch_size
     lowercase__			    =						image_size
     lowercase__			    =						patch_size
     lowercase__			    =						num_channels
     lowercase__			    =						embed_dim
     lowercase__			    =						depths
     lowercase__			    =						num_heads
     lowercase__			    =						window_size
     lowercase__			    =						mlp_ratio
     lowercase__			    =						qkv_bias
     lowercase__			    =						hidden_dropout_prob
     lowercase__			    =						attention_probs_dropout_prob
     lowercase__			    =						drop_path_rate
     lowercase__			    =						hidden_act
     lowercase__			    =						use_absolute_embeddings
     lowercase__			    =						patch_norm
     lowercase__			    =						layer_norm_eps
     lowercase__			    =						initializer_range
     lowercase__			    =						is_training
     lowercase__			    =						scope
     lowercase__			    =						use_labels
     lowercase__			    =						type_sequence_label_size
     lowercase__			    =						encoder_stride
     lowercase__			    =						out_features
     lowercase__			    =						out_indices


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





     """simple docstring"""







     lowercase__			    =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

     lowercase__			    =						None
     if self.use_labels:
       lowercase__			    =						ids_tensor([self.batch_size]    ,  self.type_sequence_label_size )

     lowercase__			    =						self.get_config()

     return config, pixel_values, labels


   def  SCREAMING_SNAKE_CASE_							(					self    :       Any )->     Dict:





     """simple docstring"""







     return MaskFormerSwinConfig(
         image_size=self.image_size    ,  patch_size=self.patch_size    ,  num_channels=self.num_channels    ,  embed_dim=self.embed_dim    ,  depths=self.depths    ,  num_heads=self.num_heads    ,  window_size=self.window_size    ,  mlp_ratio=self.mlp_ratio    ,  qkv_bias=self.qkv_bias    ,  hidden_dropout_prob=self.hidden_dropout_prob    ,  attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,  drop_path_rate=self.drop_path_rate    ,  hidden_act=self.hidden_act    ,  use_absolute_embeddings=self.use_absolute_embeddings    ,  path_norm=self.patch_norm    ,  layer_norm_eps=self.layer_norm_eps    ,  initializer_range=self.initializer_range    ,  encoder_stride=self.encoder_stride    ,  out_features=self.out_features    ,  out_indices=self.out_indices    ,  )


   def  SCREAMING_SNAKE_CASE_							(					self    :       str    ,  a    :       Optional[Any]    ,  a    :       List[Any]    ,  a    :       List[Any] )->     Dict:





     """simple docstring"""







     lowercase__			    =						MaskFormerSwinModel(config=UpperCAmelCase_ )
     model.to(UpperCAmelCase_ )
     model.eval()
     lowercase__			    =						model(UpperCAmelCase_ )

     lowercase__			    =						((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1))
     lowercase__			    =						int(config.embed_dim * 2 ** (len(config.depths ) - 1) )

     self.parent.assertEqual(result.last_hidden_state.shape    ,  (self.batch_size, expected_seq_len, expected_dim) )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[int]    ,  a    :       str    ,  a    :       str    ,  a    :       Tuple )->     Tuple:





     """simple docstring"""







     lowercase__			    =						MaskFormerSwinBackbone(config=UpperCAmelCase_ )
     model.to(UpperCAmelCase_ )
     model.eval()
     lowercase__			    =						model(UpperCAmelCase_ )

     # verify feature maps
     self.parent.assertEqual(len(result.feature_maps )    ,  len(config.out_features ) )
     self.parent.assertListEqual(list(result.feature_maps[0].shape )    ,  [13, 16, 16, 16] )

     # verify channels
     self.parent.assertEqual(len(model.channels )    ,  len(config.out_features ) )
     self.parent.assertListEqual(model.channels    ,  [16, 32, 64] )

     # verify ValueError
     with self.parent.assertRaises(UpperCAmelCase_ ):
       lowercase__			    =						['stem']
       lowercase__			    =						MaskFormerSwinBackbone(config=UpperCAmelCase_ )


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





     """simple docstring"""







     lowercase__			    =						self.prepare_config_and_inputs()
     lowercase__    ,					lowercase__    ,					lowercase__			    =						config_and_inputs
     lowercase__			    =						{'pixel_values': pixel_values}
     return config, inputs_dict






@require_torch
class        SCREAMING_SNAKE_CASE     (snake_case__    ,			snake_case__    ,			unittest.TestCase   ):
   _UpperCamelCase					:	Optional[Any]				      = (
       (
           MaskFormerSwinModel,
           MaskFormerSwinBackbone,
       )
       if is_torch_available()
       else ()
   )
   _UpperCamelCase					:	Tuple				      = {"""feature-extraction""": MaskFormerSwinModel} if is_torch_available() else {}
   _UpperCamelCase					:	Tuple				      = False
   _UpperCamelCase					:	Optional[int]				      = False
   _UpperCamelCase					:	Dict				      = False
   _UpperCamelCase					:	int				      = False
   _UpperCamelCase					:	List[str]				      = False


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





     """simple docstring"""







     lowercase__			    =						MaskFormerSwinModelTester(self )
     lowercase__			    =						ConfigTester(self    ,  config_class=UpperCAmelCase_    ,  embed_dim=37 )


   @require_torch_multi_gpu
   @unittest.skip(
       reason=(
           '`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with'
           ' `nn.DataParallel`'
       ) )
   def  SCREAMING_SNAKE_CASE_							(					self    :       int )->     Any:





     """simple docstring"""







     pass


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





     """simple docstring"""







     self.create_and_test_config_common_properties()
     self.config_tester.create_and_test_config_to_json_string()
     self.config_tester.create_and_test_config_to_json_file()
     self.config_tester.create_and_test_config_from_and_save_pretrained()
     self.config_tester.create_and_test_config_with_num_labels()
     self.config_tester.check_config_can_be_init_without_params()
     self.config_tester.check_config_arguments_init()


   def  SCREAMING_SNAKE_CASE_							(					self    :       Any )->     Tuple:





     """simple docstring"""







     return


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





     """simple docstring"""







     lowercase__			    =						self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*UpperCAmelCase_ )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Dict )->     int:





     """simple docstring"""







     lowercase__			    =						self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_backbone(*UpperCAmelCase_ )


   @unittest.skip('Swin does not use inputs_embeds' )
   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[Any] )->     int:





     """simple docstring"""







     pass


   @unittest.skip('Swin does not support feedforward chunking' )
   def  SCREAMING_SNAKE_CASE_							(					self    :       Any )->     int:





     """simple docstring"""







     pass


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[Any] )->     int:





     """simple docstring"""







     lowercase__    ,					lowercase__			    =						self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
       lowercase__			    =						model_class(UpperCAmelCase_ )
       self.assertIsInstance(model.get_input_embeddings()    ,  (nn.Module) )
       lowercase__			    =						model.get_output_embeddings()
       self.assertTrue(x is None or isinstance(UpperCAmelCase_    ,  nn.Linear ) )


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





     """simple docstring"""







     lowercase__    ,					lowercase__			    =						self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
       lowercase__			    =						model_class(UpperCAmelCase_ )
       lowercase__			    =						inspect.signature(model.forward )
       # signature.parameters is an OrderedDict => so arg_names order is deterministic
       lowercase__			    =						[*signature.parameters.keys()]

       lowercase__			    =						['pixel_values']
       self.assertListEqual(arg_names[:1]    ,  UpperCAmelCase_ )


   @unittest.skip(reason='MaskFormerSwin is only used as backbone and doesn\'t support output_attentions' )
   def  SCREAMING_SNAKE_CASE_							(					self    :       List[str] )->     Optional[Any]:





     """simple docstring"""







     pass


   @unittest.skip(reason='MaskFormerSwin is only used as an internal backbone' )
   def  SCREAMING_SNAKE_CASE_							(					self    :       int )->     Tuple:





     """simple docstring"""







     pass


   def  SCREAMING_SNAKE_CASE_							(					self    :       Dict    ,  a    :       Tuple    ,  a    :       Optional[int]    ,  a    :       Optional[Any]    ,  a    :       Optional[Any] )->     Optional[int]:





     """simple docstring"""







     lowercase__			    =						model_class(UpperCAmelCase_ )
     model.to(UpperCAmelCase_ )
     model.eval()

     with torch.no_grad():
       lowercase__			    =						model(**self._prepare_for_class(UpperCAmelCase_    ,  UpperCAmelCase_ ) )

     lowercase__			    =						outputs.hidden_states

     lowercase__			    =						getattr(
         self.model_tester    ,  'expected_num_hidden_layers'    ,  len(self.model_tester.depths ) + 1 )
     self.assertEqual(len(UpperCAmelCase_ )    ,  UpperCAmelCase_ )

     # Swin has a different seq_length
     lowercase__			    =						(
         config.patch_size
         if isinstance(config.patch_size    ,  collections.abc.Iterable )
         else (config.patch_size, config.patch_size)
     )

     lowercase__			    =						(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

     self.assertListEqual(
         list(hidden_states[0].shape[-2:] )    ,  [num_patches, self.model_tester.embed_dim]    ,  )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[Any] )->     Dict:





     """simple docstring"""







     lowercase__    ,					lowercase__			    =						self.model_tester.prepare_config_and_inputs_for_common()

     lowercase__			    =						(
         self.model_tester.image_size
         if isinstance(self.model_tester.image_size    ,  collections.abc.Iterable )
         else (self.model_tester.image_size, self.model_tester.image_size)
     )

     for model_class in self.all_model_classes:
       lowercase__			    =						True
       self.check_hidden_states_output(UpperCAmelCase_    ,  UpperCAmelCase_    ,  UpperCAmelCase_    ,  UpperCAmelCase_ )

       # check that output_hidden_states also work using config
       del inputs_dict["output_hidden_states"]
       lowercase__			    =						True

       self.check_hidden_states_output(UpperCAmelCase_    ,  UpperCAmelCase_    ,  UpperCAmelCase_    ,  UpperCAmelCase_ )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[int] )->     List[str]:





     """simple docstring"""







     lowercase__    ,					lowercase__			    =						self.model_tester.prepare_config_and_inputs_for_common()
     lowercase__			    =						3

     lowercase__			    =						(
         self.model_tester.image_size
         if isinstance(self.model_tester.image_size    ,  collections.abc.Iterable )
         else (self.model_tester.image_size, self.model_tester.image_size)
     )
     lowercase__			    =						(
         config.patch_size
         if isinstance(config.patch_size    ,  collections.abc.Iterable )
         else (config.patch_size, config.patch_size)
     )

     lowercase__			    =						image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
     lowercase__			    =						image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

     for model_class in self.all_model_classes:
       lowercase__			    =						True
       self.check_hidden_states_output(UpperCAmelCase_    ,  UpperCAmelCase_    ,  UpperCAmelCase_    ,  (padded_height, padded_width) )

       # check that output_hidden_states also work using config
       del inputs_dict["output_hidden_states"]
       lowercase__			    =						True
       self.check_hidden_states_output(UpperCAmelCase_    ,  UpperCAmelCase_    ,  UpperCAmelCase_    ,  (padded_height, padded_width) )


   @unittest.skip(reason='MaskFormerSwin doesn\'t have pretrained checkpoints' )
   def  SCREAMING_SNAKE_CASE_							(					self    :       str )->     Optional[int]:





     """simple docstring"""







     pass


   @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' )
   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[int] )->     List[str]:





     """simple docstring"""







     pass


   @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' )
   def  SCREAMING_SNAKE_CASE_							(					self    :       int )->     Optional[int]:





     """simple docstring"""







     pass


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





     """simple docstring"""







     lowercase__    ,					lowercase__			    =						self.model_tester.prepare_config_and_inputs_for_common()

     def set_nan_tensor_to_zero(a    :       List[Any] ):
       lowercase__			    =						0
       return t

     def check_equivalence(a    :       str    ,  a    :       List[Any]    ,  a    :       int    ,  a    :       Optional[int]={} ):
       with torch.no_grad():
         lowercase__			    =						model(**UpperCAmelCase_    ,  return_dict=UpperCAmelCase_    ,  **UpperCAmelCase_ )
         lowercase__			    =						model(**UpperCAmelCase_    ,  return_dict=UpperCAmelCase_    ,  **UpperCAmelCase_ ).to_tuple()

         def recursive_check(a    :       Any    ,  a    :       Optional[int] ):
           if isinstance(UpperCAmelCase_    ,  (List, Tuple) ):
             for tuple_iterable_value, dict_iterable_value in zip(UpperCAmelCase_    ,  UpperCAmelCase_ ):
               recursive_check(UpperCAmelCase_    ,  UpperCAmelCase_ )
           elif isinstance(UpperCAmelCase_    ,  UpperCAmelCase_ ):
             for tuple_iterable_value, dict_iterable_value in zip(
                 tuple_object.values()    ,  dict_object.values() ):
               recursive_check(UpperCAmelCase_    ,  UpperCAmelCase_ )
           elif tuple_object is None:
             return
           else:
             self.assertTrue(
                 torch.allclose(
                     set_nan_tensor_to_zero(UpperCAmelCase_ )    ,  set_nan_tensor_to_zero(UpperCAmelCase_ )    ,  atol=1E-5 )    ,  msg=(
                     'Tuple and dict output are not equal. Difference:'
                     f""" {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:"""
                     f""" {torch.isnan(UpperCAmelCase_ ).any()} and `inf`: {torch.isinf(UpperCAmelCase_ )}. Dict has"""
                     f""" `nan`: {torch.isnan(UpperCAmelCase_ ).any()} and `inf`: {torch.isinf(UpperCAmelCase_ )}."""
                 )    ,  )

         recursive_check(UpperCAmelCase_    ,  UpperCAmelCase_ )

     for model_class in self.all_model_classes:
       lowercase__			    =						model_class(UpperCAmelCase_ )
       model.to(UpperCAmelCase_ )
       model.eval()

       lowercase__			    =						self._prepare_for_class(UpperCAmelCase_    ,  UpperCAmelCase_ )
       lowercase__			    =						self._prepare_for_class(UpperCAmelCase_    ,  UpperCAmelCase_ )
       check_equivalence(UpperCAmelCase_    ,  UpperCAmelCase_    ,  UpperCAmelCase_ )

       lowercase__			    =						self._prepare_for_class(UpperCAmelCase_    ,  UpperCAmelCase_    ,  return_labels=UpperCAmelCase_ )
       lowercase__			    =						self._prepare_for_class(UpperCAmelCase_    ,  UpperCAmelCase_    ,  return_labels=UpperCAmelCase_ )
       check_equivalence(UpperCAmelCase_    ,  UpperCAmelCase_    ,  UpperCAmelCase_ )

       lowercase__			    =						self._prepare_for_class(UpperCAmelCase_    ,  UpperCAmelCase_ )
       lowercase__			    =						self._prepare_for_class(UpperCAmelCase_    ,  UpperCAmelCase_ )
       check_equivalence(UpperCAmelCase_    ,  UpperCAmelCase_    ,  UpperCAmelCase_    ,  {'output_hidden_states': True} )

       lowercase__			    =						self._prepare_for_class(UpperCAmelCase_    ,  UpperCAmelCase_    ,  return_labels=UpperCAmelCase_ )
       lowercase__			    =						self._prepare_for_class(UpperCAmelCase_    ,  UpperCAmelCase_    ,  return_labels=UpperCAmelCase_ )
       check_equivalence(UpperCAmelCase_    ,  UpperCAmelCase_    ,  UpperCAmelCase_    ,  {'output_hidden_states': True} )






@require_torch
class        SCREAMING_SNAKE_CASE     (unittest.TestCase    ,			snake_case__   ):
   _UpperCamelCase					:	Union[str, Any]				      = (MaskFormerSwinBackbone,) if is_torch_available() else ()
   _UpperCamelCase					:	Tuple				      = MaskFormerSwinConfig


   def  SCREAMING_SNAKE_CASE_							(					self    :       str )->     Any:





     """simple docstring"""







     lowercase__			    =						MaskFormerSwinModelTester(self )


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





     """simple docstring"""







     lowercase__    ,					lowercase__			    =						self.model_tester.prepare_config_and_inputs_for_common()
     lowercase__			    =						inputs_dict['pixel_values'].shape[0]

     for backbone_class in self.all_model_classes:
       lowercase__			    =						backbone_class(UpperCAmelCase_ )
       backbone.to(UpperCAmelCase_ )
       backbone.eval()

       lowercase__			    =						backbone(**UpperCAmelCase_ )

       # Test default outputs and verify feature maps
       self.assertIsInstance(outputs.feature_maps    ,  UpperCAmelCase_ )
       self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) )
       for feature_map, n_channels in zip(outputs.feature_maps    ,  backbone.channels ):
         self.assertTrue(feature_map.shape[:2]    ,  (batch_size, n_channels) )
       self.assertIsNone(outputs.hidden_states )
       self.assertIsNone(outputs.attentions )

       # Test output_hidden_states=True
       lowercase__			    =						backbone(**UpperCAmelCase_    ,  output_hidden_states=UpperCAmelCase_ )
       self.assertIsNotNone(outputs.hidden_states )
       self.assertTrue(len(outputs.hidden_states )    ,  len(backbone.stage_names ) )
       # We skip the stem layer
       for hidden_states, n_channels in zip(outputs.hidden_states[1:]    ,  backbone.channels ):
         for hidden_state in hidden_states:
           # Hidden states are in the format (batch_size, (height * width), n_channels)
           lowercase__    ,					lowercase__    ,					lowercase__			    =						hidden_state.shape
           self.assertTrue((h_batch_size, h_n_channels)    ,  (batch_size, n_channels) )

            # Test output_attentions=True
       if self.has_attentions:
         lowercase__			    =						backbone(**UpperCAmelCase_    ,  output_attentions=UpperCAmelCase_ )
         self.assertIsNotNone(outputs.attentions )









import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionSAGPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

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


enable_full_determinism()
class        SCREAMING_SNAKE_CASE     (UpperCAmelCase    ,			UpperCAmelCase    ,			unittest.TestCase   ):
   _UpperCamelCase					:	List[Any]				      = StableDiffusionSAGPipeline
   _UpperCamelCase					:	str				      = TEXT_TO_IMAGE_PARAMS
   _UpperCamelCase					:	Dict				      = TEXT_TO_IMAGE_BATCH_PARAMS
   _UpperCamelCase					:	str				      = TEXT_TO_IMAGE_IMAGE_PARAMS
   _UpperCamelCase					:	Optional[int]				      = TEXT_TO_IMAGE_IMAGE_PARAMS
   _UpperCamelCase					:	Union[str, Any]				      = False


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[str] )->     Dict:





     """simple docstring"""







     torch.manual_seed(0 )
     lowercase__			    =						UNetaDConditionModel(
         block_out_channels=(32, 64)    ,  layers_per_block=2    ,  sample_size=32    ,  in_channels=4    ,  out_channels=4    ,  down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')    ,  up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')    ,  cross_attention_dim=32    ,  )
     lowercase__			    =						DDIMScheduler(
         beta_start=0.00085    ,  beta_end=0.012    ,  beta_schedule='scaled_linear'    ,  clip_sample=a    ,  set_alpha_to_one=a    ,  )
     torch.manual_seed(0 )
     lowercase__			    =						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    ,  )
     torch.manual_seed(0 )
     lowercase__			    =						CLIPTextConfig(
         bos_token_id=0    ,  eos_token_id=2    ,  hidden_size=32    ,  intermediate_size=37    ,  layer_norm_eps=1E-0_5    ,  num_attention_heads=4    ,  num_hidden_layers=5    ,  pad_token_id=1    ,  vocab_size=1_000    ,  )
     lowercase__			    =						CLIPTextModel(a )
     lowercase__			    =						CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )

     lowercase__			    =						{
         'unet': unet,
         'scheduler': scheduler,
         'vae': vae,
         'text_encoder': text_encoder,
         'tokenizer': tokenizer,
         'safety_checker': None,
         'feature_extractor': None,
     }
     return components


   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple    ,  a    :       Optional[int]    ,  a    :       Any=0 )->     Union[str, Any]:





     """simple docstring"""







     if str(a ).startswith('mps' ):
       lowercase__			    =						torch.manual_seed(a )
     else:
       lowercase__			    =						torch.Generator(device=a ).manual_seed(a )
     lowercase__			    =						{
         'prompt': '.',
         'generator': generator,
         'num_inference_steps': 2,
         'guidance_scale': 1.0,
         'sag_scale': 1.0,
         'output_type': 'numpy',
     }
     return inputs


   def  SCREAMING_SNAKE_CASE_							(					self    :       Any )->     Any:





     """simple docstring"""







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






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


   def  SCREAMING_SNAKE_CASE_							(					self    :       str )->     int:





     """simple docstring"""







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


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





     """simple docstring"""







     lowercase__			    =						StableDiffusionSAGPipeline.from_pretrained('CompVis/stable-diffusion-v1-4' )
     lowercase__			    =						sag_pipe.to(a )
     sag_pipe.set_progress_bar_config(disable=a )

     lowercase__			    =						'.'
     lowercase__			    =						torch.manual_seed(0 )
     lowercase__			    =						sag_pipe(
         [prompt]    ,  generator=a    ,  guidance_scale=7.5    ,  sag_scale=1.0    ,  num_inference_steps=20    ,  output_type='np' )

     lowercase__			    =						output.images

     lowercase__			    =						image[0, -3:, -3:, -1]

     assert image.shape == (1, 512, 512, 3)
     lowercase__			    =						np.array([0.1568, 0.1738, 0.1695, 0.1693, 0.1507, 0.1705, 0.1547, 0.1751, 0.1949] )

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


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





     """simple docstring"""







     lowercase__			    =						StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base' )
     lowercase__			    =						sag_pipe.to(a )
     sag_pipe.set_progress_bar_config(disable=a )

     lowercase__			    =						'.'
     lowercase__			    =						torch.manual_seed(0 )
     lowercase__			    =						sag_pipe(
         [prompt]    ,  generator=a    ,  guidance_scale=7.5    ,  sag_scale=1.0    ,  num_inference_steps=20    ,  output_type='np' )

     lowercase__			    =						output.images

     lowercase__			    =						image[0, -3:, -3:, -1]

     assert image.shape == (1, 512, 512, 3)
     lowercase__			    =						np.array([0.3459, 0.2876, 0.2537, 0.3002, 0.2671, 0.2160, 0.3026, 0.2262, 0.2371] )

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


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





     """simple docstring"""







     lowercase__			    =						StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base' )
     lowercase__			    =						sag_pipe.to(a )
     sag_pipe.set_progress_bar_config(disable=a )

     lowercase__			    =						'.'
     lowercase__			    =						torch.manual_seed(0 )
     lowercase__			    =						sag_pipe(
         [prompt]    ,  width=768    ,  height=512    ,  generator=a    ,  guidance_scale=7.5    ,  sag_scale=1.0    ,  num_inference_steps=20    ,  output_type='np'    ,  )

     lowercase__			    =						output.images

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


