From 928468042f4da4683a0adbab1eee2cef488017ff Mon Sep 17 00:00:00 2001 From: xiaowei Date: Sat, 30 May 2026 20:57:16 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20MMRSelect=20=E4=BD=BF=E7=94=A8=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=20bigram=20Jaccard=20=E7=9B=B8=E4=BC=BC=E5=BA=A6?= =?UTF-8?q?=E6=9B=BF=E4=BB=A3=E7=A9=BA=E5=90=91=E9=87=8F=20cosineSimilarit?= =?UTF-8?q?y?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原问题:Rust LanceDB IPC search 不返回 vector,导致 cosineSimilarity 永远为 0, MMR 退化为纯相关性排序(无多样性去重效果)。 修复:改用 Content 字段的字符 bigram Jaccard 相似度,并修正 MMR 公式 (从 (1-λ)*rel - λ*maxSim 改为 (1-λ)*rel + λ*(1-maxSim), 使 maxSim 高时 MMR 降低,符合设计文档 §2.6) --- go/internal/storage/recall.go | 38 ++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/go/internal/storage/recall.go b/go/internal/storage/recall.go index 0a2fa27..f3ad768 100644 --- a/go/internal/storage/recall.go +++ b/go/internal/storage/recall.go @@ -234,7 +234,38 @@ func (p *RecallPipeline) Recall(query, namespace string, topK int, diversity flo return results, nil } -// MMRSelect 多样性去重 — 开放给 recall/debug 诊断端点 +// jaccardBigramSimilarity 计算两个文本的字符 bigram Jaccard 相似度(用于 MMR 去重) +func jaccardBigramSimilarity(a, b string) float64 { + bgA := make(map[string]bool) + bgB := make(map[string]bool) + runes := []rune(a) + for i := 0; i < len(runes)-1; i++ { + bgA[string(runes[i:i+2])] = true + } + runes = []rune(b) + for i := 0; i < len(runes)-1; i++ { + bgB[string(runes[i:i+2])] = true + } + if len(bgA) == 0 && len(bgB) == 0 { + return 1.0 // 两个空文本视为相同 + } + if len(bgA) == 0 || len(bgB) == 0 { + return 0.0 + } + intersection := 0 + for k := range bgA { + if bgB[k] { + intersection++ + } + } + union := len(bgA) + len(bgB) - intersection + if union == 0 { + return 0.0 + } + return float64(intersection) / float64(union) +} + +// MMRSelect 多样性去重 — 使用文本 bigram Jaccard 相似度(向量由 Rust LanceDB 返回但为空,改用文本) func MMRSelect(reranked []models.RerankResult, candidates []models.MemoryRecord, k int, lambda float64) []int { if len(reranked) == 0 { return nil @@ -259,13 +290,14 @@ func MMRSelect(reranked []models.RerankResult, candidates []models.MemoryRecord, maxSim := 0.0 for _, si := range selected { if si < len(candidates) && ci < len(candidates) { - sim := cosineSimilarity(candidates[ci].Vector, candidates[si].Vector) + sim := jaccardBigramSimilarity(candidates[ci].Content, candidates[si].Content) if sim > maxSim { maxSim = sim } } } - mmr := (1-lambda)*rel - lambda*maxSim + // MMR = (1-λ)*rel + λ*(1-maxSim) + mmr := (1-lambda)*rel + lambda*(1-maxSim) if mmr > bestScore { bestScore = mmr bestIdx = i