
    i,&                     l    d dl Z d dl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  G d dee
      Zy)	    N)ListOptionalTupleUnion   )ConfigMixinregister_to_config   )SchedulerMixinSchedulerOutputc                      e Zd ZdZdZe	 ddedeee	j                  ee   f      fd       Zed        Zed        Zdd	efd
Zddedeeej(                  f   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deeef   f
dZdej,                  dej,                  fdZd Zd Zy)IPNDMSchedulera'  
    A fourth-order Improved Pseudo Linear Multistep scheduler.

    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.
        trained_betas (`np.ndarray`, *optional*):
            Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
    r
   Nnum_train_timestepstrained_betasc                 l    | j                  |       d| _        d| _        g | _        d | _        d | _        y )N      ?   )set_timestepsinit_noise_sigma
pndm_orderets_step_index_begin_index)selfr   r   s      o/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/diffusers/schedulers/scheduling_ipndm.py__init__zIPNDMScheduler.__init__)   s?    
 	./ !$
       c                     | j                   S )zg
        The index counter for current timestep. It will increase 1 after each scheduler step.
        )r   r   s    r   
step_indexzIPNDMScheduler.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.
        r   r   s    r   begin_indexzIPNDMScheduler.begin_indexD   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"   )r   r#   s     r   set_begin_indexzIPNDMScheduler.set_begin_indexL   s     (r   num_inference_stepsdevicec                    || _         t        j                  dd|dz         dd }t        j                  |t        j                  dg      g      }| j
                  j                  ?t        j                  | j
                  j                  t        j                        | _        n1t        j                  |t        j                  z  dz        dz  | _        d| j                  dz  z
  d	z  | _        t        j                  | j                  | j                        t        j                  z  dz  dd }|j                  |      | _        g | _        d| _        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   Ng        )dtyper   r   g      ?)r&   torchlinspacecattensorconfigr   float32betassinmathpialphasatan2to	timestepsr   r   r   )r   r&   r'   stepsr8   s        r   r   zIPNDMScheduler.set_timestepsV   s    $7 q!%81%<=crB		5%,,u"567;;$$0dkk&?&?u}}UDJ5477?Q#671<DJTZZ]*s2[[T[[9DGGCaG"M	"f- r   timestepschedule_timestepsreturnc                     || 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   )r8   nonzerolenitem)r   r:   r;   indicesposs        r   index_for_timestepz!IPNDMScheduler.index_for_timesteps   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+   Tensorr7   r8   r'   rC   r   r   )r   r:   s     r   _init_step_indexzIPNDMScheduler._init_step_index   sW     #(ELL1#;;t~~'<'<=#66x@D#00Dr   model_outputsamplereturn_dictc                    | j                   t        d      | j                  | j                  |       | j                  }| j                  dz   }|| j                  |   z  || j
                  |   z  z   }| j                  j                  |       t        | j                        dk(  r| j                  d   }nt        | j                        dk(  r&d| j                  d   z  | j                  d   z
  dz  }nt        | j                        dk(  r<d| j                  d   z  d| j                  d   z  z
  d	| j                  d
   z  z   dz  }nNdd| j                  d   z  d| j                  d   z  z
  d| j                  d
   z  z   d| j                  d   z  z
  z  }| 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 sample with
        the linear multistep method. It performs one forward pass multiple times to approximate the solution.

        Args:
            model_output (`torch.Tensor`):
                The direct output from learned diffusion model.
            timestep (`int`):
                The current discrete timestep in the diffusion chain.
            sample (`torch.Tensor`):
                A current instance of a sample created by the diffusion process.
            return_dict (`bool`):
                Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or tuple.

        Returns:
            [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
                If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a
                tuple is returned where the first element is the sample tensor.
        zaNumber of inference steps is 'None', you need to run 'set_timesteps' after creating the schedulerr
   r)   r                  gUUUUUU?7   ;   %   	   )prev_sample)r&   
ValueErrorr    rG   r1   r5   r   appendr?   _get_prev_sampler   r   )	r   rH   r:   rI   rJ   timestep_indexprev_timestep_indexr   rX   s	            r   stepzIPNDMScheduler.step   s   4 ##+s  ??"!!(+"oo1tzz.11L4;;~C^4^^txx=A((2,C]atxx|#dhhrl2a7C]a$rDHHRL'881txx|;KKrQCb488B</"txx|2CCb488TV<FWWZ[^b^f^fgi^jZjjkC++FNDWY\] 	A>!;77r   c                     |S )a?  
        Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
        current timestep.

        Args:
            sample (`torch.Tensor`):
                The input sample.

        Returns:
            `torch.Tensor`:
                A scaled input sample.
         )r   rI   argskwargss       r   scale_model_inputz IPNDMScheduler.scale_model_input   s	     r   c                     | j                   |   }| j                  |   }| j                   |   }| j                  |   }|||z  z
  t        |d      z  }	||	z  ||z  z   }
|
S )Ng:0yE>)r5   r1   max)r   rI   r\   r]   r   alphasigma
next_alpha
next_sigmapredrX   s              r   r[   zIPNDMScheduler._get_prev_sample   sp    N+

>*[[!45
ZZ 34
$E4(88 4'#
*::r   c                 .    | j                   j                  S N)r/   r   r   s    r   __len__zIPNDMScheduler.__len__   s    {{...r   )i  N)r   rl   )T) __name__
__module____qualname____doc__orderr	   intr   r   npndarrayr   floatr   propertyr    r#   r%   strr+   r'   r   rF   rC   rG   boolr   r   r^   rc   r[   rm   r`   r   r   r   r      s    Eim!#&!>FuRZZY]^cYdMdGe>f! !&     ! !(3 (! !eCDU>V !< bf#eU\\12#HPQVQ]Q]H^#	#>1uell/B)C 1 1( !88ll88 U\\)*88 	88
 88 
%	&88t %,, 
/r   r   )r3   typingr   r   r   r   numpyrt   r+   configuration_utilsr   r	   scheduling_utilsr   r   r   r`   r   r   <module>r~      s,     / /   A =^/^[ ^/r   