| 116 | """ |
| 117 | |
| 118 | def __init__( |
| 119 | self, |
| 120 | *, |
| 121 | betas, |
| 122 | model_mean_type, |
| 123 | model_var_type, |
| 124 | loss_type, |
| 125 | rescale_timesteps=False, |
| 126 | ): |
| 127 | self.model_mean_type = model_mean_type |
| 128 | self.model_var_type = model_var_type |
| 129 | self.loss_type = loss_type |
| 130 | self.rescale_timesteps = rescale_timesteps |
| 131 | |
| 132 | # Use float64 for accuracy. |
| 133 | betas = np.array(betas, dtype=np.float64) |
| 134 | self.betas = betas |
| 135 | assert len(betas.shape) == 1, "betas must be 1-D" |
| 136 | assert (betas > 0).all() and (betas <= 1).all() |
| 137 | |
| 138 | self.num_timesteps = int(betas.shape[0]) |
| 139 | |
| 140 | alphas = 1.0 - betas |
| 141 | self.alphas_cumprod = np.cumprod(alphas, axis=0) |
| 142 | self.alphas_cumprod_prev = np.append(1.0, self.alphas_cumprod[:-1]) |
| 143 | self.alphas_cumprod_next = np.append(self.alphas_cumprod[1:], 0.0) |
| 144 | assert self.alphas_cumprod_prev.shape == (self.num_timesteps,) |
| 145 | |
| 146 | # calculations for diffusion q(x_t | x_{t-1}) and others |
| 147 | self.sqrt_alphas_cumprod = np.sqrt(self.alphas_cumprod) |
| 148 | self.sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - self.alphas_cumprod) |
| 149 | self.log_one_minus_alphas_cumprod = np.log(1.0 - self.alphas_cumprod) |
| 150 | self.sqrt_recip_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod) |
| 151 | self.sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod - 1) |
| 152 | |
| 153 | # calculations for posterior q(x_{t-1} | x_t, x_0) |
| 154 | self.posterior_variance = ( |
| 155 | betas * (1.0 - self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod) |
| 156 | ) |
| 157 | # log calculation clipped because the posterior variance is 0 at the |
| 158 | # beginning of the diffusion chain. |
| 159 | self.posterior_log_variance_clipped = np.log( |
| 160 | np.append(self.posterior_variance[1], self.posterior_variance[1:]) |
| 161 | ) |
| 162 | self.posterior_mean_coef1 = ( |
| 163 | betas * np.sqrt(self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod) |
| 164 | ) |
| 165 | self.posterior_mean_coef2 = ( |
| 166 | (1.0 - self.alphas_cumprod_prev) |
| 167 | * np.sqrt(alphas) |
| 168 | / (1.0 - self.alphas_cumprod) |
| 169 | ) |
| 170 | |
| 171 | def q_mean_variance(self, x_start, t): |
| 172 | """ |