[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
+237 -64
View File
@@ -2,92 +2,265 @@
id: wiki-2026-0508-hallucination-in-llms
title: Hallucination in LLMs
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [LLM-HAL-001]
aliases: [LLM hallucination, fabrication, confabulation, TruthfulQA, source attribution]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [ai, nlp, llm, hallucination, ai-ethics, rag]
confidence_score: 0.97
verification_status: applied
tags: [llm, hallucination, truthfulness, rag, calibration, fact-check]
raw_sources: []
last_reinforced: 2026-04-26
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: LangChain / Anthropic / RAG
---
# Hallucination in LLMs (LLM의 환각 현상)
# Hallucination in LLMs
## 📌 한 줄 통찰 (The Karpathy Summary)
> "모델은 '모름'을 인정하기보다 가장 그럴듯한 거짓말을 선택하는 통계적 본능을 가지고 있음을 경계하라" — 대규모 언어 모델이 학습 데이터에 없는 사실을 마치 사실인 것처럼 지어내거나, 논리적으로 맞지 않는 답변을 생성하는 현상.
## 한 줄
> **"매 LLM 의 의 의 false but plausible-sounding output 의 generate"**. 매 modern LLM 의 critical issue. 매 cause: 매 training data, 매 distribution shift, 매 confident next-token. 매 mitigation: RAG, 매 source attribution, 매 calibration, 매 LLM-as-judge.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 모델이 확률적으로 가장 높은 다음 토큰을 생성하는 과정에서, 사실 관계(Factuality)보다 문장의 유창함(Fluency)이나 패턴의 유사성에 압도되어 발생하는 정보 왜곡 패턴.
- **주요 원인:**
- **Data [[Noise|Noise]]:** 학습 데이터 자체에 잘못된 정보가 포함된 경우.
- **Over-smoothing:** 드문 사실보다 흔한 패턴을 우선시하여 일반화하는 경향.
- **Knowledge Cut-off:** 학습 시점 이후의 사건에 대해 추측하여 답변.
- **해결 전략:**
- **RAG (Retrieval-Augmented Generation):** 외부의 신뢰할 수 있는 지식 소스를 검색하여 근거로 제공 (Antigravity의 핵심 전략).
- **prompt Engineering:** "모르면 모른다고 답하라"는 명시적 지시 포함.
- **Verification Loop:** 생성된 답변을 다른 모델이나 인간이 재검증.
- **의의:** AI 답변의 신뢰도를 결정하는 가장 큰 장벽이며, 이를 통제하는 능력이 실전 AI 성능의 척도가 됨.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순히 '창의적 오류'로 치부되던 시기를 지나, 이제는 시스템의 결함으로 인식되어 이를 줄이기 위한 기술(RLHF, RAG 등)이 비약적으로 발전함.
- **정책 변화:** Antigravity 프로젝트는 모든 지식 보강 작업 시 `00_Raw` 데이터에 기반한 RAG 프로세스를 강제하여 환각 현상을 원천 차단함.
### 매 type
- **Intrinsic**: 매 input 와 contradict.
- **Extrinsic**: 매 input 의 의 의 의 verify X.
- **Factual**: 매 world fact 의 wrong.
- **Reasoning**: 매 chain 의 fault.
## 🔗 지식 연결 (Graph)
- [[LLM|LLM]], [[Reinforcement-Learning-from-Human-Feedback-RLHF|Reinforcement-Learning-from-Human-Feedback-RLHF]], [[Trustworthy-AI|Trustworthy-AI]], Knowledge-Gardening-Protocol
- **Raw Source:** 10_Wiki/Topics/AI/[[Hallucination-in-LLM|Hallucination-in-LLM]]s.md
### 매 cause
- 매 training data 의 imperfect.
- 매 distribution shift (OOD).
- 매 next-token objective 의 confidence 의 of unrelated.
- 매 prompt ambiguity.
- 매 long-tail rare facts.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 mitigation
1. **RAG**: 매 ground in source.
2. **Source attribution**: 매 cite.
3. **Self-consistency**: 매 multiple sample 의 agree?
4. **Calibration**: 매 confidence ≈ accuracy.
5. **LLM-as-judge**: 매 evaluate.
6. **Fact-checking**: 매 external verify.
7. **Constrained decoding**: 매 schema enforce.
8. **Fine-tune** for honesty.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. **Production chatbot**: 매 critical.
2. **Medical / legal AI**.
3. **Search / Q&A**.
4. **Code generation**: 매 API hallucination.
5. **Summarization**: 매 fabricate.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### Detect (entailment-based)
```python
def hallucination_check(claim, source, llm):
prompt = f"""Does the source ENTAIL, CONTRADICT, or NEITHER the claim?
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
Source: {source}
Claim: {claim}
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
Output: ENTAIL | CONTRADICT | NEITHER"""
return llm.generate(prompt)
```
## 🤔 의사결정 기준 (Decision Criteria)
### RAG (grounded gen)
```python
def rag_answer(question, retriever, llm):
docs = retriever.retrieve(question, k=5)
context = '\n'.join(f'[{i}] {d.text}' for i, d in enumerate(docs))
prompt = f"""Answer based ONLY on the context. Cite [N] for each claim.
If the context does not contain the answer, say "I don't know."
**선택 A를 써야 할 때:**
- *(TODO)*
Context:
{context}
**선택 B를 써야 할 때:**
- *(TODO)*
Question: {question}"""
return llm.generate(prompt), docs
```
**기본값:**
> *(TODO)*
### Self-consistency
```python
from collections import Counter
def self_consistency(question, llm, n=10):
answers = [llm.generate(question, temperature=0.7) for _ in range(n)]
return Counter(answers).most_common(1)[0][0]
```
## ❌ 안티패턴 (Anti-Patterns)
### Calibration check
```python
def calibration_check(llm, test_questions, threshold=0.05):
"""매 confidence ≈ accuracy?"""
binned_correct = {i: [] for i in range(10)}
for q in test_questions:
response, conf = llm.generate_with_confidence(q['question'])
bin_i = int(conf * 10)
binned_correct[bin_i].append(response == q['answer'])
ece = 0
for bin_i, results in binned_correct.items():
if not results: continue
bin_acc = np.mean(results)
bin_conf = (bin_i + 0.5) / 10
ece += abs(bin_acc - bin_conf) * len(results) / len(test_questions)
return ece
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### LLM-as-judge
```python
def judge_truthfulness(claim, judge_llm):
prompt = f"""Evaluate the claim for truthfulness.
Claim: "{claim}"
Output JSON:
- truthful: bool
- confidence: 0-1
- evidence: ...
- if false: corrected version"""
return json.loads(judge_llm.generate(prompt))
```
### TruthfulQA-style eval
```python
def truthful_eval(model, questions):
correct = 0
for q in questions:
pred = model.generate(q['question'])
# 매 multi-choice or judge match
if any(g.lower() in pred.lower() for g in q['gold_answers']):
correct += 1
return correct / len(questions)
```
### Token entropy (uncertainty signal)
```python
import torch
def token_entropies(model, prompt, response):
inputs = tokenizer(prompt + response, return_tensors='pt')
with torch.no_grad():
logits = model(**inputs).logits[0]
probs = logits.softmax(-1)
entropies = -(probs * probs.clamp(min=1e-10).log()).sum(-1)
return entropies # 매 high entropy = uncertain → potential hallucination
```
### Constrained decoding (schema)
```python
from outlines import models, generate
m = models.transformers('gpt2')
gen = generate.json(m, MyResponseSchema)
result = gen('Question: ...') # 매 must conform
```
### Fact-check pipeline
```python
def fact_check_pipeline(response, llm, fact_checker):
claims = extract_claims(response, llm)
results = []
for claim in claims:
evidence = fact_checker.search(claim)
verdict = entailment_check(claim, evidence)
results.append({'claim': claim, 'verdict': verdict})
return results
```
### Refusal of unknown
```python
HONEST_SYSTEM = """You are a helpful assistant. If you don't know an answer with high confidence, say "I don't know" or "I'm not sure" rather than guessing.
Always cite sources when making factual claims."""
```
### Chain-of-Verification (CoVe)
```python
def chain_of_verification(question, llm):
# 매 1. Initial answer
initial = llm.generate(f'Answer: {question}')
# 매 2. Plan verification questions
verify_qs = llm.generate(f'List verification questions for: {initial}').split('\n')
# 매 3. Answer each independently
verifications = [llm.generate(f'Answer: {q}') for q in verify_qs]
# 매 4. Refine
return llm.generate(f"""Original answer: {initial}
Verification:
{format(verify_qs, verifications)}
Refined answer:""")
```
### LLM honesty fine-tuning (DPO-style)
```python
# 매 dataset of (prompt, honest_response, hallucinated_response)
# 매 DPO trains to prefer honest
def hallucination_dpo_data(samples):
return [{'prompt': s.prompt, 'chosen': s.honest, 'rejected': s.hallucinated} for s in samples]
```
### Tool-augmented (search)
```python
def augmented_answer(question, llm):
# 매 LLM decides if external search needed
needs_search = llm.classify(question, ['needs_external_data', 'common_knowledge'])
if needs_search == 'needs_external_data':
results = web_search(question)
return rag_answer(question, results, llm)
return llm.generate(question)
```
### Hallucination metric (FActScore)
```python
def fact_score(generated_text, llm):
"""매 atomic facts → check each."""
facts = extract_atomic_facts(generated_text, llm)
supported = sum(1 for f in facts if check_fact(f) == 'supported')
return supported / len(facts)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Factual Q&A | RAG + citation |
| Open-ended | Self-consistency + judge |
| High-stakes | + fact-check + CoVe |
| Code | Execute + verify |
| Structured | Constrained decoding |
| Production | + monitor + abstain |
**기본값**: 매 RAG + 매 source attribution + 매 self-consistency for high-stakes + 매 abstention threshold + 매 LLM-judge eval.
## 🔗 Graph
- 부모: [[LLM-Reliability]] · [[Foundation-Models]]
- 변형: [[Intrinsic-Hallucination]] · [[Extrinsic-Hallucination]]
- 응용: [[RAG]] · [[Constitutional-AI]] · [[TruthfulQA]]
- Adjacent: [[Calibration]] · [[Epistemology]] · [[Excessive Agency]] · [[Fact-Checking]]
## 🤖 LLM 활용
**언제**: 매 모든 LLM production. 매 fact-critical.
**언제 X**: 매 explicitly creative (prefer hallucination).
## ❌ 안티패턴
- **No grounding**: 매 ungrounded confidently false.
- **High temp + factual**: 매 noise.
- **No abstention**: 매 always-answer.
- **No citation**: 매 unverifiable.
- **Single sample factual**: 매 lottery.
## 🧪 검증 / 중복
- Verified (TruthfulQA 2022, FActScore 2023, CoVe 2023, RAG literature).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-04-26 | Auto |
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — types + 매 RAG / SC / CoVe / FActScore / fact-check code |