





from __future__ import annotations

import unittest

from transformers import FunnelConfig, is_tf_available
from transformers.testing_utils import require_tf

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import tensorflow as tf

    from transformers import (
        TFFunnelBaseModel,
        TFFunnelForMaskedLM,
        TFFunnelForMultipleChoice,
        TFFunnelForPreTraining,
        TFFunnelForQuestionAnswering,
        TFFunnelForSequenceClassification,
        TFFunnelForTokenClassification,
        TFFunnelModel,
    )



class 					A__   :





      def __init__( self       ,							A_       ,							A_=13       ,							A_=7       ,							A_=True       ,							A_=True       ,							A_=True       ,							A_=True       ,							A_=99       ,							A_=[1, 1, 2]       ,							A_=1       ,							A_=32       ,							A_=4       ,							A_=8       ,							A_=37       ,							A_="gelu_new"       ,							A_=0.1       ,							A_=0.1       ,							A_=0.0       ,							A_=512       ,							A_=3       ,							A_=0.02       ,							A_=3       ,							A_=4       ,							A_=None       ,							A_=False       ,							):
       '''simple docstring'''




       UpperCamelCase	:					int       	=   parent
       UpperCamelCase	:					Optional[int]       	=   batch_size
       UpperCamelCase	:					List[Any]       	=   seq_length
       UpperCamelCase	:					Tuple       	=   is_training
       UpperCamelCase	:					Optional[Any]       	=   use_input_mask
       UpperCamelCase	:					Any       	=   use_token_type_ids
       UpperCamelCase	:					Optional[Any]       	=   use_labels
       UpperCamelCase	:					List[str]       	=   vocab_size
       UpperCamelCase	:					Tuple       	=   block_sizes
       UpperCamelCase	:					List[Any]       	=   num_decoder_layers
       UpperCamelCase	:					Optional[Any]       	=   d_model
       UpperCamelCase	:					List[Any]       	=   n_head
       UpperCamelCase	:					Union[str, Any]       	=   d_head
       UpperCamelCase	:					Tuple       	=   d_inner
       UpperCamelCase	:					str       	=   hidden_act
       UpperCamelCase	:					List[Any]       	=   hidden_dropout
       UpperCamelCase	:					Any       	=   attention_dropout
       UpperCamelCase	:					Tuple       	=   activation_dropout
       UpperCamelCase	:					Optional[int]       	=   max_position_embeddings
       UpperCamelCase	:					Tuple       	=   type_vocab_size
       UpperCamelCase	:					List[str]       	=   2
       UpperCamelCase	:					Optional[Any]       	=   num_labels
       UpperCamelCase	:					Union[str, Any]       	=   num_choices
       UpperCamelCase	:					Tuple       	=   scope
       UpperCamelCase	:					Dict       	=   initializer_std

       # Used in the tests to check the size of the first attention layer
       UpperCamelCase	:					str       	=   n_head
       # Used in the tests to check the size of the first hidden state
       UpperCamelCase	:					Optional[Any]       	=   self.d_model
       # Used in the tests to check the number of output hidden states/attentions
       UpperCamelCase	:					Optional[Any]       	=   sum(self.block_sizes   ) + (0 if base else self.num_decoder_layers)
       # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with
       # the last hidden state of the first block (which is the first hidden state of the decoder).
       if not base:
        UpperCamelCase	:					Union[str, Any]       	=   self.num_hidden_layers + 2





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Union[str, Any]       	=   ids_tensor([self.batch_size, self.seq_length]       ,							self.vocab_size   )

       UpperCamelCase	:					int       	=   None
       if self.use_input_mask:
        UpperCamelCase	:					List[str]       	=   random_attention_mask([self.batch_size, self.seq_length]   )

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

       UpperCamelCase	:					List[Any]       	=   None
       UpperCamelCase	:					Union[str, Any]       	=   None
       UpperCamelCase	:					Optional[int]       	=   None
       if self.use_labels:
        UpperCamelCase	:					Any       	=   ids_tensor([self.batch_size]       ,							self.type_sequence_label_size   )
        UpperCamelCase	:					Optional[int]       	=   ids_tensor([self.batch_size, self.seq_length]       ,							self.num_labels   )
        UpperCamelCase	:					Dict       	=   ids_tensor([self.batch_size]       ,							self.num_choices   )

       UpperCamelCase	:					Dict       	=   FunnelConfig(
           vocab_size=self.vocab_size       ,							block_sizes=self.block_sizes       ,							num_decoder_layers=self.num_decoder_layers       ,							d_model=self.d_model       ,							n_head=self.n_head       ,							d_head=self.d_head       ,							d_inner=self.d_inner       ,							hidden_act=self.hidden_act       ,							hidden_dropout=self.hidden_dropout       ,							attention_dropout=self.attention_dropout       ,							activation_dropout=self.activation_dropout       ,							max_position_embeddings=self.max_position_embeddings       ,							type_vocab_size=self.type_vocab_size       ,							initializer_std=self.initializer_std       ,							)

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





      def        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							):
       '''simple docstring'''




       UpperCamelCase	:					List[Any]       	=   TFFunnelModel(config=A_   )
       UpperCamelCase	:					int       	=   {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
       UpperCamelCase	:					List[str]       	=   model(A_   )

       UpperCamelCase	:					Union[str, Any]       	=   [input_ids, input_mask]
       UpperCamelCase	:					Tuple       	=   model(A_   )

       UpperCamelCase	:					Dict       	=   model(A_   )
       self.parent.assertEqual(result.last_hidden_state.shape       ,							(self.batch_size, self.seq_length, self.d_model)   )

       UpperCamelCase	:					int       	=   False
       UpperCamelCase	:					Optional[int]       	=   TFFunnelModel(config=A_   )
       UpperCamelCase	:					str       	=   model(A_   )
       self.parent.assertEqual(result.last_hidden_state.shape       ,							(self.batch_size, self.seq_length, self.d_model)   )

       UpperCamelCase	:					Union[str, Any]       	=   False
       UpperCamelCase	:					str       	=   TFFunnelModel(config=A_   )
       UpperCamelCase	:					List[Any]       	=   model(A_   )
       self.parent.assertEqual(result.last_hidden_state.shape       ,							(self.batch_size, self.seq_length, self.d_model)   )





      def        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							):
       '''simple docstring'''




       UpperCamelCase	:					List[str]       	=   TFFunnelBaseModel(config=A_   )
       UpperCamelCase	:					Tuple       	=   {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
       UpperCamelCase	:					Optional[int]       	=   model(A_   )

       UpperCamelCase	:					List[Any]       	=   [input_ids, input_mask]
       UpperCamelCase	:					int       	=   model(A_   )

       UpperCamelCase	:					str       	=   model(A_   )
       self.parent.assertEqual(result.last_hidden_state.shape       ,							(self.batch_size, 2, self.d_model)   )

       UpperCamelCase	:					str       	=   False
       UpperCamelCase	:					Union[str, Any]       	=   TFFunnelBaseModel(config=A_   )
       UpperCamelCase	:					Optional[int]       	=   model(A_   )
       self.parent.assertEqual(result.last_hidden_state.shape       ,							(self.batch_size, 3, self.d_model)   )

       UpperCamelCase	:					Union[str, Any]       	=   False
       UpperCamelCase	:					List[Any]       	=   TFFunnelBaseModel(config=A_   )
       UpperCamelCase	:					Dict       	=   model(A_   )
       self.parent.assertEqual(result.last_hidden_state.shape       ,							(self.batch_size, 2, self.d_model)   )





      def        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							):
       '''simple docstring'''




       UpperCamelCase	:					Dict       	=   TFFunnelForPreTraining(config=A_   )
       UpperCamelCase	:					List[str]       	=   {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
       UpperCamelCase	:					Union[str, Any]       	=   model(A_   )
       self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.seq_length)   )





      def        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							):
       '''simple docstring'''




       UpperCamelCase	:					Union[str, Any]       	=   TFFunnelForMaskedLM(config=A_   )
       UpperCamelCase	:					List[Any]       	=   {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
       UpperCamelCase	:					List[Any]       	=   model(A_   )
       self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.seq_length, self.vocab_size)   )





      def        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							):
       '''simple docstring'''




       UpperCamelCase	:					List[Any]       	=   self.num_labels
       UpperCamelCase	:					Dict       	=   TFFunnelForSequenceClassification(config=A_   )
       UpperCamelCase	:					Optional[int]       	=   {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
       UpperCamelCase	:					Any       	=   model(A_   )
       self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.num_labels)   )





      def        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							):
       '''simple docstring'''




       UpperCamelCase	:					List[Any]       	=   self.num_choices
       UpperCamelCase	:					str       	=   TFFunnelForMultipleChoice(config=A_   )
       UpperCamelCase	:					int       	=   tf.tile(tf.expand_dims(A_       ,							1   )       ,							(1, self.num_choices, 1)   )
       UpperCamelCase	:					Optional[Any]       	=   tf.tile(tf.expand_dims(A_       ,							1   )       ,							(1, self.num_choices, 1)   )
       UpperCamelCase	:					str       	=   tf.tile(tf.expand_dims(A_       ,							1   )       ,							(1, self.num_choices, 1)   )
       UpperCamelCase	:					Any       	=   {
           "input_ids": multiple_choice_inputs_ids,
           "attention_mask": multiple_choice_input_mask,
           "token_type_ids": multiple_choice_token_type_ids,
       }
       UpperCamelCase	:					List[str]       	=   model(A_   )
       self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.num_choices)   )





      def        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							):
       '''simple docstring'''




       UpperCamelCase	:					List[Any]       	=   self.num_labels
       UpperCamelCase	:					Optional[Any]       	=   TFFunnelForTokenClassification(config=A_   )
       UpperCamelCase	:					int       	=   {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
       UpperCamelCase	:					List[str]       	=   model(A_   )
       self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.seq_length, self.num_labels)   )





      def        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							):
       '''simple docstring'''




       UpperCamelCase	:					Any       	=   TFFunnelForQuestionAnswering(config=A_   )
       UpperCamelCase	:					Optional[Any]       	=   {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
       UpperCamelCase	:					Union[str, Any]       	=   model(A_   )
       self.parent.assertEqual(result.start_logits.shape       ,							(self.batch_size, self.seq_length)   )
       self.parent.assertEqual(result.end_logits.shape       ,							(self.batch_size, self.seq_length)   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Optional[Any]       	=   self.prepare_config_and_inputs()
       (
           (
           UpperCamelCase
       )	,    (
           UpperCamelCase
       )	,    (
           UpperCamelCase
       )	,    (
           UpperCamelCase
       )	,    (
           UpperCamelCase
       )	,    (
           UpperCamelCase
       )	,    (
           UpperCamelCase
       )	,    
       )	:					Dict       	=   config_and_inputs
       UpperCamelCase	:					Any       	=   {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
       return config, inputs_dict



@require_tf
class 					A__   (       __snake_case       ,   __snake_case       ,   unittest.TestCase			):
      _UpperCAmelCase	:List[str]						    =   (
          (
              TFFunnelModel,
              TFFunnelForMaskedLM,
              TFFunnelForPreTraining,
              TFFunnelForQuestionAnswering,
              TFFunnelForTokenClassification,
          )
          if is_tf_available()
          else ()
      )
      _UpperCAmelCase	:Dict						    =   (
          {
              'feature-extraction': (TFFunnelBaseModel, TFFunnelModel),
              'fill-mask': TFFunnelForMaskedLM,
              'question-answering': TFFunnelForQuestionAnswering,
              'text-classification': TFFunnelForSequenceClassification,
              'token-classification': TFFunnelForTokenClassification,
              'zero-shot': TFFunnelForSequenceClassification,
          }
          if is_tf_available()
          else {}
      )
      _UpperCAmelCase	:Union[str, Any]						    =   False
      _UpperCAmelCase	:Tuple						    =   False





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Any       	=   TFFunnelModelTester(self   )
       UpperCamelCase	:					List[str]       	=   ConfigTester(self       ,							config_class=A_   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       self.config_tester.run_common_tests()





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Tuple       	=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*A_   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Any       	=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_pretraining(*A_   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Union[str, Any]       	=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_lm(*A_   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					str       	=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_token_classification(*A_   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Tuple       	=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_question_answering(*A_   )



@require_tf
class 					A__   (       __snake_case       ,   unittest.TestCase			):
      _UpperCAmelCase	:Optional[Any]						    =   (
          (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else ()
      )
      _UpperCAmelCase	:List[Any]						    =   False
      _UpperCAmelCase	:List[Any]						    =   False





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Tuple       	=   TFFunnelModelTester(self       ,							base=A_   )
       UpperCamelCase	:					Dict       	=   ConfigTester(self       ,							config_class=A_   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       self.config_tester.run_common_tests()





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					List[str]       	=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_base_model(*A_   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Optional[int]       	=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_sequence_classification(*A_   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Any       	=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_multiple_choice(*A_   )




import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()






class _lowerCamelCase(						unittest.TestCase   ):
       def 			UpperCamelCase     (					self)       ->   Optional[Any]:




           """simple docstring"""

           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()
       @property
       def 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

           _lowercase       :							Optional[Any]      		=		1
           _lowercase       :							Any      		=		3
           _lowercase       :							Tuple      		=		(32, 32)

           _lowercase       :							Tuple      		=		floats_tensor((batch_size, num_channels) + sizes,      rng=random.Random(0)).to(lowerCamelCase)
           return image
       @property
       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           torch.manual_seed(0)
           _lowercase       :							Dict      		=		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,      )
           return model
       @property
       def 			UpperCamelCase     (					self)       ->   List[Any]:




           """simple docstring"""

           torch.manual_seed(0)
           _lowercase       :							str      		=		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,      )
           return model
       @property
       def 			UpperCamelCase     (					self)       ->   Optional[Any]:




           """simple docstring"""

           torch.manual_seed(0)
           _lowercase       :							Optional[int]      		=		RobertaSeriesConfig(
               hidden_size=32,      project_dim=32,      intermediate_size=37,      layer_norm_eps=1E-05,      num_attention_heads=4,      num_hidden_layers=5,      pad_token_id=1,      vocab_size=50_06,      )
           return RobertaSeriesModelWithTransformation(lowerCamelCase)
       @property
       def 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

           def extract(*lowerCamelCase,      **lowerCamelCase):






               class _lowerCamelCase:
                      def __init__(					self)       ->   Optional[Any]:




                          """simple docstring"""

                          _lowercase       :							Optional[int]      		=		torch.ones([0])




                      def 			UpperCamelCase     (					self,      lowerCamelCase)       ->   int:




                          """simple docstring"""

                          self.pixel_values.to(lowerCamelCase)
                          return self


               return Out()

           return extract
       def 			UpperCamelCase     (					self)       ->   Tuple:




           """simple docstring"""

           _lowercase       :							Any      		=		'cpu'  # ensure determinism for the device-dependent torch.Generator
           _lowercase       :							List[Any]      		=		self.dummy_cond_unet
           _lowercase       :							Union[str, Any]      		=		PNDMScheduler(skip_prk_steps=lowerCamelCase)
           _lowercase       :							Optional[Any]      		=		self.dummy_vae
           _lowercase       :							List[Any]      		=		self.dummy_text_encoder
           _lowercase       :							Any      		=		XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta')
           _lowercase       :							Tuple      		=		77

           _lowercase       :							int      		=		self.dummy_image.to(lowerCamelCase)
           _lowercase       :							int      		=		init_image / 2 + 0.5

           # make sure here that pndm scheduler skips prk
           _lowercase       :							Union[str, Any]      		=		AltDiffusionImgaImgPipeline(
               unet=lowerCamelCase,      scheduler=lowerCamelCase,      vae=lowerCamelCase,      text_encoder=lowerCamelCase,      tokenizer=lowerCamelCase,      safety_checker=lowerCamelCase,      feature_extractor=self.dummy_extractor,      )
           _lowercase       :							List[Any]      		=		VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor,      do_normalize=lowerCamelCase)
           _lowercase       :							Optional[int]      		=		alt_pipe.to(lowerCamelCase)
           alt_pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase       :							Optional[Any]      		=		'A painting of a squirrel eating a burger'
           _lowercase       :							Dict      		=		torch.Generator(device=lowerCamelCase).manual_seed(0)
           _lowercase       :							Any      		=		alt_pipe(
               [prompt],      generator=lowerCamelCase,      guidance_scale=6.0,      num_inference_steps=2,      output_type='np',      image=lowerCamelCase,      )

           _lowercase       :							Optional[int]      		=		output.images

           _lowercase       :							Optional[Any]      		=		torch.Generator(device=lowerCamelCase).manual_seed(0)
           _lowercase       :							Optional[Any]      		=		alt_pipe(
               [prompt],      generator=lowerCamelCase,      guidance_scale=6.0,      num_inference_steps=2,      output_type='np',      image=lowerCamelCase,      return_dict=lowerCamelCase,      )[0]

           _lowercase       :							Optional[int]      		=		image[0, -3:, -3:, -1]
           _lowercase       :							Dict      		=		image_from_tuple[0, -3:, -3:, -1]

           assert image.shape == (1, 32, 32, 3)
           _lowercase       :							int      		=		np.array([0.4_4_2_7, 0.3_7_3_1, 0.4_2_4_9, 0.4_9_4_1, 0.4_5_4_6, 0.4_1_4_8, 0.4_1_9_3, 0.4_6_6_6, 0.4_4_9_9])

           assert np.abs(image_slice.flatten() - expected_slice).max() < 5E-3
           assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 5E-3
       @unittest.skipIf(torch_device != 'cuda',      'This test requires a GPU')
       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           _lowercase       :							List[Any]      		=		self.dummy_cond_unet
           _lowercase       :							Tuple      		=		PNDMScheduler(skip_prk_steps=lowerCamelCase)
           _lowercase       :							str      		=		self.dummy_vae
           _lowercase       :							Optional[Any]      		=		self.dummy_text_encoder
           _lowercase       :							Optional[Any]      		=		XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta')
           _lowercase       :							Optional[Any]      		=		77

           _lowercase       :							str      		=		self.dummy_image.to(lowerCamelCase)

           # put models in fp16
           _lowercase       :							List[str]      		=		unet.half()
           _lowercase       :							List[Any]      		=		vae.half()
           _lowercase       :							Any      		=		bert.half()

           # make sure here that pndm scheduler skips prk
           _lowercase       :							Union[str, Any]      		=		AltDiffusionImgaImgPipeline(
               unet=lowerCamelCase,      scheduler=lowerCamelCase,      vae=lowerCamelCase,      text_encoder=lowerCamelCase,      tokenizer=lowerCamelCase,      safety_checker=lowerCamelCase,      feature_extractor=self.dummy_extractor,      )
           _lowercase       :							List[str]      		=		VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor,      do_normalize=lowerCamelCase)
           _lowercase       :							Any      		=		alt_pipe.to(lowerCamelCase)
           alt_pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase       :							int      		=		'A painting of a squirrel eating a burger'
           _lowercase       :							Optional[Any]      		=		torch.manual_seed(0)
           _lowercase       :							Union[str, Any]      		=		alt_pipe(
               [prompt],      generator=lowerCamelCase,      num_inference_steps=2,      output_type='np',      image=lowerCamelCase,      ).images

           assert image.shape == (1, 32, 32, 3)




       @unittest.skipIf(torch_device != 'cuda',      'This test requires a GPU')
       def 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

           _lowercase       :							int      		=		load_image(
               'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
               '/img2img/sketch-mountains-input.jpg')
           # resize to resolution that is divisible by 8 but not 16 or 32
           _lowercase       :							str      		=		init_image.resize((7_60, 5_04))

           _lowercase       :							Optional[int]      		=		'BAAI/AltDiffusion'
           _lowercase       :							str      		=		AltDiffusionImgaImgPipeline.from_pretrained(
               lowerCamelCase,      safety_checker=lowerCamelCase,      )
           pipe.to(lowerCamelCase)
           pipe.set_progress_bar_config(disable=lowerCamelCase)
           pipe.enable_attention_slicing()

           _lowercase       :							List[str]      		=		'A fantasy landscape, trending on artstation'

           _lowercase       :							Any      		=		torch.manual_seed(0)
           _lowercase       :							Dict      		=		pipe(
               prompt=lowerCamelCase,      image=lowerCamelCase,      strength=0.7_5,      guidance_scale=7.5,      generator=lowerCamelCase,      output_type='np',      )
           _lowercase       :							List[str]      		=		output.images[0]

           _lowercase       :							Tuple      		=		image[2_55:2_58, 3_83:3_86, -1]

           assert image.shape == (5_04, 7_60, 3)
           _lowercase       :							Optional[Any]      		=		np.array([0.9_3_5_8, 0.9_3_9_7, 0.9_5_9_9, 0.9_9_0_1, 1.0_0_0_0, 1.0_0_0_0, 0.9_8_8_2, 1.0_0_0_0, 1.0_0_0_0])

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






@slow
@require_torch_gpu
class _lowerCamelCase(						unittest.TestCase   ):
       def 			UpperCamelCase     (					self)       ->   Optional[Any]:




           """simple docstring"""

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




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




           """simple docstring"""

           _lowercase       :							Union[str, Any]      		=		load_image(
               'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
               '/img2img/sketch-mountains-input.jpg')
           _lowercase       :							str      		=		init_image.resize((7_68, 5_12))
           _lowercase       :							Any      		=		load_numpy(
               'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy')

           _lowercase       :							str      		=		'BAAI/AltDiffusion'
           _lowercase       :							Optional[Any]      		=		AltDiffusionImgaImgPipeline.from_pretrained(
               lowerCamelCase,      safety_checker=lowerCamelCase,      )
           pipe.to(lowerCamelCase)
           pipe.set_progress_bar_config(disable=lowerCamelCase)
           pipe.enable_attention_slicing()

           _lowercase       :							int      		=		'A fantasy landscape, trending on artstation'

           _lowercase       :							List[Any]      		=		torch.manual_seed(0)
           _lowercase       :							int      		=		pipe(
               prompt=lowerCamelCase,      image=lowerCamelCase,      strength=0.7_5,      guidance_scale=7.5,      generator=lowerCamelCase,      output_type='np',      )
           _lowercase       :							Union[str, Any]      		=		output.images[0]

           assert image.shape == (5_12, 7_68, 3)
           # img2img is flaky across GPUs even in fp32, so using MAE here
           assert np.abs(expected_image - image).max() < 1E-2


