Field Log · Entry

Synthetic Data·Distillation로 Embedding을 도메인 적응하기 (7/14)

도메인 문서에서 LLM이 query를 생성하고 teacher reranker가 positive와 hard negative를 정제해 작은 embedding student로 distill하는 흐름

이번 글의 결론

  • Label이 적은 domain에서는 강한 공개 model을 바로 full fine-tune하기보다 corpus 분석 → 작은 human eval → synthetic pair → teacher 정제 순서가 안전합니다.
  • LLM은 query 다양성을 만들고 Cross-Encoder는 candidate의 미세 relevance를 평가하는 식으로 역할을 나누면 distillation signal이 좋아집니다.
  • Teacher score를 그대로 truth로 복사하면 teacher의 언어·길이·source bias도 student가 배웁니다. Human qrel과 OOD guardrail을 유지합니다.
  • LoRA는 trainable parameter를 줄이지만 corpus re-embedding 비용을 없애지 않습니다. Adapter가 바뀌면 document vector 공간도 바뀌었는지 검증해야 합니다.
  • Domain gain은 public benchmark 평균 하락과 함께 보고합니다. Catastrophic forgetting을 허용할지 product requirement로 결정합니다.

앞 글에서 범용 instruction model을 살폈습니다. 이번 글은 회사 문서, 의료, 법률, code repository처럼 내 corpus의 relevance를 학습하는 방법입니다.


1. Fine-tuning이 필요한지 먼저 진단한다

다음 실패는 model fine-tuning보다 다른 수정이 먼저입니다.

실패먼저 할 일
답 문서가 indexing되지 않음ingestion·ACL·deletion 확인
답이 두 chunk로 분리됨chunking·parent context
exact top-k에는 있으나 ANN에서 누락index parameter·quantization
acronym·제품명 exact match 실패BM25/hybrid
관련 passage가 exact dense top-100 밖embedding adaptation 후보
top-100 안, top-5만 낮음reranker 후보

Fine-tuning 전에 exact search로 representation error를 확인합니다.

2. 최소 Domain Dataset

1,000–5,000 human-audited queries
  ├─ real traffic query
  ├─ no-answer query
  ├─ hard lexical/entity query
  ├─ long/context-dependent query
  └─ temporal/security-critical query

작아도 test set은 먼저 freeze합니다. Synthetic query를 test 문서에서 만들지 않습니다.

3. Document-to-Query Generation

각 passage에서 실제 사용자가 물을 법한 query를 생성합니다.

input:
  title + section path + passage + metadata

output:
  direct factual query
  procedural query
  paraphrased jargon-free query
  difficult implicit query
  unanswerable near-miss query

한 passage의 첫 문장을 의문문으로 바꾸는 쉬운 query만 만들면 lexical shortcut를 학습합니다.

Prompt 요구사항 예시:

- Passage만으로 정답을 지지할 수 있어야 한다.
- 답 단어를 그대로 복사한 질문만 만들지 않는다.
- 존재하지 않는 제품·날짜·원인을 전제하지 않는다.
- 한국어 실제 문의의 생략·약어를 일부 반영한다.
- query type과 answer span을 함께 출력한다.

4. Synthetic Positive를 검증한다

Round-trip gate:

passage d+ → generator → query q
q + d+ → verifier → answerable?
q → baseline retrieval → rank(d+)

너무 쉬운 query도 일부 제거합니다.

rank(d+) = 1 by BM25 with exact phrase
AND lexical overlap very high
→ low training value candidate

반대로 baseline이 못 찾았다고 좋은 query인 것은 아닙니다. Hallucinated premise일 수 있어 verifier와 표본 human audit가 필요합니다.

5. Gecko식 두 단계 Distillation

Gecko는 compact embedding model에 LLM knowledge를 distill하기 위해 다음 형태의 pipeline을 제안했습니다.

  1. LLM으로 다양한 synthetic paired data 생성
  2. 각 query로 candidate passage 검색
  3. LLM으로 positive와 hard negative relabel
  4. Student embedding 학습

핵심은 generator가 지정한 원래 passage만 positive로 믿지 않고 실제 corpus 후보를 다시 비교하는 것입니다.

synthetic intended positive
  + retrieved alternative passages
  → teacher relevance judgment
  → corrected multi-positive / hard-negative set

6. Teacher 종류

Teacher주는 signal강점위험
Cross-Encoderpair relevance score빠른 대량 scoring학습 domain bias
LLM pointwiselabel·rationaleinstruction·복합 판단비용·calibration
LLM listwiserelative ordering후보 context 비교order bias
Generator utilityanswer gainRAG 목적 정렬reader-specific
Ensembledisagreement·mean안정성비용·복잡성

Teacher rationale보다 score/order가 student loss에 직접 들어갑니다. Rationale의 그럴듯함은 label 정확도의 보장이 아닙니다.

7. Hard Label Distillation

Teacher threshold로 positive·negative를 정합니다.

teacher >= 0.8 → positive
teacher <= 0.2 → negative
otherwise      → ambiguous / low weight

간단하고 robust하지만 teacher의 미세한 ranking 정보를 버립니다.

8. Soft Score Distillation

Teacher와 student의 candidate distribution을 맞춥니다.

p_teacher(d_i|q) = softmax(t_i / τ_t)
p_student(d_i|q) = softmax(s_i / τ_s)

L_distill = KL(p_teacher || p_student)

Student는 teacher score scale 자체가 아니라 candidate 간 상대 distribution을 배웁니다. Candidate list가 너무 쉬우면 soft label이 거의 one-hot이 되어 정보가 줄어듭니다.

9. Representation Distillation

Teacher embedding (z_t)와 student (z_s) 차원이 다르면 projection head (W)를 둘 수 있습니다.

L_repr = 1 - cosine(W z_s, z_t)

하지만 teacher vector를 그대로 흉내 내는 것이 task retrieval을 보장하지 않습니다. Teacher space의 hubness·bias도 복사할 수 있습니다. Rank loss와 조합하고 projection head는 serving에서 제거되는지 명시합니다.

10. Multi-teacher Distillation

Dense teacher, sparse teacher, Cross-Encoder를 결합할 수 있습니다.

target score =
  α × dense_teacher
  + β × lexical_teacher
  + γ × cross_encoder

BGE-M3는 dense·sparse·multi-vector 기능의 self-knowledge distillation을 활용합니다. 단순 score 합산 전 각 teacher의 scale과 query별 normalization을 맞춥니다.

11. Fine-tuning 전략

Full Fine-tuning

모든 weight를 update합니다. Domain gain 잠재력이 크지만 memory와 forgetting risk가 큽니다.

LoRA/Adapter

일부 low-rank parameter만 학습합니다. 실험이 빠르고 여러 domain adapter를 보관하기 쉽습니다.

Projection Head Only

Frozen base embedding 위에 작은 transform을 학습합니다. Corpus vector를 transform해서 재사용할 수 있는 경우가 있지만, query만 transform하면 asymmetric space가 됩니다.

Continued Pretraining + Fine-tuning

Domain corpus로 MLM/MAE/contrastive adaptation 후 qrel fine-tuning합니다. Label이 적고 terminology가 크게 다를 때 검토합니다.

12. LoRA가 Re-indexing을 없애는가

아닙니다. Adapter가 document encoding을 바꾸면 기존 document vector와 새 query vector는 다른 space일 수 있습니다.

old documents: f_base(d)
new queries:   f_base+adapter(q)
→ compatibility not guaranteed

세 조건을 비교합니다.

  1. old doc vectors + new query encoder
  2. new doc vectors + new query encoder
  3. base both sides

Compatibility를 의도적으로 학습한 경우가 아니면 전체 re-embedding을 계획합니다.

13. Catastrophic Forgetting Guardrail

objective = in-domain gain
subject to:
  general retrieval drop <= δ
  multilingual drop <= δ_lang
  STS/classification drop if required

범용성이 product에 필요 없다면 일부 forgetting은 허용할 수 있습니다. 다만 의도한 trade-off여야 합니다.

대응:

  • base/general data replay
  • smaller learning rate·fewer steps
  • adapter/LoRA
  • regularization to base representation
  • checkpoint merging
  • task-balanced mixture

14. Synthetic Data Bias Audit

Generator별로 query style이 반복됩니다.

measure:
  query length distribution
  lexical overlap with positive
  interrogative pattern frequency
  entity/type coverage
  language/formality
  baseline BM25 difficulty
  answerability error

Real query와 classifier로 구분이 너무 잘되면 distribution gap이 큽니다. Generator·prompt 다양화보다 먼저 실제 query seed와 style constraints를 개선합니다.

15. Teacher Bias Matrix

teacher_audit:
  slices:
    korean: agreement 0.84
    english: agreement 0.91
    long_document: agreement 0.72
    temporal: agreement 0.68
    no_answer: agreement 0.77
  compared_to: human-adjudicated-500

Agreement가 낮은 slice는 teacher confidence를 weight로 쓰지 않거나 human data를 늘립니다.

16. 실험 순서

A  base model
B  + human pairs
C  + raw synthetic pairs
D  + verified synthetic pairs
E  + teacher-mined hard negatives
F  + soft distillation
G  + general-data replay

각 단계의 gain과 cost를 분리합니다. G만 보고 복잡한 recipe가 필요했다고 결론 내리지 않습니다.

17. Release Card

domain_embedding:
  base_model: pinned-revision
  adaptation: lora-r16
  synthetic:
    generator: pinned-model
    prompt: sha256:...
    generated: 180000
    passed_verification: 112000
    human_audit_error_rate: 0.041
  teacher:
    cross_encoder: reranker-v6
    calibration: v2
  training:
    rank_loss_weight: 1.0
    distill_weight: 0.3
    general_replay: 0.15
  compatibility:
    requires_reindex: true

스스로 확인하기

  1. Synthetic query가 원래 passage를 positive로 지정해도 corpus 후보를 다시 relabel해야 하는 이유는 무엇인가?
  2. Hard label과 soft distillation이 보존하는 teacher 정보는 어떻게 다른가?
  3. Teacher ensemble에서 score normalization이 필요한 이유는 무엇인가?
  4. LoRA fine-tuning 후 기존 document index를 그대로 쓰면 안 될 수 있는 이유는 무엇인가?
  5. In-domain gain과 catastrophic forgetting을 어떤 evaluation matrix로 함께 볼 수 있는가?

다음 글에서는 multilingual·cross-lingual embedding을 구분하고 한국어 morphology, 혼합 언어, 번역체를 포함한 학습·평가 matrix를 만듭니다.

참고자료