candle_transformers/models/stable_diffusion/
ddpm.rs1use 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 pub beta_start: f64,
18 pub beta_end: f64,
20 pub beta_schedule: BetaSchedule,
22 pub clip_sample: bool,
24 pub variance_type: DDPMVarianceType,
26 pub prediction_type: PredictionType,
28 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 let inference_steps = inference_steps.min(config.train_timesteps);
79 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 let variance = (1. - alpha_prod_t_prev) / (1. - alpha_prod_t) * current_beta_t;
106
107 match self.config.variance_type {
109 DDPMVarianceType::FixedSmall => variance.max(1e-20),
110 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 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 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 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 if self.config.clip_sample {
160 pred_original_sample = pred_original_sample.clamp(-1f32, 1f32)?;
161 }
162
163 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 let pred_prev_sample = ((&pred_original_sample * pred_original_sample_coeff)?
171 + sample * current_sample_coeff)?;
172
173 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}