SKILL.md
SKILL.mdBrowse 3 files
3,292 tokens
12,834 bytes
Token encoding: o200k_base
Snapshot 24fd22b
1---2name: stable-diffusion3description: Text-to-image generation, inpainting, and img2img.4version: 1.0.05author: Orchestra Research6license: MIT7dependencies: [diffusers>=0.30.0, transformers>=4.41.0, accelerate>=0.31.0, torch>=2.0.0]8platforms: [linux, macos, windows]9metadata:10 hermes:11 tags: [Image Generation, Stable Diffusion, Diffusers, Text-to-Image, Multimodal, Computer Vision]12 13---14 15# Stable Diffusion Image Generation16 17Guide to generating images with Stable Diffusion using the HuggingFace Diffusers library.18 19## When to use Stable Diffusion20 21**Use Stable Diffusion when:**22- Generating images from text descriptions23- Performing image-to-image translation (style transfer, enhancement)24- Inpainting (filling in masked regions)25- Outpainting (extending images beyond boundaries)26- Creating variations of existing images27- Building custom image generation workflows28 29**Key features:**30- **Text-to-Image**: Generate images from natural language prompts31- **Image-to-Image**: Transform existing images with text guidance32- **Inpainting**: Fill masked regions with context-aware content33- **ControlNet**: Add spatial conditioning (edges, poses, depth)34- **LoRA Support**: Efficient fine-tuning and style adaptation35- **Multiple Models**: SD 1.5, SDXL, SD 3.0, Flux support36 37**Use alternatives instead:**38- **DALL-E 3**: For API-based generation without GPU39- **Midjourney**: For artistic, stylized outputs40- **Imagen**: For Google Cloud integration41- **Leonardo.ai**: For web-based creative workflows42 43## Quick start44 45### Installation46 47```bash48pip install diffusers transformers accelerate torch49pip install xformers # Optional: memory-efficient attention50```51 52### Basic text-to-image53 54```python55from diffusers import DiffusionPipeline56import torch57 58# Load pipeline (auto-detects model type)59pipe = DiffusionPipeline.from_pretrained(60 "stable-diffusion-v1-5/stable-diffusion-v1-5",61 torch_dtype=torch.float1662)63pipe.to("cuda")64 65# Generate image66image = pipe(67 "A serene mountain landscape at sunset, highly detailed",68 num_inference_steps=50,69 guidance_scale=7.570).images[0]71 72image.save("output.png")73```74 75### Using SDXL (higher quality)76 77```python78from diffusers import AutoPipelineForText2Image79import torch80 81pipe = AutoPipelineForText2Image.from_pretrained(82 "stabilityai/stable-diffusion-xl-base-1.0",83 torch_dtype=torch.float16,84 variant="fp16"85)86pipe.to("cuda")87 88# Enable memory optimization89pipe.enable_model_cpu_offload()90 91image = pipe(92 prompt="A futuristic city with flying cars, cinematic lighting",93 height=1024,94 width=1024,95 num_inference_steps=3096).images[0]97```98 99## Architecture overview100 101### Three-pillar design102 103Diffusers is built around three core components:104 105```106Pipeline (orchestration)107├── Model (neural networks)108│ ├── UNet / Transformer (noise prediction)109│ ├── VAE (latent encoding/decoding)110│ └── Text Encoder (CLIP/T5)111└── Scheduler (denoising algorithm)112```113 114### Pipeline inference flow115 116```117Text Prompt → Text Encoder → Text Embeddings118 ↓119Random Noise → [Denoising Loop] ← Scheduler120 ↓121 Predicted Noise122 ↓123 VAE Decoder → Final Image124```125 126## Core concepts127 128### Pipelines129 130Pipelines orchestrate complete workflows:131 132| Pipeline | Purpose |133|----------|---------|134| `StableDiffusionPipeline` | Text-to-image (SD 1.x/2.x) |135| `StableDiffusionXLPipeline` | Text-to-image (SDXL) |136| `StableDiffusion3Pipeline` | Text-to-image (SD 3.0) |137| `FluxPipeline` | Text-to-image (Flux models) |138| `StableDiffusionImg2ImgPipeline` | Image-to-image |139| `StableDiffusionInpaintPipeline` | Inpainting |140 141### Schedulers142 143Schedulers control the denoising process:144 145| Scheduler | Steps | Quality | Use Case |146|-----------|-------|---------|----------|147| `EulerDiscreteScheduler` | 20-50 | Good | Default choice |148| `EulerAncestralDiscreteScheduler` | 20-50 | Good | More variation |149| `DPMSolverMultistepScheduler` | 15-25 | Excellent | Fast, high quality |150| `DDIMScheduler` | 50-100 | Good | Deterministic |151| `LCMScheduler` | 4-8 | Good | Very fast |152| `UniPCMultistepScheduler` | 15-25 | Excellent | Fast convergence |153 154### Swapping schedulers155 156```python157from diffusers import DPMSolverMultistepScheduler158 159# Swap for faster generation160pipe.scheduler = DPMSolverMultistepScheduler.from_config(161 pipe.scheduler.config162)163 164# Now generate with fewer steps165image = pipe(prompt, num_inference_steps=20).images[0]166```167 168## Generation parameters169 170### Key parameters171 172| Parameter | Default | Description |173|-----------|---------|-------------|174| `prompt` | Required | Text description of desired image |175| `negative_prompt` | None | What to avoid in the image |176| `num_inference_steps` | 50 | Denoising steps (more = better quality) |177| `guidance_scale` | 7.5 | Prompt adherence (7-12 typical) |178| `height`, `width` | 512/1024 | Output dimensions (multiples of 8) |179| `generator` | None | Torch generator for reproducibility |180| `num_images_per_prompt` | 1 | Batch size |181 182### Reproducible generation183 184```python185import torch186 187generator = torch.Generator(device="cuda").manual_seed(42)188 189image = pipe(190 prompt="A cat wearing a top hat",191 generator=generator,192 num_inference_steps=50193).images[0]194```195 196### Negative prompts197 198```python199image = pipe(200 prompt="Professional photo of a dog in a garden",201 negative_prompt="blurry, low quality, distorted, ugly, bad anatomy",202 guidance_scale=7.5203).images[0]204```205 206## Image-to-image207 208Transform existing images with text guidance:209 210```python211from diffusers import AutoPipelineForImage2Image212from PIL import Image213 214pipe = AutoPipelineForImage2Image.from_pretrained(215 "stable-diffusion-v1-5/stable-diffusion-v1-5",216 torch_dtype=torch.float16217).to("cuda")218 219init_image = Image.open("input.jpg").resize((512, 512))220 221image = pipe(222 prompt="A watercolor painting of the scene",223 image=init_image,224 strength=0.75, # How much to transform (0-1)225 num_inference_steps=50226).images[0]227```228 229## Inpainting230 231Fill masked regions:232 233```python234from diffusers import AutoPipelineForInpainting235from PIL import Image236 237pipe = AutoPipelineForInpainting.from_pretrained(238 "runwayml/stable-diffusion-inpainting",239 torch_dtype=torch.float16240).to("cuda")241 242image = Image.open("photo.jpg")243mask = Image.open("mask.png") # White = inpaint region244 245result = pipe(246 prompt="A red car parked on the street",247 image=image,248 mask_image=mask,249 num_inference_steps=50250).images[0]251```252 253## ControlNet254 255Add spatial conditioning for precise control:256 257```python258from diffusers import StableDiffusionControlNetPipeline, ControlNetModel259import torch260 261# Load ControlNet for edge conditioning262controlnet = ControlNetModel.from_pretrained(263 "lllyasviel/control_v11p_sd15_canny",264 torch_dtype=torch.float16265)266 267pipe = StableDiffusionControlNetPipeline.from_pretrained(268 "stable-diffusion-v1-5/stable-diffusion-v1-5",269 controlnet=controlnet,270 torch_dtype=torch.float16271).to("cuda")272 273# Use Canny edge image as control274control_image = get_canny_image(input_image)275 276image = pipe(277 prompt="A beautiful house in the style of Van Gogh",278 image=control_image,279 num_inference_steps=30280).images[0]281```282 283### Available ControlNets284 285| ControlNet | Input Type | Use Case |286|------------|------------|----------|287| `canny` | Edge maps | Preserve structure |288| `openpose` | Pose skeletons | Human poses |289| `depth` | Depth maps | 3D-aware generation |290| `normal` | Normal maps | Surface details |291| `mlsd` | Line segments | Architectural lines |292| `scribble` | Rough sketches | Sketch-to-image |293 294## LoRA adapters295 296Load fine-tuned style adapters:297 298```python299from diffusers import DiffusionPipeline300 301pipe = DiffusionPipeline.from_pretrained(302 "stable-diffusion-v1-5/stable-diffusion-v1-5",303 torch_dtype=torch.float16304).to("cuda")305 306# Load LoRA weights307pipe.load_lora_weights("path/to/lora", weight_name="style.safetensors")308 309# Generate with LoRA style310image = pipe("A portrait in the trained style").images[0]311 312# Adjust LoRA strength313pipe.fuse_lora(lora_scale=0.8)314 315# Unload LoRA316pipe.unload_lora_weights()317```318 319### Multiple LoRAs320 321```python322# Load multiple LoRAs323pipe.load_lora_weights("lora1", adapter_name="style")324pipe.load_lora_weights("lora2", adapter_name="character")325 326# Set weights for each327pipe.set_adapters(["style", "character"], adapter_weights=[0.7, 0.5])328 329image = pipe("A portrait").images[0]330```331 332## Memory optimization333 334### Enable CPU offloading335 336```python337# Model CPU offload - moves models to CPU when not in use338pipe.enable_model_cpu_offload()339 340# Sequential CPU offload - more aggressive, slower341pipe.enable_sequential_cpu_offload()342```343 344### Attention slicing345 346```python347# Reduce memory by computing attention in chunks348pipe.enable_attention_slicing()349 350# Or specific chunk size351pipe.enable_attention_slicing("max")352```353 354### xFormers memory-efficient attention355 356```python357# Requires xformers package358pipe.enable_xformers_memory_efficient_attention()359```360 361### VAE slicing for large images362 363```python364# Decode latents in tiles for large images365pipe.enable_vae_slicing()366pipe.enable_vae_tiling()367```368 369## Model variants370 371### Loading different precisions372 373```python374# FP16 (recommended for GPU)375pipe = DiffusionPipeline.from_pretrained(376 "model-id",377 torch_dtype=torch.float16,378 variant="fp16"379)380 381# BF16 (better precision, requires Ampere+ GPU)382pipe = DiffusionPipeline.from_pretrained(383 "model-id",384 torch_dtype=torch.bfloat16385)386```387 388### Loading specific components389 390```python391from diffusers import UNet2DConditionModel, AutoencoderKL392 393# Load custom VAE394vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse")395 396# Use with pipeline397pipe = DiffusionPipeline.from_pretrained(398 "stable-diffusion-v1-5/stable-diffusion-v1-5",399 vae=vae,400 torch_dtype=torch.float16401)402```403 404## Batch generation405 406Generate multiple images efficiently:407 408```python409# Multiple prompts410prompts = [411 "A cat playing piano",412 "A dog reading a book",413 "A bird painting a picture"414]415 416images = pipe(prompts, num_inference_steps=30).images417 418# Multiple images per prompt419images = pipe(420 "A beautiful sunset",421 num_images_per_prompt=4,422 num_inference_steps=30423).images424```425 426## Common workflows427 428### Workflow 1: High-quality generation429 430```python431from diffusers import StableDiffusionXLPipeline, DPMSolverMultistepScheduler432import torch433 434# 1. Load SDXL with optimizations435pipe = StableDiffusionXLPipeline.from_pretrained(436 "stabilityai/stable-diffusion-xl-base-1.0",437 torch_dtype=torch.float16,438 variant="fp16"439)440pipe.to("cuda")441pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)442pipe.enable_model_cpu_offload()443 444# 2. Generate with quality settings445image = pipe(446 prompt="A majestic lion in the savanna, golden hour lighting, 8k, detailed fur",447 negative_prompt="blurry, low quality, cartoon, anime, sketch",448 num_inference_steps=30,449 guidance_scale=7.5,450 height=1024,451 width=1024452).images[0]453```454 455### Workflow 2: Fast prototyping456 457```python458from diffusers import AutoPipelineForText2Image, LCMScheduler459import torch460 461# Use LCM for 4-8 step generation462pipe = AutoPipelineForText2Image.from_pretrained(463 "stabilityai/stable-diffusion-xl-base-1.0",464 torch_dtype=torch.float16465).to("cuda")466 467# Load LCM LoRA for fast generation468pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl")469pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)470pipe.fuse_lora()471 472# Generate in ~1 second473image = pipe(474 "A beautiful landscape",475 num_inference_steps=4,476 guidance_scale=1.0477).images[0]478```479 480## Common issues481 482**CUDA out of memory:**483```python484# Enable memory optimizations485pipe.enable_model_cpu_offload()486pipe.enable_attention_slicing()487pipe.enable_vae_slicing()488 489# Or use lower precision490pipe = DiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)491```492 493**Black/noise images:**494```python495# Check VAE configuration496# Use safety checker bypass if needed497pipe.safety_checker = None498 499# Ensure proper dtype consistency500pipe = pipe.to(dtype=torch.float16)501```502 503**Slow generation:**504```python505# Use faster scheduler506from diffusers import DPMSolverMultistepScheduler507pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)508 509# Reduce steps510image = pipe(prompt, num_inference_steps=20).images[0]511```512 513## References514 515- **[Advanced Usage](references/advanced-usage.md)** - Custom pipelines, fine-tuning, deployment516- **[Troubleshooting](references/troubleshooting.md)** - Common issues and solutions517 518## Resources519 520- **Documentation**: https://huggingface.co/docs/diffusers521- **Repository**: https://github.com/huggingface/diffusers522- **Model Hub**: https://huggingface.co/models?library=diffusers523- **Discord**: https://discord.gg/diffusers524 Discovery context
Discovered by repository scan. No exact path reference found in the snapshot’s root AGENTS.md.