Commit d90e7428c73cf91a1d29df01113a1d9a5386136e

Authored by tangwang
1 parent 038e4e2f

补充重排

config/languages.py 0 → 100644
context/request_context.py
... ... @@ -268,7 +268,6 @@ class RequestContext:
268 268 'rewritten_query': self.query_analysis.rewritten_query,
269 269 'detected_language': self.query_analysis.detected_language,
270 270 'domain': self.query_analysis.domain,
271   - 'has_vector': self.query_analysis.query_vector is not None,
272 271 'is_simple_query': self.query_analysis.is_simple_query
273 272 },
274 273 'performance': {
... ...
docs/recommendation/冷启动和数据稀缺场景下推荐系统.md 0 → 100644
... ... @@ -0,0 +1,113 @@
  1 +
  2 +
  3 +## 一、核心技术框架
  4 +
  5 +### 1. **贝叶斯方法体系 (Bayesian Methods)**
  6 +
  7 +独立站数据稀疏场景下,贝叶斯方法通过引入先验知识弥补数据不足:
  8 +
  9 +| 技术 | 原理 | 应用场景 |
  10 +|------|------|----------|
  11 +| **贝叶斯概率矩阵分解 (BPMF)** | 对用户-物品评分矩阵进行概率建模,引入高斯先验 | 新用户/新商品的评分预测 |
  12 +| **贝叶斯个性化排序 (BPR)** | 利用贝叶斯推断优化排序损失函数 | 冷启动用户的推荐列表生成 |
  13 +| **朴素贝叶斯分类器** | 基于用户属性/物品特征的联合概率分布 | 新用户初次进入时的品类推荐 |
  14 +| **贝叶斯网络** | 构建用户特征-物品特征-评分的因果DAG | 融合内容信息解决冷启动 |
  15 +
  16 +**关键优势**:通过先验分布(如用户画像、商品类目)在数据稀缺时提供合理初始估计,随着数据积累自动更新为后验分布。
  17 +
  18 +### 2. **Contextual Bandit & LinUCB 算法族**
  19 +
  20 +这是解决**探索-利用(EE)**问题的黄金标准,特别适合独立站实时推荐:
  21 +
  22 +**LinUCB (Linear Upper Confidence Bound)**
  23 +- **数学形式**:$a_t = \arg\max_{a \in A} (x_{t,a}^T \hat{\theta}_a + \alpha \sqrt{x_{t,a}^T (A_a)^{-1} x_{t,a}})$
  24 +- **独立站适配**:
  25 + - 将商品作为"臂"(arm),用户特征( demographics、浏览历史)作为上下文(context)
  26 + - 对新商品/新用户自动增加探索项($\alpha$控制探索强度)
  27 + - 在线学习,每轮交互后立即更新参数,无需离线重训练
  28 +
  29 +**汤普森采样 (Thompson Sampling)**
  30 +- 为每个候选物品维护一个奖励概率分布(通常用Beta分布)
  31 +- **冷启动友好**:新物品初始分布较宽(不确定性高),天然获得更多探索机会
  32 +- 淘宝、阿里飞猪等用于推荐理由和首图优选
  33 +
  34 +**EE-Net**
  35 +- 双神经网络结构:一个网络学习利用(Exploitation),另一个网络学习探索潜力(Exploration)
  36 +- 理论保证达到 $\mathcal{O}(\sqrt{T\log T})$ 的累积遗憾界
  37 +
  38 +### 3. **元学习 (Meta-Learning) / 小样本学习**
  39 +
  40 +针对独立站"数据少但用户/商品更新快"的特点:
  41 +
  42 +**MAML-based 推荐**
  43 +- **核心思想**:学习"如何学习",即找到一个好的模型初始化参数,使得仅用极少数据(1-5个交互)就能快速适应新用户
  44 +- **代表工作**:
  45 + - **MeLU** :为冷启动用户生成定制化嵌入向量,只需少量交互即可微调
  46 + - **MetaHIN** :结合异质信息网络(利用商品类目、品牌等side information),通过元路径增强冷启动效果
  47 + - **PAM** :针对流式数据的在线元学习,区分不同流行度级别的物品
  48 +
  49 +**优势**:
  50 +- 将每个用户视为一个task,利用相似用户(如"25岁女性"、"户外运动爱好者")的先验知识
  51 +- 支持**零历史个性化**(Zero-shot),即完全新用户也能基于人口统计学特征给出合理初始推荐
  52 +
  53 +---
  54 +
  55 +## 二、工程实现与SaaS方案
  56 +
  57 +### 1. **开源工具链**
  58 +
  59 +| 工具 | 适用场景 | 核心算法 |
  60 +|------|----------|----------|
  61 +| **Vowpal Wabbit** | 实时个性化、冷启动 | Contextual Bandit (LinUCB, Thompson Sampling),支持在线学习 |
  62 +| **Microsoft Research CB Library** | 企业级A/B测试与推荐 | UCB系列算法,Azure集成 |
  63 +| **Ray RLlib** | 多目标优化(点击+转化+停留) | 支持Multi-Armed Bandit与深度强化学习结合 |
  64 +
  65 +### 2. **独立站SaaS产品技术特点**
  66 +
  67 +**Nosto / Klaviyo**
  68 +- 利用**实时行为触发**弥补数据量不足:如"浏览帐篷的用户最终购买防潮垫"的关联规则
  69 +- **跨站数据聚合**:SaaS形态允许在保护隐私前提下利用同类独立站的匿名化行为模式(联邦学习思想)
  70 +
  71 +**技术组合**:
  72 +```
  73 +冷启动期(0-3个月):Meta-Learning初始化 + Contextual Bandit探索
  74 +增长期(3-6个月):Bayesian深度学习 + 联邦学习跨域增强
  75 +成熟期:标准协同过滤 + 在线学习微调
  76 +```
  77 +
  78 +---
  79 +
  80 +## 三、独立站特化的技术架构建议
  81 +
  82 +### 1. **分层冷启动策略**
  83 +
  84 +**数据层 - Embedding初始化三部曲**:
  85 +1. **分桶共享** (Bucket Shared Embedding):按"性别+年龄段"分桶,同桶用户共享初始向量
  86 +2. **Look-alike老带新**:找到最相似的K个老用户,平均其嵌入作为新用户初始值
  87 +3. **元学习生成**:使用MAML训练一个生成器,输入用户画像特征,输出个性化初始Embedding
  88 +
  89 +**模型层 - Shortcut连接**:
  90 +- 将`is_new_user`特征直接连接到DNN末层(Logits层),强迫模型区分新老用户,避免行为序列信号过强淹没冷启动特征
  91 +
  92 +### 2. **多行为隐式反馈建模**
  93 +
  94 +独立站通常只有点击/加购等隐式反馈,没有显式评分:
  95 +- **行为强度分层**:将点击(弱)、加购(中)、购买(强)作为不同置信度的正样本
  96 +- **Bandit建模**:将物品类别作为arm(而非单个item),降低arm数量,缓解计算复杂度
  97 +
  98 +### 3. **隐私保护的联邦增强**
  99 +
  100 +针对独立站数据孤岛问题:
  101 +- **跨域联邦学习**:多个独立站联合训练共享商品嵌入,本地保留用户数据
  102 +- **差分隐私**:在梯度更新中加入Laplace噪声,保护用户隐私同时解决冷启动
  103 +
  104 +---
  105 +
  106 +## 四、关键论文与资源
  107 +
  108 +1. **LinUCB**:Li et al., "A Contextual-Bandit Approach to Personalized News Article Recommendation" (2010)
  109 +2. **MeLU (元学习)**:Lee et al., "MeLU: Meta-Learned User Preference Estimator for Cold-Start Recommendation" (WWW 2019)
  110 +3. **EE-Net**:Chen et al., "EE-Net: Exploitation-Exploration Neural Networks in Contextual Bandits" (2021)
  111 +4. **Thompson Sampling for Cold-start**:"Modeling implicit feedback based on bandit learning for recommendation" (Neurocomputing 2023)
  112 +
  113 +这些技术方案的核心优势在于:**不依赖大规模历史数据**,通过概率建模、在线学习、跨域知识迁移等方式,在数据稀缺的独立站场景下实现快速收敛和个性化。
0 114 \ No newline at end of file
... ...
docs/recommendation/冷启动和数据稀缺场景下推荐系统2.md 0 → 100644
... ... @@ -0,0 +1,153 @@
  1 +# 独立站推荐系统在数据稀缺和冷启动场景下的先进技术调研报告
  2 +
  3 +## 摘要
  4 +
  5 +独立站(Direct-to-Consumer, DTC)电商平台在构建个性化推荐系统时,普遍面临数据稀缺和冷启动的严峻挑战。与拥有海量用户行为和商品数据的综合电商平台不同,独立站的流量规模较小,用户行为数据稀疏,且商品更新迭代速度快,导致传统的基于大规模监督学习的推荐算法难以有效应用。本报告旨在深入探讨贝叶斯学习、贝叶斯A/B实验、LinUCB以及探索-利用(Exploration-Exploitation, EE)等先进技术如何解决这些问题,并总结领先SaaS服务商在这些领域的实践经验。
  6 +
  7 +## 1. 引言:独立站推荐系统的挑战
  8 +
  9 +随着DTC模式的兴起,越来越多的品牌选择建立自己的独立站以直接触达消费者。然而,独立站的推荐系统在起步阶段和日常运营中,常常遭遇以下核心挑战:
  10 +
  11 +* **数据稀缺(Data Scarcity)**:新用户、新商品或长尾商品缺乏足够的交互数据,导致推荐模型无法准确学习其偏好或特征。
  12 +* **冷启动(Cold Start)**:当系统缺乏足够的用户历史行为或商品信息时,难以生成有效的个性化推荐,从而影响用户体验和转化率。
  13 +
  14 +这些挑战使得依赖大量数据进行训练的深度学习模型在独立站场景下效果不佳,甚至可能因过拟合而产生次优推荐。因此,需要采用更适合小样本、高不确定性环境的算法和策略。
  15 +
  16 +## 2. 先进技术解决方案
  17 +
  18 +### 2.1 贝叶斯学习 (Bayesian Learning)
  19 +
  20 +贝叶斯学习提供了一种在不确定性下进行推理和决策的强大框架。它将模型参数视为随机变量,并通过结合先验知识(Prior)和观测数据(Evidence)来更新对这些参数的信念,形成后验分布(Posterior)。
  21 +
  22 +**核心原理:**
  23 +
  24 +贝叶斯定理:`P(θ|D) = P(D|θ) * P(θ) / P(D)`
  25 +
  26 +其中:
  27 +* `P(θ|D)` 是后验概率,表示在给定数据D的情况下参数θ的概率。
  28 +* `P(D|θ)` 是似然函数,表示在给定参数θ的情况下数据D的概率。
  29 +* `P(θ)` 是先验概率,表示在观测数据D之前参数θ的信念。
  30 +* `P(D)` 是边缘似然,作为归一化常数。
  31 +
  32 +**优势:**
  33 +
  34 +* **不确定性建模**:贝叶斯方法能够自然地量化模型参数的不确定性。在数据稀少时,后验分布会更宽,明确地反映出模型对参数估计的不确定性,这有助于在推荐决策中考虑风险 [1]。
  35 +* **引入先验知识**:可以通过先验分布融入领域专家知识、历史数据或来自其他平台的通用模式,有效缓解冷启动问题。例如,对于新商品,可以利用其品类、品牌等元数据构建先验,而非从零开始学习 [2]。
  36 +
  37 +**应用案例:**
  38 +
  39 +* **Amazon**:在产品搜索中利用经验贝叶斯(Empirical Bayes)方法处理冷启动问题,通过聚合相似商品的统计数据来为新商品提供初始的质量估计 [3]。
  40 +* **BBC**:数据科学团队开发了基于贝叶斯方法的冷启动推荐原型,即使只有少量交互数据也能生成高性能的推荐 [4]。
  41 +
  42 +### 2.2 贝叶斯 A/B 实验 (Bayesian A/B Testing)
  43 +
  44 +A/B测试是评估推荐系统效果的关键工具。传统的频率派A/B测试依赖于P值和固定样本量,在数据稀缺或需要快速迭代的独立站环境中存在局限性。贝叶斯A/B测试则提供了更灵活和直观的决策方式。
  45 +
  46 +**频率派与贝叶斯派对比:**
  47 +
  48 +| 特性 | 频率派 A/B 测试 | 贝叶斯 A/B 测试 |
  49 +| :----------- | :----------------------------------- | :----------------------------------- |
  50 +| **核心问题** | 假设零假设(无差异),计算观测结果发生的概率(P值) | 计算各版本优于基线的概率,以及各版本之间优劣的概率 |
  51 +| **数据窥视** | 不允许(会导致P值失效) | 允许(可随时查看结果并更新信念) |
  52 +| **决策依据** | P值是否小于显著性水平(如0.05) | 后验概率(如B优于A的概率 > 95%)和预期增益区间 |
  53 +| **结果呈现** | 仅能判断是否存在统计显著差异 | 提供预期增益的概率分布和置信区间 |
  54 +| **样本量** | 需要预先确定,达到后才能停止 | 可根据置信度动态停止(Sequential Testing) |
  55 +
  56 +**优势:**
  57 +
  58 +* **灵活的停止规则**:允许在实验过程中随时查看数据并做出决策,无需等待预设样本量,这对于独立站快速迭代和资源有限的场景至关重要 [5]。
  59 +* **直观的商业决策**:直接给出“版本B优于版本A的概率”以及“预期增益”的概率分布,使得业务人员能更清晰地理解实验结果,并权衡切换成本与潜在收益 [6]。
  60 +* **更好地处理小样本**:通过引入先验,贝叶斯方法在小样本情况下也能给出相对稳健的估计。
  61 +
  62 +**SaaS 应用:**
  63 +
  64 +* **AB Tasty** 等主流实验优化平台已采用贝叶斯统计方法,以提供更灵活、更具商业洞察力的A/B测试结果 [5]。
  65 +
  66 +### 2.3 LinUCB 与 EE 探索利用 (Bandit 算法)
  67 +
  68 +多臂老虎机(Multi-Armed Bandit, MAB)算法,特别是其上下文感知版本(Contextual Bandit),是解决推荐系统中探索与利用(Exploration-Exploitation, EE)两难困境的有效工具。在数据稀缺和冷启动场景下,MAB算法能够动态地平衡探索新商品以获取更多信息和利用已知最优商品以最大化收益。
  69 +
  70 +**探索与利用 (Exploration-Exploitation, EE):**
  71 +
  72 +* **探索 (Exploration)**:尝试推荐新商品或不确定性高的商品,以发现潜在的用户兴趣或商品价值。
  73 +* **利用 (Exploitation)**:推荐已知能带来高收益的商品,以最大化短期回报。
  74 +
  75 +**LinUCB (Linear Upper Confidence Bound):**
  76 +
  77 +LinUCB是一种经典的上下文MAB算法,它假设每个“臂”(即推荐商品)的奖励(如点击率、购买率)是其特征的线性函数。它通过维护每个臂的线性模型参数,并利用置信区间上界(Upper Confidence Bound)来指导选择。
  78 +
  79 +**核心原理:**
  80 +
  81 +LinUCB在每次推荐时,会为每个候选商品计算一个分数,该分数由两部分组成:
  82 +
  83 +1. **预测奖励**:基于当前线性模型对该商品特征的预测。
  84 +2. **探索奖励**:基于该商品参数估计的不确定性(通常是置信区间宽度),不确定性越高,探索奖励越大。
  85 +
  86 +选择分最高的商品进行推荐。随着商品被探索,其参数估计的不确定性会降低,探索奖励也会随之减少,从而实现从探索到利用的平滑过渡 [7]。
  87 +
  88 +**优势:**
  89 +
  90 +* **实时适应性**:能够根据用户的实时反馈(点击、购买)快速更新模型,适应用户偏好和商品热度的动态变化。
  91 +* **冷启动友好**:新商品由于缺乏交互数据,其参数估计的不确定性高,因此会获得较高的探索奖励,从而有机会被推荐给用户,有效缓解商品冷启动 [8]。
  92 +* **上下文感知**:可以整合用户特征、商品特征、场景特征等上下文信息,生成更个性化的推荐。
  93 +
  94 +**应用案例:**
  95 +
  96 +* **Yahoo!**:在新闻推荐中广泛使用LinUCB,通过结合新闻文章的特征和用户上下文,实现个性化新闻分发 [9]。
  97 +* **阿里巴巴**:在商品推荐中采用LinUCB,并结合用户浏览模型来处理位置偏差,优化移动端推荐效果 [10]。
  98 +
  99 +### 2.4 Thompson Sampling (汤普森采样)
  100 +
  101 +Thompson Sampling是另一种流行的贝叶斯MAB算法,它通过从每个臂的后验奖励分布中进行采样来选择臂。它在理论上具有较好的性能,并且在实践中表现出色。
  102 +
  103 +**核心原理:**
  104 +
  105 +对于每个候选商品,Thompson Sampling会维护一个关于其奖励的后验概率分布(例如,对于二元奖励,可以使用Beta分布)。在每次推荐时,它会从每个商品的后验分布中随机抽取一个样本值,然后选择样本值最高的商品进行推荐 [11]。
  106 +
  107 +**优势:**
  108 +
  109 +* **自然地平衡探索与利用**:采样过程本身就体现了探索与利用的平衡。不确定性高的商品(后验分布较宽)有更大的机会被采样到高值,从而获得探索机会;而确定性高的商品(后验分布较窄)则倾向于被采样到接近其真实均值的值,从而被利用。
  110 +* **理论性能优越**:在许多场景下,Thompson Sampling被证明具有接近最优的遗憾(Regret)性能。
  111 +* **易于实现**:对于某些简单的奖励分布(如伯努利奖励),其实现相对直观。
  112 +
  113 +**应用案例:**
  114 +
  115 +* **Doordash**:利用Thompson Sampling进行菜系推荐,根据用户对不同菜系的订单历史构建Beta分布,从而个性化展示菜系过滤器 [12]。
  116 +* **Amazon**:在优化页面布局时采用多元Thompson Sampling,通过对模型权重进行采样来探索不同的布局组合 [13]。
  117 +
  118 +## 3. 领先SaaS厂商的实践
  119 +
  120 +许多为独立站提供推荐服务的SaaS厂商,已经将上述先进技术融入其产品中,以帮助客户应对数据挑战:
  121 +
  122 +* **Algolia**:作为搜索和推荐SaaS,Algolia强调利用预训练AI算法和合成数据来解决冷启动问题,并提供实时推理能力,确保推荐的及时性和相关性 [14]。
  123 +* **Nosto**:专注于电商个性化,其推荐引擎利用Bandit算法进行实时多变量优化,以平衡新商品的曝光和个性化推荐的准确性。
  124 +* **Spotify / Netflix**:虽然不是纯粹的独立站SaaS,但这些内容平台在处理新内容分发、UI布局优化和封面图A/B测试时,大量采用了Bandit算法和贝叶斯方法,其经验对独立站具有借鉴意义 [15] [16]。
  125 +
  126 +## 4. 总结与展望
  127 +
  128 +独立站推荐系统在数据稀缺和冷启动场景下,传统的监督学习方法面临巨大挑战。贝叶斯学习、贝叶斯A/B实验、LinUCB和Thompson Sampling等先进技术,通过有效建模不确定性、引入先验知识以及动态平衡探索与利用,为独立站提供了强大的解决方案。
  129 +
  130 +* **贝叶斯学习**:通过后验分布量化不确定性,并利用先验知识缓解数据稀疏。
  131 +* **贝叶斯A/B实验**:提供更灵活、更具商业洞察力的实验评估方式,加速产品迭代。
  132 +* **LinUCB和Thompson Sampling**:作为上下文MAB算法,能够实时适应用户偏好,并有效解决新商品和新用户的冷启动问题。
  133 +
  134 +未来,随着独立站生态的不断发展,这些技术将继续演进,并可能与更复杂的深度学习模型相结合,形成混合推荐系统,以在数据充足时发挥深度学习的强大拟合能力,在数据稀缺时则依赖贝叶斯和Bandit算法的鲁棒性。同时,可解释性(Explainability)和公平性(Fairness)也将成为独立站推荐系统发展的重要方向。
  135 +
  136 +## 参考文献
  137 +
  138 +[1] BayesCNS: A Unified Bayesian Approach to Address Cold Start and Non-Stationarity in Search Systems at Scale. [https://arxiv.org/html/2410.02126v1](https://arxiv.org/html/2410.02126v1)
  139 +[2] Bayesian cold-start recommender - by Matt Crooks. [https://medium.com/bbc-data-science/bayesian-cold-start-recommender-810c1cf9a5d6](https://medium.com/bbc-data-science/bayesian-cold-start-recommender-810c1cf9a5d6)
  140 +[3] Addressing cold start in product search via empirical bayes. [https://www.amazon.science/publications/addressing-cold-start-in-product-search-via-empirical-bayes](https://www.amazon.science/publications/addressing-cold-start-in-product-search-via-empirical-bayes)
  141 +[4] BayesCNS: A Unified Bayesian Approach to Address Cold Start and Non-Stationarity in Search Systems at Scale. [https://ojs.aaai.org/index.php/AAAI/article/download/31975/34130](https://ojs.aaai.org/index.php/AAAI/article/download/31975/34130)
  142 +[5] Frequentist vs Bayesian Methods in A/B Testing - Which is Better? [https://www.abtasty.com/blog/bayesian-ab-testing/](https://www.abtasty.com/blog/bayesian-ab-testing/)
  143 +[6] A comparative study of frequentist vs Bayesian A/B testing in the detection of E-commerce fraud. [https://www.emerald.com/jebde/article/1/1-2/3/225916/A-comparative-study-of-frequentist-vs-Bayesian-A-B](https://www.emerald.com/jebde/article/1/1-2/3/225916/A-comparative-study-of-frequentist-vs-Bayesian-A-B)
  144 +[7] Recommender systems using LinUCB: A contextual multi-armed bandit approach. [https://medium.com/data-science/recommender-systems-using-linucb-a-contextual-multi-armed-bandit-approach-35a6f0eb6c4](https://medium.com/data-science/recommender-systems-using-linucb-a-contextual-multi-armed-bandit-approach-35a6f0eb6c4)
  145 +[8] Bandits for Recommender Systems. [https://eugeneyan.com/writing/bandits/](https://eugeneyan.com/writing/bandits/)
  146 +[9] The classic example of UCB is Yahoo’s LinUCB for news recommendations. [https://eugeneyan.com/writing/bandits/](https://eugeneyan.com/writing/bandits/)
  147 +[10] Alibaba’s LinUCB for item recommendations. [https://eugeneyan.com/writing/bandits/](https://eugeneyan.com/writing/bandits/)
  148 +[11] Now, why should we care about Recommendation Systems? ft. a soft introduction to Thompson Sampling. [https://towardsdatascience.com/now-why-should-we-care-about-recommendation-systems-ft-a-soft-introduction-to-thompson-sampling-b9483b43f262/](https://towardsdatascience.com/now-why-should-we-care-about-recommendation-systems-ft-a-soft-introduction-to-thompson-sampling-b9483b43f262/)
  149 +[12] Doordash’s bandits for cuisine recommendations. [https://eugeneyan.com/writing/bandits/](https://eugeneyan.com/writing/bandits/)
  150 +[13] Amazon’s multivariate bandits to optimize page layouts. [https://eugeneyan.com/writing/bandits/](https://eugeneyan.com/writing/bandits/)
  151 +[14] Solving the cold start problem with synthetic data. [https://www.algolia.com/blog/ai/using-pre-trained-ai-algorithms-to-solve-the-cold-start-problem](https://www.algolia.com/blog/ai/using-pre-trained-ai-algorithms-to-solve-the-cold-start-problem)
  152 +[15] Bandits for Recommender Systems. [https://eugeneyan.com/writing/bandits/](https://eugeneyan.com/writing/bandits/)
  153 +[16] Artwork Personalization at Netflix. [https://eugeneyan.com/writing/bandits/](https://eugeneyan.com/writing/bandits/)
... ...
docs/搜索API对接指南.md
... ... @@ -64,7 +64,7 @@
64 64  
65 65 ### 1.1 基础信息
66 66  
67   -- **Base URL**: `http://your-domain:6002` 或 `http://120.76.41.98:6002`
  67 +- **Base URL**: `http://120.76.41.98:6002`
68 68 - **协议**: HTTP/HTTPS
69 69 - **数据格式**: JSON
70 70 - **字符编码**: UTF-8
... ... @@ -715,8 +715,7 @@ curl "http://localhost:6002/search/12345"
715 715 "translations": {
716 716 "en": "barbie doll"
717 717 },
718   - "domain": "default",
719   - "has_vector": true
  718 + "domain": "default"
720 719 },
721 720 "suggestions": [],
722 721 "related_searches": [],
... ... @@ -739,7 +738,7 @@ curl "http://localhost:6002/search/12345"
739 738 | `total` | integer | 匹配的总文档数 |
740 739 | `max_score` | float | 最高相关性分数 |
741 740 | `facets` | array | 分面统计结果 |
742   -| `query_info` | object | 查询处理信息,见 [4.2.1 query_info 说明](#421-query_info-说明) |
  741 +| `query_info` | object | query处理信息 |
743 742 | `took_ms` | integer | 搜索耗时(毫秒) |
744 743  
745 744 #### 4.2.1 query_info 说明
... ... @@ -754,7 +753,6 @@ curl "http://localhost:6002/search/12345"
754 753 | `detected_language` | string | 检测到的查询语言(如 `zh`、`en`) |
755 754 | `translations` | object | 翻译结果,键为语言代码,值为翻译文本 |
756 755 | `domain` | string | 查询域(如 `default`、`title`、`brand` 等) |
757   -| `has_vector` | boolean | 是否生成了查询向量(用于语义检索) |
758 756  
759 757 ### 4.3 SpuResult字段说明
760 758  
... ...
frontend/static/js/app.js
... ... @@ -767,7 +767,6 @@ function displayDebugInfo(data) {
767 767 html += `<div>boolean_ast: ${escapeHtml(debugInfo.query_analysis.boolean_ast)}</div>`;
768 768 }
769 769  
770   - html += `<div>has_vector: ${debugInfo.query_analysis.has_vector ? 'enabled' : 'disabled'}</div>`;
771 770 html += '</div>';
772 771 }
773 772  
... ...
query/query_parser.py
... ... @@ -313,8 +313,7 @@ class QueryParser:
313 313 should_generate_embedding = (
314 314 generate_vector and
315 315 self.config.query_config.enable_text_embedding and
316   - domain == "default" and
317   - not is_short_query
  316 + domain == "default"
318 317 )
319 318  
320 319 encoding_executor = None
... ...
query/translator.py
... ... @@ -45,6 +45,7 @@ from concurrent.futures import ThreadPoolExecutor, Future
45 45 from datetime import timedelta
46 46 from typing import Dict, List, Optional, Union
47 47 import logging
  48 +import time
48 49  
49 50 logger = logging.getLogger(__name__)
50 51  
... ... @@ -349,6 +350,7 @@ class Translator:
349 350 }
350 351 ]
351 352  
  353 + start_time = time.time()
352 354 try:
353 355 completion = self.qwen_client.chat.completions.create(
354 356 model=self.QWEN_MODEL,
... ... @@ -359,17 +361,19 @@ class Translator:
359 361 )
360 362  
361 363 translated_text = completion.choices[0].message.content.strip()
  364 + duration_ms = (time.time() - start_time) * 1000
362 365  
363   - logger.debug(
  366 + logger.info(
364 367 f"[Translator] Qwen API response success | Original text: '{text}' | Target language: {target_lang_qwen} | "
365   - f"Translation result: '{translated_text}'"
  368 + f"Translation result: '{translated_text}' | Duration: {duration_ms:.2f} ms"
366 369 )
367 370 return translated_text
368 371  
369 372 except Exception as e:
  373 + duration_ms = (time.time() - start_time) * 1000
370 374 logger.error(
371 375 f"[Translator] Qwen API request exception | Original text: '{text}' | Target language: {target_lang_qwen} | "
372   - f"Error: {e}", exc_info=True
  376 + f"Duration: {duration_ms:.2f} ms | Error: {e}", exc_info=True
373 377 )
374 378 return None
375 379  
... ...
reranker/README.md 0 → 100644
... ... @@ -0,0 +1,87 @@
  1 +# Reranker Service (BGE v2 m3)
  2 +
  3 +A minimal, production-ready reranker service based on **BAAI/bge-reranker-v2-m3**.
  4 +
  5 +Features
  6 +- FP16 on GPU
  7 +- Length-based sorting to reduce padding waste
  8 +- Deduplication to avoid redundant inference
  9 +- Scores returned in original input order
  10 +- Simple FastAPI service
  11 +
  12 +## Files
  13 +- `reranker/bge_reranker.py`: core model loading + scoring logic
  14 +- `reranker/server.py`: FastAPI service with `/health` and `/rerank`
  15 +- `reranker/config.py`: simple configuration
  16 +
  17 +## Requirements
  18 +Install Python deps (already in project requirements):
  19 +- `torch`
  20 +- `modelscope`
  21 +- `fastapi`
  22 +- `uvicorn`
  23 +
  24 +## Configuration
  25 +Edit `reranker/config.py`:
  26 +- `MODEL_NAME`: default `BAAI/bge-reranker-v2-m3`
  27 +- `DEVICE`: `None` (auto), `cuda`, or `cpu`
  28 +- `USE_FP16`: enable fp16 on GPU
  29 +- `BATCH_SIZE`: default 64
  30 +- `MAX_LENGTH`: default 512
  31 +- `PORT`: default 6007
  32 +- `MAX_DOCS`: request limit (default 1000)
  33 +
  34 +## Run the Service
  35 +```bash
  36 +uvicorn reranker.server:app --host 0.0.0.0 --port 6007
  37 +```
  38 +
  39 +## API
  40 +### Health
  41 +```
  42 +GET /health
  43 +```
  44 +
  45 +### Rerank
  46 +```
  47 +POST /rerank
  48 +Content-Type: application/json
  49 +
  50 +{
  51 + "query": "wireless mouse",
  52 + "docs": ["logitech mx master", "usb cable", "wireless mouse bluetooth"]
  53 +}
  54 +```
  55 +
  56 +Response:
  57 +```
  58 +{
  59 + "scores": [0.93, 0.02, 0.88],
  60 + "meta": {
  61 + "input_docs": 3,
  62 + "usable_docs": 3,
  63 + "unique_docs": 3,
  64 + "dedup_ratio": 0.0,
  65 + "elapsed_ms": 12.4,
  66 + "model": "BAAI/bge-reranker-v2-m3",
  67 + "device": "cuda",
  68 + "fp16": true,
  69 + "batch_size": 64,
  70 + "max_length": 512,
  71 + "normalize": true,
  72 + "service_elapsed_ms": 13.1
  73 + }
  74 +}
  75 +```
  76 +
  77 +## Logging
  78 +The service uses standard Python logging. For structured logs and full output,
  79 +run uvicorn with:
  80 +```bash
  81 +uvicorn reranker.server:app --host 0.0.0.0 --port 6007 --log-level info
  82 +```
  83 +
  84 +## Notes
  85 +- No caching is used by design.
  86 +- Inputs are deduplicated by exact string match.
  87 +- Empty or null docs are skipped and scored as 0.
... ...
reranker/bge_reranker.py 0 → 100644
... ... @@ -0,0 +1,256 @@
  1 +"""
  2 +Minimal BGE reranker for pairwise scoring (query, doc).
  3 +
  4 +Features:
  5 +- Model loading with optional FP16
  6 +- Length-based sorting to reduce padding waste
  7 +- Deduplication to avoid redundant inference
  8 +- Scores returned in original doc order
  9 +"""
  10 +
  11 +import logging
  12 +import math
  13 +import threading
  14 +import time
  15 +from typing import Any, Dict, List, Optional, Tuple
  16 +
  17 +import torch
  18 +from modelscope import AutoModelForSequenceClassification, AutoTokenizer
  19 +
  20 +logger = logging.getLogger("reranker.core")
  21 +
  22 +
  23 +class BGEReranker:
  24 + def __init__(
  25 + self,
  26 + model_name: str = "BAAI/bge-reranker-v2-m3",
  27 + device: Optional[str] = None,
  28 + batch_size: int = 64,
  29 + use_fp16: bool = True,
  30 + max_length: int = 512,
  31 + cache_dir: str = "./model_cache",
  32 + enable_warmup: bool = True,
  33 + ) -> None:
  34 + self.model_name = model_name
  35 + self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
  36 + self.batch_size = max(1, int(batch_size))
  37 + self.max_length = int(max_length)
  38 + self.use_fp16 = bool(use_fp16 and self.device == "cuda")
  39 + self._lock = threading.Lock()
  40 +
  41 + logger.info(
  42 + "[BGE_RERANKER] Loading model %s on %s (fp16=%s)",
  43 + self.model_name,
  44 + self.device,
  45 + self.use_fp16,
  46 + )
  47 +
  48 + self.tokenizer = AutoTokenizer.from_pretrained(
  49 + self.model_name, trust_remote_code=True, cache_dir=cache_dir
  50 + )
  51 + self.model = AutoModelForSequenceClassification.from_pretrained(
  52 + self.model_name, trust_remote_code=True, cache_dir=cache_dir
  53 + )
  54 +
  55 + self.model = self.model.to(self.device)
  56 + self.model.eval()
  57 +
  58 + if self.use_fp16:
  59 + self.model = self.model.half()
  60 +
  61 + if self.device == "cuda":
  62 + torch.backends.cudnn.benchmark = True
  63 +
  64 + if enable_warmup:
  65 + self._warmup()
  66 +
  67 + logger.info(
  68 + "[BGE_RERANKER] Model ready | model=%s device=%s fp16=%s batch=%s max_len=%s",
  69 + self.model_name,
  70 + self.device,
  71 + self.use_fp16,
  72 + self.batch_size,
  73 + self.max_length,
  74 + )
  75 +
  76 + def _warmup(self) -> None:
  77 + try:
  78 + with torch.inference_mode():
  79 + pairs = [["warmup", "warmup"]]
  80 + inputs = self.tokenizer(
  81 + pairs,
  82 + padding=True,
  83 + truncation=True,
  84 + return_tensors="pt",
  85 + max_length=self.max_length,
  86 + )
  87 + inputs = {k: v.to(self.device) for k, v in inputs.items()}
  88 + if self.use_fp16:
  89 + inputs = {
  90 + k: (v.half() if v.dtype == torch.float32 else v)
  91 + for k, v in inputs.items()
  92 + }
  93 + _ = self.model(**inputs, return_dict=True).logits
  94 + if self.device == "cuda":
  95 + torch.cuda.synchronize()
  96 + except Exception as exc:
  97 + logger.warning("[BGE_RERANKER] Warmup failed: %s", exc)
  98 +
  99 + def score(self, query: str, docs: List[str], normalize: bool = True) -> List[float]:
  100 + scores, _meta = self.score_with_meta(query, docs, normalize=normalize)
  101 + return scores
  102 +
  103 + def score_with_meta(
  104 + self, query: str, docs: List[str], normalize: bool = True
  105 + ) -> Tuple[List[float], Dict[str, Any]]:
  106 + start_ts = time.time()
  107 +
  108 + if docs is None:
  109 + docs = []
  110 +
  111 + query = "" if query is None else str(query).strip()
  112 + total_docs = len(docs)
  113 + output_scores: List[float] = [0.0] * total_docs
  114 +
  115 + indexed_docs: List[Tuple[int, str]] = []
  116 + for i, doc in enumerate(docs):
  117 + if doc is None:
  118 + continue
  119 + text = str(doc).strip()
  120 + if not text:
  121 + continue
  122 + indexed_docs.append((i, text))
  123 +
  124 + if not query or not indexed_docs:
  125 + elapsed_ms = (time.time() - start_ts) * 1000.0
  126 + return output_scores, {
  127 + "input_docs": total_docs,
  128 + "usable_docs": len(indexed_docs),
  129 + "unique_docs": 0,
  130 + "dedup_ratio": 0.0,
  131 + "elapsed_ms": round(elapsed_ms, 3),
  132 + }
  133 +
  134 + # Sort by estimated length + text to cluster similar lengths
  135 + indexed_docs.sort(key=lambda x: (len(x[1]), x[1]))
  136 +
  137 + unique_texts: List[str] = []
  138 + position_to_unique: List[int] = []
  139 + prev_text: Optional[str] = None
  140 +
  141 + for _idx, text in indexed_docs:
  142 + if text != prev_text:
  143 + unique_texts.append(text)
  144 + prev_text = text
  145 + position_to_unique.append(len(unique_texts) - 1)
  146 +
  147 + logger.debug(
  148 + "[BGE_RERANKER] Preprocess | input=%d usable=%d unique=%d",
  149 + total_docs,
  150 + len(indexed_docs),
  151 + len(unique_texts),
  152 + )
  153 +
  154 + unique_scores = self._score_unique(
  155 + query=query, passages=unique_texts, normalize=normalize
  156 + )
  157 +
  158 + for (orig_idx, _text), unique_idx in zip(indexed_docs, position_to_unique):
  159 + output_scores[orig_idx] = float(unique_scores[unique_idx])
  160 +
  161 + elapsed_ms = (time.time() - start_ts) * 1000.0
  162 + dedup_ratio = 0.0
  163 + if indexed_docs:
  164 + dedup_ratio = 1.0 - (len(unique_texts) / float(len(indexed_docs)))
  165 +
  166 + meta = {
  167 + "input_docs": total_docs,
  168 + "usable_docs": len(indexed_docs),
  169 + "unique_docs": len(unique_texts),
  170 + "dedup_ratio": round(dedup_ratio, 4),
  171 + "elapsed_ms": round(elapsed_ms, 3),
  172 + "model": self.model_name,
  173 + "device": self.device,
  174 + "fp16": self.use_fp16,
  175 + "batch_size": self.batch_size,
  176 + "max_length": self.max_length,
  177 + "normalize": normalize,
  178 + }
  179 +
  180 + logger.info(
  181 + "[BGE_RERANKER] Done | input=%d usable=%d unique=%d dedup=%s elapsed_ms=%s",
  182 + meta["input_docs"],
  183 + meta["usable_docs"],
  184 + meta["unique_docs"],
  185 + meta["dedup_ratio"],
  186 + meta["elapsed_ms"],
  187 + )
  188 +
  189 + return output_scores, meta
  190 +
  191 + def _compute_optimal_batch_size(self, total: int) -> int:
  192 + if total <= 0:
  193 + return 1
  194 + current_batch_size = self.batch_size + 8
  195 + current_batch_count = math.ceil(total / current_batch_size)
  196 +
  197 + optimal_batch_size = current_batch_size
  198 + test_batch_size = current_batch_size - 4
  199 +
  200 + while test_batch_size > 0:
  201 + test_batch_count = math.ceil(total / test_batch_size)
  202 + if test_batch_count <= current_batch_count:
  203 + optimal_batch_size = test_batch_size
  204 + test_batch_size -= 4
  205 + else:
  206 + break
  207 +
  208 + return max(1, optimal_batch_size)
  209 +
  210 + def _score_unique(
  211 + self, query: str, passages: List[str], normalize: bool = True
  212 + ) -> List[float]:
  213 + if not passages:
  214 + return []
  215 +
  216 + optimal_batch_size = self._compute_optimal_batch_size(len(passages))
  217 +
  218 + logger.info(
  219 + "[BGE_RERANKER] Reranking %d unique passages | batch=%d | device=%s | fp16=%s",
  220 + len(passages),
  221 + optimal_batch_size,
  222 + self.device,
  223 + self.use_fp16,
  224 + )
  225 +
  226 + scores: List[float] = []
  227 +
  228 + with self._lock:
  229 + for i in range(0, len(passages), optimal_batch_size):
  230 + batch_passages = passages[i : i + optimal_batch_size]
  231 + pairs = [[query, passage] for passage in batch_passages]
  232 +
  233 + with torch.inference_mode():
  234 + inputs = self.tokenizer(
  235 + pairs,
  236 + padding=True,
  237 + truncation=True,
  238 + return_tensors="pt",
  239 + max_length=self.max_length,
  240 + add_special_tokens=True,
  241 + )
  242 + inputs = {k: v.to(self.device) for k, v in inputs.items()}
  243 +
  244 + if self.use_fp16:
  245 + inputs = {
  246 + k: (v.half() if v.dtype == torch.float32 else v)
  247 + for k, v in inputs.items()
  248 + }
  249 +
  250 + logits = self.model(**inputs, return_dict=True).logits.view(-1).float()
  251 + if normalize:
  252 + logits = torch.sigmoid(logits)
  253 + batch_scores = logits.detach().cpu().numpy().tolist()
  254 + scores.extend(batch_scores)
  255 +
  256 + return scores
... ...
reranker/config.py 0 → 100644
... ... @@ -0,0 +1,25 @@
  1 +"""Reranker service configuration (simple Python config)."""
  2 +
  3 +
  4 +class RerankerConfig(object):
  5 + # Server
  6 + HOST = "0.0.0.0"
  7 + PORT = 6007
  8 +
  9 + # Model
  10 + MODEL_NAME = "BAAI/bge-reranker-v2-m3"
  11 + DEVICE = None # None -> auto (cuda if available)
  12 + USE_FP16 = True
  13 + BATCH_SIZE = 64
  14 + MAX_LENGTH = 512
  15 + CACHE_DIR = "./model_cache"
  16 + ENABLE_WARMUP = True
  17 +
  18 + # Request limits
  19 + MAX_DOCS = 1000
  20 +
  21 + # Output
  22 + NORMALIZE = True
  23 +
  24 +
  25 +CONFIG = RerankerConfig()
... ...
reranker/server.py 0 → 100644
... ... @@ -0,0 +1,138 @@
  1 +"""
  2 +FastAPI service for BGE reranking.
  3 +
  4 +POST /rerank
  5 +Request:
  6 +{
  7 + "query": "...",
  8 + "docs": ["doc1", "doc2", ...]
  9 +}
  10 +
  11 +Response:
  12 +{
  13 + "scores": [0.98, 0.12, ...],
  14 + "meta": {...}
  15 +}
  16 +"""
  17 +
  18 +import logging
  19 +import time
  20 +from typing import Any, Dict, List, Optional
  21 +
  22 +from fastapi import FastAPI, HTTPException
  23 +from pydantic import BaseModel, Field
  24 +
  25 +from reranker.bge_reranker import BGEReranker
  26 +from reranker.config import CONFIG
  27 +
  28 +logging.basicConfig(
  29 + level=logging.INFO,
  30 + format="%(asctime)s %(levelname)s %(name)s | %(message)s",
  31 +)
  32 +logger = logging.getLogger("reranker.service")
  33 +
  34 +app = FastAPI(title="SearchEngine Reranker Service", version="1.0.0")
  35 +
  36 +_reranker: Optional[BGEReranker] = None
  37 +
  38 +
  39 +class RerankRequest(BaseModel):
  40 + query: str = Field(..., description="Search query")
  41 + docs: List[str] = Field(..., description="Documents/passages to rerank")
  42 + normalize: Optional[bool] = Field(
  43 + default=CONFIG.NORMALIZE, description="Apply sigmoid normalization"
  44 + )
  45 +
  46 +
  47 +class RerankResponse(BaseModel):
  48 + scores: List[float] = Field(..., description="Scores aligned to input docs order")
  49 + meta: Dict[str, Any] = Field(default_factory=dict)
  50 +
  51 +
  52 +@app.on_event("startup")
  53 +def load_model() -> None:
  54 + global _reranker
  55 + logger.info("Starting reranker service on port %s", CONFIG.PORT)
  56 + try:
  57 + _reranker = BGEReranker(
  58 + model_name=CONFIG.MODEL_NAME,
  59 + device=CONFIG.DEVICE,
  60 + batch_size=CONFIG.BATCH_SIZE,
  61 + use_fp16=CONFIG.USE_FP16,
  62 + max_length=CONFIG.MAX_LENGTH,
  63 + cache_dir=CONFIG.CACHE_DIR,
  64 + enable_warmup=CONFIG.ENABLE_WARMUP,
  65 + )
  66 + logger.info(
  67 + "Reranker ready | model=%s device=%s fp16=%s batch=%s max_len=%s",
  68 + CONFIG.MODEL_NAME,
  69 + _reranker.device,
  70 + _reranker.use_fp16,
  71 + _reranker.batch_size,
  72 + _reranker.max_length,
  73 + )
  74 + except Exception as exc:
  75 + logger.error("Failed to initialize reranker: %s", exc, exc_info=True)
  76 + raise
  77 +
  78 +
  79 +@app.get("/health")
  80 +def health() -> Dict[str, Any]:
  81 + return {
  82 + "status": "ok" if _reranker is not None else "unavailable",
  83 + "model_loaded": _reranker is not None,
  84 + "model": CONFIG.MODEL_NAME,
  85 + "device": CONFIG.DEVICE,
  86 + }
  87 +
  88 +
  89 +@app.post("/rerank", response_model=RerankResponse)
  90 +def rerank(request: RerankRequest) -> RerankResponse:
  91 + if _reranker is None:
  92 + raise HTTPException(status_code=503, detail="Reranker model not loaded")
  93 +
  94 + query = (request.query or "").strip()
  95 + if not query:
  96 + raise HTTPException(status_code=400, detail="query cannot be empty")
  97 +
  98 + if request.docs is None or len(request.docs) == 0:
  99 + raise HTTPException(status_code=400, detail="docs cannot be empty")
  100 +
  101 + if len(request.docs) > CONFIG.MAX_DOCS:
  102 + raise HTTPException(
  103 + status_code=400,
  104 + detail=f"Too many docs: {len(request.docs)} > {CONFIG.MAX_DOCS}",
  105 + )
  106 +
  107 + normalize = CONFIG.NORMALIZE if request.normalize is None else bool(request.normalize)
  108 +
  109 + start_ts = time.time()
  110 + logger.info(
  111 + "Rerank request | docs=%d normalize=%s",
  112 + len(request.docs),
  113 + normalize,
  114 + )
  115 + scores, meta = _reranker.score_with_meta(query, request.docs, normalize=normalize)
  116 + meta = dict(meta)
  117 + meta.update({"service_elapsed_ms": round((time.time() - start_ts) * 1000.0, 3)})
  118 + logger.info(
  119 + "Rerank done | docs=%d unique=%s dedup=%s elapsed_ms=%s",
  120 + meta.get("input_docs"),
  121 + meta.get("unique_docs"),
  122 + meta.get("dedup_ratio"),
  123 + meta.get("service_elapsed_ms"),
  124 + )
  125 +
  126 + return RerankResponse(scores=scores, meta=meta)
  127 +
  128 +
  129 +if __name__ == "__main__":
  130 + import uvicorn
  131 +
  132 + uvicorn.run(
  133 + "reranker.server:app",
  134 + host=CONFIG.HOST,
  135 + port=CONFIG.PORT,
  136 + reload=False,
  137 + log_level="info",
  138 + )
... ...