|
| 1 | +# Copyright 2022 NVIDIA and The HuggingFace Team. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +from typing import Union |
| 17 | + |
| 18 | +import numpy as np |
| 19 | +import torch |
| 20 | + |
| 21 | +from ..configuration_utils import ConfigMixin, register_to_config |
| 22 | +from .scheduling_utils import SchedulerMixin |
| 23 | + |
| 24 | + |
| 25 | +class KarrasVeScheduler(SchedulerMixin, ConfigMixin): |
| 26 | + """ |
| 27 | + Stochastic sampling from Karras et al. [1] tailored to the Variance-Expanding (VE) models [2]. |
| 28 | + Use Algorithm 2 and the VE column of Table 1 from [1] for reference. |
| 29 | +
|
| 30 | + [1] Karras, Tero, et al. "Elucidating the Design Space of Diffusion-Based Generative Models." https://arxiv.org/abs/2206.00364 |
| 31 | + [2] Song, Yang, et al. "Score-based generative modeling through stochastic differential equations." https://arxiv.org/abs/2011.13456 |
| 32 | + """ |
| 33 | + |
| 34 | + @register_to_config |
| 35 | + def __init__( |
| 36 | + self, |
| 37 | + sigma_min=0.02, |
| 38 | + sigma_max=100, |
| 39 | + s_noise=1.007, |
| 40 | + s_churn=80, |
| 41 | + s_min=0.05, |
| 42 | + s_max=50, |
| 43 | + tensor_format="pt", |
| 44 | + ): |
| 45 | + """ |
| 46 | + For more details on the parameters, see the original paper's Appendix E.: |
| 47 | + "Elucidating the Design Space of Diffusion-Based Generative Models." https://arxiv.org/abs/2206.00364. |
| 48 | + The grid search values used to find the optimal {s_noise, s_churn, s_min, s_max} for a specific model |
| 49 | + are described in Table 5 of the paper. |
| 50 | +
|
| 51 | + Args: |
| 52 | + sigma_min (`float`): minimum noise magnitude |
| 53 | + sigma_max (`float`): maximum noise magnitude |
| 54 | + s_noise (`float`): the amount of additional noise to counteract loss of detail during sampling. |
| 55 | + A reasonable range is [1.000, 1.011]. |
| 56 | + s_churn (`float`): the parameter controlling the overall amount of stochasticity. |
| 57 | + A reasonable range is [0, 100]. |
| 58 | + s_min (`float`): the start value of the sigma range where we add noise (enable stochasticity). |
| 59 | + A reasonable range is [0, 10]. |
| 60 | + s_max (`float`): the end value of the sigma range where we add noise. |
| 61 | + A reasonable range is [0.2, 80]. |
| 62 | + """ |
| 63 | + # setable values |
| 64 | + self.num_inference_steps = None |
| 65 | + self.timesteps = None |
| 66 | + self.schedule = None # sigma(t_i) |
| 67 | + |
| 68 | + self.tensor_format = tensor_format |
| 69 | + self.set_format(tensor_format=tensor_format) |
| 70 | + |
| 71 | + def set_timesteps(self, num_inference_steps): |
| 72 | + self.num_inference_steps = num_inference_steps |
| 73 | + self.timesteps = np.arange(0, self.num_inference_steps)[::-1].copy() |
| 74 | + self.schedule = [ |
| 75 | + (self.sigma_max * (self.sigma_min**2 / self.sigma_max**2) ** (i / (num_inference_steps - 1))) |
| 76 | + for i in self.timesteps |
| 77 | + ] |
| 78 | + self.schedule = np.array(self.schedule, dtype=np.float32) |
| 79 | + |
| 80 | + self.set_format(tensor_format=self.tensor_format) |
| 81 | + |
| 82 | + def add_noise_to_input(self, sample, sigma, generator=None): |
| 83 | + """ |
| 84 | + Explicit Langevin-like "churn" step of adding noise to the sample according to |
| 85 | + a factor gamma_i ≥ 0 to reach a higher noise level sigma_hat = sigma_i + gamma_i*sigma_i. |
| 86 | + """ |
| 87 | + if self.s_min <= sigma <= self.s_max: |
| 88 | + gamma = min(self.s_churn / self.num_inference_steps, 2**0.5 - 1) |
| 89 | + else: |
| 90 | + gamma = 0 |
| 91 | + |
| 92 | + # sample eps ~ N(0, S_noise^2 * I) |
| 93 | + eps = self.s_noise * torch.randn(sample.shape, generator=generator).to(sample.device) |
| 94 | + sigma_hat = sigma + gamma * sigma |
| 95 | + sample_hat = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) |
| 96 | + |
| 97 | + return sample_hat, sigma_hat |
| 98 | + |
| 99 | + def step( |
| 100 | + self, |
| 101 | + model_output: Union[torch.FloatTensor, np.ndarray], |
| 102 | + sigma_hat: float, |
| 103 | + sigma_prev: float, |
| 104 | + sample_hat: Union[torch.FloatTensor, np.ndarray], |
| 105 | + ): |
| 106 | + pred_original_sample = sample_hat + sigma_hat * model_output |
| 107 | + derivative = (sample_hat - pred_original_sample) / sigma_hat |
| 108 | + sample_prev = sample_hat + (sigma_prev - sigma_hat) * derivative |
| 109 | + |
| 110 | + return {"prev_sample": sample_prev, "derivative": derivative} |
| 111 | + |
| 112 | + def step_correct( |
| 113 | + self, |
| 114 | + model_output: Union[torch.FloatTensor, np.ndarray], |
| 115 | + sigma_hat: float, |
| 116 | + sigma_prev: float, |
| 117 | + sample_hat: Union[torch.FloatTensor, np.ndarray], |
| 118 | + sample_prev: Union[torch.FloatTensor, np.ndarray], |
| 119 | + derivative: Union[torch.FloatTensor, np.ndarray], |
| 120 | + ): |
| 121 | + pred_original_sample = sample_prev + sigma_prev * model_output |
| 122 | + derivative_corr = (sample_prev - pred_original_sample) / sigma_prev |
| 123 | + sample_prev = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) |
| 124 | + return {"prev_sample": sample_prev, "derivative": derivative_corr} |
| 125 | + |
| 126 | + def add_noise(self, original_samples, noise, timesteps): |
| 127 | + raise NotImplementedError() |
0 commit comments