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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""BGE-M3 嵌入服务.
|
| 2 |
+
|
| 3 |
+
BGE-M3 单模型产出三路表示 (FlagEmbedding 库):
|
| 4 |
+
- dense_vecs: 1024 维稠密向量 (语义)
|
| 5 |
+
- lexical_weights: SPLADE 风格稀疏权重 (精确词命中)
|
| 6 |
+
- colbert_vecs: 多向量 (每 token 一个 1024 维) (late interaction)
|
| 7 |
+
|
| 8 |
+
设计:
|
| 9 |
+
- 全局单例 BGEM3FlagModel (首次调用懒加载)
|
| 10 |
+
- encode() 异步, 内部走线程池 (CPU 密集)
|
| 11 |
+
- encode_query() 给单 query 用, 自动加 instruction prefix
|
| 12 |
+
- 三路可独立开关 (ColBERT 占内存, 16GB RAM 下建议可降级)
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import asyncio
|
| 17 |
+
import logging
|
| 18 |
+
import threading
|
| 19 |
+
from functools import lru_cache
|
| 20 |
+
from typing import Any
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from app.config import settings
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# BGE-M3 query instruction (BAAI 官方推荐)
|
| 30 |
+
_QUERY_INSTRUCTION = (
|
| 31 |
+
"Represent this sentence for searching relevant passages: "
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@lru_cache(maxsize=1)
|
| 36 |
+
def get_bge_model():
|
| 37 |
+
"""懒加载 BGE-M3. CPU 上 fp16 自动降级为 fp32."""
|
| 38 |
+
from FlagEmbedding import BGEM3FlagModel
|
| 39 |
+
|
| 40 |
+
# CPU 上强制 fp32, 因为 FlagEmbedding 1.x 在 CPU + fp16 有数值问题
|
| 41 |
+
use_fp16 = settings.use_fp16 and settings.embedding_device in ("cuda", "mps")
|
| 42 |
+
logger.info(
|
| 43 |
+
"Loading BGE-M3: model=%s device=%s fp16=%s",
|
| 44 |
+
settings.embedding_model,
|
| 45 |
+
settings.embedding_device,
|
| 46 |
+
use_fp16,
|
| 47 |
+
)
|
| 48 |
+
model = BGEM3FlagModel(
|
| 49 |
+
settings.embedding_model,
|
| 50 |
+
use_fp16=use_fp16,
|
| 51 |
+
device=settings.embedding_device,
|
| 52 |
+
cache_dir=str(settings.hf_cache_dir),
|
| 53 |
+
)
|
| 54 |
+
# 立刻跑一次空 encode, 强制完成 meta→cpu 的 device 转移.
|
| 55 |
+
# 否则 FlagEmbedding.encode 内部的 self.model.to(device) 会撞到 meta tensor 报
|
| 56 |
+
# "Cannot copy out of meta tensor; no data!" (在 PyTorch 2.2 + transformers 4.57 组合下)
|
| 57 |
+
try:
|
| 58 |
+
with __import__("torch").no_grad():
|
| 59 |
+
model.encode(
|
| 60 |
+
["warmup"],
|
| 61 |
+
return_dense=True,
|
| 62 |
+
return_sparse=settings.enable_colbert or True,
|
| 63 |
+
return_colbert_vecs=settings.enable_colbert,
|
| 64 |
+
batch_size=1,
|
| 65 |
+
max_length=8,
|
| 66 |
+
)
|
| 67 |
+
logger.info("BGE-M3 meta→cpu device transfer done")
|
| 68 |
+
except Exception as e: # noqa: BLE001
|
| 69 |
+
logger.warning("BGE-M3 warmup encode failed (will retry on first real call): %s", e)
|
| 70 |
+
return model
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def warm_up() -> None:
|
| 74 |
+
"""在 lifespan 启动时调用, 避免首次请求时的 30s 加载延迟."""
|
| 75 |
+
try:
|
| 76 |
+
get_bge_model()
|
| 77 |
+
logger.info("BGE-M3 warmed up")
|
| 78 |
+
except Exception as e: # noqa: BLE001
|
| 79 |
+
logger.warning("BGE-M3 warm-up failed: %s (will retry on first request)", e)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _normalize_dense(vecs: np.ndarray) -> np.ndarray:
|
| 83 |
+
"""L2 归一化, 余弦相似度 = 点积."""
|
| 84 |
+
norms = np.linalg.norm(vecs, axis=1, keepdims=True)
|
| 85 |
+
norms = np.maximum(norms, 1e-12)
|
| 86 |
+
return vecs / norms
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class BGEM3Embedder:
|
| 90 |
+
"""BGE-M3 嵌入器, 同时产出 dense / sparse / colbert."""
|
| 91 |
+
|
| 92 |
+
def __init__(self) -> None:
|
| 93 |
+
self._lock = threading.Lock()
|
| 94 |
+
|
| 95 |
+
async def encode(self, texts: list[str]) -> dict[str, Any]:
|
| 96 |
+
"""编码多个文本.
|
| 97 |
+
|
| 98 |
+
Returns:
|
| 99 |
+
{
|
| 100 |
+
"dense": np.ndarray, # (N, 1024) 已 L2 归一化
|
| 101 |
+
"sparse": list[dict], # [{"token_id": weight, ...}, ...]
|
| 102 |
+
"colbert": list[np.ndarray], # [N x (T_i, 1024)]
|
| 103 |
+
}
|
| 104 |
+
"""
|
| 105 |
+
if not texts:
|
| 106 |
+
return {"dense": np.zeros((0, 1024), dtype=np.float32), "sparse": [], "colbert": []}
|
| 107 |
+
loop = asyncio.get_running_loop()
|
| 108 |
+
return await loop.run_in_executor(None, self._encode_sync, texts)
|
| 109 |
+
|
| 110 |
+
def _encode_sync(self, texts: list[str]) -> dict[str, Any]:
|
| 111 |
+
model = get_bge_model()
|
| 112 |
+
with self._lock:
|
| 113 |
+
out = model.encode(
|
| 114 |
+
texts,
|
| 115 |
+
return_dense=True,
|
| 116 |
+
return_sparse=settings.enable_colbert or True, # sparse 一直开
|
| 117 |
+
return_colbert_vecs=settings.enable_colbert,
|
| 118 |
+
batch_size=12,
|
| 119 |
+
max_length=512,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
dense = np.asarray(out["dense_vecs"], dtype=np.float32)
|
| 123 |
+
dense = _normalize_dense(dense)
|
| 124 |
+
|
| 125 |
+
# sparse: FlagEmbedding 返回 dict[token_str -> weight]; 标准化为 {token_id: weight}
|
| 126 |
+
sparse_list: list[dict[int, float]] = []
|
| 127 |
+
for sw in out.get("lexical_weights", []):
|
| 128 |
+
# sw: {token_str: weight} or {token_id(int): weight}
|
| 129 |
+
# FlagEmbedding 1.2+ 返回 token_id (int)
|
| 130 |
+
sparse_list.append({int(tid): float(w) for tid, w in sw.items()})
|
| 131 |
+
|
| 132 |
+
colbert_list: list[np.ndarray] = []
|
| 133 |
+
if settings.enable_colbert and "colbert_vecs" in out:
|
| 134 |
+
for v in out["colbert_vecs"]:
|
| 135 |
+
colbert_list.append(np.asarray(v, dtype=np.float32))
|
| 136 |
+
|
| 137 |
+
return {"dense": dense, "sparse": sparse_list, "colbert": colbert_list}
|
| 138 |
+
|
| 139 |
+
async def encode_query(self, query: str) -> dict[str, Any]:
|
| 140 |
+
"""编码单条 query. 加 instruction prefix."""
|
| 141 |
+
return await self.encode([_QUERY_INSTRUCTION + query])
|
| 142 |
+
|
| 143 |
+
# ========== 便利方法 ==========
|
| 144 |
+
async def encode_dense_only(self, texts: list[str]) -> np.ndarray:
|
| 145 |
+
"""只要 dense, 跳过 sparse/colbert (节省内存/时间)."""
|
| 146 |
+
if not texts:
|
| 147 |
+
return np.zeros((0, 1024), dtype=np.float32)
|
| 148 |
+
loop = asyncio.get_running_loop()
|
| 149 |
+
return await loop.run_in_executor(None, self._encode_dense_only_sync, texts)
|
| 150 |
+
|
| 151 |
+
def _encode_dense_only_sync(self, texts: list[str]) -> np.ndarray:
|
| 152 |
+
model = get_bge_model()
|
| 153 |
+
with self._lock:
|
| 154 |
+
out = model.encode(
|
| 155 |
+
[_QUERY_INSTRUCTION + t for t in texts],
|
| 156 |
+
return_dense=True,
|
| 157 |
+
return_sparse=False,
|
| 158 |
+
return_colbert_vecs=False,
|
| 159 |
+
batch_size=12,
|
| 160 |
+
max_length=512,
|
| 161 |
+
)
|
| 162 |
+
dense = np.asarray(out["dense_vecs"], dtype=np.float32)
|
| 163 |
+
return _normalize_dense(dense)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# 全局单例
|
| 167 |
+
_embedder: BGEM3Embedder | None = None
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def get_embedder() -> BGEM3Embedder:
|
| 171 |
+
global _embedder
|
| 172 |
+
if _embedder is None:
|
| 173 |
+
_embedder = BGEM3Embedder()
|
| 174 |
+
return _embedder
|