Path: blob/master/modules/models/diffusion/uni_pc/uni_pc.py
3078 views
import torch1import math2import tqdm345class NoiseScheduleVP:6def __init__(7self,8schedule='discrete',9betas=None,10alphas_cumprod=None,11continuous_beta_0=0.1,12continuous_beta_1=20.,13):14"""Create a wrapper class for the forward SDE (VP type).1516***17Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t.18We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution images.19***2021The forward SDE ensures that the condition distribution q_{t|0}(x_t | x_0) = N ( alpha_t * x_0, sigma_t^2 * I ).22We further define lambda_t = log(alpha_t) - log(sigma_t), which is the half-logSNR (described in the DPM-Solver paper).23Therefore, we implement the functions for computing alpha_t, sigma_t and lambda_t. For t in [0, T], we have:2425log_alpha_t = self.marginal_log_mean_coeff(t)26sigma_t = self.marginal_std(t)27lambda_t = self.marginal_lambda(t)2829Moreover, as lambda(t) is an invertible function, we also support its inverse function:3031t = self.inverse_lambda(lambda_t)3233===============================================================3435We support both discrete-time DPMs (trained on n = 0, 1, ..., N-1) and continuous-time DPMs (trained on t in [t_0, T]).36371. For discrete-time DPMs:3839For discrete-time DPMs trained on n = 0, 1, ..., N-1, we convert the discrete steps to continuous time steps by:40t_i = (i + 1) / N41e.g. for N = 1000, we have t_0 = 1e-3 and T = t_{N-1} = 1.42We solve the corresponding diffusion ODE from time T = 1 to time t_0 = 1e-3.4344Args:45betas: A `torch.Tensor`. The beta array for the discrete-time DPM. (See the original DDPM paper for details)46alphas_cumprod: A `torch.Tensor`. The cumprod alphas for the discrete-time DPM. (See the original DDPM paper for details)4748Note that we always have alphas_cumprod = cumprod(betas). Therefore, we only need to set one of `betas` and `alphas_cumprod`.4950**Important**: Please pay special attention for the args for `alphas_cumprod`:51The `alphas_cumprod` is the \hat{alpha_n} arrays in the notations of DDPM. Specifically, DDPMs assume that52q_{t_n | 0}(x_{t_n} | x_0) = N ( \sqrt{\hat{alpha_n}} * x_0, (1 - \hat{alpha_n}) * I ).53Therefore, the notation \hat{alpha_n} is different from the notation alpha_t in DPM-Solver. In fact, we have54alpha_{t_n} = \sqrt{\hat{alpha_n}},55and56log(alpha_{t_n}) = 0.5 * log(\hat{alpha_n}).5758592. For continuous-time DPMs:6061We support two types of VPSDEs: linear (DDPM) and cosine (improved-DDPM). The hyperparameters for the noise62schedule are the default settings in DDPM and improved-DDPM:6364Args:65beta_min: A `float` number. The smallest beta for the linear schedule.66beta_max: A `float` number. The largest beta for the linear schedule.67cosine_s: A `float` number. The hyperparameter in the cosine schedule.68cosine_beta_max: A `float` number. The hyperparameter in the cosine schedule.69T: A `float` number. The ending time of the forward process.7071===============================================================7273Args:74schedule: A `str`. The noise schedule of the forward SDE. 'discrete' for discrete-time DPMs,75'linear' or 'cosine' for continuous-time DPMs.76Returns:77A wrapper object of the forward SDE (VP type).7879===============================================================8081Example:8283# For discrete-time DPMs, given betas (the beta array for n = 0, 1, ..., N - 1):84>>> ns = NoiseScheduleVP('discrete', betas=betas)8586# For discrete-time DPMs, given alphas_cumprod (the \hat{alpha_n} array for n = 0, 1, ..., N - 1):87>>> ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod)8889# For continuous-time DPMs (VPSDE), linear schedule:90>>> ns = NoiseScheduleVP('linear', continuous_beta_0=0.1, continuous_beta_1=20.)9192"""9394if schedule not in ['discrete', 'linear', 'cosine']:95raise ValueError(f"Unsupported noise schedule {schedule}. The schedule needs to be 'discrete' or 'linear' or 'cosine'")9697self.schedule = schedule98if schedule == 'discrete':99if betas is not None:100log_alphas = 0.5 * torch.log(1 - betas).cumsum(dim=0)101else:102assert alphas_cumprod is not None103log_alphas = 0.5 * torch.log(alphas_cumprod)104self.total_N = len(log_alphas)105self.T = 1.106self.t_array = torch.linspace(0., 1., self.total_N + 1)[1:].reshape((1, -1))107self.log_alpha_array = log_alphas.reshape((1, -1,))108else:109self.total_N = 1000110self.beta_0 = continuous_beta_0111self.beta_1 = continuous_beta_1112self.cosine_s = 0.008113self.cosine_beta_max = 999.114self.cosine_t_max = math.atan(self.cosine_beta_max * (1. + self.cosine_s) / math.pi) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s115self.cosine_log_alpha_0 = math.log(math.cos(self.cosine_s / (1. + self.cosine_s) * math.pi / 2.))116self.schedule = schedule117if schedule == 'cosine':118# For the cosine schedule, T = 1 will have numerical issues. So we manually set the ending time T.119# Note that T = 0.9946 may be not the optimal setting. However, we find it works well.120self.T = 0.9946121else:122self.T = 1.123124def marginal_log_mean_coeff(self, t):125"""126Compute log(alpha_t) of a given continuous-time label t in [0, T].127"""128if self.schedule == 'discrete':129return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device), self.log_alpha_array.to(t.device)).reshape((-1))130elif self.schedule == 'linear':131return -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0132elif self.schedule == 'cosine':133log_alpha_fn = lambda s: torch.log(torch.cos((s + self.cosine_s) / (1. + self.cosine_s) * math.pi / 2.))134log_alpha_t = log_alpha_fn(t) - self.cosine_log_alpha_0135return log_alpha_t136137def marginal_alpha(self, t):138"""139Compute alpha_t of a given continuous-time label t in [0, T].140"""141return torch.exp(self.marginal_log_mean_coeff(t))142143def marginal_std(self, t):144"""145Compute sigma_t of a given continuous-time label t in [0, T].146"""147return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))148149def marginal_lambda(self, t):150"""151Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].152"""153log_mean_coeff = self.marginal_log_mean_coeff(t)154log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))155return log_mean_coeff - log_std156157def inverse_lambda(self, lamb):158"""159Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t.160"""161if self.schedule == 'linear':162tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))163Delta = self.beta_0**2 + tmp164return tmp / (torch.sqrt(Delta) + self.beta_0) / (self.beta_1 - self.beta_0)165elif self.schedule == 'discrete':166log_alpha = -0.5 * torch.logaddexp(torch.zeros((1,)).to(lamb.device), -2. * lamb)167t = interpolate_fn(log_alpha.reshape((-1, 1)), torch.flip(self.log_alpha_array.to(lamb.device), [1]), torch.flip(self.t_array.to(lamb.device), [1]))168return t.reshape((-1,))169else:170log_alpha = -0.5 * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))171t_fn = lambda log_alpha_t: torch.arccos(torch.exp(log_alpha_t + self.cosine_log_alpha_0)) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s172t = t_fn(log_alpha)173return t174175176def model_wrapper(177model,178noise_schedule,179model_type="noise",180model_kwargs=None,181guidance_type="uncond",182#condition=None,183#unconditional_condition=None,184guidance_scale=1.,185classifier_fn=None,186classifier_kwargs=None,187):188"""Create a wrapper function for the noise prediction model.189190DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to191firstly wrap the model function to a noise prediction model that accepts the continuous time as the input.192193We support four types of the diffusion model by setting `model_type`:1941951. "noise": noise prediction model. (Trained by predicting noise).1961972. "x_start": data prediction model. (Trained by predicting the data x_0 at time 0).1981993. "v": velocity prediction model. (Trained by predicting the velocity).200The "v" prediction is derivation detailed in Appendix D of [1], and is used in Imagen-Video [2].201202[1] Salimans, Tim, and Jonathan Ho. "Progressive distillation for fast sampling of diffusion models."203arXiv preprint arXiv:2202.00512 (2022).204[2] Ho, Jonathan, et al. "Imagen Video: High Definition Video Generation with Diffusion Models."205arXiv preprint arXiv:2210.02303 (2022).2062074. "score": marginal score function. (Trained by denoising score matching).208Note that the score function and the noise prediction model follows a simple relationship:209```210noise(x_t, t) = -sigma_t * score(x_t, t)211```212213We support three types of guided sampling by DPMs by setting `guidance_type`:2141. "uncond": unconditional sampling by DPMs.215The input `model` has the following format:216``217model(x, t_input, **model_kwargs) -> noise | x_start | v | score218``2192202. "classifier": classifier guidance sampling [3] by DPMs and another classifier.221The input `model` has the following format:222``223model(x, t_input, **model_kwargs) -> noise | x_start | v | score224``225226The input `classifier_fn` has the following format:227``228classifier_fn(x, t_input, cond, **classifier_kwargs) -> logits(x, t_input, cond)229``230231[3] P. Dhariwal and A. Q. Nichol, "Diffusion models beat GANs on image synthesis,"232in Advances in Neural Information Processing Systems, vol. 34, 2021, pp. 8780-8794.2332343. "classifier-free": classifier-free guidance sampling by conditional DPMs.235The input `model` has the following format:236``237model(x, t_input, cond, **model_kwargs) -> noise | x_start | v | score238``239And if cond == `unconditional_condition`, the model output is the unconditional DPM output.240241[4] Ho, Jonathan, and Tim Salimans. "Classifier-free diffusion guidance."242arXiv preprint arXiv:2207.12598 (2022).243244245The `t_input` is the time label of the model, which may be discrete-time labels (i.e. 0 to 999)246or continuous-time labels (i.e. epsilon to T).247248We wrap the model function to accept only `x` and `t_continuous` as inputs, and outputs the predicted noise:249``250def model_fn(x, t_continuous) -> noise:251t_input = get_model_input_time(t_continuous)252return noise_pred(model, x, t_input, **model_kwargs)253``254where `t_continuous` is the continuous time labels (i.e. epsilon to T). And we use `model_fn` for DPM-Solver.255256===============================================================257258Args:259model: A diffusion model with the corresponding format described above.260noise_schedule: A noise schedule object, such as NoiseScheduleVP.261model_type: A `str`. The parameterization type of the diffusion model.262"noise" or "x_start" or "v" or "score".263model_kwargs: A `dict`. A dict for the other inputs of the model function.264guidance_type: A `str`. The type of the guidance for sampling.265"uncond" or "classifier" or "classifier-free".266condition: A pytorch tensor. The condition for the guided sampling.267Only used for "classifier" or "classifier-free" guidance type.268unconditional_condition: A pytorch tensor. The condition for the unconditional sampling.269Only used for "classifier-free" guidance type.270guidance_scale: A `float`. The scale for the guided sampling.271classifier_fn: A classifier function. Only used for the classifier guidance.272classifier_kwargs: A `dict`. A dict for the other inputs of the classifier function.273Returns:274A noise prediction model that accepts the noised data and the continuous time as the inputs.275"""276277model_kwargs = model_kwargs or {}278classifier_kwargs = classifier_kwargs or {}279280def get_model_input_time(t_continuous):281"""282Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time.283For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N].284For continuous-time DPMs, we just use `t_continuous`.285"""286if noise_schedule.schedule == 'discrete':287return (t_continuous - 1. / noise_schedule.total_N) * 1000.288else:289return t_continuous290291def noise_pred_fn(x, t_continuous, cond=None):292if t_continuous.reshape((-1,)).shape[0] == 1:293t_continuous = t_continuous.expand((x.shape[0]))294t_input = get_model_input_time(t_continuous)295if cond is None:296output = model(x, t_input, None, **model_kwargs)297else:298output = model(x, t_input, cond, **model_kwargs)299if model_type == "noise":300return output301elif model_type == "x_start":302alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)303dims = x.dim()304return (x - expand_dims(alpha_t, dims) * output) / expand_dims(sigma_t, dims)305elif model_type == "v":306alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)307dims = x.dim()308return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x309elif model_type == "score":310sigma_t = noise_schedule.marginal_std(t_continuous)311dims = x.dim()312return -expand_dims(sigma_t, dims) * output313314def cond_grad_fn(x, t_input, condition):315"""316Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t).317"""318with torch.enable_grad():319x_in = x.detach().requires_grad_(True)320log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs)321return torch.autograd.grad(log_prob.sum(), x_in)[0]322323def model_fn(x, t_continuous, condition, unconditional_condition):324"""325The noise prediction model function that is used for DPM-Solver.326"""327if t_continuous.reshape((-1,)).shape[0] == 1:328t_continuous = t_continuous.expand((x.shape[0]))329if guidance_type == "uncond":330return noise_pred_fn(x, t_continuous)331elif guidance_type == "classifier":332assert classifier_fn is not None333t_input = get_model_input_time(t_continuous)334cond_grad = cond_grad_fn(x, t_input, condition)335sigma_t = noise_schedule.marginal_std(t_continuous)336noise = noise_pred_fn(x, t_continuous)337return noise - guidance_scale * expand_dims(sigma_t, dims=cond_grad.dim()) * cond_grad338elif guidance_type == "classifier-free":339if guidance_scale == 1. or unconditional_condition is None:340return noise_pred_fn(x, t_continuous, cond=condition)341else:342x_in = torch.cat([x] * 2)343t_in = torch.cat([t_continuous] * 2)344if isinstance(condition, dict):345assert isinstance(unconditional_condition, dict)346c_in = {}347for k in condition:348if isinstance(condition[k], list):349c_in[k] = [torch.cat([350unconditional_condition[k][i],351condition[k][i]]) for i in range(len(condition[k]))]352else:353c_in[k] = torch.cat([354unconditional_condition[k],355condition[k]])356elif isinstance(condition, list):357c_in = []358assert isinstance(unconditional_condition, list)359for i in range(len(condition)):360c_in.append(torch.cat([unconditional_condition[i], condition[i]]))361else:362c_in = torch.cat([unconditional_condition, condition])363noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2)364return noise_uncond + guidance_scale * (noise - noise_uncond)365366assert model_type in ["noise", "x_start", "v"]367assert guidance_type in ["uncond", "classifier", "classifier-free"]368return model_fn369370371class UniPC:372def __init__(373self,374model_fn,375noise_schedule,376predict_x0=True,377thresholding=False,378max_val=1.,379variant='bh1',380condition=None,381unconditional_condition=None,382before_sample=None,383after_sample=None,384after_update=None385):386"""Construct a UniPC.387388We support both data_prediction and noise_prediction.389"""390self.model_fn_ = model_fn391self.noise_schedule = noise_schedule392self.variant = variant393self.predict_x0 = predict_x0394self.thresholding = thresholding395self.max_val = max_val396self.condition = condition397self.unconditional_condition = unconditional_condition398self.before_sample = before_sample399self.after_sample = after_sample400self.after_update = after_update401402def dynamic_thresholding_fn(self, x0, t=None):403"""404The dynamic thresholding method.405"""406dims = x0.dim()407p = self.dynamic_thresholding_ratio408s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)409s = expand_dims(torch.maximum(s, self.thresholding_max_val * torch.ones_like(s).to(s.device)), dims)410x0 = torch.clamp(x0, -s, s) / s411return x0412413def model(self, x, t):414cond = self.condition415uncond = self.unconditional_condition416if self.before_sample is not None:417x, t, cond, uncond = self.before_sample(x, t, cond, uncond)418res = self.model_fn_(x, t, cond, uncond)419if self.after_sample is not None:420x, t, cond, uncond, res = self.after_sample(x, t, cond, uncond, res)421422if isinstance(res, tuple):423# (None, pred_x0)424res = res[1]425426return res427428def noise_prediction_fn(self, x, t):429"""430Return the noise prediction model.431"""432return self.model(x, t)433434def data_prediction_fn(self, x, t):435"""436Return the data prediction model (with thresholding).437"""438noise = self.noise_prediction_fn(x, t)439dims = x.dim()440alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t)441x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims)442if self.thresholding:443p = 0.995 # A hyperparameter in the paper of "Imagen" [1].444s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)445s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims)446x0 = torch.clamp(x0, -s, s) / s447return x0448449def model_fn(self, x, t):450"""451Convert the model to the noise prediction model or the data prediction model.452"""453if self.predict_x0:454return self.data_prediction_fn(x, t)455else:456return self.noise_prediction_fn(x, t)457458def get_time_steps(self, skip_type, t_T, t_0, N, device):459"""Compute the intermediate time steps for sampling.460"""461if skip_type == 'logSNR':462lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device))463lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device))464logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device)465return self.noise_schedule.inverse_lambda(logSNR_steps)466elif skip_type == 'time_uniform':467return torch.linspace(t_T, t_0, N + 1).to(device)468elif skip_type == 'time_quadratic':469t_order = 2470t = torch.linspace(t_T**(1. / t_order), t_0**(1. / t_order), N + 1).pow(t_order).to(device)471return t472else:473raise ValueError(f"Unsupported skip_type {skip_type}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'")474475def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device):476"""477Get the order of each step for sampling by the singlestep DPM-Solver.478"""479if order == 3:480K = steps // 3 + 1481if steps % 3 == 0:482orders = [3,] * (K - 2) + [2, 1]483elif steps % 3 == 1:484orders = [3,] * (K - 1) + [1]485else:486orders = [3,] * (K - 1) + [2]487elif order == 2:488if steps % 2 == 0:489K = steps // 2490orders = [2,] * K491else:492K = steps // 2 + 1493orders = [2,] * (K - 1) + [1]494elif order == 1:495K = steps496orders = [1,] * steps497else:498raise ValueError("'order' must be '1' or '2' or '3'.")499if skip_type == 'logSNR':500# To reproduce the results in DPM-Solver paper501timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device)502else:503timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[torch.cumsum(torch.tensor([0,] + orders), 0).to(device)]504return timesteps_outer, orders505506def denoise_to_zero_fn(self, x, s):507"""508Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization.509"""510return self.data_prediction_fn(x, s)511512def multistep_uni_pc_update(self, x, model_prev_list, t_prev_list, t, order, **kwargs):513if len(t.shape) == 0:514t = t.view(-1)515if 'bh' in self.variant:516return self.multistep_uni_pc_bh_update(x, model_prev_list, t_prev_list, t, order, **kwargs)517else:518assert self.variant == 'vary_coeff'519return self.multistep_uni_pc_vary_update(x, model_prev_list, t_prev_list, t, order, **kwargs)520521def multistep_uni_pc_vary_update(self, x, model_prev_list, t_prev_list, t, order, use_corrector=True):522#print(f'using unified predictor-corrector with order {order} (solver type: vary coeff)')523ns = self.noise_schedule524assert order <= len(model_prev_list)525526# first compute rks527t_prev_0 = t_prev_list[-1]528lambda_prev_0 = ns.marginal_lambda(t_prev_0)529lambda_t = ns.marginal_lambda(t)530model_prev_0 = model_prev_list[-1]531sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)532log_alpha_t = ns.marginal_log_mean_coeff(t)533alpha_t = torch.exp(log_alpha_t)534535h = lambda_t - lambda_prev_0536537rks = []538D1s = []539for i in range(1, order):540t_prev_i = t_prev_list[-(i + 1)]541model_prev_i = model_prev_list[-(i + 1)]542lambda_prev_i = ns.marginal_lambda(t_prev_i)543rk = (lambda_prev_i - lambda_prev_0) / h544rks.append(rk)545D1s.append((model_prev_i - model_prev_0) / rk)546547rks.append(1.)548rks = torch.tensor(rks, device=x.device)549550K = len(rks)551# build C matrix552C = []553554col = torch.ones_like(rks)555for k in range(1, K + 1):556C.append(col)557col = col * rks / (k + 1)558C = torch.stack(C, dim=1)559560if len(D1s) > 0:561D1s = torch.stack(D1s, dim=1) # (B, K)562C_inv_p = torch.linalg.inv(C[:-1, :-1])563A_p = C_inv_p564565if use_corrector:566#print('using corrector')567C_inv = torch.linalg.inv(C)568A_c = C_inv569570hh = -h if self.predict_x0 else h571h_phi_1 = torch.expm1(hh)572h_phi_ks = []573factorial_k = 1574h_phi_k = h_phi_1575for k in range(1, K + 2):576h_phi_ks.append(h_phi_k)577h_phi_k = h_phi_k / hh - 1 / factorial_k578factorial_k *= (k + 1)579580model_t = None581if self.predict_x0:582x_t_ = (583sigma_t / sigma_prev_0 * x584- alpha_t * h_phi_1 * model_prev_0585)586# now predictor587x_t = x_t_588if len(D1s) > 0:589# compute the residuals for predictor590for k in range(K - 1):591x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k])592# now corrector593if use_corrector:594model_t = self.model_fn(x_t, t)595D1_t = (model_t - model_prev_0)596x_t = x_t_597k = 0598for k in range(K - 1):599x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1])600x_t = x_t - alpha_t * h_phi_ks[K] * (D1_t * A_c[k][-1])601else:602log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)603x_t_ = (604(torch.exp(log_alpha_t - log_alpha_prev_0)) * x605- (sigma_t * h_phi_1) * model_prev_0606)607# now predictor608x_t = x_t_609if len(D1s) > 0:610# compute the residuals for predictor611for k in range(K - 1):612x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k])613# now corrector614if use_corrector:615model_t = self.model_fn(x_t, t)616D1_t = (model_t - model_prev_0)617x_t = x_t_618k = 0619for k in range(K - 1):620x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1])621x_t = x_t - sigma_t * h_phi_ks[K] * (D1_t * A_c[k][-1])622return x_t, model_t623624def multistep_uni_pc_bh_update(self, x, model_prev_list, t_prev_list, t, order, x_t=None, use_corrector=True):625#print(f'using unified predictor-corrector with order {order} (solver type: B(h))')626ns = self.noise_schedule627assert order <= len(model_prev_list)628dims = x.dim()629630# first compute rks631t_prev_0 = t_prev_list[-1]632lambda_prev_0 = ns.marginal_lambda(t_prev_0)633lambda_t = ns.marginal_lambda(t)634model_prev_0 = model_prev_list[-1]635sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)636log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)637alpha_t = torch.exp(log_alpha_t)638639h = lambda_t - lambda_prev_0640641rks = []642D1s = []643for i in range(1, order):644t_prev_i = t_prev_list[-(i + 1)]645model_prev_i = model_prev_list[-(i + 1)]646lambda_prev_i = ns.marginal_lambda(t_prev_i)647rk = ((lambda_prev_i - lambda_prev_0) / h)[0]648rks.append(rk)649D1s.append((model_prev_i - model_prev_0) / rk)650651rks.append(1.)652rks = torch.tensor(rks, device=x.device)653654R = []655b = []656657hh = -h[0] if self.predict_x0 else h[0]658h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1659h_phi_k = h_phi_1 / hh - 1660661factorial_i = 1662663if self.variant == 'bh1':664B_h = hh665elif self.variant == 'bh2':666B_h = torch.expm1(hh)667else:668raise NotImplementedError()669670for i in range(1, order + 1):671R.append(torch.pow(rks, i - 1))672b.append(h_phi_k * factorial_i / B_h)673factorial_i *= (i + 1)674h_phi_k = h_phi_k / hh - 1 / factorial_i675676R = torch.stack(R)677b = torch.tensor(b, device=x.device)678679# now predictor680use_predictor = len(D1s) > 0 and x_t is None681if len(D1s) > 0:682D1s = torch.stack(D1s, dim=1) # (B, K)683if x_t is None:684# for order 2, we use a simplified version685if order == 2:686rhos_p = torch.tensor([0.5], device=b.device)687else:688rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1])689else:690D1s = None691692if use_corrector:693#print('using corrector')694# for order 1, we use a simplified version695if order == 1:696rhos_c = torch.tensor([0.5], device=b.device)697else:698rhos_c = torch.linalg.solve(R, b)699700model_t = None701if self.predict_x0:702x_t_ = (703expand_dims(sigma_t / sigma_prev_0, dims) * x704- expand_dims(alpha_t * h_phi_1, dims)* model_prev_0705)706707if x_t is None:708if use_predictor:709pred_res = torch.einsum('k,bkchw->bchw', rhos_p, D1s)710else:711pred_res = 0712x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * pred_res713714if use_corrector:715model_t = self.model_fn(x_t, t)716if D1s is not None:717corr_res = torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s)718else:719corr_res = 0720D1_t = (model_t - model_prev_0)721x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t)722else:723x_t_ = (724expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x725- expand_dims(sigma_t * h_phi_1, dims) * model_prev_0726)727if x_t is None:728if use_predictor:729pred_res = torch.einsum('k,bkchw->bchw', rhos_p, D1s)730else:731pred_res = 0732x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * pred_res733734if use_corrector:735model_t = self.model_fn(x_t, t)736if D1s is not None:737corr_res = torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s)738else:739corr_res = 0740D1_t = (model_t - model_prev_0)741x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t)742return x_t, model_t743744745def sample(self, x, steps=20, t_start=None, t_end=None, order=3, skip_type='time_uniform',746method='singlestep', lower_order_final=True, denoise_to_zero=False, solver_type='dpm_solver',747atol=0.0078, rtol=0.05, corrector=False,748):749t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end750t_T = self.noise_schedule.T if t_start is None else t_start751device = x.device752if method == 'multistep':753assert steps >= order, "UniPC order must be < sampling steps"754timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device)755#print(f"Running UniPC Sampling with {timesteps.shape[0]} timesteps, order {order}")756assert timesteps.shape[0] - 1 == steps757with torch.no_grad():758vec_t = timesteps[0].expand((x.shape[0]))759model_prev_list = [self.model_fn(x, vec_t)]760t_prev_list = [vec_t]761with tqdm.tqdm(total=steps) as pbar:762# Init the first `order` values by lower order multistep DPM-Solver.763for init_order in range(1, order):764vec_t = timesteps[init_order].expand(x.shape[0])765x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, init_order, use_corrector=True)766if model_x is None:767model_x = self.model_fn(x, vec_t)768if self.after_update is not None:769self.after_update(x, model_x)770model_prev_list.append(model_x)771t_prev_list.append(vec_t)772pbar.update()773774for step in range(order, steps + 1):775vec_t = timesteps[step].expand(x.shape[0])776if lower_order_final:777step_order = min(order, steps + 1 - step)778else:779step_order = order780#print('this step order:', step_order)781if step == steps:782#print('do not run corrector at the last step')783use_corrector = False784else:785use_corrector = True786x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, step_order, use_corrector=use_corrector)787if self.after_update is not None:788self.after_update(x, model_x)789for i in range(order - 1):790t_prev_list[i] = t_prev_list[i + 1]791model_prev_list[i] = model_prev_list[i + 1]792t_prev_list[-1] = vec_t793# We do not need to evaluate the final model value.794if step < steps:795if model_x is None:796model_x = self.model_fn(x, vec_t)797model_prev_list[-1] = model_x798pbar.update()799else:800raise NotImplementedError()801if denoise_to_zero:802x = self.denoise_to_zero_fn(x, torch.ones((x.shape[0],)).to(device) * t_0)803return x804805806#############################################################807# other utility functions808#############################################################809810def interpolate_fn(x, xp, yp):811"""812A piecewise linear function y = f(x), using xp and yp as keypoints.813We implement f(x) in a differentiable way (i.e. applicable for autograd).814The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.)815816Args:817x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver).818xp: PyTorch tensor with shape [C, K], where K is the number of keypoints.819yp: PyTorch tensor with shape [C, K].820Returns:821The function values f(x), with shape [N, C].822"""823N, K = x.shape[0], xp.shape[1]824all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2)825sorted_all_x, x_indices = torch.sort(all_x, dim=2)826x_idx = torch.argmin(x_indices, dim=2)827cand_start_idx = x_idx - 1828start_idx = torch.where(829torch.eq(x_idx, 0),830torch.tensor(1, device=x.device),831torch.where(832torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,833),834)835end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1)836start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2)837end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2)838start_idx2 = torch.where(839torch.eq(x_idx, 0),840torch.tensor(0, device=x.device),841torch.where(842torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,843),844)845y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1)846start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2)847end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2)848cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x)849return cand850851852def expand_dims(v, dims):853"""854Expand the tensor `v` to the dim `dims`.855856Args:857`v`: a PyTorch tensor with shape [N].858`dim`: a `int`.859Returns:860a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`.861"""862return v[(...,) + (None,)*(dims - 1)]863864865