Write a stable diffusion 3 learning script
- User
Write a stable diffusion 3 learning script
- Assistant
Write a stable diffusion 3 learning script
Certainly! Below is a comprehensive guide and script for fine-tuning Stable Diffusion using the diffusers library by Hugging Face. This script focuses on fine-tuning the UNet component of the model, which is responsible for denoising images during the diffusion process. Fine-tuning allows you to tailor the model to specific datasets or tasks, enhancing its performance for your particular needs.
Note: As of my knowledge cutoff in October 2023, Stable Diffusion 3 may not be publicly available. This script is based on Stable Diffusion version 1.5. If Stable Diffusion 3 becomes available and follows a similar architecture, the script can be adapted accordingly.
Hardware Requirements:
Software Requirements:
diffusers, transformers, datasets, and accelerate libraries.Access to the Stable Diffusion Model:
Create and Activate a Virtual Environment:
python -m venv stable-diffusion-env
source stable-diffusion-env/bin/activate # On Windows: stable-diffusion-env\Scripts\activate
Install Required Libraries:
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
pip install diffusers transformers accelerate datasets
pip install huggingface_hub
Note: Replace
cu118with your CUDA version if necessary. For CPU-only training, install the CPU version of PyTorch.
Log In to Hugging Face:
huggingface-cli login
Follow the prompts to authenticate.
Dataset Requirements:
Organize Your Data:
data/images/.data/annotations.csv, with two columns: image_path and caption.Sample annotations.csv:
image_path,caption
images/img1.jpg,A cat sitting on a windowsill.
images/img2.jpg,A scenic view of mountains during sunset.
...
Load the Dataset Using Hugging Face's datasets Library:
from datasets import load_dataset
dataset = load_dataset('csv', data_files={'train': 'data/annotations.csv'}, delimiter=',')
Below is a detailed script for fine-tuning Stable Diffusion. The script handles data loading, preprocessing, model setup, training loop, and checkpoint saving.
import torch
from torch import nn
from torch.utils.data import DataLoader
from diffusers import (
StableDiffusionPipeline,
UNet2DConditionModel,
AutoencoderKL,
CLIPTextModel,
CLIPTokenizer,
)
from transformers import get_scheduler
from datasets import load_dataset
from tqdm.auto import tqdm
import os
# Configuration
MODEL_NAME = "runwayml/stable-diffusion-v1-5" # Update if using a different version
OUTPUT_DIR = "./stable-diffusion-finetuned"
DATA_CSV = "data/annotations.csv"
IMAGE_DIR = "data/images/"
TRAIN_BATCH_SIZE = 4
EPOCHS = 3
LEARNING_RATE = 5e-6
WEIGHT_DECAY = 1e-2
NUM_WORKERS = 4
MAX_TRAIN_STEPS = None # Set to None to compute based on epochs
# Ensure output directory exists
os.makedirs(OUTPUT_DIR, exist_ok=True)
# Device Setup
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
print(f"Using device: {device}")
# Load Components of Stable Diffusion
vae = AutoencoderKL.from_pretrained(MODEL_NAME, subfolder="vae").to(device)
tokenizer = CLIPTokenizer.from_pretrained(MODEL_NAME, subfolder="tokenizer")
text_encoder = CLIPTextModel.from_pretrained(MODEL_NAME, subfolder="text_encoder").to(device)
unet = UNet2DConditionModel.from_pretrained(MODEL_NAME, subfolder="unet").to(device)
# Freeze VAE and Text Encoder
vae.requires_grad_(False)
text_encoder.requires_grad_(False)
# Prepare the Optimizer
optimizer = torch.optim.AdamW(unet.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY)
# Load and Preprocess Dataset
dataset = load_dataset('csv', data_files={'train': DATA_CSV}, delimiter=',')['train']
def preprocess(batch):
# Load and preprocess images
images = [torch.from_numpy(np.array(image)).permute(2, 0, 1).float()/255. for image in batch['image']]
batch['pixel_values'] = images
# Tokenize captions
encodings = tokenizer(batch['caption'], padding='max_length', truncation=True, max_length=tokenizer.model_max_length)
batch['input_ids'] = encodings['input_ids']
return batch
import numpy as np
from PIL import Image
def load_image(image_path):
return Image.open(os.path.join(IMAGE_DIR, image_path)).convert("RGB")
dataset = dataset.map(lambda x: {'image': load_image(x['image_path'])}, batched=False)
dataset = dataset.map(preprocess, batched=True, batch_size=TRAIN_BATCH_SIZE)
# DataLoader
train_dataloader = DataLoader(
dataset,
batch_size=TRAIN_BATCH_SIZE,
shuffle=True,
num_workers=NUM_WORKERS,
)
# Scheduler
num_training_steps = EPOCHS * len(train_dataloader) if MAX_TRAIN_STEPS is None else MAX_TRAIN_STEPS
lr_scheduler = get_scheduler(
"linear",
optimizer=optimizer,
num_warmup_steps=0,
num_training_steps=num_training_steps,
)
# Move Models to Device
unet.to(device)
# Training Loop
progress_bar = tqdm(range(num_training_steps))
unet.train()
for epoch in range(EPOCHS):
for batch in train_dataloader:
# Move batch to device
pixel_values = torch.stack(batch['pixel_values']).to(device)
input_ids = torch.tensor(batch['input_ids']).to(device)
# Encode the text
with torch.no_grad():
encoder_hidden_states = text_encoder(input_ids)[0]
# Sample noise and timesteps
noise = torch.randn_like(pixel_values).to(device)
timesteps = torch.randint(0, 1000, (pixel_values.shape[0],), device=device).long()
# Encode the images to latent space
with torch.no_grad():
latents = vae.encode(pixel_values).latent_dist.sample()
latents = latents * 0.18215 # Scaling factor from Stable Diffusion
# Add noise to the latents
noisy_latents = latents + noise
# Predict the noise residual
noise_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
# Calculate loss (Mean Squared Error)
loss = nn.MSELoss()(noise_pred, noise)
# Backpropagation
loss.backward()
# Optimizer step
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
# Update progress bar
progress_bar.update(1)
progress_bar.set_description(f"Epoch {epoch+1} | Loss: {loss.item():.4f}")
# Early stopping if max training steps are reached
if MAX_TRAIN_STEPS is not None and progress_bar.n >= MAX_TRAIN_STEPS:
break
# Save checkpoint after each epoch
unet.save_pretrained(os.path.join(OUTPUT_DIR, f"unet_epoch_{epoch+1}"))
print("Training completed!")
# Save the final fine-tuned model
unet.save_pretrained(os.path.join(OUTPUT_DIR, "unet_final"))
Configuration Section:
TRAIN_BATCH_SIZE, EPOCHS, LEARNING_RATE, etc., based on your computational resources and dataset size.Device Setup:
Model Components:
Freezing Components:
Optimizer and Scheduler:
Dataset Loading and Preprocessing:
Training Loop:
tqdm.Checkpointing:
Batch Size and VRAM:
TRAIN_BATCH_SIZE based on your GPU's VRAM. Use smaller batches if you encounter out-of-memory errors.Gradient Accumulation:
Mixed Precision Training:
torch.cuda.amp for mixed precision to speed up training and reduce memory usage.Early Stopping and Checkpoints:
Data Augmentation:
Hyperparameter Tuning:
After training, you can load and use your fine-tuned model as follows:
from diffusers import StableDiffusionPipeline
import torch
# Load the fine-tuned UNet
fine_tuned_unet = UNet2DConditionModel.from_pretrained(
"./stable-diffusion-finetuned/unet_final",
subfolder="unet"
).to(device)
# Load other components
vae = AutoencoderKL.from_pretrained("runwayml/stable-diffusion-v1-5", subfolder="vae").to(device)
tokenizer = CLIPTokenizer.from_pretrained("runwayml/stable-diffusion-v1-5", subfolder="tokenizer")
text_encoder = CLIPTextModel.from_pretrained("runwayml/stable-diffusion-v1-5", subfolder="text_encoder").to(device)
# Create the pipeline
pipeline = StableDiffusionPipeline(
vae=vae,
text_encoder=text_encoder,
tokenizer=tokenizer,
unet=fine_tuned_unet,
).to(device)
# Generate an image
prompt = "A majestic dragon flying over a medieval castle."
image = pipeline(prompt).images[0]
image.save("generated_image.png")
Tip: Adjust the prompt to reflect the domain your model was fine-tuned on for best results.
Fine-tuning Stable Diffusion enables you to customize the model for specific tasks or datasets, enhancing its generative capabilities in desired directions. The provided script offers a foundational approach, which you can expand upon with advanced techniques like LoRA (Low-Rank Adaptation) for parameter-efficient training, gradient checkpointing to save memory, or integrating custom data augmentations.
Always ensure compliance with the licensing terms of the base models and datasets you use. Happy fine-tuning!