Skip to content

Commit c799fdb

Browse files
committed
merge in post release main
2 parents 5f18224 + e795a4c commit c799fdb

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+1332
-1279
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ For more examples see [schedulers](https://github.com/huggingface/diffusers/tree
8484

8585
```python
8686
import torch
87-
from diffusers import UNetUnconditionalModel, DDIMScheduler
87+
from diffusers import UNet2DModel, DDIMScheduler
8888
import PIL.Image
8989
import numpy as np
9090
import tqdm
@@ -93,7 +93,7 @@ torch_device = "cuda" if torch.cuda.is_available() else "cpu"
9393

9494
# 1. Load models
9595
scheduler = DDIMScheduler.from_config("fusing/ddpm-celeba-hq", tensor_format="pt")
96-
unet = UNetUnconditionalModel.from_pretrained("fusing/ddpm-celeba-hq", ddpm=True).to(torch_device)
96+
unet = UNet2DModel.from_pretrained("fusing/ddpm-celeba-hq", ddpm=True).to(torch_device)
9797

9898
# 2. Sample gaussian noise
9999
generator = torch.manual_seed(23)

examples/README.md

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,17 @@
55
The command to train a DDPM UNet model on the Oxford Flowers dataset:
66

77
```bash
8-
python -m torch.distributed.launch \
9-
--nproc_per_node 4 \
10-
train_unconditional.py \
8+
accelerate launch train_unconditional.py \
119
--dataset="huggan/flowers-102-categories" \
1210
--resolution=64 \
13-
--output_dir="flowers-ddpm" \
14-
--batch_size=16 \
11+
--output_dir="ddpm-ema-flowers-64" \
12+
--train_batch_size=16 \
1513
--num_epochs=100 \
1614
--gradient_accumulation_steps=1 \
17-
--lr=1e-4 \
18-
--warmup_steps=500 \
19-
--mixed_precision=no
15+
--learning_rate=1e-4 \
16+
--lr_warmup_steps=500 \
17+
--mixed_precision=no \
18+
--push_to_hub
2019
```
2120

2221
A full training run takes 2 hours on 4xV100 GPUs.
@@ -29,18 +28,17 @@ A full training run takes 2 hours on 4xV100 GPUs.
2928
The command to train a DDPM UNet model on the Pokemon dataset:
3029

3130
```bash
32-
python -m torch.distributed.launch \
33-
--nproc_per_node 4 \
34-
train_unconditional.py \
31+
accelerate launch train_unconditional.py \
3532
--dataset="huggan/pokemon" \
3633
--resolution=64 \
37-
--output_dir="pokemon-ddpm" \
38-
--batch_size=16 \
34+
--output_dir="ddpm-ema-pokemon-64" \
35+
--train_batch_size=16 \
3936
--num_epochs=100 \
4037
--gradient_accumulation_steps=1 \
41-
--lr=1e-4 \
42-
--warmup_steps=500 \
43-
--mixed_precision=no
38+
--learning_rate=1e-4 \
39+
--lr_warmup_steps=500 \
40+
--mixed_precision=no \
41+
--push_to_hub
4442
```
4543

4644
A full training run takes 2 hours on 4xV100 GPUs.

examples/train_unconditional.py

Lines changed: 60 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@
44
import torch
55
import torch.nn.functional as F
66

7-
from accelerate import Accelerator, DistributedDataParallelKwargs
7+
from accelerate import Accelerator
88
from accelerate.logging import get_logger
99
from datasets import load_dataset
10-
from diffusers import DDIMPipeline, DDIMScheduler, UNetModel
10+
from diffusers import DDPMPipeline, DDPMScheduler, UNetUnconditionalModel
1111
from diffusers.hub_utils import init_git_repo, push_to_hub
1212
from diffusers.optimization import get_scheduler
1313
from diffusers.training_utils import EMAModel
@@ -27,25 +27,37 @@
2727

2828

2929
def main(args):
30-
ddp_unused_params = DistributedDataParallelKwargs(find_unused_parameters=True)
3130
logging_dir = os.path.join(args.output_dir, args.logging_dir)
3231
accelerator = Accelerator(
3332
mixed_precision=args.mixed_precision,
3433
log_with="tensorboard",
3534
logging_dir=logging_dir,
36-
kwargs_handlers=[ddp_unused_params],
3735
)
3836

39-
model = UNetModel(
40-
attn_resolutions=(16,),
41-
ch=128,
42-
ch_mult=(1, 2, 4, 8),
43-
dropout=0.0,
37+
model = UNetUnconditionalModel(
38+
image_size=args.resolution,
39+
in_channels=3,
40+
out_channels=3,
4441
num_res_blocks=2,
45-
resamp_with_conv=True,
46-
resolution=args.resolution,
42+
block_channels=(128, 128, 256, 256, 512, 512),
43+
down_blocks=(
44+
"UNetResDownBlock2D",
45+
"UNetResDownBlock2D",
46+
"UNetResDownBlock2D",
47+
"UNetResDownBlock2D",
48+
"UNetResAttnDownBlock2D",
49+
"UNetResDownBlock2D",
50+
),
51+
up_blocks=(
52+
"UNetResUpBlock2D",
53+
"UNetResAttnUpBlock2D",
54+
"UNetResUpBlock2D",
55+
"UNetResUpBlock2D",
56+
"UNetResUpBlock2D",
57+
"UNetResUpBlock2D",
58+
),
4759
)
48-
noise_scheduler = DDIMScheduler(timesteps=1000, tensor_format="pt")
60+
noise_scheduler = DDPMScheduler(num_train_timesteps=1000, tensor_format="pt")
4961
optimizer = torch.optim.AdamW(
5062
model.parameters(),
5163
lr=args.learning_rate,
@@ -92,65 +104,44 @@ def transforms(examples):
92104
run = os.path.split(__file__)[-1].split(".")[0]
93105
accelerator.init_trackers(run)
94106

95-
# Train!
96-
is_distributed = torch.distributed.is_available() and torch.distributed.is_initialized()
97-
world_size = torch.distributed.get_world_size() if is_distributed else 1
98-
total_train_batch_size = args.train_batch_size * args.gradient_accumulation_steps * world_size
99-
max_steps = len(train_dataloader) // args.gradient_accumulation_steps * args.num_epochs
100-
logger.info("***** Running training *****")
101-
logger.info(f" Num examples = {len(train_dataloader.dataset)}")
102-
logger.info(f" Num Epochs = {args.num_epochs}")
103-
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
104-
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}")
105-
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
106-
logger.info(f" Total optimization steps = {max_steps}")
107-
108107
global_step = 0
109108
for epoch in range(args.num_epochs):
110109
model.train()
111110
progress_bar = tqdm(total=len(train_dataloader), disable=not accelerator.is_local_main_process)
112111
progress_bar.set_description(f"Epoch {epoch}")
113112
for step, batch in enumerate(train_dataloader):
114113
clean_images = batch["input"]
115-
noise_samples = torch.randn(clean_images.shape).to(clean_images.device)
114+
# Sample noise that we'll add to the images
115+
noise = torch.randn(clean_images.shape).to(clean_images.device)
116116
bsz = clean_images.shape[0]
117-
timesteps = torch.randint(0, noise_scheduler.timesteps, (bsz,), device=clean_images.device).long()
117+
# Sample a random timestep for each image
118+
timesteps = torch.randint(
119+
0, noise_scheduler.num_train_timesteps, (bsz,), device=clean_images.device
120+
).long()
118121

119-
# add noise onto the clean images according to the noise magnitude at each timestep
122+
# Add noise to the clean images according to the noise magnitude at each timestep
120123
# (this is the forward diffusion process)
121-
noisy_images = noise_scheduler.add_noise(clean_images, noise_samples, timesteps)
122-
123-
if step % args.gradient_accumulation_steps != 0:
124-
with accelerator.no_sync(model):
125-
output = model(noisy_images, timesteps)
126-
# predict the noise residual
127-
loss = F.mse_loss(output, noise_samples)
128-
loss = loss / args.gradient_accumulation_steps
129-
accelerator.backward(loss)
130-
else:
131-
output = model(noisy_images, timesteps)
132-
# predict the noise residual
133-
loss = F.mse_loss(output, noise_samples)
134-
loss = loss / args.gradient_accumulation_steps
124+
noisy_images = noise_scheduler.add_noise(clean_images, noise, timesteps)
125+
126+
with accelerator.accumulate(model):
127+
# Predict the noise residual
128+
noise_pred = model(noisy_images, timesteps)["sample"]
129+
loss = F.mse_loss(noise_pred, noise)
135130
accelerator.backward(loss)
136-
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
131+
132+
accelerator.clip_grad_norm_(model.parameters(), 1.0)
137133
optimizer.step()
138134
lr_scheduler.step()
139-
ema_model.step(model)
135+
if args.use_ema:
136+
ema_model.step(model)
140137
optimizer.zero_grad()
138+
141139
progress_bar.update(1)
142-
progress_bar.set_postfix(
143-
loss=loss.detach().item(), lr=optimizer.param_groups[0]["lr"], ema_decay=ema_model.decay
144-
)
145-
accelerator.log(
146-
{
147-
"train_loss": loss.detach().item(),
148-
"epoch": epoch,
149-
"ema_decay": ema_model.decay,
150-
"step": global_step,
151-
},
152-
step=global_step,
153-
)
140+
logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0], "step": global_step}
141+
if args.use_ema:
142+
logs["ema_decay"] = ema_model.decay
143+
progress_bar.set_postfix(**logs)
144+
accelerator.log(logs, step=global_step)
154145
global_step += 1
155146
progress_bar.close()
156147

@@ -159,26 +150,27 @@ def transforms(examples):
159150
# Generate a sample image for visual inspection
160151
if accelerator.is_main_process:
161152
with torch.no_grad():
162-
pipeline = DDIMPipeline(
163-
unet=accelerator.unwrap_model(ema_model.averaged_model),
164-
noise_scheduler=noise_scheduler,
153+
pipeline = DDPMPipeline(
154+
unet=accelerator.unwrap_model(ema_model.averaged_model if args.use_ema else model),
155+
scheduler=noise_scheduler,
165156
)
166157

167158
generator = torch.manual_seed(0)
168159
# run pipeline in inference (sample random noise and denoise)
169-
images = pipeline(generator=generator, batch_size=args.eval_batch_size, num_inference_steps=50)
160+
images = pipeline(generator=generator, batch_size=args.eval_batch_size)
170161

171162
# denormalize the images and save to tensorboard
172163
images_processed = (images.cpu() + 1.0) * 127.5
173164
images_processed = images_processed.clamp(0, 255).type(torch.uint8).numpy()
174165

175166
accelerator.trackers[0].writer.add_images("test_samples", images_processed, epoch)
176167

177-
# save the model
178-
if args.push_to_hub:
179-
push_to_hub(args, pipeline, repo, commit_message=f"Epoch {epoch}", blocking=False)
180-
else:
181-
pipeline.save_pretrained(args.output_dir)
168+
if epoch % args.save_model_epochs == 0 or epoch == args.num_epochs - 1:
169+
# save the model
170+
if args.push_to_hub:
171+
push_to_hub(args, pipeline, repo, commit_message=f"Epoch {epoch}", blocking=False)
172+
else:
173+
pipeline.save_pretrained(args.output_dir)
182174
accelerator.wait_for_everyone()
183175

184176
accelerator.end_training()
@@ -188,12 +180,13 @@ def transforms(examples):
188180
parser = argparse.ArgumentParser(description="Simple example of a training script.")
189181
parser.add_argument("--local_rank", type=int, default=-1)
190182
parser.add_argument("--dataset", type=str, default="huggan/flowers-102-categories")
191-
parser.add_argument("--output_dir", type=str, default="ddpm-model")
183+
parser.add_argument("--output_dir", type=str, default="ddpm-flowers-64")
192184
parser.add_argument("--overwrite_output_dir", action="store_true")
193185
parser.add_argument("--resolution", type=int, default=64)
194186
parser.add_argument("--train_batch_size", type=int, default=16)
195187
parser.add_argument("--eval_batch_size", type=int, default=16)
196188
parser.add_argument("--num_epochs", type=int, default=100)
189+
parser.add_argument("--save_model_epochs", type=int, default=5)
197190
parser.add_argument("--gradient_accumulation_steps", type=int, default=1)
198191
parser.add_argument("--learning_rate", type=float, default=1e-4)
199192
parser.add_argument("--lr_scheduler", type=str, default="cosine")
@@ -202,6 +195,7 @@ def transforms(examples):
202195
parser.add_argument("--adam_beta2", type=float, default=0.999)
203196
parser.add_argument("--adam_weight_decay", type=float, default=1e-6)
204197
parser.add_argument("--adam_epsilon", type=float, default=1e-3)
198+
parser.add_argument("--use_ema", action="store_true", default=True)
205199
parser.add_argument("--ema_inv_gamma", type=float, default=1.0)
206200
parser.add_argument("--ema_power", type=float, default=3 / 4)
207201
parser.add_argument("--ema_max_decay", type=float, default=0.9999)
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
# coding=utf-8
2+
# Copyright 2022 The HuggingFace Inc. team.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
""" Conversion script for the LDM checkpoints. """
16+
17+
import argparse
18+
import os
19+
import json
20+
import torch
21+
from diffusers import UNet2DModel, UNet2DConditionModel
22+
from transformers.file_utils import has_file
23+
24+
do_only_config = False
25+
do_only_weights = True
26+
do_only_renaming = False
27+
28+
29+
if __name__ == "__main__":
30+
parser = argparse.ArgumentParser()
31+
32+
parser.add_argument(
33+
"--repo_path",
34+
default=None,
35+
type=str,
36+
required=True,
37+
help="The config json file corresponding to the architecture.",
38+
)
39+
40+
parser.add_argument(
41+
"--dump_path", default=None, type=str, required=True, help="Path to the output model."
42+
)
43+
44+
args = parser.parse_args()
45+
46+
config_parameters_to_change = {
47+
"image_size": "sample_size",
48+
"num_res_blocks": "layers_per_block",
49+
"block_channels": "block_out_channels",
50+
"down_blocks": "down_block_types",
51+
"up_blocks": "up_block_types",
52+
"downscale_freq_shift": "freq_shift",
53+
"resnet_num_groups": "norm_num_groups",
54+
"resnet_act_fn": "act_fn",
55+
"resnet_eps": "norm_eps",
56+
"num_head_channels": "attention_head_dim",
57+
}
58+
59+
key_parameters_to_change = {
60+
"time_steps": "time_proj",
61+
"mid": "mid_block",
62+
"downsample_blocks": "down_blocks",
63+
"upsample_blocks": "up_blocks",
64+
}
65+
66+
subfolder = "" if has_file(args.repo_path, "config.json") else "unet"
67+
68+
with open(os.path.join(args.repo_path, subfolder, "config.json"), "r", encoding="utf-8") as reader:
69+
text = reader.read()
70+
config = json.loads(text)
71+
72+
if do_only_config:
73+
for key in config_parameters_to_change.keys():
74+
config.pop(key, None)
75+
76+
if has_file(args.repo_path, "config.json"):
77+
model = UNet2DModel(**config)
78+
else:
79+
class_name = UNet2DConditionModel if "ldm-text2im-large-256" in args.repo_path else UNet2DModel
80+
model = class_name(**config)
81+
82+
if do_only_config:
83+
model.save_config(os.path.join(args.repo_path, subfolder))
84+
85+
config = dict(model.config)
86+
87+
if do_only_renaming:
88+
for key, value in config_parameters_to_change.items():
89+
if key in config:
90+
config[value] = config[key]
91+
del config[key]
92+
93+
config["down_block_types"] = [k.replace("UNetRes", "") for k in config["down_block_types"]]
94+
config["up_block_types"] = [k.replace("UNetRes", "") for k in config["up_block_types"]]
95+
96+
if do_only_weights:
97+
state_dict = torch.load(os.path.join(args.repo_path, subfolder, "diffusion_pytorch_model.bin"))
98+
99+
new_state_dict = {}
100+
for param_key, param_value in state_dict.items():
101+
if param_key.endswith(".op.bias") or param_key.endswith(".op.weight"):
102+
continue
103+
has_changed = False
104+
for key, new_key in key_parameters_to_change.items():
105+
if not has_changed and param_key.split(".")[0] == key:
106+
new_state_dict[".".join([new_key] + param_key.split(".")[1:])] = param_value
107+
has_changed = True
108+
if not has_changed:
109+
new_state_dict[param_key] = param_value
110+
111+
model.load_state_dict(new_state_dict)
112+
model.save_pretrained(os.path.join(args.repo_path, subfolder))

0 commit comments

Comments
 (0)