A diffusion process which can skip steps in a base diffusion process. :param use_timesteps: a collection (sequence or set) of timesteps from the original diffusion process to retain. :param kwargs: the kwargs to create the base diffusion process.
| 1242 | |
| 1243 | |
| 1244 | class SpacedDiffusion(GaussianDiffusion): |
| 1245 | """ |
| 1246 | A diffusion process which can skip steps in a base diffusion process. |
| 1247 | |
| 1248 | :param use_timesteps: a collection (sequence or set) of timesteps from the |
| 1249 | original diffusion process to retain. |
| 1250 | :param kwargs: the kwargs to create the base diffusion process. |
| 1251 | """ |
| 1252 | |
| 1253 | def __init__(self, use_timesteps, **kwargs): |
| 1254 | self.use_timesteps = set(use_timesteps) |
| 1255 | self.timestep_map = [] |
| 1256 | self.original_num_steps = len(kwargs["betas"]) |
| 1257 | |
| 1258 | base_diffusion = GaussianDiffusion(**kwargs) # pylint: disable=missing-kwoa |
| 1259 | last_alpha_cumprod = 1.0 |
| 1260 | new_betas = [] |
| 1261 | for i, alpha_cumprod in enumerate(base_diffusion.alphas_cumprod): |
| 1262 | if i in self.use_timesteps: |
| 1263 | new_betas.append(1 - alpha_cumprod / last_alpha_cumprod) |
| 1264 | last_alpha_cumprod = alpha_cumprod |
| 1265 | self.timestep_map.append(i) |
| 1266 | kwargs["betas"] = np.array(new_betas) |
| 1267 | super().__init__(**kwargs) |
| 1268 | |
| 1269 | def p_mean_variance(self, model, *args, **kwargs): |
| 1270 | return super().p_mean_variance(self._wrap_model(model), *args, **kwargs) |
| 1271 | |
| 1272 | def condition_mean(self, cond_fn, *args, **kwargs): |
| 1273 | return super().condition_mean(self._wrap_model(cond_fn), *args, **kwargs) |
| 1274 | |
| 1275 | def condition_score(self, cond_fn, *args, **kwargs): |
| 1276 | return super().condition_score(self._wrap_model(cond_fn), *args, **kwargs) |
| 1277 | |
| 1278 | def _wrap_model(self, model): |
| 1279 | if isinstance(model, _WrappedModel): |
| 1280 | return model |
| 1281 | return _WrappedModel(model, self.timestep_map, self.original_num_steps) |
| 1282 | |
| 1283 | |
| 1284 | class _WrappedModel: |