train_unconditional.py 7.63 KB
Newer Older
anton-l's avatar
anton-l committed
1
import argparse
anton-l's avatar
anton-l committed
2
import os
anton-l's avatar
anton-l committed
3
4
5
6

import torch
import torch.nn.functional as F

anton-l's avatar
anton-l committed
7
import PIL.Image
anton-l's avatar
anton-l committed
8
9
10
from accelerate import Accelerator
from datasets import load_dataset
from diffusers import DDPM, DDPMScheduler, UNetModel
anton-l's avatar
anton-l committed
11
12
from diffusers.hub_utils import init_git_repo, push_to_hub
from diffusers.modeling_utils import unwrap_model
13
from diffusers.optimization import get_scheduler
anton-l's avatar
anton-l committed
14
from diffusers.utils import logging
anton-l's avatar
anton-l committed
15
from torchvision.transforms import (
Patrick von Platen's avatar
Patrick von Platen committed
16
    CenterCrop,
anton-l's avatar
anton-l committed
17
18
19
20
21
22
23
    Compose,
    InterpolationMode,
    Lambda,
    RandomHorizontalFlip,
    Resize,
    ToTensor,
)
anton-l's avatar
anton-l committed
24
from tqdm.auto import tqdm
anton-l's avatar
anton-l committed
25
26
27


logger = logging.get_logger(__name__)
anton-l's avatar
anton-l committed
28
29


anton-l's avatar
anton-l committed
30
31
32
33
34
35
36
37
38
39
def main(args):
    accelerator = Accelerator(mixed_precision=args.mixed_precision)

    model = UNetModel(
        attn_resolutions=(16,),
        ch=128,
        ch_mult=(1, 2, 4, 8),
        dropout=0.0,
        num_res_blocks=2,
        resamp_with_conv=True,
anton-l's avatar
anton-l committed
40
        resolution=args.resolution,
anton-l's avatar
anton-l committed
41
    )
anton-l's avatar
anton-l committed
42
    noise_scheduler = DDPMScheduler(timesteps=1000, tensor_format="pt")
anton-l's avatar
anton-l committed
43
    optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)
anton-l's avatar
anton-l committed
44
45
46

    augmentations = Compose(
        [
anton-l's avatar
anton-l committed
47
            Resize(args.resolution, interpolation=InterpolationMode.BILINEAR),
anton-l's avatar
anton-l committed
48
            CenterCrop(args.resolution),
anton-l's avatar
anton-l committed
49
50
51
52
53
            RandomHorizontalFlip(),
            ToTensor(),
            Lambda(lambda x: x * 2 - 1),
        ]
    )
anton-l's avatar
anton-l committed
54
    dataset = load_dataset(args.dataset, split="train")
anton-l's avatar
anton-l committed
55
56
57
58
59
60

    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
61
    train_dataloader = torch.utils.data.DataLoader(dataset, batch_size=args.batch_size, shuffle=True)
anton-l's avatar
anton-l committed
62

anton-l's avatar
anton-l committed
63
64
    lr_scheduler = get_scheduler(
        "linear",
anton-l's avatar
anton-l committed
65
        optimizer=optimizer,
anton-l's avatar
anton-l committed
66
67
        num_warmup_steps=args.warmup_steps,
        num_training_steps=(len(train_dataloader) * args.num_epochs) // args.gradient_accumulation_steps,
anton-l's avatar
anton-l committed
68
69
70
71
72
73
    )

    model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
        model, optimizer, train_dataloader, lr_scheduler
    )

anton-l's avatar
anton-l committed
74
75
76
77
    if args.push_to_hub:
        repo = init_git_repo(args, at_init=True)

    # Train!
anton-l's avatar
anton-l committed
78
79
    is_distributed = torch.distributed.is_available() and torch.distributed.is_initialized()
    world_size = torch.distributed.get_world_size() if is_distributed else 1
anton-l's avatar
anton-l committed
80
81
82
83
84
85
86
87
88
89
    total_train_batch_size = args.batch_size * args.gradient_accumulation_steps * world_size
    max_steps = len(train_dataloader) // args.gradient_accumulation_steps * args.num_epochs
    logger.info("***** Running training *****")
    logger.info(f"  Num examples = {len(train_dataloader.dataset)}")
    logger.info(f"  Num Epochs = {args.num_epochs}")
    logger.info(f"  Instantaneous batch size per device = {args.batch_size}")
    logger.info(f"  Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}")
    logger.info(f"  Gradient Accumulation steps = {args.gradient_accumulation_steps}")
    logger.info(f"  Total optimization steps = {max_steps}")

anton-l's avatar
anton-l committed
90
    for epoch in range(args.num_epochs):
anton-l's avatar
anton-l committed
91
92
93
94
95
        model.train()
        with tqdm(total=len(train_dataloader), unit="ba") as pbar:
            pbar.set_description(f"Epoch {epoch}")
            for step, batch in enumerate(train_dataloader):
                clean_images = batch["input"]
anton-l's avatar
anton-l committed
96
                noise_samples = torch.randn(clean_images.shape).to(clean_images.device)
anton-l's avatar
anton-l committed
97
98
                bsz = clean_images.shape[0]
                timesteps = torch.randint(0, noise_scheduler.timesteps, (bsz,), device=clean_images.device).long()
anton-l's avatar
anton-l committed
99
100
101
102

                # add noise onto the clean images according to the noise magnitude at each timestep
                # (this is the forward diffusion process)
                noisy_images = noise_scheduler.training_step(clean_images, noise_samples, timesteps)
anton-l's avatar
anton-l committed
103

anton-l's avatar
anton-l committed
104
                if step % args.gradient_accumulation_steps != 0:
anton-l's avatar
anton-l committed
105
106
                    with accelerator.no_sync(model):
                        output = model(noisy_images, timesteps)
anton-l's avatar
anton-l committed
107
                        # predict the noise residual
anton-l's avatar
anton-l committed
108
                        loss = F.mse_loss(output, noise_samples)
anton-l's avatar
anton-l committed
109
                        loss = loss / args.gradient_accumulation_steps
anton-l's avatar
anton-l committed
110
111
112
                        accelerator.backward(loss)
                else:
                    output = model(noisy_images, timesteps)
anton-l's avatar
anton-l committed
113
                    # predict the noise residual
anton-l's avatar
anton-l committed
114
                    loss = F.mse_loss(output, noise_samples)
anton-l's avatar
anton-l committed
115
                    loss = loss / args.gradient_accumulation_steps
anton-l's avatar
anton-l committed
116
117
118
119
120
121
122
123
124
                    accelerator.backward(loss)
                    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
                    optimizer.step()
                    lr_scheduler.step()
                    optimizer.zero_grad()
                pbar.update(1)
                pbar.set_postfix(loss=loss.detach().item(), lr=optimizer.param_groups[0]["lr"])

                optimizer.step()
anton-l's avatar
anton-l committed
125
126
        if is_distributed:
            torch.distributed.barrier()
anton-l's avatar
anton-l committed
127

anton-l's avatar
anton-l committed
128
        # Generate a sample image for visual inspection
anton-l's avatar
anton-l committed
129
130
131
        if args.local_rank in [-1, 0]:
            model.eval()
            with torch.no_grad():
anton-l's avatar
anton-l committed
132
                pipeline = DDPM(unet=unwrap_model(model), noise_scheduler=noise_scheduler)
anton-l's avatar
anton-l committed
133
134

                generator = torch.manual_seed(0)
anton-l's avatar
anton-l committed
135
136
137
                # run pipeline in inference (sample random noise and denoise)
                image = pipeline(generator=generator)

anton-l's avatar
anton-l committed
138
139
140
141
142
143
144
145
146
            # 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
            test_dir = os.path.join(args.output_dir, "test_samples")
            os.makedirs(test_dir, exist_ok=True)
anton-l's avatar
anton-l committed
147
            image_pil.save(f"{test_dir}/{epoch:04d}.png")
anton-l's avatar
anton-l committed
148

anton-l's avatar
anton-l committed
149
150
151
152
153
154
155
            # save the model
            if args.push_to_hub:
                push_to_hub(args, pipeline, repo, commit_message=f"Epoch {epoch}", blocking=False)
            else:
                pipeline.save_pretrained(args.output_dir)
        if is_distributed:
            torch.distributed.barrier()
anton-l's avatar
anton-l committed
156
157
158


if __name__ == "__main__":
anton-l's avatar
anton-l committed
159
    parser = argparse.ArgumentParser(description="Simple example of a training script.")
anton-l's avatar
anton-l committed
160
    parser.add_argument("--local_rank", type=int, default=-1)
anton-l's avatar
anton-l committed
161
    parser.add_argument("--dataset", type=str, default="huggan/flowers-102-categories")
anton-l's avatar
anton-l committed
162
163
    parser.add_argument("--output_dir", type=str, default="ddpm-model")
    parser.add_argument("--overwrite_output_dir", action="store_true")
anton-l's avatar
anton-l committed
164
    parser.add_argument("--resolution", type=int, default=64)
anton-l's avatar
anton-l committed
165
    parser.add_argument("--batch_size", type=int, default=16)
anton-l's avatar
anton-l committed
166
    parser.add_argument("--num_epochs", type=int, default=100)
anton-l's avatar
anton-l committed
167
    parser.add_argument("--gradient_accumulation_steps", type=int, default=1)
anton-l's avatar
anton-l committed
168
169
    parser.add_argument("--lr", type=float, default=1e-4)
    parser.add_argument("--warmup_steps", type=int, default=500)
anton-l's avatar
anton-l committed
170
    parser.add_argument("--push_to_hub", action="store_true")
anton-l's avatar
anton-l committed
171
172
173
    parser.add_argument("--hub_token", type=str, default=None)
    parser.add_argument("--hub_model_id", type=str, default=None)
    parser.add_argument("--hub_private_repo", action="store_true")
anton-l's avatar
anton-l committed
174
175
176
177
178
    parser.add_argument(
        "--mixed_precision",
        type=str,
        default="no",
        choices=["no", "fp16", "bf16"],
179
180
181
182
183
        help=(
            "Whether to use mixed precision. Choose"
            "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
            "and an Nvidia Ampere GPU."
        ),
anton-l's avatar
anton-l committed
184
185
186
187
188
189
190
191
    )

    args = parser.parse_args()
    env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
    if env_local_rank != -1 and env_local_rank != args.local_rank:
        args.local_rank = env_local_rank

    main(args)