
    bi@"                     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Zd Z	 ddej0                  deeej0                  f   dej0                  dedeeef   f
dZdej0                  dej0                  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      `/home/cdr/jupyterlab/.venv/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`):
                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   c                     || j                   }||k(  j                         }t        |      dkD  rdnd}||   j                         S )Nr
   r   )r8   nonzerolenitem)r   timestepschedule_timestepsindicesposs        r   index_for_timestepz!IPNDMScheduler.index_for_timesteps   sL    %!%%1::< w<!#as|  ""r   c                     | j                   Vt        |t        j                        r%|j	                  | j
                  j                        }| j                  |      | _        y | j                  | _        y N)
r#   
isinstancer+   Tensorr7   r8   r'   rB   r   r   )r   r>   s     r   _init_step_indexzIPNDMScheduler._init_step_index   sU    #(ELL1#;;t~~'<'<=#66x@D#00Dr   model_outputr>   samplereturn_dictreturnc                    | 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   rY   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predrY   s              r   r\   zIPNDMScheduler._get_prev_sample   sp    N+

>*[[!45
ZZ 34
$E4(88 4'#
*::r   c                 .    | j                   j                  S rD   )r/   r   r   s    r   __len__zIPNDMScheduler.__len__   s    {{...r   )i  N)r   rD   )T) __name__
__module____qualname____doc__orderr	   intr   r   npndarrayr   floatr   propertyr    r#   r%   strr+   r'   r   rB   rG   rF   boolr   r   r_   rd   r\   rm   ra   r   r   r   r      s,    Eim!#&!>FuRZZY]^cYdMdGe>f! !&     ! !(3 (! !eCDU>V !:#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   ra   r   r   <module>r~      s,     / /   A =G/^[ G/r   