Use ImagenTrainer for automated training and EMA
mainThe ImagenTrainer wrapper simplifies training by automatically handling Exponential Moving Averages (EMA) for all U-Nets in the cascade. When calling the trainer, you can use max_batch_size to automatically divide a large batch into smaller sub-batches to fit in memory (gradient accumulation). Use trainer.update(unet_number = i) to update the EMA for a specific U-Net. It is highly recommended to use trainer.save() and trainer.load() instead of manual state_dict calls to ensure proper device memory management.
import torch
from imagen_pytorch import Unet, Imagen, ImagenTrainer
unet1 = Unet(
dim = 32,
cond_dim = 512,
dim_mults = (1, 2, 4, 8),
num_resnet_blocks = 3,
layer_attns = (False, True, True, True),
)
unet2 = Unet(
dim = 32,
cond_dim = 512,
dim_mults = (1, 2, 4, 8),
num_resnet_blocks = (2, 4, 8, 8),
layer_attns = (False, False, False, True),
layer_cross_attns = (False, False, False, True),
)
imagen = Imagen(
unets = (unet1, unet2),
text_encoder_name = 't5-large',
image_sizes = (64, 256),
timesteps = 1000,
cond_drop_prob = 0.1
).cuda()
trainer = ImagenTrainer(imagen)
text_embeds = torch.randn(64, 256, 1024).cuda()
images = torch.randn(64, 3, 256, 256).cuda()
# Training with gradient accumulation via max_batch_size
loss = trainer(
images,
text_embeds = text_embeds,
unet_number = 1,
max_batch_size = 4
)
trainer.update(unet_number = 1)
# Sampling via trainer
images = trainer.sample(texts = [
'a puppy looking anxiously at a giant donut on the table',
'the milky way galaxy in the style of monet'
], cond_scale = 3.)
# Checkpointing
trainer.save('./path/to/checkpoint.pt')
trainer.load('./path/to/checkpoint.pt')
print(trainer.steps) # (2,) step number for each of the unets