It looks like you're trying to set up LoRA (Low-Rank Adaptation) training for Stable Diffusion XL (SDXL). However, the way you're setting up LoRA in your code has some issues, which are preventing it from working correctly.
Here's what's wrong and how to fix it:
-
Incorrect Replacement of Attention Processors:
- You're trying to replace attention processors in the UNet with LoRA versions using
LoRAAttnProcessor2_0.from_module(module, rank=rank). However, from_module may not correctly handle all types of attention processors present in the UNet.
- Additionally, the
LoRAAttnProcessor2_0 should be used for certain attention layers, while LoRAAttnProcessor should be used for others.
-
Not Handling Different Types of Attention Layers:
- The UNet in SDXL has different types of attention layers (cross-attention and self-attention), and they should be handled differently when setting up LoRA.
-
Improper Freezing of Parameters:
- While you are freezing the UNet parameters, you might not be correctly setting
requires_grad for the LoRA parameters.
-
Missing Configuration for Text Encoders:
- Although you're freezing the text encoders, SDXL uses two text encoders, and additional steps may be needed if you plan to train or freeze them differently.
-
Using Outdated or Incorrect Methods:
- The methods used for setting up LoRA may not be aligned with the latest
diffusers library implementations.
Here's how you can fix the code:
-
Properly Replace Attention Processors with LoRA Versions:
- Use
unet.set_attn_processor() to set the attention processors.
- Use appropriate LoRA attention processor classes for different attention layers.
-
Ensure All LoRA Parameters are Trainable:
- After replacing the attention processors, make sure that only the LoRA parameters have
requires_grad = True.
-
Adjust the Code to Match the Latest diffusers Standards:
- Update the code to align with the latest examples provided by
diffusers, especially for SDXL LoRA training.
Here's the corrected and updated code with explanations:
import torch
from torch import nn
from torch.optim import AdamW
from torch.utils.data import DataLoader
from tqdm.auto import tqdm
from diffusers import (
StableDiffusionXLPipeline,
DDPMScheduler,
)
from diffusers.models.attention_processor import (
LoRAAttnProcessor,
LoRAAttnProcessor2_0,
)
from datasets import load_dataset
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Load the SDXL pipeline
pipe = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
torch_dtype=torch.float16,
variant="fp16",
use_safetensors=True,
add_watermarker=False,
)
pipe.to(device)
# Freeze the VAE and text encoders
pipe.vae.requires_grad_(False)
pipe.text_encoder.requires_grad_(False) # CLIP-L
pipe.text_encoder_2.requires_grad_(False) # CLIP-G
# Set the LoRA rank
rank = 4
# Create a dictionary to hold the LoRA attention processors
lora_attn_procs = {}
for name, module in pipe.unet.attn_processors.items():
if name.endswith("attn1.processor"):
# Cross-Attention Layers use LoRAAttnProcessor
lora_attn_procs[name] = LoRAAttnProcessor(
hidden_size=module.hidden_size, cross_attention_dim=module.cross_attention_dim, rank=rank
)
elif name.endswith("attn2.processor"):
# Self-Attention Layers use LoRAAttnProcessor2_0
lora_attn_procs[name] = LoRAAttnProcessor2_0(
hidden_size=module.hidden_size, rank=rank
)
else:
lora_attn_procs[name] = module # Keep the original module
# Set the LoRA attention processors
pipe.unet.set_attn_processor(lora_attn_procs)
# Freeze UNet parameters except for LoRA parameters
pipe.unet.requires_grad_(False)
for param in pipe.unet.parameters():
param.requires_grad = False
for module in pipe.unet.attn_processors.values():
if hasattr(module, 'parameters'):
for param in module.parameters():
param.requires_grad = True
# Create the scheduler with Cosine-Continuous Noise Schedule
scheduler = DDPMScheduler(
beta_start=0.0001,
beta_end=0.02,
beta_schedule="squaredcos_cap_v2",
num_train_timesteps=1000,
prediction_type="v_prediction",
)
pipe.scheduler = scheduler
# Load the dataset
dataset = load_dataset("OpenFace-CQUPT/HumanCaption-10M")
dataloader = DataLoader(dataset, batch_size=4, shuffle=True, num_workers=4)
# Prepare the optimizer with only LoRA parameters
trainable_params = (
param for param in pipe.unet.parameters() if param.requires_grad
)
optimizer = AdamW(trainable_params, lr=1e-4)
num_epochs = 5
for epoch in range(num_epochs):
pipe.unet.train()
total_loss = 0.0
progress_bar = tqdm(dataloader, desc=f"Epoch {epoch+1}/{num_epochs}")
for step, batch in enumerate(progress_bar):
optimizer.zero_grad()
# Move images to device and encode to latents
images = batch['pixel_values'].to(device, dtype=torch.float16)
captions = batch['caption']
# Encode captions using both tokenizers and text encoders
inputs = pipe.tokenizer(
captions,
padding='max_length',
truncation=True,
max_length=pipe.tokenizer.model_max_length,
return_tensors='pt',
).to(device)
inputs_2 = pipe.tokenizer_2(
captions,
padding='max_length',
truncation=True,
max_length=pipe.tokenizer_2.model_max_length,
return_tensors='pt',
).to(device)
with torch.no_grad():
encoder_hidden_states = pipe.text_encoder(
input_ids=inputs.input_ids,
)[0]
encoder_hidden_states_2 = pipe.text_encoder_2(
input_ids=inputs_2.input_ids,
)[0]
# Encode images to latent space
latents = pipe.vae.encode(images).latent_dist.sample()
latents = latents * pipe.vae.config.scaling_factor # VAE scaling factor
# Sample noise
noise = torch.randn_like(latents)
# Sample random timesteps
timesteps = torch.randint(
0, scheduler.config.num_train_timesteps, (latents.shape[0],), device=device
).long()
# Add noise to latents to get noisy latents
noisy_latents = scheduler.add_noise(latents, noise, timesteps)
# Predict 'v' using the UNet model
model_pred = pipe.unet(
sample=noisy_latents,
timestep=timesteps,
encoder_hidden_states=encoder_hidden_states,
encoder_hidden_states_2=encoder_hidden_states_2,
return_dict=False,
)[0]
# Get the target for loss depending on the prediction type
target = scheduler.get_velocity(latents, noise, timesteps)
loss = nn.functional.mse_loss(model_pred.float(), target.float(), reduction="mean")
# Backpropagation
loss.backward()
optimizer.step()
# Update progress bar and total loss
total_loss += loss.item()
avg_loss = total_loss / (step + 1)
progress_bar.set_postfix({'loss': avg_loss})
print(f"Epoch {epoch + 1}/{num_epochs}, Average Loss: {avg_loss}")
def save_lora_weights(unet, save_path):
lora_state_dict = LoraLoaderMixin.convert_lora_to_state_dict(unet)
torch.save(lora_state_dict, save_path)
save_lora_weights(pipe.unet, "lora_weights.pt")
Explanation of Changes:
-
Properly Create LoRA Attention Processors:
- We iterate over
pipe.unet.attn_processors.items() to get both the name and the module.
- For attention processors that end with
"attn1.processor" (typically cross-attention layers), we use LoRAAttnProcessor.
- For those that end with
"attn2.processor" (typically self-attention layers), we use LoRAAttnProcessor2_0.
lora_attn_procs = {}
for name, module in pipe.unet.attn_processors.items():
if name.endswith("attn1.processor"):
# Cross-Attention Layers
lora_attn_procs[name] = LoRAAttnProcessor(
hidden_size=module.hidden_size, cross_attention_dim=module.cross_attention_dim, rank=rank
)
elif name.endswith("attn2.processor"):
# Self-Attention Layers
lora_attn_procs[name] = LoRAAttnProcessor2_0(
hidden_size=module.hidden_size, rank=rank
)
else:
lora_attn_procs[name] = module # Keep the original module
-
Set the LoRA Attention Processors:
- After creating the
lora_attn_procs dictionary, we set them using pipe.unet.set_attn_processor(lora_attn_procs).
-
Freeze the UNet Parameters Properly:
- We freeze all parameters in the UNet by setting
pipe.unet.requires_grad_(False).
- Then, we iterate over the attention processors' parameters and set
requires_grad = True.
pipe.unet.requires_grad_(False)
for param in pipe.unet.parameters():
param.requires_grad = False
for module in pipe.unet.attn_processors.values():
if hasattr(module, 'parameters'):
for param in module.parameters():
param.requires_grad = True
-
Ensure Only LoRA Parameters are Trainable:
- When setting up the optimizer, we only include parameters where
param.requires_grad == True.
trainable_params = (
param for param in pipe.unet.parameters() if param.requires_grad
)
optimizer = AdamW(trainable_params, lr=1e-4)
-
Adjust the Scheduler and Training Loop:
- The rest of the code remains mostly the same, but make sure to handle everything in the context of training only the LoRA parameters.
-
Save LoRA Weights Correctly:
Additional Tips:
-
Text Encoders:
- Since you're freezing
pipe.text_encoder and pipe.text_encoder_2, you don't need to modify them for LoRA.
- If you decide to train them with LoRA, similar steps would be needed.
-
Check diffusers Version:
- Ensure you have the latest version of
diffusers installed (pip install --upgrade diffusers), as the API might have changed.
-
Memory Management:
- Training SDXL with LoRA can still require significant GPU memory. If you run into memory issues, consider reducing the batch size or using gradient accumulation.
-
Validation:
- It's a good practice to validate the model periodically during training to monitor overfitting or check the qualitative performance.
References:
By updating your LoRA setup as shown, your code should work correctly, and you should be able to train LoRA adapters for SDXL.