
    bi1                         d dl mZ d dlmZmZmZ d dlZd dlZd dlm	Z
 ddlmZmZ ddlmZmZmZmZmZmZ ej*                  j                   G d d	             Ze G d
 de             Z G d dee      Zy)    )	dataclass)OptionalTupleUnionN   )ConfigMixinregister_to_config   )CommonSchedulerStateFlaxKarrasDiffusionSchedulersFlaxSchedulerMixinFlaxSchedulerOutputadd_noise_commonget_velocity_commonc                       e Zd ZU eed<   ej                  ed<   ej                  ed<   dZee	   ed<   e
dedej                  dej                  fd       Zy)DDPMSchedulerStatecommoninit_noise_sigma	timestepsNnum_inference_stepsc                      | |||      S )Nr   r   r    )clsr   r   r   s       d/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/schedulers/scheduling_ddpm_flax.pycreatezDDPMSchedulerState.create,   s    &3CyYY    )__name__
__module____qualname__r   __annotations__jnpndarrayr   r   intclassmethodr   r   r   r   r   r   #   se       kk!{{)-#-Z0 ZCKK Z\_\g\g Z Zr   r   c                       e Zd ZU eed<   y)FlaxDDPMSchedulerOutputstateN)r   r   r    r   r!   r   r   r   r'   r'   1   s    r   r'   c                      e Zd ZU dZeD  cg c]  }|j
                   c}} Zej                  e	d<   e
d        Zedddddd	d
dej                  f	dededededeej$                     dedededej                  fd       Zd*dee   defdZ	 d*dedej$                  dee   dej$                  fdZ	 d+dedededefdZd,defdZ	 	 d-ded ej$                  dedej$                  d!eej:                     d"edeeef   fd#Z ded$ej$                  d%ej$                  d&ej$                  dej$                  f
d'Z!dedej$                  d%ej$                  d&ej$                  dej$                  f
d(Z"d) Z#yc c}} w ).FlaxDDPMSchedulera  
    Denoising diffusion probabilistic models (DDPMs) explores the connections between denoising score matching and
    Langevin dynamics sampling.

    [`~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.

    For more details, see the original paper: https://huggingface.co/papers/2006.11239

    Args:
        num_train_timesteps (`int`): number of diffusion steps used to train the model.
        beta_start (`float`): the starting `beta` value of inference.
        beta_end (`float`): the final `beta` value.
        beta_schedule (`str`):
            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):
            option to pass an array of betas directly to the constructor to bypass `beta_start`, `beta_end` etc.
        variance_type (`str`):
            options to clip the variance used when adding noise to the denoised sample. Choose from `fixed_small`,
            `fixed_small_log`, `fixed_large`, `fixed_large_log`, `learned` or `learned_range`.
        clip_sample (`bool`, default `True`):
            option to clip predicted sample between -1 and 1 for numerical stability.
        prediction_type (`str`, default `epsilon`):
            indicates whether the model predicts the noise (epsilon), or the samples. One of `epsilon`, `sample`.
            `v-prediction` is not supported for this scheduler.
        dtype (`jnp.dtype`, *optional*, defaults to `jnp.float32`):
            the `dtype` used for params and computation.
    dtypec                      yNTr   selfs    r   	has_statezFlaxDDPMScheduler.has_state[   s    r   i  g-C6?g{Gz?linearNfixed_smallTepsilonnum_train_timesteps
beta_startbeta_endbeta_scheduletrained_betasvariance_typeclip_sampleprediction_typec
                     |	| _         y Nr+   )
r/   r4   r5   r6   r7   r8   r9   r:   r;   r+   s
             r   __init__zFlaxDDPMScheduler.__init___   s     
r   r   returnc                    |t        j                  |       }t        j                  d| j                        }t        j
                  d| j                  j                        j                         d d d   }t        j                  |||      S )N      ?r>   r   r   )
r   r   r"   arrayr+   arangeconfigr4   roundr   )r/   r   r   r   s       r   create_statezFlaxDDPMScheduler.create_staten   s{    >)006F 99S

;JJq$++"A"ABHHJ4R4P	!((- ) 
 	
r   r(   sampletimestepc                     |S )a  
        Args:
            state (`PNDMSchedulerState`): the `FlaxPNDMScheduler` state data class instance.
            sample (`jnp.ndarray`): input sample
            timestep (`int`, optional): current timestep

        Returns:
            `jnp.ndarray`: scaled input sample
        r   )r/   r(   rI   rJ   s       r   scale_model_inputz#FlaxDDPMScheduler.scale_model_input}   s	     r   r   shapec                     | j                   j                  |z  }t        j                  d|      |z  j	                         ddd   }|j                  ||      S )a  
        Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference.

        Args:
            state (`DDIMSchedulerState`):
                the `FlaxDDPMScheduler` state data class instance.
            num_inference_steps (`int`):
                the number of diffusion steps used when generating samples with a pre-trained model.
        r   NrC   )r   r   )rF   r4   r"   rE   rG   replace)r/   r(   r   rM   
step_ratior   s         r   set_timestepszFlaxDDPMScheduler.set_timesteps   s`     [[448KK
 ZZ#67*DKKMdPRdS	}} 3  
 	
r   c                    |j                   j                  |   }t        j                  |dkD  |j                   j                  |dz
     t        j                  d| j
                              }d|z
  d|z
  z  |j                   j                  |   z  }|| j                  j                  }|dk(  rt        j                  |d      }|S |dk(  r,t        j                  t        j                  |d            }|S |d	k(  r|j                   j                  |   }|S |d
k(  r.t        j                  |j                   j                  |         }|S |dk(  r|S |dk(  r1|}|j                   j                  |   }	|dz   dz  }
|
|	z  d|
z
  |z  z   }|S )Nr   r
   rB   r>   r2   g#B;)a_minfixed_small_logfixed_largefixed_large_loglearnedlearned_ranger   )r   alphas_cumprodr"   whererD   r+   betasrF   r9   cliplog)r/   r(   tpredicted_variancer9   alpha_prod_talpha_prod_t_prevvariancemin_logmax_logfracs              r   _get_variancezFlaxDDPMScheduler._get_variance   s   ||2215IIa!eU\\-H-HQ-OQTQZQZ[^fjfpfpQqr
 ))a,.>?%,,BTBTUVBWW  KK55M M)xx6H"  //wwsxx>?H  m+||))!,H  //wwu||11!45H  i'%%o-Gll((+G&*a/Dg~TW(<<Hr   model_outputkeyreturn_dictc                 0    |t         j                  j                  d      t        j                        dkD  rcj                  d   |j                  d   dz  k(  rA j
                  j                  dv r)t        j                  |j                  d   d      \  ndj                  j                     }t        j                  dkD  j                  j                  dz
     t        j                  d j                              }d|z
  }	d|z
  }
 j
                  j                  d	k(  r||	d
z  z  z
  |d
z  z  }nj j
                  j                  dk(  r}nN j
                  j                  dk(  r|d
z  |z  |	d
z  z  z
  }n#t        d j
                  j                   d       j
                  j                   rt        j"                  |dd      }|d
z  j                  j$                     z  |	z  }j                  j&                     d
z  |
z  |	z  }||z  ||z  z   } fd}t        j                  dkD   |       t        j(                  j                   j                              }||z   }|s|fS t+        |      S )a  
        Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
        process from the learned model outputs (most often the predicted noise).

        Args:
            state (`DDPMSchedulerState`): the `FlaxDDPMScheduler` state data class instance.
            model_output (`jnp.ndarray`): direct output from learned diffusion model.
            timestep (`int`): current discrete timestep in the diffusion chain.
            sample (`jnp.ndarray`):
                current instance of sample being created by diffusion process.
            key (`jax.Array`): a PRNG key.
            return_dict (`bool`): option for returning tuple rather than FlaxDDPMSchedulerOutput class

        Returns:
            [`FlaxDDPMSchedulerOutput`] or `tuple`: [`FlaxDDPMSchedulerOutput`] if `return_dict` is True, otherwise a
            `tuple`. When returning a tuple, the first element is the sample tensor.

        Nr   r
   r   )rW   rX   )axisrB   r>   r3         ?rI   v_predictionzprediction_type given as z? must be one of `epsilon`, `sample`  for the FlaxDDPMScheduler.rC   c                      t         j                  j                  d      d   } t         j                  j                  | j                  j
                        }j                        dz  |z  S )Nr
   )numr   )rM   r+   )r_   rl   )jaxrandomsplitnormalrM   r+   rf   )	split_keynoiserh   rg   r_   r/   r(   r^   s     r   random_variancez/FlaxDDPMScheduler.step.<locals>.random_variance  sn    

((!(4Q7IJJ%%i|7I7IQUQ[Q[%\E&&uaDV&W[^^bgggr   )prev_sampler(   )rp   rq   rh   lenrM   rF   r9   r"   rr   r   rY   rZ   rD   r+   r;   
ValueErrorr:   r\   r[   alphaszerosr'   )r/   r(   rg   rJ   rI   rh   ri   r`   ra   beta_prod_tbeta_prod_t_prevpred_original_samplepred_original_sample_coeffcurrent_sample_coeffpred_prev_samplerv   rb   r_   r^   s   ```  `           @@r   stepzFlaxDDPMScheduler.step   s   6 ;**..#C ""#a'""1%a1)<<))-II/2yyv||TU]^/_,L,!% ||2215IIa!eU\\-H-HQ-OQTQZQZ[^fjfpfpQqr,&00 ;;&&)3$*[S-AL-P$PT`ehTi#i [[((H4#/ [[((N:$0#$5#?;PSCSWcBc#c +DKK,G,G+H I. .  ;;""#&88,@"a#H  '8C&@5<<CUCUVWCX&X\g%g"$||2215#>AQQT__ 68LLOcflOll	h 	h
 99QUO$5syyASAS[_[e[e7fg+h6$e,,&3C5QQr   original_samplesru   r   c                 2    t        |j                  |||      S r=   )r   r   )r/   r(   r   ru   r   s        r   	add_noisezFlaxDDPMScheduler.add_noise  s      .>yQQr   c                 2    t        |j                  |||      S r=   )r   r   )r/   r(   rI   ru   r   s        r   get_velocityzFlaxDDPMScheduler.get_velocity%  s     #5<<	JJr   c                 .    | j                   j                  S r=   )rF   r4   r.   s    r   __len__zFlaxDDPMScheduler.__len__.  s    {{...r   r=   )r   )NNr-   )$r   r   r    __doc__r   name_compatiblesr"   r+   r!   propertyr0   r	   float32r$   floatstrr   r#   boolr?   r   r   rH   rL   r   rQ   rf   rp   Arrayr   r'   r   r   r   r   ).0es   00r   r*   r*   6   s   @ %BBqAFFBL99   $("%/3* (;;   	
   ,    yy 
8,@#A 
M_ 
  Y]'14HPQT	 SU
'
>A
JO
	
.#5 N $( WR!WR kkWR 	WR
 WR cii WR WR 
&-	.WRrR!R ++R {{	R
 ;;R 
RK!K K {{	K
 ;;K 
K/o Cs   E2r*   )dataclassesr   typingr   r   r   flaxrp   	jax.numpynumpyr"   configuration_utilsr   r	   scheduling_utils_flaxr   r   r   r   r   r   structr   r'   r*   r   r   r   <module>r      sy   " " ) )  
  A  
Z 
Z 
Z 1  y/*K y/r   