Cccccz commited on
Commit
046649d
·
verified ·
1 Parent(s): 0360ac1

Upload model source

Browse files
Files changed (8) hide show
  1. model/__init__.py +14 -0
  2. model/base.py +222 -0
  3. model/causvid.py +391 -0
  4. model/diffusion.py +125 -0
  5. model/dmd.py +332 -0
  6. model/gan.py +295 -0
  7. model/ode_regression.py +138 -0
  8. model/sid.py +283 -0
model/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .diffusion import CausalDiffusion
2
+ from .causvid import CausVid
3
+ from .dmd import DMD
4
+ from .gan import GAN
5
+ from .sid import SiD
6
+ from .ode_regression import ODERegression
7
+ __all__ = [
8
+ "CausalDiffusion",
9
+ "CausVid",
10
+ "DMD",
11
+ "GAN",
12
+ "SiD",
13
+ "ODERegression"
14
+ ]
model/base.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple
2
+ from einops import rearrange
3
+ from torch import nn
4
+ import torch.distributed as dist
5
+ import torch
6
+
7
+ from pipeline import SelfForcingTrainingPipeline
8
+ from utils.loss import get_denoising_loss
9
+ from utils.wan_wrapper import WanDiffusionWrapper, WanTextEncoder, WanVAEWrapper
10
+
11
+
12
+ class BaseModel(nn.Module):
13
+ def __init__(self, args, device):
14
+ super().__init__()
15
+ self._initialize_models(args, device)
16
+
17
+ self.device = device
18
+ self.args = args
19
+ self.dtype = torch.bfloat16 if args.mixed_precision else torch.float32
20
+ if hasattr(args, "denoising_step_list"):
21
+ self.denoising_step_list = torch.tensor(args.denoising_step_list, dtype=torch.long)
22
+ if args.warp_denoising_step:
23
+ timesteps = torch.cat((self.scheduler.timesteps.cpu(), torch.tensor([0], dtype=torch.float32)))
24
+ self.denoising_step_list = timesteps[1000 - self.denoising_step_list]
25
+
26
+ def _initialize_models(self, args, device):
27
+ self.real_model_name = getattr(args, "real_name", "Wan2.1-T2V-1.3B")
28
+ self.fake_model_name = getattr(args, "fake_name", "Wan2.1-T2V-1.3B")
29
+
30
+ self.generator = WanDiffusionWrapper(**getattr(args, "model_kwargs", {}), is_causal=True)
31
+ self.generator.model.requires_grad_(True)
32
+
33
+ self.real_score = WanDiffusionWrapper(model_name=self.real_model_name, is_causal=False)
34
+ self.real_score.model.requires_grad_(False)
35
+
36
+ self.fake_score = WanDiffusionWrapper(model_name=self.fake_model_name, is_causal=False)
37
+ self.fake_score.model.requires_grad_(True)
38
+
39
+ self.text_encoder = WanTextEncoder()
40
+ self.text_encoder.requires_grad_(False)
41
+
42
+ self.vae = WanVAEWrapper()
43
+ self.vae.requires_grad_(False)
44
+
45
+ self.scheduler = self.generator.get_scheduler()
46
+ self.scheduler.timesteps = self.scheduler.timesteps.to(device)
47
+
48
+ def _get_timestep(
49
+ self,
50
+ min_timestep: int,
51
+ max_timestep: int,
52
+ batch_size: int,
53
+ num_frame: int,
54
+ num_frame_per_block: int,
55
+ uniform_timestep: bool = False
56
+ ) -> torch.Tensor:
57
+ """
58
+ Randomly generate a timestep tensor based on the generator's task type. It uniformly samples a timestep
59
+ from the range [min_timestep, max_timestep], and returns a tensor of shape [batch_size, num_frame].
60
+ - If uniform_timestep, it will use the same timestep for all frames.
61
+ - If not uniform_timestep, it will use a different timestep for each block.
62
+ """
63
+ if uniform_timestep:
64
+ timestep = torch.randint(
65
+ min_timestep,
66
+ max_timestep,
67
+ [batch_size, 1],
68
+ device=self.device,
69
+ dtype=torch.long
70
+ ).repeat(1, num_frame)
71
+ return timestep
72
+ else:
73
+ timestep = torch.randint(
74
+ min_timestep,
75
+ max_timestep,
76
+ [batch_size, num_frame],
77
+ device=self.device,
78
+ dtype=torch.long
79
+ )
80
+ # make the noise level the same within every block
81
+ if self.independent_first_frame:
82
+ # the first frame is always kept the same
83
+ timestep_from_second = timestep[:, 1:]
84
+ timestep_from_second = timestep_from_second.reshape(
85
+ timestep_from_second.shape[0], -1, num_frame_per_block)
86
+ timestep_from_second[:, :, 1:] = timestep_from_second[:, :, 0:1]
87
+ timestep_from_second = timestep_from_second.reshape(
88
+ timestep_from_second.shape[0], -1)
89
+ timestep = torch.cat([timestep[:, 0:1], timestep_from_second], dim=1)
90
+ else:
91
+ timestep = timestep.reshape(
92
+ timestep.shape[0], -1, num_frame_per_block)
93
+ timestep[:, :, 1:] = timestep[:, :, 0:1]
94
+ timestep = timestep.reshape(timestep.shape[0], -1)
95
+ return timestep
96
+
97
+
98
+ class SelfForcingModel(BaseModel):
99
+ def __init__(self, args, device):
100
+ super().__init__(args, device)
101
+ self.denoising_loss_func = get_denoising_loss(args.denoising_loss_type)()
102
+
103
+ def _run_generator(
104
+ self,
105
+ image_or_video_shape,
106
+ conditional_dict: dict,
107
+ initial_latent: torch.tensor = None
108
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
109
+ """
110
+ Optionally simulate the generator's input from noise using backward simulation
111
+ and then run the generator for one-step.
112
+ Input:
113
+ - image_or_video_shape: a list containing the shape of the image or video [B, F, C, H, W].
114
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
115
+ - unconditional_dict: a dictionary containing the unconditional information (e.g. null/negative text embeddings, null/negative image embeddings).
116
+ - clean_latent: a tensor containing the clean latents [B, F, C, H, W]. Need to be passed when no backward simulation is used.
117
+ - initial_latent: a tensor containing the initial latents [B, F, C, H, W].
118
+ Output:
119
+ - pred_image: a tensor with shape [B, F, C, H, W].
120
+ - denoised_timestep: an integer
121
+ """
122
+ # Step 1: Sample noise and backward simulate the generator's input
123
+ assert getattr(self.args, "backward_simulation", True), "Backward simulation needs to be enabled"
124
+ if initial_latent is not None:
125
+ conditional_dict["initial_latent"] = initial_latent
126
+ if self.args.i2v:
127
+ noise_shape = [image_or_video_shape[0], image_or_video_shape[1] - 1, *image_or_video_shape[2:]]
128
+ else:
129
+ noise_shape = image_or_video_shape.copy()
130
+
131
+ # During training, the number of generated frames should be uniformly sampled from
132
+ # [21, self.num_training_frames], but still being a multiple of self.num_frame_per_block
133
+ min_num_frames = 20 if self.args.independent_first_frame else 21
134
+ max_num_frames = self.num_training_frames - 1 if self.args.independent_first_frame else self.num_training_frames
135
+ assert max_num_frames % self.num_frame_per_block == 0
136
+ assert min_num_frames % self.num_frame_per_block == 0
137
+ max_num_blocks = max_num_frames // self.num_frame_per_block
138
+ min_num_blocks = min_num_frames // self.num_frame_per_block
139
+ num_generated_blocks = torch.randint(min_num_blocks, max_num_blocks + 1, (1,), device=self.device)
140
+ dist.broadcast(num_generated_blocks, src=0)
141
+ num_generated_blocks = num_generated_blocks.item()
142
+ num_generated_frames = num_generated_blocks * self.num_frame_per_block
143
+ if self.args.independent_first_frame and initial_latent is None:
144
+ num_generated_frames += 1
145
+ min_num_frames += 1
146
+ # Sync num_generated_frames across all processes
147
+ noise_shape[1] = num_generated_frames
148
+
149
+ pred_image_or_video, denoised_timestep_from, denoised_timestep_to = self._consistency_backward_simulation(
150
+ noise=torch.randn(noise_shape,
151
+ device=self.device, dtype=self.dtype),
152
+ **conditional_dict,
153
+ )
154
+ # Slice last 21 frames
155
+ if pred_image_or_video.shape[1] > 21:
156
+ with torch.no_grad():
157
+ # Reencode to get image latent
158
+ latent_to_decode = pred_image_or_video[:, :-20, ...]
159
+ # Deccode to video
160
+ pixels = self.vae.decode_to_pixel(latent_to_decode)
161
+ frame = pixels[:, -1:, ...].to(self.dtype)
162
+ frame = rearrange(frame, "b t c h w -> b c t h w")
163
+ # Encode frame to get image latent
164
+ image_latent = self.vae.encode_to_latent(frame).to(self.dtype)
165
+ pred_image_or_video_last_21 = torch.cat([image_latent, pred_image_or_video[:, -20:, ...]], dim=1)
166
+ else:
167
+ pred_image_or_video_last_21 = pred_image_or_video
168
+
169
+ if num_generated_frames != min_num_frames:
170
+ # Currently, we do not use gradient for the first chunk, since it contains image latents
171
+ gradient_mask = torch.ones_like(pred_image_or_video_last_21, dtype=torch.bool)
172
+ if self.args.independent_first_frame:
173
+ gradient_mask[:, :1] = False
174
+ else:
175
+ gradient_mask[:, :self.num_frame_per_block] = False
176
+ else:
177
+ gradient_mask = None
178
+
179
+ pred_image_or_video_last_21 = pred_image_or_video_last_21.to(self.dtype)
180
+ return pred_image_or_video_last_21, gradient_mask, denoised_timestep_from, denoised_timestep_to
181
+
182
+ def _consistency_backward_simulation(
183
+ self,
184
+ noise: torch.Tensor,
185
+ **conditional_dict: dict
186
+ ) -> torch.Tensor:
187
+ """
188
+ Simulate the generator's input from noise to avoid training/inference mismatch.
189
+ See Sec 4.5 of the DMD2 paper (https://arxiv.org/abs/2405.14867) for details.
190
+ Here we use the consistency sampler (https://arxiv.org/abs/2303.01469)
191
+ Input:
192
+ - noise: a tensor sampled from N(0, 1) with shape [B, F, C, H, W] where the number of frame is 1 for images.
193
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
194
+ Output:
195
+ - output: a tensor with shape [B, T, F, C, H, W].
196
+ T is the total number of timesteps. output[0] is a pure noise and output[i] and i>0
197
+ represents the x0 prediction at each timestep.
198
+ """
199
+ if self.inference_pipeline is None:
200
+ self._initialize_inference_pipeline()
201
+
202
+ return self.inference_pipeline.inference_with_trajectory(
203
+ noise=noise, **conditional_dict
204
+ )
205
+
206
+ def _initialize_inference_pipeline(self):
207
+ """
208
+ Lazy initialize the inference pipeline during the first backward simulation run.
209
+ Here we encapsulate the inference code with a model-dependent outside function.
210
+ We pass our FSDP-wrapped modules into the pipeline to save memory.
211
+ """
212
+ self.inference_pipeline = SelfForcingTrainingPipeline(
213
+ denoising_step_list=self.denoising_step_list,
214
+ scheduler=self.scheduler,
215
+ generator=self.generator,
216
+ num_frame_per_block=self.num_frame_per_block,
217
+ independent_first_frame=self.args.independent_first_frame,
218
+ same_step_across_blocks=self.args.same_step_across_blocks,
219
+ last_step_only=self.args.last_step_only,
220
+ num_max_frames=self.num_training_frames,
221
+ context_noise=self.args.context_noise
222
+ )
model/causvid.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn.functional as F
2
+ from typing import Tuple
3
+ import torch
4
+
5
+ from model.base import BaseModel
6
+
7
+
8
+ class CausVid(BaseModel):
9
+ def __init__(self, args, device):
10
+ """
11
+ Initialize the DMD (Distribution Matching Distillation) module.
12
+ This class is self-contained and compute generator and fake score losses
13
+ in the forward pass.
14
+ """
15
+ super().__init__(args, device)
16
+ self.num_frame_per_block = getattr(args, "num_frame_per_block", 1)
17
+ self.num_training_frames = getattr(args, "num_training_frames", 21)
18
+
19
+ if self.num_frame_per_block > 1:
20
+ self.generator.model.num_frame_per_block = self.num_frame_per_block
21
+
22
+ self.independent_first_frame = getattr(args, "independent_first_frame", False)
23
+ if self.independent_first_frame:
24
+ self.generator.model.independent_first_frame = True
25
+ if args.gradient_checkpointing:
26
+ self.generator.enable_gradient_checkpointing()
27
+ self.fake_score.enable_gradient_checkpointing()
28
+
29
+ # Step 2: Initialize all dmd hyperparameters
30
+ self.num_train_timestep = args.num_train_timestep
31
+ self.min_step = int(0.02 * self.num_train_timestep)
32
+ self.max_step = int(0.98 * self.num_train_timestep)
33
+ if hasattr(args, "real_guidance_scale"):
34
+ self.real_guidance_scale = args.real_guidance_scale
35
+ self.fake_guidance_scale = args.fake_guidance_scale
36
+ else:
37
+ self.real_guidance_scale = args.guidance_scale
38
+ self.fake_guidance_scale = 0.0
39
+ self.timestep_shift = getattr(args, "timestep_shift", 1.0)
40
+ self.teacher_forcing = getattr(args, "teacher_forcing", False)
41
+
42
+ if getattr(self.scheduler, "alphas_cumprod", None) is not None:
43
+ self.scheduler.alphas_cumprod = self.scheduler.alphas_cumprod.to(device)
44
+ else:
45
+ self.scheduler.alphas_cumprod = None
46
+
47
+ def _compute_kl_grad(
48
+ self, noisy_image_or_video: torch.Tensor,
49
+ estimated_clean_image_or_video: torch.Tensor,
50
+ timestep: torch.Tensor,
51
+ conditional_dict: dict, unconditional_dict: dict,
52
+ normalization: bool = True
53
+ ) -> Tuple[torch.Tensor, dict]:
54
+ """
55
+ Compute the KL grad (eq 7 in https://arxiv.org/abs/2311.18828).
56
+ Input:
57
+ - noisy_image_or_video: a tensor with shape [B, F, C, H, W] where the number of frame is 1 for images.
58
+ - estimated_clean_image_or_video: a tensor with shape [B, F, C, H, W] representing the estimated clean image or video.
59
+ - timestep: a tensor with shape [B, F] containing the randomly generated timestep.
60
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
61
+ - unconditional_dict: a dictionary containing the unconditional information (e.g. null/negative text embeddings, null/negative image embeddings).
62
+ - normalization: a boolean indicating whether to normalize the gradient.
63
+ Output:
64
+ - kl_grad: a tensor representing the KL grad.
65
+ - kl_log_dict: a dictionary containing the intermediate tensors for logging.
66
+ """
67
+ # Step 1: Compute the fake score
68
+ _, pred_fake_image_cond = self.fake_score(
69
+ noisy_image_or_video=noisy_image_or_video,
70
+ conditional_dict=conditional_dict,
71
+ timestep=timestep
72
+ )
73
+
74
+ if self.fake_guidance_scale != 0.0:
75
+ _, pred_fake_image_uncond = self.fake_score(
76
+ noisy_image_or_video=noisy_image_or_video,
77
+ conditional_dict=unconditional_dict,
78
+ timestep=timestep
79
+ )
80
+ pred_fake_image = pred_fake_image_cond + (
81
+ pred_fake_image_cond - pred_fake_image_uncond
82
+ ) * self.fake_guidance_scale
83
+ else:
84
+ pred_fake_image = pred_fake_image_cond
85
+
86
+ # Step 2: Compute the real score
87
+ # We compute the conditional and unconditional prediction
88
+ # and add them together to achieve cfg (https://arxiv.org/abs/2207.12598)
89
+ _, pred_real_image_cond = self.real_score(
90
+ noisy_image_or_video=noisy_image_or_video,
91
+ conditional_dict=conditional_dict,
92
+ timestep=timestep
93
+ )
94
+
95
+ _, pred_real_image_uncond = self.real_score(
96
+ noisy_image_or_video=noisy_image_or_video,
97
+ conditional_dict=unconditional_dict,
98
+ timestep=timestep
99
+ )
100
+
101
+ pred_real_image = pred_real_image_cond + (
102
+ pred_real_image_cond - pred_real_image_uncond
103
+ ) * self.real_guidance_scale
104
+
105
+ # Step 3: Compute the DMD gradient (DMD paper eq. 7).
106
+ grad = (pred_fake_image - pred_real_image)
107
+
108
+ # TODO: Change the normalizer for causal teacher
109
+ if normalization:
110
+ # Step 4: Gradient normalization (DMD paper eq. 8).
111
+ p_real = (estimated_clean_image_or_video - pred_real_image)
112
+ normalizer = torch.abs(p_real).mean(dim=[1, 2, 3, 4], keepdim=True)
113
+ grad = grad / normalizer
114
+ grad = torch.nan_to_num(grad)
115
+
116
+ return grad, {
117
+ "dmdtrain_gradient_norm": torch.mean(torch.abs(grad)).detach(),
118
+ "timestep": timestep.detach()
119
+ }
120
+
121
+ def compute_distribution_matching_loss(
122
+ self,
123
+ image_or_video: torch.Tensor,
124
+ conditional_dict: dict,
125
+ unconditional_dict: dict,
126
+ gradient_mask: torch.Tensor = None,
127
+ ) -> Tuple[torch.Tensor, dict]:
128
+ """
129
+ Compute the DMD loss (eq 7 in https://arxiv.org/abs/2311.18828).
130
+ Input:
131
+ - image_or_video: a tensor with shape [B, F, C, H, W] where the number of frame is 1 for images.
132
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
133
+ - unconditional_dict: a dictionary containing the unconditional information (e.g. null/negative text embeddings, null/negative image embeddings).
134
+ - gradient_mask: a boolean tensor with the same shape as image_or_video indicating which pixels to compute loss .
135
+ Output:
136
+ - dmd_loss: a scalar tensor representing the DMD loss.
137
+ - dmd_log_dict: a dictionary containing the intermediate tensors for logging.
138
+ """
139
+ original_latent = image_or_video
140
+
141
+ batch_size, num_frame = image_or_video.shape[:2]
142
+
143
+ with torch.no_grad():
144
+ # Step 1: Randomly sample timestep based on the given schedule and corresponding noise
145
+ timestep = self._get_timestep(
146
+ 0,
147
+ self.num_train_timestep,
148
+ batch_size,
149
+ num_frame,
150
+ self.num_frame_per_block,
151
+ uniform_timestep=True
152
+ )
153
+
154
+ if self.timestep_shift > 1:
155
+ timestep = self.timestep_shift * \
156
+ (timestep / 1000) / \
157
+ (1 + (self.timestep_shift - 1) * (timestep / 1000)) * 1000
158
+ timestep = timestep.clamp(self.min_step, self.max_step)
159
+
160
+ noise = torch.randn_like(image_or_video)
161
+ noisy_latent = self.scheduler.add_noise(
162
+ image_or_video.flatten(0, 1),
163
+ noise.flatten(0, 1),
164
+ timestep.flatten(0, 1)
165
+ ).detach().unflatten(0, (batch_size, num_frame))
166
+
167
+ # Step 2: Compute the KL grad
168
+ grad, dmd_log_dict = self._compute_kl_grad(
169
+ noisy_image_or_video=noisy_latent,
170
+ estimated_clean_image_or_video=original_latent,
171
+ timestep=timestep,
172
+ conditional_dict=conditional_dict,
173
+ unconditional_dict=unconditional_dict
174
+ )
175
+
176
+ if gradient_mask is not None:
177
+ dmd_loss = 0.5 * F.mse_loss(original_latent.double(
178
+ )[gradient_mask], (original_latent.double() - grad.double()).detach()[gradient_mask], reduction="mean")
179
+ else:
180
+ dmd_loss = 0.5 * F.mse_loss(original_latent.double(
181
+ ), (original_latent.double() - grad.double()).detach(), reduction="mean")
182
+ return dmd_loss, dmd_log_dict
183
+
184
+ def _run_generator(
185
+ self,
186
+ image_or_video_shape,
187
+ conditional_dict: dict,
188
+ clean_latent: torch.tensor
189
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
190
+ """
191
+ Optionally simulate the generator's input from noise using backward simulation
192
+ and then run the generator for one-step.
193
+ Input:
194
+ - image_or_video_shape: a list containing the shape of the image or video [B, F, C, H, W].
195
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
196
+ - unconditional_dict: a dictionary containing the unconditional information (e.g. null/negative text embeddings, null/negative image embeddings).
197
+ - clean_latent: a tensor containing the clean latents [B, F, C, H, W]. Need to be passed when no backward simulation is used.
198
+ - initial_latent: a tensor containing the initial latents [B, F, C, H, W].
199
+ Output:
200
+ - pred_image: a tensor with shape [B, F, C, H, W].
201
+ """
202
+ simulated_noisy_input = []
203
+ for timestep in self.denoising_step_list:
204
+ noise = torch.randn(
205
+ image_or_video_shape, device=self.device, dtype=self.dtype)
206
+
207
+ noisy_timestep = timestep * torch.ones(
208
+ image_or_video_shape[:2], device=self.device, dtype=torch.long)
209
+
210
+ if timestep != 0:
211
+ noisy_image = self.scheduler.add_noise(
212
+ clean_latent.flatten(0, 1),
213
+ noise.flatten(0, 1),
214
+ noisy_timestep.flatten(0, 1)
215
+ ).unflatten(0, image_or_video_shape[:2])
216
+ else:
217
+ noisy_image = clean_latent
218
+
219
+ simulated_noisy_input.append(noisy_image)
220
+
221
+ simulated_noisy_input = torch.stack(simulated_noisy_input, dim=1)
222
+
223
+ # Step 2: Randomly sample a timestep and pick the corresponding input
224
+ index = self._get_timestep(
225
+ 0,
226
+ len(self.denoising_step_list),
227
+ image_or_video_shape[0],
228
+ image_or_video_shape[1],
229
+ self.num_frame_per_block,
230
+ uniform_timestep=False
231
+ )
232
+
233
+ # select the corresponding timestep's noisy input from the stacked tensor [B, T, F, C, H, W]
234
+ noisy_input = torch.gather(
235
+ simulated_noisy_input, dim=1,
236
+ index=index.reshape(index.shape[0], 1, index.shape[1], 1, 1, 1).expand(
237
+ -1, -1, -1, *image_or_video_shape[2:]).to(self.device)
238
+ ).squeeze(1)
239
+
240
+ timestep = self.denoising_step_list[index].to(self.device)
241
+
242
+ _, pred_image_or_video = self.generator(
243
+ noisy_image_or_video=noisy_input,
244
+ conditional_dict=conditional_dict,
245
+ timestep=timestep,
246
+ clean_x=clean_latent if self.teacher_forcing else None,
247
+ )
248
+
249
+ gradient_mask = None # timestep != 0
250
+
251
+ pred_image_or_video = pred_image_or_video.type_as(noisy_input)
252
+
253
+ return pred_image_or_video, gradient_mask
254
+
255
+ def generator_loss(
256
+ self,
257
+ image_or_video_shape,
258
+ conditional_dict: dict,
259
+ unconditional_dict: dict,
260
+ clean_latent: torch.Tensor,
261
+ initial_latent: torch.Tensor = None
262
+ ) -> Tuple[torch.Tensor, dict]:
263
+ """
264
+ Generate image/videos from noise and compute the DMD loss.
265
+ The noisy input to the generator is backward simulated.
266
+ This removes the need of any datasets during distillation.
267
+ See Sec 4.5 of the DMD2 paper (https://arxiv.org/abs/2405.14867) for details.
268
+ Input:
269
+ - image_or_video_shape: a list containing the shape of the image or video [B, F, C, H, W].
270
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
271
+ - unconditional_dict: a dictionary containing the unconditional information (e.g. null/negative text embeddings, null/negative image embeddings).
272
+ - clean_latent: a tensor containing the clean latents [B, F, C, H, W]. Need to be passed when no backward simulation is used.
273
+ Output:
274
+ - loss: a scalar tensor representing the generator loss.
275
+ - generator_log_dict: a dictionary containing the intermediate tensors for logging.
276
+ """
277
+ # Step 1: Run generator on backward simulated noisy input
278
+ pred_image, gradient_mask = self._run_generator(
279
+ image_or_video_shape=image_or_video_shape,
280
+ conditional_dict=conditional_dict,
281
+ clean_latent=clean_latent
282
+ )
283
+
284
+ # Step 2: Compute the DMD loss
285
+ dmd_loss, dmd_log_dict = self.compute_distribution_matching_loss(
286
+ image_or_video=pred_image,
287
+ conditional_dict=conditional_dict,
288
+ unconditional_dict=unconditional_dict,
289
+ gradient_mask=gradient_mask
290
+ )
291
+
292
+ # Step 3: TODO: Implement the GAN loss
293
+
294
+ return dmd_loss, dmd_log_dict
295
+
296
+ def critic_loss(
297
+ self,
298
+ image_or_video_shape,
299
+ conditional_dict: dict,
300
+ unconditional_dict: dict,
301
+ clean_latent: torch.Tensor,
302
+ initial_latent: torch.Tensor = None
303
+ ) -> Tuple[torch.Tensor, dict]:
304
+ """
305
+ Generate image/videos from noise and train the critic with generated samples.
306
+ The noisy input to the generator is backward simulated.
307
+ This removes the need of any datasets during distillation.
308
+ See Sec 4.5 of the DMD2 paper (https://arxiv.org/abs/2405.14867) for details.
309
+ Input:
310
+ - image_or_video_shape: a list containing the shape of the image or video [B, F, C, H, W].
311
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
312
+ - unconditional_dict: a dictionary containing the unconditional information (e.g. null/negative text embeddings, null/negative image embeddings).
313
+ - clean_latent: a tensor containing the clean latents [B, F, C, H, W]. Need to be passed when no backward simulation is used.
314
+ Output:
315
+ - loss: a scalar tensor representing the generator loss.
316
+ - critic_log_dict: a dictionary containing the intermediate tensors for logging.
317
+ """
318
+
319
+ # Step 1: Run generator on backward simulated noisy input
320
+ with torch.no_grad():
321
+ generated_image, _ = self._run_generator(
322
+ image_or_video_shape=image_or_video_shape,
323
+ conditional_dict=conditional_dict,
324
+ clean_latent=clean_latent
325
+ )
326
+
327
+ # Step 2: Compute the fake prediction
328
+ critic_timestep = self._get_timestep(
329
+ 0,
330
+ self.num_train_timestep,
331
+ image_or_video_shape[0],
332
+ image_or_video_shape[1],
333
+ self.num_frame_per_block,
334
+ uniform_timestep=True
335
+ )
336
+
337
+ if self.timestep_shift > 1:
338
+ critic_timestep = self.timestep_shift * \
339
+ (critic_timestep / 1000) / (1 + (self.timestep_shift - 1) * (critic_timestep / 1000)) * 1000
340
+
341
+ critic_timestep = critic_timestep.clamp(self.min_step, self.max_step)
342
+
343
+ critic_noise = torch.randn_like(generated_image)
344
+ noisy_generated_image = self.scheduler.add_noise(
345
+ generated_image.flatten(0, 1),
346
+ critic_noise.flatten(0, 1),
347
+ critic_timestep.flatten(0, 1)
348
+ ).unflatten(0, image_or_video_shape[:2])
349
+
350
+ _, pred_fake_image = self.fake_score(
351
+ noisy_image_or_video=noisy_generated_image,
352
+ conditional_dict=conditional_dict,
353
+ timestep=critic_timestep
354
+ )
355
+
356
+ # Step 3: Compute the denoising loss for the fake critic
357
+ if self.args.denoising_loss_type == "flow":
358
+ from utils.wan_wrapper import WanDiffusionWrapper
359
+ flow_pred = WanDiffusionWrapper._convert_x0_to_flow_pred(
360
+ scheduler=self.scheduler,
361
+ x0_pred=pred_fake_image.flatten(0, 1),
362
+ xt=noisy_generated_image.flatten(0, 1),
363
+ timestep=critic_timestep.flatten(0, 1)
364
+ )
365
+ pred_fake_noise = None
366
+ else:
367
+ flow_pred = None
368
+ pred_fake_noise = self.scheduler.convert_x0_to_noise(
369
+ x0=pred_fake_image.flatten(0, 1),
370
+ xt=noisy_generated_image.flatten(0, 1),
371
+ timestep=critic_timestep.flatten(0, 1)
372
+ ).unflatten(0, image_or_video_shape[:2])
373
+
374
+ denoising_loss = self.denoising_loss_func(
375
+ x=generated_image.flatten(0, 1),
376
+ x_pred=pred_fake_image.flatten(0, 1),
377
+ noise=critic_noise.flatten(0, 1),
378
+ noise_pred=pred_fake_noise,
379
+ alphas_cumprod=self.scheduler.alphas_cumprod,
380
+ timestep=critic_timestep.flatten(0, 1),
381
+ flow_pred=flow_pred
382
+ )
383
+
384
+ # Step 4: TODO: Compute the GAN loss
385
+
386
+ # Step 5: Debugging Log
387
+ critic_log_dict = {
388
+ "critic_timestep": critic_timestep.detach()
389
+ }
390
+
391
+ return denoising_loss, critic_log_dict
model/diffusion.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple
2
+ import torch
3
+
4
+ from model.base import BaseModel
5
+ from utils.wan_wrapper import WanDiffusionWrapper, WanTextEncoder, WanVAEWrapper
6
+
7
+
8
+ class CausalDiffusion(BaseModel):
9
+ def __init__(self, args, device):
10
+ """
11
+ Initialize the Diffusion loss module.
12
+ """
13
+ super().__init__(args, device)
14
+ self.num_frame_per_block = getattr(args, "num_frame_per_block", 1)
15
+ if self.num_frame_per_block > 1:
16
+ self.generator.model.num_frame_per_block = self.num_frame_per_block
17
+ self.independent_first_frame = getattr(args, "independent_first_frame", False)
18
+ if self.independent_first_frame:
19
+ self.generator.model.independent_first_frame = True
20
+
21
+ if args.gradient_checkpointing:
22
+ self.generator.enable_gradient_checkpointing()
23
+
24
+ # Step 2: Initialize all hyperparameters
25
+ self.num_train_timestep = args.num_train_timestep
26
+ self.min_step = int(0.02 * self.num_train_timestep)
27
+ self.max_step = int(0.98 * self.num_train_timestep)
28
+ self.guidance_scale = args.guidance_scale
29
+ self.timestep_shift = getattr(args, "timestep_shift", 1.0)
30
+ self.teacher_forcing = getattr(args, "teacher_forcing", False)
31
+ # Noise augmentation in teacher forcing, we add small noise to clean context latents
32
+ self.noise_augmentation_max_timestep = getattr(args, "noise_augmentation_max_timestep", 0)
33
+
34
+ def _initialize_models(self, args):
35
+ self.generator = WanDiffusionWrapper(**getattr(args, "model_kwargs", {}), is_causal=True)
36
+ self.generator.model.requires_grad_(True)
37
+
38
+ self.text_encoder = WanTextEncoder()
39
+ self.text_encoder.requires_grad_(False)
40
+
41
+ self.vae = WanVAEWrapper()
42
+ self.vae.requires_grad_(False)
43
+
44
+ def generator_loss(
45
+ self,
46
+ image_or_video_shape,
47
+ conditional_dict: dict,
48
+ unconditional_dict: dict,
49
+ clean_latent: torch.Tensor,
50
+ initial_latent: torch.Tensor = None
51
+ ) -> Tuple[torch.Tensor, dict]:
52
+ """
53
+ Generate image/videos from noise and compute the DMD loss.
54
+ The noisy input to the generator is backward simulated.
55
+ This removes the need of any datasets during distillation.
56
+ See Sec 4.5 of the DMD2 paper (https://arxiv.org/abs/2405.14867) for details.
57
+ Input:
58
+ - image_or_video_shape: a list containing the shape of the image or video [B, F, C, H, W].
59
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
60
+ - unconditional_dict: a dictionary containing the unconditional information (e.g. null/negative text embeddings, null/negative image embeddings).
61
+ - clean_latent: a tensor containing the clean latents [B, F, C, H, W]. Need to be passed when no backward simulation is used.
62
+ Output:
63
+ - loss: a scalar tensor representing the generator loss.
64
+ - generator_log_dict: a dictionary containing the intermediate tensors for logging.
65
+ """
66
+ noise = torch.randn_like(clean_latent)
67
+ batch_size, num_frame = image_or_video_shape[:2]
68
+
69
+ # Step 2: Randomly sample a timestep and add noise to denoiser inputs
70
+ index = self._get_timestep(
71
+ 0,
72
+ self.scheduler.num_train_timesteps,
73
+ image_or_video_shape[0],
74
+ image_or_video_shape[1],
75
+ self.num_frame_per_block,
76
+ uniform_timestep=False
77
+ )
78
+ timestep = self.scheduler.timesteps[index].to(dtype=self.dtype, device=self.device)
79
+ noisy_latents = self.scheduler.add_noise(
80
+ clean_latent.flatten(0, 1),
81
+ noise.flatten(0, 1),
82
+ timestep.flatten(0, 1)
83
+ ).unflatten(0, (batch_size, num_frame))
84
+ training_target = self.scheduler.training_target(clean_latent, noise, timestep)
85
+
86
+ # Step 3: Noise augmentation, also add small noise to clean context latents
87
+ if self.noise_augmentation_max_timestep > 0:
88
+ index_clean_aug = self._get_timestep(
89
+ 0,
90
+ self.noise_augmentation_max_timestep,
91
+ image_or_video_shape[0],
92
+ image_or_video_shape[1],
93
+ self.num_frame_per_block,
94
+ uniform_timestep=False
95
+ )
96
+ timestep_clean_aug = self.scheduler.timesteps[index_clean_aug].to(dtype=self.dtype, device=self.device)
97
+ clean_latent_aug = self.scheduler.add_noise(
98
+ clean_latent.flatten(0, 1),
99
+ noise.flatten(0, 1),
100
+ timestep_clean_aug.flatten(0, 1)
101
+ ).unflatten(0, (batch_size, num_frame))
102
+ else:
103
+ clean_latent_aug = clean_latent
104
+ timestep_clean_aug = None
105
+
106
+ # Compute loss
107
+ flow_pred, x0_pred = self.generator(
108
+ noisy_image_or_video=noisy_latents,
109
+ conditional_dict=conditional_dict,
110
+ timestep=timestep,
111
+ clean_x=clean_latent_aug if self.teacher_forcing else None,
112
+ aug_t=timestep_clean_aug if self.teacher_forcing else None
113
+ )
114
+ # loss = torch.nn.functional.mse_loss(flow_pred.float(), training_target.float())
115
+ loss = torch.nn.functional.mse_loss(
116
+ flow_pred.float(), training_target.float(), reduction='none'
117
+ ).mean(dim=(2, 3, 4))
118
+ loss = loss * self.scheduler.training_weight(timestep).unflatten(0, (batch_size, num_frame))
119
+ loss = loss.mean()
120
+
121
+ log_dict = {
122
+ "x0": clean_latent.detach(),
123
+ "x0_pred": x0_pred.detach()
124
+ }
125
+ return loss, log_dict
model/dmd.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pipeline import SelfForcingTrainingPipeline
2
+ import torch.nn.functional as F
3
+ from typing import Optional, Tuple
4
+ import torch
5
+
6
+ from model.base import SelfForcingModel
7
+
8
+
9
+ class DMD(SelfForcingModel):
10
+ def __init__(self, args, device):
11
+ """
12
+ Initialize the DMD (Distribution Matching Distillation) module.
13
+ This class is self-contained and compute generator and fake score losses
14
+ in the forward pass.
15
+ """
16
+ super().__init__(args, device)
17
+ self.num_frame_per_block = getattr(args, "num_frame_per_block", 1)
18
+ self.same_step_across_blocks = getattr(args, "same_step_across_blocks", True)
19
+ self.num_training_frames = getattr(args, "num_training_frames", 21)
20
+
21
+ if self.num_frame_per_block > 1:
22
+ self.generator.model.num_frame_per_block = self.num_frame_per_block
23
+
24
+ self.independent_first_frame = getattr(args, "independent_first_frame", False)
25
+ if self.independent_first_frame:
26
+ self.generator.model.independent_first_frame = True
27
+ if args.gradient_checkpointing:
28
+ self.generator.enable_gradient_checkpointing()
29
+ self.fake_score.enable_gradient_checkpointing()
30
+
31
+ # this will be init later with fsdp-wrapped modules
32
+ self.inference_pipeline: SelfForcingTrainingPipeline = None
33
+
34
+ # Step 2: Initialize all dmd hyperparameters
35
+ self.num_train_timestep = args.num_train_timestep
36
+ self.min_step = int(0.02 * self.num_train_timestep)
37
+ self.max_step = int(0.98 * self.num_train_timestep)
38
+ if hasattr(args, "real_guidance_scale"):
39
+ self.real_guidance_scale = args.real_guidance_scale
40
+ self.fake_guidance_scale = args.fake_guidance_scale
41
+ else:
42
+ self.real_guidance_scale = args.guidance_scale
43
+ self.fake_guidance_scale = 0.0
44
+ self.timestep_shift = getattr(args, "timestep_shift", 1.0)
45
+ self.ts_schedule = getattr(args, "ts_schedule", True)
46
+ self.ts_schedule_max = getattr(args, "ts_schedule_max", False)
47
+ self.min_score_timestep = getattr(args, "min_score_timestep", 0)
48
+
49
+ if getattr(self.scheduler, "alphas_cumprod", None) is not None:
50
+ self.scheduler.alphas_cumprod = self.scheduler.alphas_cumprod.to(device)
51
+ else:
52
+ self.scheduler.alphas_cumprod = None
53
+
54
+ def _compute_kl_grad(
55
+ self, noisy_image_or_video: torch.Tensor,
56
+ estimated_clean_image_or_video: torch.Tensor,
57
+ timestep: torch.Tensor,
58
+ conditional_dict: dict, unconditional_dict: dict,
59
+ normalization: bool = True
60
+ ) -> Tuple[torch.Tensor, dict]:
61
+ """
62
+ Compute the KL grad (eq 7 in https://arxiv.org/abs/2311.18828).
63
+ Input:
64
+ - noisy_image_or_video: a tensor with shape [B, F, C, H, W] where the number of frame is 1 for images.
65
+ - estimated_clean_image_or_video: a tensor with shape [B, F, C, H, W] representing the estimated clean image or video.
66
+ - timestep: a tensor with shape [B, F] containing the randomly generated timestep.
67
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
68
+ - unconditional_dict: a dictionary containing the unconditional information (e.g. null/negative text embeddings, null/negative image embeddings).
69
+ - normalization: a boolean indicating whether to normalize the gradient.
70
+ Output:
71
+ - kl_grad: a tensor representing the KL grad.
72
+ - kl_log_dict: a dictionary containing the intermediate tensors for logging.
73
+ """
74
+ # Step 1: Compute the fake score
75
+ _, pred_fake_image_cond = self.fake_score(
76
+ noisy_image_or_video=noisy_image_or_video,
77
+ conditional_dict=conditional_dict,
78
+ timestep=timestep
79
+ )
80
+
81
+ if self.fake_guidance_scale != 0.0:
82
+ _, pred_fake_image_uncond = self.fake_score(
83
+ noisy_image_or_video=noisy_image_or_video,
84
+ conditional_dict=unconditional_dict,
85
+ timestep=timestep
86
+ )
87
+ pred_fake_image = pred_fake_image_cond + (
88
+ pred_fake_image_cond - pred_fake_image_uncond
89
+ ) * self.fake_guidance_scale
90
+ else:
91
+ pred_fake_image = pred_fake_image_cond
92
+
93
+ # Step 2: Compute the real score
94
+ # We compute the conditional and unconditional prediction
95
+ # and add them together to achieve cfg (https://arxiv.org/abs/2207.12598)
96
+ _, pred_real_image_cond = self.real_score(
97
+ noisy_image_or_video=noisy_image_or_video,
98
+ conditional_dict=conditional_dict,
99
+ timestep=timestep
100
+ )
101
+
102
+ _, pred_real_image_uncond = self.real_score(
103
+ noisy_image_or_video=noisy_image_or_video,
104
+ conditional_dict=unconditional_dict,
105
+ timestep=timestep
106
+ )
107
+
108
+ pred_real_image = pred_real_image_cond + (
109
+ pred_real_image_cond - pred_real_image_uncond
110
+ ) * self.real_guidance_scale
111
+
112
+ # Step 3: Compute the DMD gradient (DMD paper eq. 7).
113
+ grad = (pred_fake_image - pred_real_image)
114
+
115
+ # TODO: Change the normalizer for causal teacher
116
+ if normalization:
117
+ # Step 4: Gradient normalization (DMD paper eq. 8).
118
+ p_real = (estimated_clean_image_or_video - pred_real_image)
119
+ normalizer = torch.abs(p_real).mean(dim=[1, 2, 3, 4], keepdim=True)
120
+ grad = grad / normalizer
121
+ grad = torch.nan_to_num(grad)
122
+
123
+ return grad, {
124
+ "dmdtrain_gradient_norm": torch.mean(torch.abs(grad)).detach(),
125
+ "timestep": timestep.detach()
126
+ }
127
+
128
+ def compute_distribution_matching_loss(
129
+ self,
130
+ image_or_video: torch.Tensor,
131
+ conditional_dict: dict,
132
+ unconditional_dict: dict,
133
+ gradient_mask: Optional[torch.Tensor] = None,
134
+ denoised_timestep_from: int = 0,
135
+ denoised_timestep_to: int = 0
136
+ ) -> Tuple[torch.Tensor, dict]:
137
+ """
138
+ Compute the DMD loss (eq 7 in https://arxiv.org/abs/2311.18828).
139
+ Input:
140
+ - image_or_video: a tensor with shape [B, F, C, H, W] where the number of frame is 1 for images.
141
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
142
+ - unconditional_dict: a dictionary containing the unconditional information (e.g. null/negative text embeddings, null/negative image embeddings).
143
+ - gradient_mask: a boolean tensor with the same shape as image_or_video indicating which pixels to compute loss .
144
+ Output:
145
+ - dmd_loss: a scalar tensor representing the DMD loss.
146
+ - dmd_log_dict: a dictionary containing the intermediate tensors for logging.
147
+ """
148
+ original_latent = image_or_video
149
+
150
+ batch_size, num_frame = image_or_video.shape[:2]
151
+
152
+ with torch.no_grad():
153
+ # Step 1: Randomly sample timestep based on the given schedule and corresponding noise
154
+ min_timestep = denoised_timestep_to if self.ts_schedule and denoised_timestep_to is not None else self.min_score_timestep
155
+ max_timestep = denoised_timestep_from if self.ts_schedule_max and denoised_timestep_from is not None else self.num_train_timestep
156
+ timestep = self._get_timestep(
157
+ min_timestep,
158
+ max_timestep,
159
+ batch_size,
160
+ num_frame,
161
+ self.num_frame_per_block,
162
+ uniform_timestep=True
163
+ )
164
+
165
+ # TODO:should we change it to `timestep = self.scheduler.timesteps[timestep]`?
166
+ if self.timestep_shift > 1:
167
+ timestep = self.timestep_shift * \
168
+ (timestep / 1000) / \
169
+ (1 + (self.timestep_shift - 1) * (timestep / 1000)) * 1000
170
+ timestep = timestep.clamp(self.min_step, self.max_step)
171
+
172
+ noise = torch.randn_like(image_or_video)
173
+ noisy_latent = self.scheduler.add_noise(
174
+ image_or_video.flatten(0, 1),
175
+ noise.flatten(0, 1),
176
+ timestep.flatten(0, 1)
177
+ ).detach().unflatten(0, (batch_size, num_frame))
178
+
179
+ # Step 2: Compute the KL grad
180
+ grad, dmd_log_dict = self._compute_kl_grad(
181
+ noisy_image_or_video=noisy_latent,
182
+ estimated_clean_image_or_video=original_latent,
183
+ timestep=timestep,
184
+ conditional_dict=conditional_dict,
185
+ unconditional_dict=unconditional_dict
186
+ )
187
+
188
+ if gradient_mask is not None:
189
+ dmd_loss = 0.5 * F.mse_loss(original_latent.double(
190
+ )[gradient_mask], (original_latent.double() - grad.double()).detach()[gradient_mask], reduction="mean")
191
+ else:
192
+ dmd_loss = 0.5 * F.mse_loss(original_latent.double(
193
+ ), (original_latent.double() - grad.double()).detach(), reduction="mean")
194
+ return dmd_loss, dmd_log_dict
195
+
196
+ def generator_loss(
197
+ self,
198
+ image_or_video_shape,
199
+ conditional_dict: dict,
200
+ unconditional_dict: dict,
201
+ clean_latent: torch.Tensor,
202
+ initial_latent: torch.Tensor = None
203
+ ) -> Tuple[torch.Tensor, dict]:
204
+ """
205
+ Generate image/videos from noise and compute the DMD loss.
206
+ The noisy input to the generator is backward simulated.
207
+ This removes the need of any datasets during distillation.
208
+ See Sec 4.5 of the DMD2 paper (https://arxiv.org/abs/2405.14867) for details.
209
+ Input:
210
+ - image_or_video_shape: a list containing the shape of the image or video [B, F, C, H, W].
211
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
212
+ - unconditional_dict: a dictionary containing the unconditional information (e.g. null/negative text embeddings, null/negative image embeddings).
213
+ - clean_latent: a tensor containing the clean latents [B, F, C, H, W]. Need to be passed when no backward simulation is used.
214
+ Output:
215
+ - loss: a scalar tensor representing the generator loss.
216
+ - generator_log_dict: a dictionary containing the intermediate tensors for logging.
217
+ """
218
+ # Step 1: Unroll generator to obtain fake videos
219
+ pred_image, gradient_mask, denoised_timestep_from, denoised_timestep_to = self._run_generator(
220
+ image_or_video_shape=image_or_video_shape,
221
+ conditional_dict=conditional_dict,
222
+ initial_latent=initial_latent
223
+ )
224
+
225
+ # Step 2: Compute the DMD loss
226
+ dmd_loss, dmd_log_dict = self.compute_distribution_matching_loss(
227
+ image_or_video=pred_image,
228
+ conditional_dict=conditional_dict,
229
+ unconditional_dict=unconditional_dict,
230
+ gradient_mask=gradient_mask,
231
+ denoised_timestep_from=denoised_timestep_from,
232
+ denoised_timestep_to=denoised_timestep_to
233
+ )
234
+
235
+ return dmd_loss, dmd_log_dict
236
+
237
+ def critic_loss(
238
+ self,
239
+ image_or_video_shape,
240
+ conditional_dict: dict,
241
+ unconditional_dict: dict,
242
+ clean_latent: torch.Tensor,
243
+ initial_latent: torch.Tensor = None
244
+ ) -> Tuple[torch.Tensor, dict]:
245
+ """
246
+ Generate image/videos from noise and train the critic with generated samples.
247
+ The noisy input to the generator is backward simulated.
248
+ This removes the need of any datasets during distillation.
249
+ See Sec 4.5 of the DMD2 paper (https://arxiv.org/abs/2405.14867) for details.
250
+ Input:
251
+ - image_or_video_shape: a list containing the shape of the image or video [B, F, C, H, W].
252
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
253
+ - unconditional_dict: a dictionary containing the unconditional information (e.g. null/negative text embeddings, null/negative image embeddings).
254
+ - clean_latent: a tensor containing the clean latents [B, F, C, H, W]. Need to be passed when no backward simulation is used.
255
+ Output:
256
+ - loss: a scalar tensor representing the generator loss.
257
+ - critic_log_dict: a dictionary containing the intermediate tensors for logging.
258
+ """
259
+
260
+ # Step 1: Run generator on backward simulated noisy input
261
+ with torch.no_grad():
262
+ generated_image, _, denoised_timestep_from, denoised_timestep_to = self._run_generator(
263
+ image_or_video_shape=image_or_video_shape,
264
+ conditional_dict=conditional_dict,
265
+ initial_latent=initial_latent
266
+ )
267
+
268
+ # Step 2: Compute the fake prediction
269
+ min_timestep = denoised_timestep_to if self.ts_schedule and denoised_timestep_to is not None else self.min_score_timestep
270
+ max_timestep = denoised_timestep_from if self.ts_schedule_max and denoised_timestep_from is not None else self.num_train_timestep
271
+ critic_timestep = self._get_timestep(
272
+ min_timestep,
273
+ max_timestep,
274
+ image_or_video_shape[0],
275
+ image_or_video_shape[1],
276
+ self.num_frame_per_block,
277
+ uniform_timestep=True
278
+ )
279
+
280
+ if self.timestep_shift > 1:
281
+ critic_timestep = self.timestep_shift * \
282
+ (critic_timestep / 1000) / (1 + (self.timestep_shift - 1) * (critic_timestep / 1000)) * 1000
283
+
284
+ critic_timestep = critic_timestep.clamp(self.min_step, self.max_step)
285
+
286
+ critic_noise = torch.randn_like(generated_image)
287
+ noisy_generated_image = self.scheduler.add_noise(
288
+ generated_image.flatten(0, 1),
289
+ critic_noise.flatten(0, 1),
290
+ critic_timestep.flatten(0, 1)
291
+ ).unflatten(0, image_or_video_shape[:2])
292
+
293
+ _, pred_fake_image = self.fake_score(
294
+ noisy_image_or_video=noisy_generated_image,
295
+ conditional_dict=conditional_dict,
296
+ timestep=critic_timestep
297
+ )
298
+
299
+ # Step 3: Compute the denoising loss for the fake critic
300
+ if self.args.denoising_loss_type == "flow":
301
+ from utils.wan_wrapper import WanDiffusionWrapper
302
+ flow_pred = WanDiffusionWrapper._convert_x0_to_flow_pred(
303
+ scheduler=self.scheduler,
304
+ x0_pred=pred_fake_image.flatten(0, 1),
305
+ xt=noisy_generated_image.flatten(0, 1),
306
+ timestep=critic_timestep.flatten(0, 1)
307
+ )
308
+ pred_fake_noise = None
309
+ else:
310
+ flow_pred = None
311
+ pred_fake_noise = self.scheduler.convert_x0_to_noise(
312
+ x0=pred_fake_image.flatten(0, 1),
313
+ xt=noisy_generated_image.flatten(0, 1),
314
+ timestep=critic_timestep.flatten(0, 1)
315
+ ).unflatten(0, image_or_video_shape[:2])
316
+
317
+ denoising_loss = self.denoising_loss_func(
318
+ x=generated_image.flatten(0, 1),
319
+ x_pred=pred_fake_image.flatten(0, 1),
320
+ noise=critic_noise.flatten(0, 1),
321
+ noise_pred=pred_fake_noise,
322
+ alphas_cumprod=self.scheduler.alphas_cumprod,
323
+ timestep=critic_timestep.flatten(0, 1),
324
+ flow_pred=flow_pred
325
+ )
326
+
327
+ # Step 5: Debugging Log
328
+ critic_log_dict = {
329
+ "critic_timestep": critic_timestep.detach()
330
+ }
331
+
332
+ return denoising_loss, critic_log_dict
model/gan.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ from pipeline import SelfForcingTrainingPipeline
3
+ import torch.nn.functional as F
4
+ from typing import Tuple
5
+ import torch
6
+
7
+ from model.base import SelfForcingModel
8
+
9
+
10
+ class GAN(SelfForcingModel):
11
+ def __init__(self, args, device):
12
+ """
13
+ Initialize the GAN module.
14
+ This class is self-contained and compute generator and fake score losses
15
+ in the forward pass.
16
+ """
17
+ super().__init__(args, device)
18
+ self.num_frame_per_block = getattr(args, "num_frame_per_block", 1)
19
+ self.same_step_across_blocks = getattr(args, "same_step_across_blocks", True)
20
+ self.concat_time_embeddings = getattr(args, "concat_time_embeddings", False)
21
+ self.num_class = args.num_class
22
+ self.relativistic_discriminator = getattr(args, "relativistic_discriminator", False)
23
+
24
+ if self.num_frame_per_block > 1:
25
+ self.generator.model.num_frame_per_block = self.num_frame_per_block
26
+
27
+ self.fake_score.adding_cls_branch(
28
+ atten_dim=1536, num_class=args.num_class, time_embed_dim=1536 if self.concat_time_embeddings else 0)
29
+ self.fake_score.model.requires_grad_(True)
30
+
31
+ self.independent_first_frame = getattr(args, "independent_first_frame", False)
32
+ if self.independent_first_frame:
33
+ self.generator.model.independent_first_frame = True
34
+ if args.gradient_checkpointing:
35
+ self.generator.enable_gradient_checkpointing()
36
+ self.fake_score.enable_gradient_checkpointing()
37
+
38
+ # this will be init later with fsdp-wrapped modules
39
+ self.inference_pipeline: SelfForcingTrainingPipeline = None
40
+
41
+ # Step 2: Initialize all dmd hyperparameters
42
+ self.num_train_timestep = args.num_train_timestep
43
+ self.min_step = int(0.02 * self.num_train_timestep)
44
+ self.max_step = int(0.98 * self.num_train_timestep)
45
+ if hasattr(args, "real_guidance_scale"):
46
+ self.real_guidance_scale = args.real_guidance_scale
47
+ self.fake_guidance_scale = args.fake_guidance_scale
48
+ else:
49
+ self.real_guidance_scale = args.guidance_scale
50
+ self.fake_guidance_scale = 0.0
51
+ self.timestep_shift = getattr(args, "timestep_shift", 1.0)
52
+ self.critic_timestep_shift = getattr(args, "critic_timestep_shift", self.timestep_shift)
53
+ self.ts_schedule = getattr(args, "ts_schedule", True)
54
+ self.ts_schedule_max = getattr(args, "ts_schedule_max", False)
55
+ self.min_score_timestep = getattr(args, "min_score_timestep", 0)
56
+
57
+ self.gan_g_weight = getattr(args, "gan_g_weight", 1e-2)
58
+ self.gan_d_weight = getattr(args, "gan_d_weight", 1e-2)
59
+ self.r1_weight = getattr(args, "r1_weight", 0.0)
60
+ self.r2_weight = getattr(args, "r2_weight", 0.0)
61
+ self.r1_sigma = getattr(args, "r1_sigma", 0.01)
62
+ self.r2_sigma = getattr(args, "r2_sigma", 0.01)
63
+
64
+ if getattr(self.scheduler, "alphas_cumprod", None) is not None:
65
+ self.scheduler.alphas_cumprod = self.scheduler.alphas_cumprod.to(device)
66
+ else:
67
+ self.scheduler.alphas_cumprod = None
68
+
69
+ def _run_cls_pred_branch(self,
70
+ noisy_image_or_video: torch.Tensor,
71
+ conditional_dict: dict,
72
+ timestep: torch.Tensor) -> torch.Tensor:
73
+ """
74
+ Run the classifier prediction branch on the generated image or video.
75
+ Input:
76
+ - image_or_video: a tensor with shape [B, F, C, H, W].
77
+ Output:
78
+ - cls_pred: a tensor with shape [B, 1, 1, 1, 1] representing the feature map for classification.
79
+ """
80
+ _, _, noisy_logit = self.fake_score(
81
+ noisy_image_or_video=noisy_image_or_video,
82
+ conditional_dict=conditional_dict,
83
+ timestep=timestep,
84
+ classify_mode=True,
85
+ concat_time_embeddings=self.concat_time_embeddings
86
+ )
87
+
88
+ return noisy_logit
89
+
90
+ def generator_loss(
91
+ self,
92
+ image_or_video_shape,
93
+ conditional_dict: dict,
94
+ unconditional_dict: dict,
95
+ clean_latent: torch.Tensor,
96
+ initial_latent: torch.Tensor = None
97
+ ) -> Tuple[torch.Tensor, dict]:
98
+ """
99
+ Generate image/videos from noise and compute the DMD loss.
100
+ The noisy input to the generator is backward simulated.
101
+ This removes the need of any datasets during distillation.
102
+ See Sec 4.5 of the DMD2 paper (https://arxiv.org/abs/2405.14867) for details.
103
+ Input:
104
+ - image_or_video_shape: a list containing the shape of the image or video [B, F, C, H, W].
105
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
106
+ - unconditional_dict: a dictionary containing the unconditional information (e.g. null/negative text embeddings, null/negative image embeddings).
107
+ - clean_latent: a tensor containing the clean latents [B, F, C, H, W]. Need to be passed when no backward simulation is used.
108
+ Output:
109
+ - loss: a scalar tensor representing the generator loss.
110
+ - generator_log_dict: a dictionary containing the intermediate tensors for logging.
111
+ """
112
+ # Step 1: Unroll generator to obtain fake videos
113
+ pred_image, gradient_mask, denoised_timestep_from, denoised_timestep_to = self._run_generator(
114
+ image_or_video_shape=image_or_video_shape,
115
+ conditional_dict=conditional_dict,
116
+ initial_latent=initial_latent
117
+ )
118
+
119
+ # Step 2: Get timestep and add noise to generated/real latents
120
+ min_timestep = denoised_timestep_to if self.ts_schedule and denoised_timestep_to is not None else self.min_score_timestep
121
+ max_timestep = denoised_timestep_from if self.ts_schedule_max and denoised_timestep_from is not None else self.num_train_timestep
122
+ critic_timestep = self._get_timestep(
123
+ min_timestep,
124
+ max_timestep,
125
+ image_or_video_shape[0],
126
+ image_or_video_shape[1],
127
+ self.num_frame_per_block,
128
+ uniform_timestep=True
129
+ )
130
+
131
+ if self.critic_timestep_shift > 1:
132
+ critic_timestep = self.critic_timestep_shift * \
133
+ (critic_timestep / 1000) / (1 + (self.critic_timestep_shift - 1) * (critic_timestep / 1000)) * 1000
134
+
135
+ critic_timestep = critic_timestep.clamp(self.min_step, self.max_step)
136
+
137
+ critic_noise = torch.randn_like(pred_image)
138
+ noisy_fake_latent = self.scheduler.add_noise(
139
+ pred_image.flatten(0, 1),
140
+ critic_noise.flatten(0, 1),
141
+ critic_timestep.flatten(0, 1)
142
+ ).unflatten(0, image_or_video_shape[:2])
143
+
144
+ # Step 4: Compute the real GAN discriminator loss
145
+ real_image_or_video = clean_latent.clone()
146
+ critic_noise = torch.randn_like(real_image_or_video)
147
+ noisy_real_latent = self.scheduler.add_noise(
148
+ real_image_or_video.flatten(0, 1),
149
+ critic_noise.flatten(0, 1),
150
+ critic_timestep.flatten(0, 1)
151
+ ).unflatten(0, image_or_video_shape[:2])
152
+
153
+ conditional_dict["prompt_embeds"] = torch.concatenate(
154
+ (conditional_dict["prompt_embeds"], conditional_dict["prompt_embeds"]), dim=0)
155
+ critic_timestep = torch.concatenate((critic_timestep, critic_timestep), dim=0)
156
+ noisy_latent = torch.concatenate((noisy_fake_latent, noisy_real_latent), dim=0)
157
+ _, _, noisy_logit = self.fake_score(
158
+ noisy_image_or_video=noisy_latent,
159
+ conditional_dict=conditional_dict,
160
+ timestep=critic_timestep,
161
+ classify_mode=True,
162
+ concat_time_embeddings=self.concat_time_embeddings
163
+ )
164
+ noisy_fake_logit, noisy_real_logit = noisy_logit.chunk(2, dim=0)
165
+
166
+ if not self.relativistic_discriminator:
167
+ gan_G_loss = F.softplus(-noisy_fake_logit.float()).mean() * self.gan_g_weight
168
+ else:
169
+ relative_fake_logit = noisy_fake_logit - noisy_real_logit
170
+ gan_G_loss = F.softplus(-relative_fake_logit.float()).mean() * self.gan_g_weight
171
+
172
+ return gan_G_loss
173
+
174
+ def critic_loss(
175
+ self,
176
+ image_or_video_shape,
177
+ conditional_dict: dict,
178
+ unconditional_dict: dict,
179
+ clean_latent: torch.Tensor,
180
+ real_image_or_video: torch.Tensor,
181
+ initial_latent: torch.Tensor = None
182
+ ) -> Tuple[torch.Tensor, dict]:
183
+ """
184
+ Generate image/videos from noise and train the critic with generated samples.
185
+ The noisy input to the generator is backward simulated.
186
+ This removes the need of any datasets during distillation.
187
+ See Sec 4.5 of the DMD2 paper (https://arxiv.org/abs/2405.14867) for details.
188
+ Input:
189
+ - image_or_video_shape: a list containing the shape of the image or video [B, F, C, H, W].
190
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
191
+ - unconditional_dict: a dictionary containing the unconditional information (e.g. null/negative text embeddings, null/negative image embeddings).
192
+ - clean_latent: a tensor containing the clean latents [B, F, C, H, W]. Need to be passed when no backward simulation is used.
193
+ Output:
194
+ - loss: a scalar tensor representing the generator loss.
195
+ - critic_log_dict: a dictionary containing the intermediate tensors for logging.
196
+ """
197
+
198
+ # Step 1: Run generator on backward simulated noisy input
199
+ with torch.no_grad():
200
+ generated_image, _, denoised_timestep_from, denoised_timestep_to, num_sim_steps = self._run_generator(
201
+ image_or_video_shape=image_or_video_shape,
202
+ conditional_dict=conditional_dict,
203
+ initial_latent=initial_latent
204
+ )
205
+
206
+ # Step 2: Get timestep and add noise to generated/real latents
207
+ min_timestep = denoised_timestep_to if self.ts_schedule and denoised_timestep_to is not None else self.min_score_timestep
208
+ max_timestep = denoised_timestep_from if self.ts_schedule_max and denoised_timestep_from is not None else self.num_train_timestep
209
+ critic_timestep = self._get_timestep(
210
+ min_timestep,
211
+ max_timestep,
212
+ image_or_video_shape[0],
213
+ image_or_video_shape[1],
214
+ self.num_frame_per_block,
215
+ uniform_timestep=True
216
+ )
217
+
218
+ if self.critic_timestep_shift > 1:
219
+ critic_timestep = self.critic_timestep_shift * \
220
+ (critic_timestep / 1000) / (1 + (self.critic_timestep_shift - 1) * (critic_timestep / 1000)) * 1000
221
+
222
+ critic_timestep = critic_timestep.clamp(self.min_step, self.max_step)
223
+
224
+ critic_noise = torch.randn_like(generated_image)
225
+ noisy_fake_latent = self.scheduler.add_noise(
226
+ generated_image.flatten(0, 1),
227
+ critic_noise.flatten(0, 1),
228
+ critic_timestep.flatten(0, 1)
229
+ ).unflatten(0, image_or_video_shape[:2])
230
+
231
+ # Step 4: Compute the real GAN discriminator loss
232
+ noisy_real_latent = self.scheduler.add_noise(
233
+ real_image_or_video.flatten(0, 1),
234
+ critic_noise.flatten(0, 1),
235
+ critic_timestep.flatten(0, 1)
236
+ ).unflatten(0, image_or_video_shape[:2])
237
+
238
+ conditional_dict_cloned = copy.deepcopy(conditional_dict)
239
+ conditional_dict_cloned["prompt_embeds"] = torch.concatenate(
240
+ (conditional_dict_cloned["prompt_embeds"], conditional_dict_cloned["prompt_embeds"]), dim=0)
241
+ _, _, noisy_logit = self.fake_score(
242
+ noisy_image_or_video=torch.concatenate((noisy_fake_latent, noisy_real_latent), dim=0),
243
+ conditional_dict=conditional_dict_cloned,
244
+ timestep=torch.concatenate((critic_timestep, critic_timestep), dim=0),
245
+ classify_mode=True,
246
+ concat_time_embeddings=self.concat_time_embeddings
247
+ )
248
+ noisy_fake_logit, noisy_real_logit = noisy_logit.chunk(2, dim=0)
249
+
250
+ if not self.relativistic_discriminator:
251
+ gan_D_loss = F.softplus(-noisy_real_logit.float()).mean() + F.softplus(noisy_fake_logit.float()).mean()
252
+ else:
253
+ relative_real_logit = noisy_real_logit - noisy_fake_logit
254
+ gan_D_loss = F.softplus(-relative_real_logit.float()).mean()
255
+ gan_D_loss = gan_D_loss * self.gan_d_weight
256
+
257
+ # R1 regularization
258
+ if self.r1_weight > 0.:
259
+ noisy_real_latent_perturbed = noisy_real_latent.clone()
260
+ epison_real = self.r1_sigma * torch.randn_like(noisy_real_latent_perturbed)
261
+ noisy_real_latent_perturbed = noisy_real_latent_perturbed + epison_real
262
+ noisy_real_logit_perturbed = self._run_cls_pred_branch(
263
+ noisy_image_or_video=noisy_real_latent_perturbed,
264
+ conditional_dict=conditional_dict,
265
+ timestep=critic_timestep
266
+ )
267
+
268
+ r1_grad = (noisy_real_logit_perturbed - noisy_real_logit) / self.r1_sigma
269
+ r1_loss = self.r1_weight * torch.mean((r1_grad)**2)
270
+ else:
271
+ r1_loss = torch.zeros_like(gan_D_loss)
272
+
273
+ # R2 regularization
274
+ if self.r2_weight > 0.:
275
+ noisy_fake_latent_perturbed = noisy_fake_latent.clone()
276
+ epison_generated = self.r2_sigma * torch.randn_like(noisy_fake_latent_perturbed)
277
+ noisy_fake_latent_perturbed = noisy_fake_latent_perturbed + epison_generated
278
+ noisy_fake_logit_perturbed = self._run_cls_pred_branch(
279
+ noisy_image_or_video=noisy_fake_latent_perturbed,
280
+ conditional_dict=conditional_dict,
281
+ timestep=critic_timestep
282
+ )
283
+
284
+ r2_grad = (noisy_fake_logit_perturbed - noisy_fake_logit) / self.r2_sigma
285
+ r2_loss = self.r2_weight * torch.mean((r2_grad)**2)
286
+ else:
287
+ r2_loss = torch.zeros_like(r2_loss)
288
+
289
+ critic_log_dict = {
290
+ "critic_timestep": critic_timestep.detach(),
291
+ 'noisy_real_logit': noisy_real_logit.detach(),
292
+ 'noisy_fake_logit': noisy_fake_logit.detach(),
293
+ }
294
+
295
+ return (gan_D_loss, r1_loss, r2_loss), critic_log_dict
model/ode_regression.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn.functional as F
2
+ from typing import Tuple
3
+ import torch
4
+
5
+ from model.base import BaseModel
6
+ from utils.wan_wrapper import WanDiffusionWrapper, WanTextEncoder, WanVAEWrapper
7
+
8
+
9
+ class ODERegression(BaseModel):
10
+ def __init__(self, args, device):
11
+ """
12
+ Initialize the ODERegression module.
13
+ This class is self-contained and compute generator losses
14
+ in the forward pass given precomputed ode solution pairs.
15
+ This class supports the ode regression loss for both causal and bidirectional models.
16
+ See Sec 4.3 of CausVid https://arxiv.org/abs/2412.07772 for details
17
+ """
18
+ super().__init__(args, device)
19
+
20
+ # Step 1: Initialize all models
21
+
22
+ self.generator = WanDiffusionWrapper(**getattr(args, "model_kwargs", {}), is_causal=True)
23
+ self.generator.model.requires_grad_(True)
24
+ if getattr(args, "generator_ckpt", False):
25
+ print(f"Loading pretrained generator from {args.generator_ckpt}")
26
+ state_dict = torch.load(args.generator_ckpt, map_location="cpu")[
27
+ 'generator']
28
+ self.generator.load_state_dict(
29
+ state_dict, strict=True
30
+ )
31
+
32
+ self.num_frame_per_block = getattr(args, "num_frame_per_block", 1)
33
+
34
+ if self.num_frame_per_block > 1:
35
+ self.generator.model.num_frame_per_block = self.num_frame_per_block
36
+
37
+ self.independent_first_frame = getattr(args, "independent_first_frame", False)
38
+ if self.independent_first_frame:
39
+ self.generator.model.independent_first_frame = True
40
+ if args.gradient_checkpointing:
41
+ self.generator.enable_gradient_checkpointing()
42
+
43
+ # Step 2: Initialize all hyperparameters
44
+ self.timestep_shift = getattr(args, "timestep_shift", 1.0)
45
+
46
+ def _initialize_models(self, args):
47
+ self.generator = WanDiffusionWrapper(**getattr(args, "model_kwargs", {}), is_causal=True)
48
+ self.generator.model.requires_grad_(True)
49
+
50
+ self.text_encoder = WanTextEncoder()
51
+ self.text_encoder.requires_grad_(False)
52
+
53
+ self.vae = WanVAEWrapper()
54
+ self.vae.requires_grad_(False)
55
+
56
+ @torch.no_grad()
57
+ def _prepare_generator_input(self, ode_latent: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
58
+ """
59
+ Given a tensor containing the whole ODE sampling trajectories,
60
+ randomly choose an intermediate timestep and return the latent as well as the corresponding timestep.
61
+ Input:
62
+ - ode_latent: a tensor containing the whole ODE sampling trajectories [batch_size, num_denoising_steps, num_frames, num_channels, height, width].
63
+ Output:
64
+ - noisy_input: a tensor containing the selected latent [batch_size, num_frames, num_channels, height, width].
65
+ - timestep: a tensor containing the corresponding timestep [batch_size].
66
+ """
67
+ batch_size, num_denoising_steps, num_frames, num_channels, height, width = ode_latent.shape
68
+
69
+ # Step 1: Randomly choose a timestep for each frame
70
+ index = self._get_timestep(
71
+ 0,
72
+ len(self.denoising_step_list),
73
+ batch_size,
74
+ num_frames,
75
+ self.num_frame_per_block,
76
+ uniform_timestep=False
77
+ )
78
+ if self.args.i2v:
79
+ index[:, 0] = len(self.denoising_step_list) - 1
80
+
81
+ noisy_input = torch.gather(
82
+ ode_latent, dim=1,
83
+ index=index.reshape(batch_size, 1, num_frames, 1, 1, 1).expand(
84
+ -1, -1, -1, num_channels, height, width).to(self.device)
85
+ ).squeeze(1)
86
+
87
+ timestep = self.denoising_step_list[index].to(self.device)
88
+
89
+ # if self.extra_noise_step > 0:
90
+ # random_timestep = torch.randint(0, self.extra_noise_step, [
91
+ # batch_size, num_frames], device=self.device, dtype=torch.long)
92
+ # perturbed_noisy_input = self.scheduler.add_noise(
93
+ # noisy_input.flatten(0, 1),
94
+ # torch.randn_like(noisy_input.flatten(0, 1)),
95
+ # random_timestep.flatten(0, 1)
96
+ # ).detach().unflatten(0, (batch_size, num_frames)).type_as(noisy_input)
97
+
98
+ # noisy_input[timestep == 0] = perturbed_noisy_input[timestep == 0]
99
+
100
+ return noisy_input, timestep
101
+
102
+ def generator_loss(self, ode_latent: torch.Tensor, conditional_dict: dict) -> Tuple[torch.Tensor, dict]:
103
+ """
104
+ Generate image/videos from noisy latents and compute the ODE regression loss.
105
+ Input:
106
+ - ode_latent: a tensor containing the ODE latents [batch_size, num_denoising_steps, num_frames, num_channels, height, width].
107
+ They are ordered from most noisy to clean latents.
108
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
109
+ Output:
110
+ - loss: a scalar tensor representing the generator loss.
111
+ - log_dict: a dictionary containing additional information for loss timestep breakdown.
112
+ """
113
+ # Step 1: Run generator on noisy latents
114
+ target_latent = ode_latent[:, -1]
115
+
116
+ noisy_input, timestep = self._prepare_generator_input(
117
+ ode_latent=ode_latent)
118
+
119
+ _, pred_image_or_video = self.generator(
120
+ noisy_image_or_video=noisy_input,
121
+ conditional_dict=conditional_dict,
122
+ timestep=timestep
123
+ )
124
+
125
+ # Step 2: Compute the regression loss
126
+ mask = timestep != 0
127
+
128
+ loss = F.mse_loss(
129
+ pred_image_or_video[mask], target_latent[mask], reduction="mean")
130
+
131
+ log_dict = {
132
+ "unnormalized_loss": F.mse_loss(pred_image_or_video, target_latent, reduction='none').mean(dim=[1, 2, 3, 4]).detach(),
133
+ "timestep": timestep.float().mean(dim=1).detach(),
134
+ "input": noisy_input.detach(),
135
+ "output": pred_image_or_video.detach(),
136
+ }
137
+
138
+ return loss, log_dict
model/sid.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pipeline import SelfForcingTrainingPipeline
2
+ from typing import Optional, Tuple
3
+ import torch
4
+
5
+ from model.base import SelfForcingModel
6
+
7
+
8
+ class SiD(SelfForcingModel):
9
+ def __init__(self, args, device):
10
+ """
11
+ Initialize the DMD (Distribution Matching Distillation) module.
12
+ This class is self-contained and compute generator and fake score losses
13
+ in the forward pass.
14
+ """
15
+ super().__init__(args, device)
16
+ self.num_frame_per_block = getattr(args, "num_frame_per_block", 1)
17
+
18
+ if self.num_frame_per_block > 1:
19
+ self.generator.model.num_frame_per_block = self.num_frame_per_block
20
+
21
+ if args.gradient_checkpointing:
22
+ self.generator.enable_gradient_checkpointing()
23
+ self.fake_score.enable_gradient_checkpointing()
24
+ self.real_score.enable_gradient_checkpointing()
25
+
26
+ # this will be init later with fsdp-wrapped modules
27
+ self.inference_pipeline: SelfForcingTrainingPipeline = None
28
+
29
+ # Step 2: Initialize all dmd hyperparameters
30
+ self.num_train_timestep = args.num_train_timestep
31
+ self.min_step = int(0.02 * self.num_train_timestep)
32
+ self.max_step = int(0.98 * self.num_train_timestep)
33
+ if hasattr(args, "real_guidance_scale"):
34
+ self.real_guidance_scale = args.real_guidance_scale
35
+ else:
36
+ self.real_guidance_scale = args.guidance_scale
37
+ self.timestep_shift = getattr(args, "timestep_shift", 1.0)
38
+ self.sid_alpha = getattr(args, "sid_alpha", 1.0)
39
+ self.ts_schedule = getattr(args, "ts_schedule", True)
40
+ self.ts_schedule_max = getattr(args, "ts_schedule_max", False)
41
+
42
+ if getattr(self.scheduler, "alphas_cumprod", None) is not None:
43
+ self.scheduler.alphas_cumprod = self.scheduler.alphas_cumprod.to(device)
44
+ else:
45
+ self.scheduler.alphas_cumprod = None
46
+
47
+ def compute_distribution_matching_loss(
48
+ self,
49
+ image_or_video: torch.Tensor,
50
+ conditional_dict: dict,
51
+ unconditional_dict: dict,
52
+ gradient_mask: Optional[torch.Tensor] = None,
53
+ denoised_timestep_from: int = 0,
54
+ denoised_timestep_to: int = 0
55
+ ) -> Tuple[torch.Tensor, dict]:
56
+ """
57
+ Compute the DMD loss (eq 7 in https://arxiv.org/abs/2311.18828).
58
+ Input:
59
+ - image_or_video: a tensor with shape [B, F, C, H, W] where the number of frame is 1 for images.
60
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
61
+ - unconditional_dict: a dictionary containing the unconditional information (e.g. null/negative text embeddings, null/negative image embeddings).
62
+ - gradient_mask: a boolean tensor with the same shape as image_or_video indicating which pixels to compute loss .
63
+ Output:
64
+ - dmd_loss: a scalar tensor representing the DMD loss.
65
+ - dmd_log_dict: a dictionary containing the intermediate tensors for logging.
66
+ """
67
+ original_latent = image_or_video
68
+
69
+ batch_size, num_frame = image_or_video.shape[:2]
70
+
71
+ # Step 1: Randomly sample timestep based on the given schedule and corresponding noise
72
+ min_timestep = denoised_timestep_to if self.ts_schedule and denoised_timestep_to is not None else self.min_score_timestep
73
+ max_timestep = denoised_timestep_from if self.ts_schedule_max and denoised_timestep_from is not None else self.num_train_timestep
74
+ timestep = self._get_timestep(
75
+ min_timestep,
76
+ max_timestep,
77
+ batch_size,
78
+ num_frame,
79
+ self.num_frame_per_block,
80
+ uniform_timestep=True
81
+ )
82
+
83
+ if self.timestep_shift > 1:
84
+ timestep = self.timestep_shift * \
85
+ (timestep / 1000) / \
86
+ (1 + (self.timestep_shift - 1) * (timestep / 1000)) * 1000
87
+ timestep = timestep.clamp(self.min_step, self.max_step)
88
+
89
+ noise = torch.randn_like(image_or_video)
90
+ noisy_latent = self.scheduler.add_noise(
91
+ image_or_video.flatten(0, 1),
92
+ noise.flatten(0, 1),
93
+ timestep.flatten(0, 1)
94
+ ).unflatten(0, (batch_size, num_frame))
95
+
96
+ # Step 2: SiD (May be wrap it?)
97
+ noisy_image_or_video = noisy_latent
98
+ # Step 2.1: Compute the fake score
99
+ _, pred_fake_image = self.fake_score(
100
+ noisy_image_or_video=noisy_image_or_video,
101
+ conditional_dict=conditional_dict,
102
+ timestep=timestep
103
+ )
104
+ # Step 2.2: Compute the real score
105
+ # We compute the conditional and unconditional prediction
106
+ # and add them together to achieve cfg (https://arxiv.org/abs/2207.12598)
107
+ # NOTE: This step may cause OOM issue, which can be addressed by the CFG-free technique
108
+
109
+ _, pred_real_image_cond = self.real_score(
110
+ noisy_image_or_video=noisy_image_or_video,
111
+ conditional_dict=conditional_dict,
112
+ timestep=timestep
113
+ )
114
+
115
+ _, pred_real_image_uncond = self.real_score(
116
+ noisy_image_or_video=noisy_image_or_video,
117
+ conditional_dict=unconditional_dict,
118
+ timestep=timestep
119
+ )
120
+
121
+ pred_real_image = pred_real_image_cond + (
122
+ pred_real_image_cond - pred_real_image_uncond
123
+ ) * self.real_guidance_scale
124
+
125
+ # Step 2.3: SiD Loss
126
+ # TODO: Add alpha
127
+ # TODO: Double?
128
+ sid_loss = (pred_real_image.double() - pred_fake_image.double()) * ((pred_real_image.double() - original_latent.double()) - self.sid_alpha * (pred_real_image.double() - pred_fake_image.double()))
129
+
130
+ # Step 2.4: Loss normalizer
131
+ with torch.no_grad():
132
+ p_real = (original_latent - pred_real_image)
133
+ normalizer = torch.abs(p_real).mean(dim=[1, 2, 3, 4], keepdim=True)
134
+ sid_loss = sid_loss / normalizer
135
+
136
+ sid_loss = torch.nan_to_num(sid_loss)
137
+ num_frame = sid_loss.shape[1]
138
+ sid_loss = sid_loss.mean()
139
+
140
+ sid_log_dict = {
141
+ "dmdtrain_gradient_norm": torch.zeros_like(sid_loss),
142
+ "timestep": timestep.detach()
143
+ }
144
+
145
+ return sid_loss, sid_log_dict
146
+
147
+ def generator_loss(
148
+ self,
149
+ image_or_video_shape,
150
+ conditional_dict: dict,
151
+ unconditional_dict: dict,
152
+ clean_latent: torch.Tensor,
153
+ initial_latent: torch.Tensor = None
154
+ ) -> Tuple[torch.Tensor, dict]:
155
+ """
156
+ Generate image/videos from noise and compute the DMD loss.
157
+ The noisy input to the generator is backward simulated.
158
+ This removes the need of any datasets during distillation.
159
+ See Sec 4.5 of the DMD2 paper (https://arxiv.org/abs/2405.14867) for details.
160
+ Input:
161
+ - image_or_video_shape: a list containing the shape of the image or video [B, F, C, H, W].
162
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
163
+ - unconditional_dict: a dictionary containing the unconditional information (e.g. null/negative text embeddings, null/negative image embeddings).
164
+ - clean_latent: a tensor containing the clean latents [B, F, C, H, W]. Need to be passed when no backward simulation is used.
165
+ Output:
166
+ - loss: a scalar tensor representing the generator loss.
167
+ - generator_log_dict: a dictionary containing the intermediate tensors for logging.
168
+ """
169
+ # Step 1: Unroll generator to obtain fake videos
170
+ pred_image, gradient_mask, denoised_timestep_from, denoised_timestep_to = self._run_generator(
171
+ image_or_video_shape=image_or_video_shape,
172
+ conditional_dict=conditional_dict,
173
+ initial_latent=initial_latent
174
+ )
175
+
176
+ # Step 2: Compute the DMD loss
177
+ dmd_loss, dmd_log_dict = self.compute_distribution_matching_loss(
178
+ image_or_video=pred_image,
179
+ conditional_dict=conditional_dict,
180
+ unconditional_dict=unconditional_dict,
181
+ gradient_mask=gradient_mask,
182
+ denoised_timestep_from=denoised_timestep_from,
183
+ denoised_timestep_to=denoised_timestep_to
184
+ )
185
+
186
+ return dmd_loss, dmd_log_dict
187
+
188
+ def critic_loss(
189
+ self,
190
+ image_or_video_shape,
191
+ conditional_dict: dict,
192
+ unconditional_dict: dict,
193
+ clean_latent: torch.Tensor,
194
+ initial_latent: torch.Tensor = None
195
+ ) -> Tuple[torch.Tensor, dict]:
196
+ """
197
+ Generate image/videos from noise and train the critic with generated samples.
198
+ The noisy input to the generator is backward simulated.
199
+ This removes the need of any datasets during distillation.
200
+ See Sec 4.5 of the DMD2 paper (https://arxiv.org/abs/2405.14867) for details.
201
+ Input:
202
+ - image_or_video_shape: a list containing the shape of the image or video [B, F, C, H, W].
203
+ - conditional_dict: a dictionary containing the conditional information (e.g. text embeddings, image embeddings).
204
+ - unconditional_dict: a dictionary containing the unconditional information (e.g. null/negative text embeddings, null/negative image embeddings).
205
+ - clean_latent: a tensor containing the clean latents [B, F, C, H, W]. Need to be passed when no backward simulation is used.
206
+ Output:
207
+ - loss: a scalar tensor representing the generator loss.
208
+ - critic_log_dict: a dictionary containing the intermediate tensors for logging.
209
+ """
210
+
211
+ # Step 1: Run generator on backward simulated noisy input
212
+ with torch.no_grad():
213
+ generated_image, _, denoised_timestep_from, denoised_timestep_to = self._run_generator(
214
+ image_or_video_shape=image_or_video_shape,
215
+ conditional_dict=conditional_dict,
216
+ initial_latent=initial_latent
217
+ )
218
+
219
+ # Step 2: Compute the fake prediction
220
+ min_timestep = denoised_timestep_to if self.ts_schedule and denoised_timestep_to is not None else self.min_score_timestep
221
+ max_timestep = denoised_timestep_from if self.ts_schedule_max and denoised_timestep_from is not None else self.num_train_timestep
222
+ critic_timestep = self._get_timestep(
223
+ min_timestep,
224
+ max_timestep,
225
+ image_or_video_shape[0],
226
+ image_or_video_shape[1],
227
+ self.num_frame_per_block,
228
+ uniform_timestep=True
229
+ )
230
+
231
+ if self.timestep_shift > 1:
232
+ critic_timestep = self.timestep_shift * \
233
+ (critic_timestep / 1000) / (1 + (self.timestep_shift - 1) * (critic_timestep / 1000)) * 1000
234
+
235
+ critic_timestep = critic_timestep.clamp(self.min_step, self.max_step)
236
+
237
+ critic_noise = torch.randn_like(generated_image)
238
+ noisy_generated_image = self.scheduler.add_noise(
239
+ generated_image.flatten(0, 1),
240
+ critic_noise.flatten(0, 1),
241
+ critic_timestep.flatten(0, 1)
242
+ ).unflatten(0, image_or_video_shape[:2])
243
+
244
+ _, pred_fake_image = self.fake_score(
245
+ noisy_image_or_video=noisy_generated_image,
246
+ conditional_dict=conditional_dict,
247
+ timestep=critic_timestep
248
+ )
249
+
250
+ # Step 3: Compute the denoising loss for the fake critic
251
+ if self.args.denoising_loss_type == "flow":
252
+ from utils.wan_wrapper import WanDiffusionWrapper
253
+ flow_pred = WanDiffusionWrapper._convert_x0_to_flow_pred(
254
+ scheduler=self.scheduler,
255
+ x0_pred=pred_fake_image.flatten(0, 1),
256
+ xt=noisy_generated_image.flatten(0, 1),
257
+ timestep=critic_timestep.flatten(0, 1)
258
+ )
259
+ pred_fake_noise = None
260
+ else:
261
+ flow_pred = None
262
+ pred_fake_noise = self.scheduler.convert_x0_to_noise(
263
+ x0=pred_fake_image.flatten(0, 1),
264
+ xt=noisy_generated_image.flatten(0, 1),
265
+ timestep=critic_timestep.flatten(0, 1)
266
+ ).unflatten(0, image_or_video_shape[:2])
267
+
268
+ denoising_loss = self.denoising_loss_func(
269
+ x=generated_image.flatten(0, 1),
270
+ x_pred=pred_fake_image.flatten(0, 1),
271
+ noise=critic_noise.flatten(0, 1),
272
+ noise_pred=pred_fake_noise,
273
+ alphas_cumprod=self.scheduler.alphas_cumprod,
274
+ timestep=critic_timestep.flatten(0, 1),
275
+ flow_pred=flow_pred
276
+ )
277
+
278
+ # Step 5: Debugging Log
279
+ critic_log_dict = {
280
+ "critic_timestep": critic_timestep.detach()
281
+ }
282
+
283
+ return denoising_loss, critic_log_dict