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       UpperCAmelCase  (						A__   ,						A__   ,						unittest.TestCase ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   CycleDiffusionPipeline
       SCREAMING_SNAKE_CASE 		=   TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
           'negative_prompt',
           'height',
           'width',
           'negative_prompt_embeds',
       }
       SCREAMING_SNAKE_CASE 		=   PipelineTesterMixin.required_optional_params - {'latents'}
       SCREAMING_SNAKE_CASE 		=   TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"source_prompt"} )
       SCREAMING_SNAKE_CASE 		=   IMAGE_TO_IMAGE_IMAGE_PARAMS
       SCREAMING_SNAKE_CASE 		=   IMAGE_TO_IMAGE_IMAGE_PARAMS

       def _lowerCAmelCase(						self			)  ->  int:
        torch.manual_seed(0			)
        lowercase__    :   List[Any]						= UNetaDConditionModel(
            block_out_channels=(32, 64)     ,       layers_per_block=2     ,       sample_size=32     ,       in_channels=4     ,       out_channels=4     ,       down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')     ,       up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')     ,       cross_attention_dim=32     ,       )
        lowercase__    :   Tuple						= DDIMScheduler(
            beta_start=0.0_0_0_8_5     ,       beta_end=0.0_1_2     ,       beta_schedule='''scaled_linear'''     ,       num_train_timesteps=1000     ,       clip_sample=lowerCamelCase__     ,       set_alpha_to_one=lowerCamelCase__     ,       )
        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     ,       )
        torch.manual_seed(0			)
        lowercase__    :   Optional[int]						= CLIPTextConfig(
            bos_token_id=0     ,       eos_token_id=2     ,       hidden_size=32     ,       intermediate_size=37     ,       layer_norm_eps=1E-05     ,       num_attention_heads=4     ,       num_hidden_layers=5     ,       pad_token_id=1     ,       vocab_size=1000     ,       )
        lowercase__    :   Dict						= CLIPTextModel(lowerCamelCase__			)
        lowercase__    :   List[str]						= CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''			)

        lowercase__    :   Union[str, Any]						= {
            '''unet''': unet,
            '''scheduler''': scheduler,
            '''vae''': vae,
            '''text_encoder''': text_encoder,
            '''tokenizer''': tokenizer,
            '''safety_checker''': None,
            '''feature_extractor''': None,
        }
        return components

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase=0			)  ->  Union[str, Any]:
        lowercase__    :   Union[str, Any]						= floats_tensor((1, 3, 32, 32)     ,       rng=random.Random(lowerCamelCase__			)			).to(lowerCamelCase__			)
        lowercase__    :   Tuple						= image / 2 + 0.5
        if str(lowerCamelCase__			).startswith('''mps'''			):
         lowercase__    :   Optional[Any]						= torch.manual_seed(lowerCamelCase__			)
        else:
         lowercase__    :   str						= torch.Generator(device=lowerCamelCase__			).manual_seed(lowerCamelCase__			)
        lowercase__    :   Optional[int]						= {
            '''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 _lowerCAmelCase(						self			)  ->  Dict:
        lowercase__    :   Any						= '''cpu'''  # ensure determinism for the device-dependent torch.Generator

        lowercase__    :   List[Any]						= self.get_dummy_components()
        lowercase__    :   Union[str, Any]						= CycleDiffusionPipeline(**lowerCamelCase__			)
        lowercase__    :   List[Any]						= pipe.to(lowerCamelCase__			)
        pipe.set_progress_bar_config(disable=lowerCamelCase__			)

        lowercase__    :   List[Any]						= self.get_dummy_inputs(lowerCamelCase__			)
        lowercase__    :   Union[str, Any]						= pipe(**lowerCamelCase__			)
        lowercase__    :   int						= output.images

        lowercase__    :   Union[str, Any]						= images[0, -3:, -3:, -1]

        assert images.shape == (1, 32, 32, 3)
        lowercase__    :   List[str]						= 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 _lowerCAmelCase(						self			)  ->  List[Any]:
        lowercase__    :   List[str]						= self.get_dummy_components()
        for name, module in components.items():
         if hasattr(lowerCamelCase__     ,       '''half'''			):
          lowercase__    :   int						= module.half()
        lowercase__    :   Optional[int]						= CycleDiffusionPipeline(**lowerCamelCase__			)
        lowercase__    :   Optional[Any]						= pipe.to(lowerCamelCase__			)
        pipe.set_progress_bar_config(disable=lowerCamelCase__			)

        lowercase__    :   Dict						= self.get_dummy_inputs(lowerCamelCase__			)
        lowercase__    :   List[str]						= pipe(**lowerCamelCase__			)
        lowercase__    :   List[Any]						= output.images

        lowercase__    :   Tuple						= images[0, -3:, -3:, -1]

        assert images.shape == (1, 32, 32, 3)
        lowercase__    :   Union[str, Any]						= 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 _lowerCAmelCase(						self			)  ->  Any:
        return super().test_save_load_local()

       @unittest.skip('''non-deterministic pipeline'''			)
       def _lowerCAmelCase(						self			)  ->  List[str]:
        return super().test_inference_batch_single_identical()

       @skip_mps
       def _lowerCAmelCase(						self			)  ->  Optional[Any]:
        return super().test_dict_tuple_outputs_equivalent()

       @skip_mps
       def _lowerCAmelCase(						self			)  ->  int:
        return super().test_save_load_optional_components()


       @skip_mps
       def _lowerCAmelCase(						self			)  ->  Dict:
        return super().test_attention_slicing_forward_pass()



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





       '''simple docstring'''



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

       def _lowerCAmelCase(						self			)  ->  Union[str, Any]:
        lowercase__    :   Union[str, Any]						= load_image(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
            '''/cycle-diffusion/black_colored_car.png'''			)
        lowercase__    :   str						= load_numpy(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy'''			)
        lowercase__    :   int						= init_image.resize((512, 512)			)

        lowercase__    :   List[Any]						= '''CompVis/stable-diffusion-v1-4'''
        lowercase__    :   Tuple						= DDIMScheduler.from_pretrained(lowerCamelCase__     ,       subfolder='''scheduler'''			)
        lowercase__    :   Tuple						= 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()

        lowercase__    :   Any						= '''A black colored car'''
        lowercase__    :   Optional[int]						= '''A blue colored car'''

        lowercase__    :   Tuple						= torch.manual_seed(0			)
        lowercase__    :   Optional[int]						= pipe(
            prompt=lowerCamelCase__     ,       source_prompt=lowerCamelCase__     ,       image=lowerCamelCase__     ,       num_inference_steps=100     ,       eta=0.1     ,       strength=0.8_5     ,       guidance_scale=3     ,       source_guidance_scale=1     ,       generator=lowerCamelCase__     ,       output_type='''np'''     ,       )
        lowercase__    :   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 _lowerCAmelCase(						self			)  ->  Optional[Any]:
        lowercase__    :   int						= load_image(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
            '''/cycle-diffusion/black_colored_car.png'''			)
        lowercase__    :   List[Any]						= load_numpy(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy'''			)
        lowercase__    :   int						= init_image.resize((512, 512)			)

        lowercase__    :   List[Any]						= '''CompVis/stable-diffusion-v1-4'''
        lowercase__    :   Dict						= DDIMScheduler.from_pretrained(lowerCamelCase__     ,       subfolder='''scheduler'''			)
        lowercase__    :   Tuple						= CycleDiffusionPipeline.from_pretrained(lowerCamelCase__     ,       scheduler=lowerCamelCase__     ,       safety_checker=lowerCamelCase__			)

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

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

        lowercase__    :   str						= torch.manual_seed(0			)
        lowercase__    :   Tuple						= pipe(
            prompt=lowerCamelCase__     ,       source_prompt=lowerCamelCase__     ,       image=lowerCamelCase__     ,       num_inference_steps=100     ,       eta=0.1     ,       strength=0.8_5     ,       guidance_scale=3     ,       source_guidance_scale=1     ,       generator=lowerCamelCase__     ,       output_type='''np'''     ,       )
        lowercase__    :   int						= output.images

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


'''simple docstring'''

import re
from typing import Callable, List, Optional, Union

import tensorflow as tf


try:
  from tensorflow.keras.optimizers.legacy import Adam
except ImportError:
  from tensorflow.keras.optimizers import Adam



class       UpperCAmelCase  (						tf.keras.optimizers.schedules.LearningRateSchedule ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase = 1.0     ,       __lowerCAmelCase = None     ,       )  ->  Union[str, Any]:
        super().__init__()
        lowercase__    :   Any						= initial_learning_rate
        lowercase__    :   str						= warmup_steps
        lowercase__    :   Dict						= power
        lowercase__    :   int						= decay_schedule_fn
        lowercase__    :   Dict						= name

       def __call__(						self     ,       __lowerCAmelCase			)  ->  int:
        with tf.name_scope(self.name or '''WarmUp'''			) as name:
         # Implements polynomial warmup. i.e., if global_step < warmup_steps, the
         # learning rate will be `global_step/num_warmup_steps * init_lr`.
         lowercase__    :   Union[str, Any]						= tf.cast(__lowerCAmelCase     ,       tf.floataa			)
         lowercase__    :   Optional[int]						= tf.cast(self.warmup_steps     ,       tf.floataa			)
         lowercase__    :   Dict						= global_step_float / warmup_steps_float
         lowercase__    :   Dict						= self.initial_learning_rate * tf.math.pow(__lowerCAmelCase     ,       self.power			)
         return tf.cond(
             global_step_float < warmup_steps_float     ,       lambda: warmup_learning_rate     ,       lambda: self.decay_schedule_fn(step - self.warmup_steps			)     ,       name=__lowerCAmelCase     ,       )


       def _lowerCAmelCase(						self			)  ->  List[str]:
        return {
            "initial_learning_rate": self.initial_learning_rate,
            "decay_schedule_fn": self.decay_schedule_fn,
            "warmup_steps": self.warmup_steps,
            "power": self.power,
            "name": self.name,
        }


def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase = 0.0		,					UpperCAmelCase = 0.9		,					UpperCAmelCase = 0.9_9_9		,					UpperCAmelCase = 1E-8		,					UpperCAmelCase = None		,					UpperCAmelCase = None		,					UpperCAmelCase = 0.0		,					UpperCAmelCase = 1.0		,					UpperCAmelCase = None		,					):
 lowercase__    :   List[Any]						= tf.keras.optimizers.schedules.PolynomialDecay(
     initial_learning_rate=UpperCAmelCase		,					decay_steps=num_train_steps - num_warmup_steps		,					end_learning_rate=init_lr * min_lr_ratio		,					power=UpperCAmelCase		,					)
 if num_warmup_steps:
  lowercase__    :   Optional[Any]						= WarmUp(
      initial_learning_rate=UpperCAmelCase		,					decay_schedule_fn=UpperCAmelCase		,					warmup_steps=UpperCAmelCase		,					)
 if weight_decay_rate > 0.0:
  lowercase__    :   str						= AdamWeightDecay(
      learning_rate=UpperCAmelCase		,					weight_decay_rate=UpperCAmelCase		,					beta_a=UpperCAmelCase		,					beta_a=UpperCAmelCase		,					epsilon=UpperCAmelCase		,					clipnorm=UpperCAmelCase		,					global_clipnorm=UpperCAmelCase		,					exclude_from_weight_decay=['''LayerNorm''', '''layer_norm''', '''bias''']		,					include_in_weight_decay=UpperCAmelCase		,					)
 else:
  lowercase__    :   Any						= tf.keras.optimizers.Adam(
      learning_rate=UpperCAmelCase		,					beta_a=UpperCAmelCase		,					beta_a=UpperCAmelCase		,					epsilon=UpperCAmelCase		,					clipnorm=UpperCAmelCase		,					global_clipnorm=UpperCAmelCase		,					)
 # We return the optimizer and the LR scheduler in order to better track the
 # evolution of the LR independently of the optimizer.
 return optimizer, lr_schedule



class       UpperCAmelCase  (						a__ ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase = 0.0_0_1     ,       __lowerCAmelCase = 0.9     ,       __lowerCAmelCase = 0.9_9_9     ,       __lowerCAmelCase = 1E-7     ,       __lowerCAmelCase = False     ,       __lowerCAmelCase = 0.0     ,       __lowerCAmelCase = None     ,       __lowerCAmelCase = None     ,       __lowerCAmelCase = "AdamWeightDecay"     ,       **__lowerCAmelCase     ,       )  ->  str:
        super().__init__(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       **__lowerCAmelCase			)
        lowercase__    :   int						= weight_decay_rate
        lowercase__    :   Dict						= include_in_weight_decay
        lowercase__    :   List[str]						= exclude_from_weight_decay

       @classmethod
       def _lowerCAmelCase(						cls     ,       __lowerCAmelCase			)  ->  str:
        lowercase__    :   int						= {'''WarmUp''': WarmUp}
        return super(__lowerCAmelCase     ,       cls			).from_config(__lowerCAmelCase     ,       custom_objects=__lowerCAmelCase			)

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)  ->  List[str]:
        super(__lowerCAmelCase     ,       self			)._prepare_local(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)
        lowercase__    :   Any						= tf.constant(
            self.weight_decay_rate     ,       name='''adam_weight_decay_rate'''			)

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)  ->  Tuple:
        lowercase__    :   str						= self._do_use_weight_decay(var.name			)
        if do_decay:
         return var.assign_sub(
             learning_rate * var * apply_state[(var.device, var.dtype.base_dtype)]['''weight_decay_rate''']     ,       use_locking=self._use_locking     ,       )
        return tf.no_op()

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase=None     ,       **__lowerCAmelCase			)  ->  List[Any]:
        lowercase__			,							lowercase__    :   Any						= list(zip(*__lowerCAmelCase			)			)
        return super(__lowerCAmelCase     ,       self			).apply_gradients(zip(__lowerCAmelCase     ,       __lowerCAmelCase			)     ,       name=__lowerCAmelCase     ,       **__lowerCAmelCase			)

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)  ->  Optional[int]:
        if apply_state is None:
         return self._decayed_lr_t[var_dtype], {}

        lowercase__    :   Union[str, Any]						= apply_state or {}
        lowercase__    :   Optional[Any]						= apply_state.get((var_device, var_dtype)			)
        if coefficients is None:
         lowercase__    :   Union[str, Any]						= self._fallback_apply_state(__lowerCAmelCase     ,       __lowerCAmelCase			)
         lowercase__    :   Optional[int]						= coefficients

        return coefficients["lr_t"], {"apply_state": apply_state}

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase=None			)  ->  Any:
        lowercase__			,							lowercase__    :   Dict						= self._get_lr(var.device     ,       var.dtype.base_dtype     ,       __lowerCAmelCase			)
        lowercase__    :   List[str]						= self._decay_weights_op(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)
        with tf.control_dependencies([decay]			):
         return super(__lowerCAmelCase     ,       self			)._resource_apply_dense(__lowerCAmelCase     ,       __lowerCAmelCase     ,       **__lowerCAmelCase			)

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase=None			)  ->  List[str]:
        lowercase__			,							lowercase__    :   List[Any]						= self._get_lr(var.device     ,       var.dtype.base_dtype     ,       __lowerCAmelCase			)
        lowercase__    :   Union[str, Any]						= self._decay_weights_op(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)
        with tf.control_dependencies([decay]			):
         return super(__lowerCAmelCase     ,       self			)._resource_apply_sparse(__lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       **__lowerCAmelCase			)

       def _lowerCAmelCase(						self			)  ->  List[str]:
        lowercase__    :   Optional[Any]						= super().get_config()
        config.update({'''weight_decay_rate''': self.weight_decay_rate}			)
        return config


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  List[Any]:
        if self.weight_decay_rate == 0:
         return False

        if self._include_in_weight_decay:
         for r in self._include_in_weight_decay:
          if re.search(__lowerCAmelCase     ,       __lowerCAmelCase			) is not None:
           return True

        if self._exclude_from_weight_decay:
         for r in self._exclude_from_weight_decay:
          if re.search(__lowerCAmelCase     ,       __lowerCAmelCase			) is not None:
           return False
        return True



class       UpperCAmelCase  (						a__ ):





       '''simple docstring'''



       def __init__(						self			)  ->  List[Any]:
        lowercase__    :   List[str]						= []
        lowercase__    :   Optional[int]						= None

       @property
       def _lowerCAmelCase(						self			)  ->  Optional[Any]:
        if self._accum_steps is None:
         lowercase__    :   int						= tf.Variable(
             tf.constant(0     ,       dtype=tf.intaa			)     ,       trainable=__lowerCAmelCase     ,       synchronization=tf.VariableSynchronization.ON_READ     ,       aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA     ,       )

        return self._accum_steps.value()

       @property
       def _lowerCAmelCase(						self			)  ->  Union[str, Any]:
        if not self._gradients:
         raise ValueError('''The accumulator should be called first to initialize the gradients'''			)
        return [gradient.value() if gradient is not None else gradient for gradient in self._gradients]

       def __call__(						self     ,       __lowerCAmelCase			)  ->  Optional[Any]:
        if not self._gradients:
         lowercase__    :   str						= self.step  # Create the step variable.
         self._gradients.extend(
             [
                 tf.Variable(
                     tf.zeros_like(__lowerCAmelCase			)     ,       trainable=__lowerCAmelCase     ,       synchronization=tf.VariableSynchronization.ON_READ     ,       aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA     ,       )
                 if gradient is not None
                 else gradient
                 for gradient in gradients
             ]			)
        if len(__lowerCAmelCase			) != len(self._gradients			):
         raise ValueError(F"""Expected {len(self._gradients			)} gradients, but got {len(__lowerCAmelCase			)}"""			)

        for accum_gradient, gradient in zip(self._gradients     ,       __lowerCAmelCase			):
         if accum_gradient is not None and gradient is not None:
          accum_gradient.assign_add(__lowerCAmelCase			)

        self._accum_steps.assign_add(1			)


       def _lowerCAmelCase(						self			)  ->  Optional[Any]:
        if not self._gradients:
         return
        self._accum_steps.assign(0			)
        for gradient in self._gradients:
         if gradient is not None:
          gradient.assign(tf.zeros_like(__lowerCAmelCase			)			)

