mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-09-21 17:38:10 +00:00
此前三段式拆分后 ONNX 路径从未从 Go 侧跑通:embedder_onnx_test.go 仍引用 分段前的 API(e.renderInput、TextTower.onnx、旧目录),go vet -tags onnxruntime 直接编译失败。导出脚本只在 /tmp 且硬编码本机路径、从第三个目录拷贝固定形状的 Vision.onnx,完全不可复现。音频会被视觉塔编码,静默往统一空间灌入错误坐标。 本提交补齐这些缺口: 一、可复现导出脚本(scripts/export_qwen3vl_embedding_onnx.py) - 自动拉取模型(HuggingFace 优先,失败回落 ModelScope,支持 HF_ENDPOINT 镜像); - 导出 TokenEmbedding + Transformer + Vision 三段图,图文共用同一 token embedding、28 层 Transformer、last-token 池化与 fingerprint; - 双重自检(不可省):分段 PyTorch vs 完整模型 + 导出后的 ONNX vs 完整模型, cos < 0.999999 即非零退出——「能加载」不等于「算得对」; - 默认把 L2 归一化后的冻结参考向量写入产物目录(qwen_reference.json)—— Go 测试据此做逐维冻结回归,且「该目录是哪次导出的」从文件本身可追溯; - --verify-only 校验既有产物不重新导出,可用来确认线上在用的图没坏。 关键实测结论(已写入 docs/zh/multimodal-space.md 与长期记忆): 原生多帧视频不可行——Qwen3-VL 视觉塔把 grid_thw 当 Python 值消费 (grid_thw.tolist()),legacy tracer 固化为常量,导出后图中根本没有 grid_thw 输入,换帧数调用直接 Invalid input name: grid_thw。故视觉塔固定 (1,48,48), 视频由上层抽帧后逐帧按图像编码(同模型/同维度/同 fingerprint),音频明确 unsupported。 二、模态边界(vector.ErrModalityUnsupported) - 新增 vector.ErrModalityUnsupported:表示「该模态不在本统一空间的原生覆盖 范围内」,与普通错误语义不同——调用方应把它当「永远不会有向量」而非 「本次失败、下次重试」; - qwen.EmbedImageDense 按 mime 拒绝 audio/* 与 video/*:此前它会拿视觉塔 去解音频字节,往统一空间灌入语义错误的坐标且静默; - reembedStaleMedia 对 ErrModalityUnsupported 不计失败、不重试、不用别的 模型向量顶替(TestReembedStaleMedia_SkipsUnsupportedWithoutFaking 守住)。 三、Go ONNX 测试首次完整通过 - 重写 embedder_onnx_test.go:修复编译 + 文本冻结回归 + 图像冻结回归 + 两条阴性对照(不同输入必须不同、图像与文本必须不同)+ 不支持模态断言; - 参考值从产物目录的 qwen_reference.json 读取(不在测试里硬编码浮点); - 用线上部署产物实测全部通过(text cos=0.999999940, image cos=0.999999762)。 四、.gitignore 修复 - /scripts/ 此前被列在「运行时产物」下,但它是作者维护的工具目录 (模型导出、侧车、部署校验),deploy/systemd/embed-sidecar.service 直接 引用 scripts/embed_sidecar.py,忽略它会让那份 unit 在别人的机器上指向 不存在的文件。改为只忽略 __pycache__。 五、文档(docs/zh/multimodal-space.md) - 获取/启用/产物契约/模态边界/验证/资源成本/与现有部署产物的等价性。 验证:go build ./...、go vet ./...、go vet -tags onnxruntime ./...、 go test -short 全部通过;ONNX 标签测试对线上部署产物全部通过。
193 lines
7.0 KiB
Python
193 lines
7.0 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
TF-IDF embedding sidecar for HomeAgent.
|
|
|
|
HTTP interface:
|
|
POST /embed → {"text":"...", "side":"query|document"} → {"embedding":[...]}
|
|
POST /train → {"documents": {"id":"text", ...}} → {"status":"ok", "count":N}
|
|
POST /search → {"query":"...", "topK":5} → {"results":[{"id":"...", "score":0.3, "text":"..."}]}
|
|
GET /health → {"status":"ok","count":N,"type":"tfidf"}
|
|
|
|
Provides TF-IDF sparse vectors via the same HTTP contract as Jina/ONNX dense vectors,
|
|
allowing the core to treat all embedding providers uniformly.
|
|
"""
|
|
|
|
import json
|
|
import math
|
|
import os
|
|
import re
|
|
import sys
|
|
import threading
|
|
import time
|
|
from collections import Counter
|
|
from http.server import HTTPServer, BaseHTTPRequestHandler
|
|
from urllib.parse import urlparse
|
|
|
|
# ─── Chinese Tokenizer (jieba) ──────────────────────────────────────────────
|
|
try:
|
|
import jieba
|
|
def tokenize(text):
|
|
return [w for w in jieba.cut(text) if w.strip()]
|
|
except ImportError:
|
|
# Fallback: simple character/word split
|
|
def tokenize(text):
|
|
return re.findall(r'[\w\u4e00-\u9fff]+', text)
|
|
|
|
# ─── TF-IDF Engine ──────────────────────────────────────────────────────────
|
|
class TFIDFEngine:
|
|
def __init__(self):
|
|
self.lock = threading.RLock()
|
|
self.doc_freq = Counter()
|
|
self.total_docs = 0
|
|
self.docs = {} # id -> {"text": ..., "vec": ...}
|
|
|
|
def train(self, docs: dict):
|
|
"""Train IDF statistics from a batch of documents."""
|
|
with self.lock:
|
|
self.total_docs = len(docs)
|
|
self.doc_freq = Counter()
|
|
seen_per_doc = []
|
|
for text in docs.values():
|
|
features = tokenize(text)
|
|
seen = set()
|
|
for f in features:
|
|
if f not in seen:
|
|
self.doc_freq[f] += 1
|
|
seen.add(f)
|
|
# Store docs with their vectors
|
|
for did, text in docs.items():
|
|
self.docs[did] = {"text": text, "vec": self._vectorize(text)}
|
|
print(f"[tfidf] trained on {len(docs)} docs, {len(self.doc_freq)} features", flush=True)
|
|
|
|
def _vectorize(self, text):
|
|
features = tokenize(text)
|
|
tf = Counter(features)
|
|
max_tf = max(tf.values()) if tf else 1
|
|
vec = {}
|
|
for f, count in tf.items():
|
|
tf_norm = count / max_tf
|
|
if self.total_docs < 3:
|
|
vec[f] = tf_norm
|
|
continue
|
|
df = self.doc_freq.get(f, 0)
|
|
if df <= 0:
|
|
continue
|
|
idf = math.log((self.total_docs + 1) / (df + 1))
|
|
if idf < 0.1:
|
|
continue
|
|
vec[f] = tf_norm * idf
|
|
return vec
|
|
|
|
def vectorize(self, text):
|
|
with self.lock:
|
|
return self._vectorize(text)
|
|
|
|
def search(self, query, top_k=5):
|
|
with self.lock:
|
|
q_vec = self._vectorize(query)
|
|
results = []
|
|
for did, entry in self.docs.items():
|
|
score = self._cosine(q_vec, entry["vec"])
|
|
if score > 0.01:
|
|
results.append({"id": did, "score": score, "text": entry["text"][:200]})
|
|
results.sort(key=lambda x: -x["score"])
|
|
return results[:top_k]
|
|
|
|
def add(self, did, text):
|
|
with self.lock:
|
|
self.docs[did] = {"text": text, "vec": self._vectorize(text)}
|
|
|
|
def remove(self, did):
|
|
with self.lock:
|
|
self.docs.pop(did, None)
|
|
|
|
@staticmethod
|
|
def _cosine(a, b):
|
|
dot = sum(a.get(k, 0) * b.get(k, 0) for k in set(a) | set(b))
|
|
na = math.sqrt(sum(v * v for v in a.values()))
|
|
nb = math.sqrt(sum(v * v for v in b.values()))
|
|
if na == 0 or nb == 0:
|
|
return 0
|
|
return dot / (na * nb)
|
|
|
|
# ─── HTTP Server ─────────────────────────────────────────────────────────────
|
|
PORT = int(os.environ.get("TFIDF_PORT", "18998"))
|
|
engine = TFIDFEngine()
|
|
|
|
class TFIDFHandler(BaseHTTPRequestHandler):
|
|
def log_message(self, fmt, *args):
|
|
if "/health" not in str(args[0]):
|
|
print(f"[tfidf] {fmt % args}", flush=True)
|
|
|
|
def do_GET(self):
|
|
if urlparse(self.path).path == "/health":
|
|
self._respond(200, {"status": "ok", "count": len(engine.docs), "type": "tfidf"})
|
|
else:
|
|
self._respond(404, {"error": "not found"})
|
|
|
|
def do_POST(self:
|
|
path = urlparse(self.path).path
|
|
try:
|
|
length = int(self.headers.get("Content-Length", 0))
|
|
body = json.loads(self.rfile.read(length))
|
|
except Exception as e:
|
|
self._respond(400, {"error": str(e)})
|
|
return
|
|
|
|
if path == "/train":
|
|
docs = body.get("documents", {})
|
|
engine.train(docs)
|
|
self._respond(200, {"status": "ok", "count": len(docs)})
|
|
|
|
elif path == "/embed":
|
|
text = body.get("text", "")
|
|
vec = engine.vectorize(text)
|
|
# Convert to list format matching HTTPEmbedder contract
|
|
# Sparse vector → dense-ish list (feature indices as keys)
|
|
embedding = [vec.get(k, 0) for k in sorted(vec.keys())] if vec else []
|
|
self._respond(200, {"embedding": embedding, "sparse": vec})
|
|
|
|
elif path == "/search":
|
|
query = body.get("query", "")
|
|
top_k = body.get("topK", 5)
|
|
results = engine.search(query, top_k)
|
|
self._respond(200, {"results": results})
|
|
|
|
elif path == "/add":
|
|
did = body.get("id", "")
|
|
text = body.get("text", "")
|
|
engine.add(did, text)
|
|
self._respond(200, {"status": "ok"})
|
|
|
|
elif path == "/remove":
|
|
did = body.get("id", "")
|
|
engine.remove(did)
|
|
self._respond(200, {"status": "ok"})
|
|
|
|
else:
|
|
self._respond(404, {"error": "not found"})
|
|
|
|
def _respond(self, status, data):
|
|
body = json.dumps(data).encode("utf-8")
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
if __name__ == "__main__":
|
|
# Load from disk if available
|
|
data_file = os.environ.get("TFIDF_DATA", "/home/newqqagent/memory/tfidf_index.json")
|
|
if os.path.exists(data_file):
|
|
try:
|
|
with open(data_file) as f:
|
|
docs = json.load(f)
|
|
engine.train(docs)
|
|
print(f"[tfidf] loaded {len(docs)} docs from {data_file}", flush=True)
|
|
except Exception as e:
|
|
print(f"[tfidf] failed to load: {e}", flush=True)
|
|
|
|
server = HTTPServer(("0.0.0.0", PORT), TFIDFHandler)
|
|
print(f"[tfidf] listening on :{PORT}", flush=True)
|
|
server.serve_forever()
|