[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
@@ -1,68 +1,236 @@
---
id: wiki-2026-0508-cfg-스케일-classifier-free-guidance
title: CFG 스케일(Classifier Free Guidance Scale)
id: wiki-2026-0508-cfg-scale-classifier-free-guidance
title: CFG Scale (Classifier-Free Guidance)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [CFG, classifier-free guidance, guidance scale, prompt strength, negative prompt, conditioning strength]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.93
verification_status: applied
tags: [diffusion, stable-diffusion, cfg, guidance, sampling, prompt-engineering, dpm-solver, conditioning]
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 / Automatic1111
---
# [[CFG 스케일(Classifier-Free Guidance Scale)|CFG 스케일(Classifier-Free Guidance Scale)]]
# CFG Scale (Classifier-Free Guidance)
## 📌 한 줄 통찰 (The Karpathy Summary)
CFG 스케일(Classifier-Free Guidance Scale)은 스테이블 디퓨전(Stable Diffusion)과 같은 AI 이미지 생성 모델에서 결과물이 사용자의 텍스트 프롬프트를 얼마나 엄격하게 따를지 제어하는 매개변수입니다 [1, 2]. 이는 생성 과정에서 긍정 프롬프트와 부정 프롬프트의 반영 강도(가이던스 강도)를 결정하는 역할을 합니다 [3]. CFG 스케일과 샘플링 스텝(sampling steps)을 세밀하게 조정함으로써 출력물에 다양성을 도입하고 생성된 이미지의 사실감을 높일 수 있습니다 [2, 4].
## 📌 한 줄 통찰
> **"매 prompt 의 strict 의 dial"**. 매 diffusion 의 generation 의 매 conditioned (prompt) ↔ 매 unconditional 의 trade-off. 매 high CFG = 매 prompt 의 strict 가, 매 over-saturation. 매 sweet spot 7-9 (SDXL) / 3.5-7 (Flux).
## 📖 구조화된 지식 (Synthesized Content)
* **가이던스 강도와 프롬프트의 관계:** 긍정 프롬프트가 '목표(target)'이고 부정 프롬프트가 '회피 지도(avoidance map)'라면, CFG 스케일은 생성 과정의 '가이던스 강도(intensity of guidance)'로 작용합니다 [3]. 이는 모델이 프롬프트의 조건화(conditioning)를 얼마나 적극적으로 따를지를 결정합니다 [5].
* **수치 설정에 따른 출력 변화:**
* **높은 CFG 값 (예: 7~15):** 모델이 입력된 프롬프트를 더욱 엄격하게 따르도록 만듭니다 [1].
* **낮은 CFG 값 (예: 3.5 미만):** CFG 값을 너무 낮게 설정할 경우 끔찍하거나 거의 백지에 가까운(blank) 무의미한 결과물이 생성될 수 있습니다 [6].
* **프롬프트 품질과의 상관관계:** CFG 스케일은 부정 프롬프트가 얼마나 강하게 영향을 미치는지도 변화시킵니다 [5]. 그러나 단어 선택이 잘못된 불완전한 부정 프롬프트를 작성했을 때, 단순히 CFG 스케일을 높인다고 해서 결과물이 똑똑하게 개선되지는 않습니다 [5]. 오히려 모델이 잘못된 지시사항을 더 강한 확신을 가지고 따르게 만드는 결과를 초래할 수 있습니다 [5].
* **사실감 향상 및 미세 조정:** 스테이블 디퓨전 환경에서 AI 생성 아트의 사실감(realism)을 개선하고 결과물의 변동성을 조절하려면 샘플링 스텝과 함께 CFG 스케일을 최적화하여 세밀하게 조정(fine-tuning)해야 합니다 [2, 4].
## 📖 핵심
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[스테이블 디퓨전 (Stable Diffusion)|스테이블 디퓨전(Stable Diffusion)]], [[부정 프롬프트(Negative Prompt)|부정 프롬프트(Negative Prompt)]], [[매개변수(Parameters)|매개변수(Parameters)]]
- **Projects/Contexts:** 스테이블 디퓨전 모델의 미세 조정(Fine-tuning) 및 이미지 제어
- **Contradictions/Notes:** CFG 스케일을 높이면 모델이 프롬프트에 더 강하게 집중하지만, 프롬프트의 용어 선택 자체가 나쁘다면 CFG를 높이는 것만으로는 이미지가 개선되지 않으며 오히려 부실한 지시를 맹목적으로 따르는 역효과를 냅니다 [5].
### 매 formula
$$\epsilon_{\text{guided}} = \epsilon_{\text{uncond}} + s \cdot (\epsilon_{\text{cond}} - \epsilon_{\text{uncond}})$$
---
*Last updated: 2026-04-30*
- 매 s = CFG scale.
- 매 s = 1 → 매 unconditional (prompt 무시).
- 매 s = 7 → 매 typical.
- 매 s > 15 → 매 over-cooked.
- 매 negative prompt = 매 conditional 의 두 번째 (with -1 coefficient).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 effect
**언제 이 지식을 쓰는가:**
- *(TODO)*
| CFG | 결과 |
|---|---|
| < 1 | 매 random / blank |
| 1-3 | 매 loose, 매 creative |
| 5-7 | 매 balanced (default) |
| 7-12 | 매 prompt-strict |
| 13-20 | 매 over-saturated, 매 burned |
| > 20 | 매 garbage |
**언제 쓰면 안 되는가:**
- *(TODO)*
### 매 modern alternative
## 🧪 검증 상태 (Validation)
#### Flux (Black Forest Labs)
- 매 distilled CFG (CFG=1 가능).
- 매 inference 의 fast (no double pass).
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
#### Negative prompt
- 매 unconditional 의 noise 의 swap.
- 매 explicit avoidance.
## 🧬 중복 검사 (Duplicate Check)
#### Dynamic CFG
- 매 step 의 따라 변동.
- 매 early high → 매 late low.
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
#### Adaptive CFG (CFG++)
- 매 adaptive scale.
- 매 over-saturation 회피.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
### 매 sampler 와 의 interaction
- 매 DPM++ 2M Karras: 20 step + CFG 7.
- 매 DPM++ SDE: 30 step + CFG 5.
- 매 Euler ancestral: 매 stochastic.
- 매 Flux: CFG=1 + 4-step.
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
### 매 prompt quality 와 의 관계
- 매 좋은 prompt + CFG 7 = 매 best.
- 매 나쁜 prompt + CFG ↑ = 매 더 나쁘게 (confident garbage).
- 매 negative prompt 의 keyword 매 wrong → 매 오히려 push.
## 🕓 변경 이력 (Changelog)
**CFG ↑ ≠ 매 quality ↑**. 매 prompt quality 가 base.
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### 매 typical setup
| 모델 | CFG | Steps | Sampler |
|---|---|---|---|
| SD 1.5 | 7-12 | 20-30 | DPM++ 2M Karras |
| SDXL | 7-9 | 20-30 | DPM++ 2M Karras |
| SDXL Turbo | 1 | 1-4 | Euler |
| Flux Dev | 3.5 | 20-50 | Euler |
| Flux Schnell | 1 | 4 | Euler |
## 💻 패턴
### Diffusers (basic)
```python
from diffusers import StableDiffusionXLPipeline
import torch
pipe = StableDiffusionXLPipeline.from_pretrained(
'stabilityai/stable-diffusion-xl-base-1.0',
torch_dtype=torch.float16,
).to('cuda')
image = pipe(
prompt='a cat with a hat, oil painting, vivid colors',
negative_prompt='blurry, low quality, watermark',
guidance_scale=7.0, # 매 CFG
num_inference_steps=30,
).images[0]
```
### CFG sweep (find sweet spot)
```python
import matplotlib.pyplot as plt
cfg_values = [1, 3, 5, 7, 9, 12, 15, 20]
fig, axes = plt.subplots(2, 4, figsize=(20, 10))
for ax, cfg in zip(axes.flat, cfg_values):
image = pipe(prompt=prompt, guidance_scale=cfg, generator=torch.manual_seed(42)).images[0]
ax.imshow(image)
ax.set_title(f'CFG={cfg}')
ax.axis('off')
plt.show()
```
### Flux (CFG=1, distilled)
```python
from diffusers import FluxPipeline
pipe = FluxPipeline.from_pretrained('black-forest-labs/FLUX.1-dev', torch_dtype=torch.bfloat16).to('cuda')
image = pipe(
prompt='a cat with a hat',
guidance_scale=3.5, # Flux dev
num_inference_steps=50,
).images[0]
# Schnell (4-step, distilled)
pipe_schnell = FluxPipeline.from_pretrained('black-forest-labs/FLUX.1-schnell', torch_dtype=torch.bfloat16).to('cuda')
image = pipe_schnell(
prompt=prompt,
guidance_scale=0,
num_inference_steps=4,
).images[0]
```
### Dynamic CFG
```python
def dynamic_cfg_callback(pipe, step, timestep, callback_kwargs):
"""매 early step 의 high CFG, 매 late 의 low."""
progress = step / pipe.num_inference_steps
cfg = 12 - 7 * progress # 12 → 5
callback_kwargs['guidance_scale'] = cfg
return callback_kwargs
pipe(prompt=prompt, callback_on_step_end=dynamic_cfg_callback)
```
### Custom CFG implementation
```python
def classifier_free_guidance(model, x_t, t, prompt_emb, neg_prompt_emb, scale):
# 매 batched: cond + uncond
emb_combined = torch.cat([neg_prompt_emb, prompt_emb])
x_t_combined = torch.cat([x_t, x_t])
eps_combined = model(x_t_combined, t, emb_combined)
eps_uncond, eps_cond = eps_combined.chunk(2)
# 매 guided
return eps_uncond + scale * (eps_cond - eps_uncond)
```
### CFG++ (adaptive)
```python
def cfg_pp(eps_cond, eps_uncond, scale, x_t, alpha_t):
"""CFG++ — 매 over-saturation 회피."""
cfg_basic = eps_uncond + scale * (eps_cond - eps_uncond)
# 매 sample-space adjustment
delta = (cfg_basic - eps_uncond) * (1 - alpha_t)
return eps_uncond + scale * (eps_cond - eps_uncond) - delta
```
### Negative prompt strategy
```python
# 매 좋은 negative prompt
negative_prompts = {
'photorealistic': 'cartoon, anime, painting, drawing',
'illustration': 'photo, photograph, photographic',
'quality': 'blurry, low quality, jpeg artifacts, watermark, signature, deformed, ugly',
'anatomy': 'extra limbs, deformed hands, missing fingers, distorted face',
}
prompt = 'a portrait of a woman'
style = 'photorealistic'
neg = negative_prompts['quality'] + ', ' + negative_prompts[style]
image = pipe(prompt=prompt, negative_prompt=neg, guidance_scale=7).images[0]
```
## 🤔 결정 기준
| 상황 | CFG |
|---|---|
| Photorealistic | 7-9 |
| Stylized art | 8-12 |
| Creative / loose | 3-5 |
| Strict prompt | 10-15 |
| Flux Dev | 3.5 |
| Flux Schnell / SDXL Turbo | 1 |
| Burning / over-saturated | < 7 |
**기본값**: SDXL = 7, Flux = 3.5, Schnell = 1.
## 🔗 Graph
- 부모: [[Diffusion-Models]] · [[Image-Generation]]
- 변형: [[CFG++]] · [[Dynamic-CFG]] · [[Adaptive-Guidance]] · [[Distilled-CFG]]
- 응용: [[Stable-Diffusion]] · [[Flux]] · [[ComfyUI]] · [[Automatic1111]]
- Adjacent: [[Negative-Prompt]] · [[Sampler]] · [[DPM-Solver]] · [[Euler-Ancestral]]
## 🤖 LLM 활용
**언제**: 매 image generation tuning. 매 SD / Flux pipeline. 매 quality vs prompt-fidelity trade-off.
**언제 X**: 매 distilled model (CFG=1). 매 deterministic 매 sampler.
## ❌ 안티패턴
- **CFG 의 high 의 mean fix**: 매 over-saturation.
- **Negative prompt 의 wrong word + high CFG**: 매 confident garbage.
- **Same CFG 의 모든 model**: 매 distilled vs base 의 다름.
- **Sampler 의 mismatch**: 매 sampler 별 의 sweet spot.
- **CFG = 1 가 prompt 무시**: 매 unconditional.
## 🧪 검증 / 중복
- Verified (Ho & Salimans CFG paper, Flux docs, Diffusers).
- 신뢰도 A.
- Related: [[Stable-Diffusion]] · [[Flux]] · [[Negative-Prompt]] · [[DPM-Solver]] · [[AI-Image-Generation]].
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — formula + dynamic / Flux / sweep + 매 diffusers code |