
    bi                        d dl Z d dlm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 ddlmZmZ ddlmZ  ej*                  e      Ze G d	 d
e             Z	 	 ddZde
j4                  de
j4                  fdZ G d dee      Zy)    N)	dataclass)ListOptionalTupleUnion   )ConfigMixinregister_to_config)SchedulerMixin)
BaseOutputlogging)randn_tensorc                   X    e Zd ZU dZej
                  ed<   dZeej
                     ed<   y)TCDSchedulerOutputa  
    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_noised_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
            The predicted noised sample `(x_{s})` based on the model output from the current timestep.
    prev_sampleNpred_noised_sample)	__name__
__module____qualname____doc__torchTensor__annotations__r   r        ^/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/schedulers/scheduling_tcd.pyr   r   "   s'    	 15.5r   r   c           
      $   |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 )a  
    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`): the maximum beta to use; use values lower than 1 to
                     prevent singularities.
        alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
                     Choose from `cosine` or `exp`

    Returns:
        betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
    cosinec                 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   expc                 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:    dtype)
ValueErrorrangeappendminr   tensorfloat32)num_diffusion_timestepsmax_betaalpha_transform_typer%   betasit1t2s           r   betas_for_alpha_barr8   4   s    . x'	D 
	&	' =>R=STUUE*+ M((!e..S\"-R0@@@(KLM <<U]]33r   r4   returnc                 (   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)r4   alphasalphas_cumprodalphas_bar_sqrtalphas_bar_sqrt_0alphas_bar_sqrt_T
alphas_bars          r   rescale_zero_terminal_snrrI   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            $       (   e Zd ZdZdZe	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d2dedededede	e
ej                  ee   f      d	ed
ededededededededededef"d       Zd3dZd Zed        Zed        Zd4defdZd3dej.                  de	e   dej.                  fdZd  Zdej.                  dej.                  fd!Z	 	 	 	 	 d5d"e	e   d#e
eej6                  f   d	e	e   d$e	ee      d%ef
d&Z	 	 	 d6d'ej.                  dedej.                  d(ed)e	ej:                     d*ede
eef   fd+Z d,ej.                  d-ej.                  d$ejB                  dej.                  fd.Z"dej.                  d-ej.                  d$ejB                  dej.                  fd/Z#d0 Z$d1 Z%y)7TCDSchedulera  
    `TCDScheduler` incorporates the `Strategic Stochastic Sampling` introduced by the paper `Trajectory Consistency
    Distillation`, extending the original Multistep Consistency Sampling to enable unrestricted trajectory traversal.

    This code is based on the official repo of TCD(https://github.com/jabir-zheng/TCD).

    This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. [`~ConfigMixin`] takes care of storing all config
    attributes that are passed in the scheduler's `__init__` function, such as `num_train_timesteps`. They can be
    accessed via `scheduler.config.num_train_timesteps`. [`SchedulerMixin`] provides general loading and saving
    functionality via the [`SchedulerMixin.save_pretrained`] and [`~SchedulerMixin.from_pretrained`] functions.

    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 (`str`, 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`.
        original_inference_steps (`int`, *optional*, defaults to 50):
            The default number of inference steps used to generate a linearly-spaced timestep schedule, from which we
            will ultimately take `num_inference_steps` evenly spaced timesteps to form the final timestep schedule.
        clip_sample (`bool`, defaults to `True`):
            Clip the predicted sample for numerical stability.
        clip_sample_range (`float`, defaults to 1.0):
            The maximum magnitude for sample clipping. Valid only when `clip_sample=True`.
        set_alpha_to_one (`bool`, defaults to `True`):
            Each diffusion step uses the alphas product value at that step and at the previous one. For the final step
            there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,
            otherwise it uses the alpha value at step 0.
        steps_offset (`int`, defaults to 0):
            An offset added to the inference steps, as required by some model families.
        prediction_type (`str`, 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://imagen.research.google/video/paper.pdf) paper).
        thresholding (`bool`, defaults to `False`):
            Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
            as Stable Diffusion.
        dynamic_thresholding_ratio (`float`, defaults to 0.995):
            The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
        sample_max_value (`float`, defaults to 1.0):
            The threshold value for dynamic thresholding. Valid only when `thresholding=True`.
        timestep_spacing (`str`, defaults to `"leading"`):
            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.
        timestep_scaling (`float`, defaults to 10.0):
            The factor the timesteps will be multiplied by when calculating the consistency model boundary conditions
            `c_skip` and `c_out`. Increasing this will decrease the approximation error (although the approximation
            error at the default of `10.0` is already pretty small).
        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trained_betasoriginal_inference_stepsclip_sampleclip_sample_rangeset_alpha_to_onesteps_offsetprediction_typethresholdingdynamic_thresholding_ratiosample_max_valuetimestep_spacingtimestep_scalingrescale_betas_zero_snrc                    |+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t        j                  d      n| j                  d	   | _        d| _        d | _        t        j                  t!        j"                  d	|      d d d   j%                         j'                  t         j(                              | _        d| _        d | _        d | _        y )Nr)   linearscaled_linear      ?r   squaredcos_cap_v2z is not implemented for r;   r   r<   r>   F)r   r/   r0   r4   linspacer8   NotImplementedError	__class__rI   rC   r?   rD   final_alpha_cumprodinit_noise_sigmanum_inference_steps
from_numpynparangecopyastypeint64	timestepscustom_timesteps_step_index_begin_index)selfrL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   s                     r   __init__zTCDScheduler.__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? 9I5<<#4dNaNabcNd  !$ $( ))"))A7J*KDbD*Q*V*V*X*_*_`b`h`h*ij % r   c                     || j                   }||k(  j                         }t        |      dkD  rdnd}||   j                         S )Nr(   r   )rn   nonzerolenitem)rr   timestepschedule_timestepsindicesposs        r   index_for_timestepzTCDScheduler.index_for_timestep   sL    %!%%1::< w<!#as|  ""r   c                     | j                   Vt        |t        j                        r%|j	                  | j
                  j                        }| j                  |      | _        y | j                  | _        y N)
begin_index
isinstancer   r   torn   devicer|   rp   rq   )rr   rx   s     r   _init_step_indexzTCDScheduler._init_step_index  sU    #(ELL1#;;t~~'<'<=#66x@D#00Dr   c                     | j                   S r~   )rp   rr   s    r   
step_indexzTCDScheduler.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.
        rq   r   s    r   r   zTCDScheduler.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`):
                The begin index for the scheduler.
        Nr   )rr   r   s     r   set_begin_indexzTCDScheduler.set_begin_index"  s     (r   samplerx   r9   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.
            timestep (`int`, *optional*):
                The current timestep in the diffusion chain.

        Returns:
            `torch.Tensor`:
                A scaled input sample.
        r   )rr   r   rx   s      r   scale_model_inputzTCDScheduler.scale_model_input,  s	     r   c                     | j                   |   }|dk\  r| j                   |   n| j                  }d|z
  }d|z
  }||z  d||z  z
  z  }|S )Nr   r(   )rD   re   )rr   rx   prev_timestepalpha_prod_talpha_prod_t_prevbeta_prod_tbeta_prod_t_prevvariances           r   _get_variancezTCDScheduler._get_variance>  si    **84BOSTBTD//>Z^ZrZr,&00${2q<J[;[7[\r   c                 b   |j                   }|j                  ^}}}|t        j                  t        j                  fvr|j                         }|j                  ||t        j                  |      z        }|j                         }t        j                  || j                  j                  d      }t        j                  |d| j                  j                        }|j                  d      }t        j                  || |      |z  } |j                  ||g| }|j!                  |      }|S )a{  
        "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
        prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
        s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
        pixels from saturation at each step. We find that dynamic thresholding results in significantly better
        photorealism as well as better image-text alignment, especially when using very large guidance weights."

        https://huggingface.co/papers/2205.11487
        r(   r<   )r.   max)r*   shaper   r0   float64floatreshaperi   prodabsquantileconfigrX   clamprY   	unsqueezer   )rr   r   r*   
batch_sizechannelsremaining_dims
abs_sampless           r   _threshold_samplezTCDScheduler._threshold_sampleI  s     06-
H~66\\^F 
Hrww~7N,NOZZ\
NN:t{{'M'MSTUKK1$++66
 KKNVaR+a/
HF~F5!r   rg   r   rn   strengthc                 :
   ||t        d      ||t        d      ||n| j                  j                  }||| j                  j                  kD  r=t        d| d| j                  j                   d| j                  j                   d      | j                  j                  |z  }t	        j
                  t        t        dt        ||z        dz                     |z  dz
  }nHt	        j
                  t        t        d	t        | j                  j                  |z                          }|6t        |      }	g }
t        dt        |            D ]7  }||   ||dz
     k\  rt        d
      ||   |	vs$|
j                  ||          9 |d	   | j                  j                  k\  r#t        d| j                  j                   d      |dk(  rU|d	   | j                  j                  dz
  k7  r6t        j                  d|d	    d| j                  j                  dz
   d       |
rt        j                  d|
 d       |4t        |      |kD  rt        j                  dt        |       d| d       n[t        |      | j                  j                  kD  r9t        j                  dt        |       d| j                  j                   d       t	        j                  |t        j                        }t        |      | _        d| _        t%        t        | j                   |z        | j                         }t'        | j                   |z
  d	      }||| j(                  z  d }nl|| j                  j                  kD  r=t        d| d| j                  j                   d| j                  j                   d      |Ft        |      |z  }|dk  r3t        d| d| d| dt        ||z         dt+        ||z         d      || _        |||kD  rQt        d| d| d      || j                  j                  kD  r&t        d| d| j                  j                   d       |ddd!   j-                         }t	        j.                  d	t        |      |d"#      }t	        j0                  |      j3                  t        j                        }||   }t5        j6                  |      j9                  |t4        j:                  $      | _        d| _        d| _         y)%a  
        Sets the discrete timesteps used for the diffusion chain (to be run before inference).

        Args:
            num_inference_steps (`int`, *optional*):
                The number of diffusion steps used when generating samples with a pre-trained model. If used,
                `timesteps` must be `None`.
            device (`str` or `torch.device`, *optional*):
                The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
            original_inference_steps (`int`, *optional*):
                The original number of inference steps, which will be used to generate a linearly-spaced timestep
                schedule (which is different from the standard `diffusers` implementation). We will then take
                `num_inference_steps` timesteps from this schedule, evenly spaced in terms of indices, and use that as
                our final timestep schedule. If not set, this will default to the `original_inference_steps` attribute.
            timesteps (`List[int]`, *optional*):
                Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
                timestep spacing strategy of equal spacing between timesteps on the training/distillation timestep
                schedule is used. If `timesteps` is passed, `num_inference_steps` must be `None`.
            strength (`float`, *optional*, defaults to 1.0):
                Used to determine the number of timesteps used for inference when using img2img, inpaint, etc.
        NzEMust pass exactly one of `num_inference_steps` or `custom_timesteps`.zACan only pass one of `num_inference_steps` or `custom_timesteps`.z`original_steps`: z6 cannot be larger than `self.config.train_timesteps`: zG as the unet model trained with this scheduler can only handle maximal z timesteps.r(   r   z/`custom_timesteps` must be in descending order.z=`timesteps` must start before `self.config.train_timesteps`: .r;   z6The first timestep on the custom timestep schedule is z-, not `self.config.num_train_timesteps - 1`: zC. You may get unexpected results when using this timestep schedule.zThe custom timestep schedule contains the following timesteps which are not on the original training/distillation timestep schedule: z;The number of timesteps in the custom timestep schedule is zK, which exceeds the the length of the timestep schedule used for training: zH. You may get some unexpected results when using this timestep schedule.r)   Tz`num_inference_steps`: z0The combination of `original_steps x strength`: z x z( is smaller than `num_inference_steps`: zK. Make sure to either reduce `num_inference_steps` to a value smaller than z/ or increase `strength` to a value higher than z3 cannot be larger than `original_inference_steps`: zx because the final timestep schedule will be a subset of the `original_inference_steps`-sized initial timestep schedule.z. cannot be larger than `num_train_timesteps`: zs because the final timestep schedule will be a subset of the `num_train_timesteps`-sized initial timestep schedule.r>   F)numendpoint)r   r*   )!r+   r   rQ   rL   ri   asarraylistr,   intsetrv   r-   loggerwarningarrayrm   rg   ro   r.   r   orderr   rk   rb   floorrl   r   rh   r   longrn   rp   rq   )rr   rg   r   rQ   rn   r   original_stepsktcd_origin_timestepstrain_timestepsnon_train_timestepsr5   init_timestept_startskipping_stepinference_indicess                   r   set_timestepszTCDScheduler.set_timestepsj  s   < &9+<dee*y/D`aa )A(L$RVR]R]RvRv 	 $+ ? ?? ((8 9778 9  $ ? ?@M  //>AA#%::d5CQY@Y<Z]^<^3_.`#ade#ehi#i  $&::d5C@_@_bj@j<k3l.m#n   !"67O"$1c)n- =Q<9QU#33$%VWWQ<6'..y|<= |t{{>>> STXT_T_TsTsSttuv 
 39Q<4;;3R3RUV3V#VLYWX\N [??C{{?^?^ab?b>c dMN #AAT@U V:; )y>N2NNUVYZcVdUe fSSaRb cQR y>DKK$C$CCNNUVYZcVdUe fSSWS^S^SrSrRs tQR "((;I'*9~D$$(D!  D$<$<x$G H$JbJbcM$22]BAFG!'DJJ"6"89I #T[[%D%DD -.A-B C778 9  $ ? ?@M  ) #$8 9=P P 1$$J>JZZ]^f]g  hP  Qd  Pe  ep  qt  uC  FN  uN  qO  pP  P  @E  FY  \j  Fj  @k  l  lm  n  (;D$)&7$12E1F G*+ ,WX  ')H)HH$12E1F G KK;;< =RS  $8"#=#B#B#D  "As3G/HNalq r "): ; B B288 L,->?I)))477vUZZ7X r   model_outputeta	generatorreturn_dictc                    | j                   t        d      | j                  | j                  |       d|cxk  rdk  sJ d        J d       | j                  dz   }|t	        | j
                        k  r| j
                  |   }nt        j                  d      }t        j                  d|z
  |z        j                  t        j                        }	| j                  |   }
d|
z
  }|dk\  r| j                  |   n| j                  }| j                  |	   }d|z
  }| j                  j                  dk(  rQ||j                         |z  z
  |
j                         z  }|}|j                         |z  |j                         |z  z   }n| j                  j                  dk(  r;|}||
d	z  |z  z
  |d	z  z  }|j                         |z  |j                         |z  z   }n| j                  j                  d
k(  rJ|
d	z  |z  |d	z  |z  z
  }|
d	z  |z  |d	z  |z  z   }|j                         |z  |j                         |z  z   }n#t        d| j                  j                   d      |dkD  r}| j                  | j                   dz
  k7  r^t!        |j"                  ||j$                  |j&                        }||z  j                         |z  d||z  z
  j                         |z  z   }n|}n|}| xj(                  dz  c_        |s||fS t+        ||      S )aq  
        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 (`int`):
                The current discrete timestep in the diffusion chain.
            sample (`torch.Tensor`):
                A current instance of a sample created by the diffusion process.
            eta (`float`):
                A stochastic parameter (referred to as `gamma` in the paper) used to control the stochasticity in every
                step. When eta = 0, it represents deterministic sampling, whereas eta = 1 indicates full stochastic
                sampling.
            generator (`torch.Generator`, *optional*):
                A random number generator.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~schedulers.scheduling_tcd.TCDSchedulerOutput`] or `tuple`.
        Returns:
            [`~schedulers.scheduling_utils.TCDSchedulerOutput`] or `tuple`:
                If return_dict is `True`, [`~schedulers.scheduling_tcd.TCDSchedulerOutput`] 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;   z'gamma must be less than or equal to 1.0r(   r)   epsilonr   r`   v_predictionzprediction_type given as zI must be one of `epsilon`, `sample` or `v_prediction` for `TCDScheduler`.)r   r   r*   )r   r   )rg   r+   r   r   rv   rn   r   r/   r   r   r   rD   re   r   rV   r@   r   r   r   r*   rp   r   )rr   r   rx   r   r   r   r   prev_step_indexr   
timestep_sr   r   r   alpha_prod_sbeta_prod_spred_original_samplepred_epsilonr   noiser   s                       r   stepzTCDScheduler.step  sI   B ##+s  ??"!!(+C3I III II //A-S00 NN?;M!LLOM[[!c']!:;>>UZZ>P
 **84,&BOSTBTD//>Z^ZrZr**:6,& ;;&&)3$*[-=-=-?,-N$NR^RcRcRe#e 'L!-!2!2!47K!KkN^N^N`coNo!o[[((H4#/ "\c%:=Q%QQU`ehUiiL!-!2!2!47K!KkN^N^N`coNo!o[[((N:$0#$5#?;PSCSWcBc#c (#-=cAQU[@[[L!-!2!2!47K!KkN^N^N`coNo!o+DKK,G,G+H I6 6  7$":":Q">>$ &&)LDWDW_q_w_w  1<?EEGJ\\)L88$&5`! ! 1,K 	A!344!kN`aar   original_samplesr   c                    | j                   j                  |j                        | _         | j                   j                  |j                        }|j                  |j                        }||   dz  }|j	                         }t        |j                        t        |j                        k  r=|j                  d      }t        |j                        t        |j                        k  r=d||   z
  dz  }|j	                         }t        |j                        t        |j                        k  r=|j                  d      }t        |j                        t        |j                        k  r=||z  ||z  z   }|S N)r   r)   r`   r>   r(   rD   r   r   r*   flattenrv   r   r   )rr   r   r   rn   rD   sqrt_alpha_prodsqrt_one_minus_alpha_prodnoisy_sampless           r   	add_noisezTCDScheduler.add_noisew  sa    #1144<L<S<S4T,,//6F6L6L/MLL!1!8!89	(3s:)113/''(3/?/E/E+FF-77;O /''(3/?/E/E+FF &'	)B%Bs$J!$=$E$E$G!+112S9I9O9O5PP(A(K(KB(O% +112S9I9O9O5PP (*::=VY^=^^r   c                    | j                   j                  |j                        | _         | j                   j                  |j                        }|j                  |j                        }||   dz  }|j	                         }t        |j                        t        |j                        k  r=|j                  d      }t        |j                        t        |j                        k  r=d||   z
  dz  }|j	                         }t        |j                        t        |j                        k  r=|j                  d      }t        |j                        t        |j                        k  r=||z  ||z  z
  }|S r   r   )rr   r   r   rn   rD   r   r   velocitys           r   get_velocityzTCDScheduler.get_velocity  sG   "1144FMM4J,,//fll/CLL/	(3s:)113/''(3v||+<<-77;O /''(3v||+<< &'	)B%Bs$J!$=$E$E$G!+112S5FF(A(K(KB(O% +112S5FF #U*-F-OOr   c                 .    | j                   j                  S r~   )r   rL   r   s    r   __len__zTCDScheduler.__len__  s    {{...r   c                    | j                   s| j                  ro| j                  |k(  j                  d      d   d   }|| j                  j                  d   dz
  k(  rt        j                  d      }|S | j                  |dz      }|S |dz
  }|S )NT)as_tupler   r(   r>   )ro   rg   rn   ru   r   r   r/   )rr   rx   indexprev_ts       r   previous_timestepzTCDScheduler.previous_timestep  s      D$<$<^^x/88$8GJ1ME,,Q/!33b)
  	2  \Fr   )i  g_QK?g~jt?r_   N2   Fr;   Tr   r   Fgףp=
?r;   leadingg      $@Fr~   )r   )NNNNr;   )g333333?NT)&r   r   r   r   r   r
   r   r   strr   r   ri   ndarrayr   boolrs   r|   r   propertyr   r   r   r   r   r   r   r   r   r   	Generatorr   r   r   	IntTensorr   r   r   r   r   r   r   rK   rK      s   :x E $(#,BF(*!#&!%(",1"% )"&',%7! 7! 7! 	7!
 7!  bjj$u+&= >?7! #&7! 7! !7! 7! 7! 7! 7! %*7!  7!  !7!"  #7!$ !%%7! 7!t#1     ! !(3 (  Y^YeYe $  F .2+/26)-`!%c]`! c5<<'(`! #+3-	`!
 DI&`! `!N /3 hbllhb hb 	hb
 hb EOO,hb hb 
!5(	)hbV,, || ??	
 
65<<  QVQ`Q` ejeqeq &/	r   rK   )g+?r   )r    dataclassesr   typingr   r   r   r   numpyri   r   configuration_utilsr	   r
   schedulers.scheduling_utilsr   utilsr   r   utils.torch_utilsr   
get_loggerr   r   r   r8   r   rI   rK   r   r   r   <module>r      s   $  ! / /   A 8 ' , 
		H	% 6 6 6& !)4Z!U\\ !ell !Hm>; mr   