Spaces:
Runtime error
Runtime error
Mike commited on
Commit Β·
94b89fb
1
Parent(s): 3341d43
run.py fix
Browse files- model/model.py +1 -1
- model/run.py +39 -30
model/model.py
CHANGED
|
@@ -33,7 +33,7 @@ class FactChecker(nn.Module):
|
|
| 33 |
class TruthfulnessSayer(nn.Module):
|
| 34 |
def __init__(self, model_name, num_labels=3, weights_path=None):
|
| 35 |
super().__init__()
|
| 36 |
-
self.fact_checker = FactChecker(model_name, num_labels)
|
| 37 |
if weights_path:
|
| 38 |
self.fact_checker.load_state_dict(torch.load(weights_path, map_location="cpu"))
|
| 39 |
self.fact_checker.eval()
|
|
|
|
| 33 |
class TruthfulnessSayer(nn.Module):
|
| 34 |
def __init__(self, model_name, num_labels=3, weights_path=None):
|
| 35 |
super().__init__()
|
| 36 |
+
self.fact_checker = FactChecker(model_name, num_labels).float()
|
| 37 |
if weights_path:
|
| 38 |
self.fact_checker.load_state_dict(torch.load(weights_path, map_location="cpu"))
|
| 39 |
self.fact_checker.eval()
|
model/run.py
CHANGED
|
@@ -19,7 +19,6 @@ from transformers import AutoTokenizer
|
|
| 19 |
from sentence_transformers import SentenceTransformer
|
| 20 |
|
| 21 |
args, device = parse_gpu_args(extra_args=[
|
| 22 |
-
(["claim"], {"type": str, "help": "Claim to check"}),
|
| 23 |
(["--weights"], {"type": str, "default": None, "help": "Path to model weights"}),
|
| 24 |
(["--model"], {"type": str, "default": MODEL_NAME}),
|
| 25 |
(["--pq"], {"type": str, "default": PQ_NAME}),
|
|
@@ -29,6 +28,7 @@ weights = args.weights or os.path.join(
|
|
| 29 |
"checkpoints", f"{args.model.rsplit('/', 1)[-1]}__{args.pq}", "best.pt"
|
| 30 |
)
|
| 31 |
|
|
|
|
| 32 |
embedder = SentenceTransformer(EMBEDDER, device=device, model_kwargs={"dtype": "auto"})
|
| 33 |
tokenizer = AutoTokenizer.from_pretrained(args.model)
|
| 34 |
model = TruthfulnessSayer(args.model, NUM_LABELS, weights).to(device)
|
|
@@ -36,36 +36,45 @@ model = TruthfulnessSayer(args.model, NUM_LABELS, weights).to(device)
|
|
| 36 |
index = faiss.read_index(faiss_path(args.pq))
|
| 37 |
faiss.extract_index_ivf(index).nprobe = NPROBE
|
| 38 |
conn = sqlite3.connect(DB_PATH)
|
|
|
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
).
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
evidence_texts = []
|
| 48 |
-
if chunk_ids:
|
| 49 |
-
ph = ",".join("?" * len(chunk_ids))
|
| 50 |
-
rows = conn.execute(f"SELECT id, chunk FROM chunks WHERE id IN ({ph})", chunk_ids).fetchall()
|
| 51 |
-
id_to_text = {r[0]: r[1] for r in rows}
|
| 52 |
-
evidence_texts = [id_to_text.get(i, "") for i in chunk_ids]
|
| 53 |
-
while len(evidence_texts) < TOP_K:
|
| 54 |
-
evidence_texts.append("")
|
| 55 |
-
conn.close()
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
)
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
from sentence_transformers import SentenceTransformer
|
| 20 |
|
| 21 |
args, device = parse_gpu_args(extra_args=[
|
|
|
|
| 22 |
(["--weights"], {"type": str, "default": None, "help": "Path to model weights"}),
|
| 23 |
(["--model"], {"type": str, "default": MODEL_NAME}),
|
| 24 |
(["--pq"], {"type": str, "default": PQ_NAME}),
|
|
|
|
| 28 |
"checkpoints", f"{args.model.rsplit('/', 1)[-1]}__{args.pq}", "best.pt"
|
| 29 |
)
|
| 30 |
|
| 31 |
+
print("Loading models...")
|
| 32 |
embedder = SentenceTransformer(EMBEDDER, device=device, model_kwargs={"dtype": "auto"})
|
| 33 |
tokenizer = AutoTokenizer.from_pretrained(args.model)
|
| 34 |
model = TruthfulnessSayer(args.model, NUM_LABELS, weights).to(device)
|
|
|
|
| 36 |
index = faiss.read_index(faiss_path(args.pq))
|
| 37 |
faiss.extract_index_ivf(index).nprobe = NPROBE
|
| 38 |
conn = sqlite3.connect(DB_PATH)
|
| 39 |
+
print("Ready.\n")
|
| 40 |
|
| 41 |
+
while True:
|
| 42 |
+
try:
|
| 43 |
+
claim = input("Claim: ").strip()
|
| 44 |
+
except (EOFError, KeyboardInterrupt):
|
| 45 |
+
break
|
| 46 |
+
if not claim:
|
| 47 |
+
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
+
query_emb = embedder.encode(
|
| 50 |
+
[claim], prompt_name=QUERY_PROMPT, normalize_embeddings=True
|
| 51 |
+
).astype(np.float32)
|
| 52 |
+
|
| 53 |
+
_, ids_found = index.search(query_emb, TOP_K)
|
| 54 |
+
chunk_ids = [i for i in ids_found[0].tolist() if i >= 0]
|
| 55 |
+
|
| 56 |
+
evidence_texts = []
|
| 57 |
+
if chunk_ids:
|
| 58 |
+
ph = ",".join("?" * len(chunk_ids))
|
| 59 |
+
rows = conn.execute(f"SELECT id, chunk FROM chunks WHERE id IN ({ph})", chunk_ids).fetchall()
|
| 60 |
+
id_to_text = {r[0]: r[1] for r in rows}
|
| 61 |
+
evidence_texts = [id_to_text.get(i, "") for i in chunk_ids]
|
| 62 |
+
while len(evidence_texts) < TOP_K:
|
| 63 |
+
evidence_texts.append("")
|
| 64 |
|
| 65 |
+
pairs = tokenizer(
|
| 66 |
+
[claim] * TOP_K, evidence_texts,
|
| 67 |
+
truncation=True, max_length=MAX_LENGTH, padding="longest", return_tensors="pt",
|
| 68 |
+
)
|
| 69 |
+
input_ids = pairs["input_ids"].unsqueeze(0).to(device)
|
| 70 |
+
attention_mask = pairs["attention_mask"].unsqueeze(0).to(device)
|
| 71 |
|
| 72 |
+
score = model(input_ids, attention_mask).item()
|
| 73 |
+
|
| 74 |
+
print(f"Truthfulness: {score:.4f}")
|
| 75 |
+
for i, ev in enumerate(evidence_texts):
|
| 76 |
+
if ev:
|
| 77 |
+
print(f" Evidence {i+1}: {ev[:120]}...")
|
| 78 |
+
print()
|
| 79 |
+
|
| 80 |
+
conn.close()
|