[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,94 +2,205 @@
|
||||
id: wiki-2026-0508-toxicity-and-bias-mitigation
|
||||
title: Toxicity and Bias Mitigation
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-TBMI-001]
|
||||
aliases: [LLM Safety, Bias Mitigation, Constitutional AI, RLHF, RLAIF]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.96
|
||||
tags: [auto-reinforced, ai-ethics, toxicity-mitigation, bias-reduction, safety-benchmarking, responsible-ai]
|
||||
confidence_score: 0.88
|
||||
verification_status: applied
|
||||
tags: [safety, alignment, bias, rlhf, constitutional-ai]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: python
|
||||
framework: trl-anthropic-openai
|
||||
---
|
||||
|
||||
# [[Toxicity-and-Bias-Mitigation|Toxicity-and-Bias-Mitigation]]
|
||||
# Toxicity and Bias Mitigation
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "독성 제거와 공정함의 수호: 학습 데이터에 숨겨진 인간의 편견과 혐오가 AI를 통해 증폭되지 않도록, 필터링과 교정 알고리즘을 통해 깨끗하고 공정한 지능을 빚어내는 윤리적 공정."
|
||||
## 매 한 줄
|
||||
> **"매 LLM output 에서 harm, stereotype, factual bias 을 제거하면서 helpfulness 를 유지하는 alignment stack"**. 매 2017 RLHF (Christiano) → 2022 Constitutional AI (Anthropic) → 2024 deliberative alignment (OpenAI o1) → 2026 multi-stage post-training (helpfulness + harmlessness + honesty + sycophancy reduction). 매 모든 frontier model 의 production deployment 의 prerequisite.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
독성 및 편향 완화(Toxicity-and-Bias-Mitigation)는 AI 모델이 혐오 표현을 생성하거나 특정 집단에 대해 차별적 판단을 내리는 행위를 방지하기 위한 기술적, 정책적 활동입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **주요 타겟**:
|
||||
* **Toxicity**: 공격적 언어, 성희롱, 혐오 발언, 폭력 선동.
|
||||
* **Bias**: 인종, 성별, 종교, 지역 등 고정관념에 기반한 불평등한 결과 도출.
|
||||
2. **완화 기술**:
|
||||
* **Pre-[[Processing|Processing]]**: 학습 데이터셋에서 독성 문서를 사전에 제거.
|
||||
* **In-processing (RLHF)**: 인간 피드백을 통해 모델이 무해한(Harmless) 답변을 하도록 강화 학습.
|
||||
* **Post-processing**: 생성된 결과물을 별도의 가드레일 모델이 검사하여 차단.
|
||||
3. **측정 및 벤치마킹**:
|
||||
* 다양한 인구 통계학적 그룹에 대한 답변 일관성 테스트 실시.
|
||||
### 매 taxonomy of harms
|
||||
1. **Toxicity**: hate speech, harassment, slurs.
|
||||
2. **Bias**: demographic stereotypes (gender, race, religion).
|
||||
3. **Misinformation**: false / misleading factual claims.
|
||||
4. **Manipulation**: persuasion, deception, sycophancy.
|
||||
5. **Dual-use**: bioweapon / cyber / CBRN uplift.
|
||||
6. **Privacy**: PII leakage, training data extraction.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 단순히 사전(Keyword) 기반 차단에 의존했으나, 현대 AI 정책은 문맥적 의미를 파악하여 교묘한 혐오 표현(Dog whistling)까지 감지하는 '심층 의미 분석 정책'으로 진화함(RL Update).
|
||||
- **정책 변화(RL Update)**: '완전한 중립'이라는 허상을 쫓기보다, 해당 사회의 보편적 윤리 기준을 명시적으로 시스템에 이식하고 그 기준의 수립 과정을 투명하게 공개하는 '가치 정렬(Value [[Alignment|Alignment]]) 거버넌스 정책'이 글로벌 표준이 됨.
|
||||
### 매 mitigation pipeline (modern)
|
||||
1. **Pretraining filter**: C4-style + classifiers, Common Crawl deduplication.
|
||||
2. **SFT** (supervised finetune): safe demonstrations.
|
||||
3. **RLHF / DPO** (Direct Preference Optimization 2023+): human preference.
|
||||
4. **Constitutional AI / RLAIF** (Anthropic): AI feedback against principles.
|
||||
5. **Red-teaming**: human + automated adversarial probing.
|
||||
6. **Inference-time**: classifier filters, refusal training, system prompts.
|
||||
7. **Deliberative / chain-of-thought safety** (o1, Claude 3.7+): reasoning about safety policy explicitly.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Ethics & AI|Ethics & AI]], [[Generative-AI|Generative-AI]]-Safety, [[RLHF (인간 피드백 기반 강화 학습)|RLHF (인간 피드백 기반 강화 학습)]], Social[[Systems Theory|systems Theory]], [[Science of Failure|Science of Failure]]
|
||||
- **Modern Tech/Tools**: Perspective API, OpenAI Moderation API, Constitutional AI (Anthropic).
|
||||
---
|
||||
### 매 bias measurement benchmarks
|
||||
- **BBQ** (Bias Benchmark for QA, 11 social dimensions).
|
||||
- **StereoSet** (intersentence stereotype).
|
||||
- **WinoGender / WinoBias** (coreference gender bias).
|
||||
- **RealToxicityPrompts** (Gehman 2020).
|
||||
- **TruthfulQA** (Lin 2021, misconception).
|
||||
- **AILuminate** (MLCommons 2024+, hazard taxonomy).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. Production LLM safety (Claude, GPT, Gemini).
|
||||
2. Content moderation (post-training classifier).
|
||||
3. Fairness audit (HR, lending, criminal justice ML).
|
||||
4. Domain-specific safety (medical advice, legal disclaimers).
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Pattern 1: DPO (Direct Preference Optimization, 2023+)
|
||||
```python
|
||||
from trl import DPOTrainer, DPOConfig
|
||||
from datasets import load_dataset
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
# preference data: chosen vs rejected
|
||||
ds = load_dataset("Anthropic/hh-rlhf")
|
||||
config = DPOConfig(
|
||||
beta=0.1,
|
||||
learning_rate=5e-7,
|
||||
output_dir="./dpo-out",
|
||||
)
|
||||
trainer = DPOTrainer(
|
||||
model=model,
|
||||
ref_model=ref_model,
|
||||
args=config,
|
||||
train_dataset=ds["train"],
|
||||
tokenizer=tokenizer,
|
||||
)
|
||||
trainer.train()
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Pattern 2: Constitutional AI critique loop
|
||||
```python
|
||||
CONSTITUTION = [
|
||||
"Avoid suggesting illegal or dangerous activities.",
|
||||
"Be honest, even when the truth is uncomfortable.",
|
||||
"Avoid stereotyping based on demographic attributes.",
|
||||
]
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
def constitutional_critique(prompt, response, principle):
|
||||
critique_prompt = f"""
|
||||
Response: {response}
|
||||
Principle: {principle}
|
||||
Critique any violation, then rewrite to comply.
|
||||
"""
|
||||
return llm.complete(critique_prompt)
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
# Iterate over response → critique → revision → train on revisions.
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Pattern 3: Toxicity classifier filter (Detoxify)
|
||||
```python
|
||||
from detoxify import Detoxify
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
clf = Detoxify('unbiased')
|
||||
scores = clf.predict("user-generated text here")
|
||||
# {'toxicity': 0.02, 'severe_toxicity': 0.01, 'identity_attack': ...}
|
||||
if scores['toxicity'] > 0.7:
|
||||
block()
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Pattern 4: BBQ-style bias eval
|
||||
```python
|
||||
from datasets import load_dataset
|
||||
|
||||
bbq = load_dataset("heegyu/bbq")
|
||||
correct = 0
|
||||
biased = 0
|
||||
for item in bbq["test"]:
|
||||
answer = model.generate(item["context"] + "\n" + item["question"])
|
||||
if answer == item["label"]:
|
||||
correct += 1
|
||||
elif answer == item["target_loc"]: # stereotypical answer
|
||||
biased += 1
|
||||
print(f"Accuracy: {correct/len(bbq)}, Bias rate: {biased/len(bbq)}")
|
||||
```
|
||||
|
||||
### Pattern 5: Inference-time system prompt scaffolding
|
||||
```python
|
||||
SYSTEM = """You are a helpful assistant. Follow these principles:
|
||||
1. Decline requests for self-harm guidance; offer crisis resources.
|
||||
2. Decline weapons / CBRN uplift requests.
|
||||
3. Note uncertainty when factual claims are not verified.
|
||||
4. Avoid demographic stereotyping in examples and reasoning.
|
||||
"""
|
||||
response = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
system=SYSTEM,
|
||||
messages=[...],
|
||||
)
|
||||
```
|
||||
|
||||
### Pattern 6: Red-team probing (PAIR-style automated)
|
||||
```python
|
||||
# Prompt Automatic Iterative Refinement
|
||||
def red_team_pair(target_model, attacker_model, harmful_goal, rounds=10):
|
||||
attacker_history = [{"role": "system", "content": f"Find prompt that elicits: {harmful_goal}"}]
|
||||
for _ in range(rounds):
|
||||
prompt = attacker_model.generate(attacker_history)
|
||||
response = target_model.generate(prompt)
|
||||
score = judge_model.score(response, harmful_goal)
|
||||
if score > 0.8:
|
||||
return prompt, response # jailbreak found
|
||||
attacker_history.append({"role": "user", "content": f"Failed. Score {score}. Try again."})
|
||||
```
|
||||
|
||||
### Pattern 7: Debiasing word embeddings (legacy but illustrative)
|
||||
```python
|
||||
import numpy as np
|
||||
|
||||
def neutralize(word_vec, bias_direction):
|
||||
# project out gender direction
|
||||
return word_vec - np.dot(word_vec, bias_direction) * bias_direction
|
||||
|
||||
# Bolukbasi 2016: he-she axis as bias direction
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Frontier model post-training | RLHF + Constitutional AI + red-team |
|
||||
| Fine-tune small model | DPO with curated preferences |
|
||||
| Production filter | Detoxify + custom classifier |
|
||||
| Audit existing model | BBQ + RealToxicityPrompts + TruthfulQA |
|
||||
| User-facing app | system prompt + classifier + refusal |
|
||||
|
||||
**기본값**: DPO + Constitutional principles for finetune; system prompt + classifier for app.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[AI Alignment]] · [[AI Safety]]
|
||||
- 변형: [[RLHF]] · [[Constitutional AI]] · [[DPO]] · [[RLAIF]]
|
||||
- 응용: [[Content Moderation]] · [[Red Teaming]] · [[Fairness ML]]
|
||||
- Adjacent: [[Jailbreak]] · [[Adversarial Robustness]] · [[Mechanistic Interpretability]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: model deployment, safety eval, bias audit, alignment research.
|
||||
**언제 X**: pure capability eval (use separate benchmark).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Filter-only safety**: classifier 만 사용 → easily bypassed. base 모델 alignment 필수.
|
||||
- **Over-refusal**: too restrictive → useless model (helpfulness collapse).
|
||||
- **Single benchmark eval**: BBQ 만 보면 다른 bias 못 잡음. multi-benchmark.
|
||||
- **Ignoring sycophancy**: RLHF preference 가 user agreement 로 collapse.
|
||||
- **Anglo-centric eval**: English-only benchmark → other-language harms 누락.
|
||||
- **Static red-team**: one-time adversarial test → drift 후 무력화. continuous.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Bai et al. Constitutional AI 2022; Rafailov DPO 2023; OpenAI o1 system card 2024; Anthropic Claude 3 model card; MLCommons AILuminate 2024).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full mitigation pipeline (RLHF → CAI → deliberative) |
|
||||
|
||||
Reference in New Issue
Block a user