Views
No views yet
edm2_xl_ema.pt and edm2_s_ema.pt. The XL model is sampled with the S model as the autoguidance network.1# Clone EDM2 generation code
2import os, sys, subprocess
3subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "huggingface_hub", "matplotlib"])
4if not os.path.isdir("edm2"):
5 subprocess.check_call(["git", "clone", "--depth", "1", "https://github.com/NVlabs/edm2.git"])
6sys.path.insert(0, "edm2")
7
8# Import libraries
9from pathlib import Path
10import json, torch, matplotlib.pyplot as plt
11from huggingface_hub import snapshot_download
12import dnnlib
13from training.encoders import StandardRGBEncoder, StabilityVAEEncoder
14
15# Helper function for loading diffusion UNet
16def make_net(meta, dropout, dev):
17 return dnnlib.util.construct_class_by_name(
18 class_name="training.networks_edm2.Precond", model_channels=meta["model_channels"],
19 dropout=dropout, use_fp16=True,
20 **dict(interface, img_resolution=meta["img_resolution"], img_channels=meta["img_channels"], label_dim=meta["label_dim"]),
21 ).to(dev).eval().requires_grad_(False)
22
23# EDM sampling (image generation function)
24@torch.no_grad()
25def edm_sampler(net, noise, labels, gnet, guidance=2.25, num_steps=32, sigma_min=0.002, sigma_max=80, rho=7):
26 def denoise(x, t):
27 dx = net(x, t, labels)
28 gx = gnet(x.to(device), t.to(device), labels.to(device)).to(x.device)
29 return gx.lerp(dx, guidance)
30 steps = torch.arange(num_steps, device=noise.device, dtype=torch.float32)
31 t = (sigma_max ** (1 / rho) + steps / (num_steps - 1) * (sigma_min ** (1 / rho) - sigma_max ** (1 / rho))) ** rho
32 t = torch.cat([t, t[:1] * 0])
33 x = noise * t[0]
34 for i, (tc, tn) in enumerate(zip(t[:-1], t[1:])):
35 d = (x - denoise(x, tc)) / tc
36 x_next = x + (tn - tc) * d
37 if i < num_steps - 1:
38 d2 = (x_next - denoise(x_next, tn)) / tn
39 x = x + (tn - tc) * (d + d2) / 2
40 else:
41 x = x_next
42 return x
43
44# Huggingface repo
45repo_dir = Path(snapshot_download("harveymannering/ultrasound-edm2"))
46config = json.loads((repo_dir / "config.json").read_text())
47device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
48interface = dict(img_resolution=None, img_channels=None, label_dim=None)
49
50# Load the diffusion models
51net = make_net(config["files"]["xl"], 0.10, device)
52gnet = make_net(config["files"]["s"], 0.0, device)
53net.load_state_dict(torch.load(repo_dir / config["files"]["xl"]["filename"], map_location="cpu"))
54gnet.load_state_dict(torch.load(repo_dir / config["files"]["s"]["filename"], map_location="cpu"))
55net.to(device)
56gnet.to(device)
57
58# Generate and display image
59class_idx, num_steps = 1, 32
60noise = torch.randn(1, 4, 64, 64, device=device)
61labels = torch.eye(9, device=device)[[class_idx]]
62latents = edm_sampler(net, noise, labels, gnet, guidance=2.25, num_steps=num_steps)
63encoder = StabilityVAEEncoder(batch_size=1)
64img = encoder.decode(latents)[0].permute(1, 2, 0).cpu().numpy()
65plt.figure(figsize=(4, 4))
66plt.imshow(img)
67plt.axis("off")
68plt.show()