




'''simple docstring'''







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






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






    """simple docstring"""


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






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






    """simple docstring"""


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

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

    A__       =     self.get_config()

    return config, pixel_values, labels






 def 						_UpperCamelCase (self       :  str    )       ->   Tuple:






    """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 						_UpperCamelCase (self       :  int    ,		a       :  Dict    ,		a       :  Any    ,		a       :  List[Any]    )       ->   List[str]:






    """simple docstring"""


    A__       =     MaskFormerSwinModel(config=a    )
    model.to(a    )
    model.eval()
    A__       =     model(a    )

    A__       =     ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths    ) - 1))
    A__       =     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 						_UpperCamelCase (self       :  Optional[int]    ,		a       :  Optional[int]    ,		a       :  List[Any]    ,		a       :  Any    )       ->   str:






    """simple docstring"""


    A__       =     MaskFormerSwinBackbone(config=a    )
    model.to(a    )
    model.eval()
    A__       =     model(a    )

    # 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(a    ):
       A__       =     ['stem']
       A__       =     MaskFormerSwinBackbone(config=a    )






 def 						_UpperCamelCase (self       :  List[Any]    )       ->   Tuple:






    """simple docstring"""


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




@require_torch
class 	_snake_case(			UpperCAmelCase       , UpperCAmelCase       , unittest.TestCase      ):
 __snake_case:							Any						=					(
     (
         MaskFormerSwinModel,
         MaskFormerSwinBackbone,
     )
     if is_torch_available()
     else ()
 )
 __snake_case:							Optional[Any]						=					{'''feature-extraction''': MaskFormerSwinModel} if is_torch_available() else {}
 __snake_case:							Optional[Any]						=					False
 __snake_case:							Union[str, Any]						=					False
 __snake_case:							int						=					False
 __snake_case:							int						=					False
 __snake_case:							Optional[Any]						=					False






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






    """simple docstring"""


    A__       =     MaskFormerSwinModelTester(self    )
    A__       =     ConfigTester(self    ,		config_class=a    ,		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 						_UpperCamelCase (self       :  Dict    )       ->   List[str]:






    """simple docstring"""


    pass






 def 						_UpperCamelCase (self       :  Tuple    )       ->   Tuple:






    """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 						_UpperCamelCase (self       :  int    )       ->   Tuple:






    """simple docstring"""


    return






 def 						_UpperCamelCase (self       :  Optional[int]    )       ->   Dict:






    """simple docstring"""


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






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






    """simple docstring"""


    A__       =     self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_backbone(*a    )






 @unittest.skip('Swin does not use inputs_embeds'    )
 def 						_UpperCamelCase (self       :  str    )       ->   Any:






    """simple docstring"""


    pass






 @unittest.skip('Swin does not support feedforward chunking'    )
 def 						_UpperCamelCase (self       :  Dict    )       ->   str:






    """simple docstring"""


    pass






 def 						_UpperCamelCase (self       :  Tuple    )       ->   str:






    """simple docstring"""


    A__  ,			A__       =     self.model_tester.prepare_config_and_inputs_for_common()

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






 def 						_UpperCamelCase (self       :  Dict    )       ->   Any:






    """simple docstring"""


    A__  ,			A__       =     self.model_tester.prepare_config_and_inputs_for_common()

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

       A__       =     ['pixel_values']
       self.assertListEqual(arg_names[:1]    ,		a    )






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






    """simple docstring"""


    pass






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






    """simple docstring"""


    pass






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






    """simple docstring"""


    A__       =     model_class(a    )
    model.to(a    )
    model.eval()

    with torch.no_grad():
       A__       =     model(**self._prepare_for_class(a    ,		a    )    )

    A__       =     outputs.hidden_states

    A__       =     getattr(
        self.model_tester    ,		'expected_num_hidden_layers'    ,		len(self.model_tester.depths    ) + 1    )
    self.assertEqual(len(a    )    ,		a    )

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

    A__       =     (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 						_UpperCamelCase (self       :  Tuple    )       ->   Optional[int]:






    """simple docstring"""


    A__  ,			A__       =     self.model_tester.prepare_config_and_inputs_for_common()

    A__       =     (
        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:
       A__       =     True
       self.check_hidden_states_output(a    ,		a    ,		a    ,		a    )

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

       self.check_hidden_states_output(a    ,		a    ,		a    ,		a    )






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






    """simple docstring"""


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

    A__       =     (
        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)
    )
    A__       =     (
        config.patch_size
        if isinstance(config.patch_size    ,		collections.abc.Iterable    )
        else (config.patch_size, config.patch_size)
    )

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

    for model_class in self.all_model_classes:
       A__       =     True
       self.check_hidden_states_output(a    ,		a    ,		a    ,		(padded_height, padded_width)    )

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






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






    """simple docstring"""


    pass






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






    """simple docstring"""


    pass






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






    """simple docstring"""


    pass






 def 						_UpperCamelCase (self       :  Tuple    )       ->   str:






    """simple docstring"""


    A__  ,			A__       =     self.model_tester.prepare_config_and_inputs_for_common()

    def set_nan_tensor_to_zero(a       :  List[str]    ):
       A__       =     0
       return t

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

          def recursive_check(a       :  Tuple    ,		a       :  Any    ):
             if isinstance(a    ,		(List, Tuple)    ):
                for tuple_iterable_value, dict_iterable_value in zip(a    ,		a    ):
                   recursive_check(a    ,		a    )
             elif isinstance(a    ,		a    ):
                for tuple_iterable_value, dict_iterable_value in zip(
                    tuple_object.values()    ,		dict_object.values()    ):
                   recursive_check(a    ,		a    )
             elif tuple_object is None:
                return
             else:
                self.assertTrue(
                    torch.allclose(
                        set_nan_tensor_to_zero(a    )    ,		set_nan_tensor_to_zero(a    )    ,		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(a    ).any()} and `inf`: {torch.isinf(a    )}. Dict has"""
                        f""" `nan`: {torch.isnan(a    ).any()} and `inf`: {torch.isinf(a    )}."""
                    )    ,		)

          recursive_check(a    ,		a    )

    for model_class in self.all_model_classes:
       A__       =     model_class(a    )
       model.to(a    )
       model.eval()

       A__       =     self._prepare_for_class(a    ,		a    )
       A__       =     self._prepare_for_class(a    ,		a    )
       check_equivalence(a    ,		a    ,		a    )

       A__       =     self._prepare_for_class(a    ,		a    ,		return_labels=a    )
       A__       =     self._prepare_for_class(a    ,		a    ,		return_labels=a    )
       check_equivalence(a    ,		a    ,		a    )

       A__       =     self._prepare_for_class(a    ,		a    )
       A__       =     self._prepare_for_class(a    ,		a    )
       check_equivalence(a    ,		a    ,		a    ,		{'output_hidden_states': True}    )

       A__       =     self._prepare_for_class(a    ,		a    ,		return_labels=a    )
       A__       =     self._prepare_for_class(a    ,		a    ,		return_labels=a    )
       check_equivalence(a    ,		a    ,		a    ,		{'output_hidden_states': True}    )




@require_torch
class 	_snake_case(			unittest.TestCase       , UpperCAmelCase      ):
 __snake_case:							List[str]						=					(MaskFormerSwinBackbone,) if is_torch_available() else ()
 __snake_case:							List[str]						=					MaskFormerSwinConfig






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






    """simple docstring"""


    A__       =     MaskFormerSwinModelTester(self    )






 def 						_UpperCamelCase (self       :  Tuple    )       ->   str:






    """simple docstring"""


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

    for backbone_class in self.all_model_classes:
       A__       =     backbone_class(a    )
       backbone.to(a    )
       backbone.eval()

       A__       =     backbone(**a    )

       # Test default outputs and verify feature maps
       self.assertIsInstance(outputs.feature_maps    ,		a    )
       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
       A__       =     backbone(**a    ,		output_hidden_states=a    )
       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)
             A__  ,			A__  ,			A__       =     hidden_state.shape
             self.assertTrue((h_batch_size, h_n_channels)    ,		(batch_size, n_channels)    )

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








'''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(			UpperCAmelCase       , UpperCAmelCase       , UpperCAmelCase       , unittest.TestCase      ):
 __snake_case:							Union[str, Any]						=					StableUnCLIPPipeline
 __snake_case:							List[str]						=					TEXT_TO_IMAGE_PARAMS
 __snake_case:							str						=					TEXT_TO_IMAGE_BATCH_PARAMS
 __snake_case:							Dict						=					TEXT_TO_IMAGE_IMAGE_PARAMS
 __snake_case:							List[str]						=					TEXT_TO_IMAGE_IMAGE_PARAMS

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






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






    """simple docstring"""


    A__       =     32
    A__       =     embedder_hidden_size

    # prior components

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

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

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

    torch.manual_seed(0    )
    A__       =     DDPMScheduler(
        variance_type='fixed_small_log'    ,		prediction_type='sample'    ,		num_train_timesteps=10_00    ,		clip_sample=a    ,		clip_sample_range=5.0    ,		beta_schedule='squaredcos_cap_v2'    ,		)

    # regular denoising components

    torch.manual_seed(0    )
    A__       =     StableUnCLIPImageNormalizer(embedding_dim=a    )
    A__       =     DDPMScheduler(beta_schedule='squaredcos_cap_v2'    )

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

    torch.manual_seed(0    )
    A__       =     CLIPTextModel(
        CLIPTextConfig(
            bos_token_id=0    ,		eos_token_id=2    ,		hidden_size=a    ,		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=10_00    ,		)    )

    torch.manual_seed(0    )
    A__       =     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=a    ,		layers_per_block=1    ,		upcast_attention=a    ,		use_linear_projection=a    ,		)

    torch.manual_seed(0    )
    A__       =     DDIMScheduler(
        beta_schedule='scaled_linear'    ,		beta_start=0.0_0085    ,		beta_end=0.012    ,		prediction_type='v_prediction'    ,		set_alpha_to_one=a    ,		steps_offset=1    ,		)

    torch.manual_seed(0    )
    A__       =     AutoencoderKL()

    A__       =     {
        # 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 						_UpperCamelCase (self       :  List[Any]    ,		a       :  Optional[Any]    ,		a       :  str=0    )       ->   Dict:






    """simple docstring"""


    if str(a    ).startswith('mps'    ):
       A__       =     torch.manual_seed(a    )
    else:
       A__       =     torch.Generator(device=a    ).manual_seed(a    )
    A__       =     {
        '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 						_UpperCamelCase (self       :  List[str]    )       ->   Optional[int]:






    """simple docstring"""


    A__       =     torch_device == 'cpu'

    self._test_attention_slicing_forward_pass(test_max_difference=a    )






 def 						_UpperCamelCase (self       :  Dict    )       ->   str:






    """simple docstring"""


    A__       =     torch_device in ['cpu', 'mps']

    self._test_inference_batch_single_identical(test_max_difference=a    )




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






 def 						_UpperCamelCase (self       :  Any    )       ->   Optional[Any]:






    """simple docstring"""


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






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






    """simple docstring"""


    A__       =     load_numpy(
        'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy'    )

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

    A__       =     torch.Generator(device='cpu'    ).manual_seed(0    )
    A__       =     pipe('anime turle'    ,		generator=a    ,		output_type='np'    )

    A__       =     output.images[0]

    assert image.shape == (7_68, 7_68, 3)

    assert_mean_pixel_difference(a    ,		a    )






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






    """simple docstring"""


    torch.cuda.empty_cache()
    torch.cuda.reset_max_memory_allocated()
    torch.cuda.reset_peak_memory_stats()

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

    A__       =     pipe(
        'anime turtle'    ,		prior_num_inference_steps=2    ,		num_inference_steps=2    ,		output_type='np'    ,		)

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


