Code of DDPM and DDIM
DDPM 公式 ✅ 公式 (15) $$ x_0 \approx \hat{x}_0 = \frac{x_t - \sqrt{1-\bar{\alpha}_t}\,\epsilon_\theta(x_t)} {\sqrt{\bar{\alpha}_t}} \tag{15} $$✅ 公式 (6) $$ q(x_{t-1} \mid x_t, x_0) = \mathcal{N}\bigl(x_{t-1};\; \mu_t(x_t, x_0),\; \tilde{\beta}_t I\bigr) \tag{6} $$ ✅ 公式 (7) $$ \mu_t(x_t, x_0) := \frac{\sqrt{\bar{\alpha}_{t-1}}\,\beta_t}{1-\bar{\alpha}_t}\, x_0 + \frac{\sqrt{\bar{\alpha}_t}\,(1-\bar{\alpha}_{t-1})}{1-\bar{\alpha}_t}\, x_t, \quad \tilde{\beta}_t := \frac{1-\bar{\alpha}_{t-1}}{1-\bar{\alpha}_t}\,\beta_t \tag{7} $$Code 1.计算 $\bar{\alpha}_t, \bar{\alpha}_{t-1}, \alpha_t$ t = timestep prev_t = self.previous_timestep(t) # 1. compute alphas, betas alpha_prod_t = self.alphas_cumprod[t] alpha_prod_t_prev = self.alphas_cumprod[prev_t] if prev_t >= 0 else self.one beta_prod_t = 1 - alpha_prod_t beta_prod_t_prev = 1 - alpha_prod_t_prev current_alpha_t = alpha_prod_t / alpha_prod_t_prev current_beta_t = 1 - current_alpha_t 2.计算 $$ x_0 \approx \hat{x}_0 = \frac{x_t - \sqrt{1-\bar{\alpha}_t}\,\epsilon_\theta(x_t)} {\sqrt{\bar{\alpha}_t}} \tag{15} $$ # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://huggingface.co/papers/2006.11239 pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5) 3.计算公式(7)里的$x_0和x_t前边的系数$ $\frac{\sqrt{\bar{\alpha}_{t-1}}\,\beta_t}{1-\bar{\alpha}_t}$ 和 $\frac{\sqrt{\bar{\alpha}_t}\,(1-\bar{\alpha}_{t-1})}{1-\bar{\alpha}_t}$ ...