Spaces:
Running
Running
Rerank the candidate pool with Qwen3-Reranker-4B on ZeroGPU (joshruby/ner-rerank)
Browse files- Dockerfile +1 -1
- app.py +65 -9
Dockerfile
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
FROM python:3.11-slim
|
| 2 |
RUN pip install --no-cache-dir torch==2.5.1 --index-url https://download.pytorch.org/whl/cpu && \
|
| 3 |
-
pip install --no-cache-dir "transformers==4.57.1" "sentence-transformers==5.1.2" fastapi==0.115.6 "uvicorn[standard]==0.32.1" numpy==2.1.3 requests huggingface_hub
|
| 4 |
RUN useradd -m -u 1000 user
|
| 5 |
USER user
|
| 6 |
ENV HOME=/home/user PYTHONUNBUFFERED=1 HF_HOME=/home/user/hfcache
|
|
|
|
| 1 |
FROM python:3.11-slim
|
| 2 |
RUN pip install --no-cache-dir torch==2.5.1 --index-url https://download.pytorch.org/whl/cpu && \
|
| 3 |
+
pip install --no-cache-dir "transformers==4.57.1" "sentence-transformers==5.1.2" fastapi==0.115.6 "uvicorn[standard]==0.32.1" numpy==2.1.3 requests huggingface_hub gradio_client==1.5.2
|
| 4 |
RUN useradd -m -u 1000 user
|
| 5 |
USER user
|
| 6 |
ENV HOME=/home/user PYTHONUNBUFFERED=1 HF_HOME=/home/user/hfcache
|
app.py
CHANGED
|
@@ -467,8 +467,36 @@ def need_ready():
|
|
| 467 |
raise HTTPException(503, detail={"stage": S["stage"], "error": S["error"]})
|
| 468 |
|
| 469 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 470 |
@app.get("/api/search")
|
| 471 |
-
def search(q: str, mode: str = "both", shelves: str = "", limit: int = 40):
|
| 472 |
need_ready()
|
| 473 |
t0 = time.time()
|
| 474 |
q = q.strip()[:300]
|
|
@@ -479,10 +507,10 @@ def search(q: str, mode: str = "both", shelves: str = "", limit: int = 40):
|
|
| 479 |
if mode in ("both", "meaning"):
|
| 480 |
t = time.time(); qv = encode(q); tm["encode"] = time.time() - t
|
| 481 |
t = time.time(); segs, sc = meaning(qv); tm["vectors"] = time.time() - t
|
| 482 |
-
m_list = shape(segs, sc, sh, limit, seen)
|
| 483 |
if mode in ("both", "words"):
|
| 484 |
t = time.time(); segs, sc = words_search(q); tm["words"] = time.time() - t
|
| 485 |
-
w_list = shape(segs, sc, sh, limit, seen)
|
| 486 |
if mode == "both":
|
| 487 |
merged, i, j = [], 0, 0
|
| 488 |
while len(merged) < limit and (i < len(m_list) or j < len(w_list)):
|
|
@@ -503,15 +531,43 @@ def search(q: str, mode: str = "both", shelves: str = "", limit: int = 40):
|
|
| 503 |
it = item(s, "source", cap=160)
|
| 504 |
it["weight"] = round(v / top_v, 3)
|
| 505 |
trail.append(it)
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 511 |
counts = defaultdict(int)
|
| 512 |
for h in hits:
|
| 513 |
counts[h["shelf"]] += 1
|
| 514 |
-
return {"q": q, "mode": mode, "ms": round((time.time() - t0) * 1000), "hits": hits, "trail": trail,
|
| 515 |
"counts": counts, "exact": len(w_list),
|
| 516 |
"timing_ms": {k: round(v * 1000) for k, v in tm.items()}}
|
| 517 |
|
|
|
|
| 467 |
raise HTTPException(503, detail={"stage": S["stage"], "error": S["error"]})
|
| 468 |
|
| 469 |
|
| 470 |
+
# ---- rerank on ZeroGPU ---------------------------------------------------------------------------------
|
| 471 |
+
RERANK_SPACE = os.environ.get("RERANK_SPACE", "joshruby/ner-rerank")
|
| 472 |
+
_pool = None
|
| 473 |
+
_client = None
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def rerank_scores(q, docs, timeout=25):
|
| 477 |
+
"""p(yes) per doc from Qwen3-Reranker-4B (joshruby/ner-rerank, ZeroGPU, PRO quota), or None."""
|
| 478 |
+
global _pool, _client
|
| 479 |
+
import concurrent.futures as cf
|
| 480 |
+
from gradio_client import Client
|
| 481 |
+
if _pool is None:
|
| 482 |
+
_pool = cf.ThreadPoolExecutor(4)
|
| 483 |
+
|
| 484 |
+
def call():
|
| 485 |
+
global _client
|
| 486 |
+
if _client is None:
|
| 487 |
+
_client = Client(RERANK_SPACE, hf_token=os.environ.get("HF_TOKEN"), verbose=False)
|
| 488 |
+
return json.loads(_client.predict(q, json.dumps(docs, ensure_ascii=False), api_name="/rerank"))
|
| 489 |
+
|
| 490 |
+
try:
|
| 491 |
+
return _pool.submit(call).result(timeout=timeout)
|
| 492 |
+
except Exception as e:
|
| 493 |
+
print("rerank failed:", type(e).__name__, e, flush=True)
|
| 494 |
+
_client = None
|
| 495 |
+
return None
|
| 496 |
+
|
| 497 |
+
|
| 498 |
@app.get("/api/search")
|
| 499 |
+
def search(q: str, mode: str = "both", shelves: str = "", limit: int = 40, rerank: int = 1):
|
| 500 |
need_ready()
|
| 501 |
t0 = time.time()
|
| 502 |
q = q.strip()[:300]
|
|
|
|
| 507 |
if mode in ("both", "meaning"):
|
| 508 |
t = time.time(); qv = encode(q); tm["encode"] = time.time() - t
|
| 509 |
t = time.time(); segs, sc = meaning(qv); tm["vectors"] = time.time() - t
|
| 510 |
+
m_list = shape(segs, sc, sh, 40 if rerank else limit, seen)
|
| 511 |
if mode in ("both", "words"):
|
| 512 |
t = time.time(); segs, sc = words_search(q); tm["words"] = time.time() - t
|
| 513 |
+
w_list = shape(segs, sc, sh, 25 if rerank and mode == "both" else limit, seen)
|
| 514 |
if mode == "both":
|
| 515 |
merged, i, j = [], 0, 0
|
| 516 |
while len(merged) < limit and (i < len(m_list) or j < len(w_list)):
|
|
|
|
| 531 |
it = item(s, "source", cap=160)
|
| 532 |
it["weight"] = round(v / top_v, 3)
|
| 533 |
trail.append(it)
|
| 534 |
+
reranked = False
|
| 535 |
+
if rerank and mode == "both":
|
| 536 |
+
pool = {}
|
| 537 |
+
for s_, sc_ in m_list:
|
| 538 |
+
pool.setdefault(int(s_), "meaning")
|
| 539 |
+
for s_, sc_ in w_list:
|
| 540 |
+
pool.setdefault(int(s_), "words")
|
| 541 |
+
for t_ in trail:
|
| 542 |
+
if not sh or SHELVES.index(t_["shelf"]) in sh:
|
| 543 |
+
pool.setdefault(t_["seg"], "source")
|
| 544 |
+
items = [item(s_, tag_) for s_, tag_ in pool.items()]
|
| 545 |
+
t = time.time()
|
| 546 |
+
rs = rerank_scores(q, [f"{h['ref']}\n{h['text']}\n{h['en']}".strip() for h in items])
|
| 547 |
+
tm["rerank"] = time.time() - t
|
| 548 |
+
if rs is not None and len(rs) == len(items):
|
| 549 |
+
reranked = True
|
| 550 |
+
per = defaultdict(int)
|
| 551 |
+
hits = []
|
| 552 |
+
for h, r_ in sorted(zip(items, rs), key=lambda x: -x[1]):
|
| 553 |
+
w = X["title"][h["seg"]]
|
| 554 |
+
if per[w] >= 3:
|
| 555 |
+
continue
|
| 556 |
+
per[w] += 1
|
| 557 |
+
hits.append({**h, "score": r_})
|
| 558 |
+
if len(hits) >= limit:
|
| 559 |
+
break
|
| 560 |
+
if not reranked:
|
| 561 |
+
merged = merged[:limit]
|
| 562 |
+
hits = [item(s, tag, sc) for s, sc, tag in merged]
|
| 563 |
+
# primaries the results point to, placed after the first and third result as on the device
|
| 564 |
+
ins = [t for t in trail if t["seg"] not in shown and t["weight"] >= 0.3][:2]
|
| 565 |
+
for pos, t in zip((1, 4), ins):
|
| 566 |
+
hits.insert(min(pos, len(hits)), {**item(t["seg"], "source"), "weight": t["weight"]})
|
| 567 |
counts = defaultdict(int)
|
| 568 |
for h in hits:
|
| 569 |
counts[h["shelf"]] += 1
|
| 570 |
+
return {"q": q, "mode": mode, "ms": round((time.time() - t0) * 1000), "hits": hits, "trail": trail, "reranked": reranked,
|
| 571 |
"counts": counts, "exact": len(w_list),
|
| 572 |
"timing_ms": {k: round(v * 1000) for k, v in tm.items()}}
|
| 573 |
|