prateekhh commited on
Commit
44d0c28
·
verified ·
1 Parent(s): f63c0b3

Merit NLI backend — HHEM-2.1-Open factual-consistency scorer (Docker Space)

Browse files
Files changed (4) hide show
  1. Dockerfile +23 -0
  2. README.md +67 -5
  3. requirements.txt +8 -0
  4. server.py +154 -0
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Merit NLI backend — free, self-hostable factual-consistency scorer (CPU-only, ~1-1.5GB image).
2
+ # Build: docker build -t merit-nli .
3
+ # Run: docker run -p 8000:8000 merit-nli
4
+ # Wire: MERIT_NLI_URL=http://localhost:8000/score MERIT_NLI_MODEL=vectara/hhem-2.1-open (in Merit's env)
5
+ FROM python:3.11-slim
6
+
7
+ ENV HF_HOME=/models \
8
+ TRANSFORMERS_OFFLINE=0 \
9
+ MERIT_NLI_BACKEND=hhem \
10
+ PYTHONUNBUFFERED=1
11
+
12
+ WORKDIR /app
13
+ COPY requirements.txt .
14
+ RUN pip install --no-cache-dir -r requirements.txt
15
+
16
+ # Bake the default model into the image so the first request isn't a cold ~600MB download.
17
+ RUN python -c "from transformers import AutoModelForSequenceClassification as M; \
18
+ M.from_pretrained('vectara/hallucination_evaluation_model', trust_remote_code=True)"
19
+
20
+ COPY . .
21
+ EXPOSE 8000
22
+ # 1 worker: each worker loads its own model copy (RAM x workers). Scale with replicas, not workers, on CPU.
23
+ CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]
README.md CHANGED
@@ -1,10 +1,72 @@
1
  ---
2
- title: Merit Nli
3
- emoji: 🏆
4
- colorFrom: green
5
- colorTo: gray
6
  sdk: docker
 
7
  pinned: false
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Merit NLI Backend
3
+ emoji: 🔍
4
+ colorFrom: indigo
5
+ colorTo: blue
6
  sdk: docker
7
+ app_port: 8000
8
  pinned: false
9
+ license: apache-2.0
10
+ short_description: Free CPU-only NLI scorer for citation verification
11
  ---
12
 
13
+ # Merit NLI backend
14
+
15
+ A **free, self-hostable, CPU-only** factual-consistency scorer that turns Merit's verifier into a real
16
+ **dual-gate** — a deterministic numeric check + an encoder-NLI leg + the adversarial LLM judge — instead of
17
+ leaning on a rate-limited LLM for every citation. No paid API, permissive-licensed models only.
18
+
19
+ It implements the exact contract Merit's engine (`lib/verify/nli.ts`) calls:
20
+
21
+ ```
22
+ POST /score { "claim": "...", "source": "..." } -> { "score": 0.0..1.0, "support": ..., "model": "..." }
23
+ ```
24
+
25
+ `score` = probability the **source supports the claim** (0 = unsupported/contradicted, 1 = fully supported).
26
+
27
+ ## Run it (one command)
28
+
29
+ ```bash
30
+ docker build -t merit-nli .
31
+ docker run -p 8000:8000 merit-nli
32
+ ```
33
+
34
+ or locally:
35
+
36
+ ```bash
37
+ python -m venv .venv && . .venv/bin/activate # Windows: .venv\Scripts\activate
38
+ pip install -r requirements.txt
39
+ uvicorn server:app --port 8000
40
+ ```
41
+
42
+ ## Point Merit at it
43
+
44
+ In `merit/app/.env.local` (or the deploy env):
45
+
46
+ ```
47
+ MERIT_NLI_URL=http://localhost:8000/score
48
+ MERIT_NLI_MODEL=vectara/hhem-2.1-open
49
+ MERIT_STRICT_GATE=1 # require BOTH the NLI leg and the judge to confirm support (highest precision)
50
+ ```
51
+
52
+ Now Merit catches **non-numeric** wrong-answers (contradictions, off-topic, right-entity/wrong-answer) with
53
+ **no LLM call** — the NLI leg decides, and the LLM judge is only a second gate.
54
+
55
+ ## Models (all permissive, CPU-friendly)
56
+
57
+ | `MERIT_NLI_BACKEND` | Model | License | Notes |
58
+ |---|---|---|---|
59
+ | `hhem` (default) | `vectara/hallucination_evaluation_model` (HHEM-2.1-Open) | Apache-2.0 | ~100M params, ~600MB RAM, ~1.5s/2k-token CPU, **unlimited context**; `predict([(source, claim)])` is the contract verbatim |
60
+ | `crossencoder` | `cross-encoder/nli-deberta-v3-base` | Apache-2.0 | 3-way NLI; `score` = softmax entailment prob; 512-token cap |
61
+
62
+ Optional second gate: set `MERIT_NLI_CONTRA=1` to also load a cross-encoder and **penalize contradictions**
63
+ (`score = support · (1 − contradiction)`) — the "support AND not-contradict" gate.
64
+
65
+ **Not shipped (non-commercial):** Bespoke-MiniCheck-7B is CC-BY-NC-4.0 — excluded. `lytang/MiniCheck-Flan-T5-Large`
66
+ (Apache-2.0, 770M) is a drop-in higher-accuracy alternative if you have the CPU headroom.
67
+
68
+ ## Endpoints
69
+
70
+ - `GET /healthz` → `{ ok, backend, model, dualGate }`
71
+ - `POST /score` → `{ score, support, model }`
72
+ - `POST /score/batch` `{ items: [{claim, source}] }` → `{ model, scores: [...] }`
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cpu
2
+ torch==2.3.1
3
+ transformers==4.44.2
4
+ sentencepiece==0.2.0
5
+ protobuf==5.28.2
6
+ fastapi==0.115.0
7
+ uvicorn[standard]==0.30.6
8
+ pydantic==2.9.2
server.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Merit NLI backend — a free, self-hostable factual-consistency scorer for the verification engine.
3
+
4
+ It implements the exact contract lib/verify/nli.ts expects:
5
+
6
+ POST /score { "claim": "...", "source": "..." } -> { "score": 0.0..1.0, ... }
7
+
8
+ `score` is the probability that SOURCE supports CLAIM. Point Merit at it with:
9
+
10
+ MERIT_NLI_URL=http://localhost:8000/score
11
+ MERIT_NLI_MODEL=vectara/hhem-2.1-open # recorded on every verdict for reproducibility
12
+
13
+ Two permissive, CPU-friendly, zero-API backends (choose via MERIT_NLI_BACKEND):
14
+
15
+ * "hhem" (DEFAULT) — Vectara HHEM-2.1-Open (Apache-2.0, ~100M params, ~600MB RAM, unlimited context).
16
+ model.predict([(source, claim)]) natively returns P(source supports claim) in 0..1 — a drop-in match.
17
+ * "crossencoder" — a 3-way NLI cross-encoder (Apache-2.0 / MIT). score = softmax entailment probability.
18
+
19
+ Optional second gate (MERIT_NLI_CONTRA=1): also load a cross-encoder and PENALIZE contradictions, so a claim
20
+ the source both partly-entails AND contradicts (mixed evidence) is scored down — the "support AND not-contradict"
21
+ dual gate the faithfulness literature (AlignScore/Ragas-with-HHEM) converges on. Everything runs on CPU with
22
+ permissive-licensed models; nothing calls a paid API.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import os
27
+ from typing import List, Optional
28
+
29
+ from fastapi import FastAPI
30
+ from pydantic import BaseModel
31
+
32
+ BACKEND = os.getenv("MERIT_NLI_BACKEND", "hhem").lower()
33
+ HHEM_MODEL = os.getenv("MERIT_NLI_HHEM_MODEL", "vectara/hallucination_evaluation_model")
34
+ CE_MODEL = os.getenv("MERIT_NLI_CE_MODEL", "cross-encoder/nli-deberta-v3-base")
35
+ USE_CONTRA = os.getenv("MERIT_NLI_CONTRA", "0") == "1"
36
+
37
+ app = FastAPI(title="Merit NLI backend", version="0.1.0")
38
+
39
+ _support = None # primary support scorer
40
+ _contra = None # optional contradiction scorer (cross-encoder)
41
+
42
+
43
+ class _HHEM:
44
+ """Vectara HHEM-2.1-Open — predict([(premise, hypothesis)]) -> P(premise supports hypothesis)."""
45
+
46
+ tag = "vectara/hhem-2.1-open"
47
+
48
+ def __init__(self, name: str):
49
+ from transformers import AutoModelForSequenceClassification # lazy: keep import cost off /healthz
50
+ self.m = AutoModelForSequenceClassification.from_pretrained(name, trust_remote_code=True)
51
+ self.m.eval()
52
+
53
+ def score_batch(self, pairs: List[tuple]) -> List[float]:
54
+ # pairs = [(claim, source), ...]; HHEM wants (premise=source, hypothesis=claim)
55
+ preds = self.m.predict([(s, c) for (c, s) in pairs])
56
+ return [float(x) for x in preds]
57
+
58
+
59
+ class _CrossEncoder:
60
+ """3-way NLI cross-encoder. Returns (entailment_prob, contradiction_prob) via softmax over the logits.
61
+
62
+ Label order differs by model — configured for cross-encoder/nli-deberta-v3-base
63
+ ([contradiction, entailment, neutral]); override with MERIT_NLI_ENTAIL_IDX / MERIT_NLI_CONTRA_IDX.
64
+ """
65
+
66
+ def __init__(self, name: str):
67
+ import torch
68
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
69
+ self.torch = torch
70
+ self.tok = AutoTokenizer.from_pretrained(name)
71
+ self.m = AutoModelForSequenceClassification.from_pretrained(name)
72
+ self.m.eval()
73
+ self.entail_idx = int(os.getenv("MERIT_NLI_ENTAIL_IDX", "1"))
74
+ self.contra_idx = int(os.getenv("MERIT_NLI_CONTRA_IDX", "0"))
75
+ self.tag = name
76
+
77
+ def probs(self, claim: str, source: str) -> tuple:
78
+ with self.torch.no_grad():
79
+ x = self.tok(source, claim, truncation=True, max_length=512, return_tensors="pt")
80
+ p = self.torch.softmax(self.m(**x).logits[0], dim=-1)
81
+ return float(p[self.entail_idx]), float(p[self.contra_idx])
82
+
83
+ def score_batch(self, pairs: List[tuple]) -> List[float]:
84
+ return [self.probs(c, s)[0] for (c, s) in pairs]
85
+
86
+ def contra_batch(self, pairs: List[tuple]) -> List[float]:
87
+ return [self.probs(c, s)[1] for (c, s) in pairs]
88
+
89
+
90
+ def support():
91
+ global _support
92
+ if _support is None:
93
+ if BACKEND == "crossencoder":
94
+ _support = _CrossEncoder(CE_MODEL)
95
+ else:
96
+ _support = _HHEM(HHEM_MODEL)
97
+ return _support
98
+
99
+
100
+ def contra():
101
+ global _contra
102
+ if _contra is None and USE_CONTRA:
103
+ _contra = _CrossEncoder(CE_MODEL)
104
+ return _contra
105
+
106
+
107
+ def model_tag() -> str:
108
+ t = getattr(support(), "tag", BACKEND)
109
+ return f"{t}+contra" if USE_CONTRA else t
110
+
111
+
112
+ class ScoreReq(BaseModel):
113
+ claim: str
114
+ source: str
115
+
116
+
117
+ class BatchReq(BaseModel):
118
+ items: List[ScoreReq]
119
+
120
+
121
+ def _score_pairs(pairs: List[tuple]) -> List[dict]:
122
+ sup = support().score_batch(pairs)
123
+ if USE_CONTRA and contra() is not None:
124
+ con = contra().contra_batch(pairs)
125
+ # dual gate: a claim the source contradicts is penalized even if it superficially entails
126
+ out = [{"score": max(0.0, s * (1.0 - c)), "support": s, "contradiction": c} for s, c in zip(sup, con)]
127
+ else:
128
+ out = [{"score": s, "support": s} for s in sup]
129
+ return out
130
+
131
+
132
+ @app.get("/healthz")
133
+ def healthz():
134
+ return {"ok": True, "backend": BACKEND, "model": model_tag(), "dualGate": USE_CONTRA}
135
+
136
+
137
+ @app.on_event("startup")
138
+ def _warm():
139
+ try:
140
+ _score_pairs([("warm up", "warming up the model on startup")])
141
+ except Exception as e: # never block startup on a warm-up hiccup
142
+ print(f"[nli] warm-up skipped: {e}")
143
+
144
+
145
+ @app.post("/score")
146
+ def score(req: ScoreReq):
147
+ r = _score_pairs([(req.claim, req.source)])[0]
148
+ return {**r, "model": model_tag()}
149
+
150
+
151
+ @app.post("/score/batch")
152
+ def score_batch(req: BatchReq):
153
+ rows = _score_pairs([(i.claim, i.source) for i in req.items])
154
+ return {"model": model_tag(), "scores": rows}