base_model: stabilityai/stable-diffusion-3-medium-diffusers
library_name: diffusers
license: openrail++
tags:
- text-to-image
- diffusers-training
- diffusers
- lora
- template:sd-lora
- stable-diffusion-3
- stable-diffusion-3-diffusers
instance_prompt: <leaf microstructure>
widget: []
Stable Diffusion 3 Medium Fine-tuned with Leaf Images
Model description
These are LoRA adaption weights for stabilityai/stable-diffusion-3-medium-diffusers.
Trigger keywords
The following image were used during fine-tuning using the keyword <leaf microstructure>:
You should use to trigger the image generation.
How to use
Defining some helper functions:
from diffusers import DiffusionPipeline
import torch
import os
from datetime import datetime
from PIL import Image
def generate_filename(base_name, extension=".png"):
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
return f"{base_name}_{timestamp}{extension}"
def save_image(image, directory, base_name="image_grid"):
filename = generate_filename(base_name)
file_path = os.path.join(directory, filename)
image.save(file_path)
print(f"Image saved as {file_path}")
def image_grid(imgs, rows, cols, save=True, save_dir='generated_images', base_name="image_grid",
save_individual_files=False):
if not os.path.exists(save_dir):
os.makedirs(save_dir)
assert len(imgs) == rows * cols
w, h = imgs[0].size
grid = Image.new('RGB', size=(cols * w, rows * h))
grid_w, grid_h = grid.size
for i, img in enumerate(imgs):
grid.paste(img, box=(i % cols * w, i // cols * h))
if save_individual_files:
save_image(img, save_dir, base_name=base_name+f'_{i}-of-{len(imgs)}_')
if save and save_dir:
save_image(grid, save_dir, base_name)
return grid
Text-to-image
Model loading and generation pipeline:
repo_id_load='lamm-mit/stable-diffusion-3-medium-leaf-inspired'
pipeline = DiffusionPipeline.from_pretrained ("stabilityai/stable-diffusion-3-medium-diffusers",
torch_dtype=torch.float16
)
pipeline.load_lora_weights(repo_id_load)
pipeline=pipeline.to('cuda')
prompt = "a cube in the shape of a <leaf microstructure>"
negative_prompt = ""
num_samples = 3
num_rows = 3
n_steps=75
guidance_scale=15
all_images = []
for _ in range(num_rows):
image = pipeline(prompt,num_inference_steps=n_steps,num_images_per_prompt=num_samples,
guidance_scale=guidance_scale,negative_prompt=negative_prompt).images
all_images.extend(image)
grid = image_grid(all_images, num_rows, num_samples,
save_individual_files=True,
save_dir='generated_images',
base_name="image_grid",
)
grid
Image-to-image
We start with this image generated earlier:
from diffusers import StableDiffusion3Img2ImgPipeline
from diffusers.utils import load_image
pipeline = StableDiffusion3Img2ImgPipeline.from_pretrained("stabilityai/stable-diffusion-3-medium-diffusers", torch_dtype=torch.float16)
pipeline=pipeline.to('cuda')
init_image = load_image("https://huggingface.co/lamm-mit/stable-diffusion-3-medium-leaf-inspired/resolve/main/image_20240721_212111.png")
prompt = "Turn this image into a spider web."
negative_prompt=""
n_steps=20
guidance_scale=25
image = pipeline(prompt, num_inference_steps=n_steps,
guidance_scale=guidance_scale,
negative_prompt=negative_prompt,
image=init_image,
).images[0]
save_image(image, directory='generated_images', base_name="image_grid", )
image
More examples
Fine-tuning script
Download this script: SD3 DreamBooth-LoRA_Fine-Tune.ipynb
You need to create a local folder leaf_concept_dir_SD3_12
and add the leaf images (provided in this repository, see subfolder). The code will automatically download the training script. The training script can handle custom prompts associated with each image, which are generated using BLIP.
For instance, for the images used here, they are:
['<leaf microstructure>, a close up of a green plant with a lot of small holes',
'<leaf microstructure>, a close up of a leaf with a small insect on it',
'<leaf microstructure>, a close up of a plant with a lot of green leaves',
'<leaf microstructure>, a close up of a green plant with a yellow light',
'<leaf microstructure>, a close up of a green plant with a white center',
'<leaf microstructure>, arafed leaf with a white line on the center',
'<leaf microstructure>, a close up of a leaf with a yellow light shining through it',
'<leaf microstructure>, arafed image of a green plant with a yellow cross']
The Parquet dataset generated during pre-calculation of embeddings is stored in the folder {data_df_path}
. It includes the image paths, embeddings, and a few other columns that are used by the training script.
Training then proceeds as:
accelerate launch train_dreambooth_lora_sd3_miniature.py \
--pretrained_model_name_or_path="{pretrained_model_name_or_path}" \
--instance_data_dir="{instance_data_dir}" \
--data_df_path="{instance_output_dir_embed}" \
--output_dir="{instance_output_dir}" \
--mixed_precision="fp16" \
--instance_prompt="{instance_prompt}" \
--resolution=1024 \
--train_batch_size=1 \
--gradient_accumulation_steps=4 \
--gradient_checkpointing \
--learning_rate=1e-4 \
--lr_scheduler="constant" \
--weighting_scheme="logit_normal" \
--lr_warmup_steps=0 \
--use_8bit_adam \
--max_train_steps=500 \
--checkpointing_steps=500 \
--seed="3234290"