|
from dataclasses import dataclass |
|
NUM_TIMESTEPS = 50 |
|
@dataclass |
|
class TrainingConfig: |
|
image_size = 64 |
|
train_batch_size = 16 |
|
eval_batch_size = 16 |
|
num_epochs = 2000 |
|
gradient_accumulation_steps = 1 |
|
learning_rate = 1e-4 |
|
lr_warmup_steps = 500 |
|
save_image_epochs = 100 |
|
save_model_epochs = 300 |
|
mixed_precision = "fp16" |
|
output_dir = "ddpm-rct" |
|
|
|
push_to_hub = False |
|
hub_private_repo = False |
|
overwrite_output_dir = True |
|
seed = 0 |
|
|
|
|
|
config = TrainingConfig() |
|
|
|
from datasets import load_dataset |
|
|
|
config.dataset_name = "frutiemax/rct_dataset" |
|
dataset = load_dataset(config.dataset_name, split="train[0:4]") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
from torchvision import transforms |
|
|
|
preprocess = transforms.Compose( |
|
[ |
|
transforms.Resize((config.image_size, config.image_size)), |
|
transforms.RandomHorizontalFlip(), |
|
transforms.ToTensor(), |
|
transforms.Normalize([0.5], [0.5]), |
|
] |
|
) |
|
|
|
def transform(examples): |
|
images = [preprocess(image.convert("RGB")) for image in examples["image"]] |
|
return {"images": images} |
|
|
|
|
|
dataset.set_transform(transform) |
|
import torch |
|
|
|
train_dataloader = torch.utils.data.DataLoader(dataset, batch_size=config.train_batch_size, shuffle=True) |
|
from diffusers import UNet2DModel |
|
|
|
model = UNet2DModel( |
|
sample_size=config.image_size, |
|
in_channels=3, |
|
out_channels=3, |
|
layers_per_block=2, |
|
block_out_channels=(256, 256, 512, 512, 1024, 1024), |
|
down_block_types=( |
|
"DownBlock2D", |
|
"DownBlock2D", |
|
"DownBlock2D", |
|
"DownBlock2D", |
|
"AttnDownBlock2D", |
|
"DownBlock2D", |
|
), |
|
up_block_types=( |
|
"UpBlock2D", |
|
"AttnUpBlock2D", |
|
"UpBlock2D", |
|
"UpBlock2D", |
|
"UpBlock2D", |
|
"UpBlock2D", |
|
), |
|
) |
|
sample_image = dataset[0]["images"].unsqueeze(0) |
|
print("Input shape:", sample_image.shape) |
|
|
|
print("Output shape:", model(sample_image, timestep=0).sample.shape) |
|
import torch |
|
from PIL import Image |
|
from diffusers import DDPMScheduler |
|
|
|
noise_scheduler = DDPMScheduler(num_train_timesteps=NUM_TIMESTEPS) |
|
noise = torch.randn(sample_image.shape) |
|
import torch.nn.functional as F |
|
from diffusers.optimization import get_cosine_schedule_with_warmup |
|
|
|
optimizer = torch.optim.AdamW(model.parameters(), lr=config.learning_rate) |
|
lr_scheduler = get_cosine_schedule_with_warmup( |
|
optimizer=optimizer, |
|
num_warmup_steps=config.lr_warmup_steps, |
|
num_training_steps=(len(train_dataloader) * config.num_epochs), |
|
) |
|
|
|
from diffusers import DDPMPipeline |
|
from diffusers.utils import make_image_grid |
|
import math |
|
import os |
|
|
|
|
|
def evaluate(config, epoch, pipeline): |
|
|
|
|
|
images = pipeline( |
|
batch_size=config.eval_batch_size, |
|
generator=torch.manual_seed(config.seed), num_inference_steps=NUM_TIMESTEPS |
|
).images |
|
|
|
|
|
image_grid = make_image_grid(images, rows=4, cols=4) |
|
|
|
|
|
test_dir = os.path.join(config.output_dir, "samples") |
|
os.makedirs(test_dir, exist_ok=True) |
|
image_grid.save(f"{test_dir}/{epoch:04d}.png") |
|
|
|
from accelerate import Accelerator |
|
from huggingface_hub import HfFolder, Repository, whoami |
|
from tqdm.auto import tqdm |
|
from pathlib import Path |
|
import os |
|
|
|
|
|
def get_full_repo_name(model_id: str, organization: str = None, token: str = None): |
|
if token is None: |
|
token = HfFolder.get_token() |
|
if organization is None: |
|
username = whoami(token)["name"] |
|
return f"{username}/{model_id}" |
|
else: |
|
return f"{organization}/{model_id}" |
|
|
|
|
|
def train_loop(config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler): |
|
|
|
accelerator = Accelerator( |
|
mixed_precision=config.mixed_precision, |
|
gradient_accumulation_steps=config.gradient_accumulation_steps, |
|
log_with="tensorboard", |
|
project_dir=os.path.join(config.output_dir, "logs"), |
|
) |
|
if accelerator.is_main_process: |
|
if config.push_to_hub: |
|
repo_name = get_full_repo_name(Path(config.output_dir).name) |
|
repo = Repository(config.output_dir, clone_from=repo_name) |
|
elif config.output_dir is not None: |
|
os.makedirs(config.output_dir, exist_ok=True) |
|
accelerator.init_trackers("train_example") |
|
|
|
|
|
|
|
|
|
model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare( |
|
model, optimizer, train_dataloader, lr_scheduler |
|
) |
|
|
|
global_step = 0 |
|
|
|
|
|
for epoch in range(config.num_epochs): |
|
progress_bar = tqdm(total=len(train_dataloader), disable=not accelerator.is_local_main_process) |
|
progress_bar.set_description(f"Epoch {epoch}") |
|
|
|
for step, batch in enumerate(train_dataloader): |
|
clean_images = batch["images"] |
|
|
|
noise = torch.randn(clean_images.shape).to(clean_images.device) |
|
bs = clean_images.shape[0] |
|
|
|
|
|
timesteps = torch.randint( |
|
0, noise_scheduler.config.num_train_timesteps, (bs,), device=clean_images.device |
|
).long() |
|
|
|
|
|
|
|
noisy_images = noise_scheduler.add_noise(clean_images, noise, timesteps) |
|
|
|
with accelerator.accumulate(model): |
|
|
|
noise_pred = model(noisy_images, timesteps, return_dict=False)[0] |
|
loss = F.mse_loss(noise_pred, noise) |
|
accelerator.backward(loss) |
|
|
|
accelerator.clip_grad_norm_(model.parameters(), 1.0) |
|
optimizer.step() |
|
lr_scheduler.step() |
|
optimizer.zero_grad() |
|
|
|
progress_bar.update(1) |
|
logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0], "step": global_step} |
|
progress_bar.set_postfix(**logs) |
|
accelerator.log(logs, step=global_step) |
|
global_step += 1 |
|
|
|
|
|
if accelerator.is_main_process: |
|
pipeline = DDPMPipeline(unet=accelerator.unwrap_model(model), scheduler=noise_scheduler) |
|
|
|
if (epoch + 1) % config.save_image_epochs == 0 or epoch == config.num_epochs - 1: |
|
evaluate(config, epoch, pipeline) |
|
|
|
if (epoch + 1) % config.save_model_epochs == 0 or epoch == config.num_epochs - 1: |
|
if config.push_to_hub: |
|
repo.push_to_hub(commit_message=f"Epoch {epoch}", blocking=True) |
|
else: |
|
pipeline.save_pretrained(config.output_dir) |
|
|
|
from accelerate import notebook_launcher |
|
|
|
args = (config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler) |
|
|
|
notebook_launcher(train_loop, args, num_processes=1) |
|
|
|
import glob |
|
|
|
sample_images = sorted(glob.glob(f"{config.output_dir}/samples/*.png")) |
|
Image.open(sample_images[-1]) |