Skip to main content

candle_transformers/models/stable_diffusion/
ddpm.rs

1use super::schedulers::{betas_for_alpha_bar, BetaSchedule, PredictionType};
2use candle::{Result, Tensor};
3
4#[derive(Debug, Default, Clone, PartialEq, Eq)]
5pub enum DDPMVarianceType {
6    #[default]
7    FixedSmall,
8    FixedSmallLog,
9    FixedLarge,
10    FixedLargeLog,
11    Learned,
12}
13
14#[derive(Debug, Clone)]
15pub struct DDPMSchedulerConfig {
16    /// The value of beta at the beginning of training.
17    pub beta_start: f64,
18    /// The value of beta at the end of training.
19    pub beta_end: f64,
20    /// How beta evolved during training.
21    pub beta_schedule: BetaSchedule,
22    /// Option to predicted sample between -1 and 1 for numerical stability.
23    pub clip_sample: bool,
24    /// Option to clip the variance used when adding noise to the denoised sample.
25    pub variance_type: DDPMVarianceType,
26    /// prediction type of the scheduler function
27    pub prediction_type: PredictionType,
28    /// number of diffusion steps used to train the model.
29    pub train_timesteps: usize,
30}
31
32impl Default for DDPMSchedulerConfig {
33    fn default() -> Self {
34        Self {
35            beta_start: 0.00085,
36            beta_end: 0.012,
37            beta_schedule: BetaSchedule::ScaledLinear,
38            clip_sample: false,
39            variance_type: DDPMVarianceType::FixedSmall,
40            prediction_type: PredictionType::Epsilon,
41            train_timesteps: 1000,
42        }
43    }
44}
45
46pub struct DDPMScheduler {
47    alphas_cumprod: Vec<f64>,
48    init_noise_sigma: f64,
49    timesteps: Vec<usize>,
50    step_ratio: usize,
51    pub config: DDPMSchedulerConfig,
52}
53
54impl DDPMScheduler {
55    pub fn new(inference_steps: usize, config: DDPMSchedulerConfig) -> Result<Self> {
56        let betas = match config.beta_schedule {
57            BetaSchedule::ScaledLinear => super::utils::linspace(
58                config.beta_start.sqrt(),
59                config.beta_end.sqrt(),
60                config.train_timesteps,
61            )?
62            .sqr()?,
63            BetaSchedule::Linear => {
64                super::utils::linspace(config.beta_start, config.beta_end, config.train_timesteps)?
65            }
66            BetaSchedule::SquaredcosCapV2 => betas_for_alpha_bar(config.train_timesteps, 0.999)?,
67        };
68
69        let betas = betas.to_vec1::<f64>()?;
70        let mut alphas_cumprod = Vec::with_capacity(betas.len());
71        for &beta in betas.iter() {
72            let alpha = 1.0 - beta;
73            alphas_cumprod.push(alpha * *alphas_cumprod.last().unwrap_or(&1f64))
74        }
75
76        // min(train_timesteps, inference_steps)
77        // https://github.com/huggingface/diffusers/blob/8331da46837be40f96fbd24de6a6fb2da28acd11/src/diffusers/schedulers/scheduling_ddpm.py#L187
78        let inference_steps = inference_steps.min(config.train_timesteps);
79        // arange the number of the scheduler's timesteps
80        let step_ratio = config.train_timesteps / inference_steps;
81        let timesteps: Vec<usize> = (0..inference_steps).map(|s| s * step_ratio).rev().collect();
82
83        Ok(Self {
84            alphas_cumprod,
85            init_noise_sigma: 1.0,
86            timesteps,
87            step_ratio,
88            config,
89        })
90    }
91
92    fn get_variance(&self, timestep: usize) -> f64 {
93        let prev_t = timestep as isize - self.step_ratio as isize;
94        let alpha_prod_t = self.alphas_cumprod[timestep];
95        let alpha_prod_t_prev = if prev_t >= 0 {
96            self.alphas_cumprod[prev_t as usize]
97        } else {
98            1.0
99        };
100        let current_beta_t = 1. - alpha_prod_t / alpha_prod_t_prev;
101
102        // For t > 0, compute predicted variance βt (see formula (6) and (7) from [the pdf](https://arxiv.org/pdf/2006.11239.pdf))
103        // and sample from it to get previous sample
104        // x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample
105        let variance = (1. - alpha_prod_t_prev) / (1. - alpha_prod_t) * current_beta_t;
106
107        // retrieve variance
108        match self.config.variance_type {
109            DDPMVarianceType::FixedSmall => variance.max(1e-20),
110            // for rl-diffuser https://arxiv.org/abs/2205.09991
111            DDPMVarianceType::FixedSmallLog => {
112                let variance = variance.max(1e-20).ln();
113                (variance * 0.5).exp()
114            }
115            DDPMVarianceType::FixedLarge => current_beta_t,
116            DDPMVarianceType::FixedLargeLog => current_beta_t.ln(),
117            DDPMVarianceType::Learned => variance,
118        }
119    }
120
121    pub fn timesteps(&self) -> &[usize] {
122        self.timesteps.as_slice()
123    }
124
125    ///  Ensures interchangeability with schedulers that need to scale the denoising model input
126    /// depending on the current timestep.
127    pub fn scale_model_input(&self, sample: Tensor, _timestep: usize) -> Tensor {
128        sample
129    }
130
131    pub fn step(&self, model_output: &Tensor, timestep: usize, sample: &Tensor) -> Result<Tensor> {
132        let prev_t = timestep as isize - self.step_ratio as isize;
133
134        // https://github.com/huggingface/diffusers/blob/df2b548e893ccb8a888467c2508756680df22821/src/diffusers/schedulers/scheduling_ddpm.py#L272
135        // 1. compute alphas, betas
136        let alpha_prod_t = self.alphas_cumprod[timestep];
137        let alpha_prod_t_prev = if prev_t >= 0 {
138            self.alphas_cumprod[prev_t as usize]
139        } else {
140            1.0
141        };
142        let beta_prod_t = 1. - alpha_prod_t;
143        let beta_prod_t_prev = 1. - alpha_prod_t_prev;
144        let current_alpha_t = alpha_prod_t / alpha_prod_t_prev;
145        let current_beta_t = 1. - current_alpha_t;
146
147        // 2. compute predicted original sample from predicted noise also called "predicted x_0" of formula (15)
148        let mut pred_original_sample = match self.config.prediction_type {
149            PredictionType::Epsilon => {
150                ((sample - model_output * beta_prod_t.sqrt())? / alpha_prod_t.sqrt())?
151            }
152            PredictionType::Sample => model_output.clone(),
153            PredictionType::VPrediction => {
154                ((sample * alpha_prod_t.sqrt())? - model_output * beta_prod_t.sqrt())?
155            }
156        };
157
158        // 3. clip predicted x_0
159        if self.config.clip_sample {
160            pred_original_sample = pred_original_sample.clamp(-1f32, 1f32)?;
161        }
162
163        // 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
164        // See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
165        let pred_original_sample_coeff = (alpha_prod_t_prev.sqrt() * current_beta_t) / beta_prod_t;
166        let current_sample_coeff = current_alpha_t.sqrt() * beta_prod_t_prev / beta_prod_t;
167
168        // 5. Compute predicted previous sample µ_t
169        // See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
170        let pred_prev_sample = ((&pred_original_sample * pred_original_sample_coeff)?
171            + sample * current_sample_coeff)?;
172
173        // https://github.com/huggingface/diffusers/blob/df2b548e893ccb8a888467c2508756680df22821/src/diffusers/schedulers/scheduling_ddpm.py#L305
174        // 6. Add noise
175        let mut variance = model_output.zeros_like()?;
176        if timestep > 0 {
177            let variance_noise = model_output.randn_like(0., 1.)?;
178            if self.config.variance_type == DDPMVarianceType::FixedSmallLog {
179                variance = (variance_noise * self.get_variance(timestep))?;
180            } else {
181                variance = (variance_noise * self.get_variance(timestep).sqrt())?;
182            }
183        }
184        &pred_prev_sample + variance
185    }
186
187    pub fn add_noise(
188        &self,
189        original_samples: &Tensor,
190        noise: Tensor,
191        timestep: usize,
192    ) -> Result<Tensor> {
193        (original_samples * self.alphas_cumprod[timestep].sqrt())?
194            + noise * (1. - self.alphas_cumprod[timestep]).sqrt()
195    }
196
197    pub fn init_noise_sigma(&self) -> f64 {
198        self.init_noise_sigma
199    }
200}