[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,65 +2,182 @@
|
||||
id: wiki-2026-0508-prompt-weight
|
||||
title: Prompt Weight
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [Prompt Weighting, Attention Weighting, Token Emphasis, Prompt Strength]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [uncategorized]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [prompt-engineering, generative-ai, stable-diffusion, midjourney, image-gen]
|
||||
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 / Midjourney
|
||||
---
|
||||
|
||||
# [[Prompt Weight|Prompt Weight]]
|
||||
# Prompt Weight
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
Prompt Weight(프롬프트 가중치)는 AI 이미지 생성 시 텍스트 프롬프트 내 특정 단어나 구문의 반영 강도를 조절하는 기법이다 [1]. 기본값은 1이며, 수치를 높이거나 낮추어 이미지 내 특정 요소의 비중을 세밀하게 제어할 수 있다 [1, 2]. 스테이블 디퓨전(Stable Diffusion)의 괄호 및 숫자 표기법과 미드저니(Midjourney)의 `::` 매개변수 등 AI 모델마다 서로 다른 문법 체계를 지니고 있다 [3, 4].
|
||||
## 매 한 줄
|
||||
> **"매 emphasize / de-emphasize specific tokens in a prompt — `(word:1.3)` syntax of Stable Diffusion, `--w` of Midjourney, attention scaling under the hood"**. AUTOMATIC1111 (2022) 의 prompt-weight syntax 가 community standard 로 자리잡음. 2026 currently FLUX, SD3.5, SDXL Turbo, Midjourney v7 모두 weighting 지원; T5-encoded models 는 syntax 가 다름.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **가중치의 개념 및 기본 원리:** 가중치(Weight)는 프롬프트에서 특정 요소에 대한 모델의 주목도를 상대적으로 지정하는 수단이다 [2, 5]. 기본값은 1이며, 1보다 큰 값을 주면 요소가 강조되고 0에서 0.9 사이의 값을 주면 비중이 축소된다 [1, 6]. 그러나 가중치를 너무 높게 설정(예: 2.0 이상)하면 이미지 품질이 저하되거나 렌더링에 오류가 발생할 위험이 있으므로 주의가 필요하다 [1, 2, 7]. 일반적으로 가장 안전하게 시작할 수 있는 가중치는 0.7 수준이며, 이는 기본 모델의 화풍을 해치지 않으면서 특정 요소를 반영하는 데 효과적이다 [6].
|
||||
* **스테이블 디퓨전(Stable Diffusion)의 가중치 문법:** 일반적으로 `(단어:수치)` 형태를 사용하여 가중치를 명시한다(예: `(dog:1.1)`) [8]. 괄호 없이 `dog:1.6`과 같이 입력하면 파서(Parser)가 이를 제대로 인식하지 못한다 [8, 9]. 또한 `+`나 `-` 기호를 통해 강도를 조절하는 문법도 널리 사용되는데, `+`는 1.1배, `++`는 1.1의 제곱, `-`는 0.9배의 가중치를 의미한다 [10]. 부정 프롬프트(Negative Prompt)에서는 `[단어]` 형태를 사용하여 생성 확률을 낮추거나 `[(bad:1.2)]`와 같이 가중치를 함께 부여할 수 있다 [7, 8].
|
||||
* **미드저니(Midjourney)의 가중치 매개변수:** 미드저니는 텍스트 뒤에 `::` 기호와 숫자를 입력하여 단어 간의 상대적 가중치를 부여하는 다중 프롬프트(Multi-prompt) 방식을 사용한다(예: `red car::2 blue car::1`) [4, 11]. 이 외에도 텍스트 대비 참조 이미지의 비중을 결정하는 `--iw`(Image Weight), 캐릭터 참조의 일관성 비중을 조절하는 `--cw`(Character Weight, 0~100), 스타일 참조의 영향력을 정하는 `--sw`(Style Weight, 0~1000) 등 다양한 전용 매개변수(Parameter)를 제공하여 정교한 제어를 가능하게 한다 [12-14].
|
||||
* **가중치 사용의 한계 및 주의사항:** 가중치가 강력한 도구이긴 하지만, 프롬프트 내 단어의 배치 순서(Word Order)가 가중치 이상으로 결과물에 더 큰 영향을 미칠 수 있다 [5]. 또한, 결함을 수정하기 위해 부정 프롬프트에 너무 공격적인 가중치를 부여하면(예: `(blurry:1.5)`), 오히려 이미지의 전체적인 구조를 왜곡시키는 등 새로운 문제를 야기할 수 있으므로 가벼운 수치부터 점진적으로 조절하는 것이 권장된다 [15, 16].
|
||||
## 매 핵심
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[Stable Diffusion|Stable Diffusion]], [[Midjourney|Midjourney]], [[Negative Prompt|Negative Prompt]], [[Parameter|Parameter]]
|
||||
- **Projects/Contexts:** 이미지 생성의 미세 제어(Fine-grained Control), 멀티 프롬프트(Multi-prompting)
|
||||
- **Contradictions/Notes:** 스테이블 디퓨전의 프롬프트 가중치 문법은 사용 중인 인터페이스나 파서(Parser)에 따라 차이가 있다. 일부 오픈소스 인터페이스에서는 `()`를 가중치 증가로, `[]`를 가중치 감소로 사용하는 구문을 표준으로 쓰지만, 특정 툴(예: getimg.ai)에서는 `+/-` 및 숫자 기반 구문만 지원하며 과도한 괄호 중첩은 처리를 지연시킬 수 있다고 경고한다 [17].
|
||||
### 매 syntax (Stable Diffusion / A1111 / ComfyUI)
|
||||
- `(word)` — weight ×1.1.
|
||||
- `((word))` — ×1.21.
|
||||
- `(word:1.3)` — explicit weight ×1.3.
|
||||
- `[word]` — weight ÷1.1.
|
||||
- `[word:0.5]` — weight ×0.5.
|
||||
- `(red hair:1.4) (blue eyes:0.8)` — phrase-level.
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-30*
|
||||
### 매 syntax (Midjourney v7)
|
||||
- `cat dog` — equal weight.
|
||||
- `cat::2 dog::1` — double-colon multi-prompt with weights.
|
||||
- `--w 0.5` — image weight (text vs reference image).
|
||||
- `--s 250` — stylize strength.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 syntax (FLUX / T5-encoded)
|
||||
- T5 understands natural language; `(word:1.3)` syntax 매 mostly ignored.
|
||||
- Use **emphasis via wording**: "very prominent X", "subtle hint of Y".
|
||||
- Some forks (forge, ComfyUI) 매 still parse weights via re-prompting.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 매 mechanism (under the hood)
|
||||
- CLIP/T5 text encoder → token embeddings.
|
||||
- A1111: weight w → multiply token embedding by w (post-encoding rescale).
|
||||
- Compel library: more sophisticated — interpolates between conditioning vectors.
|
||||
- Cross-attention scaling: alternative — scale K/V at attention layer.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### 매 best practices
|
||||
- Stay between 0.5 and 1.5; 매 above 1.5 → distortion / saturation.
|
||||
- Negative prompts often more effective than `[word]` syntax.
|
||||
- Long prompts: weight the critical 3-5 tokens, leave rest at 1.0.
|
||||
- For T5 models, use natural-language emphasis instead.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
## 💻 패턴
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
### diffusers + Compel (programmatic weighting)
|
||||
```python
|
||||
from diffusers import StableDiffusionXLPipeline
|
||||
from compel import Compel, ReturnedEmbeddingsType
|
||||
import torch
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
pipe = StableDiffusionXLPipeline.from_pretrained(
|
||||
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
||||
).to("cuda")
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
compel = Compel(
|
||||
tokenizer=[pipe.tokenizer, pipe.tokenizer_2],
|
||||
text_encoder=[pipe.text_encoder, pipe.text_encoder_2],
|
||||
returned_embeddings_type=ReturnedEmbeddingsType.PENULTIMATE_HIDDEN_STATES_NON_NORMALIZED,
|
||||
requires_pooled=[False, True],
|
||||
)
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
prompt = "a (red:1.4) sports car on a (sunny:0.7) beach, cinematic"
|
||||
conditioning, pooled = compel(prompt)
|
||||
image = pipe(prompt_embeds=conditioning, pooled_prompt_embeds=pooled).images[0]
|
||||
```
|
||||
|
||||
- **과거 데이터와의 충돌:** 없음
|
||||
- **정책 변화:** 없음
|
||||
### A1111-style parsing (manual)
|
||||
```python
|
||||
import re
|
||||
def parse_weighted(prompt):
|
||||
"""Return list of (text, weight) tuples."""
|
||||
out, depth_paren, depth_brack = [], 0, 0
|
||||
# Simplified: handles (text:1.3) only
|
||||
pattern = re.compile(r"\(([^():]+):([\d.]+)\)")
|
||||
parts, last = [], 0
|
||||
for m in pattern.finditer(prompt):
|
||||
if m.start() > last:
|
||||
parts.append((prompt[last:m.start()], 1.0))
|
||||
parts.append((m.group(1), float(m.group(2))))
|
||||
last = m.end()
|
||||
if last < len(prompt):
|
||||
parts.append((prompt[last:], 1.0))
|
||||
return parts
|
||||
```
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### Cross-attention scaling (Hugging Face)
|
||||
```python
|
||||
# Scale a specific token's attention by factor
|
||||
from diffusers.models.attention_processor import AttnProcessor
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
class WeightedAttn(AttnProcessor):
|
||||
def __init__(self, token_idx, scale):
|
||||
self.token_idx, self.scale = token_idx, scale
|
||||
def __call__(self, attn, hidden, encoder_hidden, attention_mask=None):
|
||||
# In encoder_hidden, multiply token_idx slot by scale before attn
|
||||
encoder_hidden = encoder_hidden.clone()
|
||||
encoder_hidden[:, self.token_idx] *= self.scale
|
||||
return super().__call__(attn, hidden, encoder_hidden, attention_mask)
|
||||
```
|
||||
|
||||
### Midjourney prompt
|
||||
```
|
||||
masterpiece anime girl::3 cyberpunk city background::1 neon lights::0.5
|
||||
--ar 16:9 --s 500 --v 7
|
||||
```
|
||||
|
||||
### FLUX-style natural-language emphasis (no syntax)
|
||||
```python
|
||||
# Bad (FLUX ignores): "(red hair:1.5) girl"
|
||||
# Good: "girl with strikingly vivid red hair, the red is the most prominent color in the image"
|
||||
```
|
||||
|
||||
### Prompt-blending (interpolate two prompts)
|
||||
```python
|
||||
from compel import Compel
|
||||
c1 = compel("a cat in a forest")
|
||||
c2 = compel("a robot in a city")
|
||||
mixed = (c1 + c2) / 2 # Compel supports tensor arithmetic
|
||||
image = pipe(prompt_embeds=mixed).images[0]
|
||||
```
|
||||
|
||||
### Step-conditional weighting (`[from:to:step]`)
|
||||
```
|
||||
[cat:dog:0.5] in a field
|
||||
# 0-50% steps: "cat", 50-100%: "dog"
|
||||
# Useful for changing subject mid-denoising
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| SDXL / SD1.5 / SD2.1 | A1111 `(word:1.3)` syntax via Compel |
|
||||
| FLUX / SD3.5 (T5) | Natural-language emphasis |
|
||||
| Midjourney v7 | `::weight` syntax |
|
||||
| Subject + style mix | Multi-prompt with `::` or compel blends |
|
||||
| Subtle adjustment | 0.8-1.2 range |
|
||||
| Strong push | 1.3-1.5; rarely above |
|
||||
| Suppress concept | Negative prompt (preferred) over `[word]` |
|
||||
|
||||
**기본값**: Compel for SDXL programmatic; A1111 syntax for casual; natural language for FLUX.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Prompt-Engineering]] · [[Image-Generation]]
|
||||
- 변형: [[Negative-Prompt]] · [[Cross-Attention-Control]] · [[Prompt-Blending]]
|
||||
- 응용: [[Stable-Diffusion]] · [[FLUX]] · [[Midjourney]] · [[ComfyUI]]
|
||||
- Adjacent: [[CLIP]] · [[T5]] · [[Diffusion-Models]] · [[ControlNet]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: image generation pipelines, fine-grained subject/style control, automated prompt synthesis.
|
||||
**언제 X**: text-only LLM prompts (GPT/Claude don't use this syntax — use emphasis words instead), T5-only models.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Weight > 2.0**: 매 saturated artifacts, deformed output.
|
||||
- **Stacking parens** `(((((word)))))`: hard to read; use explicit `(word:1.6)`.
|
||||
- **A1111 syntax on FLUX/T5**: silently ignored — switch to natural language.
|
||||
- **Weighting every token**: dilutes effect; pick 2-4 priorities.
|
||||
- **Forgetting negative prompt**: often the right tool for "not X".
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (AUTOMATIC1111 wiki, Compel docs, Midjourney v7 docs 2024-2025, FLUX official guidance).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — canonical prompt-weight ref + FLUX/T5 caveat |
|
||||
|
||||
Reference in New Issue
Block a user