Source: sources/0363/REG-b9c867cff57a/DiT/forward_with_cfg.py
SHA256: 084deb64750649bccd5a2616884494002ab9030ed74769d9f57650a470d41d51
Read at: 2026-10-25T10:05:28.130716+00:00
1: import torch
2: import torch.nn as nn
3: import numpy as np
4: import math
5: import warnings
6: from typing import Optional
7: from torch.cuda.amp import autocast
8: 
9: def forward_with_cfg(self, x, t, y, cfg_param: Optional[dict]= None):
10:         """
11:         Forward pass of DiT, but also batches the unconditional forward pass for classifier-free guidance.
12:         """
13:         # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb
14:         half = x[: len(x) // 2]
15: 
16:         if not self.training:
17:             assert torch.all(t[:len(t) // 2] == t[len(t) // 2:]), "First half of t does not equal the second half in sampling"
18:         else:
19:             warnings.warn(f"REG only modifies code for sampling, haven't considered training.")
20: 
21:         if cfg_param['cfg_type'] == 'original':
22:             with autocast():
23:                 combined = torch.cat([half, half], dim=0)
24:                 model_out = self.forward(combined, t, y)
25:                 eps, rest = model_out[:, :3], model_out[:, 3:]
26:                 cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
27:                 # notice that in original DiT codebase, they use: half_eps = uncond_eps + a * (cond_eps - uncond_eps)
28:                 # but we use: half_eps = cond_eps + b * (cond_eps - uncond_eps)
29:                 # essentially they are identical by the relationship a - 1 = b.
30:                 # We use the second one for implementing our approach.
31:                 # So the value of cfg_scale in our case should differ from the original DiT by 1.0
32:                 half_eps = cond_eps + cfg_param['cfg_scale'] * (cond_eps - uncond_eps)
33:         elif cfg_param['cfg_type'] == 'intervalt':
34:             with autocast():
35:                 interval_min, interval_max = cfg_param['intervalt']
36:                 in_interval = (interval_min <= t[0]) & (t[0] <= interval_max)
37:                 if in_interval:
38:                     combined = torch.cat([half, half], dim=0)
39:                     model_out = self.forward(combined, t, y)
40:                     eps, rest = model_out[:, :3], model_out[:, 3:]
41:                     cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
42:                     half_eps = cond_eps + cfg_param['cfg_scale'] * (cond_eps - uncond_eps)
43:                 else:
44:                     model_out = self.forward(half, t[:half.shape[0]], y[:half.shape[0]])
45:                     half_eps, rest = model_out[:, :3], model_out[:, 3:]
46:                     rest = torch.cat([rest, rest], dim=0)
47:         elif cfg_param['cfg_type'] == 'linear':
48:             with autocast():
49:                 start_scale, end_scale = cfg_param['cfg_scale'], cfg_param['end_scale']
50:                 k = (end_scale - start_scale) / (0-1000) # in sampling, t from 1000 to 0.
51:                 combined = torch.cat([half, half], dim=0)
52:                 model_out = self.forward(combined, t, y)
53:                 eps, rest = model_out[:, :3], model_out[:, 3:]
54:                 cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
55:                 shape = tuple([-1] + [1] * (cond_eps.ndimension() - 1))
56:                 half_eps = cond_eps + (t[:len(t)//2] * k + start_scale).view(*shape) * (cond_eps - uncond_eps)
57:         elif cfg_param['cfg_type'] == 'cosine':
58:             with autocast():
59:                 combined = torch.cat([half, half], dim=0)
60:                 model_out = self.forward(combined, t, y)
61:                 eps, rest = model_out[:, :3], model_out[:, 3:]
62:                 cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
63:                 progress = 1 - t[:len(t)//2]/1000
64:                 coeff = (1 - torch.cos(torch.pi * torch.pow(progress, cfg_param['s']))) * 0.5 * cfg_param['cfg_scale']
65:                 shape = tuple([-1] + [1] * (cond_eps.ndimension() - 1))
66:                 half_eps = uncond_eps + coeff.view(*shape) * (cond_eps - uncond_eps)
67:                 # The above is the original used in MDT, and it is equivalent to:
68:                 # half_eps = cond_eps + (coeff.view(*shape)-1) * (cond_eps - uncond_eps)
69:         elif cfg_param['cfg_type'] == 'reg_original':
70:             alpha_bar = cfg_param['alpha_bar']
71:             with autocast():
72:                 with torch.enable_grad():
73:                     half.requires_grad_(True)
74:                     combined = torch.cat([half, half], dim=0)
75:                     model_out = self.forward(combined, t, y)
76:                     eps  = model_out[:, :self.in_channels]
77:                     cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
78:                     shape = tuple([-1] + [1] * (cond_eps.ndimension() - 1))
79:                     tmp = torch.autograd.grad(cond_eps.sum(), half, create_graph=False)[0].detach()
80:                     half.requires_grad_(False)
81:                 cond_eps, uncond_eps = cond_eps.detach(), uncond_eps.detach()
82:                 rest = model_out[:, 3:].detach()
83:                 coeff = cfg_param['cfg_scale'] * (1 - torch.sqrt(1 - alpha_bar[:len(alpha_bar)//2]).view(*shape) * tmp)
84:                 half_eps = (cond_eps + coeff * (cond_eps - uncond_eps))[:,:3]
85:         elif cfg_param['cfg_type'] == 'reg_intervalt':
86:             alpha_bar = cfg_param['alpha_bar']
87:             interval_min, interval_max = cfg_param['intervalt']
88:             assert torch.max(t) == torch.min(t), f"the max and min of t is identical"
89:             with autocast():
90:                 in_interval = (interval_min <= t[0]) & (t[0] <= interval_max)
91:                 if in_interval:
92:                     with torch.enable_grad():
93:                         half.requires_grad_(True)
94:                         combined = torch.cat([half, half], dim=0)
95:                         model_out = self.forward(combined, t, y)
96:                         eps  = model_out[:, :self.in_channels]
97:                         cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
98:                         shape = tuple([-1] + [1] * (cond_eps.ndimension() - 1))
99:                         tmp = torch.autograd.grad(cond_eps.sum(), half, create_graph=False)[0].detach()
100:                         half.requires_grad_(False)
101:                     cond_eps, uncond_eps = cond_eps.detach(), uncond_eps.detach()
102:                     rest = model_out[:, 3:].detach()
103:                     coeff = cfg_param['cfg_scale'] * (1 - torch.sqrt(1 - alpha_bar[:len(alpha_bar)//2]).view(*shape) * tmp)
104:                     half_eps = (cond_eps + coeff * (cond_eps - uncond_eps))[:,:3]
105:                 else:
106:                     model_out = self.forward(half, t[:half.shape[0]], y[:half.shape[0]])
107:                     half_eps, rest = model_out[:, :3], model_out[:, 3:]
108:                     rest = torch.cat([rest, rest], dim=0)
109:         elif cfg_param['cfg_type'] == 'reg_cosine':
110:             alpha_bar = cfg_param['alpha_bar']
111:             with autocast():
112:                 with torch.enable_grad():
113:                     half.requires_grad_(True)
114:                     combined = torch.cat([half, half], dim=0)
115:                     model_out = self.forward(combined, t, y)
116:                     eps  = model_out[:, :self.in_channels]
117:                     cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
118:                     shape = tuple([-1] + [1] * (cond_eps.ndimension() - 1))
119:                     tmp = torch.autograd.grad(cond_eps.sum(), half, create_graph=False)[0].detach()
120:                     half.requires_grad_(False)
121:                 cond_eps, uncond_eps = cond_eps.detach(), uncond_eps.detach()
122:                 rest = model_out[:, 3:].detach()
123:                 progress = 1 - t[:len(t)//2]/1000 # in sampling, t from 1000 to 0.
124:                 coeff = (1 - torch.cos(torch.pi * torch.pow(progress, cfg_param['s']))) * 0.5 * cfg_param['cfg_scale']
125:                 coeff = coeff.view(*shape) * (1 - torch.sqrt(1 - alpha_bar[:len(alpha_bar)//2]).view(*shape) * tmp)
126:                 half_eps = (cond_eps + coeff * (cond_eps - uncond_eps))[:,:3]
127:         elif cfg_param['cfg_type'] == 'reg_linear':
128:             alpha_bar = cfg_param['alpha_bar']
129:             start_scale, end_scale = cfg_param['cfg_scale'], cfg_param['end_scale']
130:             k = (end_scale - start_scale) / (0 - 1000)  # in sampling, t from 1000 to 0.
131:             with autocast():
132:                 with torch.enable_grad():
133:                     half.requires_grad_(True)
134:                     combined = torch.cat([half, half], dim=0)
135:                     model_out = self.forward(combined, t, y)
136:                     eps  = model_out[:, :self.in_channels]
137:                     cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
138:                     shape = tuple([-1] + [1] * (cond_eps.ndimension() - 1))
139:                     tmp = torch.autograd.grad(cond_eps.sum(), half, create_graph=False)[0].detach()
140:                     half.requires_grad_(False)
141:                 cond_eps, uncond_eps = cond_eps.detach(), uncond_eps.detach()
142:                 rest = model_out[:, 3:].detach()
143:                 coeff = (t[:len(t) // 2] * k + start_scale).view(*shape) * (1 - torch.sqrt(1 - alpha_bar[:len(alpha_bar)//2]).view(*shape) * tmp)
144:                 half_eps = (cond_eps + coeff * (cond_eps - uncond_eps))[:,:3]
145:         else:
146:             raise NotImplementedError(f"Unsupported cfg_type={cfg_param['cfg_type']}")
147:         eps = torch.cat([half_eps, half_eps], dim=0)
148:         return torch.cat([eps, rest], dim=1)
149: 
