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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import huggingface_hub
|
| 2 |
+
import matplotlib.pyplot as plt
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import os
|
| 6 |
+
import glob
|
| 7 |
+
import socket
|
| 8 |
+
|
| 9 |
+
from huggingface_hub import notebook_login
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
from datasets import load_dataset
|
| 12 |
+
from torchvision import transforms
|
| 13 |
+
from diffusers import UNet2DModel
|
| 14 |
+
from PIL import Image
|
| 15 |
+
from diffusers import DDPMScheduler
|
| 16 |
+
from diffusers.optimization import get_cosine_schedule_with_warmup
|
| 17 |
+
from diffusers import DDPMPipeline
|
| 18 |
+
from diffusers.utils import make_image_grid
|
| 19 |
+
from accelerate import Accelerator
|
| 20 |
+
from huggingface_hub import create_repo, upload_folder
|
| 21 |
+
from tqdm.auto import tqdm
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from accelerate import notebook_launcher
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
notebook_login()
|
| 27 |
+
huggingface_hub.login()
|
| 28 |
+
#################################################
|
| 29 |
+
@dataclass
|
| 30 |
+
class TrainingConfig:
|
| 31 |
+
image_size = 128 # the generated image resolution
|
| 32 |
+
train_batch_size = 16
|
| 33 |
+
eval_batch_size = 16 # how many images to sample during evaluation
|
| 34 |
+
num_epochs = 100
|
| 35 |
+
gradient_accumulation_steps = 1
|
| 36 |
+
learning_rate = 1e-4
|
| 37 |
+
lr_warmup_steps = 500
|
| 38 |
+
save_image_epochs = 10
|
| 39 |
+
save_model_epochs = 30
|
| 40 |
+
mixed_precision = "fp16" # `no` for float32, `fp16` for automatic mixed precision
|
| 41 |
+
output_dir = "ddpm-mikel-128" # the model name locally and on the HF Hub
|
| 42 |
+
|
| 43 |
+
push_to_hub = True # whether to upload the saved model to the HF Hub
|
| 44 |
+
hub_model_id = "mikelola/modelTFM" # the name of the repository to create on the HF Hub
|
| 45 |
+
hub_private_repo = False
|
| 46 |
+
overwrite_output_dir = True # overwrite the old model when re-running the notebook
|
| 47 |
+
seed = 0
|
| 48 |
+
|
| 49 |
+
config = TrainingConfig()
|
| 50 |
+
#################################################
|
| 51 |
+
# If the dataset is gated/private, make sure you have run huggingface-cli login
|
| 52 |
+
dataset = load_dataset("mikelola/imagenesmikel")
|
| 53 |
+
#################################################
|
| 54 |
+
fig, axs = plt.subplots(1, 4, figsize=(16, 4))
|
| 55 |
+
for i, image in enumerate(dataset["train"][:4]["image"]):
|
| 56 |
+
axs[i].imshow(image)
|
| 57 |
+
axs[i].set_axis_off()
|
| 58 |
+
fig.show()
|
| 59 |
+
#################################################
|
| 60 |
+
preprocess = transforms.Compose(
|
| 61 |
+
[
|
| 62 |
+
transforms.Resize((config.image_size, config.image_size)),
|
| 63 |
+
transforms.RandomHorizontalFlip(),
|
| 64 |
+
transforms.ToTensor(),
|
| 65 |
+
transforms.Normalize([0.5], [0.5]),
|
| 66 |
+
]
|
| 67 |
+
)
|
| 68 |
+
#################################################
|
| 69 |
+
def transform(examples):
|
| 70 |
+
images = [preprocess(image.convert("RGB")) for image in examples["image"]]
|
| 71 |
+
return {"images": images}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
dataset.set_transform(transform)
|
| 75 |
+
#################################################
|
| 76 |
+
train_dataloader = torch.utils.data.DataLoader(dataset["train"], batch_size=config.train_batch_size, shuffle=True)
|
| 77 |
+
#################################################
|
| 78 |
+
model = UNet2DModel(
|
| 79 |
+
sample_size=config.image_size, # the target image resolution
|
| 80 |
+
in_channels=3, # the number of input channels, 3 for RGB images
|
| 81 |
+
out_channels=3, # the number of output channels
|
| 82 |
+
layers_per_block=2, # how many ResNet layers to use per UNet block
|
| 83 |
+
block_out_channels=(128, 128, 256, 256, 512, 512), # the number of output channels for each UNet block
|
| 84 |
+
down_block_types=(
|
| 85 |
+
"DownBlock2D", # a regular ResNet downsampling block
|
| 86 |
+
"DownBlock2D",
|
| 87 |
+
"DownBlock2D",
|
| 88 |
+
"DownBlock2D",
|
| 89 |
+
"AttnDownBlock2D", # a ResNet downsampling block with spatial self-attention
|
| 90 |
+
"DownBlock2D",
|
| 91 |
+
),
|
| 92 |
+
up_block_types=(
|
| 93 |
+
"UpBlock2D", # a regular ResNet upsampling block
|
| 94 |
+
"AttnUpBlock2D", # a ResNet upsampling block with spatial self-attention
|
| 95 |
+
"UpBlock2D",
|
| 96 |
+
"UpBlock2D",
|
| 97 |
+
"UpBlock2D",
|
| 98 |
+
"UpBlock2D",
|
| 99 |
+
),
|
| 100 |
+
)
|
| 101 |
+
#################################################
|
| 102 |
+
sample_image = dataset["train"][0]["images"].unsqueeze(0)
|
| 103 |
+
print("Input shape:", sample_image.shape)
|
| 104 |
+
|
| 105 |
+
print("Output shape:", model(sample_image, timestep=0).sample.shape)
|
| 106 |
+
#################################################
|
| 107 |
+
noise_scheduler = DDPMScheduler(num_train_timesteps=1000)
|
| 108 |
+
noise = torch.randn(sample_image.shape)
|
| 109 |
+
timesteps = torch.LongTensor([50])
|
| 110 |
+
noisy_image = noise_scheduler.add_noise(sample_image, noise, timesteps)
|
| 111 |
+
|
| 112 |
+
Image.fromarray(((noisy_image.permute(0, 2, 3, 1) + 1.0) * 127.5).type(torch.uint8).numpy()[0])
|
| 113 |
+
#################################################
|
| 114 |
+
noise_pred = model(noisy_image, timesteps).sample
|
| 115 |
+
loss = F.mse_loss(noise_pred, noise)
|
| 116 |
+
|
| 117 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=config.learning_rate)
|
| 118 |
+
lr_scheduler = get_cosine_schedule_with_warmup(
|
| 119 |
+
optimizer=optimizer,
|
| 120 |
+
num_warmup_steps=config.lr_warmup_steps,
|
| 121 |
+
num_training_steps=(len(train_dataloader) * config.num_epochs),
|
| 122 |
+
)
|
| 123 |
+
#################################################
|
| 124 |
+
def evaluate(config, epoch, pipeline):
|
| 125 |
+
# Sample some images from random noise (this is the backward diffusion process).
|
| 126 |
+
# The default pipeline output type is `List[PIL.Image]`
|
| 127 |
+
images = pipeline(
|
| 128 |
+
batch_size=config.eval_batch_size,
|
| 129 |
+
generator=torch.manual_seed(config.seed),
|
| 130 |
+
).images
|
| 131 |
+
|
| 132 |
+
# Make a grid out of the images
|
| 133 |
+
image_grid = make_image_grid(images, rows=4, cols=4)
|
| 134 |
+
|
| 135 |
+
# Save the images
|
| 136 |
+
test_dir = os.path.join(config.output_dir, "samples")
|
| 137 |
+
os.makedirs(test_dir, exist_ok=True)
|
| 138 |
+
image_grid.save(f"{test_dir}/{epoch:04d}.png")
|
| 139 |
+
#################################################
|
| 140 |
+
def train_loop(config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler):
|
| 141 |
+
# Initialize accelerator and tensorboard logging
|
| 142 |
+
accelerator = Accelerator(
|
| 143 |
+
mixed_precision=config.mixed_precision,
|
| 144 |
+
gradient_accumulation_steps=config.gradient_accumulation_steps,
|
| 145 |
+
log_with="tensorboard",
|
| 146 |
+
project_dir=os.path.join(config.output_dir, "logs"),
|
| 147 |
+
)
|
| 148 |
+
if accelerator.is_main_process:
|
| 149 |
+
if config.output_dir is not None:
|
| 150 |
+
os.makedirs(config.output_dir, exist_ok=True)
|
| 151 |
+
if config.push_to_hub:
|
| 152 |
+
repo_id = create_repo(
|
| 153 |
+
repo_id=config.hub_model_id or Path(config.output_dir).name, exist_ok=True
|
| 154 |
+
).repo_id
|
| 155 |
+
accelerator.init_trackers("train_example")
|
| 156 |
+
|
| 157 |
+
# Prepare everything
|
| 158 |
+
# There is no specific order to remember, you just need to unpack the
|
| 159 |
+
# objects in the same order you gave them to the prepare method.
|
| 160 |
+
model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 161 |
+
model, optimizer, train_dataloader, lr_scheduler
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
global_step = 0
|
| 165 |
+
|
| 166 |
+
# Now you train the model
|
| 167 |
+
for epoch in range(config.num_epochs):
|
| 168 |
+
progress_bar = tqdm(total=len(train_dataloader), disable=not accelerator.is_local_main_process)
|
| 169 |
+
progress_bar.set_description(f"Epoch {epoch}")
|
| 170 |
+
|
| 171 |
+
for step, batch in enumerate(train_dataloader):
|
| 172 |
+
clean_images = batch["images"]
|
| 173 |
+
# Sample noise to add to the images
|
| 174 |
+
noise = torch.randn(clean_images.shape, device=clean_images.device)
|
| 175 |
+
bs = clean_images.shape[0]
|
| 176 |
+
|
| 177 |
+
# Sample a random timestep for each image
|
| 178 |
+
timesteps = torch.randint(
|
| 179 |
+
0, noise_scheduler.config.num_train_timesteps, (bs,), device=clean_images.device,
|
| 180 |
+
dtype=torch.int64
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
# Add noise to the clean images according to the noise magnitude at each timestep
|
| 184 |
+
# (this is the forward diffusion process)
|
| 185 |
+
noisy_images = noise_scheduler.add_noise(clean_images, noise, timesteps)
|
| 186 |
+
|
| 187 |
+
with accelerator.accumulate(model):
|
| 188 |
+
# Predict the noise residual
|
| 189 |
+
noise_pred = model(noisy_images, timesteps, return_dict=False)[0]
|
| 190 |
+
loss = F.mse_loss(noise_pred, noise)
|
| 191 |
+
accelerator.backward(loss)
|
| 192 |
+
|
| 193 |
+
accelerator.clip_grad_norm_(model.parameters(), 1.0)
|
| 194 |
+
optimizer.step()
|
| 195 |
+
lr_scheduler.step()
|
| 196 |
+
optimizer.zero_grad()
|
| 197 |
+
|
| 198 |
+
progress_bar.update(1)
|
| 199 |
+
logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0], "step": global_step}
|
| 200 |
+
progress_bar.set_postfix(**logs)
|
| 201 |
+
accelerator.log(logs, step=global_step)
|
| 202 |
+
global_step += 1
|
| 203 |
+
|
| 204 |
+
# After each epoch you optionally sample some demo images with evaluate() and save the model
|
| 205 |
+
if accelerator.is_main_process:
|
| 206 |
+
pipeline = DDPMPipeline(unet=accelerator.unwrap_model(model), scheduler=noise_scheduler)
|
| 207 |
+
|
| 208 |
+
if (epoch + 1) % config.save_image_epochs == 0 or epoch == config.num_epochs - 1:
|
| 209 |
+
evaluate(config, epoch, pipeline)
|
| 210 |
+
|
| 211 |
+
if (epoch + 1) % config.save_model_epochs == 0 or epoch == config.num_epochs - 1:
|
| 212 |
+
if config.push_to_hub:
|
| 213 |
+
upload_folder(
|
| 214 |
+
repo_id=repo_id,
|
| 215 |
+
folder_path=config.output_dir,
|
| 216 |
+
commit_message=f"Epoch {epoch}",
|
| 217 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 218 |
+
)
|
| 219 |
+
else:
|
| 220 |
+
pipeline.save_pretrained(config.output_dir)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
args = (config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler)
|
| 224 |
+
notebook_launcher(train_loop, args, num_processes=1)
|
| 225 |
+
|
| 226 |
+
#train_loop(config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler)
|
| 227 |
+
|
| 228 |
+
sample_images = sorted(glob.glob(f"{config.output_dir}/samples/*.png"))
|
| 229 |
+
Image.open(sample_images[-1])
|