机器学习与深度学习 / 系统课时
合并多路召回并控制配额
合并多路召回并控制配额
这一课把热门、协同过滤、向量检索等多路候选合并成一个稳定的召回池:先统一候选结构,再完成去重、来源累积和配额控制,避免某一路径占满候选池,同时保留排序模型可直接使用的召回来源特征。
学习目标
- 能设计统一的多路召回候选结构,并正确完成跨路去重
- 能用配额控制各召回源进入候选池的数量
- 能保留
sources等来源特征,供后续排序模型使用
先统一候选结构
多路召回最容易出现的问题不是“合并列表”,而是每一路返回结构不同。有的只有物品 ID,有的带相似度,有的带业务分数。进入融合层之前,应统一为最小结构:物品 ID、召回源、该路原始分数。
单个物品可能被多路同时召回。此时不能简单保留第一条或最后一条,否则会丢失“这个物品被哪些通道命中”的信息。更合理的做法是按 item_id 去重,同时累积来源集合与各路分数。

下面先定义一个最小可运行的数据结构与输入样例。
from dataclasses import dataclass
from typing import Dict, List
@dataclass(frozen=True)
class RecallItem:
item_id: int
source: str
score: float
recall_results: Dict[str, List[RecallItem]] = {
"popular": [
RecallItem(101, "popular", 0.92),
RecallItem(102, "popular", 0.88),
RecallItem(103, "popular", 0.84),
],
"cf": [
RecallItem(102, "cf", 0.95),
RecallItem(104, "cf", 0.90),
RecallItem(105, "cf", 0.86),
],
"vector": [
RecallItem(104, "vector", 0.97),
RecallItem(106, "vector", 0.91),
RecallItem(107, "vector", 0.89),
],
}
print(sum(len(items) for items in recall_results.values()))预期输出
9这里共有 9 条原始候选,但物品 102 和 104 分别被两路命中,因此真正的唯一物品数更少。
用配额阻止单一路径吞噬候选池
如果直接把所有结果按分数排序后截取 TopN,不同召回源的分数尺度通常不可比。例如向量相似度可能集中在 0.7~0.9,而热门分可能是经过归一化后的另一套分布。直接混排容易让某一路径占满候选池。
更稳妥的基础方案是先给每一路设置配额,再进入统一去重。配额可以来自固定配置,也可以根据用户分群、流量场景或召回质量动态调整。
from collections import defaultdict
from dataclasses import dataclass
from typing import Dict, List
@dataclass(frozen=True)
class RecallItem:
item_id: int
source: str
score: float
quotas = {
"popular": 2,
"cf": 2,
"vector": 2,
}
def merge_with_quota(
results: Dict[str, List[RecallItem]],
quotas: Dict[str, int],
) -> List[dict]:
merged = {}
for source, items in results.items():
limit = quotas.get(source, 0)
# 每一路先按自己的分数排序,再只取该路配额。
selected = sorted(
items,
key=lambda x: x.score,
reverse=True,
)[:limit]
for item in selected:
if item.item_id not in merged:
merged[item.item_id] = {
"item_id": item.item_id,
"sources": set(),
"source_scores": {},
}
candidate = merged[item.item_id]
candidate["sources"].add(source)
candidate["source_scores"][source] = item.score
output = []
for candidate in merged.values():
output.append({
"item_id": candidate["item_id"],
"sources": sorted(candidate["sources"]),
"source_scores": candidate["source_scores"],
})
return output
recall_results = {
"popular": [
RecallItem(101, "popular", 0.92),
RecallItem(102, "popular", 0.88),
RecallItem(103, "popular", 0.84),
],
"cf": [
RecallItem(102, "cf", 0.95),
RecallItem(104, "cf", 0.90),
RecallItem(105, "cf", 0.86),
],
"vector": [
RecallItem(104, "vector", 0.97),
RecallItem(106, "vector", 0.91),
RecallItem(107, "vector", 0.89),
],
}
for row in merge_with_quota(recall_results, quotas):
print(row)预期输出
{'item_id': 101, 'sources': ['popular'], 'source_scores': {'popular': 0.92}}
{'item_id': 102, 'sources': ['cf', 'popular'], 'source_scores': {'popular': 0.88, 'cf': 0.95}}
{'item_id': 104, 'sources': ['cf', 'vector'], 'source_scores': {'cf': 0.9, 'vector': 0.97}}
{'item_id': 106, 'sources': ['vector'], 'source_scores': {'vector': 0.91}}结果只有 4 个唯一物品,因为配额在去重前生效,而重复候选占用了各自通道的名额。这个行为很重要:如果目标候选池必须稳定达到固定大小,就还需要补位逻辑。
去重后补位才不会浪费配额
一个常见线上策略是“两阶段合并”:第一阶段按通道配额取候选并去重;第二阶段发现候选池不足时,再从各路剩余结果中补位,直到达到目标池大小或所有来源耗尽。
补位时最好使用轮询或按权重轮询,而不是继续从某一路一次性拿满,否则“配额控制”会在补位阶段失效。下面给出一个按来源轮询补位的实现。
from collections import deque
def fill_to_target(
results: Dict[str, List[RecallItem]],
merged: List[dict],
target_size: int,
) -> List[dict]:
by_id = {row["item_id"]: row for row in merged}
queues = {}
for source, items in results.items():
queues[source] = deque(
sorted(items, key=lambda x: x.score, reverse=True)
)
while len(by_id) < target_size:
added_in_round = False
for source, queue in queues.items():
while queue:
item = queue.popleft()
if item.item_id in by_id:
row = by_id[item.item_id]
if source not in row["sources"]:
row["sources"].append(source)
row["sources"].sort()
row["source_scores"][source] = item.score
continue
by_id[item.item_id] = {
"item_id": item.item_id,
"sources": [source],
"source_scores": {source: item.score},
}
added_in_round = True
break
if len(by_id) >= target_size:
break
if not added_in_round:
break
return list(by_id.values())
base = merge_with_quota(recall_results, quotas)
filled = fill_to_target(recall_results, base, target_size=6)
print("size:", len(filled))
print("ids:", [row["item_id"] for row in filled])预期输出
size: 6
ids: [101, 102, 104, 106, 103, 105]这个例子中先得到 4 个唯一候选,再按来源轮询补到 6 个。真实系统还应定义稳定的来源遍历顺序,否则不同进程的字典构造顺序可能让补位结果难以复现。
来源标签要为排序阶段服务
融合层输出的 sources 不只是调试字段。排序模型可以把它转成多热特征,例如 from_popular、from_cf、from_vector,也可以使用命中来源数 source_count。同一物品被多个独立通道同时命中,往往本身就是有价值的相关性信号。
不同通道的原始 score 不宜直接横向比较,但可以保留成 source_scores,再由排序侧分别做归一化、分桶或缺失值处理。这样既不丢信息,也不把不同尺度的分数强行混成一个值。
线上验收时至少检查三件事:候选池最终大小是否稳定、各来源实际占比是否符合预期、重复命中后 sources 是否完整。做到这三点,多路召回才能既扩大覆盖,又不会因为单一路径过强而失去候选多样性。