

'''simple docstring'''





import inspect
import unittest
import warnings
from math import ceil, floor

from transformers import LevitConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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 transformers import (
           MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
           MODEL_MAPPING,
           LevitForImageClassification,
           LevitForImageClassificationWithTeacher,
           LevitModel,
       )
       from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import LevitImageProcessor






class  UpperCAmelCase__	( A__ ):






  """simple docstring"""


  def    lowercase_	(							self		:	List[Any]      )	->							Dict:
       SCREAMING_SNAKE_CASE__					=					self.config_class(**self.inputs_dict      )
       self.parent.assertTrue(hasattr(__UpperCamelCase			,     '''hidden_sizes'''      )      )
       self.parent.assertTrue(hasattr(__UpperCamelCase			,     '''num_attention_heads'''      )      )






class  UpperCAmelCase__	:






  """simple docstring"""


  def __init__(							self		:	Tuple			,     __lowerCamelCase		:	Any			,     __lowerCamelCase		:	List[Any]=13			,     __lowerCamelCase		:	Tuple=64			,     __lowerCamelCase		:	int=3			,     __lowerCamelCase		:	int=3			,     __lowerCamelCase		:	Tuple=2			,     __lowerCamelCase		:	int=1			,     __lowerCamelCase		:	Any=16			,     __lowerCamelCase		:	Optional[Any]=[128, 256, 384]			,     __lowerCamelCase		:	Any=[4, 6, 8]			,     __lowerCamelCase		:	Any=[2, 3, 4]			,     __lowerCamelCase		:	Optional[int]=[16, 16, 16]			,     __lowerCamelCase		:	List[str]=0			,     __lowerCamelCase		:	List[str]=[2, 2, 2]			,     __lowerCamelCase		:	List[Any]=[2, 2, 2]			,     __lowerCamelCase		:	Tuple=0.02			,     __lowerCamelCase		:	Union[str, Any]=True			,     __lowerCamelCase		:	str=True			,     __lowerCamelCase		:	List[str]=2			,     )	->							Union[str, Any]:
       SCREAMING_SNAKE_CASE__					=					parent
       SCREAMING_SNAKE_CASE__					=					batch_size
       SCREAMING_SNAKE_CASE__					=					image_size
       SCREAMING_SNAKE_CASE__					=					num_channels
       SCREAMING_SNAKE_CASE__					=					kernel_size
       SCREAMING_SNAKE_CASE__					=					stride
       SCREAMING_SNAKE_CASE__					=					padding
       SCREAMING_SNAKE_CASE__					=					hidden_sizes
       SCREAMING_SNAKE_CASE__					=					num_attention_heads
       SCREAMING_SNAKE_CASE__					=					depths
       SCREAMING_SNAKE_CASE__					=					key_dim
       SCREAMING_SNAKE_CASE__					=					drop_path_rate
       SCREAMING_SNAKE_CASE__					=					patch_size
       SCREAMING_SNAKE_CASE__					=					attention_ratio
       SCREAMING_SNAKE_CASE__					=					mlp_ratio
       SCREAMING_SNAKE_CASE__					=					initializer_range
       SCREAMING_SNAKE_CASE__					=					[
           ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
           ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
       ]
       SCREAMING_SNAKE_CASE__					=					is_training
       SCREAMING_SNAKE_CASE__					=					use_labels
       SCREAMING_SNAKE_CASE__					=					num_labels
       SCREAMING_SNAKE_CASE__					=					initializer_range






  def    lowercase_	(							self		:	Optional[Any]      )	->							Union[str, Any]:
       SCREAMING_SNAKE_CASE__					=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

       SCREAMING_SNAKE_CASE__					=					None
       if self.use_labels:
            SCREAMING_SNAKE_CASE__					=					ids_tensor([self.batch_size]			,     self.num_labels      )

       SCREAMING_SNAKE_CASE__					=					self.get_config()
       return config, pixel_values, labels






  def    lowercase_	(							self		:	Tuple      )	->							Any:
       return LevitConfig(
           image_size=self.image_size			,     num_channels=self.num_channels			,     kernel_size=self.kernel_size			,     stride=self.stride			,     padding=self.padding			,     patch_size=self.patch_size			,     hidden_sizes=self.hidden_sizes			,     num_attention_heads=self.num_attention_heads			,     depths=self.depths			,     key_dim=self.key_dim			,     drop_path_rate=self.drop_path_rate			,     mlp_ratio=self.mlp_ratio			,     attention_ratio=self.attention_ratio			,     initializer_range=self.initializer_range			,     down_ops=self.down_ops			,     )






  def    lowercase_	(							self		:	Union[str, Any]			,     __lowerCamelCase		:	Any			,     __lowerCamelCase		:	str			,     __lowerCamelCase		:	Optional[int]      )	->							List[Any]:
       SCREAMING_SNAKE_CASE__					=					LevitModel(config=__UpperCamelCase      )
       model.to(__UpperCamelCase      )
       model.eval()
       SCREAMING_SNAKE_CASE__					=					model(__UpperCamelCase      )
       SCREAMING_SNAKE_CASE__					=					(self.image_size, self.image_size)
       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					image_size[0], image_size[1]
       for _ in range(4      ):
            SCREAMING_SNAKE_CASE__					=					floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1      )
            SCREAMING_SNAKE_CASE__					=					floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1      )
       self.parent.assertEqual(
           result.last_hidden_state.shape			,     (self.batch_size, ceil(height / 4      ) * ceil(width / 4      ), self.hidden_sizes[-1])			,     )






  def    lowercase_	(							self		:	Dict			,     __lowerCamelCase		:	List[str]			,     __lowerCamelCase		:	int			,     __lowerCamelCase		:	int      )	->							Tuple:
       SCREAMING_SNAKE_CASE__					=					self.num_labels
       SCREAMING_SNAKE_CASE__					=					LevitForImageClassification(__UpperCamelCase      )
       model.to(__UpperCamelCase      )
       model.eval()
       SCREAMING_SNAKE_CASE__					=					model(__UpperCamelCase			,     labels=__UpperCamelCase      )
       self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.num_labels)      )







  def    lowercase_	(							self		:	Union[str, Any]      )	->							Union[str, Any]:
       SCREAMING_SNAKE_CASE__					=					self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					config_and_inputs
       SCREAMING_SNAKE_CASE__					=					{'''pixel_values''': pixel_values}
       return config, inputs_dict






@require_torch
class  UpperCAmelCase__	( A__		,  A__		,  unittest.TestCase ):






  """simple docstring"""


  a     =      (
      (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher)
      if is_torch_available()
      else ()
  )
  a     =      (
      {
          "feature-extraction": LevitModel,
          "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher),
      }
      if is_torch_available()
      else {}
  )

  a     =      False
  a     =      False
  a     =      False
  a     =      False
  a     =      False






  def    lowercase_	(							self		:	List[str]      )	->							Dict:
       SCREAMING_SNAKE_CASE__					=					LevitModelTester(self      )
       SCREAMING_SNAKE_CASE__					=					ConfigTester(self			,     config_class=__UpperCamelCase			,     has_text_modality=__UpperCamelCase			,     hidden_size=37      )






  def    lowercase_	(							self		:	Tuple      )	->							Any:
       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    lowercase_	(							self		:	Union[str, Any]      )	->							int:
       return






  @unittest.skip(reason='''Levit does not use inputs_embeds'''      )
  def    lowercase_	(							self		:	str      )	->							Optional[Any]:
       pass






  @unittest.skip(reason='''Levit does not support input and output embeddings'''      )
  def    lowercase_	(							self		:	int      )	->							str:
       pass






  @unittest.skip(reason='''Levit does not output attentions'''      )
  def    lowercase_	(							self		:	Tuple      )	->							Tuple:
       pass






  def    lowercase_	(							self		:	str      )	->							Optional[int]:
       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					self.model_tester.prepare_config_and_inputs_for_common()

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

            SCREAMING_SNAKE_CASE__					=					['''pixel_values''']
            self.assertListEqual(arg_names[:1]			,     __UpperCamelCase      )






  def    lowercase_	(							self		:	Union[str, Any]      )	->							List[Any]:
       def check_hidden_states_output(__lowerCamelCase		:	int			,     __lowerCamelCase		:	Optional[int]			,     __lowerCamelCase		:	int      ):
            SCREAMING_SNAKE_CASE__					=					model_class(__UpperCamelCase      )
            model.to(__UpperCamelCase      )
            model.eval()

            with torch.no_grad():
                 SCREAMING_SNAKE_CASE__					=					model(**self._prepare_for_class(__UpperCamelCase			,     __UpperCamelCase      )      )

            SCREAMING_SNAKE_CASE__					=					outputs.hidden_states

            SCREAMING_SNAKE_CASE__					=					len(self.model_tester.depths      ) + 1
            self.assertEqual(len(__UpperCamelCase      )			,     __UpperCamelCase      )

            SCREAMING_SNAKE_CASE__					=					(self.model_tester.image_size, self.model_tester.image_size)
            SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					image_size[0], image_size[1]
            for _ in range(4      ):
                 SCREAMING_SNAKE_CASE__					=					floor(
                     (
                         (height + 2 * self.model_tester.padding - self.model_tester.kernel_size)
                         / self.model_tester.stride
                     )
                     + 1      )
                 SCREAMING_SNAKE_CASE__					=					floor(
                     (
                         (width + 2 * self.model_tester.padding - self.model_tester.kernel_size)
                         / self.model_tester.stride
                     )
                     + 1      )
            # verify the first hidden states (first block)
            self.assertListEqual(
                list(hidden_states[0].shape[-2:]      )			,     [
                    height * width,
                    self.model_tester.hidden_sizes[0],
                ]			,     )

       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            SCREAMING_SNAKE_CASE__					=					True
            check_hidden_states_output(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase      )

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

            check_hidden_states_output(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase      )






  @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''      )
  def    lowercase_	(							self		:	str      )	->							int:
       pass






  def    lowercase_	(							self		:	Optional[Any]			,     __lowerCamelCase		:	Union[str, Any]			,     __lowerCamelCase		:	List[Any]			,     __lowerCamelCase		:	Union[str, Any]=False      )	->							Dict:
       SCREAMING_SNAKE_CASE__					=					super()._prepare_for_class(__UpperCamelCase			,     __UpperCamelCase			,     return_labels=__UpperCamelCase      )

       if return_labels:
            if model_class.__name__ == "LevitForImageClassificationWithTeacher":
                 del inputs_dict["labels"]

       return inputs_dict






  def    lowercase_	(							self		:	List[Any]      )	->							List[Any]:
       SCREAMING_SNAKE_CASE__					=					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__UpperCamelCase      )






  def    lowercase_	(							self		:	List[Any]      )	->							List[Any]:
       SCREAMING_SNAKE_CASE__					=					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase      )






  def    lowercase_	(							self		:	Tuple      )	->							List[str]:
       if not self.model_tester.is_training:
            return

       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					self.model_tester.prepare_config_and_inputs_for_common()
       SCREAMING_SNAKE_CASE__					=					True

       for model_class in self.all_model_classes:
            # LevitForImageClassificationWithTeacher supports inference-only
            if (
                model_class in get_values(__UpperCamelCase      )
                or model_class.__name__ == "LevitForImageClassificationWithTeacher"
            ):
                 continue
            SCREAMING_SNAKE_CASE__					=					model_class(__UpperCamelCase      )
            model.to(__UpperCamelCase      )
            model.train()
            SCREAMING_SNAKE_CASE__					=					self._prepare_for_class(__UpperCamelCase			,     __UpperCamelCase			,     return_labels=__UpperCamelCase      )
            SCREAMING_SNAKE_CASE__					=					model(**__UpperCamelCase      ).loss
            loss.backward()






  def    lowercase_	(							self		:	int      )	->							Any:
       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					self.model_tester.prepare_config_and_inputs_for_common()
       if not self.model_tester.is_training:
            return

       SCREAMING_SNAKE_CASE__					=					False
       SCREAMING_SNAKE_CASE__					=					True

       for model_class in self.all_model_classes:
            if model_class in get_values(__UpperCamelCase      ) or not model_class.supports_gradient_checkpointing:
                 continue
            # LevitForImageClassificationWithTeacher supports inference-only
            if model_class.__name__ == "LevitForImageClassificationWithTeacher":
                 continue
            SCREAMING_SNAKE_CASE__					=					model_class(__UpperCamelCase      )
            model.gradient_checkpointing_enable()
            model.to(__UpperCamelCase      )
            model.train()
            SCREAMING_SNAKE_CASE__					=					self._prepare_for_class(__UpperCamelCase			,     __UpperCamelCase			,     return_labels=__UpperCamelCase      )
            SCREAMING_SNAKE_CASE__					=					model(**__UpperCamelCase      ).loss
            loss.backward()






  def    lowercase_	(							self		:	List[str]      )	->							str:
       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					self.model_tester.prepare_config_and_inputs_for_common()

       SCREAMING_SNAKE_CASE__					=					[
           {'''title''': '''multi_label_classification''', '''num_labels''': 2, '''dtype''': torch.float},
           {'''title''': '''single_label_classification''', '''num_labels''': 1, '''dtype''': torch.long},
           {'''title''': '''regression''', '''num_labels''': 1, '''dtype''': torch.float},
       ]

       for model_class in self.all_model_classes:
            if (
                model_class
                not in [
                    *get_values(__UpperCamelCase      ),
                ]
                or model_class.__name__ == "LevitForImageClassificationWithTeacher"
            ):
                 continue

            for problem_type in problem_types:
                 with self.subTest(msg=f'''Testing {model_class} with {problem_type["title"]}'''      ):
                      SCREAMING_SNAKE_CASE__					=					problem_type['''title''']
                      SCREAMING_SNAKE_CASE__					=					problem_type['''num_labels''']

                      SCREAMING_SNAKE_CASE__					=					model_class(__UpperCamelCase      )
                      model.to(__UpperCamelCase      )
                      model.train()

                      SCREAMING_SNAKE_CASE__					=					self._prepare_for_class(__UpperCamelCase			,     __UpperCamelCase			,     return_labels=__UpperCamelCase      )

                      if problem_type["num_labels"] > 1:
                           SCREAMING_SNAKE_CASE__					=					inputs['''labels'''].unsqueeze(1      ).repeat(1			,     problem_type['''num_labels''']      )

                      SCREAMING_SNAKE_CASE__					=					inputs['''labels'''].to(problem_type['''dtype''']      )

                      # This tests that we do not trigger the warning form PyTorch "Using a target size that is different
                      # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
                      # they have the same size." which is a symptom something in wrong for the regression problem.
                      # See https://github.com/huggingface/transformers/issues/11780
                      with warnings.catch_warnings(record=__UpperCamelCase      ) as warning_list:
                           SCREAMING_SNAKE_CASE__					=					model(**__UpperCamelCase      ).loss
                      for w in warning_list:
                           if "Using a target size that is different to the input size" in str(w.message      ):
                                raise ValueError(
                                    f'''Something is going wrong in the regression problem: intercepted {w.message}'''      )

                      loss.backward()







  @slow
  def    lowercase_	(							self		:	List[Any]      )	->							Union[str, Any]:
       for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            SCREAMING_SNAKE_CASE__					=					LevitModel.from_pretrained(__UpperCamelCase      )
            self.assertIsNotNone(__UpperCamelCase      )



def        UpperCAmelCase_     (		):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''       )
     return image







@require_torch
@require_vision
class  UpperCAmelCase__	( unittest.TestCase ):






  """simple docstring"""


  @cached_property
  def    lowercase_	(							self		:	Optional[Any]      )	->							int:
       return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )







  @slow
  def    lowercase_	(							self		:	str      )	->							Any:
       SCREAMING_SNAKE_CASE__					=					LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]      ).to(
           __UpperCamelCase      )

       SCREAMING_SNAKE_CASE__					=					self.default_image_processor
       SCREAMING_SNAKE_CASE__					=					prepare_img()
       SCREAMING_SNAKE_CASE__					=					image_processor(images=__UpperCamelCase			,     return_tensors='''pt'''      ).to(__UpperCamelCase      )

       # forward pass
       with torch.no_grad():
            SCREAMING_SNAKE_CASE__					=					model(**__UpperCamelCase      )

       # verify the logits
       SCREAMING_SNAKE_CASE__					=					torch.Size((1, 1000)      )
       self.assertEqual(outputs.logits.shape			,     __UpperCamelCase      )

       SCREAMING_SNAKE_CASE__					=					torch.tensor([1.0448, -0.3745, -1.8317]      ).to(__UpperCamelCase      )

       self.assertTrue(torch.allclose(outputs.logits[0, :3]			,     __UpperCamelCase			,     atol=1e-4      )      )





import gc
import unittest

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

from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
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 PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class  UpperCAmelCase__	( A__		,  A__		,  A__		,  unittest.TestCase ):






  """simple docstring"""


  a     =      AltDiffusionPipeline
  a     =      TEXT_TO_IMAGE_PARAMS
  a     =      TEXT_TO_IMAGE_BATCH_PARAMS
  a     =      TEXT_TO_IMAGE_IMAGE_PARAMS
  a     =      TEXT_TO_IMAGE_IMAGE_PARAMS






  def    lowercase_	(							self		:	Tuple      )	->							Tuple:
       torch.manual_seed(0      )
       SCREAMING_SNAKE_CASE__					=					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			,     )
       SCREAMING_SNAKE_CASE__					=					DDIMScheduler(
           beta_start=0.00085			,     beta_end=0.012			,     beta_schedule='''scaled_linear'''			,     clip_sample=__lowerCamelCase			,     set_alpha_to_one=__lowerCamelCase			,     )
       torch.manual_seed(0      )
       SCREAMING_SNAKE_CASE__					=					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			,     )

       # TODO: address the non-deterministic text encoder (fails for save-load tests)
       # torch.manual_seed(0)
       # text_encoder_config = RobertaSeriesConfig(
       #     hidden_size=32,
       #     project_dim=32,
       #     intermediate_size=37,
       #     layer_norm_eps=1e-05,
       #     num_attention_heads=4,
       #     num_hidden_layers=5,
       #     vocab_size=5002,
       # )
       # text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config)

       torch.manual_seed(0      )
       SCREAMING_SNAKE_CASE__					=					CLIPTextConfig(
           bos_token_id=0			,     eos_token_id=2			,     hidden_size=32			,     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=5002			,     )
       SCREAMING_SNAKE_CASE__					=					CLIPTextModel(__lowerCamelCase      )

       SCREAMING_SNAKE_CASE__					=					XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta'''      )
       SCREAMING_SNAKE_CASE__					=					77

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






  def    lowercase_	(							self		:	Any			,     __lowerCamelCase		:	Tuple			,     __lowerCamelCase		:	Optional[int]=0      )	->							Union[str, Any]:
       if str(__lowerCamelCase      ).startswith('''mps'''      ):
            SCREAMING_SNAKE_CASE__					=					torch.manual_seed(__lowerCamelCase      )
       else:
            SCREAMING_SNAKE_CASE__					=					torch.Generator(device=__lowerCamelCase      ).manual_seed(__lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					{
           '''prompt''': '''A painting of a squirrel eating a burger''',
           '''generator''': generator,
           '''num_inference_steps''': 2,
           '''guidance_scale''': 6.0,
           '''output_type''': '''numpy''',
       }
       return inputs






  def    lowercase_	(							self		:	List[Any]      )	->							str:
       super().test_attention_slicing_forward_pass(expected_max_diff=3e-3      )






  def    lowercase_	(							self		:	List[Any]      )	->							int:
       super().test_inference_batch_single_identical(expected_max_diff=3e-3      )






  def    lowercase_	(							self		:	Dict      )	->							Optional[int]:
       SCREAMING_SNAKE_CASE__					=					'''cpu'''  # ensure determinism for the device-dependent torch.Generator

       SCREAMING_SNAKE_CASE__					=					self.get_dummy_components()
       torch.manual_seed(0      )
       SCREAMING_SNAKE_CASE__					=					RobertaSeriesConfig(
           hidden_size=32			,     project_dim=32			,     intermediate_size=37			,     layer_norm_eps=1e-05			,     num_attention_heads=4			,     num_hidden_layers=5			,     vocab_size=5002			,     )
       # TODO: remove after fixing the non-deterministic text encoder
       SCREAMING_SNAKE_CASE__					=					RobertaSeriesModelWithTransformation(__lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					text_encoder

       SCREAMING_SNAKE_CASE__					=					AltDiffusionPipeline(**__lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					alt_pipe.to(__lowerCamelCase      )
       alt_pipe.set_progress_bar_config(disable=__lowerCamelCase      )

       SCREAMING_SNAKE_CASE__					=					self.get_dummy_inputs(__lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					'''A photo of an astronaut'''
       SCREAMING_SNAKE_CASE__					=					alt_pipe(**__lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					output.images
       SCREAMING_SNAKE_CASE__					=					image[0, -3:, -3:, -1]

       assert image.shape == (1, 64, 64, 3)
       SCREAMING_SNAKE_CASE__					=					np.array(
           [0.5748162, 0.60447145, 0.48821217, 0.50100636, 0.5431185, 0.45763683, 0.49657696, 0.48132733, 0.47573093]      )

       assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-2







  def    lowercase_	(							self		:	List[Any]      )	->							Optional[Any]:
       SCREAMING_SNAKE_CASE__					=					'''cpu'''  # ensure determinism for the device-dependent torch.Generator

       SCREAMING_SNAKE_CASE__					=					self.get_dummy_components()
       SCREAMING_SNAKE_CASE__					=					PNDMScheduler(skip_prk_steps=__lowerCamelCase      )
       torch.manual_seed(0      )
       SCREAMING_SNAKE_CASE__					=					RobertaSeriesConfig(
           hidden_size=32			,     project_dim=32			,     intermediate_size=37			,     layer_norm_eps=1e-05			,     num_attention_heads=4			,     num_hidden_layers=5			,     vocab_size=5002			,     )
       # TODO: remove after fixing the non-deterministic text encoder
       SCREAMING_SNAKE_CASE__					=					RobertaSeriesModelWithTransformation(__lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					text_encoder
       SCREAMING_SNAKE_CASE__					=					AltDiffusionPipeline(**__lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					alt_pipe.to(__lowerCamelCase      )
       alt_pipe.set_progress_bar_config(disable=__lowerCamelCase      )

       SCREAMING_SNAKE_CASE__					=					self.get_dummy_inputs(__lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					alt_pipe(**__lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					output.images
       SCREAMING_SNAKE_CASE__					=					image[0, -3:, -3:, -1]

       assert image.shape == (1, 64, 64, 3)
       SCREAMING_SNAKE_CASE__					=					np.array(
           [0.51605093, 0.5707241, 0.47365507, 0.50578886, 0.5633877, 0.4642503, 0.5182081, 0.48763484, 0.49084237]      )

       assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-2






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






  """simple docstring"""


  def    lowercase_	(							self		:	Tuple      )	->							str:
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()






  def    lowercase_	(							self		:	str      )	->							Any:
       # make sure here that pndm scheduler skips prk
       SCREAMING_SNAKE_CASE__					=					AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion'''			,     safety_checker=__lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					alt_pipe.to(__lowerCamelCase      )
       alt_pipe.set_progress_bar_config(disable=__lowerCamelCase      )

       SCREAMING_SNAKE_CASE__					=					'''A painting of a squirrel eating a burger'''
       SCREAMING_SNAKE_CASE__					=					torch.manual_seed(0      )
       SCREAMING_SNAKE_CASE__					=					alt_pipe([prompt]			,     generator=__lowerCamelCase			,     guidance_scale=6.0			,     num_inference_steps=20			,     output_type='''np'''      )

       SCREAMING_SNAKE_CASE__					=					output.images

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

       assert image.shape == (1, 512, 512, 3)
       SCREAMING_SNAKE_CASE__					=					np.array([0.1010, 0.0800, 0.0794, 0.0885, 0.0843, 0.0762, 0.0769, 0.0729, 0.0586]      )

       assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-2







  def    lowercase_	(							self		:	Optional[int]      )	->							List[str]:
       SCREAMING_SNAKE_CASE__					=					DDIMScheduler.from_pretrained('''BAAI/AltDiffusion'''			,     subfolder='''scheduler'''      )

       SCREAMING_SNAKE_CASE__					=					AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion'''			,     scheduler=__lowerCamelCase			,     safety_checker=__lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					alt_pipe.to(__lowerCamelCase      )
       alt_pipe.set_progress_bar_config(disable=__lowerCamelCase      )

       SCREAMING_SNAKE_CASE__					=					'''A painting of a squirrel eating a burger'''
       SCREAMING_SNAKE_CASE__					=					torch.manual_seed(0      )

       SCREAMING_SNAKE_CASE__					=					alt_pipe([prompt]			,     generator=__lowerCamelCase			,     num_inference_steps=2			,     output_type='''numpy'''      )
       SCREAMING_SNAKE_CASE__					=					output.images

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

       assert image.shape == (1, 512, 512, 3)
       SCREAMING_SNAKE_CASE__					=					np.array([0.4019, 0.4052, 0.3810, 0.4119, 0.3916, 0.3982, 0.4651, 0.4195, 0.5323]      )

       assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-2


