[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,66 +2,186 @@
id: wiki-2026-0508-샘플링-스텝-sampling-steps
title: 샘플링 스텝 (Sampling Steps)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Sampling Steps, Diffusion Steps, Inference Steps, num_inference_steps]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [diffusion, sampling, sdxl, flux, inference, image-generation]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: python
framework: diffusers/ComfyUI
---
# [[샘플링 스텝 (Sampling Steps)|샘플링 스텝 (Sampling Steps)]]
# 샘플링 스텝 (Sampling Steps)
## 📌 한 줄 통찰 (The Karpathy Summary)
샘플링 스텝(Sampling Steps)은 스테이블 디퓨전(Stable Diffusion)과 같은 디퓨전 모델 기반의 AI 이미지 생성기에서 무작위 노이즈를 점진적으로 제거하여 이미지를 완성해 나가는 반복적인 연산 단계를 의미합니다[1, 2]. 사용자는 이 매개변수를 직접 조정하여 결과물의 가변성(variability)을 제어할 수 있습니다[2]. CFG 스케일(CFG scale)과 함께 조합하여 미세 조정(fine-tuning)함으로써 이미지의 사실감과 품질을 향상시키는 핵심적인 역할을 수행합니다[3].
## 한 줄
> **"매 step 은 noise → image 의 길 위 의 한 발자국"**. 매 diffusion model 에서 `num_inference_steps` 는 매 reverse-diffusion ODE 의 discretization count — 매 적으면 빠르지만 muddy, 매 많으면 sharp 지만 expensive 하고 어느 임계점 이상 은 의미 X. 매 2026 의 modern sampler (DPM++ 2M Karras, FLUX 의 Euler) + Lightning/Turbo distillation 으로 매 sweet-spot 이 1230 steps 로 안정.
## 📖 구조화된 지식 (Synthesized Content)
* **디퓨전 모델의 디노이징 과정:** 디퓨전 모델을 통한 이미지 생성은 무작위 노이즈(random noise) 상태에서 출발합니다[1]. 이후 모델이 학습한 디노이징(denoising) 단계를 반복적(iteratively)으로 적용하여 노이즈를 일관성 있는 형태의 결과물로 변환해 나가는 과정을 거치게 되며, 이 각각의 단계가 샘플링 스텝에 해당합니다[1].
* **출력의 가변성 및 품질 제어:** 스테이블 디퓨전 사용자는 프롬프트 외에도 '샘플링 스텝'과 'CFG 스케일(Classifier-Free Guidance Scale)'을 조정하여 생성되는 출력물에 다양성을 부여할 수 있습니다[2].
* **사실성(Realism) 향상을 위한 미세 조정:** AI가 생성한 예술 작품의 사실감을 높이기 위해서는 프롬프트의 개선뿐만 아니라 샘플링 스텝과 같은 매개변수들의 세밀한 조정(fine-tuning)이 동반되어야 합니다[3].
## 매 핵심
*(※ 소스에 샘플링 스텝 수(예: 20스텝과 50스텝의 차이)에 따른 구체적인 결과 변화나, 특정 샘플러(Sampler)의 종류 등에 대한 상세한 기술적 관련 정보가 부족합니다.)*
### 매 정의
- **Sampling step**: 매 reverse diffusion 의 한 iteration. matrix t = T → 0 의 discretization.
- **Sampler / scheduler**: 매 step 사이 noise 의 schedule + 알고리즘 (Euler, DPM, UniPC, LMS, DDIM, DPM++ SDE).
- **CFG (guidance scale)**: 매 step 마다 conditional vs unconditional 의 weighting.
- **Sigma schedule**: 매 noise level 의 t-vs-sigma curve (linear, karras, exponential).
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[스테이블 디퓨전 (Stable Diffusion)|스테이블 디퓨전 (Stable Diffusion)]], [[CFG 스케일 (CFG Scale)|CFG 스케일 (CFG Scale)]], [[디퓨전 모델 (Diffusion Models)|디퓨전 모델 (Diffusion Models)]]
- **Projects/Contexts:** 이미지 생성 매개변수 미세 조정 (Fine-tuning image generation parameters)
- **Contradictions/Notes:** 소스에서는 샘플링 스텝이 이미지의 가변성과 사실성 향상에 기여한다는 점과 디노이징 단계라는 작동 원리만 간략히 언급되어 있으며, 스텝 수치에 따른 구체적인 차이나 알고리즘에 대한 깊이 있는 정보는 부족합니다.
### 매 sampler family (2026 state)
- **Euler / Euler a**: 매 simple, fast, good baseline (1525).
- **DPM++ 2M Karras**: 매 SDXL community default (2030). 매 quality leader 의 하나.
- **DPM++ 3M SDE**: 매 detail 강함 (2840).
- **UniPC**: 매 빠른 convergence (1020).
- **DDIM**: 매 deterministic, ControlNet 호환.
- **LCM / Turbo / Lightning**: 매 distilled 18 steps.
- **FLUX 의 Euler / fm_euler**: 매 flow-matching 형식. 매 2530 steps default.
---
*Last updated: 2026-04-30*
### 매 step 수 의 trade-off
- 매 510: muddy, oversmooth (distilled 모델 의 경우 ok).
- 매 1520: 매 production sweet spot (대부분 SDXL / FLUX dev).
- 매 2530: 매 detail-critical scene.
- 매 40+: 매 returns diminishing. 매 거의 무의미.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용 의 결정 요인
1. Latency budget (real-time vs batch).
2. Sampler 의 스타일 (Karras vs exponential).
3. Distillation 의 사용 여부.
4. ControlNet / IP-Adapter 의 noise floor.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Pattern 1 — diffusers basic
```python
from diffusers import StableDiffusionXLPipeline, DPMSolverMultistepScheduler
import torch
## 🧪 검증 상태 (Validation)
pipe = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipe.scheduler = DPMSolverMultistepScheduler.from_config(
pipe.scheduler.config, algorithm_type="dpmsolver++", use_karras_sigmas=True
)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
img = pipe(prompt="cinematic portrait, dramatic light",
num_inference_steps=25, guidance_scale=6.5).images[0]
```
## 🧬 중복 검사 (Duplicate Check)
### Pattern 2 — Turbo / Lightning (low-step)
```python
from diffusers import StableDiffusionXLPipeline, EulerDiscreteScheduler
pipe = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16"
).to("cuda")
pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
img = pipe(prompt="a wizard casting a fireball",
num_inference_steps=4, guidance_scale=0.0).images[0]
```
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
### Pattern 3 — FLUX (flow-matching)
```python
from diffusers import FluxPipeline
pipe = FluxPipeline.from_pretrained(
"black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16
).to("cuda")
img = pipe(prompt="forest stream at golden hour",
num_inference_steps=28, guidance_scale=3.5,
max_sequence_length=512).images[0]
```
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
### Pattern 4 — UniPC (fast convergence)
```python
from diffusers import UniPCMultistepScheduler
pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
img = pipe(prompt="..", num_inference_steps=12, guidance_scale=6.0).images[0]
```
## 🕓 변경 이력 (Changelog)
### Pattern 5 — sweep test
```python
import os, time
prompts = ["a stoic samurai standing in falling snow"]
for steps in (8, 12, 16, 20, 25, 30, 40):
t0 = time.time()
out = pipe(prompt=prompts[0], num_inference_steps=steps,
guidance_scale=6.5, generator=torch.Generator("cuda").manual_seed(42)).images[0]
out.save(f"sweep_{steps:02d}.png")
print(f"steps={steps} time={time.time()-t0:.2f}s")
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Pattern 6 — Karras sigmas custom
```python
import torch
def karras_sigmas(n, sigma_min=0.029, sigma_max=14.6, rho=7.0):
ramp = torch.linspace(0, 1, n)
min_inv = sigma_min ** (1/rho); max_inv = sigma_max ** (1/rho)
return (max_inv + ramp * (min_inv - max_inv)) ** rho
sigmas = karras_sigmas(20).to("cuda")
pipe.scheduler.set_timesteps(sigmas=sigmas)
```
### Pattern 7 — ControlNet 의 step 협응
```python
# ControlNet 의 conditioning step 시작/종료 비율
img = pipe(prompt=p, image=control_img, num_inference_steps=25,
controlnet_conditioning_scale=0.9,
control_guidance_start=0.0, # 첫 step 부터
control_guidance_end=0.7 # 70% 지점 에서 중단 → free 마지막 30%
).images[0]
```
### Pattern 8 — early-exit (latent preview)
```python
# Inspect mid-process latent
def callback(pipe, step, timestep, callback_kwargs):
if step == 5:
latents = callback_kwargs["latents"]
# decode preview, show, etc.
return callback_kwargs
pipe(prompt=p, num_inference_steps=20,
callback_on_step_end=callback,
callback_on_step_end_tensor_inputs=["latents"])
```
## 매 결정 기준
| 상황 | Steps | Sampler |
|---|---|---|
| SDXL turbo / lightning | 14 | Euler |
| LCM | 48 | LCM |
| SDXL 일반 | 2028 | DPM++ 2M Karras |
| SDXL detail-critical | 2835 | DPM++ 3M SDE |
| FLUX dev | 2530 | flow-match Euler |
| FLUX schnell (distilled) | 4 | Euler |
| ControlNet inpaint | 2530 | DPM++ / UniPC |
**기본값**: 매 SDXL → 25 steps DPM++ 2M Karras CFG 6.5. 매 FLUX dev → 28 steps CFG 3.5.
## 🔗 Graph
- 부모: [[Stable Diffusion]] · [[Diffusion Models]]
- 변형: [[CFG 스케일(Classifier-Free Guidance Scale)]] · [[Schedulers]]
- 응용: [[AI 이미지 생성 (AI Image Generation)]] · [[사후 편집 (Post-editing)]]
- Adjacent: [[FLUX]] · [[ComfyUI]] · [[LCM]]
## 🤖 LLM 활용
**언제**: 매 sweep config 의 generation, 매 sampler comparison table 의 작성.
**언제 X**: 매 visual quality 의 final judge — 매 image grid 의 inspection 이 필요.
## ❌ 안티패턴
- **Steps 100**: 매 cost 4× 의 quality gain 거의 0.
- **Distilled model + high steps**: 매 SDXL Turbo 의 30 step → 매 over-burn.
- **Sampler 의 random pick**: 매 prompt-sampler interaction 의 무시.
- **CFG + steps 의 단독 변경**: 매 둘은 결합 — 매 high CFG → 매 더 많은 step 필요.
## 🧪 검증 / 중복
- Verified (k-diffusion repo, diffusers schedulers docs, ComfyUI manager).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — sampler family + step decision matrix |