Chuyển tới nội dung chính

{/* Trang này được tạo tự động từ SKILL.md của kỹ năng bởi website/scripts/generate-skill-docs.py. Chỉnh sửa nguồn SKILL.md, không phải trang này. */}

Tạo hình ảnh khuếch tán ổn định

Tạo văn bản thành hình ảnh tiên tiến nhất với các mô hình Khuếch tán ổn định thông qua Bộ khuếch tán HuggingFace. Sử dụng khi tạo hình ảnh từ lời nhắc văn bản, thực hiện dịch từ hình ảnh sang hình ảnh, vẽ nội dung hoặc xây dựng quy trình khuếch tán tùy chỉnh.

Siêu dữ liệu kỹ năng

NguồnTùy chọn — cài đặt với
`Hermes skills install official/mlops/stable-diffusion
`
Đường dẫn

optional-skills/mlops/stable-diffusion ` | | Phiên bản |

1.0.0 ` | | Tác giả | Nghiên cứu dàn nhạc | | Giấy phép | MIT | | Phụ thuộc |

diffusers>=0.30.0

, `transformers>=4.41.0

, `accelerate>=0.31.0

, torch>=2.0.0 | | Nền tảng | Linux, macOS, Windows | | Thẻ |

Image Generation

, `Stable Diffusion

, `Diffusers

, `Text-to-Image

, `Multimodal

, Computer Vision |

Tham khảo: đầy đủ SKILL.md

thông tin

Sau đây là định nghĩa kỹ năng đầy đủ mà Hermes tải khi kỹ năng này được kích hoạt. Đây là những gì tác nhân coi là hướng dẫn khi kỹ năng được kích hoạt.

Tạo hình ảnh khuếch tán ổn định

Hướng dẫn toàn diện về cách tạo hình ảnh với Khuếch tán ổn định bằng thư viện HuggingFace Diffusers.

Khi nào nên sử dụng Khuếch tán ổn định`Sử dụng Khuếch tán ổn định khi:

  • Tạo hình ảnh từ mô tả văn bản
  • Thực hiện dịch từ ảnh sang ảnh (chuyển style, nâng cao)
  • Inpainting (điền vào các vùng bị che)
  • Outpainting (mở rộng hình ảnh vượt ra ngoài ranh giới)
  • Tạo các biến thể của hình ảnh hiện có
  • Xây dựng quy trình tạo hình ảnh tùy chỉnh`Các tính năng chính:
  • Chuyển văn bản thành hình ảnh: Tạo hình ảnh từ lời nhắc bằng ngôn ngữ tự nhiên
  • Chuyển hình ảnh thành hình ảnh: Chuyển đổi hình ảnh hiện có bằng hướng dẫn văn bản
  • Inpainting: Lấp đầy các vùng bị che bằng nội dung nhận biết ngữ cảnh
  • ControlNet: Thêm điều hòa không gian (cạnh, tư thế, độ sâu)
  • Hỗ trợ LoRA: Tinh chỉnh hiệu quả và thích ứng phong cách
  • Nhiều mẫu: SD 1.5, SDXL, SD 3.0, hỗ trợ Flux`Sử dụng các lựa chọn thay thế thay thế:
  • DALL-E 3: Dành cho thế hệ dựa trên API không có GPU
  • Giữa hành trình: Dành cho kết quả mang tính nghệ thuật, cách điệu
  • Imagen: Để tích hợp Google Cloud
  • Leonardo.ai: Dành cho quy trình làm việc sáng tạo dựa trên web

Bắt đầu nhanh

Cài đặt

pip install diffusers transformers accelerate torch
pip install xformers # Optional: memory-efficient attention

`

### Chuyển văn bản thành hình ảnh cơ bản

`Python
from diffusers import Diffusionpipeline
import torch

# Load pipeline (auto-detects model type)
pipe = Diffusionpipeline.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5",
torch_dtype=torch.float16
)
pipe.to("cuda")

# Generate image
image = pipe(
"A serene mountain landscape at sunset, highly detailed",
num_inference_steps=50,
guidance_scale=7.5
).images[0]

image.save("output.png")

`

### Sử dụng SDXL (chất lượng cao hơn)

`Python
from diffusers import AutopipelineForText2Image
import torch`pipe = AutopipelineForText2Image.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
torch_dtype=torch.float16,
variant="fp16"
)
pipe.to("cuda")

# Enable memory optimization
pipe.enable_model_cpu_offload()

image = pipe(
prompt="A futuristic city with flying cars, cinematic lighting",
height=1024,
width=1024,
num_inference_steps=30
).images[0]

`

## Tổng quan về kiến trúc`###Thiết kế ba trụ

Bộ khuếch tán được xây dựng xung quanh ba thành phần cốt lõi:`<!-- ascii-guard-ignore -->

`

pipeline (orchestration)
├── Model (neural networks)
│ ├── UNet / Transformer (noise prediction)
│ ├── VAE (latent encoding/decoding)
│ └── Text Encoder (CLIP/T5)
└── Scheduler (denoising algorithm)

`

<!-- ascii-guard-ignore-end -->

### Luồng suy luận đường ống

`
Text Prompt → Text Encoder → Text Embeddings

Random Noise → [Denoising Loop] ← Scheduler

Predicted Noise

VAE Decoder → Final Image

`

## Khái niệm cốt lõi

### Đường ống

Các quy trình sắp xếp các quy trình công việc hoàn chỉnh:

| Đường ống | Mục đích |
|----------|----------|
|
`StableDiffusionpipeline
` | Chuyển văn bản thành hình ảnh (SD 1.x/2.x) |
|
`StableDiffusionXLpipeline
` | Chuyển văn bản thành hình ảnh (SDXL) |
|
`StableDiffusion3pipeline
` | Chuyển văn bản thành hình ảnh (SD 3.0) |
|
`Fluxpipeline
` | Chuyển văn bản thành hình ảnh (Mô hình thông lượng) |
|
`StableDiffusionImg2Imgpipeline
` | Hình ảnh thành hình ảnh |
|
`StableDiffusionInpaintpipeline
` | Sơn trong |

### Bộ lập lịch

Bộ lập lịch kiểm soát quá trình khử nhiễu:

| Lập lịch | Bước | Chất lượng | Trường hợp sử dụng |
|----------|-------|---------|----------|
|
`EulerDiscreteScheduler
` | 20-50 | Tốt | Lựa chọn mặc định |
|
`EulerAncestralDiscreteScheduler
` | 20-50 | Tốt | Nhiều biến thể hơn |
|
`DPMSolverMultistepScheduler
` | 15-25 | Xuất sắc | Nhanh chóng, chất lượng cao |
|
`DDIMScheduler
` | 50-100 | Tốt | Xác định |
|
`LCMScheduler
` | 4-8 | Tốt | Rất nhanh |
|
`UniPCMultistepScheduler
` | 15-25 | Xuất sắc | Hội tụ nhanh |

### Hoán đổi bộ lập lịch

`Python
from diffusers import DPMSolverMultistepScheduler

# Swap for faster generation
pipe.scheduler = DPMSolverMultistepScheduler.from_config(
pipe.scheduler.config
)

# Now generate with fewer steps
image = pipe(prompt, num_inference_steps=20).images[0]

`

## Thông số thế hệ

### Thông số chính

| Tham số | Mặc định | Mô tả |
|----------||----------|-------------|
|
`prompt
` | Bắt buộc | Mô tả văn bản của hình ảnh mong muốn |
|
`negative_prompt
` | Không có | Những điều cần tránh trong ảnh |
|
`num_inference_steps
` | 50 | Các bước khử nhiễu (nhiều hơn = chất lượng tốt hơn) |
|
`guidance_scale
` | 7,5 | Tuân thủ nhanh chóng (điển hình là 7-12) |
|
`height

,
`width
` | 512/1024 | Kích thước đầu ra (bội số của 8) |
|
`generator
` | Không có | Máy phát điện ngọn đuốc để tái tạo |
|
`num_images_per_prompt
` | 1 | Kích thước lô |

### Thế hệ có thể tái tạo

`Python
import torch`generator = torch.Generator(device="cuda").manual_seed(42)

image = pipe(
prompt="A cat wearing a top hat",
generator=generator,
num_inference_steps=50
).images[0]

`

### Lời nhắc tiêu cực

`Python
image = pipe(
prompt="Professional photo of a dog in a garden",
negative_prompt="blurry, low quality, distorted, ugly, bad anatomy",
guidance_scale=7.5
).images[0]

`

## Chuyển hình ảnh sang hình ảnh

Chuyển đổi hình ảnh hiện có bằng văn bản hướng dẫn:

`Python
from diffusers import AutopipelineForImage2Image
from PIL import Image`pipe = AutopipelineForImage2Image.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5",
torch_dtype=torch.float16
).to("cuda")

init_image = Image.open("input.jpg").resize((512, 512))

image = pipe(
prompt="A watercolor painting of the scene",
image=init_image,
strength=0.75, # How much to transform (0-1)
num_inference_steps=50
).images[0]

`

## Sơn nội bộ

Điền vào các vùng bị che:

`Python
from diffusers import AutopipelineForInpainting
from PIL import Image`pipe = AutopipelineForInpainting.from_pretrained(
"runwayml/stable-diffusion-inpainting",
torch_dtype=torch.float16
).to("cuda")

image = Image.open("photo.jpg")
mask = Image.open("mask.png") # White = inpaint region`result = pipe(
prompt="A red car parked on the street",
image=image,
mask_image=mask,
num_inference_steps=50
).images[0]

`

## Mạng điều khiểnThêm điều hòa không gian để kiểm soát chính xác:

`Python
from diffusers import StableDiffusionControlNetpipeline, ControlNetModel
import torch

# Load ControlNet for edge conditioning
controlnet = ControlNetModel.from_pretrained(
"lllyasviel/control_v11p_sd15_canny",
torch_dtype=torch.float16
)

pipe = StableDiffusionControlNetpipeline.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5",
controlnet=controlnet,
torch_dtype=torch.float16
).to("cuda")

# Use Canny edge image as control
control_image = get_canny_image(input_image)

image = pipe(
prompt="A beautiful house in the style of Van Gogh",
image=control_image,
num_inference_steps=30
).images[0]

`

### Mạng điều khiển có sẵn

| ControlNet | Loại đầu vào | Trường hợp sử dụng |
|----------||-------------|----------|
|
`canny
` | Bản đồ cạnh | Bảo tồn cấu trúc |
|
`openpose
` | Tạo dáng bộ xương | Tư thế con người |
|
`depth
` | Bản đồ độ sâu | Thế hệ nhận biết 3D |
|
`normal
` | Bản đồ thông thường | Chi tiết bề mặt |
|
`mlsd
` | Đoạn đường | Đường nét kiến ​​trúc |
|
`scribble
` | Bản phác thảo thô | Phác thảo thành hình ảnh |

## Bộ điều hợp LoRA

Tải bộ điều hợp kiểu tinh chỉnh:

`Python
from diffusers import Diffusionpipeline`pipe = Diffusionpipeline.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5",
torch_dtype=torch.float16
).to("cuda")

# Load LoRA weights
pipe.load_lora_weights("path/to/lora", weight_name="style.safetensors")

# Generate with LoRA style
image = pipe("A portrait in the trained style").images[0]

# Adjust LoRA strength
pipe.fuse_lora(lora_scale=0.8)

# Unload LoRA
pipe.unload_lora_weights()

`

### Nhiều LoRA

`Python

# Load multiple LoRAs
pipe.load_lora_weights("lora1", adapter_name="style")
pipe.load_lora_weights("lora2", adapter_name="character")

# Set weights for each
pipe.set_adapters(["style", "character"], adapter_weights=[0.7, 0.5])

image = pipe("A portrait").images[0]

`

## Tối ưu hóa bộ nhớ

### Kích hoạt tính năng giảm tải CPU

``` python

# Model CPU offload - moves models to CPU when not in use
pipe.enable_model_cpu_offload()

# Sequential CPU offload - more aggressive, slower
pipe.enable_sequential_cpu_offload()

`

### Cắt sự chú ý

``` python

# Reduce memory by computing attention in chunks
pipe.enable_attention_slicing()

# Or specific chunk size
pipe.enable_attention_slicing("max")

`

### xFormers chú ý tiết kiệm bộ nhớ

``` python

# Requires xformers package
pipe.enable_xformers_memory_efficient_attention()

`

### Cắt VAE cho hình ảnh lớn

``` python

# Decode latents in tiles for large images
pipe.enable_vae_slicing()
pipe.enable_vae_tiling()

`

## Các biến thể của mô hình

### Đang tải các độ chính xác khác nhau

``` python

# FP16 (recommended for GPU)
pipe = Diffusionpipeline.from_pretrained(
"model-id",
torch_dtype=torch.float16,
variant="fp16"
)

# BF16 (better precision, requires Ampere+ GPU)
pipe = Diffusionpipeline.from_pretrained(
"model-id",
torch_dtype=torch.bfloat16
)

`

### Đang tải các thành phần cụ thể

``` python
from diffusers import UNet2DConditionModel, AutoencoderKL

# Load custom VAE
vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse")

# Use with pipeline
pipe = Diffusionpipeline.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5",
vae=vae,
torch_dtype=torch.float16
)

`

## Tạo hàng loạt

Tạo nhiều hình ảnh một cách hiệu quả:

`Python

# Multiple prompts
prompts = [
"A cat playing piano",
"A dog reading a book",
"A bird painting a picture"
]

images = pipe(prompts, num_inference_steps=30).images

# Multiple images per prompt
images = pipe(
"A beautiful sunset",
num_images_per_prompt=4,
num_inference_steps=30
).images

`

## Quy trình công việc chung

### Quy trình 1: Tạo chất lượng cao

``` python
from diffusers import StableDiffusionXLpipeline, DPMSolverMultistepScheduler
import torch

# 1. Load SDXL with optimizations
pipe = StableDiffusionXLpipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
torch_dtype=torch.float16,
variant="fp16"
)
pipe.to("cuda")
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
pipe.enable_model_cpu_offload()

# 2. Generate with quality settings
image = pipe(
prompt="A majestic lion in the savanna, golden hour lighting, 8k, detailed fur",
negative_prompt="blurry, low quality, cartoon, anime, sketch",
num_inference_steps=30,
guidance_scale=7.5,
height=1024,
width=1024
).images[0]

`

### Quy trình 2: Tạo nguyên mẫu nhanh

`Python
from diffusers import AutopipelineForText2Image, LCMScheduler
import torch

# Use LCM for 4-8 step generation
pipe = AutopipelineForText2Image.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
torch_dtype=torch.float16
).to("cuda")

# Load LCM LoRA for fast generation
pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl")
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
pipe.fuse_lora()

# Generate in ~1 second
image = pipe(
"A beautiful landscape",
num_inference_steps=4,
guidance_scale=1.0
).images[0]

`

## Các vấn đề thường gặp`**CUDA hết bộ nhớ:**

`
`Python

# Enable memory optimizations
pipe.enable_model_cpu_offload()
pipe.enable_attention_slicing()
pipe.enable_vae_slicing()

# Or use lower precision
pipe = Diffusionpipeline.from_pretrained(model_id, torch_dtype=torch.float16)

`
``**Hình ảnh đen/nhiễu:**

`
``` python

# Check VAE configuration
# Use safety checker bypass if needed
pipe.safety_checker = None

# Ensure proper dtype consistency
pipe = pipe.to(dtype=torch.float16)

`
``**Thế hệ chậm:**

`
``` python

# Use faster scheduler
from diffusers import DPMSolverMultistepScheduler
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)

# Reduce steps
image = pipe(prompt, num_inference_steps=20).images[0]

`

## Tài liệu tham khảo
- **[Advanced Usage](https://GitHub.com/NousResearch/Hermes-agent/blob/main/optional-skills/mlops/stable-diffusion/references/advanced-usage.md)** - Đường ống tùy chỉnh, tinh chỉnh, triển khai
- **[Troubleshooting](https://GitHub.com/NousResearch/Hermes-agent/blob/main/optional-skills/mlops/stable-diffusion/references/troubleshooting.md)** - Các vấn đề thường gặp và giải pháp

## Tài nguyên
- **Tài liệu**: https://huggingface.co/docs/diffusers
- **Kho lưu trữ**: https://GitHub.com/huggingface/diffusers
- **Trung tâm mô hình**: https://huggingface.co/models?library=diffusers
- **Discord**: https://Discord.gg/diffusers