make a python animation plot with FuncAnimation (python) with a stack tensor for a…
- User
make a python animation plot with FuncAnimation (python) with a stack tensor for a single image def plot_sample(x_gen_store, n_sample, nrows, save_dir, fn): ncols = n_sample // nrows sx_gen_store = np.moveaxis(x_gen_store, 2, 4) # change to Numpy image format (h,w,channels) vs (channels,h,w) nsx_gen_store = denormalize_and_clip(sx_gen_store) # create gif of images evolving over time, based on x_gen_store fig, axs = plt.subplots( nrows=nrows, ncols=ncols, sharex=True, sharey=True, figsize=(ncols, nrows) ) def animate_diff(i, store): print(f'gif animating frame {i} of {store.shape[0]}', end='\r') plots = [] for row in range(nrows): for col in range(ncols): axs[row, col].clear() axs[row, col].set_xticks([]) axs[row, col].set_yticks([]) plots.append(axs[row, col].imshow(store[i, (row * ncols) + col])) return plots ani = FuncAnimation( fig, animate_diff, fargs=[nsx_gen_store], interval=200, blit=False, repeat=True, frames=nsx_gen_store.shape[0] ) plt.close() ani.save(save_dir + f"{fn}.gif", dpi=100, writer=PillowWriter(fps=5)) return ani
Assistant
- User
it should make a plot for a single image as gif
Assistant
- User
def denormalize_and_clip(image: torch.Tensor) -> torch.Tensor: image *= 0.5 image += 0.5 return image.clip(0, 1)
class NoiseScheduler(nn.Module): def init( self, timesteps: int = 24, beta_start: float = 1e-4, beta_end: float = 0.6 ): super().init() self.timesteps = timesteps self.beta_start = beta_start self.beta_end = beta_end
beta = torch.linspace(beta_start, beta_end, timesteps) alpha = 1. - beta alpha_bar = torch.cumprod(alpha, 0) self.register_buffer('beta', beta) self.register_buffer('alpha', alpha) self.register_buffer('alpha_bar', alpha_bar) def add_noise( self, x: torch.Tensor, t: torch.Tensor, noise: torch.Tensor ) -> torch.Tensor: """ Adds a single step of noise :param x: image we are adding noise to :param t: step number, 0 indexed (0 <= t < steps) :return: image with noise added """ alpha_bar = self.alpha_bar[t].view(-1, 1, 1, 1) return torch.sqrt(alpha_bar) * x + torch.sqrt(1 - alpha_bar) * noise def sample_prev_step( self, xt: torch.Tensor, t: torch.Tensor, pred_noise: torch.Tensor ) -> torch.Tensor: z = torch.randn_like(xt) z[t.expand_as(z) == 0] = 0 mean = (1 / torch.sqrt(self.alpha[t])) * (xt - (self.beta[t] / torch.sqrt(1 - self.alpha_bar[t])) * pred_noise) var = ((1 - self.alpha_bar[t - 1]) / (1 - self.alpha_bar[t])) * self.beta[t] sigma = torch.sqrt(var) x = mean + sigma * z return x def ddim( self, xt: torch.Tensor, t: torch.Tensor, t_prev: torch.Tensor, pred_noise: torch.Tensor ) -> torch.Tensor: ab = self.alpha_bar[t] ab_prev = self.alpha_bar[t_prev] x0_pred = ab_prev.sqrt() / ab.sqrt() * (xt - (1 - ab).sqrt() * pred_noise) dir_xt = (1 - ab_prev).sqrt() * pred_noise return x0_pred + dir_xt Assistant
Looking at your DDIM implementation, there's an issue with the x0 prediction formula. In DDIM, you need to first predict x0 from the current noisy image xt, then use that to compute the previous timestep. Here's the corrected version:
def ddim( self, xt: torch.Tensor, t: torch.Tensor, t_prev: torch.Tensor, pred_noise: torch.Tensor ) -> torch.Tensor: ab = self.alpha_bar[t].view(-1, 1, 1, 1) ab_prev = self.alpha_bar[t_prev].view(-1, 1, 1, 1) # First predict x0 from xt and the predicted noise x0_pred = (xt - torch.sqrt(1 - ab) * pred_noise) / torch.sqrt(ab) # Then compute x_{t-1} using the DDIM formula dir_xt = torch.sqrt(1 - ab_prev) * pred_noise x_prev = torch.sqrt(ab_prev) * x0_pred + dir_xt return x_prevThe key differences:
- x0 prediction: The correct formula is
x0 = (xt - sqrt(1 - alpha_bar_t) * noise) / sqrt(alpha_bar_t) - View reshaping: Added
.view(-1, 1, 1, 1)to ensure proper broadcasting with image tensors - Clearer variable names: The final step combines the predicted x0 scaled by with the direction pointing towards xt
- x0 prediction: The correct formula is
- User
@torch.no_grad() def sample_ddim( context: torch.Tensor, n_sample: int, n_step: int, channels: int = 3, size: int = 16, save_rate: int = 20, ): # x_T ~ N(0, 1), sample initial noise samples = torch.randn(n_sample, channels, size, size).to(device) step_size = timesteps // n_step
# array to keep track of generated steps for plotting intermediate = [] for i in range(timesteps - 1, 0, -step_size): print(f'Sampling timestep {i:3d}', end='\r') # reshape time tensor t = torch.tensor([i / timesteps])[:, None, None, None].to(device) eps = nn_model(samples, t, context) tensor_i = torch.tensor(i, device=device).view(1,) samples = noise_scheduler.ddim(samples, tensor_i, tensor_i - step_size, eps) intermediate.append(samples.detach().cpu().numpy()) intermediate = np.stack(intermediate) return samples, intermediateSomehow, I got an error on the last step of generation, it is completely noise, while previous step is clean generatio
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.