
"""simple docstring"""

import math
from collections import defaultdict
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import randn_tensor
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput






def 				A		(							snake_case :List[Any]							,   snake_case :str=0.999							,   snake_case :Any="cosine"							,   ) ->      Dict:
 if alpha_transform_type == "cosine":

  def alpha_bar_fn(snake_case :List[str]						):
   return math.cos((t + 0.008) / 1.008 * math.pi / 2						) ** 2

 elif alpha_transform_type == "exp":

  def alpha_bar_fn(snake_case :Any						):
   return math.exp(t * -12.0						)

 else:
  raise ValueError(f'Unsupported alpha_tranform_type: {alpha_transform_type}'						)

 __UpperCamelCase							    =			[]
 for i in range(_lowerCamelCase						):
  __UpperCamelCase							    =			i / num_diffusion_timesteps
  __UpperCamelCase							    =			(i + 1) / num_diffusion_timesteps
  betas.append(min(1 - alpha_bar_fn(_lowerCamelCase						) / alpha_bar_fn(_lowerCamelCase						)							,   _lowerCamelCase						)						)
 return torch.tensor(_lowerCamelCase							,   dtype=torch.floataa						)





class __lowerCAmelCase						( snake_case_     ,    snake_case_     ):
     lowercase		  =		[e.name for e in KarrasDiffusionSchedulers]
     lowercase		  =		2





     @register_to_config
     def __init__(      self      ,	__UpperCAmelCase = 1000      ,	__UpperCAmelCase = 0.0_0_0_8_5      ,	__UpperCAmelCase = 0.0_1_2      ,	__UpperCAmelCase = "linear"      ,	__UpperCAmelCase = None      ,	__UpperCAmelCase = "epsilon"      ,	__UpperCAmelCase = "linspace"      ,	__UpperCAmelCase = 0      ,	):

      '''simple docstring'''




      if trained_betas is not None:
       __UpperCamelCase							    =			torch.tensor(lowerCamelCase_      ,	dtype=torch.floataa )
      elif beta_schedule == "linear":
       __UpperCamelCase							    =			torch.linspace(lowerCamelCase_      ,	lowerCamelCase_      ,	lowerCamelCase_      ,	dtype=torch.floataa )
      elif beta_schedule == "scaled_linear":
       # this schedule is very specific to the latent diffusion model.
       __UpperCamelCase							    =			(
           torch.linspace(beta_start**0.5      ,	beta_end**0.5      ,	lowerCamelCase_      ,	dtype=torch.floataa ) ** 2
       )
      elif beta_schedule == "squaredcos_cap_v2":
       # Glide cosine schedule
       __UpperCamelCase							    =			betas_for_alpha_bar(lowerCamelCase_ )
      else:
       raise NotImplementedError(F'{beta_schedule} does is not implemented for {self.__class__}' )

      __UpperCamelCase							    =			1.0 - self.betas
      __UpperCamelCase							    =			torch.cumprod(self.alphas      ,	dim=0 )

      #  set all values
      self.set_timesteps(lowerCamelCase_      ,	lowerCamelCase_      ,	lowerCamelCase_ )





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase=None ):

      '''simple docstring'''




      if schedule_timesteps is None:
       __UpperCamelCase							    =			self.timesteps

      __UpperCamelCase							    =			(schedule_timesteps == timestep).nonzero()

      # The sigma index that is taken for the **very** first `step`
      # is always the second index (or the last index if there is only 1)
      # This way we can ensure we don't accidentally skip a sigma in
      # case we start in the middle of the denoising schedule (e.g. for image-to-image)
      if len(self._index_counter ) == 0:
       __UpperCamelCase							    =			1 if len(lowerCamelCase_ ) > 1 else 0
      else:
       __UpperCamelCase							    =			timestep.cpu().item() if torch.is_tensor(lowerCamelCase_ ) else timestep
       __UpperCamelCase							    =			self._index_counter[timestep_int]

      return indices[pos].item()





     @property
     def 		UpperCAmelCase   (      self ):

      '''simple docstring'''




      if self.config.timestep_spacing in ["linspace", "trailing"]:
       return self.sigmas.max()

      return (self.sigmas.max() ** 2 + 1) ** 0.5





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	):

      '''simple docstring'''




      __UpperCamelCase							    =			self.index_for_timestep(lowerCamelCase_ )

      if self.state_in_first_order:
       __UpperCamelCase							    =			self.sigmas[step_index]
      else:
       __UpperCamelCase							    =			self.sigmas_interpol[step_index - 1]

      __UpperCamelCase							    =			sample / ((sigma**2 + 1) ** 0.5)
      return sample





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase = None      ,	__UpperCAmelCase = None      ,	):

      '''simple docstring'''




      __UpperCamelCase							    =			num_inference_steps

      __UpperCamelCase							    =			num_train_timesteps or self.config.num_train_timesteps

      # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
      if self.config.timestep_spacing == "linspace":
       __UpperCamelCase							    =			np.linspace(0      ,	num_train_timesteps - 1      ,	lowerCamelCase_      ,	dtype=lowerCamelCase_ )[::-1].copy()
      elif self.config.timestep_spacing == "leading":
       __UpperCamelCase							    =			num_train_timesteps // self.num_inference_steps
       # creates integer timesteps by multiplying by ratio
       # casting to int to avoid issues when num_inference_step is power of 3
       __UpperCamelCase							    =			(np.arange(0      ,	lowerCamelCase_ ) * step_ratio).round()[::-1].copy().astype(lowerCamelCase_ )
       timesteps += self.config.steps_offset
      elif self.config.timestep_spacing == "trailing":
       __UpperCamelCase							    =			num_train_timesteps / self.num_inference_steps
       # creates integer timesteps by multiplying by ratio
       # casting to int to avoid issues when num_inference_step is power of 3
       __UpperCamelCase							    =			(np.arange(lowerCamelCase_      ,	0      ,	-step_ratio )).round().copy().astype(lowerCamelCase_ )
       timesteps -= 1
      else:
       raise ValueError(
           F'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' )

      __UpperCamelCase							    =			np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 )
      __UpperCamelCase							    =			torch.from_numpy(np.log(lowerCamelCase_ ) ).to(lowerCamelCase_ )

      __UpperCamelCase							    =			np.interp(lowerCamelCase_      ,	np.arange(0      ,	len(lowerCamelCase_ ) )      ,	lowerCamelCase_ )
      __UpperCamelCase							    =			np.concatenate([sigmas, [0.0]] ).astype(np.floataa )
      __UpperCamelCase							    =			torch.from_numpy(lowerCamelCase_ ).to(device=lowerCamelCase_ )

      # compute up and down sigmas
      __UpperCamelCase							    =			sigmas.roll(-1 )
      __UpperCamelCase							    =			0.0
      __UpperCamelCase							    =			(sigmas_next**2 * (sigmas**2 - sigmas_next**2) / sigmas**2) ** 0.5
      __UpperCamelCase							    =			(sigmas_next**2 - sigmas_up**2) ** 0.5
      __UpperCamelCase							    =			0.0

      # compute interpolated sigmas
      __UpperCamelCase							    =			sigmas.log().lerp(sigmas_down.log()      ,	0.5 ).exp()
      __UpperCamelCase							    =			0.0

      # set sigmas
      __UpperCamelCase							    =			torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] )
      __UpperCamelCase							    =			torch.cat(
          [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] )
      __UpperCamelCase							    =			torch.cat([sigmas_up[:1], sigmas_up[1:].repeat_interleave(2 ), sigmas_up[-1:]] )
      __UpperCamelCase							    =			torch.cat([sigmas_down[:1], sigmas_down[1:].repeat_interleave(2 ), sigmas_down[-1:]] )

      if str(lowerCamelCase_ ).startswith('mps' ):
       # mps does not support float64
       __UpperCamelCase							    =			torch.from_numpy(lowerCamelCase_ ).to(lowerCamelCase_      ,	dtype=torch.floataa )
      else:
       __UpperCamelCase							    =			torch.from_numpy(lowerCamelCase_ ).to(lowerCamelCase_ )

      __UpperCamelCase							    =			self.sigma_to_t(lowerCamelCase_ ).to(lowerCamelCase_      ,	dtype=timesteps.dtype )
      __UpperCamelCase							    =			torch.stack((timesteps_interpol[:-2, None], timesteps[1:, None])      ,	dim=-1 ).flatten()

      __UpperCamelCase							    =			torch.cat([timesteps[:1], interleaved_timesteps] )

      __UpperCamelCase							    =			None

      # for exp beta schedules, such as the one for `pipeline_shap_e.py`
      # we need an index counter
      __UpperCamelCase							    =			defaultdict(lowerCamelCase_ )





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase ):

      '''simple docstring'''




      __UpperCamelCase							    =			sigma.log()

      # get distribution
      __UpperCamelCase							    =			log_sigma - self.log_sigmas[:, None]

      # get sigmas range
      __UpperCamelCase							    =			dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 )
      __UpperCamelCase							    =			low_idx + 1

      __UpperCamelCase							    =			self.log_sigmas[low_idx]
      __UpperCamelCase							    =			self.log_sigmas[high_idx]

      # interpolate sigmas
      __UpperCamelCase							    =			(low - log_sigma) / (low - high)
      __UpperCamelCase							    =			w.clamp(0      ,	1 )

      # transform interpolation to time range
      __UpperCamelCase							    =			(1 - w) * low_idx + w * high_idx
      __UpperCamelCase							    =			t.view(sigma.shape )
      return t





     @property
     def 		UpperCAmelCase   (      self ):

      '''simple docstring'''




      return self.sample is None





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	__UpperCAmelCase = None      ,	__UpperCAmelCase = True      ,	):

      '''simple docstring'''




      __UpperCamelCase							    =			self.index_for_timestep(lowerCamelCase_ )

      # advance index counter by 1
      __UpperCamelCase							    =			timestep.cpu().item() if torch.is_tensor(lowerCamelCase_ ) else timestep
      self._index_counter[timestep_int] += 1

      if self.state_in_first_order:
       __UpperCamelCase							    =			self.sigmas[step_index]
       __UpperCamelCase							    =			self.sigmas_interpol[step_index]
       __UpperCamelCase							    =			self.sigmas_up[step_index]
       __UpperCamelCase							    =			self.sigmas_down[step_index - 1]
      else:
       # 2nd order / KPDM2's method
       __UpperCamelCase							    =			self.sigmas[step_index - 1]
       __UpperCamelCase							    =			self.sigmas_interpol[step_index - 1]
       __UpperCamelCase							    =			self.sigmas_up[step_index - 1]
       __UpperCamelCase							    =			self.sigmas_down[step_index - 1]

      # currently only gamma=0 is supported. This usually works best anyways.
      # We can support gamma in the future but then need to scale the timestep before
      # passing it to the model which requires a change in API
      __UpperCamelCase							    =			0
      __UpperCamelCase							    =			sigma * (gamma + 1)  # Note: sigma_hat == sigma for now

      __UpperCamelCase							    =			model_output.device
      __UpperCamelCase							    =			randn_tensor(model_output.shape      ,	dtype=model_output.dtype      ,	device=lowerCamelCase_      ,	generator=lowerCamelCase_ )

      # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
      if self.config.prediction_type == "epsilon":
       __UpperCamelCase							    =			sigma_hat if self.state_in_first_order else sigma_interpol
       __UpperCamelCase							    =			sample - sigma_input * model_output
      elif self.config.prediction_type == "v_prediction":
       __UpperCamelCase							    =			sigma_hat if self.state_in_first_order else sigma_interpol
       __UpperCamelCase							    =			model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
           sample / (sigma_input**2 + 1)
       )
      elif self.config.prediction_type == "sample":
       raise NotImplementedError('prediction_type not implemented yet: sample' )
      else:
       raise ValueError(
           F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' )

      if self.state_in_first_order:
       # 2. Convert to an ODE derivative for 1st order
       __UpperCamelCase							    =			(sample - pred_original_sample) / sigma_hat
       # 3. delta timestep
       __UpperCamelCase							    =			sigma_interpol - sigma_hat

       # store for 2nd order step
       __UpperCamelCase							    =			sample
       __UpperCamelCase							    =			dt
       __UpperCamelCase							    =			sample + derivative * dt
      else:
       # DPM-Solver-2
       # 2. Convert to an ODE derivative for 2nd order
       __UpperCamelCase							    =			(sample - pred_original_sample) / sigma_interpol
       # 3. delta timestep
       __UpperCamelCase							    =			sigma_down - sigma_hat

       __UpperCamelCase							    =			self.sample
       __UpperCamelCase							    =			None

       __UpperCamelCase							    =			sample + derivative * dt
       __UpperCamelCase							    =			prev_sample + noise * sigma_up

      if not return_dict:
       return (prev_sample,)

      return SchedulerOutput(prev_sample=lowerCamelCase_ )





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	):

      '''simple docstring'''




      __UpperCamelCase							    =			self.sigmas.to(device=original_samples.device      ,	dtype=original_samples.dtype )
      if original_samples.device.type == "mps" and torch.is_floating_point(lowerCamelCase_ ):
       # mps does not support float64
       __UpperCamelCase							    =			self.timesteps.to(original_samples.device      ,	dtype=torch.floataa )
       __UpperCamelCase							    =			timesteps.to(original_samples.device      ,	dtype=torch.floataa )
      else:
       __UpperCamelCase							    =			self.timesteps.to(original_samples.device )
       __UpperCamelCase							    =			timesteps.to(original_samples.device )

      __UpperCamelCase							    =			[self.index_for_timestep(lowerCamelCase_      ,	lowerCamelCase_ ) for t in timesteps]

      __UpperCamelCase							    =			sigmas[step_indices].flatten()
      while len(sigma.shape ) < len(original_samples.shape ):
       __UpperCamelCase							    =			sigma.unsqueeze(-1 )

      __UpperCamelCase							    =			original_samples + noise * sigma
      return noisy_samples







     def __len__(      self ):

      '''simple docstring'''




      return self.config.num_train_timesteps











"""simple docstring"""
import unittest

import numpy as np
import torch
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class 						a_ (      snake_case_    ,		unittest.TestCase					):







      '''simple docstring'''

      lowerCamelCase__			:							Optional[Any]					=      KandinskyPriorPipeline
      lowerCamelCase__			:							Any					=      ['prompt']
      lowerCamelCase__			:							Any					=      ['prompt', 'negative_prompt']
      lowerCamelCase__			:							str					=      [
          'num_images_per_prompt',
          'generator',
          'num_inference_steps',
          'latents',
          'negative_prompt',
          'guidance_scale',
          'output_type',
          'return_dict',
      ]
      lowerCamelCase__			:							Dict					=      False




      @property
      def      a__				(self   ):

       '''simple docstring'''



       return 3_2




      @property
      def      a__				(self   ):

       '''simple docstring'''



       return 3_2




      @property
      def      a__				(self   ):

       '''simple docstring'''



       return self.time_input_dim




      @property
      def      a__				(self   ):

       '''simple docstring'''



       return self.time_input_dim * 4




      @property
      def      a__				(self   ):

       '''simple docstring'''



       return 1_0_0




      @property
      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Any								=		CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'   )
       return tokenizer




      @property
      def      a__				(self   ):

       '''simple docstring'''



       torch.manual_seed(0   )
       lowerCamelCase__	:     int								=		CLIPTextConfig(
           bos_token_id=0,	eos_token_id=2,	hidden_size=self.text_embedder_hidden_size,	projection_dim=self.text_embedder_hidden_size,	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,	)
       return CLIPTextModelWithProjection(lowerCamelCase_   )




      @property
      def      a__				(self   ):

       '''simple docstring'''



       torch.manual_seed(0   )

       lowerCamelCase__	:     Optional[int]								=		{
           'num_attention_heads': 2,
           'attention_head_dim': 1_2,
           'embedding_dim': self.text_embedder_hidden_size,
           'num_layers': 1,
       }

       lowerCamelCase__	:     Optional[int]								=		PriorTransformer(**lowerCamelCase_   )
       # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
       lowerCamelCase__	:     Dict								=		nn.Parameter(torch.ones(model.clip_std.shape   )   )
       return model




      @property
      def      a__				(self   ):

       '''simple docstring'''



       torch.manual_seed(0   )
       lowerCamelCase__	:     List[str]								=		CLIPVisionConfig(
           hidden_size=self.text_embedder_hidden_size,	image_size=2_2_4,	projection_dim=self.text_embedder_hidden_size,	intermediate_size=3_7,	num_attention_heads=4,	num_channels=3,	num_hidden_layers=5,	patch_size=1_4,	)

       lowerCamelCase__	:     int								=		CLIPVisionModelWithProjection(lowerCamelCase_   )
       return model




      @property
      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Union[str, Any]								=		CLIPImageProcessor(
           crop_size=2_2_4,	do_center_crop=lowerCamelCase_,	do_normalize=lowerCamelCase_,	do_resize=lowerCamelCase_,	image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073],	image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711],	resample=3,	size=2_2_4,	)

       return image_processor




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     str								=		self.dummy_prior
       lowerCamelCase__	:     Optional[Any]								=		self.dummy_image_encoder
       lowerCamelCase__	:     Optional[Any]								=		self.dummy_text_encoder
       lowerCamelCase__	:     Union[str, Any]								=		self.dummy_tokenizer
       lowerCamelCase__	:     List[Any]								=		self.dummy_image_processor

       lowerCamelCase__	:     List[Any]								=		UnCLIPScheduler(
           variance_type='fixed_small_log',	prediction_type='sample',	num_train_timesteps=1_0_0_0,	clip_sample=lowerCamelCase_,	clip_sample_range=10.0,	)

       lowerCamelCase__	:     Union[str, Any]								=		{
           'prior': prior,
           'image_encoder': image_encoder,
           'text_encoder': text_encoder,
           'tokenizer': tokenizer,
           'scheduler': scheduler,
           'image_processor': image_processor,
       }

       return components




      def      a__				(self,	lowerCamelCase_,	lowerCamelCase_=0   ):

       '''simple docstring'''



       if str(lowerCamelCase_   ).startswith('mps'   ):
        lowerCamelCase__	:     List[Any]								=		torch.manual_seed(lowerCamelCase_   )
       else:
        lowerCamelCase__	:     Optional[int]								=		torch.Generator(device=lowerCamelCase_   ).manual_seed(lowerCamelCase_   )
       lowerCamelCase__	:     List[Any]								=		{
           'prompt': 'horse',
           'generator': generator,
           'guidance_scale': 4.0,
           'num_inference_steps': 2,
           'output_type': 'np',
       }
       return inputs




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     List[str]								=		'cpu'

       lowerCamelCase__	:     str								=		self.get_dummy_components()

       lowerCamelCase__	:     Any								=		self.pipeline_class(**lowerCamelCase_   )
       lowerCamelCase__	:     Dict								=		pipe.to(lowerCamelCase_   )

       pipe.set_progress_bar_config(disable=lowerCamelCase_   )

       lowerCamelCase__	:     Tuple								=		pipe(**self.get_dummy_inputs(lowerCamelCase_   )   )
       lowerCamelCase__	:     Dict								=		output.image_embeds

       lowerCamelCase__	:     Optional[Any]								=		pipe(
           **self.get_dummy_inputs(lowerCamelCase_   ),	return_dict=lowerCamelCase_,	)[0]

       lowerCamelCase__	:     Dict								=		image[0, -1_0:]
       lowerCamelCase__	:     Tuple								=		image_from_tuple[0, -1_0:]

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

       lowerCamelCase__	:     Dict								=		np.array(
           [-0.0_532, 1.7_120, 0.3_656, -1.0_852, -0.8_946, -1.1_756, 0.4_348, 0.2_482, 0.5_146, -0.1_156]   )

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




      @skip_mps
      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Optional[int]								=		torch_device == 'cpu'
       lowerCamelCase__	:     Any								=		True
       lowerCamelCase__	:     List[Any]								=		False

       self._test_inference_batch_single_identical(
           test_max_difference=lowerCamelCase_,	relax_max_difference=lowerCamelCase_,	test_mean_pixel_difference=lowerCamelCase_,	)





      @skip_mps
      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     str								=		torch_device == 'cpu'
       lowerCamelCase__	:     int								=		False

       self._test_attention_slicing_forward_pass(
           test_max_difference=lowerCamelCase_,	test_mean_pixel_difference=lowerCamelCase_,	)

