= Parameters().from_json('../config.json')
params = params.from_json('../tokens.json') _
Training a Diffuser
Learn how to train a diffuser
Setup basic parameters
Since the model checkpoints are quite large, install Git-LFS to version these large files:
!sudo apt -qq install git-lfs
!git config --global credential.helper store
git-lfs is already the newest version (2.9.2-1).
0 upgraded, 0 newly installed, 0 to remove and 20 not upgraded.
Set training hyperparameters
= Parameters(
params.config = 128, # the generated image resolution
image_size = 16,
train_batch_size = 16, # how many images to sample during evaluation
eval_batch_size = 50,
num_epochs = 1,
gradient_accumulation_steps = 1e-4,
learning_rate = 500,
lr_warmup_steps = 10, #10
save_image_epochs = 30, #30
save_model_epochs = "fp16", # `no` for float32, `fp16` for automatic mixed precision
mixed_precision = f"{params.path.output}/ddpm-butterflies-128", # the model name locally and on the HF Hub
output_dir = False, # whether to upload the saved model to the HF Hub
push_to_hub = False,
hub_private_repo = True, # overwrite the old model when re-running the notebook
overwrite_output_dir = 0) seed
Load the dataset
Load the Smithsonian Butterflies dataset with the 🤗 Datasets library:
= "huggan/smithsonian_butterflies_subset"
params.config.dataset_name = load_dataset(params.config.dataset_name, split="train") dataset
Let’s explore the dataset and look at some images
print(f'The dataset has {len(dataset)} images')
= plt.subplots(1, 4, figsize=(16, 4))
fig, axs for i, image in enumerate(dataset[:4]["image"]):
= axs[i].imshow(image)
_
axs[i].set_axis_off() fig.show()
The dataset has 1000 images
We want to create a transform that would resize the image to the same size, do random flip and create a tensor
= transforms.Compose(
preprocess
[
transforms.Resize((params.config.image_size, params.config.image_size)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),0.5], [0.5]),
transforms.Normalize([
]
)
def transform(examples):
= [preprocess(image.convert("RGB")) for image in examples["image"]]
images return {"images": images}
dataset.set_transform(transform)
Define dataloader
= torch.utils.data.DataLoader(dataset, batch_size=params.config.train_batch_size, shuffle=True) train_dataloader
Create a UNet2DModel
= UNet2DModel(
model =params.config.image_size, # the target image resolution
sample_size=3, # the number of input channels, 3 for RGB images
in_channels=3, # the number of output channels
out_channels=2, # how many ResNet layers to use per UNet block
layers_per_block=(128, 128, 256, 256, 512, 512), # the number of output channels for each UNet block
block_out_channels=(
down_block_types"DownBlock2D", # a regular ResNet downsampling block
"DownBlock2D",
"DownBlock2D",
"DownBlock2D",
"AttnDownBlock2D", # a ResNet downsampling block with spatial self-attention
"DownBlock2D",
),=(
up_block_types"UpBlock2D", # a regular ResNet upsampling block
"AttnUpBlock2D", # a ResNet upsampling block with spatial self-attention
"UpBlock2D",
"UpBlock2D",
"UpBlock2D",
"UpBlock2D",
), )
Checking the model sample output’s shape matches the input’s shape
= dataset[0]["images"].unsqueeze(0)
sample_image print("Input shape:", sample_image.shape)
print("Output shape:", model(sample_image, timestep=0).sample.shape)
Input shape: torch.Size([1, 3, 128, 128])
Output shape: torch.Size([1, 3, 128, 128])
Create a scheduler
= DDPMScheduler(num_train_timesteps=1000)
noise_scheduler = torch.randn(sample_image.shape)
noise = torch.LongTensor([50])
timesteps = noise_scheduler.add_noise(sample_image, noise, timesteps)
noisy_image
0, 2, 3, 1) + 1.0) * 127.5).type(torch.uint8).numpy()[0]) Image.fromarray(((noisy_image.permute(
Define loss and prediction
= model(noisy_image, timesteps).sample
noise_pred = F.mse_loss(noise_pred, noise) loss
Train the model
optimizer and a learning rate scheduler
= torch.optim.AdamW(model.parameters(), lr=params.config.learning_rate)
optimizer = get_cosine_schedule_with_warmup(
lr_scheduler =optimizer,
optimizer=params.config.lr_warmup_steps,
num_warmup_steps=(len(train_dataloader) * params.config.num_epochs),
num_training_steps )
Evaluation functions
def make_grid(images, rows, cols):
= images[0].size
w, h = Image.new("RGB", size=(cols * w, rows * h))
grid for i, image in enumerate(images):
=(i % cols * w, i // cols * h))
grid.paste(image, boxreturn grid
def evaluate(config, epoch, pipeline):
# Sample some images from random noise (this is the backward diffusion process).
# The default pipeline output type is `List[PIL.Image]`
= pipeline(
images =params.config.eval_batch_size,
batch_size=torch.manual_seed(config.seed),
generator
).images
# Make a grid out of the images
= make_grid(images, rows=4, cols=4)
image_grid
# Save the images
= os.path.join(config.output_dir, f"samples")
test_dir =True)
os.makedirs(test_dir, exist_okf"{test_dir}/{epoch:04d}_{config.seed}.png") image_grid.save(
Training Loop
def get_full_repo_name(model_id: str, organization: str = None, token: str = None):
if token is None:
= HfFolder.get_token()
token if organization is None:
= whoami(token)["name"]
username return f"{username}/{model_id}"
else:
return f"{organization}/{model_id}"
def train_loop(config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler):
# Initialize accelerator and tensorboard logging
= Accelerator(
accelerator =config.mixed_precision,
mixed_precision=config.gradient_accumulation_steps,
gradient_accumulation_steps="tensorboard",
log_with=os.path.join(config.output_dir, "logs"),
logging_dir
)if accelerator.is_main_process:
if config.push_to_hub:
= get_full_repo_name(Path(config.output_dir).name)
repo_name = Repository(config.output_dir, clone_from=repo_name)
repo elif config.output_dir is not None:
=True)
os.makedirs(config.output_dir, exist_ok"train_example")
accelerator.init_trackers(
# Prepare everything
# There is no specific order to remember, you just need to unpack the
# objects in the same order you gave them to the prepare method.
= accelerator.prepare(
model, optimizer, train_dataloader, lr_scheduler
model, optimizer, train_dataloader, lr_scheduler
)
= 0
global_step
# Now you train the model
for epoch in range(config.num_epochs):
= tqdm(total=len(train_dataloader), disable=not accelerator.is_local_main_process)
progress_bar f"Epoch {epoch}")
progress_bar.set_description(
for step, batch in enumerate(train_dataloader):
= batch["images"]
clean_images # Sample noise to add to the images
= torch.randn(clean_images.shape).to(clean_images.device)
noise = clean_images.shape[0]
bs
# Sample a random timestep for each image
= torch.randint(
timesteps 0, noise_scheduler.config.num_train_timesteps, (bs,), device=clean_images.device
long()
).
# Add noise to the clean images according to the noise magnitude at each timestep
# (this is the forward diffusion process)
= noise_scheduler.add_noise(clean_images, noise, timesteps)
noisy_images
with accelerator.accumulate(model):
# Predict the noise residual
= model(noisy_images, timesteps, return_dict=False)[0]
noise_pred = F.mse_loss(noise_pred, noise)
loss
accelerator.backward(loss)
1.0)
accelerator.clip_grad_norm_(model.parameters(),
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
1)
progress_bar.update(= {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0], "step": global_step}
logs **logs)
progress_bar.set_postfix(=global_step)
accelerator.log(logs, step+= 1
global_step
# After each epoch you optionally sample some demo images with evaluate() and save the model
if accelerator.is_main_process:
= DDPMPipeline(unet=accelerator.unwrap_model(model), scheduler=noise_scheduler)
pipeline
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:
=f"Epoch {epoch}", blocking=True)
repo.push_to_hub(commit_messageelse:
pipeline.save_pretrained(config.output_dir)
Let’s train
= (params.config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler)
args
=1) notebook_launcher(train_loop, args, num_processes
Launching training on one GPU.
View the output
= sorted(glob.glob(f"{params.config.output_dir}/samples/*.png"))
sample_images open(sample_images[-1]) Image.
= sorted(glob.glob(f"{params.config.output_dir}/samples/*.png"))
sample_images open(sample_images[-2]) Image.
open(sample_images[-3]) Image.