하이브리드 검색
읽는 데 약 54분분 걸린다, 12절에 12개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.10판을 번역한 것이다. 원문 읽기
이 장을 마치면 어휘 기반 순위와 의미 기반 순위를 하나로 결합할 수 있다. 정규화한 점수를 더하거나 역순위 결합(reciprocal rank fusion)을 쓰면 된다. 각 순위가 얼마나 반영될지는 학습 질의로 조정한다. 그리고 테스트 질의에서 대응 표본 검정을 수행하여, 결합한 순위가 두 입력 중 더 나은 쪽을 이기는지 판단할 수 있다.
상점은 가구와 생활용품 카탈로그를 두 가지 검색기로 검색하며, 1장에서는 두 검색기를 하나의 순위로 결합했다. 이 결합은 의미 기반 검색 단독보다 나은 결과를 내지 못했다. 테스트 질의에서 nDCG@10은 결합이 0.812, 의미 기반 검색이 0.830였다. 3장의 검정으로는 이 차이가 어느 쪽에 유리한지 확정할 수 없다. 따라서 상점은 더 나은 조합이 의미 기반 검색을 이길 수 있는지 알아야 한다. 의미 기반 검색은 지금까지의 최고 순위기이므로 넘어야 할 기준이다.
그래서 이 장은 먼저 BM25와 의미 기반 검색이 서로 다른 질의에서 실패하는지 묻는다. BM25는 bm25s의 기본 설정에서 어간 추출을 하지 않은 이 책의 기준선이며, 의미 기반 검색은 공개 모델 Snowflake/snowflake-arctic-embed-m-v1.5로 임베딩한다. 결합은 두 검색기가 서로 다른 질의에서 실패할 때만 도움이 될 수 있으므로, 그다음에 두 가지 결합 방식을 조정한다.
산업 현장의 검색 시스템은 흔히 이 둘을 함께 쓴다. 어떤 의미 기반 상품 검색 모델은 "애드혹 상품 검색에서 어휘 검색 엔진을 보완하도록" 만들어졌으며(Nigam et al., 2019), 어떤 소셜 네트워크의 검색 엔진은 임베딩 검색과 키워드 매칭을 함께 사용하여 문서의 점수를 매긴다(Huang et al., 2020).
상점에는 조정용 학습 질의가 50개, 보고용 테스트 질의가 30개 있다. 이 장은 각 검색기가 이기는 질의를 찾고 각 검색기를 단독으로 점검한다. 이어서 두 가지 결합(blend)을 만들고 가중치를 조정한다. 결합은 어휘 기반 순위와 의미 기반 순위를 융합하는 방법이며, 가중치는 각 순위가 얼마나 반영될지를 정한다. 모든 분석과 조정 단계는 학습 질의에서 수행한다. 이 장은 테스트 질의에서 두 가지 비교를 마지막에 한 번만 수행하도록 계획한다. 조정을 마친 각 결합, 곧 가중합과 가중 역순위 결합을 의미 기반 검색과 비교한다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Find the queries each retriever wins
Hybrid retrieval combines the rankings of a lexical and a semantic retriever into one ranking. Combining rankings is called fusion. Fusion can only help if the two retrievers fail on different queries: if both put poor products first for a query, no mix of their rankings fixes it. Published studies find that they do. Embeddings miss rare entities and selective keywords that BM25 matches (chapter 6), and on a dataset built to test the limits of one embedding per text, BM25 finds what embeddings miss but loses most of its score when words are replaced with synonyms (chapter 1). So the first check is per query, not on average.
Score both of the store's retrievers by nDCG@10 on every train query, keeping each one's top 100.
1"""Scores BM25 and semantic retrieval on each train query and counts the queries each one wins, ties included.2The prose's point rests on the win counts and on the mean of the better score per query."""3import numpy as np45from lib.lexical import LexicalSearch6from lib.metrics import evaluate7from lib.semantic import SemanticSearch8from lib.store import load_products, load_queries, qrels910products, queries, judgments = load_products(), load_queries("train"), qrels("train")11bm25 = LexicalSearch(products).run(queries, k=100)12semantic = SemanticSearch().run(queries, k=100)13bm25_scores, semantic_scores = evaluate(bm25, judgments)["ndcg@10"], evaluate(semantic, judgments)["ndcg@10"]1415print("train queries:", len(queries))16print(f"bm25 ndcg@10: {bm25_scores.mean():.3f}")17print(f"semantic ndcg@10: {semantic_scores.mean():.3f}")18# rounded to 3 places, so differences that are float noise count as ties19lead = (bm25_scores - semantic_scores).round(3) # per train query; above 0 means BM25 wins20print("bm25 better:", (lead > 0).sum())21print("semantic better:", (lead < 0).sum())22print("tied:", (lead == 0).sum())23print(f"better of the two, chosen per query: {np.maximum(bm25_scores, semantic_scores).mean():.3f}")24has_digit = queries["query"].str.contains(r"\d")25print("queries with a digit:", has_digit.sum())26print("queries with a digit, bm25 better:", (lead[has_digit] > 0).sum())27print()28print("queries where bm25 leads by 0.1 or more:", (lead >= 0.1).sum())29print(queries.loc[lead[lead >= 0.1].index, "query"].to_string())
python bm25-semantic-wins-by-query.pytrain queries: 50
bm25 ndcg@10: 0.695
semantic ndcg@10: 0.772
bm25 better: 15
semantic better: 31
tied: 4
better of the two, chosen per query: 0.802
queries with a digit: 5
queries with a digit, bm25 better: 1
queries where bm25 leads by 0.1 or more: 6
query_id
44 chrome shower head and valve
146 laundry vanity cabinet
277 barstool patio sets
313 malachi sled
359 french molding
432 butcher block island
Neither retriever wins every query. Semantic retrieval averages 0.772 nDCG@10 against BM25's 0.695, but BM25 still wins 15 train queries to semantic retrieval's 31, and 4 tie.
If you could choose the better of the two for each query, the mean would be 0.802. That isn't a ceiling for fusion, which mixes the lists rather than choosing one, but it shows what the differences could be worth.
Next, see whether the two lists hold different products, and what share of each query's exact products (those the judges graded as fully matching) each list finds:
1"""Measures how much BM25's and semantic retrieval's top 10s overlap, and the share of each query's exact products2that each list, and their union, holds at depths 100 and 20. The prose's point rests on the union's shares at both depths."""3import numpy as np45from lib.lexical import LexicalSearch6from lib.metrics import recall_at_k7from lib.semantic import SemanticSearch8from lib.store import load_products, load_queries, qrels910products, queries, judgments = load_products(), load_queries("train"), qrels("train")11bm25 = LexicalSearch(products).run(queries, k=100)12semantic = SemanticSearch().run(queries, k=100)1314shared = [len(set(bm25[query_id][:10]) & set(semantic[query_id][:10])) for query_id in queries.index]15print(f"products in both top 10s, mean: {np.mean(shared):.1f}")161718def share_retrieved(run):19 """The share of each query's exact products that the run's list holds, averaged over queries."""20 # k is the whole list, so this is the share of exact products (grade 2) anywhere in it21 shares = [recall_at_k(ranking, judgments[query_id], k=len(ranking)) for query_id, ranking in run.items()]22 return np.mean(shares)232425for depth in [100, 20]:26 lists = {"bm25": {query_id: ranking[:depth] for query_id, ranking in bm25.items()},27 "semantic": {query_id: ranking[:depth] for query_id, ranking in semantic.items()}}28 # the union in first-seen order, without repeats29 lists["union"] = {query_id: list(dict.fromkeys(lists["bm25"][query_id] + lists["semantic"][query_id]))30 for query_id in queries.index}31 for name, run in lists.items():32 print(f"{name} top {depth}, share of exact products retrieved: {share_retrieved(run):.3f}")
python overlap-and-union-recall.pyproducts in both top 10s, mean: 3.7
bm25 top 100, share of exact products retrieved: 0.672
semantic top 100, share of exact products retrieved: 0.759
union top 100, share of exact products retrieved: 0.810
bm25 top 20, share of exact products retrieved: 0.297
semantic top 20, share of exact products retrieved: 0.353
union top 20, share of exact products retrieved: 0.445
The two top 10s share 3.7 products on average, so most of each is missing from the other. Fusion can't rank a product neither list holds, so each list's depth caps what fusion can reach. The union beats either list at both depths:
| Share of exact products retrieved | Top 20 | Top 100 |
|---|---|---|
| BM25 | 0.297 | 0.672 |
| Semantic retrieval | 0.353 | 0.759 |
| Union of both | 0.445 | 0.810 |
Two train queries show the kinds of failure:
1"""Prints the top 5 products of BM25 and semantic retrieval for two train queries, with their judgments, and counts2the exact products in each top 10. The prose's point rests on those exact counts and on the two spellings of 7qt."""3from lib.lexical import LexicalSearch4from lib.semantic import SemanticSearch5from lib.store import load_products, load_queries, product_text, qrels67LABELS = {2: "exact", 1: "partial", 0: "irrelevant"}8products, queries, judgments = load_products(), load_queries("train"), qrels("train")9bm25 = LexicalSearch(products).run(queries, k=10)10semantic = SemanticSearch().run(queries, k=10)11text = product_text(products)12# the size written as one token, `7qt`13print("products containing 7qt:", text.str.contains(r"\b7qt\b", case=False).sum())14# the size written apart, `7 qt`15print("products containing 7 qt:", text.str.contains(r"\b7 qt\b", case=False).sum())1617for query_id in [432, 62]: # butcher block island, 7qt slow cooker18 query = queries.at[query_id, "query"]19 for name, run in [("bm25", bm25), ("semantic", semantic)]:20 # grade 2 is exact, 1 partial, 0 irrelevant; None for a product nobody judged21 grades = [judgments[query_id].get(product_id) for product_id in run[query_id]]22 print()23 print(f"exact in {name} top 10 for {query}: {grades.count(2)}")24 for product_id, grade in list(zip(run[query_id], grades))[:5]:25 print(f" {LABELS.get(grade, 'unjudged'):<10} {products.at[product_id, 'name'][:55]}")
python two-queries-two-winners.pyproducts containing 7qt: 0
products containing 7 qt: 9
exact in bm25 top 10 for butcher block island: 9
exact carol kitchen island with butcher block top
exact brunton kitchen island with butcher block top
partial brunton kitchen cart butcher block top
exact janigian kitchen island with butcher block
exact avelar kitchen island with butcher block
exact in semantic top 10 for butcher block island: 3
partial boosblock® prep table with butcher block top
partial boosblock® butcher block
partial prep table
partial pro chef kitchen cart with butcher block top
exact brunton kitchen island with butcher block top
exact in bm25 top 10 for 7qt slow cooker: 1
partial cuisinart 6.5 quart programmable slow cooker
partial midea 6.5 qt . slow cooker
partial delonghi cks1660d livenza programmable 6 qt . slow cook
partial nesco 1.5 qt . analog slow cooker
partial 360 cookware gourmet slow cooker
exact in semantic top 10 for 7qt slow cooker: 7
exact 7-qt . stay or go slow cooker
exact crock-pot 7 qt . slow cooker
exact zing 7 qt . digital slow cooker
exact black + decker 7 qt . digital slow cooker
exact crock-pot 7 qt . slow cooker
For butcher block island, BM25's top 10 holds 9 exact products to semantic retrieval's 3. BM25 rewards products whose text contains all three words: kitchen islands with butcher-block tops. Semantic retrieval ranks prep tables and carts with butcher-block tops near the top too, and the judges graded those partial: the right material, but not the island the query asks for.
For 7qt slow cooker it's the other way round: BM25's top 10 holds 1 exact and semantic retrieval's 7. The catalog has 0 products whose text contains 7qt and 9 that contain 7 qt, so BM25 matches only slow cooker and ranks cookers of every size, while semantic retrieval puts 7-quart cookers first.
Those are single queries: they show a kind of failure, not its frequency. The per-query count lists the 6 train queries where BM25 leads by 0.1 nDCG@10 or more. Most name a specific kind of product in two or more words that all have to match, and one, malachi sled, names a product line.
Chapter 1 found BM25 ahead on 2 of the 2 test queries that give a size in inches, yet of the 5 train queries that contain a digit, BM25 wins 1.
Working rule: Before you fuse, count per query where each retriever wins on your train queries, and check how many relevant products the union of their lists holds that the better one misses. Consider fusing when each wins a real share of queries and the union holds more relevant products than either list. That is necessary, not sufficient: next, check each retriever alone, and test the tuned blend on held-out queries before you adopt it.
융합하기 전에 각 검색기를 점검하라
각 검색기가 어디에서 우위인지 아는 것만으로는 충분하지 않다. 융합은 약한 입력을 포함해 모든 입력이 최종 순위에 영향을 미치게 하기 때문이다. 11개 데이터셋에서 하이브리드 검색을 연구한 결과는 "가장 약한 고리" 효과를 보고했다. 약한 검색기 하나가 융합 결과의 정확도를 크게 끌어내릴 수 있으므로, 융합 전에 각 검색기를 점검해야 한다(Wang et al., PVLDB 2026). 따라서 검색기별 평균 nDCG@10을 비교하고, 그 옆에 judged@10을 함께 놓는다. 그런 다음 질의별로 쌍체 검정을 사용해 비교한다. 두 검색기의 성능이 같다면 이 정도로 큰 평균 차이가 나타날 가능성은 얼마인가? 이 책에서 쓰는 검정은 순열 검정이며, 쌍체 t-검정을 함께 제시한다.
1장에서처럼 상호 순위 융합(RRF)으로 BM25와 의미 기반 검색을 융합한다. 각 상품은 각 순위에서 1 / (60 + 순위)점을 받고 두 순위에서 받은 점수를 합산하므로, 두 순위가 동등한 표를 갖는다. 그런 다음 학습 질의를 우세한 검색기에 따라 나누고, 융합 결과를 의미 기반 검색 단독과 비교한다.
1"""Compares BM25, semantic retrieval and their RRF fusion on the train queries, then splits the queries by which2retriever wins. The prose's point rests on the hybrid-minus-semantic lines, which give the net change, and on the mean3change within each winning group."""4from lib.fusion import reciprocal_rank_fusion5from lib.lexical import LexicalSearch6from lib.metrics import evaluate7from lib.semantic import SemanticSearch8from lib.significance import compare9from lib.store import load_products, load_queries, qrels1011products, queries, judgments = load_products(), load_queries("train"), qrels("train")12bm25 = LexicalSearch(products).run(queries, k=100)13semantic = SemanticSearch().run(queries, k=100)14hybrid = reciprocal_rank_fusion([bm25, semantic]) # k = 60 and equal votes, as in chapter 115bm25_scores, semantic_scores, hybrid_scores = (evaluate(run, judgments) for run in (bm25, semantic, hybrid))1617print(f"bm25 judged@10: {bm25_scores['judged@10'].mean():.3f}")18print(f"semantic judged@10: {semantic_scores['judged@10'].mean():.3f}")19for name, after, before in [("semantic minus bm25", semantic_scores, bm25_scores),20 ("hybrid minus semantic", hybrid_scores, semantic_scores)]:21 result = compare(after["ndcg@10"], before["ndcg@10"]) # paired by query22 print(f"{name}, mean ndcg@10: {result['mean difference']:.3f}")23 print(f"{name}, permutation p: {result['permutation p']:.3f}")24 print(f"{name}, t-test p: {result['t-test p']:.3f}")25print()2627# rounded to 3 places, so float noise can't make a query a win or a loss28change = (hybrid_scores["ndcg@10"] - semantic_scores["ndcg@10"]).round(3) # fusion against semantic alone29lead = (bm25_scores["ndcg@10"] - semantic_scores["ndcg@10"]).round(3) # above 0 means BM25 wins30for name, group in [("bm25 wins", lead > 0), ("semantic wins", lead < 0)]:31 print(f"{name}, queries: {group.sum()}")32 print(f"{name}, fusion better than semantic: {(change[group] > 0).sum()}")33 print(f"{name}, fusion worse than semantic: {(change[group] < 0).sum()}")34 print(f"{name}, mean change in ndcg@10: {change[group].mean():.3f}")
python fusion-gain-by-winning-retriever.pybm25 judged@10: 0.930
semantic judged@10: 0.964
semantic minus bm25, mean ndcg@10: 0.077
semantic minus bm25, permutation p: 0.003
semantic minus bm25, t-test p: 0.004
hybrid minus semantic, mean ndcg@10: 0.002
hybrid minus semantic, permutation p: 0.863
hybrid minus semantic, t-test p: 0.872
bm25 wins, queries: 15
bm25 wins, fusion better than semantic: 12
bm25 wins, fusion worse than semantic: 2
bm25 wins, mean change in ndcg@10: 0.101
semantic wins, queries: 31
semantic wins, fusion better than semantic: 5
semantic wins, fusion worse than semantic: 25
semantic wins, mean change in ndcg@10: -0.045
BM25의 judged@10은 0.930이고 의미 기반 검색은 0.964이다. 따라서 BM25의 상위 10개 결과에는 아무도 판정하지 않은 상품이 조금 더 많이 들어 있으며, 그런 상품이 점수를 낮출 수 있는 방식은 2장에서 다룬다. 의미 기반 검색은 nDCG@10에서 0.077만큼 앞서며, 순열 검정 p값은 0.003, t-검정 p값은 0.004이다. 테스트 질의에서도 3장은 같은 우위를 확립한다. 따라서 이 상점에는 강한 검색기와 약한 검색기가 있다.
우세한 검색기에 따라 나누면, 융합은 BM25가 우세한 질의에서는 평균적으로 도움이 되고 의미 기반 검색이 우세한 질의에서는 해가 된다.
| 해당 질의 | 질의 수 | 융합이 의미 기반 검색보다 나음 | 융합이 의미 기반 검색보다 나쁨 | nDCG@10 평균 변화 |
|---|---|---|---|---|
| BM25가 우세 | 15 | 12 | 2 | 0.101 |
| 의미 기반 검색이 우세 | 31 | 5 | 25 | -0.045 |
우세한 검색기로 질의를 묶으면 이 패턴이 처음부터 내장된다. BM25가 우세한 질의에서는 거의 어떤 혼합이든 도움이 되고, BM25가 지는 질의에서는 해가 되기 때문이다. 중요한 것은 모든 학습 질의에 걸친 순변화이다. 융합은 의미 기반 검색과 평균 0.002의 nDCG@10 차이를 보이며, 순열 검정 p값은 0.863이다. 이 질의들에서 동등한 표는 측정 가능한 이득을 주지 못한다.
이 분할은 어느 검색기가 우세한지 정하는 데 판정을 사용하므로 패턴을 진단할 뿐이며, 판정이 없는 실제 질의에서 검색기를 고르는 데는 쓸 수 없다.
작업 규칙: 융합하기 전에 학습 질의에서 각 검색기를 단독으로 judged@10과 쌍체 검정으로 점검하라. 한 검색기가 더 약하고 우세한 질의가 더 적다면 동등한 표를 주지 말라. 가중치를 주고 가중치를 조정하거나, 그 검색기를 제외하라. 동등한 표는 품질이 비슷한 두 검색기에 적합하다.
점수를 더하기 전에 정규화한다
더 약한 검색기, 즉 이 상점에서는 BM25에 더 작은 발언권을 주는 가장 직접적인 방법은 두 검색기의 점수에 가중치를 두어 더하는 것이다. 의미 점수에 α를 곱하고 BM25 점수에 (1 − α)를 곱해 더한다. 가중치의 합이 1인 합을 볼록 결합(convex combination), 또는 가중합이라고 한다. 이 방법은 점수의 척도가 비슷할 때만 제대로 동작하는데, 여기서는 그렇지 않다. BM25 점수는 고정된 범위가 없고 질의 단어의 수와 희소성에 따라 커지는 반면, 의미 검색의 점수인 코사인 유사도는 −1과 1 사이에 놓인다. 점수 정규화(score normalization)는 점수를 더하기 전에 질의마다 각 검색기의 점수를 다시 조정한다. 질의별 min-max 스케일링은 그 질의에서 순위가 매겨진 상품 가운데 가장 낮은 점수를 0으로, 가장 높은 점수를 1로 대응시킨다. 결합 함수를 다룬 한 연구는 이를 "문헌에서 사실상의 표준 방법"이라고 부르며 두 가지 대안을 시험한다(Bruch et al., 2023). 이론적 min-max는 관측된 최저값 대신 각 점수가 가질 수 있는 최저값을 쓴다. BM25는 0, 코사인은 −1이다. z-점수는 질의의 점수에서 평균을 빼고 표준편차로 나눈다. 예제들이 함께 쓰는 모듈 lib/blend.py은 각 방법을 몇 줄로 구현한다.
min-max(s) = (s − lowest score among the query's candidates) / (highest − lowest)
blend = α · min-max(similarity) + (1 − α) · min-max(BM25)
합을 계산하려면 순위를 매기는 모든 상품에 두 점수가 모두 필요하다. 질의의 후보 집합은 BM25 상위 100개와 의미 검색 상위 100개의 합집합이며, lib.blend.candidates는 그 안의 모든 상품에 대해 두 점수를 조회한다. 하나는 BM25 점수로, 상품이 질의와 단어를 하나도 공유하지 않으면 0이다. 다른 하나는 코사인 유사도다.
먼저 상점의 원점수를 train 질의에서 α = 0.5로 더하고, 이어서 min-max 스케일링 후에 같은 계산을 한다. 이 과정은 예제에 직접 풀어 쓰고 lib.blend.weighted_sum로 검증한다.
1"""Adds BM25 and cosine scores with equal weights, raw and after min-max scaling, and checks the scaled sum against2lib.blend.weighted_sum. The prose's point rests on the two sums' top 10 overlaps and nDCG@10, and on the count of3train queries where the by-hand ranking matches the library's."""4from lib.blend import candidates, weighted_sum5from lib.lexical import LexicalSearch6from lib.metrics import evaluate7from lib.semantic import SemanticSearch8from lib.significance import compare9from lib.store import load_products, load_queries, qrels1011products, queries, judgments = load_products(), load_queries("train"), qrels("train")12lexical, semantic = LexicalSearch(products), SemanticSearch()13tables = candidates(lexical, semantic, queries) # both scores for each query's candidates1415# the candidate tables are keyed by query_id16table = tables[36] # laundry basket with wheels17print("candidates for laundry basket with wheels:", len(table))18print(f"bm25 range: {table['bm25'].min():.3f} to {table['bm25'].max():.3f}")19print(f"similarity range: {table['similarity'].min():.3f} to {table['similarity'].max():.3f}")202122def min_max(scores):23 return (scores - scores.min()) / (scores.max() - scores.min())242526def blend(normalize, alpha=0.5):27 run = {}28 for query_id, table in tables.items():29 score = alpha * normalize(table["similarity"]) + (1 - alpha) * normalize(table["bm25"])30 # the top 100; the stable sort keeps the candidates' order on equal scores31 run[query_id] = list(score.sort_values(ascending=False, kind="stable").index[:100])32 return run333435top_10s = {"bm25": lexical.run(queries, k=10), "semantic": semantic.run(queries, k=10)}36per_query = {}37for name, normalize in [("raw", lambda scores: scores), ("min-max", min_max)]:38 run = blend(normalize)39 per_query[name] = evaluate(run, judgments)["ndcg@10"]40 print(f"{name} sum ndcg@10: {per_query[name].mean():.3f}")41 for other, top in top_10s.items():42 shared = [len(set(run[query_id][:10]) & set(top[query_id])) for query_id in queries.index]43 print(f"{name} sum, products shared with the {other} top 10: {sum(shared) / len(shared):.1f}")44# the library sorts equal scores by product_id; this blend keeps the candidates' order45by_hand, library = blend(min_max), weighted_sum(tables, 0.5)46matches = sum(by_hand[query_id] == library[query_id] for query_id in tables)47print(f"train queries ranked as lib.blend.weighted_sum ranks them: {matches} of {len(tables)}")48p_value = compare(per_query["min-max"], per_query["raw"])["permutation p"] # a tuning check on train49print("min-max minus raw, permutation p:", "below 0.001" if p_value < 0.001 else f"{p_value:.3f}")
python raw-scores-versus-min-max.pycandidates for laundry basket with wheels: 125
bm25 range: 2.059 to 8.229
similarity range: 0.336 to 0.597
raw sum ndcg@10: 0.706
raw sum, products shared with the bm25 top 10: 9.6
raw sum, products shared with the semantic top 10: 3.9
min-max sum ndcg@10: 0.771
min-max sum, products shared with the bm25 top 10: 6.5
min-max sum, products shared with the semantic top 10: 6.2
train queries ranked as lib.blend.weighted_sum ranks them: 50 of 50
min-max minus raw, permutation p: below 0.001
laundry basket with wheels의 경우 125개의 후보가 있으며, BM25 점수는 2.059 to 8.229, 유사도는 0.336 to 0.597의 범위에 있다. BM25의 분포 폭이 몇 배나 크므로 원점수 합의 순서는 BM25가 결정한다. train 질의 전체에서 원점수 합의 상위 10개는 BM25의 상위 10개와 평균 9.6개 상품을, 의미 검색의 상위 10개와는 3.9개 상품을 공유한다.
가중치는 "각각 절반"이라고 말하지만 순위는 대부분 BM25가 정한다. 원점수 합의 nDCG@10인 0.706은 BM25의 0.695에 가깝다.
min-max 스케일링 후에는 두 검색기가 모두 발언권을 갖는다. 스케일링한 합의 상위 10개는 BM25의 상위 10개와 6.5개, 의미 검색의 상위 10개와 6.2개 상품을 공유하며, nDCG@10은 0.771으로 오른다. 원점수 합과의 이 차이에 대한 순열 검정 p값은 below 0.001이다. 직접 계산한 방식은 train 질의 50 of 50개의 순위를 lib.blend.weighted_sum와 정확히 같게 매긴다.
원점수도 가중치를 조정하면 쓸 수 있다. 임베딩 기반 검색기인 DPR의 저자들은 BM25에 DPR 유사도의 1.1배를 더해 후보의 순위를 매겼고, 1.1은 개발 세트에서 정했다(Karpukhin et al., 2020). 정규화는 α가 모든 질의에서 같은 의미를 갖게 한다. 정규화하지 않으면 BM25가 차지하는 발언권의 몫이 질의마다 BM25의 범위에 따라 달라진다. 다만 min-max는 절대적인 척도가 아니다. 질의의 후보에 상대적이므로 최고 후보는 아무리 나빠도 항상 1을 받는다.
작업 규칙: 추측한 가중치로 BM25 원점수와 코사인 점수를 그대로 더하지 않는다. 어느 점수 함수에 대한 지식도 필요 없으므로 기본값으로 질의별 min-max를 권장한다. 각 점수의 최저 가능값을 알고 있고 후보에 따라 움직이지 않는 하한을 원한다면 이론적 min-max를 쓴다. 어느 경우든 α는 train 질의에서 조정한다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Test reciprocal rank fusion's settings on train queries
Ranks, unlike scores, share one scale, so fusing by rank needs no normalization. Reciprocal rank fusion (RRF) scores each product by adding, over the rankings that contain it, 1 divided by the sum of a constant k and its rank (Cormack et al., 2009), as chapter 1's formula writes it. The price is information: "because RRF is a function of ranks, it disregards the distribution of scores and, as such, discards useful information" (Bruch et al., 2023). A product a hair behind the leader and one far behind it get scores set by their ranks alone.
The constant k sets how much the top ranks dominate. Chapter 1 took k = 60 from RRF's authors, who found in a pilot study that 60 came close to the best value and that the exact choice mattered little. Their pilots fused 30 configurations of Wumpus Search, one search engine, on collections from TREC, a series of shared retrieval evaluations (Cormack et al., 2009). Bruch et al. fused one lexical and one semantic retriever, gave each its own constant, η, and found the results sensitive to the balance between the constants, which acts as a weight: "where the semantic model already performs strongly, for example, discounting the lexical system by increasing η_Lex leads to better performance". One k shared by both rankings, as in the store, sets no balance between them.
The depth of each list matters too. A product in one retriever's top 20 but not in the other's earns nothing from the second ranking, though it has a low rank there. As Bruch et al. put it, "ranks cannot be computed exactly unless the entire collection D is ranked by retrieval system o for every query." On the store's train queries, the union of two top-20 lists holds far fewer exact products than the union of two top-100 lists, as the shares of exact products in each list show.
Try six values of k on the train queries, fusing lists 100 deep. One check is planned before running: does the best k beat the default, k = 60?
1"""Fuses BM25 and semantic retrieval with six values of k on the train queries, and tests the best k against the2default k = 60. The prose's point rests on the rank ratios at k = 1 and k = 60, on the best k, and on its permutation3p-value."""4from lib.fusion import reciprocal_rank_fusion5from lib.lexical import LexicalSearch6from lib.metrics import evaluate7from lib.semantic import SemanticSearch8from lib.significance import compare9from lib.store import load_products, load_queries, qrels1011products, queries, judgments = load_products(), load_queries("train"), qrels("train")12bm25 = LexicalSearch(products).run(queries, k=100)13semantic = SemanticSearch().run(queries, k=100)1415# RRF gives rank r the score 1 / (k + r), so rank 1 over rank 10 is (k + 10) / (k + 1)16for k in [1, 60]:17 print(f"rank 1 over rank 10 at k={k}: {(1 / (k + 1)) / (1 / (k + 10)):.3f}")18scores = {k: evaluate(reciprocal_rank_fusion([bm25, semantic], k=k), judgments)["ndcg@10"]19 for k in [1, 10, 30, 60, 100, 300]}20for k, per_query in scores.items():21 print(f"k={k} ndcg@10: {per_query.mean():.3f}")2223best = max(scores, key=lambda k: scores[k].mean()) # ties go to the smaller k24print("best k on train:", best)25result = compare(scores[best], scores[60]) # the planned check: best k against the default26print(f"best k minus k=60: {result['mean difference']:.3f}")27print(f"best k minus k=60, permutation p: {result['permutation p']:.3f}")28print(f"best k minus k=60, t-test p: {result['t-test p']:.3f}")29print(f"best k minus k=60, 95% interval: {result['ci low']:.3f} to {result['ci high']:.3f}")30print(f"best k minus k=60, wins, losses, ties: {result['wins']}, {result['losses']}, {result['ties']}")
python rrf-k-on-train.pyrank 1 over rank 10 at k=1: 5.500
rank 1 over rank 10 at k=60: 1.148
k=1 ndcg@10: 0.753
k=10 ndcg@10: 0.770
k=30 ndcg@10: 0.771
k=60 ndcg@10: 0.774
k=100 ndcg@10: 0.778
k=300 ndcg@10: 0.777
best k on train: 100
best k minus k=60: 0.004
best k minus k=60, permutation p: 0.093
best k minus k=60, t-test p: 0.103
best k minus k=60, 95% interval: 0.001 to 0.011
best k minus k=60, wins, losses, ties: 6, 3, 41
At k = 1, rank 1 earns 5.500 times what rank 10 earns. At k = 60, it earns 1.148 times as much, so a product near the top of both lists beats one at the top of only one. From k = 1 to k = 300, the six settings score 0.753, 0.770, 0.771, 0.774, 0.778 and 0.777.
The best setting on train, k = 100, leads k = 60 by 0.004, with a permutation p-value of 0.093 and a t-test p-value of 0.103. The book takes its verdict from the permutation test, which can't tell that gain from chance at 0.05. The gain's 95% bootstrap interval, 0.001 to 0.011, excludes 0, so the interval disagrees with both tests.
The two settings' rankings differ on only a handful of queries (wins, losses and ties: 6, 3, 41). Which k is best is fragile too: with BM25's tied products listed the other way, k = 300 wins instead. This fits Cormack et al.'s finding that the choice of k matters little.
Working rule: Keep k = 60 as the default, and fuse lists at least 100 deep, because a deeper list can only add candidates. Move off k = 60 only when the best k on train beats it by a margin the permutation test can tell from chance, with p below 0.05. When one retriever is the stronger one, as in the store, k isn't the setting to change: RRF's equal vote is. Give the rankings weights and tune them.
훈련 질의로 블렌드의 가중치 조정하기
이 장의 두 블렌드는 각각 가중치 α 하나를 받는다. α는 의미 기반 검색에 주는 비중이다. 가중합에서는 α가 정규화한 유사도에 곱해지고, 1 − α가 정규화한 BM25 점수에 곱해진다. 가중 RRF에서는 상품의 점수가 (1 − α) / (k + BM25 순위)에 α / (k + 의미 기반 순위)를 더한 값이다. 두 방식 모두 α = 0이면 BM25 단독이고 α = 1이면 의미 기반 검색 단독이다. RRF에서 α = 0.5는 모든 점수가 절반이 된 1장의 가중치 없는 융합과 같다. 다음은 설명을 위해 α = 0.75로 두고, 훈련 질의 하나의 최상위 상품에 대해 계산한 과정이다.
1"""Scores every candidate for one train query by weighted RRF, by hand, and checks the ranking against2lib.blend.weighted_rrf. The prose's point rests on the top product's two ranks and its score, and on the count of3places that match the library."""4from lib.blend import weighted_rrf5from lib.lexical import LexicalSearch6from lib.semantic import SemanticSearch7from lib.store import load_products, load_queries89alpha, k = 0.75, 60 # an illustrative weight; tuning picks one on train10products, queries = load_products(), load_queries("train")11bm25 = LexicalSearch(products).run(queries, k=100)12semantic = SemanticSearch().run(queries, k=100)13query_id = 36 # laundry basket with wheels141516def part(ranking, weight, product_id):17 """weight / (k + rank) from one ranking, or 0 when the product isn't in it."""18 # index counts from 0, so one is added to get the rank19 return weight / (k + ranking.index(product_id) + 1) if product_id in ranking else 0.0202122candidates = dict.fromkeys(bm25[query_id] + semantic[query_id]) # the union, in the order first seen23score = {product_id: part(bm25[query_id], 1 - alpha, product_id) + part(semantic[query_id], alpha, product_id)24 for product_id in candidates}25ranking = sorted(score, key=lambda product_id: (-score[product_id], product_id)) # ties by product_id26first = ranking[0]27print("first product:", products.at[first, "name"])28print("its bm25 rank:", bm25[query_id].index(first) + 1)29print("its semantic rank:", semantic[query_id].index(first) + 1)30print(f"its weighted rrf score: {score[first]:.5f}")31library = weighted_rrf(bm25, semantic, alpha)[query_id] # the top 10032matches = sum(mine == theirs for mine, theirs in zip(ranking, library))33print(f"places that match lib.blend.weighted_rrf: {matches} of {len(library)}")
python weighted-rrf-one-product.pyfirst product: laundry sorter basket on wheels
its bm25 rank: 1
its semantic rank: 2
its weighted rrf score: 0.01620
places that match lib.blend.weighted_rrf: 100 of 100
laundry basket with wheels에서 최상위 상품인 laundry sorter basket on wheels은 BM25 순위에서 1위, 의미 기반 검색 순위에서 2위에 있으므로, 점수는 0.25 / (60 + 1) + 0.75 / (60 + 2) = 0.01620이다.
예제는 모든 후보의 점수를 이런 방식으로 계산한다. 그 순위는 lib.blend.weighted_rrf와 100 of 100곳에서 일치한다.
조정은 훈련 질의에서 α 값의 격자를 시도하여 평균 nDCG@10이 가장 높은 값을 고르는 과정이다. Bruch et al.(2023)은 볼록 결합, 즉 CC를 조정할 때 나타나는 세 가지 결과를 보고한다. 조정한 CC는 어떤 점수 정규화를 쓰든 비슷한 성능을 내고, 도메인 안에서나 밖에서나 RRF보다 낫고, 표본 효율이 좋다는 것이다. 표본 효율이 좋다는 말은 α가 "훈련 데이터의 5% 미만으로" 수렴했다는 뜻이며, 이는 이 상점의 훈련 집합보다 훨씬 큰 훈련 집합의 일부다.
가중합에서는 세 가지 정규화 각각에 대해 α를 0, 0.1, … 1로 조정하고, 가중 RRF에서는 k = 60으로 조정한다. 그런 다음 조정 점검으로서 각 정규화를 min-max와 비교 검정하고, 테스트 질의에 쓸 두 블렌드를 의미 기반 검색과 비교 검정한다.
1"""Tunes α on the train queries for the weighted sum under three normalizations and for weighted RRF, then compares2the two blends that go to test with semantic retrieval. The prose's point rests on each setting's best α and nDCG@10,3on the p-values against tuned min-max, and on the two gains over semantic retrieval."""4from lib.blend import ALPHAS, NORMALIZATIONS, best_alpha, candidates, scores_by_alpha, weighted_rrf, weighted_sum5from lib.lexical import LexicalSearch6from lib.semantic import SemanticSearch7from lib.significance import compare8from lib.store import load_products, load_queries, qrels910products, queries, judgments = load_products(), load_queries("train"), qrels("train")11lexical, semantic = LexicalSearch(products), SemanticSearch()12tables = candidates(lexical, semantic, queries)13bm25, semantic_run = lexical.run(queries, k=100), semantic.run(queries, k=100)1415per_query = {} # nDCG@10 per query (rows) and alpha (columns)16for name in NORMALIZATIONS:17 per_query[name] = scores_by_alpha(lambda alpha: weighted_sum(tables, alpha, name), judgments)18per_query["weighted rrf"] = scores_by_alpha(lambda alpha: weighted_rrf(bm25, semantic_run, alpha), judgments)19semantic_alone = per_query["min-max"][1.0] # alpha = 1 is semantic retrieval in either blend20print("alphas tried:", len(ALPHAS))21print("min-max ndcg@10 for alpha 0 to 1:", " ".join(f"{mean:.3f}" for mean in per_query["min-max"].mean()))22print(f"semantic alone ndcg@10: {semantic_alone.mean():.3f}")23# alpha 0.5 is unweighted RRF, chapter 1's fusion24print(f"unweighted rrf (alpha 0.5) ndcg@10: {per_query['weighted rrf'][0.5].mean():.3f}")2526best = {name: frame[best_alpha(frame)] for name, frame in per_query.items()}27for name, frame in per_query.items():28 print(f"{name} best alpha: {best_alpha(frame)}")29 print(f"{name} best ndcg@10: {best[name].mean():.3f}")30for name in ["theoretical min-max", "z-score", "weighted rrf"]: # each tuned, against tuned min-max31 print(f"{name} against min-max, permutation p: {compare(best[name], best['min-max'])['permutation p']:.3f}")32for name in ["min-max", "weighted rrf"]: # the two blends that go to test33 gain = compare(best[name], semantic_alone)34 print(f"{name} gain over semantic: {gain['mean difference']:.3f}")35 print(f"{name} gain over semantic, permutation p: {gain['permutation p']:.3f}")36 print(f"{name} gain over semantic, t-test p: {gain['t-test p']:.3f}")
python tune-blend-weights-on-train.pyalphas tried: 11
min-max ndcg@10 for alpha 0 to 1: 0.695 0.709 0.736 0.746 0.758 0.771 0.781 0.784 0.777 0.778 0.772
semantic alone ndcg@10: 0.772
unweighted rrf (alpha 0.5) ndcg@10: 0.774
min-max best alpha: 0.7
min-max best ndcg@10: 0.784
theoretical min-max best alpha: 0.9
theoretical min-max best ndcg@10: 0.789
z-score best alpha: 0.7
z-score best ndcg@10: 0.787
weighted rrf best alpha: 0.6
weighted rrf best ndcg@10: 0.787
theoretical min-max against min-max, permutation p: 0.164
z-score against min-max, permutation p: 0.349
weighted rrf against min-max, permutation p: 0.776
min-max gain over semantic: 0.013
min-max gain over semantic, permutation p: 0.177
min-max gain over semantic, t-test p: 0.161
weighted rrf gain over semantic: 0.015
weighted rrf gain over semantic, permutation p: 0.215
weighted rrf gain over semantic, t-test p: 0.205
같은 질의에서 의미 기반 검색 단독의 점수는 0.772이다. 각 설정의 최적 α와 점수는 다음과 같다.
| 설정 | 최적 α | 평균 nDCG@10 | 조정된 min-max에 대한 순열 p |
|---|---|---|---|
| 가중합, min-max | 0.7 | 0.784 | — |
| 가중합, 이론적 min-max | 0.9 | 0.789 | 0.164 |
| 가중합, z-점수 | 0.7 | 0.787 | 0.349 |
| 가중 RRF, k = 60 | 0.6 | 0.787 | 0.776 |
0.05 수준에서 훈련 질의로 한 검정은 두 대안 정규화 중 어느 쪽도 min-max와 구별하지 못한다. 이는 정규화가 거의 중요하지 않다는 Bruch et al.의 결과와 맞아떨어진다. 가중 RRF 역시 조정된 min-max와 구별하지 못한다. 가중합이 RRF보다 낫다는 Bruch et al.의 두 번째 결과는 여기서 드러나지 않으며, 이 질의들로는 그 결과를 판가름할 수 없다.
α = 1이 격자에 들어 있으므로, 조정된 모든 블렌드는 훈련 질의에서 의미 기반 검색 이상의 점수를 낸다. 그러나 α를 고른 바로 그 질의에서조차 순열 검정은 어느 블렌드의 이득도 0.05 수준에서 우연과 구별하지 못한다. 가중합의 이득은 0.013이고 순열 p값은 0.177이다. 가중 RRF의 이득은 0.015이고 순열 p값은 0.215이다. 또한 각 이득은 같은 질의에서 11번 시도한 것 중 가장 좋은 값이므로, 이득이 한층 더 부풀려진다.
작업 규칙: 가중치 하나를 성긴 격자 위에서 훈련 질의로 조정하고, 다른 정규화가 훈련 질의 검정에서 우연과 구별될 만큼의 차이, 즉 p가 0.05 미만인 차이로 앞서지 않는 한 정규화는 min-max로 유지한다. 가장 좋은 단일 검색기에 대한 훈련 이득은 낙관적인 값으로 보고, 테스트 질의에서는 줄어들 것으로 예상한다. 이는 여러 후보 중 가장 좋은 것으로 고른 모든 설정에 통하는 경험칙이다. 그 설정을 신뢰하기 전에 안정적인지 확인하고, 그다음 테스트 질의에서 보고한다.
조정한 가중치가 안정적인지 확인하기
조정한 가중치는 수십 개의 질의에서 나온 것이므로, 어떤 질의를 가졌는지에 따라 달라질 수 있다. 부트스트랩은 그 정도를 보여 준다. 학습 질의를 재표집하고, 각 표본에서 α를 조정하는 과정을 여러 번 반복한다. 선택된 α가 크게 흔들린다면, 조정된 값은 상점보다 표본을 더 많이 반영한 것이다. 3장은 같은 재표집을 사용해 점수에 구간을 부여한다.
고정된 시드로 학습 질의를 1000번 재표집하고, 조정한 두 혼합 방식인 최소-최대 점수의 가중합과 가중 RRF에 대해 같은 재표집에서 각 α가 얼마나 자주 최선이 되는지 센다.
1"""Resamples the train queries with a fixed seed and counts which α wins each resample, for the weighted sum and for2weighted RRF on the same resamples. The prose's point rests on the α tuned on all train queries and on the counts of3resamples choosing each α."""4import numpy as np5import pandas as pd67from lib.blend import best_alpha, candidates, scores_by_alpha, weighted_rrf, weighted_sum8from lib.lexical import LexicalSearch9from lib.semantic import SemanticSearch10from lib.store import load_products, load_queries, qrels1112products, queries, judgments = load_products(), load_queries("train"), qrels("train")13lexical, semantic = LexicalSearch(products), SemanticSearch()14tables = candidates(lexical, semantic, queries)15bm25, semantic_run = lexical.run(queries, k=100), semantic.run(queries, k=100)16blends = {"weighted sum": scores_by_alpha(lambda alpha: weighted_sum(tables, alpha), judgments),17 "weighted rrf": scores_by_alpha(lambda alpha: weighted_rrf(bm25, semantic_run, alpha), judgments)}1819resamples = 100020print("resamples:", resamples)21# a fixed seed, so every run draws the same resamples22rng = np.random.default_rng(2026)23draws = [rng.integers(0, len(queries), len(queries)) for _ in range(resamples)] # the same draws for both24for name, per_query in blends.items(): # per_query: train queries x alphas25 print(f"{name} alpha tuned on all train queries: {best_alpha(per_query)}")26 # best alpha per resample; idxmax takes the first, smaller alpha when two tie27 chosen = pd.Series([per_query.iloc[draw].mean().idxmax() for draw in draws])28 for alpha, count in chosen.value_counts().sort_index().items():29 print(f"{name} resamples choosing alpha {alpha}: {count}")
python blend-weight-bootstrap.pyresamples: 1000
weighted sum alpha tuned on all train queries: 0.7
weighted sum resamples choosing alpha 0.5: 13
weighted sum resamples choosing alpha 0.6: 171
weighted sum resamples choosing alpha 0.7: 686
weighted sum resamples choosing alpha 0.8: 11
weighted sum resamples choosing alpha 0.9: 74
weighted sum resamples choosing alpha 1.0: 45
weighted rrf alpha tuned on all train queries: 0.6
weighted rrf resamples choosing alpha 0.5: 2
weighted rrf resamples choosing alpha 0.6: 513
weighted rrf resamples choosing alpha 0.7: 76
weighted rrf resamples choosing alpha 0.8: 365
weighted rrf resamples choosing alpha 0.9: 26
weighted rrf resamples choosing alpha 1.0: 18
가중합의 가중치는 안정적이다. 전체 학습 질의에서 α는 0.7이고, α = 0.7은 686번의 재표집에서 최선이 되어 다른 어떤 선택보다 많다. α = 0.6은 171번, 의미 기반 검색만 쓰는 α = 1은 45번 최선이 된다.
α = 0.6로 조정한 가중 RRF는 덜 안정적이다. 가중치가 0.6에서 0.8 사이에서 움직이며, α = 0.6이 513번, α = 0.8이 365번, α = 0.7이 76번 최선이 된다.
두 가중치는 모두 격자에서 의미 기반 검색에 유리한 쪽에 머문다. 예외는 동일 가중치인 α = 0.5로, 가중합에서는 13번, 가중 RRF에서는 2번 최선이 된다.
재표집만이 유일한 점검은 아니다. BM25 점수가 같은 상품에는 어떤 순서가 필요한데, lib.lexical은 이들을 product_id 순으로 나열하며, 이 순서에는 정보가 없다. product_id의 내림차순도 마찬가지로 정보가 없다. 가중합은 동점 상품에 같은 BM25 항을 주므로 순서가 거의 영향을 주지 않지만, RRF는 이들에게 연속된 순위를 매기므로 점수가 달라진다. BM25의 동점을 product_id 내림차순으로 나열하고, 학습 질의에서 최적의 RRF k와 두 가중치를 다시 조정한다.
1"""Tunes RRF's k and both blends' α again with BM25's equal scores listed in descending product_id order, to test2whether the order of ties matters. The prose's point rests on each setting's pair of lines, ties by product_id and3ties reversed."""4import numpy as np56from lib.blend import best_alpha, candidates, scores_by_alpha, weighted_rrf, weighted_sum7from lib.fusion import reciprocal_rank_fusion8from lib.lexical import LexicalSearch9from lib.metrics import evaluate10from lib.semantic import SemanticSearch11from lib.store import load_products, load_queries, qrels121314class TiesReversed(LexicalSearch):15 """BM25 with equal scores in descending product_id order, an order as arbitrary as ascending."""1617 def search(self, query, k=100):18 scores = super().search(query, k=len(self.ids)) # every match, so the cut at k can move too19 # highest score first, then descending product_id (np.lexsort sorts by its last key first)20 order = np.lexsort((-scores.index.to_numpy(), -scores.to_numpy()))21 return scores.iloc[order[:k]]222324products, queries, judgments = load_products(), load_queries("train"), qrels("train")25semantic = SemanticSearch()26semantic_run = semantic.run(queries, k=100)27# each order runs in turn, against the same semantic run28for ties, lexical in [("ties by product_id", LexicalSearch(products)), ("ties reversed", TiesReversed(products))]:29 bm25 = lexical.run(queries, k=100)30 by_k = {k: evaluate(reciprocal_rank_fusion([bm25, semantic_run], k=k), judgments)["ndcg@10"].mean()31 for k in [1, 10, 30, 60, 100, 300]}32 print(f"best rrf k, {ties}: {max(by_k, key=by_k.get)}") # ties go to the smaller k33 rrf = scores_by_alpha(lambda alpha: weighted_rrf(bm25, semantic_run, alpha), judgments)34 print(f"weighted rrf alpha, {ties}: {best_alpha(rrf)}")35 tables = candidates(lexical, semantic, queries)36 total = scores_by_alpha(lambda alpha: weighted_sum(tables, alpha), judgments)37 print(f"weighted sum alpha, {ties}: {best_alpha(total)}")
python tuning-with-ties-reversed.pybest rrf k, ties by product_id: 100
weighted rrf alpha, ties by product_id: 0.6
weighted sum alpha, ties by product_id: 0.7
best rrf k, ties reversed: 300
weighted rrf alpha, ties reversed: 0.8
weighted sum alpha, ties reversed: 0.7
동점 순서를 뒤집으면 RRF의 설정은 바뀌지만 가중합의 설정은 바뀌지 않는다.
| 설정 | product_id 순 동점 | 동점 역순 |
|---|---|---|
| 최적 RRF k | 100 | 300 |
| 가중 RRF α | 0.6 | 0.8 |
| 가중합 α | 0.7 | 0.7 |
정보가 없는 순서가 설정을 바꾼다면 학습 질의로는 그 설정들을 구별할 수 없다. 따라서 RRF의 k와 가중치는 취약하고 가중합의 가중치는 그렇지 않다. 상점에는 가중 RRF의 가중치를 확정할 만한 학습 질의가 더 없고, 테스트 비교는 product_id 순으로 동점을 처리해 조정한 가중치를 기준으로 계획되었으므로, α = 0.6를 테스트로 넘긴다.
안정성은 학습 질의들이 가중치에 동의한다는 뜻이지, 그 가중치가 다른 질의에서 검색을 개선한다는 뜻은 아니다. 재표집은 같은 질의를 다시 쓰므로 그 질의들의 공통된 특성을 그대로 공유한다.
작업 규칙: 학습 질의를 부트스트랩하여 각 표본에서 조정하고, 정보가 없는 다른 순서로 동점을 나열해 한 번 더 조정한다. 선택된 가중치가 격자 전체에 흩어지면 더 성긴 격자나 더 많은 학습 질의를 사용하거나, 더 단순한 설정을 택한다. 동점 순서만으로 가중치가 움직이면 그 값을 보고하는 모든 곳에 그 사실을 밝힌다. 두 점검에서 모두 안정적이면 테스트 질의로 넘긴다.
테스트 질의에서 조정한 블렌드 보고하기
조정한 설정이 그 설정을 고른 질의를 넘어서도 도움이 되는지는 따로 떼어 둔 질의만이 보여 준다. 조정한 각 블렌드를 테스트 질의에서 한 번씩 실행하고, 3장의 하네스를 사용해 최고의 단일 검색기인 시맨틱 검색과 질의별로 비교한다. 3장에서는 이 두 비교를 결과를 보기 전에 미리 정해 두었다. 3장에 따라 본페로니 보정은 순열 검정의 p값 기준을 0.025 미만으로 정하며, 이는 0.05를 계획한 두 비교로 나눈 값이다. t-검정과 이에 대응하는 신뢰 수준 0.975의 부트스트랩 구간을 함께 제시한다.
스토어의 훈련 질의에서 조정한 블렌드는 시맨틱 검색보다 각각 0.013과 0.015만큼 앞섰지만, 어느 쪽도 순열 검정으로 우연과 구별할 수 있는 이득은 아니었다. 먼저 예측해 보자. 테스트 질의에서 α = 0.7인 가중합과 α = 0.6인 가중 RRF는 시맨틱 검색보다 높은 점수를 받을까, 비슷할까, 낮을까?
1"""Chooses each blend's α on the train queries, runs both once on the test queries, and compares each with semantic2retrieval at the corrected threshold. The prose's point rests on the two mean differences and their permutation3p-values, and the assert checks that neither clears the threshold."""4from lib.blend import best_alpha, candidates, scores_by_alpha, weighted_rrf, weighted_sum5from lib.lexical import LexicalSearch6from lib.metrics import evaluate7from lib.semantic import SemanticSearch8from lib.significance import compare9from lib.store import load_products, load_queries, qrels1011lexical, semantic = LexicalSearch(load_products()), SemanticSearch()121314def blends(queries):15 tables, bm25, semantic_run = candidates(lexical, semantic, queries), lexical.run(queries), semantic.run(queries)16 return {"weighted sum": lambda alpha: weighted_sum(tables, alpha), # each blend's run at a given alpha17 "weighted rrf": lambda alpha: weighted_rrf(bm25, semantic_run, alpha)}181920train, test = blends(load_queries("train")), blends(load_queries("test"))21threshold = 0.05 / len(test) # two planned comparisons, Bonferroni-corrected22semantic_scores = evaluate(semantic.run(load_queries("test")), qrels("test"))23print("test queries:", len(semantic_scores))24print(f"semantic ndcg@10: {semantic_scores['ndcg@10'].mean():.3f}")25unweighted = evaluate(test["weighted rrf"](0.5), qrels("test")) # alpha 0.5 is chapter 1's fusion26print(f"unweighted rrf ndcg@10: {unweighted['ndcg@10'].mean():.3f}")27print(f"p-value threshold for each comparison: {threshold:.3f}")28print(f"confidence level of each interval: {1 - threshold:.3f}")29judged = [semantic_scores["judged@10"].mean()]30for name, blend in test.items():31 alpha = best_alpha(scores_by_alpha(train[name], qrels("train"))) # train only32 scores = evaluate(blend(alpha), qrels("test"))33 judged.append(scores["judged@10"].mean())34 # the interval's level matches the corrected threshold35 result = compare(scores["ndcg@10"], semantic_scores["ndcg@10"], confidence=1 - threshold)36 print(f"{name} alpha chosen on train: {alpha}")37 print(f"{name} ndcg@10: {scores['ndcg@10'].mean():.3f}")38 print(f"{name} minus semantic: {result['mean difference']:.3f}")39 print(f"{name} permutation p: {result['permutation p']:.3f}")40 print(f"{name} t-test p: {result['t-test p']:.3f}")41 print(f"{name} interval: {result['ci low']:.3f} to {result['ci high']:.3f}")42 # neither difference is established: each permutation p-value stays at or above the corrected threshold43 assert result['permutation p'] >= threshold44print(f"lowest judged@10: {min(judged):.3f}")45print(f"highest judged@10: {max(judged):.3f}")
python tuned-blends-on-test.pytest queries: 30
semantic ndcg@10: 0.830
unweighted rrf ndcg@10: 0.812
p-value threshold for each comparison: 0.025
confidence level of each interval: 0.975
weighted sum alpha chosen on train: 0.7
weighted sum ndcg@10: 0.816
weighted sum minus semantic: -0.014
weighted sum permutation p: 0.229
weighted sum t-test p: 0.221
weighted sum interval: -0.042 to 0.008
weighted rrf alpha chosen on train: 0.6
weighted rrf ndcg@10: 0.825
weighted rrf minus semantic: -0.005
weighted rrf permutation p: 0.650
weighted rrf t-test p: 0.643
weighted rrf interval: -0.029 to 0.016
lowest judged@10: 0.980
highest judged@10: 0.990
어느 블렌드도 시맨틱 검색을 이기지 못한다. 시맨틱 검색은 0.830, 최소-최대 점수의 가중합은 0.816, 가중 RRF는 0.825을 기록한다.
실행 결과의 judged@10 값은 0.980에서 0.990 사이에 있으므로, 누락된 판정은 세 가지 모두에 거의 같은 정도로 영향을 준다.
두 차이 모두 확정되지 않는다. 각 순열 검정 p값은 보정된 기준인 0.025 이상에 머문다. 가중합은 시맨틱 검색과 -0.014만큼 차이가 나며, 순열 검정 p값은 0.229, t-검정 p값은 0.221이고 구간은 -0.042 to 0.008이다. 가중 RRF는 -0.005만큼 차이가 나며, p값은 0.650과 0.643이고 구간은 -0.029 to 0.016이다. 두 구간 모두 0을 포함하고 검정 결과도 이와 일치하므로, 이 결과는 "더 나빠졌다"가 아니라 "개선이 없다"이다. 가중 RRF의 경우 이는 α = 0.6에 대한 결과이며, 이 가중치는 BM25 동점의 순서에 따라 움직일 수 있다.
"높다"고 판단했다면 훈련 이득을 믿은 셈이 되었을 것이다. 그 이득은 그것을 고른 질의에서조차 순열 검정으로 우연과 구별되지 않았고, 여러 시도 중 가장 좋은 값이었다.
작업 규칙: 블렌드는 따로 떼어 둔 질의에서 최고의 단일 검색기를 이기되, 그 순열 검정 p값이 계획한 비교 수에 맞게 보정한 기준 미만일 때만 채택한다. 그렇지 않으면 더 단순한 시스템을 유지한다. 그러면 시맨틱 검색만이 스토어에서 넘어서야 할 랭커로 남는다. 조정한 가중치와 코드는 보관하고, 검색기나 카탈로그가 바뀌면 블렌드를 다시 시험한다.
SPLADE로 희소 용어 가중치 학습하기
두 검색기를 융합하는 대신, 한 검색기를 바꿔서 놓치는 경우를 줄일 수 있다. BM25는 상품 텍스트에 나타나는 단어만 일치시킨다. 학습된 희소 검색(learned sparse retrieval)은 용어의 역색인이라는 BM25의 구조를 그대로 유지하되, 각 상품의 용어와 그 가중치를 신경망 모델이 고르게 한다. SPLADE는 학습된 희소 검색 모델의 하나다(Formal et al., 2021). 텍스트를 하위 단어 토큰으로 읽는 트랜스포머인 BERT 계열의 언어 모델이 상품 텍스트를 읽고, 각 토큰 i에서 어휘의 모든 용어 j에 원점수 w_ij를 부여한다. ReLU가 음수 점수를 0으로 만들고, 원 논문은 남은 값에 로그를 취한 것을 텍스트의 토큰에 걸쳐 합산한다고 한다.
weight of term j = sum over the text's tokens i of log(1 + ReLU(w_ij))
이 로그는 BM25의 포화처럼 일종의 포화 장치다. 저자들의 표현으로는 "일부 용어가 지배하는 것을 막고 표현의 희소성을 자연스럽게 보장한다"고 한다. SPLADE v2는 합을 토큰에 걸친 최댓값으로 바꾸었고, 저자들은 최댓값 풀링을 기본값으로 삼았다(Formal et al., 2021, SPLADE v2). SPLADE 벡터는 어휘 항목마다 하나의 차원을 가지며, BERT 어휘에서는 30,522개이고, 보통 그중 99% 넘는 차원이 0이다(Sentence Transformers). SPLADE 벡터의 0이 아닌 용어에는 확장 용어(expansion term)가 포함된다. 텍스트에 들어 있지 않지만 모델이 그래도 가중치를 주는 단어이므로, 상품은 자신이 쓰지 않은 질의 단어와도 일치할 수 있다.
확장 용어는 이 상점에서 나타나는 BM25의 실패 하나를 겨냥한다. 학습 질의에서, BM25의 토크나이저가 보는 대로 질의 단어 중 적어도 하나가 빠진 정확 일치 상품이 몇 개인지 센다.
1"""Counts the exact train pairs whose product lacks a word of its query, as BM25's tokenizer sees them, and counts the2exact products of one query by term. The prose's point rests on the share missing a query word and on the per-term3counts for midcentury tv unit."""4from collections import Counter56import bm25s78from lib.store import load_products, load_queries, product_text, qrels910products, queries, judgments = load_products(), load_queries("train"), qrels("train")111213def words(texts):14 """The tokens BM25 matches on: bm25s's default tokenizer with English stopwords, as in lib.lexical."""15 tokenized = bm25s.tokenize(texts, stopwords="en", return_ids=False, show_progress=False)16 return [set(tokens) for tokens in tokenized]171819product_words = dict(zip(products.index, words(product_text(products).tolist())))20query_words = dict(zip(queries.index, words(queries["query"].tolist())))21exact_pairs = [(query_id, product_id) for query_id in queries.index22 for product_id, grade in judgments[query_id].items() if grade == 2]23missed = Counter(word for query_id, product_id in exact_pairs24 for word in query_words[query_id] - product_words[product_id])25# a pair counts as missing when some query word is absent from the product's set of tokens26missing = sum(not query_words[query_id] <= product_words[product_id] for query_id, product_id in exact_pairs)27print("exact train pairs:", len(exact_pairs))28print("exact pairs missing a query word:", missing)29print(f"share missing a query word: {missing / len(exact_pairs):.3f}")30print("most often missing:", ", ".join(f"{word} ({count})" for word, count in missed.most_common(8)))3132exact = [product_id for query_id, product_id in exact_pairs if query_id == 453] # midcentury tv unit33print("exact products for midcentury tv unit:", len(exact))34for word in ["midcentury", "unit", "stand"]:35 print(f"exact products containing {word}:", sum(word in product_words[product_id] for product_id in exact))36mid_century = product_text(products)[exact].str.contains("mid-century")37print("exact products whose text says mid-century:", mid_century.sum())
python exact-products-missing-query-words.pyexact train pairs: 1937
exact pairs missing a query word: 1454
share missing a query word: 0.751
most often missing: ligth (193), decorative (134), modern (102), freestanding (78), floats (58), queen (57), dining (56), infant (43)
exact products for midcentury tv unit: 25
exact products containing midcentury: 0
exact products containing unit: 0
exact products containing stand: 25
exact products whose text says mid-century: 20
정확 일치 (질의, 상품) 쌍 1937개 중 1454개가 질의 단어를 하나 이상 놓치며, 그 비율은 0.751이다. 가장 자주 빠지는 단어와 그 횟수는 ligth (193), decorative (134), modern (102), freestanding (78), floats (58), queen (57), dining (56), infant (43)이다. 일부는 8장의 교정기가 겨냥하는 오타이고, 일부는 5장에서 어간을 추출한 복수형이다. 나머지는 상품 텍스트가 생략한 서술어이거나 같은 사물을 가리키는 다른 단어다.
midcentury tv unit의 경우 정확 일치 상품은 다른 단어를 쓴다. 25개의 정확 일치 상품 중 0개가 midcentury를 포함하고 0개가 unit를 포함한다. 상품 텍스트는 그 대신 mid-century이라고 쓰는 경우가 20개이고, stand라고 쓰는 경우가 25개다.
확장 용어는 이런 간극을 겨냥하지만, 모델이 TV 스탠드가 TV 유닛임을 학습하는지는 직접 측정해 볼 일이다.
SPLADE 저자들의 기술 보고서는 SPLADE-v3가 문단 순위 벤치마크인 MS MARCO 개발 세트에서 MRR@10 0.40 이상을 기록한다고 밝히고, "교차 인코더 재순위기와 견줄 만하다"고 설명한다. 여기서 MRR@10은 첫 번째 관련 문단이 얼마나 높은 순위에 놓이는지를 측정한다(Lassance et al., 2024). 이 책은 SPLADE를 실행하지 않는다. 기준 체크포인트인 naver/splade-cocondenser-ensembledistil와 naver/splade-v3는 CC-BY-NC-SA-4.0 라이선스이므로 상업적 사용이 불가능하다. Apache-2.0 모델인 opensearch-neural-sparse-encoding-doc-v3-distill는 신경망 모델을 상품에만 실행하고, 질의는 토크나이저와 가중치 표로 인코딩한다.
작업 규칙: BM25의 누락이 대부분 어휘 불일치이고 역색인을 유지하고 싶다면 학습된 희소 검색을 고려한다. 먼저 모델의 라이선스를 확인하고, 다른 검색기와 마찬가지로 측정한다. 단독으로, 질의별로, 학습 질의에서 측정한 뒤 테스트에서 측정한다.
ColBERT로 토큰 단위로 매칭하기
SPLADE가 어휘 기반 검색을 바꾼다면, 지연 상호작용(late interaction)은 의미 기반 검색을 바꾼다. 상점의 의미 기반 검색은 단일 벡터 방식이다. 상품마다 임베딩 하나, 질의마다 임베딩 하나를 두고 한 번만 비교한다. 지연 상호작용은 텍스트마다 벡터 하나를 두는 대신 토큰마다 벡터 하나를 유지하므로 다중 벡터 검색이라고도 부른다. ColBERT는 임베딩 모델처럼 질의와 상품을 따로 인코딩하고, 마지막에야 둘을 비교한다. ColBERT는 질의의 각 토큰마다 가장 유사한 상품 토큰을 찾고 그 최댓값들을 합산한다. 이 연산을 MaxSim이라고 한다(Khattab and Zaharia, 2020).
score(query, product) = sum over query tokens q of max over product tokens d of cosine(q, d)
상품은 질의와 무관하게 인코딩되므로 상품의 토큰 벡터를 미리 계산해 둘 수 있다. 교차 인코더는 두 텍스트를 하나의 입력으로 읽기 때문에 이렇게 할 수 없다. ColBERT 논문은 질의와 본문을 함께 읽는 기존 BERT 기반 모델과 "견줄 만한(competitive)" 효과를 보이면서 속도는 "두 자릿수 크기(100배)만큼 빠르다"고 보고한다. 대가는 저장 공간이다. 상품당 하나가 아니라 토큰당 하나의 벡터를 저장해야 한다. ColBERTv2는 이 벡터를 압축하여 지연 상호작용 모델이 필요로 하는 공간을 6배에서 10배 줄인다(Santhanam et al., 2022).
midcentury tv unit의 경우를 다시 보자. 이 질의의 정확한 상품은 stand이라고 하며 unit이라고는 하지 않는다. 단일 벡터는 질의 전체를 하나의 방향으로, 상품 텍스트 전체를 또 하나의 방향으로 접어 넣는다. 지연 상호작용에서는 질의의 unit이 상품의 각 토큰과 비교되고, 그중에는 stand도 있으며, 가장 잘 맞는 결과가 따로 반영된다. 토큰 단위 매칭은 어려운 사례 일부에서 도움이 된다. 무작위로 고르면 25%인 부정(negation) 벤치마크 NevIR에서 ColBERTv1은 19.7%, ColBERTv2는 13.0%를 기록해 시험한 모든 단일 벡터 모델(12% 이하)보다 높았지만, 여전히 우연 수준에는 못 미쳤다(Weller et al., 2024). 모델을 학습하지 않은 데이터셋에서 제로샷으로 평가하는 벤치마크인 BEIR에서는 재순위기와 지연 상호작용 모델이 "평균적으로 가장 좋은 제로샷 성능을 달성"했으나 계산 비용이 높았다(Thakur et al., 2021). PyLate 라이브러리나 Apache-2.0 라이선스 모델 lightonai/GTE-ModernColBERT-v1 같은 공개 도구가 있다(Chaffin and Sourty, 2025). 이 책은 ColBERT도 실행하지 않는다.
작업 규칙: 단일 벡터 검색이 단어 하나에 좌우되는 세부 사항을 놓치고, 토큰마다 벡터를 둘 여유가 있다면 지연 상호작용을 고려한다. 상점 정도 규모의 카탈로그라면 먼저 후보 목록에 재순위기를 시험해 볼 것을 권한다(9장). 재순위기는 질의 시점에 같은 세부 사항을 읽고 새 색인도 필요 없다. 다만 9장의 재순위기 중 어느 것도 상점의 의미 기반 검색보다 확립된 향상을 보이지는 않는다.
하이브리드 검색이 효과를 내는 경우 판단하기
융합이 도움이 되는지는 융합하는 검색기에 달려 있으며, 발표된 연구들의 결과도 양쪽으로 갈린다. 어휘 기반 검색과 밀집 검색(밀집은 임베딩 기반을 뜻한다)은 밀집 모델이 더 약한 경우에도 서로를 보완할 수 있다. 도메인 밖에서 제로샷 하이브리드는 세 데이터셋 평균으로 심층 검색 모델보다 상대적으로 20.4% 향상되었다(T. Chen et al., 2022). 어휘 기반 기준선도 중요하다. 밀집 검색기인 DPR의 저자들은 하이브리드에서 얻은 이득이 작다고 보았지만, 더 강력한 BM25로 수행한 재현 연구는 "통계적으로 유의미한 이득"을 발견했다(Ma et al., 2021). 의미 기반 검색기의 강도 역시 중요하다. 추론 비중이 큰 질의로 구성된 벤치마크인 BRIGHT에서 α = 0.5로 min-max 점수의 가중합을 이용해 BM25를 융합하자, 중간 수준의 밀집 검색기는 nDCG@10이 3.5점에서 4.9점 올랐고 가장 강한 두 검색기는 2.0점에서 2.9점 내려갔다. 저자들은 "융합된 목록이 어휘적으로는 비슷하지만 의미적으로는 무관한 문서를 끌어올리기" 때문에 이미 강한 검색기는 융합으로 손해를 볼 수 있다고 경고한다(Abdallah et al., 2026).
실무 보고는 대개 하이브리드를 어휘 검색 단독과 비교한다. 한 소매업체의 프리프린트는 온라인 A/B 테스트에서 어휘 검색과 벡터 검색을 결합한 하이브리드가 어휘 검색 단독보다 우수했으며 클릭률이 0.97%, 전환율이 0.98% 올랐다고 보고한다(Sonagara et al., 2026). 이는 어휘 기반 시스템에 의미 기반 검색을 더하는 근거이지, 강한 의미 기반 검색에 어휘 기반 검색을 더하는 근거는 아니다. 후자가 이 상점이 던지는 질문이다.
이 상점은 강한 검색기의 경우에 해당한다. 테스트 질의에서 3장은 BM25에 대한 의미 기반 검색의 우위를 확인하며, 조정한 어떤 혼합도 이를 넘지 못한다. 이 상점의 BM25는 어간 추출을 하지 않은 이 책의 기준선이다. 5장은 더 강한 BM25를 구축하므로, Ma et al.의 재현 연구는 그것으로 혼합을 다시 시험해 볼 이유가 된다.
점수 융합만이 하이브리드의 유일한 형태는 아니다. 검색 엔진은 어휘 일치를 의미 기반 검색의 필터로 쓸 수도 있다. 한 엔진은 질의 언어에 임베딩 연산자를 추가하여 "임베딩과 용어를 임의로 조합한 하이브리드 검색 표현"을 하나의 질의로 실행한다(Huang et al., 2020). 이 상점의 필터는 48 같은 크기가 정확히 일치하도록 요구한 다음, 일치한 결과를 임베딩으로 순위화할 수 있다. 이는 검증할 가설이지 결과가 아니며, 단순한 필터는 7qt slow cooker에서 실패한다. 이 표기를 쓰는 상품이 없기 때문이다. 질의가 이런 제약을 담고 있는지 판단하는 일은 질의 이해이며(8장), 8장은 색상, 모양, 크기, 마감을 언급하는 쇼핑객의 후속 메시지에 이러한 필터를 시험한다. 질의마다 가중치를 고르는 것도 질의 이해에 속하며, 이 책은 이를 구현하지 않는다. 학습 질의마다 더 나은 순위를 고르면 0.802점을 얻겠지만, 목록을 섞는 질의별 가중치는 그 수치에 묶이지 않는다. 질의별 방법 하나는 LLM(대규모 언어 모델)에게 각 검색기의 최상위 결과를 판정하게 하고 그에 따라 α를 정한다(Hsu and Tzeng, 2025). BRIGHT 연구는 이 방법의 점수 기반 변형이 불안정하다고 보았다(Abdallah et al., 2026).
작업 규칙: 두 검색기의 품질이 비슷하거나, 임베딩 모델이 학습된 도메인 밖에서 작동하거나, 임베딩이 놓치는 정확한 용어에 의존하는 질의가 많다면 하이브리드를 시도할 것을 권한다. 가중 RRF로 시작한다. 순위만 필요하고, 이 상점의 학습 질의에서 순열 검정으로는 가중합과 구별되지 않았다. 두 엔진이 모든 후보에 점수를 제공한다면 정규화한 점수의 가중합으로 옮긴다. 두 연구에서 해당 데이터에서 RRF보다 앞섰고(Bruch et al., 2023; Abdallah et al., 2026), 이 상점의 학습 질의에서도 가중합의 가중치가 더 안정적이었다. 보류한 질의에서 한 검색기가 더 강하다고 확립되었고 조정한 어떤 혼합도 거기서 이를 넘지 못한다면, 그 검색기만 사용하고 다른 쪽은 기준선으로 남겨 두며, 정확한 제약을 위한 어휘 필터를 시험한다. 이것이 이 상점의 경우다.
운영 환경에서 무엇이 잘못되는가
검색기가 두 개이면 모든 비용이 두 배가 된다. 예제는 카탈로그의 표본을 오프라인으로 채점하지만, 실제 하이브리드 검색은 인덱스 두 개를 최신 상태로 유지하고 질의마다 검색을 두 번 실행한다. 두 검색은 병렬로 실행할 수 있으나 느린 쪽이 응답 시간을 결정하며, 어느 한쪽이 실패해도 결과가 나빠진다. 측정한 이득과 이 비용을 함께 따져 보아야 한다.
목록이 짧으면 후보가 빠진다. 융합은 두 검색기 모두 반환하지 않은 상품의 순위를 매길 수 없다. 이 상점의 학습용 질의에서 상위 100개 목록 두 개의 합집합은 각 질의의 정확한 상품 중 0.810를 담고 있고, 상위 20개 목록 두 개의 합집합은 0.445를 담고 있다. 한 엔진의 설정에 있는 깊이 제한은 아무도 모르는 사이에 후보를 잘라낼 수 있다.
누락된 점수에는 규칙이 필요하다. 각 검색기가 상위 k개만 반환하면, 한 목록에서 빠진 상품은 그 검색기의 점수를 갖지 못한다. DPR 재현 연구는 이 상품에 "검색된 문서 중 밀집 검색 점수의 최솟값"을 부여하며, BM25에는 그 반대로 적용한다(Ma et al., 2021). Bruch 등은 누락된 점수를 대입하는 대신 정확하게 계산하며, lib.blend.candidates도 그렇게 한다. 운영 엔진은 이런 계산을 허용하지 않을 수 있다(Bruch et al., 2023).
최소-최대 정규화는 상대적이다. 한 질의에서 가장 좋은 후보는 모든 후보가 나쁜 경우에도 항상 1을 받는다. 카탈로그의 어떤 상품과도 단어를 공유하지 않는 질의는 모든 후보에 BM25 점수 0을 준다. 이때 단순한 최소-최대 정규화는 0으로 나누게 되고, lib.blend은 0을 반환하므로 혼합 결과는 조용히 의미 기반 검색만으로 바뀐다. 이 상점의 질의 중에는 이런 경우가 없지만, 실제 검색창에서는 생긴다.
융합 점수는 신뢰도가 아니다. 검색 점수는 보정이 잘 되어 있지 않다. "신뢰도 보정은 모든 모델 계열에서 일관되게 약하다"(Abdallah et al., 2026). 질의에 좋은 결과가 없다고 판단하려고 융합 점수에 임계값을 두어서는 안 된다.
조정된 가중치는 특정한 검색기 쌍에만 해당한다. 이 상점의 α는 이 BM25 설정, 이 임베딩 모델, 이 카탈로그에 맞춘 값이다. 이 중 하나라도 바꾸면 기존 가중치를 믿기 전에 학습용 질의로 다시 조정해야 한다. 조정된 RRF도 "도메인 밖 데이터셋에는 일반화가 잘 되지 않는다"(Bruch et al., 2023).
작업 규칙: 융합 결과 옆에 두 검색기의 순위를 함께 기록하고, 모든 엔진의 설정에서 목록 깊이를 확인하며, 검색기가 바뀔 때마다 α를 다시 조정한다.
이 장이 내린 결정
이후의 변경은 각 결정을 이길 만한 이유가 있어야 한다.
- 학습 질의로 조정하고, 테스트 질의로 보고한다. 모든 분석과 조정된 모든 설정은 50개의 학습 질의를 사용한다. 이 장은 테스트 질의를 보고를 위해 한 번만 읽는다.
- 계획된 비교는 두 가지이다. 조정된 각 블렌드를 의미 기반 검색과 비교하며, 판정은 0.05를 2로 나눈 기준의 순열 검정으로 한다. t-검정과 부트스트랩 구간을 함께 본다.
- 융합하기 전에 각 검색기를 점검한다. judged@10과 대응 검정을 사용하고, 질의별로 어느 쪽이 이기는지 센다.
- 후보는 두 검색기의 상위 100개를 합한 집합이다. 모든 후보에 대해 두 점수를 모두 조회하므로 점수가 빠진 제품이 없다.
- 정규화는 질의별 min-max이다. 학습 질의에서 한 순열 검정으로는 나머지 두 정규화를 0.05 수준에서 min-max와 구별할 수 없고, min-max는 두 점수 함수에 대한 지식이 필요 없다.
- RRF는 k = 60이고 목록 깊이는 100이다. 학습 질의에서 가장 좋은 k도 60보다 낫다고 해도, 그 차이는 순열 검정으로 0.05 수준에서 우연과 구별되지 않으며, BM25의 동점 순서에 따라 달라진다. 목록을 더 깊게 하면 후보가 늘어날 수만 있다.
- 가중치 α 하나를 0에서 1까지 0.1 간격으로 조정한다. 두 블렌드에 모두 적용하며, 학습 질의의 평균 nDCG@10으로 고른 뒤 부트스트랩을 하고 BM25의 동점 순서를 뒤집어 다시 조정한다. 가중합의 α는 두 점검을 모두 통과하지만, 가중 RRF의 α는 그렇지 못하다.
- SPLADE와 ColBERT는 기록하지 않고 설명만 한다. 상점의 질문에 답하는 데 둘 다 필요하지 않기 때문이다.
- 블렌드는 테스트에서 가장 좋은 단일 검색기를 이길 때만 채택한다. 조정된 두 블렌드 모두 그렇지 못하므로, 상점이 넘어야 할 랭커는 의미 기반 검색 단독으로 남고, 어간 처리를 하지 않은 BM25는 기준선으로 유지한다.
- 이 장이 보인 것: 블렌드는 두 검색기가 서로 다른 질의에서 실패할 때에만 도움이 될 수 있으며, 학습 질의에서 이긴 가중치는 테스트 질의에서도 유지되어야 한다. 이 상점에서는 조정된 어느 블렌드도 의미 기반 검색을 이기지 못했다.
이 판의 이 장
2026.11.10판예제 통과 2026년 11월 19이 장에서 12개 예제개 중 12개가 통과한다
영어판 2026.11.10판을 번역한 것이다.