Spaces:
Running
Running
Exact words: firmware postings layout; CPU quota threads; model in image; timings
Browse files- Dockerfile +2 -0
- app.py +59 -38
Dockerfile
CHANGED
|
@@ -4,6 +4,8 @@ RUN pip install --no-cache-dir torch==2.5.1 --index-url https://download.pytorch
|
|
| 4 |
RUN useradd -m -u 1000 user
|
| 5 |
USER user
|
| 6 |
ENV HOME=/home/user PYTHONUNBUFFERED=1 HF_HOME=/home/user/hfcache
|
|
|
|
|
|
|
| 7 |
WORKDIR /home/user/app
|
| 8 |
COPY --chown=user app.py .
|
| 9 |
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
|
|
|
| 4 |
RUN useradd -m -u 1000 user
|
| 5 |
USER user
|
| 6 |
ENV HOME=/home/user PYTHONUNBUFFERED=1 HF_HOME=/home/user/hfcache
|
| 7 |
+
# the model ships in the image, so a restart only fetches the index
|
| 8 |
+
RUN python -c "from huggingface_hub import snapshot_download; snapshot_download('Qwen/Qwen3-Embedding-0.6B')"
|
| 9 |
WORKDIR /home/user/app
|
| 10 |
COPY --chown=user app.py .
|
| 11 |
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
app.py
CHANGED
|
@@ -144,6 +144,16 @@ def marked(n):
|
|
| 144 |
return s + "׳" if len(s) == 1 else s[:-1] + "״" + s[-1]
|
| 145 |
|
| 146 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
def load():
|
| 148 |
try:
|
| 149 |
S["stage"] = "lexicon"
|
|
@@ -197,11 +207,12 @@ def load():
|
|
| 197 |
S["stage"] = "model"
|
| 198 |
import torch
|
| 199 |
from sentence_transformers import SentenceTransformer
|
| 200 |
-
torch.set_num_threads(
|
| 201 |
m = SentenceTransformer("Qwen/Qwen3-Embedding-0.6B", device="cpu")
|
| 202 |
m.max_seq_length = 256
|
| 203 |
X["model"] = m
|
| 204 |
encode("warm up")
|
|
|
|
| 205 |
S["stage"], S["ready"] = "ready", True
|
| 206 |
S["load_s"] = round(time.time() - S["t0"])
|
| 207 |
except Exception as e: # shown by /api/status
|
|
@@ -289,8 +300,24 @@ def meaning(qv, k=400):
|
|
| 289 |
|
| 290 |
|
| 291 |
# ---- exact words --------------------------------------------------------------------------------------
|
| 292 |
-
|
| 293 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
|
| 295 |
|
| 296 |
def term_id(w):
|
|
@@ -298,44 +325,35 @@ def term_id(w):
|
|
| 298 |
return i if i < len(X["terms"]) and X["terms"][i] == w else -1
|
| 299 |
|
| 300 |
|
| 301 |
-
def postings(t):
|
| 302 |
-
a, b = int(X["post_idx"][t]), int(X["post_idx"][t + 1])
|
| 303 |
-
return np.asarray(X["post"][a:b])
|
| 304 |
-
|
| 305 |
-
|
| 306 |
def words_search(q, k=400):
|
| 307 |
-
ws =
|
| 308 |
if not ws:
|
| 309 |
return [], []
|
| 310 |
-
n,
|
| 311 |
-
for w in
|
| 312 |
-
|
| 313 |
-
if
|
| 314 |
continue
|
| 315 |
-
|
| 316 |
-
if
|
| 317 |
continue
|
| 318 |
-
|
| 319 |
-
|
|
|
|
|
|
|
|
|
|
| 320 |
return [], []
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
for i in range(min(120, len(segs))):
|
| 333 |
-
if phrase in plain_he(text(int(segs[i]))):
|
| 334 |
-
sc[i] *= 2
|
| 335 |
-
o = np.lexsort((-sc[:120], -cover[top][:120]))
|
| 336 |
-
segs = np.concatenate([segs[:120][o], segs[120:]])
|
| 337 |
-
sc = np.concatenate([sc[:120][o], sc[120:]])
|
| 338 |
-
return segs[:k], sc[:k]
|
| 339 |
|
| 340 |
|
| 341 |
# ---- shaping, voting ----------------------------------------------------------------------------------
|
|
@@ -396,11 +414,13 @@ def search(q: str, mode: str = "both", shelves: str = "", limit: int = 40):
|
|
| 396 |
sh = {SHELVES.index(x) for x in shelves.split(",") if x in SHELVES}
|
| 397 |
seen = set()
|
| 398 |
m_list, w_list = [], []
|
|
|
|
| 399 |
if mode in ("both", "meaning"):
|
| 400 |
-
|
|
|
|
| 401 |
m_list = shape(segs, sc, sh, limit, seen)
|
| 402 |
if mode in ("both", "words"):
|
| 403 |
-
segs, sc = words_search(q)
|
| 404 |
w_list = shape(segs, sc, sh, limit, seen)
|
| 405 |
if mode == "both":
|
| 406 |
merged, i, j = [], 0, 0
|
|
@@ -431,7 +451,8 @@ def search(q: str, mode: str = "both", shelves: str = "", limit: int = 40):
|
|
| 431 |
for h in hits:
|
| 432 |
counts[h["shelf"]] += 1
|
| 433 |
return {"q": q, "mode": mode, "ms": round((time.time() - t0) * 1000), "hits": hits, "trail": trail,
|
| 434 |
-
"counts": counts, "exact": len(w_list)
|
|
|
|
| 435 |
|
| 436 |
|
| 437 |
@app.get("/api/passage")
|
|
|
|
| 144 |
return s + "׳" if len(s) == 1 else s[:-1] + "״" + s[-1]
|
| 145 |
|
| 146 |
|
| 147 |
+
def cpu_quota():
|
| 148 |
+
try:
|
| 149 |
+
q, p = Path("/sys/fs/cgroup/cpu.max").read_text().split()
|
| 150 |
+
if q != "max":
|
| 151 |
+
return max(1, round(int(q) / int(p)))
|
| 152 |
+
except Exception:
|
| 153 |
+
pass
|
| 154 |
+
return len(os.sched_getaffinity(0))
|
| 155 |
+
|
| 156 |
+
|
| 157 |
def load():
|
| 158 |
try:
|
| 159 |
S["stage"] = "lexicon"
|
|
|
|
| 207 |
S["stage"] = "model"
|
| 208 |
import torch
|
| 209 |
from sentence_transformers import SentenceTransformer
|
| 210 |
+
torch.set_num_threads(cpu_quota())
|
| 211 |
m = SentenceTransformer("Qwen/Qwen3-Embedding-0.6B", device="cpu")
|
| 212 |
m.max_seq_length = 256
|
| 213 |
X["model"] = m
|
| 214 |
encode("warm up")
|
| 215 |
+
S["threads"] = torch.get_num_threads()
|
| 216 |
S["stage"], S["ready"] = "ready", True
|
| 217 |
S["load_s"] = round(time.time() - S["t0"])
|
| 218 |
except Exception as e: # shown by /api/status
|
|
|
|
| 300 |
|
| 301 |
|
| 302 |
# ---- exact words --------------------------------------------------------------------------------------
|
| 303 |
+
# As NerLexicalSearch.cpp reads the lexicon: postings pack the segment in the
|
| 304 |
+
# low 22 bits, tf in bits 22-30, and bit 31 marks a form made by peeling a
|
| 305 |
+
# Hebrew prefix (weighted 0.35); BM25-saturated tf; then the top candidates'
|
| 306 |
+
# text is read for how many query words it holds and whether in order.
|
| 307 |
+
SEG_MASK, TF_MASK, DERIVED = (1 << 22) - 1, 0x1FF, 1 << 31
|
| 308 |
+
MAX_POSTINGS = 400_000 # the device stops at 50,000; here there is room
|
| 309 |
+
WORD = re.compile(r"[א-ת]{2,}|[A-Za-z][A-Za-z']+")
|
| 310 |
+
PFX = "ובכלמשה"
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def match_text(s):
|
| 314 |
+
return " " + " ".join(WORD.findall(plain_he(clean(s)).lower())) + " "
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def has_word(t, w):
|
| 318 |
+
for m in re.finditer(r"(?<= )([%s]{0,2})%s(?= )" % (PFX, re.escape(w)), t):
|
| 319 |
+
return True
|
| 320 |
+
return False
|
| 321 |
|
| 322 |
|
| 323 |
def term_id(w):
|
|
|
|
| 325 |
return i if i < len(X["terms"]) and X["terms"][i] == w else -1
|
| 326 |
|
| 327 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
def words_search(q, k=400):
|
| 329 |
+
ws = list(dict.fromkeys(w.lower() for w in WORD.findall(plain_he(q))))
|
| 330 |
if not ws:
|
| 331 |
return [], []
|
| 332 |
+
n, segs_l, wts_l = X["n"], [], []
|
| 333 |
+
for w in ws:
|
| 334 |
+
t = term_id(w)
|
| 335 |
+
if t < 0:
|
| 336 |
continue
|
| 337 |
+
a, b = int(X["post_idx"][t]), int(X["post_idx"][t + 1])
|
| 338 |
+
if b == a or b - a > MAX_POSTINGS:
|
| 339 |
continue
|
| 340 |
+
p = np.asarray(X["post"][a:b])
|
| 341 |
+
tf = np.maximum((p >> 22) & TF_MASK, 1).astype(np.float32)
|
| 342 |
+
wt = np.log(n / (b - a)) * tf * 2.2 / (tf + 1.2) * np.where(p & DERIVED, 0.35, 1.0)
|
| 343 |
+
segs_l.append((p & SEG_MASK).astype(np.int64)); wts_l.append(wt.astype(np.float32))
|
| 344 |
+
if not segs_l:
|
| 345 |
return [], []
|
| 346 |
+
u, inv = np.unique(np.concatenate(segs_l), return_inverse=True)
|
| 347 |
+
score = np.bincount(inv, weights=np.concatenate(wts_l))
|
| 348 |
+
top = np.argsort(-score)[:max(k, 120)]
|
| 349 |
+
segs, sc = u[top], score[top].copy()
|
| 350 |
+
phrase = " " + " ".join(ws) + " "
|
| 351 |
+
for i in range(min(120, len(segs))):
|
| 352 |
+
t = match_text(text(int(segs[i]), 1024))
|
| 353 |
+
found = sum(has_word(t, w) for w in ws)
|
| 354 |
+
sc[i] *= (0.25 + found / len(ws)) * (2.0 if len(ws) > 1 and phrase in t else 1.0)
|
| 355 |
+
o = np.argsort(-sc[:120], kind="stable")
|
| 356 |
+
return np.concatenate([segs[:120][o], segs[120:]])[:k], np.concatenate([sc[:120][o], sc[120:]])[:k]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
|
| 358 |
|
| 359 |
# ---- shaping, voting ----------------------------------------------------------------------------------
|
|
|
|
| 414 |
sh = {SHELVES.index(x) for x in shelves.split(",") if x in SHELVES}
|
| 415 |
seen = set()
|
| 416 |
m_list, w_list = [], []
|
| 417 |
+
tm = {}
|
| 418 |
if mode in ("both", "meaning"):
|
| 419 |
+
t = time.time(); qv = encode(q); tm["encode"] = time.time() - t
|
| 420 |
+
t = time.time(); segs, sc = meaning(qv); tm["vectors"] = time.time() - t
|
| 421 |
m_list = shape(segs, sc, sh, limit, seen)
|
| 422 |
if mode in ("both", "words"):
|
| 423 |
+
t = time.time(); segs, sc = words_search(q); tm["words"] = time.time() - t
|
| 424 |
w_list = shape(segs, sc, sh, limit, seen)
|
| 425 |
if mode == "both":
|
| 426 |
merged, i, j = [], 0, 0
|
|
|
|
| 451 |
for h in hits:
|
| 452 |
counts[h["shelf"]] += 1
|
| 453 |
return {"q": q, "mode": mode, "ms": round((time.time() - t0) * 1000), "hits": hits, "trail": trail,
|
| 454 |
+
"counts": counts, "exact": len(w_list),
|
| 455 |
+
"timing_ms": {k: round(v * 1000) for k, v in tm.items()}}
|
| 456 |
|
| 457 |
|
| 458 |
@app.get("/api/passage")
|