






import gc
import random
import unittest

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

from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel
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, skip_mps

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()




class     _lowerCAmelCase(	UpperCAmelCase_							,     UpperCAmelCase_							,     unittest.TestCase ):





       """simple docstring"""







       a    :		int									=CycleDiffusionPipeline
       a    :		List[str]									=TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
           '''negative_prompt''',
           '''height''',
           '''width''',
           '''negative_prompt_embeds''',
       }
       a    :		Tuple									=PipelineTesterMixin.required_optional_params - {'''latents'''}
       a    :		List[str]									=TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''source_prompt'''} )
       a    :		Optional[Any]									=IMAGE_TO_IMAGE_IMAGE_PARAMS
       a    :		List[Any]									=IMAGE_TO_IMAGE_IMAGE_PARAMS





       def       _a   ( self							):
         torch.manual_seed(0							)
         UpperCamelCase_: Tuple   				=    UNetaDConditionModel(
             block_out_channels=(3_2, 6_4)  ,      layers_per_block=2  ,      sample_size=3_2  ,      in_channels=4  ,      out_channels=4  ,      down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')  ,      up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')  ,      cross_attention_dim=3_2  ,      )
         UpperCamelCase_: Union[str, Any]   				=    DDIMScheduler(
             beta_start=0.0_0_0_8_5  ,      beta_end=0.0_1_2  ,      beta_schedule='scaled_linear'  ,      num_train_timesteps=1_0_0_0  ,      clip_sample=_lowerCamelCase  ,      set_alpha_to_one=_lowerCamelCase  ,      )
         torch.manual_seed(0							)
         UpperCamelCase_: int   				=    AutoencoderKL(
             block_out_channels=[3_2, 6_4]  ,      in_channels=3  ,      out_channels=3  ,      down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']  ,      up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']  ,      latent_channels=4  ,      )
         torch.manual_seed(0							)
         UpperCamelCase_: str   				=    CLIPTextConfig(
             bos_token_id=0  ,      eos_token_id=2  ,      hidden_size=3_2  ,      intermediate_size=3_7  ,      layer_norm_eps=1e-05  ,      num_attention_heads=4  ,      num_hidden_layers=5  ,      pad_token_id=1  ,      vocab_size=1_0_0_0  ,      )
         UpperCamelCase_: str   				=    CLIPTextModel(_lowerCamelCase							)
         UpperCamelCase_: int   				=    CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'							)

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





       def       _a   ( self  ,      _lowerCamelCase  ,      _lowerCamelCase=0							):
         UpperCamelCase_: Any   				=    floats_tensor((1, 3, 3_2, 3_2)  ,      rng=random.Random(_lowerCamelCase							)							).to(_lowerCamelCase							)
         UpperCamelCase_: Optional[Any]   				=    image / 2 + 0.5
         if str(_lowerCamelCase							).startswith('mps'							):
           UpperCamelCase_: Optional[Any]   				=    torch.manual_seed(_lowerCamelCase							)
         else:
           UpperCamelCase_: Optional[Any]   				=    torch.Generator(device=_lowerCamelCase							).manual_seed(_lowerCamelCase							)
         UpperCamelCase_: List[Any]   				=    {
             'prompt': 'An astronaut riding an elephant',
             'source_prompt': 'An astronaut riding a horse',
             'image': image,
             'generator': generator,
             'num_inference_steps': 2,
             'eta': 0.1,
             'strength': 0.8,
             'guidance_scale': 3,
             'source_guidance_scale': 1,
             'output_type': 'numpy',
         }
         return inputs





       def       _a   ( self							):
         UpperCamelCase_: Optional[Any]   				=    'cpu'  # ensure determinism for the device-dependent torch.Generator

         UpperCamelCase_: Any   				=    self.get_dummy_components()
         UpperCamelCase_: Dict   				=    CycleDiffusionPipeline(**_lowerCamelCase							)
         UpperCamelCase_: List[str]   				=    pipe.to(_lowerCamelCase							)
         pipe.set_progress_bar_config(disable=_lowerCamelCase							)

         UpperCamelCase_: Optional[Any]   				=    self.get_dummy_inputs(_lowerCamelCase							)
         UpperCamelCase_: Optional[Any]   				=    pipe(**_lowerCamelCase							)
         UpperCamelCase_: Optional[Any]   				=    output.images

         UpperCamelCase_: Optional[Any]   				=    images[0, -3:, -3:, -1]

         assert images.shape == (1, 3_2, 3_2, 3)
         UpperCamelCase_: Optional[int]   				=    np.array([0.4_4_5_9, 0.4_9_4_3, 0.4_5_4_4, 0.6_6_4_3, 0.5_4_7_4, 0.4_3_2_7, 0.5_7_0_1, 0.5_9_5_9, 0.5_1_7_9]							)

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





       @unittest.skipIf(torch_device != 'cuda'  ,      'This test requires a GPU'							)
       def       _a   ( self							):
         UpperCamelCase_: Optional[Any]   				=    self.get_dummy_components()
         for name, module in components.items():
           if hasattr(_lowerCamelCase  ,      'half'							):
             UpperCamelCase_: Dict   				=    module.half()
         UpperCamelCase_: int   				=    CycleDiffusionPipeline(**_lowerCamelCase							)
         UpperCamelCase_: Optional[int]   				=    pipe.to(_lowerCamelCase							)
         pipe.set_progress_bar_config(disable=_lowerCamelCase							)

         UpperCamelCase_: Dict   				=    self.get_dummy_inputs(_lowerCamelCase							)
         UpperCamelCase_: str   				=    pipe(**_lowerCamelCase							)
         UpperCamelCase_: str   				=    output.images

         UpperCamelCase_: Optional[int]   				=    images[0, -3:, -3:, -1]

         assert images.shape == (1, 3_2, 3_2, 3)
         UpperCamelCase_: str   				=    np.array([0.3_5_0_6, 0.4_5_4_3, 0.4_4_6, 0.4_5_7_5, 0.5_1_9_5, 0.4_1_5_5, 0.5_2_7_3, 0.5_1_8, 0.4_1_1_6]							)

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





       @skip_mps
       def       _a   ( self							):
         return super().test_save_load_local()





       @unittest.skip('non-deterministic pipeline'							)
       def       _a   ( self							):
         return super().test_inference_batch_single_identical()





       @skip_mps
       def       _a   ( self							):
         return super().test_dict_tuple_outputs_equivalent()





       @skip_mps
       def       _a   ( self							):
         return super().test_save_load_optional_components()





       @skip_mps
       def       _a   ( self							):
         return super().test_attention_slicing_forward_pass()







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





       """simple docstring"""







       def       _a   ( self							):
         # clean up the VRAM after each test
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()





       def       _a   ( self							):
         UpperCamelCase_: Tuple   				=    load_image(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
             '/cycle-diffusion/black_colored_car.png'							)
         UpperCamelCase_: int   				=    load_numpy(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy'							)
         UpperCamelCase_: Optional[int]   				=    init_image.resize((5_1_2, 5_1_2)							)

         UpperCamelCase_: Dict   				=    'CompVis/stable-diffusion-v1-4'
         UpperCamelCase_: int   				=    DDIMScheduler.from_pretrained(_lowerCamelCase  ,      subfolder='scheduler'							)
         UpperCamelCase_: Dict   				=    CycleDiffusionPipeline.from_pretrained(
             _lowerCamelCase  ,      scheduler=_lowerCamelCase  ,      safety_checker=_lowerCamelCase  ,      torch_dtype=torch.floataa  ,      revision='fp16'							)

         pipe.to(_lowerCamelCase							)
         pipe.set_progress_bar_config(disable=_lowerCamelCase							)
         pipe.enable_attention_slicing()

         UpperCamelCase_: Optional[int]   				=    'A black colored car'
         UpperCamelCase_: List[str]   				=    'A blue colored car'

         UpperCamelCase_: List[Any]   				=    torch.manual_seed(0							)
         UpperCamelCase_: Tuple   				=    pipe(
             prompt=_lowerCamelCase  ,      source_prompt=_lowerCamelCase  ,      image=_lowerCamelCase  ,      num_inference_steps=1_0_0  ,      eta=0.1  ,      strength=0.8_5  ,      guidance_scale=3  ,      source_guidance_scale=1  ,      generator=_lowerCamelCase  ,      output_type='np'  ,      )
         UpperCamelCase_: List[str]   				=    output.images

         # the values aren't exactly equal, but the images look the same visually
         assert np.abs(image - expected_image							).max() < 5e-1





       def       _a   ( self							):
         UpperCamelCase_: int   				=    load_image(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
             '/cycle-diffusion/black_colored_car.png'							)
         UpperCamelCase_: Dict   				=    load_numpy(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy'							)
         UpperCamelCase_: int   				=    init_image.resize((5_1_2, 5_1_2)							)

         UpperCamelCase_: Optional[int]   				=    'CompVis/stable-diffusion-v1-4'
         UpperCamelCase_: Dict   				=    DDIMScheduler.from_pretrained(_lowerCamelCase  ,      subfolder='scheduler'							)
         UpperCamelCase_: Optional[Any]   				=    CycleDiffusionPipeline.from_pretrained(_lowerCamelCase  ,      scheduler=_lowerCamelCase  ,      safety_checker=_lowerCamelCase							)

         pipe.to(_lowerCamelCase							)
         pipe.set_progress_bar_config(disable=_lowerCamelCase							)
         pipe.enable_attention_slicing()

         UpperCamelCase_: List[str]   				=    'A black colored car'
         UpperCamelCase_: List[Any]   				=    'A blue colored car'

         UpperCamelCase_: Any   				=    torch.manual_seed(0							)
         UpperCamelCase_: List[str]   				=    pipe(
             prompt=_lowerCamelCase  ,      source_prompt=_lowerCamelCase  ,      image=_lowerCamelCase  ,      num_inference_steps=1_0_0  ,      eta=0.1  ,      strength=0.8_5  ,      guidance_scale=3  ,      source_guidance_scale=1  ,      generator=_lowerCamelCase  ,      output_type='np'  ,      )
         UpperCamelCase_: Optional[Any]   				=    output.images

         assert np.abs(image - expected_image							).max() < 2e-2









import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch


if is_torch_available():
   import torch

   from transformers.activations import gelu_new, gelu_python, get_activation




@require_torch
class     _lowerCAmelCase(	unittest.TestCase ):





       """simple docstring"""







       def       _a   ( self							):
         UpperCamelCase_: Any   				=    torch.tensor([-1_0_0, -1, -0.1, 0, 0.1, 1.0, 1_0_0]							)
         UpperCamelCase_: List[str]   				=    get_activation('gelu'							)
         self.assertTrue(torch.allclose(gelu_python(_lowerCamelCase							)  ,      torch_builtin(_lowerCamelCase							)							)							)
         self.assertFalse(torch.allclose(gelu_python(_lowerCamelCase							)  ,      gelu_new(_lowerCamelCase							)							)							)





       def       _a   ( self							):
         UpperCamelCase_: Optional[Any]   				=    torch.tensor([-1_0_0, -1, -0.1, 0, 0.1, 1.0, 1_0_0]							)
         UpperCamelCase_: Union[str, Any]   				=    get_activation('gelu'							)
         UpperCamelCase_: int   				=    get_activation('gelu_10'							)

         UpperCamelCase_: Union[str, Any]   				=    torch_builtin(_lowerCamelCase							)
         UpperCamelCase_: List[str]   				=    geluaa(_lowerCamelCase							)

         UpperCamelCase_: Dict   				=    torch.where(y_gelu_aa < 1_0.0  ,      1  ,      0							)

         self.assertTrue(torch.max(_lowerCamelCase							).item() == 1_0.0							)
         self.assertTrue(torch.allclose(y_gelu * clipped_mask  ,      y_gelu_aa * clipped_mask							)							)





       def       _a   ( self							):
         get_activation('gelu'							)
         get_activation('gelu_10'							)
         get_activation('gelu_fast'							)
         get_activation('gelu_new'							)
         get_activation('gelu_python'							)
         get_activation('gelu_pytorch_tanh'							)
         get_activation('linear'							)
         get_activation('mish'							)
         get_activation('quick_gelu'							)
         get_activation('relu'							)
         get_activation('sigmoid'							)
         get_activation('silu'							)
         get_activation('swish'							)
         get_activation('tanh'							)
         with self.assertRaises(_lowerCamelCase							):
           get_activation('bogus'							)
         with self.assertRaises(_lowerCamelCase							):
           get_activation(_lowerCamelCase							)





       def       _a   ( self							):
         UpperCamelCase_: str   				=    get_activation('gelu'							)
         UpperCamelCase_: str   				=    1
         UpperCamelCase_: int   				=    get_activation('gelu'							)
         self.assertEqual(acta.a  ,      1							)
         with self.assertRaises(_lowerCamelCase							):
           UpperCamelCase_: Tuple   				=    acta.a