
    i[              	       L   d dl Z d dlmZ d dlmZmZmZmZmZ d dl	Z
d dlZddlmZmZ ddlmZmZ ddlmZ dd	lmZmZ  ej.                  e      Ze G d
 de             Z	 	 ddededed   dej:                  fdZdej:                  dej:                  fdZ G d dee      Z y)    N)	dataclass)ListLiteralOptionalTupleUnion   )ConfigMixinregister_to_config)
BaseOutputlogging)randn_tensor   )KarrasDiffusionSchedulersSchedulerMixinc                   X    e Zd ZU dZej
                  ed<   dZeej
                     ed<   y)%EulerAncestralDiscreteSchedulerOutputaq  
    Output class for the scheduler's `step` function output.

    Args:
        prev_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
            Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
            denoising loop.
        pred_original_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
            The predicted denoised sample `(x_{0})` based on the model output from the current timestep.
            `pred_original_sample` can be used to preview progress or for guidance.
    prev_sampleNpred_original_sample)	__name__
__module____qualname____doc__torchTensor__annotations__r   r        /home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/diffusers/schedulers/scheduling_euler_ancestral_discrete.pyr   r      s'    
 37(5<<07r   r   num_diffusion_timestepsmax_betaalpha_transform_type)cosineexpreturnc           
      $   |dk(  rd }n|dk(  rd }nt        d|       g }t        |       D ]<  }|| z  }|dz   | z  }|j                  t        d ||       ||      z  z
  |             > t	        j
                  |t        j                        S )aB  
    Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
    (1-beta) over time from t = [0,1].

    Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
    to that part of the diffusion process.

    Args:
        num_diffusion_timesteps (`int`):
            The number of betas to produce.
        max_beta (`float`, defaults to `0.999`):
            The maximum beta to use; use values lower than 1 to avoid numerical instability.
        alpha_transform_type (`"cosine"` or `"exp"`, defaults to `"cosine"`):
            The type of noise schedule for `alpha_bar`. Choose from `cosine` or `exp`.

    Returns:
        `torch.Tensor`:
            The betas used by the scheduler to step the model outputs.
    r#   c                 f    t        j                  | dz   dz  t         j                  z  dz        dz  S )NgMb?gT㥛 ?r	   )mathcospits    r   alpha_bar_fnz)betas_for_alpha_bar.<locals>.alpha_bar_fnM   s-    88QY%/$''9A=>!CCr   r$   c                 2    t        j                  | dz        S )Ng      ()r(   r$   r+   s    r   r-   z)betas_for_alpha_bar.<locals>.alpha_bar_fnR   s    88AI&&r   z"Unsupported alpha_transform_type: r   dtype)
ValueErrorrangeappendminr   tensorfloat32)r    r!   r"   r-   betasit1t2s           r   betas_for_alpha_barr;   3   s    0 x'	D 
	&	' =>R=STUUE*+ M((!e..S\"-R0@@@(KLM <<U]]33r   r7   c                 (   d| z
  }t        j                  |d      }|j                         }|d   j                         }|d   j                         }||z  }||||z
  z  z  }|dz  }|dd |dd z  }t        j                  |dd |g      }d|z
  } | S )a:  
    Rescales betas to have zero terminal SNR Based on https://huggingface.co/papers/2305.08891 (Algorithm 1)

    Args:
        betas (`torch.Tensor`):
            The betas that the scheduler is being initialized with.

    Returns:
        `torch.Tensor`:
            Rescaled betas with zero terminal SNR.
          ?r   dimr	   r   N)r   cumprodsqrtclonecat)r7   alphasalphas_cumprodalphas_bar_sqrtalphas_bar_sqrt_0alphas_bar_sqrt_T
alphas_bars          r   rescale_zero_terminal_snrrK   a   s     5[F]]6q1N$))+O (*002'+113 ((O (,=@Q,QRRO !!#J^j"o-FYY
1Q01FJELr   c                   l   e Zd ZdZeD  cg c]  }|j
                   c}} ZdZe	 	 	 	 	 	 	 	 	 d)de	de
de
ded   d	eeej                  ee
   f      d
ed   ded   de	deddfd       Zedej*                  fd       Zedee	   fd       Zedee	   fd       Zd*de	ddfdZdej*                  dee
ej*                  f   dej*                  fdZd+de	deeeej8                  f      ddfdZ	 d+dee
ej*                  f   deej*                     de	fdZdee
ej*                  f   ddfdZ	 	 d,d ej*                  dee
ej*                  f   dej*                  d!eej@                     d"edee!e"f   fd#Z#d$ej*                  d%ej*                  d&ej*                  dej*                  fd'Z$de	fd(Z%yc c}} w )-EulerAncestralDiscreteSchedulera  
    Ancestral sampling with Euler method steps.

    This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
    methods the library implements for all schedulers such as loading and saving.

    Args:
        num_train_timesteps (`int`, defaults to 1000):
            The number of diffusion steps to train the model.
        beta_start (`float`, defaults to 0.0001):
            The starting `beta` value of inference.
        beta_end (`float`, defaults to 0.02):
            The final `beta` value.
        beta_schedule (`"linear"`, `"scaled_linear"`, or `"squaredcos_cap_v2"`, defaults to `"linear"`):
            The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
            `linear`, `scaled_linear`, or `squaredcos_cap_v2`.
        trained_betas (`np.ndarray`, *optional*):
            Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
        prediction_type (`"epsilon"`, `"sample"`, or `"v_prediction"`, defaults to `"epsilon"`, *optional*):
            Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
            `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
            Video](https://huggingface.co/papers/2210.02303) paper).
        timestep_spacing (`"linspace"`, `"leading"`, or `"trailing"`, defaults to `"linspace"`):
            The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
            Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
        steps_offset (`int`, defaults to 0):
            An offset added to the inference steps, as required by some model families.
        rescale_betas_zero_snr (`bool`, defaults to `False`):
            Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and
            dark samples instead of limiting it to samples with medium brightness. Loosely related to
            [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
    r   Nnum_train_timesteps
beta_startbeta_endbeta_schedule)linearscaled_linearsquaredcos_cap_v2trained_betasprediction_type)epsilonsamplev_predictiontimestep_spacing)linspaceleadingtrailingsteps_offsetrescale_betas_zero_snrr%   c
                    |+t        j                  |t         j                        | _        n|dk(  r-t        j                  |||t         j                        | _        nk|dk(  r6t        j                  |dz  |dz  |t         j                        dz  | _        n0|dk(  rt        |      | _        nt        | d| j                         |	rt        | j                        | _        d| j                  z
  | _	        t        j                  | j                  d	
      | _        |	rd| j                  d<   t        j                  d| j                  z
  | j                  z  dz        }
t        j                  |
d d d   dgg      j                  t        j                        }
t        j                   |
      | _        d | _        t        j                  d	|dz
  |t&              d d d   j)                         }t        j                   |      | _        d| _        d | _        d | _        | j"                  j3                  d      | _        y )Nr/   rR   rS         ?r	   rT   z is not implemented for r=   r   r>   g      p>r@   r           Fcpu)r   r5   r6   r7   r[   r;   NotImplementedError	__class__rK   rE   rA   rF   nparrayconcatenateastype
from_numpysigmasnum_inference_stepsfloatcopy	timestepsis_scale_input_called_step_index_begin_indexto)selfrN   rO   rP   rQ   rU   rV   rZ   r^   r_   rk   ro   s               r   __init__z(EulerAncestralDiscreteScheduler.__init__   s    $m5==IDJh&
H>QY^YfYfgDJo-
C3H[chcpcpquvvDJ11,-@ADJ%7OPTP^P^O_&`aa!24::>DJDJJ&#mmDKKQ?! '-D#A 3 33t7J7JJsRS"u 56==bjjI&&v. $( KK#6#:<OW\]^b`b^bchhj	)))4%*" kknnU+r   c                     | j                   j                  dv r| j                  j                         S | j                  j                         dz  dz   dz  S )N)r[   r]   r	   r   ra   )configrZ   rk   maxrt   s    r   init_noise_sigmaz0EulerAncestralDiscreteScheduler.init_noise_sigma   sH     ;;''+CC;;??$$!Q&*s22r   c                     | j                   S )zg
        The index counter for current timestep. It will increase 1 after each scheduler step.
        )rq   ry   s    r   
step_indexz*EulerAncestralDiscreteScheduler.step_index   s    
 r   c                     | j                   S )zq
        The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
        rr   ry   s    r   begin_indexz+EulerAncestralDiscreteScheduler.begin_index   s    
    r   r   c                     || _         y)z
        Sets the begin index for the scheduler. This function should be run from pipeline before the inference.

        Args:
            begin_index (`int`, defaults to `0`):
                The begin index for the scheduler.
        Nr~   )rt   r   s     r   set_begin_indexz/EulerAncestralDiscreteScheduler.set_begin_index   s     (r   rX   timestepc                     | j                   | j                  |       | j                  | j                      }||dz  dz   dz  z  }d| _        |S )a  
        Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
        current timestep. Scales the denoising model input by `(sigma**2 + 1) ** 0.5` to match the Euler algorithm.

        Args:
            sample (`torch.Tensor`):
                The input sample.
            timestep (`float` or `torch.Tensor`):
                The current timestep in the diffusion chain.

        Returns:
            `torch.Tensor`:
                A scaled input sample.
        r	   r   ra   T)r|   _init_step_indexrk   rp   )rt   rX   r   sigmas       r   scale_model_inputz1EulerAncestralDiscreteScheduler.scale_model_input   sR      ??"!!(+DOO,E1HqLS01%)"r   rl   devicec           	         || _         | j                  j                  dk(  rTt        j                  d| j                  j
                  dz
  |t        j                        ddd   j                         }nw| j                  j                  dk(  r| j                  j
                  | j                   z  }t        j                  d|      |z  j                         ddd   j                         j                  t        j                        }|| j                  j                  z  }n| j                  j                  dk(  r| j                  j
                  | j                   z  }t        j                  | j                  j
                  d|       j                         j                         j                  t        j                        }|dz  }n"t        | j                  j                   d	      t        j                  d| j                  z
  | j                  z  d
z        }t        j                  |t        j                  dt!        |            |      }t        j"                  |dgg      j                  t        j                        }t%        j&                  |      j)                  |      | _        t%        j&                  |      j)                  |      | _        d| _        d| _        | j*                  j)                  d      | _        y)a  
        Sets the discrete timesteps used for the diffusion chain (to be run before inference).

        Args:
            num_inference_steps (`int`):
                The number of diffusion steps used when generating samples with a pre-trained model.
            device (`str` or `torch.device`, *optional*):
                The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
        r[   r   r   r/   Nr@   r\   r]   zY is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.ra   rb   )r   rc   )rl   rw   rZ   rf   r[   rN   r6   rn   arangeroundri   r^   r1   rg   rF   interplenrh   r   rj   rs   rk   ro   rq   rr   )rt   rl   r   ro   
step_ratiork   s         r   set_timestepsz-EulerAncestralDiscreteScheduler.set_timesteps  s`    $7  ;;'':5At{{'F'F'JL_gigqgqr"df  [[))Y688D<T<TTJ 1&9:ZGNNPQUSUQUV[[]ddegeoeopI111I[[))Z7884;S;SSJ 4;;#B#BA
{SZZ\aacjjkmkukuvINI;;//0  1J  K  A 3 33t7J7JJsRS9bii3v;&?H#077

C&&v.111@)))477v7F kknnU+r   schedule_timestepsc                     || j                   }||k(  j                         }t        |      dkD  rdnd}||   j                         S )ak  
        Find the index of a given timestep in the timestep schedule.

        Args:
            timestep (`float` or `torch.Tensor`):
                The timestep value to find in the schedule.
            schedule_timesteps (`torch.Tensor`, *optional*):
                The timestep schedule to search in. If `None`, uses `self.timesteps`.

        Returns:
            `int`:
                The index of the timestep in the schedule. For the very first step, returns the second index if
                multiple matches exist to avoid skipping a sigma when starting mid-schedule (e.g., for image-to-image).
        r   r   )ro   nonzeror   item)rt   r   r   indicesposs        r   index_for_timestepz2EulerAncestralDiscreteScheduler.index_for_timestepC  sN    " %!%%1::< w<!#as|  ""r   c                     | j                   Vt        |t        j                        r%|j	                  | j
                  j                        }| j                  |      | _        y| j                  | _        y)z
        Initialize the step index for the scheduler based on the given timestep.

        Args:
            timestep (`float` or `torch.Tensor`):
                The current timestep to initialize the step index from.
        N)
r   
isinstancer   r   rs   ro   r   r   rq   rr   )rt   r   s     r   r   z0EulerAncestralDiscreteScheduler._init_step_indexb  sW     #(ELL1#;;t~~'<'<=#66x@D#00Dr   model_output	generatorreturn_dictc                 |   t        |t        t        j                  t        j                  f      rt        d      | j                  st        j                  d       | j                  | j                  |       | j                  | j                     }|j                  t        j                        }| j                  j                  dk(  r	|||z  z
  }n| j                  j                  dk(  r|| |dz  dz   dz  z  z  ||dz  dz   z  z   }nG| j                  j                  dk(  rt!        d	      t        d
| j                  j                   d      | j                  | j                     }| j                  | j                  dz      }	|	dz  |dz  |	dz  z
  z  |dz  z  dz  }
|	dz  |
dz  z
  dz  }||z
  |z  }||z
  }|||z  z   }|j"                  }t%        |j&                  |j(                  ||      }|||
z  z   }|j                  |j(                        }| xj*                  dz  c_        |s||fS t-        ||      S )a  
        Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
        process from the learned model outputs (most often the predicted noise).

        Args:
            model_output (`torch.Tensor`):
                The direct output from learned diffusion model.
            timestep (`float` or `torch.Tensor`):
                The current discrete timestep in the diffusion chain.
            sample (`torch.Tensor`):
                A current instance of a sample created by the diffusion process.
            generator (`torch.Generator`, *optional*):
                A random number generator.
            return_dict (`bool`, defaults to `True`):
                Whether or not to return a
                [`~schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteSchedulerOutput`] or tuple.

        Returns:
            [`~schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteSchedulerOutput`] or `tuple`:
                If return_dict is `True`,
                [`~schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteSchedulerOutput`] is returned,
                otherwise a tuple is returned where the first element is the sample tensor.

        zPassing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to `EulerDiscreteScheduler.step()` is not supported. Make sure to pass one of the `scheduler.timesteps` as a timestep.zThe `scale_model_input` function should be called before `step` to ensure correct denoising. See `StableDiffusionPipeline` for a usage example.rW   rY   r	   r   ra   rX   z+prediction_type not implemented yet: samplezprediction_type given as z, must be one of `epsilon`, or `v_prediction`)r0   r   r   )r   r   )r   intr   	IntTensor
LongTensorr1   rp   loggerwarningr|   r   rk   rs   r6   rw   rV   rd   r   r   shaper0   rq   r   )rt   r   r   rX   r   r   r   r   
sigma_fromsigma_tosigma_up
sigma_down
derivativedtr   r   noises                    r   stepz$EulerAncestralDiscreteScheduler.stepq  s_   B heoou7G7G HIG  ))NNE
 ??"!!(+DOO, 5==) ;;&&)3#)EL,@#@ [[((N:#/E6UAX\c<Q3Q#RV\`egh`hkl`lVm#n [[((H4%&STT+DKK,G,G+HHtu  [[1
;;t23aK:q=8Q;#>?*a-OTWWkHaK/C7
 33u<
%zB.$$\//|7I7IRXdmn!EH$44 "nn\%7%78 	A$ 
 5#:N
 	
r   original_samplesr   ro   c                    | j                   j                  |j                  |j                        }|j                  j                  dk(  rvt        j                  |      ra| j                  j                  |j                  t
        j                        }|j                  |j                  t
        j                        }n@| j                  j                  |j                        }|j                  |j                        }| j                   |D cg c]  }| j                  ||       }}nG| j                  | j                  g|j                  d   z  }n| j                  g|j                  d   z  }||   j                         }t        |j                        t        |j                        k  r=|j                  d      }t        |j                        t        |j                        k  r=|||z  z   }	|	S c c}w )am  
        Add noise to the original samples according to the noise schedule at the specified timesteps.

        Args:
            original_samples (`torch.Tensor`):
                The original samples to which noise will be added.
            noise (`torch.Tensor`):
                The noise tensor to add to the original samples.
            timesteps (`torch.Tensor`):
                The timesteps at which to add noise, determining the noise level from the schedule.

        Returns:
            `torch.Tensor`:
                The noisy samples with added noise scaled according to the timestep schedule.
        )r   r0   mpsr/   r   r@   )rk   rs   r   r0   typer   is_floating_pointro   r6   r   r   r|   r   flattenr   	unsqueeze)
rt   r   r   ro   rk   r   r,   step_indicesr   noisy_sampless
             r   	add_noisez)EulerAncestralDiscreteScheduler.add_noise  s   , '7'>'>FVF\F\]""''50U5L5LY5W!%!2!23C3J3JRWR_R_!2!`!%5%<%<EMMRI!%!2!23C3J3J!K!%5%<%<=I #T]^qD33A7IJ^L^__( OO,yq/AAL !,,-	0BBL|$,,.%++%5%;%;!<<OOB'E %++%5%;%;!<< )55=8 _s   G9c                 .    | j                   j                  S N)rw   rN   ry   s    r   __len__z'EulerAncestralDiscreteScheduler.__len__  s    {{...r   )	i  g-C6?g{Gz?rR   NrW   r[   r   F)r   r   )NT)&r   r   r   r   r   name_compatiblesorderr   r   rm   r   r   r   rf   ndarrayr   boolru   propertyr   r   rz   r|   r   r   r   strr   r   r   r   	Generatorr   r   r   r   r   ).0es   00r   rM   rM      s   B %>>qAFF>LE $("QYBFHQGQ',0, 0, 0, 	0,
 MN0,  bjj$u+&= >?0, !!DE0, ""CD0, 0, !%0, 
0, 0,d 3%,, 3 3  HSM     !Xc] ! !(3 (t ( eU\\FY@Z _d_k_k 0*, *,huSRWR^R^M^G_>` *,lp *,\ bf#eU\\12#HPQVQ]Q]H^#	#>1uell/B)C 1 1( 04 d
lld
 u||+,d
 	d

 EOO,d
 d
 
4e;	<d
N.,,. ||. <<	.
 
.`/ /C ?s   F0rM   )g+?r#   )!r(   dataclassesr   typingr   r   r   r   r   numpyrf   r   configuration_utilsr
   r   utilsr   r   utils.torch_utilsr   scheduling_utilsr   r   
get_loggerr   r   r   r   rm   r   r;   rK   rM   r   r   r   <module>r      s     ! 8 8   A ' , G 
		H	% 8J 8 8( 5=*4 *4*4 "/2*4 \\	*4\!U\\ !ell !HD/nk D/r   