






"""simple docstring"""


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 						snake_case  (  UpperCAmelCase       ,			UpperCAmelCase       ,			unittest.TestCase	):
    __magic_name__   					=					CycleDiffusionPipeline
    __magic_name__   					=					TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
        '''negative_prompt''',
        '''height''',
        '''width''',
        '''negative_prompt_embeds''',
    }
    __magic_name__   					=					PipelineTesterMixin.required_optional_params - {'''latents'''}
    __magic_name__   					=					TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''source_prompt'''}	)
    __magic_name__   					=					IMAGE_TO_IMAGE_IMAGE_PARAMS
    __magic_name__   					=					IMAGE_TO_IMAGE_IMAGE_PARAMS





    def     lowerCamelCase__				(							self     : Tuple      ):


      '''simple docstring'''




      torch.manual_seed(0      )
      a					:      List[Any]    =       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    ,		)
      a					:      str    =       DDIMScheduler(
          beta_start=0.0_00_85    ,		beta_end=0.0_12    ,		beta_schedule='scaled_linear'    ,		num_train_timesteps=1_0_0_0    ,		clip_sample=_lowerCAmelCase    ,		set_alpha_to_one=_lowerCAmelCase    ,		)
      torch.manual_seed(0      )
      a					:      str    =       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      )
      a					:      Optional[int]    =       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    ,		)
      a					:      str    =       CLIPTextModel(_lowerCAmelCase      )
      a					:      Optional[Any]    =       CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'      )

      a					:      Optional[int]    =       {
          'unet': unet,
          'scheduler': scheduler,
          'vae': vae,
          'text_encoder': text_encoder,
          'tokenizer': tokenizer,
          'safety_checker': None,
          'feature_extractor': None,
      }
      return components





    def     lowerCamelCase__				(							self     : List[Any]    ,		A     : Tuple    ,		A     : Union[str, Any]=0      ):


      '''simple docstring'''




      a					:      int    =       floats_tensor((1, 3, 3_2, 3_2)    ,		rng=random.Random(_lowerCAmelCase      )      ).to(_lowerCAmelCase      )
      a					:      str    =       image / 2 + 0.5
      if str(_lowerCAmelCase      ).startswith('mps'      ):
        a					:      Dict    =       torch.manual_seed(_lowerCAmelCase      )
      else:
        a					:      Any    =       torch.Generator(device=_lowerCAmelCase      ).manual_seed(_lowerCAmelCase      )
      a					:      List[str]    =       {
          '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     : Any      ):


      '''simple docstring'''




      a					:      Optional[int]    =       'cpu'  # ensure determinism for the device-dependent torch.Generator

      a					:      str    =       self.get_dummy_components()
      a					:      Any    =       CycleDiffusionPipeline(**_lowerCAmelCase      )
      a					:      Any    =       pipe.to(_lowerCAmelCase      )
      pipe.set_progress_bar_config(disable=_lowerCAmelCase      )

      a					:      Union[str, Any]    =       self.get_dummy_inputs(_lowerCAmelCase      )
      a					:      Dict    =       pipe(**_lowerCAmelCase      )
      a					:      List[str]    =       output.images

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

      assert images.shape == (1, 3_2, 3_2, 3)
      a					:      Optional[Any]    =       np.array([0.44_59, 0.49_43, 0.45_44, 0.66_43, 0.54_74, 0.43_27, 0.57_01, 0.59_59, 0.51_79]      )

      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[str]      ):


      '''simple docstring'''




      a					:      Optional[Any]    =       self.get_dummy_components()
      for name, module in components.items():
        if hasattr(_lowerCAmelCase    ,		'half'      ):
          a					:      Dict    =       module.half()
      a					:      List[str]    =       CycleDiffusionPipeline(**_lowerCAmelCase      )
      a					:      List[str]    =       pipe.to(_lowerCAmelCase      )
      pipe.set_progress_bar_config(disable=_lowerCAmelCase      )

      a					:      Union[str, Any]    =       self.get_dummy_inputs(_lowerCAmelCase      )
      a					:      int    =       pipe(**_lowerCAmelCase      )
      a					:      Union[str, Any]    =       output.images

      a					:      str    =       images[0, -3:, -3:, -1]

      assert images.shape == (1, 3_2, 3_2, 3)
      a					:      Optional[int]    =       np.array([0.35_06, 0.45_43, 0.4_46, 0.45_75, 0.51_95, 0.41_55, 0.52_73, 0.5_18, 0.41_16]      )

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





    @skip_mps
    def     lowerCamelCase__				(							self     : Optional[int]      ):


      '''simple docstring'''




      return super().test_save_load_local()





    @unittest.skip('non-deterministic pipeline'      )
    def     lowerCamelCase__				(							self     : List[str]      ):


      '''simple docstring'''




      return super().test_inference_batch_single_identical()





    @skip_mps
    def     lowerCamelCase__				(							self     : int      ):


      '''simple docstring'''




      return super().test_dict_tuple_outputs_equivalent()





    @skip_mps
    def     lowerCamelCase__				(							self     : Optional[Any]      ):


      '''simple docstring'''




      return super().test_save_load_optional_components()





    @skip_mps
    def     lowerCamelCase__				(							self     : Any      ):


      '''simple docstring'''




      return super().test_attention_slicing_forward_pass()






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





    def     lowerCamelCase__				(							self     : Optional[Any]      ):


      '''simple docstring'''




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





    def     lowerCamelCase__				(							self     : Optional[Any]      ):


      '''simple docstring'''




      a					:      List[str]    =       load_image(
          'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
          '/cycle-diffusion/black_colored_car.png'      )
      a					:      Dict    =       load_numpy(
          'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy'      )
      a					:      int    =       init_image.resize((5_1_2, 5_1_2)      )

      a					:      Union[str, Any]    =       'CompVis/stable-diffusion-v1-4'
      a					:      Optional[int]    =       DDIMScheduler.from_pretrained(_lowerCAmelCase    ,		subfolder='scheduler'      )
      a					:      List[str]    =       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()

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

      a					:      int    =       torch.manual_seed(0      )
      a					:      List[Any]    =       pipe(
          prompt=_lowerCAmelCase    ,		source_prompt=_lowerCAmelCase    ,		image=_lowerCAmelCase    ,		num_inference_steps=1_0_0    ,		eta=0.1    ,		strength=0.85    ,		guidance_scale=3    ,		source_guidance_scale=1    ,		generator=_lowerCAmelCase    ,		output_type='np'    ,		)
      a					:      Dict    =       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     : Any      ):


      '''simple docstring'''




      a					:      Union[str, Any]    =       load_image(
          'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
          '/cycle-diffusion/black_colored_car.png'      )
      a					:      Optional[int]    =       load_numpy(
          'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy'      )
      a					:      List[str]    =       init_image.resize((5_1_2, 5_1_2)      )

      a					:      Dict    =       'CompVis/stable-diffusion-v1-4'
      a					:      List[str]    =       DDIMScheduler.from_pretrained(_lowerCAmelCase    ,		subfolder='scheduler'      )
      a					:      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()

      a					:      Optional[Any]    =       'A black colored car'
      a					:      Dict    =       'A blue colored car'

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

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












"""simple docstring"""


import logging
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional, Union

from .generation.configuration_utils import GenerationConfig
from .training_args import TrainingArguments
from .utils import add_start_docstrings


_UpperCamelCase    :   Dict   			=						logging.getLogger(__name__)






@dataclass
@add_start_docstrings(TrainingArguments.__doc__	)
class 						snake_case  (  UpperCAmelCase	):
    __magic_name__   					=					field(default=UpperCAmelCase       ,			metadata={'''help''': '''Whether to use SortishSampler or not.'''}	)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={'''help''': '''Whether to use generate to calculate generative metrics (ROUGE, BLEU).'''}	)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={
            '''help''': (
                '''The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default '''
                '''to the `max_length` value of the model configuration.'''
            )
        }       ,			)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={
            '''help''': (
                '''The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default '''
                '''to the `num_beams` value of the model configuration.'''
            )
        }       ,			)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={
            '''help''': '''Model id, file path or url pointing to a GenerationConfig json file, to use during prediction.'''
        }       ,			)





    def     lowerCamelCase__				(							self     : Optional[int]      ):


      '''simple docstring'''




      a					:      List[Any]    =       super().to_dict()
      for k, v in d.items():
        if isinstance(A    ,		A      ):
          a					:      str    =       v.to_dict()
      return d




