Source: sources/0363/REG-b9c867cff57a/EDMv2/generate_images.py
SHA256: 165c850321f7f4c01e42a0045d8bf70d84eb524647b928609ec4b736bd983e67
Read at: 2026-10-25T10:06:04.198077+00:00
93: def edm_sampler(
94:     net, noise, labels=None, gnet=None,
95:     num_steps=32, sigma_min=0.002, sigma_max=80, rho=7, guidance=1,
96:     S_churn=0, S_min=0, S_max=float('inf'), S_noise=1,
97:     dtype=torch.float32, randn_like=torch.randn_like,
98:     cfg = None,
99: ):
100:     assert isinstance(cfg, dict), 'cfg must be a dict'
101: 
102:     def denoise(x, t, cfg):
103:         guid_network_labels = labels if cfg['guid_network_labels'] else None
104:         if cfg['cfg_type'] == 'original':
105:             Dx = net(x, t, labels).to(dtype)
106:             if guidance == 1:
107:                 return Dx
108:             ref_Dx = gnet(x, t, guid_network_labels).to(dtype)
109:             res = ref_Dx.lerp(Dx, guidance) # original in edm, but essentially is the same as: ref_Dx + guidance * (Dx - ref_Dx)
110:             peak_mem = torch.cuda.max_memory_allocated()
111:             print(f"Peak memory during computation: {peak_mem/1024**3:.4f} GB GB")
112:             return res
113:         elif cfg['cfg_type'] == 'linear':
114:             Dx = net(x, t, labels).to(dtype)
115:             k = (guidance - cfg['end_scale']) / (sigma_max - sigma_min)
116:             cur_guidance = k * (t - sigma_max) + guidance
117:             ref_Dx = gnet(x, t, guid_network_labels).to(dtype)
118:             return Dx + cur_guidance * (Dx - ref_Dx)
119:         elif cfg['cfg_type'] == 'intervalt':
120:             Dx = net(x, t, labels).to(dtype)
121:             if cfg['intervalt'][0] <= t <= cfg['intervalt'][1]:
122:                 ref_Dx = gnet(x, t, guid_network_labels).to(dtype)
123:                 return ref_Dx.lerp(Dx, guidance)
124:             else:
125:                 return Dx
126:         elif cfg['cfg_type'] == 'cosine':
127:             Dx = net(x, t, labels).to(dtype)
128:             progress = 1.0 - t / sigma_max
129:             # print(f"t={t}, progress= {progress}")
130:             coeff = (1 - torch.cos(torch.pi * torch.pow(progress, cfg['s']))) * 0.5 * guidance
131:             ref_Dx = gnet(x, t, guid_network_labels).to(dtype)
132:             res = Dx + coeff * (Dx - ref_Dx)
133:             return res
134:         elif cfg['cfg_type'] == 'reg_original':
135:             
136:             with torch.enable_grad():
137:                 x = x.detach()
138:                 x.requires_grad_(True)
139:                 Dx = net(x, t, labels)
140: 
141:                 wrk = torch.autograd.grad(Dx.sum(), x, create_graph=False, retain_graph=False)[0].detach()
142: 
143:                 peak_mem = torch.cuda.max_memory_allocated()
144: 
145:                 x.requires_grad_(False)
146:                 
147:             Dx = Dx.detach()
148:             ref_Dx = gnet(x, t, guid_network_labels).to(dtype)
149:             res = Dx + guidance * wrk * (Dx - ref_Dx)
150:             del Dx, wrk, ref_Dx
151:             torch.cuda.empty_cache()
152:             return res
153:         elif cfg['cfg_type'] == 'reg_intervalt':
154:             if cfg['intervalt'][0] <= t <= cfg['intervalt'][1]:
155:                 with torch.enable_grad():
156:                     x = x.detach()
157:                     x.requires_grad_(True)
158:                     Dx = net(x, t, labels)
159:                     wrk = torch.autograd.grad(Dx.sum(), x, create_graph=False, retain_graph=False)[0].detach()
160:                     x.requires_grad_(False)
161:                 Dx = Dx.detach()
162:                 ref_Dx = gnet(x, t, guid_network_labels).to(dtype)
163:                 res = Dx + guidance * wrk * (Dx - ref_Dx)
164:                 del Dx, wrk, ref_Dx
165:                 torch.cuda.empty_cache()
166:                 return res
167:             else:
168:                 res = net(x, t, labels)
169:                 return res
170:         elif cfg['cfg_type'] == 'reg_linear':
171:             with torch.enable_grad():
172:                 x = x.detach()
173:                 x.requires_grad_(True)
174:                 Dx = net(x, t, labels)
175:                 wrk = torch.autograd.grad(Dx.sum(), x, create_graph=False, retain_graph=False)[0].detach()
176:                 x.requires_grad_(False)
177:             Dx = Dx.detach()
178:             k = (guidance - cfg['end_scale']) / (sigma_max - sigma_min)
179:             cur_guidance = k * (t - sigma_max) + guidance
180:             ref_Dx = gnet(x, t, guid_network_labels).to(dtype)
181:             res = Dx + cur_guidance * wrk * (Dx - ref_Dx)
182:             del Dx, wrk, ref_Dx
183:             torch.cuda.empty_cache()
184:             return res
185:         elif cfg['cfg_type'] == 'reg_cosine':
186:             with torch.enable_grad():
187:                 x = x.detach()
188:                 x.requires_grad_(True)
189:                 Dx = net(x, t, labels)
190:                 wrk = torch.autograd.grad(Dx.sum(), x, create_graph=False, retain_graph=False)[0].detach()
191:                 x.requires_grad_(False)
192:             Dx = Dx.detach()
193:             progress = 1.0 - t / sigma_max
194:             coeff = (1 - torch.cos(torch.pi * torch.pow(progress, cfg['s']))) * 0.5 * guidance
195:             ref_Dx = gnet(x, t, guid_network_labels).to(dtype)
196:             res = Dx + coeff * wrk * (Dx - ref_Dx)
197:             return res
198:         else:
199:             raise NotImplementedError(f"{cfg['cfg_type']} is not implemented.")
200: 
201:     # Time step discretization.
202:     step_indices = torch.arange(num_steps, dtype=dtype, device=noise.device)
203:     t_steps = (sigma_max ** (1 / rho) + step_indices / (num_steps - 1) * (sigma_min ** (1 / rho) - sigma_max ** (1 / rho))) ** rho
204:     t_steps = torch.cat([t_steps, torch.zeros_like(t_steps[:1])]) # t_N = 0
205:     # Main sampling loop.
206:     x_next = noise.to(dtype) * t_steps[0]
207:     for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])): # 0, ..., N-1
208:         x_cur = x_next
209: 
210:         # Increase noise temporarily.
211:         if S_churn > 0 and S_min <= t_cur <= S_max:
212:             gamma = min(S_churn / num_steps, np.sqrt(2) - 1)
213:             t_hat = t_cur + gamma * t_cur
214:             x_hat = x_cur + (t_hat ** 2 - t_cur ** 2).sqrt() * S_noise * randn_like(x_cur)
215:         else:
216:             t_hat = t_cur
217:             x_hat = x_cur
218: 
219:         # Euler step.
220:         d_cur = (x_hat - denoise(x_hat, t_hat, cfg)) / t_hat
221:         x_next = x_hat + (t_next - t_hat) * d_cur
222: 
223:         # Apply 2nd order correction.
224:         if i < num_steps - 1:
225:             d_prime = (x_next - denoise(x_next, t_next, cfg)) / t_next
226:             x_next = x_hat + (t_next - t_hat) * (0.5 * d_cur + 0.5 * d_prime)
