# This code is based on https://github.com/openai/guided-diffusion """ This code started out as a PyTorch port of Ho et al's diffusion models: https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py Docstrings have been added, as well as DDIM sampling and a new collection of beta schedules. """ import enum import math import numpy as np import torch import torch as th from copy import deepcopy from motion.diffusion.nn import sum_flat from motion.dataset.recover_smr import * from SMPLX.rotation_conversions import rotation_6d_to_matrix, matrix_to_axis_angle # os.environ['CUDA_LAUNCH_BLOCKING'] = '1' def get_named_beta_schedule(schedule_name, num_diffusion_timesteps, scale_betas=1.): """ Get a pre-defined beta schedule for the given name. The beta schedule library consists of beta schedules which remain similar in the limit of num_diffusion_timesteps. Beta schedules may be added, but should not be removed or changed once they are committed to maintain backwards compatibility. """ if schedule_name == "linear": # Linear schedule from Ho et al, extended to work for any number of # diffusion steps. scale = scale_betas * 1000 / num_diffusion_timesteps beta_start = scale * 0.0001 beta_end = scale * 0.02 return np.linspace( beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64 ) elif schedule_name == "cosine": return betas_for_alpha_bar( num_diffusion_timesteps, lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2, ### t=0->1, t=1->0, t=2->1, t=3->0, 近似于 0,1 交替输入 ) else: raise NotImplementedError(f"unknown beta schedule: {schedule_name}") def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999): """ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of (1-beta) over time from t = [0,1]. :param num_diffusion_timesteps: the number of betas to produce. :param alpha_bar: a lambda that takes an argument t from 0 to 1 and produces the cumulative product of (1-beta) up to that part of the diffusion process. :param max_beta: the maximum beta to use; use values lower than 1 to prevent singularities. """ betas = [] for i in range(num_diffusion_timesteps): t1 = i / num_diffusion_timesteps t2 = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta)) return np.array(betas) class ModelMeanType(enum.Enum): """ Which type of output the model predicts. """ PREVIOUS_X = enum.auto() # the model predicts x_{t-1} START_X = enum.auto() # the model predicts x_0 EPSILON = enum.auto() # the model predicts epsilon class ModelVarType(enum.Enum): """ What is used as the model's output variance. The LEARNED_RANGE option has been added to allow the model to predict values between FIXED_SMALL and FIXED_LARGE, making its job easier. """ LEARNED = enum.auto() FIXED_SMALL = enum.auto() FIXED_LARGE = enum.auto() LEARNED_RANGE = enum.auto() class LossType(enum.Enum): MSE = enum.auto() # use raw MSE loss (and KL when learning variances) RESCALED_MSE = ( enum.auto() ) # use raw MSE loss (with RESCALED_KL when learning variances) KL = enum.auto() # use the variational lower-bound RESCALED_KL = enum.auto() # like KL, but rescale to estimate the full VLB def is_vb(self): return self == LossType.KL or self == LossType.RESCALED_KL class GaussianDiffusion: """ Utilities for training and sampling diffusion models. Ported directly from here, and then adapted over time to further experimentation. https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py#L42 :param betas: a 1-D numpy array of betas for each diffusion timestep, starting at T and going to 1. :param model_mean_type: a ModelMeanType determining what the model outputs. :param model_var_type: a ModelVarType determining how variance is output. :param loss_type: a LossType determining the loss function to use. :param rescale_timesteps: if True, pass floating point timesteps into the model so that they are always scaled like in the original paper (0 to 1000). """ def __init__( self, *, betas, model_mean_type, model_var_type, loss_type, rescale_timesteps=False, rep="t2m" ): self.model_mean_type = model_mean_type self.model_var_type = model_var_type self.loss_type = loss_type self.rescale_timesteps = rescale_timesteps self.rep = rep # Use float64 for accuracy. betas = np.array(betas, dtype=np.float64) self.betas = betas assert len(betas.shape) == 1, "betas must be 1-D" assert (betas > 0).all() and (betas <= 1).all() self.num_timesteps = int(betas.shape[0]) alphas = 1.0 - betas self.alphas_cumprod = np.cumprod(alphas, axis=0) #### 累乘变成 alpha_bar self.alphas_cumprod_prev = np.append(1.0, self.alphas_cumprod[:-1]) ### append 是合并, 意思是倒序排列,但是去掉把第一个换成 1 self.alphas_cumprod_next = np.append(self.alphas_cumprod[1:], 0.0) #### 正序排列,但是把第一个换成 0 并插到最后 assert self.alphas_cumprod_prev.shape == (self.num_timesteps,) # calculations for diffusion q(x_t | x_{t-1}) and others self.sqrt_alphas_cumprod = np.sqrt(self.alphas_cumprod) self.sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - self.alphas_cumprod) self.log_one_minus_alphas_cumprod = np.log(1.0 - self.alphas_cumprod) self.sqrt_recip_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod) self.sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod - 1) # calculations for posterior q(x_{t-1} | x_t, x_0) self.posterior_variance = ( ###### 计算 \mu(xt, x0) 的一部分 betas * (1.0 - self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod) ) # log calculation clipped because the posterior variance is 0 at the # beginning of the diffusion chain. self.posterior_log_variance_clipped = np.log( np.append(self.posterior_variance[1], self.posterior_variance[1:]) ) self.posterior_mean_coef1 = ( betas * np.sqrt(self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod) ) self.posterior_mean_coef2 = ( (1.0 - self.alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - self.alphas_cumprod) ) self.l2_loss = lambda a, b: (a - b) ** 2 # th.nn.MSELoss(reduction='none') # must be None for handling mask later on. def masked_l2(self, a, b, mask, addition_rotate_mask): loss = self.l2_loss(a, b) #### [bs, 263, 1, num_frames] loss = sum_flat(loss * mask.float() * addition_rotate_mask.float()) # gives \sigma_euclidean over unmasked elements ### [Batch] n_entries = a.shape[1] * a.shape[2] ##### BS * 263 * 1 * num_frame -> 263 non_zero_elements = sum_flat(mask) * n_entries mse_loss_val = loss / non_zero_elements return mse_loss_val def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = ( _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start ) variance = _extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = _extract_into_tensor( self.log_one_minus_alphas_cumprod, t, x_start.shape ) return mean, variance, log_variance def q_sample(self, x_start, t, noise=None, model_kwargs=None): """ Diffuse the dataset for a given number of diffusion steps. In other words, sample from q(x_t | x_0). :param x_start: the initial dataset batch. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :param noise: if specified, the split-out normal noise. :return: A noisy version of x_start. """ if noise is None: noise = th.randn_like(x_start) assert noise.shape == x_start.shape return ( ######### 前向传播 xt = self.sqrt_alphas_cumprod[t] * x0 + self.sqrt_one_minus_alphas_cumprod[t] * \epsilon _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise ) def q_posterior_mean_variance(self, x_start, x_t, t): """ Compute the mean and variance of the diffusion posterior: q(x_{t-1} | x_t, x_0) """ assert x_start.shape == x_t.shape posterior_mean = ( _extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + _extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = _extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = _extract_into_tensor( self.posterior_log_variance_clipped, t, x_t.shape ) assert ( posterior_mean.shape[0] == posterior_variance.shape[0] == posterior_log_variance_clipped.shape[0] == x_start.shape[0] ) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance( self, model, x, t, clip_denoised=True, denoised_fn=None, model_kwargs=None ): if model_kwargs is None: model_kwargs = {} B, C = x.shape[:2] assert t.shape == (B,) model_output = model(x, self._scale_timesteps(t), **model_kwargs) model_output = model_output["output"] x_t = x if 'inpainting_mask' in model_kwargs['y'].keys() and 'inpainted_motion' in model_kwargs['y'].keys(): inpainting_mask, inpainted_motion = model_kwargs['y']['inpainting_mask'], model_kwargs['y']['inpainted_motion'] assert self.model_mean_type == ModelMeanType.START_X, 'This feature supports only X_start pred for mow!' assert model_output.shape == inpainting_mask.shape == inpainted_motion.shape ones = torch.ones_like(inpainting_mask, dtype=torch.float, device=inpainting_mask.device) inpainting_mask = ones * inpainting_mask model_output = (model_output * (1 - inpainting_mask)) + (inpainted_motion * inpainting_mask) if self.model_var_type in [ModelVarType.LEARNED, ModelVarType.LEARNED_RANGE]: assert model_output.shape == (B, C * 2, *x.shape[2:]) model_output, model_var_values = th.split(model_output, C, dim=1) if self.model_var_type == ModelVarType.LEARNED: model_log_variance = model_var_values model_variance = th.exp(model_log_variance) else: min_log = _extract_into_tensor( self.posterior_log_variance_clipped, t, x.shape ) max_log = _extract_into_tensor(np.log(self.betas), t, x.shape) # The model_var_values is [-1, 1] for [min_var, max_var]. frac = (model_var_values + 1) / 2 model_log_variance = frac * max_log + (1 - frac) * min_log model_variance = th.exp(model_log_variance) else: model_variance, model_log_variance = { ModelVarType.FIXED_LARGE: ( np.append(self.posterior_variance[1], self.betas[1:]), np.log(np.append(self.posterior_variance[1], self.betas[1:])), ), ModelVarType.FIXED_SMALL: ( ############ USE IT self.posterior_variance, self.posterior_log_variance_clipped, ), }[self.model_var_type] model_variance = _extract_into_tensor(model_variance, t, x_t.shape) model_log_variance = _extract_into_tensor(model_log_variance, t, x_t.shape) def process_xstart(x): if denoised_fn is not None: x = denoised_fn(x) if clip_denoised: # print('clip_denoised', clip_denoised) return x.clamp(-1, 1) return x if self.model_mean_type == ModelMeanType.PREVIOUS_X: pred_xstart = process_xstart( self._predict_xstart_from_xprev(x_t=x_t, t=t, xprev=model_output) ) model_mean = model_output elif self.model_mean_type in [ModelMeanType.START_X, ModelMeanType.EPSILON]: # THIS IS US! if self.model_mean_type == ModelMeanType.START_X: pred_xstart = process_xstart(model_output) else: pred_xstart = process_xstart(self._predict_xstart_from_eps(x_t=x_t, t=t, eps=model_output)) model_mean, _, _ = self.q_posterior_mean_variance(x_start=pred_xstart, x_t=x_t, t=t) else: raise NotImplementedError(self.model_mean_type) assert (model_mean.shape == model_log_variance.shape == pred_xstart.shape == x_t.shape) return { "mean": model_mean, "variance": model_variance, "log_variance": model_log_variance, "pred_xstart": pred_xstart, } def _predict_xstart_from_eps(self, x_t, t, eps): assert x_t.shape == eps.shape return ( _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps ) def _predict_xstart_from_xprev(self, x_t, t, xprev): assert x_t.shape == xprev.shape return ( # (xprev - coef2*x_t) / coef1 _extract_into_tensor(1.0 / self.posterior_mean_coef1, t, x_t.shape) * xprev - _extract_into_tensor( self.posterior_mean_coef2 / self.posterior_mean_coef1, t, x_t.shape ) * x_t ) def _scale_timesteps(self, t): if self.rescale_timesteps: return t.float() * (1000.0 / self.num_timesteps) return t def p_sample( self, model, x, t, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, const_noise=False, ): """ Sample x_{t-1} from the model at the given timestep. :param model: the model to sample from. :param x: the current tensor at x_{t-1}. :param t: the value of t, starting at 0 for the first diffusion step. :param clip_denoised: if True, clip the x_start prediction to [-1, 1]. :param denoised_fn: if not None, a function which applies to the x_start prediction before it is used to sample. :param cond_fn: if not None, this is a gradient function that acts similarly to the model. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :return: a dict containing the following keys: - 'sample': a random sample from the model. - 'pred_xstart': a prediction of x_0. """ out = self.p_mean_variance( model, x, #### x 列表 t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, model_kwargs=model_kwargs, ) noise = th.randn_like(out["mean"]) if const_noise: noise = noise[[0]].repeat(out["mean"].shape[0], 1, 1, 1) nonzero_mask = ((t != 0).float().view(-1, *([1] * (len(out["mean"].shape) - 1)))) # no noise when t == 0 sample = out["mean"] + nonzero_mask * th.exp(0.5 * out["log_variance"]) * noise ## \mu + nonzero_mask * \std * noise return {"sample": sample, "pred_xstart": out["pred_xstart"]} def p_sample_loop( self, model, shape, noise=None, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, device=None, progress=False, skip_timesteps=0, init_image=None, randomize_class=False, cond_fn_with_grad=False, dump_steps=None, const_noise=False, unfolding_handshake=0, # 0 means no unfolding eval_mask=None ): """ Generate samples from the model. :param model: the model module. :param shape: the shape of the samples, (N, C, H, W). :param noise: if specified, the noise from the encoder to sample. Should be of the same shape as `shape`. :param clip_denoised: if True, clip x_start predictions to [-1, 1]. :param denoised_fn: if not None, a function which applies to the x_start prediction before it is used to sample. :param cond_fn: if not None, this is a gradient function that acts similarly to the model. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :param device: if specified, the device to create the samples on. If not specified, use a model parameter's device. :param progress: if True, show a tqdm progress bar. :param const_noise: If True, will noise all samples with the same noise throughout sampling :return: a non-differentiable batch of samples. """ final = None if dump_steps is not None: dump = [] for i, sample in enumerate(self.p_sample_loop_progressive( model, shape, noise=noise, clip_denoised=clip_denoised, denoised_fn=denoised_fn, cond_fn=cond_fn, model_kwargs=model_kwargs, device=device, progress=progress, skip_timesteps=skip_timesteps, init_image=init_image, randomize_class=randomize_class, cond_fn_with_grad=cond_fn_with_grad, const_noise=const_noise, eval_mask=eval_mask )): # unfolding if unfolding_handshake > 0: ''' first take 点这里 ''' alpha = torch.arange(0, unfolding_handshake, 1, device=sample['sample'].device) / unfolding_handshake for sample_i, len in zip(range(1, sample['sample'].shape[0]), model_kwargs['y']['lengths']): _suffix = sample['sample'][sample_i - 1, :, :, -unfolding_handshake + len:len] _prefix = sample['sample'][sample_i, :, :, :unfolding_handshake] try: _blend = (_suffix * (1 - alpha) + _prefix * alpha) except(RuntimeError): print("Error") sample['sample'][sample_i - 1, :, :, -unfolding_handshake + len:len] = _blend #### 混合操作,保证下一帧的 left = 这一帧的 right, 这样 double take 的时候才能直接用 right 覆盖 left sample['sample'][sample_i, :, :, :unfolding_handshake] = _blend if dump_steps is not None and i in dump_steps: dump.append(deepcopy(sample["sample"])) final = sample if dump_steps is not None: return dump res = {"output":final["sample"]} return res def p_sample_loop_progressive( self, model, shape, noise=None, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, device=None, progress=False, skip_timesteps=0, init_image=None, randomize_class=False, cond_fn_with_grad=False, const_noise=False, eval_mask=None ): """ Generate samples from the model and yield intermediate samples from each timestep of diffusion. Arguments are the same as p_sample_loop(). Returns a generator over dicts, where each dict is the return value of p_sample(). """ if device is None: device = next(model.parameters()).device assert isinstance(shape, (tuple, list)) if noise is not None: img = noise else: img = th.randn(*shape, device=device) if skip_timesteps and init_image is None: init_image = th.zeros_like(img) indices = list(range(self.num_timesteps - skip_timesteps))[::-1] #### [999, 998, ... 0] if init_image is not None: my_t = th.ones([shape[0]], device=device, dtype=th.long) * indices[0] img = self.q_sample(init_image, my_t, img, model_kwargs=model_kwargs) ''' 把 eval_mask 放在这里相当于初始化时若干帧的结果存在问题 如果把 eval_mask 放在循环中, 就相当于推理过程中指定位置一直在生成不同的错误帧 ''' if eval_mask is not None and img.shape[0] != 1: rand_img = torch.randperm(img.shape[0]) rand_img = img[rand_img] img = img * (1 - eval_mask) + rand_img * eval_mask elif eval_mask is not None and img.shape[0] == 1: rand_img = th.randn(*shape, device=device) img = img * (1 - eval_mask) + rand_img * eval_mask if progress: # Lazy import so that we don't depend on tqdm. from tqdm.auto import tqdm indices = tqdm(indices) for i in indices: t = th.tensor([i] * shape[0], device=device) ### t = [999] if randomize_class and 'y' in model_kwargs: model_kwargs['y'] = th.randint(low=0, high=model.num_classes, size=model_kwargs['y'].shape, device=model_kwargs['y'].device) with th.no_grad(): sample_fn = self.p_sample condition = deepcopy(model_kwargs) out = sample_fn( model, img, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, cond_fn=cond_fn, model_kwargs=condition, const_noise=const_noise, ) yield out img = out["sample"] ##### 最开始是随机噪声,然后会得到 999 的输出,然后得到 998 的输出,最后一步是预测的 x0 def training_losses(self, model, x_start, t, model_kwargs=None, noise=None): """ Compute training losses for a single timestep. :param model: the model to evaluate loss on. :param x_start: the [N x C x ...] tensor of inputs. 生成目标 x0 :param t: a batch of timestep indices. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :param noise: if specified, the specific Gaussian noise to try to remove. :return: a dict with the key "loss" containing a tensor of shape [N]. Some mean or variance settings may also have other keys. """ mask = model_kwargs['y']['mask'] if len(x_start.shape) == 3: x_start = x_start.permute(0, 2, 1).unsqueeze(2) elif len(x_start.shape) == 4: x_start = x_start.permute(0, 2, 3, 1) if self.rep == "smplx": addition_rotate_mask = torch.ones_like(x_start) # addition_rotate_mask = mask.repeat(1, x_start.shape[1], x_start.shape[2], 1) ### [bs, njoints, nfeats, nframes] # speed = x_start[..., 1::] - x_start[..., :-1] #### [bs, njoints, nfeats, nframes-1] # speed = speed.sum(dim=-1).sum(dim=-1) #### [bs, njoints] # nosub = speed == 0 #### find joints that have no change between different frames and not calculate loss function # addition_rotate_mask[nosub] = 0 else: addition_rotate_mask = torch.ones_like(x_start) if noise is None: noise = th.randn_like(x_start) x_t = self.q_sample(x_start, t, noise=noise, model_kwargs=model_kwargs) ###### 前向传播 x0 到 xt terms = {} if self.loss_type == LossType.MSE or self.loss_type == LossType.RESCALED_MSE: #### 默认用 mse 损失 model_output = model(x_t, self._scale_timesteps(t), **model_kwargs) #### mixup_res model_output = model_output["output"] #### [bs, 263, 1, nframes] -> [nfrmaes, bs, 512] -> [bs, 263, 1, nframes] if self.model_mean_type == ModelMeanType.START_X: target = x_start elif self.model_mean_type == ModelMeanType.EPSILON: target = noise elif self.model_mean_type == ModelMeanType.PREVIOUS_X: target = self.q_posterior_mean_variance(x_start=x_start, x_t=x_t, t=t)[0] assert model_output.shape == target.shape == x_start.shape terms["rot_mse"] = self.masked_l2(target, model_output, mask, addition_rotate_mask=addition_rotate_mask) terms["loss"] = terms["rot_mse"] else: raise NotImplementedError(self.loss_type) return terms def _extract_into_tensor(arr, timesteps, broadcast_shape): """ Extract values from a 1-D numpy array for a batch of indices. :param arr: the 1-D numpy array. :param timesteps: a tensor of indices into the array to extract. :param broadcast_shape: a larger shape of K dimensions with the batch dimension equal to the length of timesteps. :return: a tensor of shape [batch_size, 1, ...] where the shape has K dims. """ res = th.from_numpy(arr).to(device=timesteps.device)[timesteps].float() while len(res.shape) < len(broadcast_shape): res = res[..., None] return res.expand(broadcast_shape)