Raphael2099's picture
scripts
56a0f31 verified
Raw History Blame Contribute Delete
8.42 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""cs_retrieve.py —— 传世考释问答 v1 · 两路检索(进程内 fls,只读线上 shards.json:ft1 4B@2560 + rr3;不走 HTTP、不碰 18080、不写 service/)。
路 1 诸家说:lib C,source_type ∈ {paper, related, collected},channel main,k=16 候选(doc_cap 1)→ 去 eval/dev_overlap;
装配时与抽样锚(C 主快照 8-gram 引用块)合并,共 ≤5 条(锚优先 ≤2)。
路 2 传世对读:lib A2,source_type ∈ {classic, parallel},k=8(doc_cap 1)→ 去本段自身与同书他版(近似重文)、去 eval/dev_overlap。
不跑 lib A 辞例与 private/theory 路(传世问答不需要;省一半检索时间)。
并发:--workers N 子进程(同一张卡,CUDA_VISIBLE_DEVICES 由外层给定)× --threads T;各写 OUT.shardK(断点续跑);
--deadline "YYYY-mm-dd HH:MM":到点各子进程停止取新记录、落盘退出;合并已完成部分(按输入序)。
用法: CUDA_VISIBLE_DEVICES=2 python cs_retrieve.py --in S.jsonl --out L.jsonl --workers 6 --threads 4 --deadline "2026-10-24 13:58"
"""
import argparse, json, os, subprocess, sys, time, datetime
W = "/root/autodl-tmp/llm_rag_20261023"
SERVICE = "/root/autodl-tmp/llm_rag_20260919/service"
def log(m):
sys.stdout.write("%s [cs_retrieve] %s\n" % (time.strftime("%H:%M:%S"), m)); sys.stdout.flush()
def read_ids(p):
s = set()
if os.path.exists(p):
for l in open(p, encoding="utf-8"):
try:
s.add(json.loads(l)["id"])
except Exception:
pass
return s
def slim(b):
m = b.get("meta") or {}
return {"id": b.get("id"), "cite": b.get("cite") or "", "source_type": b.get("source_type") or "",
"text": b.get("text") or "",
"meta": {k: m.get(k) for k in ("lib", "channel", "source_lib", "doc_key", "quotable", "eval_overlap", "dev_overlap",
"book", "author", "year", "pian", "corpus") if k in m},
"eval_overlap": bool(b.get("eval_overlap") or m.get("eval_overlap")),
"dev_overlap": bool(b.get("dev_overlap") or m.get("dev_overlap")),
"rerank": (b.get("score") or {}).get("rerank")}
def worker(a):
sys.dont_write_bytecode = True
os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
for k in ("FLS_ROOT", "FLS_SHARDS", "FLS_SCRIPTS", "FLS_PORT"):
os.environ.pop(k, None)
for k in ("FLS_OMP_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMEXPR_NUM_THREADS"):
os.environ[k] = "8"
if a.cpu_smoke:
os.environ["CUDA_VISIBLE_DEVICES"] = ""
else:
assert os.environ.get("CUDA_VISIBLE_DEVICES") == a.gpu, "CUDA_VISIBLE_DEVICES 须为 %s" % a.gpu
os.environ["FLS_BATCH_DIR"] = os.path.join(W, "tmp", "fls_batch_unused")
sys.path.insert(0, SERVICE)
import fls_core # noqa: F401
import threading
from concurrent.futures import ThreadPoolExecutor
dl = datetime.datetime.strptime(a.deadline, "%Y-%m-%d %H:%M").timestamp() if a.deadline else 0
rows = [json.loads(l) for l in open(a.inp, encoding="utf-8") if l.strip()]
if a.limit:
rows = rows[:a.limit]
rows = [r for i, r in enumerate(rows) if i % a.nshards == a.shard]
done = read_ids(a.out)
todo = [r for r in rows if r["cid"] not in done]
log("shard %d/%d: %d rows, %d done, %d todo" % (a.shard, a.nshards, len(rows), len(done), len(todo)))
if not todo:
return 0
t0 = time.time()
s = fls_core.FederatedSearcher(use_dense=not a.cpu_smoke, use_rerank=not a.cpu_smoke, quiet=True)
timing, deg = s.warmup()
if a.cpu_smoke:
deg = []
h = s.health(); m = h.get("models") or {}
log("searcher ready %.1fs degraded=%s embed=%s rerank=%s fp=%s" % (time.time() - t0, deg, m.get("embed"), m.get("rerank"), s.state_fingerprint()))
assert not deg, "warmup degraded %s" % deg
lock = threading.Lock(); st = {"n": 0, "deg": 0, "t1": time.time(), "stop": False}
f = open(a.out, "a", encoding="utf-8")
def srch(**kw):
try:
r = s.search(**kw)
except Exception as e:
return [], ["search_error:%s" % type(e).__name__]
if not r.get("ok"):
return [], ["search_error"]
return list(r.get("blocks") or []), list(r.get("degraded") or [])
def one(r):
if st["stop"] or (dl and time.time() > dl):
st["stop"] = True; return 0
q = r["text"][:300]
cb, d1 = srch(q=q, k=16, doc_cap=1, quota={"C": 16},
filters={"lib": ["C"], "source_type": ["paper", "related", "collected"], "channel": ["main"]})
ab, d2 = srch(q=q, k=8, doc_cap=1, quota={"A2": 8}, filters={"lib": ["A2"], "source_type": ["classic", "parallel"]})
cb = [slim(b) for b in cb if (b.get("meta") or {}).get("lib") == "C"]
ab = [slim(b) for b in ab if (b.get("meta") or {}).get("lib") == "A2" and b.get("id") != r["cid"]]
out = {"id": r["cid"], "c_blocks": cb, "a2_blocks": ab, "degraded": sorted(set(d1) | set(d2))}
with lock:
f.write(json.dumps(out, ensure_ascii=False, separators=(",", ":")) + "\n")
st["n"] += 1; st["deg"] += bool(out["degraded"])
if st["n"] % 100 == 0:
f.flush(); os.fsync(f.fileno())
log("shard %d: %d/%d %.2f rec/s degraded=%d" % (a.shard, st["n"], len(todo), st["n"] / (time.time() - st["t1"]), st["deg"]))
return 0
with ThreadPoolExecutor(max_workers=a.threads) as ex:
list(ex.map(one, todo))
f.flush(); os.fsync(f.fileno()); f.close()
meta = {"shard": a.shard, "n": st["n"], "todo": len(todo), "stopped_at_deadline": st["stop"], "sec": round(time.time() - st["t1"], 1),
"degraded_records": st["deg"], "fingerprint": s.state_fingerprint(), "code_sha256": s.code_sha256(),
"blocklist_sha256": h.get("blocklist_sha256"), "models": m, "tuning": s.tuning_defaults(),
"lanes": "C{paper,related,collected}/main k16 doc_cap1; A2{classic,parallel} k8 doc_cap1", "threads": a.threads}
json.dump(meta, open(a.out + ".meta.json", "w"), ensure_ascii=False, indent=1, default=str)
try:
s.close()
except Exception:
pass
return 0
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--in", dest="inp", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--workers", type=int, default=1)
ap.add_argument("--threads", type=int, default=4)
ap.add_argument("--cpu-smoke", action="store_true")
ap.add_argument("--gpu", default="2")
ap.add_argument("--shard", type=int, default=-1)
ap.add_argument("--nshards", type=int, default=1)
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--deadline", default="")
a = ap.parse_args()
if a.shard >= 0:
return worker(a)
procs = []
for k in range(max(1, a.workers)):
cmd = [sys.executable, os.path.abspath(__file__), "--in", a.inp, "--out", "%s.shard%d" % (a.out, k), "--shard", str(k),
"--nshards", str(max(1, a.workers)), "--threads", str(a.threads), "--gpu", a.gpu, "--deadline", a.deadline] + \
(["--cpu-smoke"] if a.cpu_smoke else []) + (["--limit", str(a.limit)] if a.limit else [])
procs.append(subprocess.Popen(cmd)); time.sleep(2)
rcs = [p.wait() for p in procs]
log("workers rc=%s" % rcs)
got = {}
for k in range(max(1, a.workers)):
p = "%s.shard%d" % (a.out, k)
if os.path.exists(p):
for l in open(p, encoding="utf-8"):
if l.strip():
try:
o = json.loads(l)
except Exception:
continue
got[o["id"]] = l.rstrip("\n")
ids = [json.loads(l)["cid"] for l in open(a.inp, encoding="utf-8") if l.strip()]
if a.limit:
ids = ids[:a.limit]
tmp = a.out + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
for i in ids:
if i in got:
f.write(got[i] + "\n")
os.replace(tmp, a.out)
n = sum(1 for i in ids if i in got)
log("merged %d / %d -> %s" % (n, len(ids), a.out))
return 0 if n > 0 and not any(rcs) else (5 if n == 0 else 0)
if __name__ == "__main__":
sys.exit(main())