"vscode:/vscode.git/clone" did not exist on "c75cafdb58632b21b8208715623d2e601c897cbc"
training_ddpm.py 4.2 KB
Newer Older
anton-l's avatar
anton-l committed
1
2
3
4
5
6
7
8
9
10
import random

import numpy as np
import torch
import torch.nn.functional as F

import PIL.Image
from accelerate import Accelerator
from datasets import load_dataset
from diffusers import DDPM, DDPMScheduler, UNetModel
anton-l's avatar
anton-l committed
11
12
13
14
15
16
17
18
19
20
from torchvision.transforms import (
    Compose,
    InterpolationMode,
    Lambda,
    RandomCrop,
    RandomHorizontalFlip,
    RandomVerticalFlip,
    Resize,
    ToTensor,
)
anton-l's avatar
anton-l committed
21
22
23
24
25
from tqdm.auto import tqdm
from transformers import get_linear_schedule_with_warmup


def set_seed(seed):
anton-l's avatar
anton-l committed
26
27
    # torch.backends.cudnn.deterministic = True
    # torch.backends.cudnn.benchmark = False
anton-l's avatar
anton-l committed
28
29
30
31
32
33
34
35
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    np.random.seed(seed)
    random.seed(seed)


set_seed(0)

anton-l's avatar
anton-l committed
36
37
38
39
40
41
accelerator = Accelerator()

model = UNetModel(
    attn_resolutions=(16,),
    ch=128,
    ch_mult=(1, 2, 2, 2),
anton-l's avatar
anton-l committed
42
    dropout=0.0,
anton-l's avatar
anton-l committed
43
44
    num_res_blocks=2,
    resamp_with_conv=True,
anton-l's avatar
anton-l committed
45
    resolution=32,
anton-l's avatar
anton-l committed
46
)
anton-l's avatar
anton-l committed
47
noise_scheduler = DDPMScheduler(timesteps=1000)
anton-l's avatar
anton-l committed
48
optimizer = torch.optim.Adam(model.parameters(), lr=3e-4)
anton-l's avatar
anton-l committed
49
50

num_epochs = 100
anton-l's avatar
anton-l committed
51
52
batch_size = 64
gradient_accumulation_steps = 2
anton-l's avatar
anton-l committed
53
54
55

augmentations = Compose(
    [
anton-l's avatar
anton-l committed
56
        Resize(32, interpolation=InterpolationMode.BILINEAR),
anton-l's avatar
anton-l committed
57
58
59
        RandomHorizontalFlip(),
        RandomVerticalFlip(),
        RandomCrop(32),
anton-l's avatar
anton-l committed
60
61
62
63
        ToTensor(),
        Lambda(lambda x: x * 2 - 1),
    ]
)
anton-l's avatar
anton-l committed
64
dataset = load_dataset("huggan/flowers-102-categories", split="train")
anton-l's avatar
anton-l committed
65
66
67
68
69
70
71
72


def transforms(examples):
    images = [augmentations(image.convert("RGB")) for image in examples["image"]]
    return {"input": images}


dataset.set_transform(transforms)
anton-l's avatar
anton-l committed
73
train_dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True)
anton-l's avatar
anton-l committed
74

anton-l's avatar
anton-l committed
75
76
77
78
79
lr_scheduler = get_linear_schedule_with_warmup(
    optimizer=optimizer,
    num_warmup_steps=500,
    num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
)
anton-l's avatar
anton-l committed
80

anton-l's avatar
anton-l committed
81
82
model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
    model, optimizer, train_dataloader, lr_scheduler
anton-l's avatar
anton-l committed
83
84
85
86
87
88
)

for epoch in range(num_epochs):
    model.train()
    pbar = tqdm(total=len(train_dataloader), unit="ba")
    pbar.set_description(f"Epoch {epoch}")
anton-l's avatar
anton-l committed
89
    losses = []
anton-l's avatar
anton-l committed
90
91
92
    for step, batch in enumerate(train_dataloader):
        clean_images = batch["input"]
        noisy_images = torch.empty_like(clean_images)
anton-l's avatar
anton-l committed
93
        noise_samples = torch.empty_like(clean_images)
anton-l's avatar
anton-l committed
94
95
96
97
        bsz = clean_images.shape[0]

        timesteps = torch.randint(0, noise_scheduler.timesteps, (bsz,), device=clean_images.device).long()
        for idx in range(bsz):
anton-l's avatar
anton-l committed
98
99
            noise = torch.randn((3, 32, 32)).to(clean_images.device)
            noise_samples[idx] = noise
anton-l's avatar
anton-l committed
100
101
102
103
104
            noisy_images[idx] = noise_scheduler.forward_step(clean_images[idx], noise, timesteps[idx])

        if step % gradient_accumulation_steps == 0:
            with accelerator.no_sync(model):
                output = model(noisy_images, timesteps)
anton-l's avatar
anton-l committed
105
106
                # predict the noise
                loss = F.l1_loss(output, noise_samples)
anton-l's avatar
anton-l committed
107
108
109
110
111
                accelerator.backward(loss)
        else:
            output = model(noisy_images, timesteps)
            loss = F.l1_loss(output, clean_images)
            accelerator.backward(loss)
anton-l's avatar
anton-l committed
112
            torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
anton-l's avatar
anton-l committed
113
            optimizer.step()
anton-l's avatar
anton-l committed
114
            lr_scheduler.step()
anton-l's avatar
anton-l committed
115
            optimizer.zero_grad()
anton-l's avatar
anton-l committed
116
117
        loss = loss.detach().item()
        losses.append(loss)
anton-l's avatar
anton-l committed
118
        pbar.update(1)
anton-l's avatar
anton-l committed
119
        pbar.set_postfix(loss=loss, avg_loss=np.mean(losses), lr=optimizer.param_groups[0]["lr"])
anton-l's avatar
anton-l committed
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138

        optimizer.step()

    # eval
    model.eval()
    with torch.no_grad():
        pipeline = DDPM(unet=model, noise_scheduler=noise_scheduler)
        generator = torch.Generator()
        generator = generator.manual_seed(0)
        # run pipeline in inference (sample random noise and denoise)
        image = pipeline(generator=generator)

        # process image to PIL
        image_processed = image.cpu().permute(0, 2, 3, 1)
        image_processed = (image_processed + 1.0) * 127.5
        image_processed = image_processed.type(torch.uint8).numpy()
        image_pil = PIL.Image.fromarray(image_processed[0])

        # save image
anton-l's avatar
anton-l committed
139
140
        pipeline.save_pretrained("./flowers-ddpm")
        image_pil.save(f"./flowers-ddpm/test_{epoch}.png")