[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
+111 -67
View File
@@ -2,93 +2,137 @@
id: wiki-2026-0508-encoder-decoder-inconsistency
title: Encoder Decoder Inconsistency
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [PREI-AUTO-ENC-DEC-INC-001]
aliases: [encoder-decoder-mismatch, seq2seq-inconsistency]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
tags: [auto-reinforced, Encoder-Decoder-Inconsistency, RAG, alignment, semantic-gap, inference-quality]
confidence_score: 0.9
verification_status: applied
tags: [nlp, transformer, training, decoding]
raw_sources: []
last_reinforced: 2026-05-05
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: pytorch
---
# [[Encoder-Decoder-Inconsistency|인코더-디코더 불일치 (Encoder-Decoder Inconsistency)]]
# Encoder Decoder Inconsistency
## 📌 한 줄 통찰 (The Karpathy Summary)
> "찾아온 사람(인코더)과 대답하는 사람(디코더)이 서로 다른 언어와 가치관을 가졌을 때 발생하는 인지적 불협화음: [[RAG|RAG]] 성능 저하의 숨은 주범."
## 한 줄
> **"매 encoder가 본 분포 ≠ decoder가 생성하는 분포"**. Seq2seq training 시 encoder는 ground-truth context를 보지만 decoder는 inference에서 자기 prediction을 다시 입력으로 받기 때문에 train/inference 간 distribution shift가 발생한다. 매 exposure bias 의 근본 원인.
## 📖 구조화된 지식 (Synthesized Content)
인코더-디코더 불일치는 텍스트를 벡터로 변환하여 검색하는 모델(인코더)과 텍스트를 생성하는 모델(디코더)이 동일한 정보를 서로 다르게 해석할 때 발생합니다.
## 매 핵심
1. **발생 원인**:
* 두 모델이 서로 다른 데이터셋으로 훈련되었거나, 학습 목표(검색 vs 생성)가 상이하여 텍스트의 중요도를 판단하는 기준이 다르기 때문.
* 특히 검색 기반의 [[RAG|RAG]] 아키텍처에서 두 독립적인 모델을 결합할 때 흔히 발생.
2. **부작용**:
* 인코더가 '중요하다'고 판단하여 가져온 문서가 디코더의 입장에서는 '무의미'하거나 '방해'되는 정보일 수 있으며, 이로 인해 답변의 정확도가 하락함.
3. **해결 전략 (Alignment)**:
* **[[E2LLM|E2LLM]] 방식**: 어댑터를 통해 인코더의 출력을 디코더의 입력 공간과 물리적으로 정렬.
* **상호 훈련**: 인코더와 디코더를 공동 학습시켜 동일한 의미론적 해상도를 갖도록 조율.
### 매 정의
- **Train**: decoder input = teacher-forced ground truth.
- **Inference**: decoder input = previously generated token.
- **Gap**: 매 error compounds along sequence — early mistake → later tokens conditioned on out-of-distribution prefix.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **독립성의 트레이드오프 (RL Update)**: 모델을 분리해서 쓰면 구축이 빠르고 유연하지만(Plug-and-play), 불일치로 인한 오류 전파를 피하기 어려움. 따라서 고성능 시스템일수록 두 모델 사이의 '의미적 밀착도'를 높이는 정렬 과정이 필수적임.
- **Antigravity 정책**: 검색 엔진 Astra는 검색 성능만을 보지 않고, 가져온 결과가 에이전트의 생성 품질에 기여하는지를 실시간으로 점수화하는 '하용론적 피드백'을 통해 이 불일치 문제를 해결함.
### 매 표현
- Exposure bias (Ranzato 2016).
- Schedule sampling 의 motivation.
- Hallucination 의 한 원인 (특히 long-form generation).
## 🔗 지식 연결 (Graph)
- [[RAG|RAG]], [[E2LLM|E2LLM]], [[Context-Integration|Context-Integration]], [[AI-Alignment|AI-Alignment]]
- **Raw Source**: Datacollector_MAC/out_wiki/인코더-디코더 불일치 (Encoder-Decoder Inconsistency).md
---
### 매 응용
1. NMT (Neural Machine Translation) — 매 long sentence translation degradation.
2. Summarization — repetition / drift.
3. Speech recognition — RNN-T vs CTC trade-off.
4. Code generation — 매 long completion 의 syntax break.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Scheduled Sampling
```python
import torch
import torch.nn.functional as F
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (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
def scheduled_sampling_step(decoder, prev_token, hidden, gt_token, p_use_gt: float):
"""p_use_gt 의 확률로 ground-truth, 아니면 model prediction 의 사용."""
if torch.rand(1).item() < p_use_gt:
input_tok = gt_token
else:
with torch.no_grad():
logits, _ = decoder(prev_token, hidden)
input_tok = logits.argmax(dim=-1)
out_logits, hidden = decoder(input_tok, hidden)
return out_logits, hidden
```
## 🤔 의사결정 기준 (Decision Criteria)
### Minimum Risk Training
```python
def mrt_loss(model, src, refs, n_samples=8):
"""매 sequence-level loss 의 — 매 sampled hypotheses 에 대해 risk minimize."""
hyps = [model.sample(src) for _ in range(n_samples)]
risks = torch.tensor([1 - bleu(h, refs) for h in hyps])
log_probs = torch.stack([model.log_prob(h, src) for h in hyps])
weights = F.softmax(log_probs, dim=0)
return (weights * risks).sum()
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Self-distillation Fix
```python
def self_distill(student, teacher, src, T=2.0):
"""매 teacher 가 자기 생성한 sequence 의 사용 — 매 train/inference gap 축소."""
with torch.no_grad():
gen = teacher.generate(src, do_sample=True, top_p=0.9)
teacher_logits = teacher(src, gen).logits
student_logits = student(src, gen).logits
return F.kl_div(
F.log_softmax(student_logits / T, dim=-1),
F.softmax(teacher_logits / T, dim=-1),
reduction="batchmean",
) * T * T
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Beam Search with Length Penalty
```python
def length_penalty(score, length, alpha=0.7):
"""GNMT length penalty — 매 short hypothesis 의 bias 보정."""
return score / ((5 + length) ** alpha / (5 + 1) ** alpha)
```
**기본값:**
> *(TODO)*
### Contrastive Decoding
```python
def contrastive_decode(big, small, prompt, alpha=0.5):
"""매 large model logit small model logit — 매 expert/amateur gap 의 강조."""
big_logits = big(prompt).logits[:, -1]
small_logits = small(prompt).logits[:, -1]
return big_logits - alpha * small_logits
```
## ❌ 안티패턴 (Anti-Patterns)
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Short sequence (<32) | Teacher forcing 충분 |
| Long sequence | Scheduled sampling / MRT |
| Production NMT | Beam + length penalty + coverage |
| LLM long-form | Contrastive decoding / self-distillation |
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
**기본값**: teacher forcing + 1k step warmup 이후 scheduled sampling.
## 🔗 Graph
- 부모: [[Sequence-to-Sequence]] · [[Transformer]]
- 변형: [[Scheduled-Sampling]] · [[Minimum-Risk-Training]]
- 응용: [[Neural-Machine-Translation]] · [[Abstractive-Summarization]]
- Adjacent: [[Exposure-Bias]] · [[Hallucination]] · [[Beam-Search]]
## 🤖 LLM 활용
**언제**: long-form generation 의 quality issue 분석 시. Train/eval BLEU gap 의 진단.
**언제 X**: 매 short classification — 매 inconsistency 의 무관.
## ❌ 안티패턴
- **Pure teacher forcing forever**: 매 inference distribution 의 미본 채 deploy.
- **Greedy decoding only**: 매 early mistake 의 lock-in.
- **No length normalization**: beam 의 short hypothesis bias.
## 🧪 검증 / 중복
- Verified (Ranzato et al. 2016, Bengio et al. 2015 scheduled sampling).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — encoder/decoder distribution shift + scheduled sampling/MRT/contrastive decoding |