File size: 4,830 Bytes
d302357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3098ff9
d302357
 
 
 
 
 
 
3098ff9
 
d302357
3098ff9
 
d302357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3098ff9
d302357
 
3098ff9
d302357
 
 
 
 
3098ff9
d302357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3098ff9
d302357
 
 
 
 
 
 
 
 
3098ff9
d302357
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
"""Load the matched DM-VAE / LightningDiT inference tensors and generate images."""
import argparse
from contextlib import nullcontext
import hashlib
import json
from pathlib import Path

import torch
from safetensors.torch import load_file


def digest(path):
    h = hashlib.sha256()
    with Path(path).open('rb') as f:
        for block in iter(lambda: f.read(8 * 1024 * 1024), b''):
            h.update(block)
    return h.hexdigest()


def load_pair(directory, variant='d32', device='cpu', dtype=torch.float32, dit_epochs=400):
    """Return VAE, DiT, and the channel normalization for one matched pair."""
    from dmvae.autoencoder import DMVAE
    from generation.model import LatentDiT
    from generation.model_d64 import LatentDiT64

    if variant not in ('d32', 'd64'):
        raise ValueError('variant must be d32 or d64')
    if dit_epochs not in (64, 400) or (dit_epochs == 64 and variant != 'd32'):
        raise ValueError('64ep is available for d32; 400ep is available for d32 and d64')
    root = Path(directory)
    config_name = variant + ('-64ep' if dit_epochs == 64 else '') + '.json'
    config = json.loads((root / 'configs' / config_name).read_text())
    loaded = {}
    for component in ('vae', 'dit'):
        spec = config[component]
        path = root / spec['file']
        if digest(path) != spec['sha256']:
            raise ValueError(component + ' SHA-256 mismatch')
        loaded[component] = load_file(str(path), device='cpu')
    with torch.device('meta'):
        vae = DMVAE(**config['vae']['architecture'])
        dit_cls = LatentDiT64 if variant == 'd64' else LatentDiT
        dit = dit_cls(**config['dit']['architecture'])
    vae.load_state_dict(loaded.pop('vae'), strict=True, assign=True)
    dit.load_state_dict(loaded.pop('dit'), strict=True, assign=True)
    vae = vae.eval().requires_grad_(False).to(device=device, dtype=dtype)
    dit = dit.eval().requires_grad_(False).to(device=device, dtype=dtype)
    means = torch.tensor(config['channel_means'], device=device, dtype=dtype).view(1, -1, 1, 1)
    scales = torch.tensor(config['channel_std'], dtype=torch.float64).reciprocal().to(device=device, dtype=dtype).view(1, -1, 1, 1)
    return vae, dit, means, scales


@torch.no_grad()
def generate(directory, variant='d32', classes=(207,), seed=1234, steps=250, device='cpu', dtype=torch.float32, cfg=False, dit_epochs=400):
    from generation.sampling import euler_sample, RECIPES

    vae, dit, means, scales = load_pair(directory, variant, device, dtype, dit_epochs=dit_epochs)
    labels = torch.tensor(classes, device=device, dtype=torch.long)
    if labels.numel() == 0 or ((labels < 0) | (labels >= 1000)).any():
        raise ValueError('Provide ImageNet class indices in [0, 999]')
    generator = torch.Generator(device=device).manual_seed(seed)
    noise = torch.randn((len(labels), vae.z_channels_high, 16, 16), generator=generator, device=device, dtype=dtype)
    recipe = ('d64-' if variant == 'd64' else '') + f'{dit_epochs}ep-ig' + ('-cfg' if cfg else '')
    autocast = torch.autocast(torch.device(device).type, dtype=dtype) if dtype == torch.bfloat16 else nullcontext()
    with autocast:
        latent = euler_sample(dit, vae, noise, labels, means, scales, *RECIPES[recipe], steps=steps)
        images = vae.decode(latent / scales + means)
    if not torch.isfinite(images).all():
        raise FloatingPointError('Non-finite generated image')
    return images.float().clamp(-1, 1)


def main():
    from PIL import Image

    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--directory', type=Path, default=Path(__file__).resolve().parent)
    p.add_argument('--variant', choices=('d32', 'd64'), default='d32')
    p.add_argument('--dit-epochs', type=int, choices=(64, 400), default=400)
    p.add_argument('--classes', type=int, nargs='+', default=[207])
    p.add_argument('--seed', type=int, default=1234)
    p.add_argument('--steps', type=int, default=250, help='Euler sampling steps')
    p.add_argument('--device', default='cuda' if torch.cuda.is_available() else 'cpu')
    p.add_argument('--precision', choices=('fp32', 'bf16'), default='fp32')
    p.add_argument('--cfg', action='store_true')
    p.add_argument('--output', type=Path, default=Path('samples'))
    args = p.parse_args()
    dtype = torch.bfloat16 if args.precision == 'bf16' else torch.float32
    images = generate(args.directory, args.variant, args.classes, args.seed, args.steps, args.device, dtype, args.cfg, dit_epochs=args.dit_epochs)
    args.output.mkdir(parents=True, exist_ok=True)
    for index, image in enumerate(images):
        rgb = image.add(1).mul(127.5).round().to(torch.uint8).permute(1, 2, 0).cpu().numpy()
        Image.fromarray(rgb).save(args.output / f'{args.variant}-{index:04d}.png')


if __name__ == '__main__':
    main()