Field Log · Entry
Reranker 학습 심화: Ranking Loss·Distillation·Calibration (8/14)
이번 글의 결론
- Loss는 architecture보다 label·candidate list·evaluation metric의 구조에 맞춰 고릅니다.
- Pointwise BCE는 강한 baseline, pairwise logistic은 hard preference, listwise softmax는 query 내부 경쟁을 직접 학습하는 데 유용합니다.
- Distillation은 hard label뿐 아니라 teacher의 score margin·grade distribution·permutation을 전달합니다. Teacher가 student보다 실제로 강하지 않으면 이득을 기대하기 어렵습니다.
- Ranking만 필요하면 score의 절대값은 중요하지 않을 수 있지만 threshold·fallback·confidence routing에는 calibration이 필수입니다.
- Training template, tokenizer, truncation, candidate mixture가 serving과 다르면 더 좋은 loss도 distribution mismatch를 이기지 못합니다.
앞 글에서 actual retriever candidate와 graded label을 만들었습니다. 이제 같은 dataset에서 무엇을 직접 최적화할지 정합니다.
data contract
query-grouped candidates + labels + provenance
↓
objective
point / pair / list / distillation / multi-task
↓
score
raw ranking signal
↓
optional calibration
threshold·routing에 쓸 probability-like value
1. 먼저 Training Target을 분리한다
Reranker training에는 서로 다른 target이 섞일 수 있습니다.
| target | 예 | 의미 |
|---|---|---|
| Hard relevance | 0/1, 0...3 | Human·rule이 정한 grade |
| Pair preference | d_i > d_j | 상대 순서 |
| Teacher scalar | 4.71, 0.82 | 강한 model의 score |
| Teacher distribution | [0.02, 0.13, 0.85] | 불확실성 포함 grade |
| Teacher permutation | [d3,d1,d2] | 목록 전체 ordering |
| Downstream utility | answer EM·support delta | Generator에 실제 유용함 |
Loss 하나로 모두 같은 의미처럼 처리하지 않습니다. Provenance와 scale을 보존한 뒤 objective별 adapter를 둡니다.
2. Pointwise BCE Baseline
Binary label y ∈ {0,1}와 single logit s를 사용합니다.
L_BCE = -y log σ(s) - (1-y) log(1-σ(s))
PyTorch에서는 numerical stability를 위해 binary_cross_entropy_with_logits를 씁니다.
import torch
import torch.nn.functional as F
def pointwise_bce_loss(
logits: torch.Tensor,
labels: torch.Tensor,
weights: torch.Tensor | None = None,
) -> torch.Tensor:
losses = F.binary_cross_entropy_with_logits(
logits.float(),
labels.float(),
reduction="none",
)
if weights is not None:
losses = losses * weights.float()
return losses.mean()
Grade를 Binary로 접을 때 잃는 것
grade 3 → 1
grade 2 → 1
grade 1 → 0
grade 0 → 0
Direct answer와 supporting evidence, topic-only와 contradiction의 차이를 잃습니다. Binary decision이 제품 목표에 맞는지 확인합니다.
Class Imbalance
Candidate 100개 중 positive가 1개라면 negative가 loss를 지배합니다.
대응:
- Query당 negative sampling 수를 제한합니다.
- Positive weight를 사용합니다.
- Hard·easy negative mixture를 제어합니다.
- Query별 loss를 평균한 뒤 query 간 평균을 냅니다.
마지막 방식은 candidate가 많은 query가 전체 gradient를 지배하지 않게 합니다.
3. Graded Pointwise Objective
Grade 0...3을 multiclass로 예측할 수 있습니다.
z_i = [z_0, z_1, z_2, z_3]
L_grade = CrossEntropy(z_i, y_i)
Ranking score는 expected grade로 만들 수 있습니다.
score_i = Σ_g g × P(g | q, d_i)
일반 CE는 class 사이의 ordinal distance를 모릅니다. Grade 3을 2로 틀린 것과 0으로 틀린 것을 같은 “오분류”로 볼 수 있습니다.
대안:
- ordinal regression
- cumulative binary targets:
y≥1,y≥2,y≥3 - expected-grade regression
- pairwise grade ordering 추가
Annotation rubric이 noisy하면 복잡한 ordinal head가 이득인지 validation으로 확인합니다.
4. Pairwise Logistic Loss
같은 query에서 grade가 높은 positive와 낮은 negative를 고릅니다.
Δs = s_positive - s_negative
L_pair = softplus(-Δs)
= -log sigmoid(Δs)
def pairwise_logistic_loss(
positive_scores: torch.Tensor,
negative_scores: torch.Tensor,
pair_weights: torch.Tensor | None = None,
) -> torch.Tensor:
losses = F.softplus(-(positive_scores - negative_scores))
if pair_weights is not None:
losses = losses * pair_weights
return losses.mean()
Pair Weight
다음 signal로 pair 중요도를 조절할 수 있습니다.
grade gap
× label confidence
× expected ΔnDCG
× traffic or business weight
하지만 traffic weight를 넣으면 head query에 과적합할 수 있습니다. General quality와 weighted business metric을 따로 report합니다.
Margin을 무한히 키우지 않는다
Ranking에는 순서만 맞으면 되지만 logistic loss는 더 큰 margin을 계속 선호할 수 있습니다. Regularization, label noise, calibration에 영향을 줍니다.
5. Listwise Softmax Loss
한 query의 candidate score를 함께 normalize합니다.
p_model(i|q) = exp(s_i/τ_s) / Σ_j exp(s_j/τ_s)
p_label(i|q) = exp(y_i/τ_y) / Σ_j exp(y_j/τ_y)
L_list = -Σ_i p_label(i|q) log p_model(i|q)
def listwise_softmax_loss(
scores: torch.Tensor, # [batch, candidates]
grades: torch.Tensor, # [batch, candidates]
valid_mask: torch.Tensor, # [batch, candidates]
*,
score_temperature: float = 1.0,
label_temperature: float = 1.0,
) -> torch.Tensor:
minus_inf = torch.finfo(scores.dtype).min
masked_scores = scores.masked_fill(~valid_mask, minus_inf)
masked_grades = grades.masked_fill(~valid_mask, minus_inf)
log_probs = F.log_softmax(masked_scores / score_temperature, dim=-1)
targets = F.softmax(masked_grades / label_temperature, dim=-1)
losses = -(targets * log_probs).masked_fill(~valid_mask, 0.0).sum(dim=-1)
return losses.mean()
Temperature의 의미
- 낮은 label temperature: 최고 grade에 mass가 집중됩니다.
- 높은 label temperature: lower-grade candidate도 signal을 받습니다.
- 낮은 score temperature: model distribution이 sharp해집니다.
Temperature는 “성능을 올리는 마법 숫자”가 아니라 target distribution의 모양입니다. Grid search를 validation nDCG와 calibration 모두에서 봅니다.
Multiple Positive
Grade 3 문서가 여러 개면 label distribution이 positive들에 나뉩니다. 하나만 정답인 softmax보다 자연스럽지만, duplicate가 많으면 같은 evidence cluster가 probability mass를 독점할 수 있습니다. Canonical cluster weight가 필요할 수 있습니다.
6. Approximate Metric-aware Weighting
nDCG 자체는 rank change에 불연속적입니다. LambdaRank식으로 pair swap의 |ΔnDCG|를 pair loss weight로 사용할 수 있습니다.
L_lambda-pair
= Σ_(i,j) |ΔnDCG_ij| × softplus(-(s_i - s_j))
Top-5 metric이라면 cutoff 밖의 swap weight는 작거나 0입니다. Training compute를 top-heavy error에 집중합니다.
주의할 점:
- Current score가 정한 rank에 따라 weight가 변합니다.
- Grade tie와 unjudged candidate를 처리해야 합니다.
- Candidate list가 너무 작으면 serving top-100 distribution을 반영하지 못합니다.
- Metric convention과 cutoff를 evaluation과 맞춥니다.
7. Multi-objective Loss를 섞는 방법
L_total
= α L_point
+ β L_pair
+ γ L_list
+ δ L_distill
각 loss의 raw scale이 다르므로 coefficient 값만 비교하면 안 됩니다.
기록할 것:
- batch당 각 objective가 활성화되는 비율
- 각 loss 평균과 gradient norm
- shared backbone에 미치는 conflict
- objective 하나씩 제거한 ablation
Curriculum
한 예시는 다음과 같습니다.
Stage 1: pointwise hard labels로 안정적인 relevance boundary
Stage 2: hard pair로 near-miss discrimination
Stage 3: listwise·metric-aware loss로 top-k ordering
반드시 이 순서가 최선은 아닙니다. 처음부터 listwise가 안정적인 dataset도 있습니다. Curriculum의 이득을 same-step budget으로 비교합니다.
8. Knowledge Distillation의 세 Level
Hard Label Distillation
Teacher가 grade나 binary label을 만듭니다.
teacher(q,d) → grade 0...3
student learns CE
쉽지만 teacher uncertainty를 버립니다.
Score Distillation
Teacher logit 또는 probability distribution을 맞춥니다.
L_KD = T² KL(
softmax(z_teacher / T)
||
softmax(z_student / T)
)
T²는 temperature에 따른 gradient scale을 보정하는 흔한 convention입니다. Scalar score라면 MSE나 pairwise margin matching을 사용할 수 있습니다.
Permutation Distillation
Teacher LLM이 후보 목록 순서를 만들고 student가 그 순열을 학습합니다.
teacher list: [d7, d2, d9, d1, ...]
→ pair preferences or listwise target
→ smaller student ranker
RankGPT는 permutation distillation을 통해 작은 specialized model로 ranking 능력을 옮기는 실험을 포함했고, RankZephyr도 강한 teacher의 listwise behavior를 학습하는 흐름에 속합니다.
9. Teacher가 정말 더 강한지 확인한다
Teacher size가 크다는 사실은 ranking quality를 보장하지 않습니다.
2025년 Distillation versus Contrastive Learning 연구는 같은 data에서 여러 student size와 architecture를 비교해, 더 강한 teacher에서 distill할 때 일반적으로 contrastive hard-label training보다 in-domain·out-of-domain ranking이 좋았다고 보고했습니다. 반면 같은 capacity 수준의 teacher에서는 같은 이점이 나타나지 않았습니다.
실전 gate:
teacher nDCG on frozen candidates
> student hard-label baseline
teacher robustness on target slices
> acceptable
teacher label cost
< expected serving/training benefit
Teacher가 한국어 temporal query에서 약하면 그 slice를 student에 대량 복제하지 않습니다.
10. Teacher Score Scale을 맞춘다
서로 다른 teacher를 섞으면 score 범위가 다릅니다.
Cross-Encoder teacher: logits [-8, 12]
LLM grade teacher: integers [0, 3]
Behavior teacher: propensity-corrected CTR [0, 1]
Raw scalar를 평균내지 않습니다.
방법:
- Query 내부 rank나 percentile로 변환
- Grade distribution으로 mapping
- Pair preference만 추출
- Teacher별 calibration 후 ensemble
- Confidence-weighted mixture
Source별 target을 별도 head나 loss로 유지하는 것도 가능합니다.
11. Synthetic Rationale는 Feature가 아니라 Artifact일 수 있다
Reasoning teacher가 relevance rationale를 생성할 수 있습니다.
"문서가 S2와 shutdown을 언급하고 승인 상태를 명시하므로 grade 3"
활용:
- Human audit를 빠르게 함
- Error taxonomy 자동 분류
- Reasoning reranker SFT data
- Pair preference의 설명
주의:
- 결론을 정한 뒤 그럴듯한 설명을 만들 수 있습니다.
- Hallucinated evidence span이 들어갈 수 있습니다.
- Rationale style을 student가 외우고 relevance는 못 배울 수 있습니다.
- 공개 reasoning trace에는 민감한 document text가 포함될 수 있습니다.
Rationale와 label 정확도를 별도로 검증합니다.
12. Train-Serve Parity
다음 값이 하나라도 다르면 input distribution이 바뀝니다.
input_contract:
tokenizer_revision: abc123
template_version: rerank-template-v5
max_length: 512
truncation: title_plus_query_aware_window
document_fields: [title, status, effective_date, body]
field_order: fixed
unicode_normalization: NFC
candidate_source: hybrid-v6-top50
흔한 Mismatch
- Training은 title+body, serving은 body만 사용
- Training은 512 token, serving engine은 384 token
- Training negative는 BM25, serving은 dense-only
- Training은 window max, serving은 head truncation
- Training query는 standalone, serving은 대화의 마지막 utterance만 사용
Loss 개선보다 먼저 고칠 문제입니다.
13. Calibration은 Ranking과 다른 문제다
같은 query에서 monotonic transform은 순서를 바꾸지 않습니다.
rank(s) = rank(sigmoid(s))
그러나 다음 정책에는 절대값이 필요합니다.
score < threshold → no evidence / abstain
score gap small → large reranker로 escalate
score high → cache or skip verifier
Raw logit을 probability로 오해하면 routing이 깨집니다.
Temperature Scaling
Binary logit s를 validation set에서 scalar temperature T>0로 보정합니다.
p = sigmoid(s / T)
T는 validation negative log-likelihood를 최소화하도록 학습합니다. Monotonic이므로 ranking은 같고 confidence sharpness만 바뀝니다.
Platt Scaling
p = sigmoid(a s + b)
Slope와 bias를 학습합니다. a>0이면 순서를 보존합니다.
Isotonic Regression
Non-parametric monotonic mapping입니다. Data가 적으면 overfit하고 piecewise constant라 tie를 만들 수 있습니다.
14. Calibration을 어떻게 평가하는가
Reliability Bin
Prediction을 confidence bin으로 나눕니다.
predicted 0.8~0.9인 pair 중
실제 relevant 비율은 얼마인가?
ECE
Expected Calibration Error는 bin별 confidence와 accuracy 차이를 가중 평균합니다. Bin 정의에 민감하므로 ECE 하나만 보지 않습니다.
Brier Score·NLL
Probability quality를 proper scoring rule로 측정합니다.
Slice Calibration
전체 평균이 좋아도 다음 slice가 깨질 수 있습니다.
- 한국어 vs 영어
- short vs long document
- in-domain vs new domain
- top retrieval rank vs tail candidate
- answerable vs no-answer
Threshold는 운영 slice별 error cost를 반영합니다.
15. Score Fusion도 학습 문제다
Retriever와 reranker score를 결합하려면 validation data에서 weight를 학습할 수 있습니다.
final_score
= w₁ × calibrated_reranker
+ w₂ × normalized_bm25
+ w₃ × normalized_dense
+ w₄ × freshness
+ w₅ × authority
Linear model이나 LambdaMART를 사용합니다. Reranker score만 쓰는 baseline과 비교해야 합니다.
Retriever score를 남기는 것이 도움이 되는 경우:
- Reranker가 out-of-domain에서 불안정함
- Exact lexical ID match가 강한 signal임
- Freshness·authority 같은 external feature가 필요함
반대로 잘못 normalize한 score fusion은 strong reranker를 희석할 수 있습니다.
16. Training Run Manifest
run:
id: reranker-train-2026-07-20-04
base_model: multilingual-cross-encoder-base
base_revision: PINNED_COMMIT
dataset: support-reranker-ds-v12
input_contract: rerank-template-v5
objectives:
pointwise_bce: 0.4
pairwise_logistic: 0.3
listwise_softmax: 0.3
pair_sampling: hard-types-balanced-v3
list_size: 16
teacher:
model: rank-teacher-v7
target: query-normalized-soft-scores
temperature: 2.0
optimizer:
learning_rate: 2.0e-5
weight_decay: 0.01
selection_metric: ndcg_at_10
calibration:
method: temperature_scaling
dataset: calibration-v3
Calibration set은 training·model selection test와 분리하는 편이 안전합니다.
17. 학습 체크리스트
- Objective가 label 형태와 query grouping을 보존한다.
- Pair sampling이 easy negative에 지배되지 않는다.
- Listwise padding과 unjudged candidate가 mask된다.
- Teacher가 target slice에서 student baseline보다 실제로 강하다.
- Teacher model·prompt·temperature·score normalization을 고정했다.
- Loss mixture의 gradient와 ablation을 기록한다.
- Training과 serving의 template·max length·candidate source가 같다.
- Ranking score와 calibrated probability를 이름부터 구분한다.
- Threshold는 no-answer·language·domain slice에서 검증한다.
- Model checkpoint와 calibration artifact를 함께 versioning한다.
스스로 확인하기
- Pointwise BCE와 listwise softmax가 candidate를 normalize하는 범위는 어떻게 다른가?
- Teacher가 student와 같은 수준일 때 distillation 이득이 약할 수 있는 이유는 무엇인가?
- Temperature scaling이 ranking metric을 바꾸지 않으면서 calibration을 바꿀 수 있는 이유는 무엇인가?
- Training candidate가 BM25이고 serving candidate가 dense일 때 어떤 mismatch가 생기는가?
- Retriever score와 reranker score를 raw 상태로 더하면 안 되는 이유는 무엇인가?
다음 글에서는 model gain을 착각하지 않도록 candidate ceiling, nDCG·MRR, paired significance, efficiency Pareto, RAG end-to-end metric을 하나의 evaluation protocol로 묶습니다.
참고자료
- RankT5: Fine-Tuning T5 for Text Ranking with Ranking Losses
- Distillation versus Contrastive Learning: How to Train Your Rerankers
- Is ChatGPT Good at Search? — Permutation Distillation
- RRADistill: Distilling LLMs’ Passage Ranking Ability for Long-Tail Queries
- Sentence Transformers Cross-Encoder Training Overview