Field Log · Entry
Embedding 학습 데이터: Positive·Hard Negative·False Negative (4/14)
이번 글의 결론
- Embedding model은 label ontology를 geometry로 바꿉니다. Positive를 “같은 주제”로 정의할지 “답을 직접 제공”으로 정의할지가 model보다 먼저입니다.
- Random negative는 너무 쉽고, 최고 score hard negative는 false negative일 위험이 큽니다. 난이도 구간과 source를 섞어 curriculum을 만듭니다.
- In-batch negative를 쓰기 전에 duplicate·multi-positive·같은 문서의 sibling chunk를 검사해야 합니다.
- LLM·Cross-Encoder teacher는 정제 도구이지 진실이 아닙니다. Boundary sample의 human audit와 teacher disagreement를 기록합니다.
- 최근 연구는 데이터 양보다 품질이 더 중요할 수 있음을 보여 줍니다. Dataset별 ablation과 relabeling을 먼저 해 볼 가치가 큽니다.
앞 글에서 InfoNCE를 배웠습니다. Loss는 비교 대상을 정확히 정의했을 때만 좋은 공간을 만듭니다.
1. Positive Definition부터 쓴다
질문 “Python에서 파일을 안전하게 원자적으로 교체하는 법”에 대해 다음 문서는 모두 관련 있어 보입니다.
| 문서 | 주제 관련 | 답 직접 지지 | 학습 label 후보 |
|---|---|---|---|
os.replace 공식 문서 | 높음 | 높음 | strong positive |
| 일반 파일 I/O tutorial | 높음 | 낮음 | weak positive 또는 hard negative |
shutil.move 예제 | 중간 | 부분 | graded relevance |
| Java atomic move | 중간 | 낮음 | cross-language hard negative |
| 임시 파일 security guide | 중간 | 보완 | multi-hop positive 가능 |
Task가 topic search라면 두 번째도 positive입니다. Answer-bearing RAG라면 hard negative에 가깝습니다. 이를 label guide에 씁니다.
2. 권장 Data Unit
Binary pair만 저장하면 나중에 관계를 복구하기 어렵습니다.
{
"query_id": "q-101",
"query": "Python에서 파일을 원자적으로 교체하는 법",
"task": "answer_bearing_retrieval",
"language": "ko",
"documents": [
{"id":"d-1","grade":3,"reason":"direct_api_evidence","group":"e1"},
{"id":"d-2","grade":1,"reason":"topic_only","group":null},
{"id":"d-3","grade":0,"reason":"different_language_api","group":null}
],
"provenance": {
"query_source": "support-log-redacted",
"labeler": "human-v2",
"corpus_snapshot": "docs-2026-07-01"
}
}
Grade, reason, evidence group, provenance가 있으면 binary·pairwise·listwise objective를 모두 만들 수 있습니다.
3. Positive를 만드는 여섯 경로
Human Qrel
가장 직접적이지만 비용이 큽니다. Pooling된 candidate를 label하면 retrieval bias가 들어가므로 BM25+dense+random 후보를 함께 제공합니다.
Click·Interaction Log
실제 intent를 반영하지만 position, UI, exposure, popularity bias가 있습니다. Click하지 않았다고 irrelevant는 아닙니다.
QA Pair
Question의 answer span을 담은 passage를 positive로 둡니다. String match만 쓰면 우연한 answer mention과 실제 근거를 혼동합니다.
Citation·Link
논문 citation, issue→documentation link, query→resolved article을 weak supervision으로 쓸 수 있습니다. Link의 의미가 endorsement인지 반박인지 확인합니다.
Adjacent Context
문서의 한 구간으로 다른 구간을 찾는 inverse cloze류 self-supervision입니다. 같은 document style을 학습해 topic locality에는 좋지만 실제 query-document 비대칭과 다를 수 있습니다.
LLM Synthetic Query
Passage를 주고 답할 수 있는 query를 생성합니다. Coverage를 빠르게 늘리지만 teacher style, 지나치게 명시적인 wording, hallucinated premise를 audit해야 합니다.
4. Negative Difficulty Ladder
Level 0 random corpus negative
Level 1 same language/domain random
Level 2 BM25 lexical hard negative
Level 3 current dense model ANN hard negative
Level 4 cross-encoder high-score but judged nonrelevant
Level 5 adversarial minimal pair / contradiction / stale version
모든 example을 Level 5로 만들면 noise와 overfitting이 커질 수 있습니다. Easy negative도 global space를 유지하는 데 필요합니다.
5. BM25 Hard Negative
Query token을 공유하지만 답은 없는 문서를 찾습니다.
query: "제품 3.2 지원 종료일"
negative: "제품 3.2 출시일과 기능"
Lexical shortcut를 깨는 데 유용합니다. 단, BM25 상위 unjudged 문서가 실제 relevant일 가능성이 큽니다.
6. Dense/ANN Hard Negative
현재 model로 corpus를 검색하고 positive가 아닌 상위 문서를 고릅니다.
for query in queries:
hits = index.search(encode_query(query.text), top_k=200)
candidates = [
hit for hit in hits
if hit.document_id not in known_positive_ids[query.id]
]
Model이 헷갈리는 경계를 직접 학습하지만 self-confirming bias가 있습니다. 한 model의 blind spot만 반복하지 않도록 BM25, 서로 다른 embedding, teacher ranker source를 섞습니다.
7. Positive-aware Mining
Positive와 너무 비슷하거나 teacher가 positive보다 높게 평가한 후보는 제거하거나 relabel합니다.
keep negative h if:
dense_score(q,h) is high
AND teacher_relevance(q,h) < threshold
AND teacher_relevance(q,d+) - teacher_relevance(q,h) >= margin
Teacher margin이 작은 후보는 ambiguous pool로 보내 human audit에 우선 배정합니다.
8. False Negative가 만드는 Gradient
실제로 relevant인 (d_f)를 negative로 넣으면 InfoNCE는 다음을 강요합니다.
sim(q, true positive) ↑
sim(q, unlabeled true positive d_f) ↓
여러 표현의 정답을 한 좁은 canonical wording으로 몰아 generalization을 해칠 수 있습니다.
False negative 유형:
- qrel 누락
- duplicate·near-duplicate
- 같은 문서의 answer-bearing sibling chunk
- 번역·cross-lingual equivalent
- 최신 replacement document
- partial/multi-hop evidence
- personalization에 따라 relevant인 item
9. 최근의 데이터 품질 교훈
2025년 Hard Negatives, Hard Lessons는 BGE training collection의 일부 dataset을 제거했을 때 data가 2.35배 줄었는데도 BEIR nDCG@10이 1 point 올랐다고 보고했습니다. LLM으로 false negative를 찾아 relabel한 실험에서도 E5와 Qwen 기반 retriever·reranker가 개선됐습니다.
이 결과를 “LLM label이면 해결”로 읽으면 안 됩니다. 더 중요한 메시지는 다음입니다.
more pairs ≠ more useful supervision
dataset source별 contribution과 label error를 측정하라
10. In-batch Collision 처리
Batch 안의 d_j+가 q_i에도 positive일 수 있습니다.
valid_negative_mask[i, j] = (
document_ids[j] not in all_positive_ids[query_ids[i]]
and not same_duplicate_group(i, j)
)
Invalid negative logit을 denominator에서 mask합니다. Document ID만 다르고 content hash가 같은 duplicate도 검사합니다.
11. Multi-dataset Mixture
Dataset마다 positive의 의미와 난이도가 다릅니다.
mixture:
qa_retrieval:
weight: 0.35
positive: answer_support
semantic_similarity:
weight: 0.15
positive: paraphrase
code_search:
weight: 0.20
positive: solves_intent
multilingual_bitext:
weight: 0.15
positive: translation
in_domain:
weight: 0.15
positive: human_qrel
Raw row 수에 비례해 sampling하면 가장 큰 dataset이 objective를 사실상 결정합니다. Temperature sampling 또는 capped quota를 사용하고 batch별 task를 log합니다.
12. Synthetic Query Quality Gate
Passage에서 query를 만들 때 다음을 필터링합니다.
- Query가 passage 없이도 상식으로 풀리는가?
- Passage가 query의 모든 전제를 실제로 지지하는가?
- 답 phrase를 그대로 복사해 lexical match가 너무 쉬운가?
- 너무 모호해 여러 문서가 모두 positive인가?
- 실제 사용자 query style과 길이를 닮았는가?
- 개인 정보·저작권·비공개 데이터 사용 정책을 통과하는가?
Round-trip 검증:
passage → synthetic query
query → retrieve corpus
teacher/human → positive really answers?
생성 model, prompt, seed, filtering model version을 provenance에 남깁니다.
13. Temporal·Source-aware Split
Random split은 같은 template과 문서 revision을 양쪽에 둡니다.
train: product docs before 2026-01
dev: 2026-01..03
test: 2026-04..06 and unseen product families
Group key 후보:
- query session/intent cluster
- canonical document와 revisions
- duplicate hash
- source domain·repository
- product/entity
- time
Generalization claim에 맞는 group을 선택합니다.
14. Negative Curriculum
초기 model에 최고 난이도 negative만 주면 label noise에 끌릴 수 있습니다.
stage 1: random + cross-batch diversity
stage 2: BM25 + first dense mining
stage 3: refreshed ANN hard negatives + teacher filtering
stage 4: domain adversarial and temporal negatives
Dynamic mining은 model checkpoint와 corpus snapshot을 고정해 재현합니다. 매 step 실시간 index가 바뀌면 experiment가 비결정적이 됩니다.
15. Human Audit Sampling
모든 pair를 검수하기 어렵다면 다음을 우선합니다.
- positive와 hard negative의 teacher margin이 작음
- 여러 teacher가 불일치
- top-k boundary에서 rank flip
- new language/domain/source
- critical compliance query
- very high loss example
- duplicate detector가 애매함
Labeler agreement와 adjudication 결과를 data version에 포함합니다.
16. Dataset Ablation
각 source를 하나씩 빼서 보는 leave-one-dataset-out 실험:
full mixture 0.512 nDCG@10
- weak click logs 0.519
- synthetic FAQ 0.508
- multilingual bitext 0.497 on cross-lingual slice
- in-domain human qrels 0.481 on domain slice
예시처럼 dataset은 평균과 slice에 다른 영향을 줍니다. 전체 평균만으로 제거하지 않습니다.
17. Data Manifest
dataset:
id: embed-train-v7
corpus_snapshot: docs-2026-07-01
query_count: 182000
pair_count: 2400000
grade_schema: relevance-v3
sources:
- name: human_qrels
revision: v5
license: internal-approved
- name: synthetic_queries
generator: pinned-model
prompt_sha256: "..."
negatives:
miner: dense-v4
corpus_sha256: "..."
teacher: cross-encoder-v6
false_negative_filter: v2
splits:
strategy: query+document-family+time
seed: 17
Weight 파일과 함께 이 manifest가 있어야 학습을 설명할 수 있습니다.
18. 체크리스트
- Positive의 의미를 task별로 정의했다.
- Binary label 외에 grade·reason·provenance를 저장한다.
- Random·lexical·dense·adversarial negative를 섞는다.
- In-batch duplicate와 multi-positive collision을 mask한다.
- Hard negative의 false-negative rate를 표본 감사했다.
- Teacher score와 human truth를 구분한다.
- Synthetic query가 실제 traffic style과 닮았는지 본다.
- Query·document family·time leakage를 막았다.
- Dataset source별 leave-one-out ablation을 수행한다.
- Mining checkpoint·corpus·prompt를 versioning한다.
스스로 확인하기
- Topic-relevant 문서를 answer-bearing retrieval의 hard negative로 둘 수 있는 이유는 무엇인가?
- Dense model이 뽑은 최고-score negative만 쓰면 어떤 두 위험이 있는가?
- In-batch negative에서 duplicate group을 mask해야 하는 이유는 무엇인가?
- LLM-generated query와 human query의 distribution 차이를 어떻게 측정할 수 있는가?
- Random pair split 대신 temporal/source-aware split이 필요한 연구 질문은 무엇인가?
다음 글에서는 DPR, ANCE, RocketQA, Contriever, RetroMAE, E5로 이어지는 dense retrieval 학습 계보를 하나의 recipe로 정리합니다.
참고자료
- Approximate Nearest Neighbor Negative Contrastive Learning for Dense Text Retrieval
- RocketQA: Cross-batch Negatives, Denoised Hard Negatives and Data Augmentation
- Hard Negatives, Hard Lessons
- Negative Sampling Techniques in Information Retrieval: A Survey
- Improving Text Embeddings with Large Language Models