Photon-17B: the honest local honesty package (Lucidia/Photon)
Browse files- .gitattributes +1 -0
- LICENSE +3 -0
- Qwen2.5-14B-Instruct.cert.json +118 -0
- README.md +81 -0
- bloom_atlas.py +145 -0
- grounded_atlas.bloom +3 -0
- hedge_reader.py +223 -0
- offline_atlas.py +133 -0
- photon_ollama.py +112 -0
- resid_probe_Qwen2.5-14B-Instruct.npz +3 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
grounded_atlas.bloom filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The Photon honesty layer (this repo's code, the Grounded Atlas, the probes/certs) is released under
|
| 2 |
+
the Apache-2.0 license. The stock base models it orchestrates carry their own licenses: Qwen2.5 (Apache-2.0)
|
| 3 |
+
and Phi-3.5-mini (MIT). Photon modifies no model weights.
|
Qwen2.5-14B-Instruct.cert.json
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model": "Qwen2.5-14B-Instruct",
|
| 3 |
+
"lineage": "Lucidia-Answerer candidate",
|
| 4 |
+
"feature_recipe": {
|
| 5 |
+
"logprob": "[mean_lp,min_lp,mean_ent,max_ent] @ max_tokens=24,temp=0,top5",
|
| 6 |
+
"resid": "mid-stack mean-pooled residual @ layer L*=3"
|
| 7 |
+
},
|
| 8 |
+
"instruments": {
|
| 9 |
+
"logprob": {
|
| 10 |
+
"quants": {
|
| 11 |
+
"fp16": {
|
| 12 |
+
"cv_auroc": 0.863,
|
| 13 |
+
"off_map_thr": 0.95,
|
| 14 |
+
"held_out_fp": 0.0,
|
| 15 |
+
"off_map_recall": 0.125,
|
| 16 |
+
"null": {
|
| 17 |
+
"mean": 0.489,
|
| 18 |
+
"p95": 0.633,
|
| 19 |
+
"n": 200
|
| 20 |
+
},
|
| 21 |
+
"significant": true,
|
| 22 |
+
"probe": {
|
| 23 |
+
"mean": [
|
| 24 |
+
-0.180105,
|
| 25 |
+
-0.956432,
|
| 26 |
+
0.327842,
|
| 27 |
+
1.223276
|
| 28 |
+
],
|
| 29 |
+
"scale": [
|
| 30 |
+
0.115502,
|
| 31 |
+
0.502964,
|
| 32 |
+
0.169046,
|
| 33 |
+
0.294146
|
| 34 |
+
],
|
| 35 |
+
"coef": [
|
| 36 |
+
-0.354884,
|
| 37 |
+
-0.340988,
|
| 38 |
+
0.959516,
|
| 39 |
+
0.523133
|
| 40 |
+
],
|
| 41 |
+
"intercept": -0.577295,
|
| 42 |
+
"uncertain_thr": 0.835,
|
| 43 |
+
"off_map_thr": 0.95
|
| 44 |
+
}
|
| 45 |
+
},
|
| 46 |
+
"nf4": {
|
| 47 |
+
"cv_auroc": 0.806,
|
| 48 |
+
"off_map_thr": 0.95,
|
| 49 |
+
"held_out_fp": 0.0,
|
| 50 |
+
"off_map_recall": 0.042,
|
| 51 |
+
"null": {
|
| 52 |
+
"mean": 0.476,
|
| 53 |
+
"p95": 0.629,
|
| 54 |
+
"n": 200
|
| 55 |
+
},
|
| 56 |
+
"significant": true,
|
| 57 |
+
"probe": {
|
| 58 |
+
"mean": [
|
| 59 |
+
-0.167199,
|
| 60 |
+
-0.933136,
|
| 61 |
+
0.302731,
|
| 62 |
+
1.192777
|
| 63 |
+
],
|
| 64 |
+
"scale": [
|
| 65 |
+
0.115854,
|
| 66 |
+
0.547072,
|
| 67 |
+
0.161657,
|
| 68 |
+
0.313941
|
| 69 |
+
],
|
| 70 |
+
"coef": [
|
| 71 |
+
-0.393379,
|
| 72 |
+
-0.164267,
|
| 73 |
+
0.63115,
|
| 74 |
+
0.454104
|
| 75 |
+
],
|
| 76 |
+
"intercept": -0.483511,
|
| 77 |
+
"uncertain_thr": 0.896,
|
| 78 |
+
"off_map_thr": 0.95
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
},
|
| 83 |
+
"resid": {
|
| 84 |
+
"layer": 3,
|
| 85 |
+
"quants": {
|
| 86 |
+
"fp16": {
|
| 87 |
+
"cv_auroc": 1.0,
|
| 88 |
+
"off_map_thr": 0.328,
|
| 89 |
+
"held_out_fp": 0.0,
|
| 90 |
+
"off_map_recall": 0.971,
|
| 91 |
+
"null": {
|
| 92 |
+
"mean": 0.522,
|
| 93 |
+
"p95": 0.672,
|
| 94 |
+
"n": 50
|
| 95 |
+
},
|
| 96 |
+
"significant": true,
|
| 97 |
+
"uncertain_thr": 0.208
|
| 98 |
+
},
|
| 99 |
+
"nf4": {
|
| 100 |
+
"cv_auroc": 1.0,
|
| 101 |
+
"off_map_thr": 0.343,
|
| 102 |
+
"held_out_fp": 0.0,
|
| 103 |
+
"off_map_recall": 0.971,
|
| 104 |
+
"null": {
|
| 105 |
+
"mean": 0.517,
|
| 106 |
+
"p95": 0.655,
|
| 107 |
+
"n": 50
|
| 108 |
+
},
|
| 109 |
+
"significant": true,
|
| 110 |
+
"uncertain_thr": 0.223
|
| 111 |
+
}
|
| 112 |
+
},
|
| 113 |
+
"weights_ref": "resid_probe_Qwen2.5-14B-Instruct.npz"
|
| 114 |
+
}
|
| 115 |
+
},
|
| 116 |
+
"scope": "flags off-map/fabricated ENTITIES + off-distribution inputs and hedges on them; NOT a truth oracle (blind to confident on-manifold reasoning ~0.61 and fluent lies ~0.59); per-model + per-quant calibration; no activation steering.",
|
| 117 |
+
"regime_note": "each quant carries its OWN reals-anchored thresholds (logprob scores shift under quant; resid is robust)."
|
| 118 |
+
}
|
README.md
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language: [en]
|
| 4 |
+
tags: [honesty, hallucination-detection, grounding, calibrated, lucidia, photon, abstention]
|
| 5 |
+
pipeline_tag: text-generation
|
| 6 |
+
---
|
| 7 |
+
|
| 8 |
+
# Photon-17B — a local model that knows when it's inventing an entity
|
| 9 |
+
|
| 10 |
+
*Lucidia family · Photon line · honesty.tools*
|
| 11 |
+
|
| 12 |
+
> **Scope, read first.** Photon catches **entities that do not exist at all** (made-up drugs, companies,
|
| 13 |
+
> people, papers, case citations). It is **at chance on everything else** — fluent lies about *real* entities
|
| 14 |
+
> and confident reasoning errors. It does **not** make the model answer better; it makes it **abstain better,
|
| 15 |
+
> with a receipt.** Route real-entity lies and reasoning errors to a separate verifier.
|
| 16 |
+
|
| 17 |
+
**Photon-17B is a package over stock models, not a fine-tune.** It is **Qwen2.5-14B-Instruct, unchanged** — same
|
| 18 |
+
weights, same answers, same capability — wrapped by an honesty layer. No LoRA, no merge, nothing trained. The
|
| 19 |
+
"17" is the param sum of the two stock models it orchestrates (a 14B answerer + a 3.8B
|
| 20 |
+
independent lens). It adds zero capability; the novelty is the *architecture of the check*.
|
| 21 |
+
|
| 22 |
+
## How it works
|
| 23 |
+
|
| 24 |
+
1. **A cross-family independent lens** — Phi-3.5-mini-instruct, a *different model family* from the answerer. A verifier
|
| 25 |
+
from the same mind only confirms; a different one **checks**. If either model refuses in its own words,
|
| 26 |
+
Photon abstains. This is the universal spine — it holds out-of-distribution and on private entities.
|
| 27 |
+
2. **The Grounded Atlas** — Lucidia's **offline** existence index (~16.7M real-entity names) baked into the
|
| 28 |
+
package: no network, no API call, swappable for your own domain (compiled from public article-title
|
| 29 |
+
corpora). Presence is a prior, not proof; absence is not proof of non-existence.
|
| 30 |
+
3. **A signed receipt** — every verdict ships an ed25519-signed record + its **null** (what the detector reads
|
| 31 |
+
on shuffled labels, ≈0.5). Auditable, not asserted.
|
| 32 |
+
|
| 33 |
+
## The honest numbers
|
| 34 |
+
|
| 35 |
+
Measured across four held-out batteries (frozen thresholds, each ships its null):
|
| 36 |
+
|
| 37 |
+
| setting | fabrication recall | over-abstain |
|
| 38 |
+
|---|---|---|
|
| 39 |
+
| **dual-family hedge + Grounded Atlas** (Ollama tier) | ~77–97% | 2–10% |
|
| 40 |
+
| disjoint held-out (full package) | 95–96.6% | 3.7% (reals with an atlas entry) |
|
| 41 |
+
| out-of-distribution (deployed fusion) | ~90–96% | ~10% (≈ the base model's own refusal rate) |
|
| 42 |
+
|
| 43 |
+
The out-of-distribution ~10% over-abstain is essentially what bare Qwen-14B already refuses on obscure reals —
|
| 44 |
+
Photon adds ≈0. On a HalluLens-protocol head-to-head it cuts base Qwen-14B's fabricated-entity false-acceptance
|
| 45 |
+
roughly 10–16× (in-distribution, on the model's easier domains — not a cross-model leaderboard claim).
|
| 46 |
+
|
| 47 |
+
**Never read these as more than they are:** the in-distribution figures isolate the *mechanism*; plan a
|
| 48 |
+
deployment around the out-of-distribution one. The numbers are measured on held-out batteries with frozen
|
| 49 |
+
thresholds, and each ships its null. Full methodology (including where the layer is weakest) is open at
|
| 50 |
+
honesty.tools.
|
| 51 |
+
|
| 52 |
+
## Scope & limits (load-bearing, not fine print)
|
| 53 |
+
|
| 54 |
+
- **Catches:** entities (people, places, papers, works, businesses, species, drug/company/case names) that
|
| 55 |
+
**do not exist at all**, and off-distribution inputs.
|
| 56 |
+
- **Blind to:** fluent lies about *real* entities, and confident reasoning errors — geometry charts
|
| 57 |
+
*familiarity, not truth*. Complementary to semantic-entropy / SelfCheckGPT, which own that axis.
|
| 58 |
+
- **Per-model calibration** is a hard dependency; swapping the answerer needs re-calibration.
|
| 59 |
+
- **Not-in-atlas entities:** on real entities outside the Grounded Atlas (private/enterprise), the reliable
|
| 60 |
+
signal is the model's own refusal (the hedge leg); swap a domain index to ground them.
|
| 61 |
+
|
| 62 |
+
## Run it (Ollama)
|
| 63 |
+
|
| 64 |
+
```bash
|
| 65 |
+
ollama pull qwen2.5:14b-instruct
|
| 66 |
+
ollama pull phi3.5
|
| 67 |
+
python photon_ollama.py --answerer qwen2.5:14b-instruct --lens phi3.5 \
|
| 68 |
+
--bloom grounded_atlas.bloom "Tell me about the medicine Velodose"
|
| 69 |
+
# -> off_map: true, route: "dual-family refusal" (a fabricated drug)
|
| 70 |
+
python photon_ollama.py ... "Tell me about Marie Curie"
|
| 71 |
+
# -> off_map: false, route: "grounded" (a real, atlas-covered entity)
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
`grounded_atlas.bloom` (~33 MB) is the offline existence index, included. The dual-family hedge + atlas is the
|
| 75 |
+
universal spine (words-only, runs in Ollama/llama.cpp). A stronger Python-served tier adds a residual-stream
|
| 76 |
+
probe (+recall on atlas-covered domains) — see honesty.tools.
|
| 77 |
+
|
| 78 |
+
## Provenance
|
| 79 |
+
|
| 80 |
+
Built on stock **Qwen2.5-14B-Instruct** + **Phi-3.5-mini-instruct** + the Grounded Atlas. **No weights were modified, merged,
|
| 81 |
+
or trained.** Methodology, batteries, and the where-it's-weakest writeups are open at honesty.tools.
|
bloom_atlas.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Slim, shippable variant of the offline existence atlas: a bloom filter over the 16.7M normalized titles.
|
| 2 |
+
|
| 3 |
+
Why: the exact sqlite atlas is 446MB — too big to ship inside a GGUF/Ollama-tier package. A bloom filter
|
| 4 |
+
trades ~33MB for a tunable false-POSITIVE rate and ZERO false-negatives. The no-false-negative property is
|
| 5 |
+
exactly right for grounding: every REAL title still matches (reals stay 100% grounded, same as sqlite); only
|
| 6 |
+
a small FPR can spuriously "ground" a fabrication (a false-rescue). We size for a low per-query FPR so the
|
| 7 |
+
structural zero-false-rescue guarantee degrades only negligibly.
|
| 8 |
+
|
| 9 |
+
Build: python bloom_atlas.py build wiki_titles.db wiki_titles.bloom [bits_per_item]
|
| 10 |
+
Probe: python bloom_atlas.py probe wiki_titles.bloom ../eval/hl_battery.json
|
| 11 |
+
The BloomGrounder mirrors Grounder.grounded() candidate logic exactly, querying the bloom instead of sqlite.
|
| 12 |
+
"""
|
| 13 |
+
import sys, os, sqlite3, hashlib, struct, math, json, re
|
| 14 |
+
import numpy as np
|
| 15 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 16 |
+
from offline_atlas import norm, STOP, _sig
|
| 17 |
+
|
| 18 |
+
MAGIC = b"LBLOOM1\n"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _two_hashes(b):
|
| 22 |
+
d = hashlib.blake2b(b, digest_size=16).digest()
|
| 23 |
+
return struct.unpack("<QQ", d) # two 64-bit hashes for double-hashing
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Bloom:
|
| 27 |
+
def __init__(self, m_bits, k):
|
| 28 |
+
self.m = int(m_bits); self.k = int(k)
|
| 29 |
+
self.bits = np.zeros((self.m + 7) // 8, dtype=np.uint8)
|
| 30 |
+
|
| 31 |
+
def _pos(self, key):
|
| 32 |
+
h1, h2 = _two_hashes(key.encode("utf-8"))
|
| 33 |
+
return [(h1 + i * h2) % self.m for i in range(self.k)]
|
| 34 |
+
|
| 35 |
+
def add(self, key):
|
| 36 |
+
for p in self._pos(key):
|
| 37 |
+
self.bits[p >> 3] |= (1 << (p & 7))
|
| 38 |
+
|
| 39 |
+
def __contains__(self, key):
|
| 40 |
+
for p in self._pos(key):
|
| 41 |
+
if not (self.bits[p >> 3] >> (p & 7)) & 1:
|
| 42 |
+
return False
|
| 43 |
+
return True
|
| 44 |
+
|
| 45 |
+
def save(self, path):
|
| 46 |
+
with open(path, "wb") as f:
|
| 47 |
+
f.write(MAGIC); f.write(struct.pack("<QI", self.m, self.k)); f.write(self.bits.tobytes())
|
| 48 |
+
|
| 49 |
+
@classmethod
|
| 50 |
+
def load(cls, path):
|
| 51 |
+
with open(path, "rb") as f:
|
| 52 |
+
assert f.read(len(MAGIC)) == MAGIC, "bad bloom magic"
|
| 53 |
+
m, k = struct.unpack("<QI", f.read(12))
|
| 54 |
+
b = cls(m, k); b.bits = np.frombuffer(f.read(), dtype=np.uint8).copy()
|
| 55 |
+
return b
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def build(db_path, out_path, bits_per_item=16):
|
| 59 |
+
con = sqlite3.connect(db_path)
|
| 60 |
+
n = con.execute("SELECT COUNT(*) FROM t").fetchone()[0]
|
| 61 |
+
m = n * int(bits_per_item)
|
| 62 |
+
k = max(1, round((m / n) * math.log(2)))
|
| 63 |
+
fpr = (1 - math.exp(-k * n / m)) ** k
|
| 64 |
+
print(f"n={n} titles, m={m} bits ({m/8/1e6:.1f} MB), k={k}, theoretical FPR={fpr:.4%}", flush=True)
|
| 65 |
+
bl = Bloom(m, k)
|
| 66 |
+
done = 0
|
| 67 |
+
cur = con.execute("SELECT n FROM t")
|
| 68 |
+
while True:
|
| 69 |
+
rows = cur.fetchmany(200000)
|
| 70 |
+
if not rows:
|
| 71 |
+
break
|
| 72 |
+
for (t,) in rows:
|
| 73 |
+
bl.add(t)
|
| 74 |
+
done += len(rows)
|
| 75 |
+
if done % 2000000 == 0:
|
| 76 |
+
print(f" {done//1000000}M ...", flush=True)
|
| 77 |
+
con.close()
|
| 78 |
+
bl.save(out_path)
|
| 79 |
+
print(f"built {out_path}: {os.path.getsize(out_path)/1e6:.1f} MB", flush=True)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class BloomGrounder:
|
| 83 |
+
"""Mirrors offline_atlas.Grounder.grounded() candidate logic, against the bloom filter."""
|
| 84 |
+
def __init__(self, bloom_path):
|
| 85 |
+
self.bl = Bloom.load(bloom_path)
|
| 86 |
+
|
| 87 |
+
def _exists(self, nm):
|
| 88 |
+
return nm in self.bl
|
| 89 |
+
|
| 90 |
+
def _candidates(self, entity):
|
| 91 |
+
c = [entity]
|
| 92 |
+
if "," in entity:
|
| 93 |
+
c.append(entity.split(",")[0])
|
| 94 |
+
if " by " in entity:
|
| 95 |
+
c.append(entity.split(" by ")[0])
|
| 96 |
+
m = re.search(r"'s\s+(.+)", entity)
|
| 97 |
+
if m:
|
| 98 |
+
c.append(m.group(1))
|
| 99 |
+
c2 = []
|
| 100 |
+
for s in c:
|
| 101 |
+
c2.append(s)
|
| 102 |
+
if "(" in s:
|
| 103 |
+
c2.append(re.sub(r"\([^)]*\)", "", s))
|
| 104 |
+
return [s.strip() for s in c2 if s.strip()]
|
| 105 |
+
|
| 106 |
+
def grounded(self, entity):
|
| 107 |
+
for m in self._candidates(entity):
|
| 108 |
+
nm = norm(m)
|
| 109 |
+
if nm and self._exists(nm):
|
| 110 |
+
return {"matched": True, "hit": nm}
|
| 111 |
+
e = norm(entity); toks = e.split()
|
| 112 |
+
esig = [t for t in toks if _sig(t)]
|
| 113 |
+
if not esig:
|
| 114 |
+
return {"matched": False, "hit": ""}
|
| 115 |
+
for L in range(len(toks), 1, -1):
|
| 116 |
+
for i in range(0, len(toks) - L + 1):
|
| 117 |
+
w = toks[i:i + L]
|
| 118 |
+
wsig = [t for t in w if _sig(t)]
|
| 119 |
+
if len(wsig) >= 2 and len(wsig) / len(esig) >= 0.6:
|
| 120 |
+
wn = " ".join(w)
|
| 121 |
+
if self._exists(wn):
|
| 122 |
+
return {"matched": True, "hit": wn}
|
| 123 |
+
return {"matched": False, "hit": ""}
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def probe(bloom_path, battery_path):
|
| 127 |
+
g = BloomGrounder(bloom_path)
|
| 128 |
+
items = json.load(open(battery_path))["items"]
|
| 129 |
+
y = np.array([it["label"] for it in items])
|
| 130 |
+
key = "name" if "name" in items[0] else "entity"
|
| 131 |
+
matched = np.array([g.grounded(it[key])["matched"] for it in items])
|
| 132 |
+
fake, real = y == 1, y == 0
|
| 133 |
+
print(f"bloom grounder on {os.path.basename(battery_path)} ({len(items)} items):")
|
| 134 |
+
print(f" REAL matched {matched[real].mean():.4f} (want 1.0 — bloom has no false-negatives)")
|
| 135 |
+
print(f" FAKE matched {matched[fake].mean():.4f} (want ~0 — these are bloom false-positives = false-rescues)")
|
| 136 |
+
fr = [items[i][key] for i in range(len(items)) if fake[i] and matched[i]]
|
| 137 |
+
print(f" false-rescues (fakes matched): {len(fr)} {fr[:10]}")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
cmd = sys.argv[1]
|
| 142 |
+
if cmd == "build":
|
| 143 |
+
build(sys.argv[2], sys.argv[3], int(sys.argv[4]) if len(sys.argv) > 4 else 16)
|
| 144 |
+
elif cmd == "probe":
|
| 145 |
+
probe(sys.argv[2], sys.argv[3])
|
grounded_atlas.bloom
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:03b4762f6a559369c054eefce623055998b33dcc23d052d3535ea6606f927cd9
|
| 3 |
+
size 33428804
|
hedge_reader.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Aperture · **Hedge reader** — the *second* off-map signal, read from the answer's WORDS.
|
| 2 |
+
|
| 3 |
+
Iris's primary signal is the answer-logprob *trajectory* (`aperture.iris`): a grounded answer holds steady
|
| 4 |
+
confidence, a fabricated one's confidence collapses. That signal is strong on most models — but it has a known
|
| 5 |
+
**dead spot** (boundary *b2*). Some models put their honesty in the *text*, not the logprobs: asked about an
|
| 6 |
+
entity they don't know, they emit a *fluent, high-confidence refusal* — "There is no record of …", "I'm not
|
| 7 |
+
able to verify …", "I couldn't find any information on …". The tokens of that refusal are perfectly ordinary
|
| 8 |
+
English, so the logprob trajectory stays flat and the logprob probe scores it GROUNDED. (Measured: phi-4
|
| 9 |
+
refuses in text 40/40 but its in-family logprob AUROC is only 0.56 — the probe misses the very case the model
|
| 10 |
+
is being most honest about.)
|
| 11 |
+
|
| 12 |
+
This module is the complementary reader: a calibrated lexical detector of *epistemic disclaimers* in the
|
| 13 |
+
model's OUTPUT TEXT. It is deliberately conservative — it must catch the word-hedger WITHOUT firing on a
|
| 14 |
+
grounded direct answer that happens to contain a hedge token. Two tiers:
|
| 15 |
+
|
| 16 |
+
* **STRONG** — the answer ASSERTS a gap or non-existence ("there is no record of", "does not exist",
|
| 17 |
+
"I can't verify", "I have no information about", "I couldn't find", "this appears to be fictional").
|
| 18 |
+
This is an off-map admission. Fused with the logprob probe, it fires the cert OFF-MAP.
|
| 19 |
+
* **SOFT** — the answer *qualifies* a claim it nonetheless makes ("I think", "possibly", "it may be",
|
| 20 |
+
"if I recall", "roughly"). Real uncertainty, but the model is still committing to an answer — so this
|
| 21 |
+
only lifts the band to UNCERTAIN, never to off-map on its own.
|
| 22 |
+
|
| 23 |
+
The phrase lists here CONSOLIDATE the (independently-grown, battle-tested) refusal/negation lists already in
|
| 24 |
+
``web/engine.py::_is_refusal``, ``web/council.py``, ``web/debate.py::_NEG`` and the eval ``ABST`` tuples, plus
|
| 25 |
+
the soft-hedge vocabulary from ``aperture/honesty_frames.py``. Pure-stdlib, no model, no network — it reads a
|
| 26 |
+
string. Fail-open to "no hedge" on any malformed input (a reader that can't parse must not invent a signal).
|
| 27 |
+
|
| 28 |
+
Calibration: ``read_hedge`` is anchored on a *head window* (the first ~280 chars, where a model that is
|
| 29 |
+
declining says so) and a small set of guards that keep grounded prose ("There is no doubt that Gates founded
|
| 30 |
+
Microsoft", "I think therefore I am" as a *quoted* answer) from tripping STRONG. See
|
| 31 |
+
``tests/test_hedge_reader.py`` for the contract and the grounded-prose anti-firing cases.
|
| 32 |
+
"""
|
| 33 |
+
from __future__ import annotations
|
| 34 |
+
|
| 35 |
+
import re
|
| 36 |
+
|
| 37 |
+
# ── STRONG: the answer admits a knowledge gap / asserts non-existence (an off-map disclaimer). ──────────────
|
| 38 |
+
# Curated UNION of the repo's hardened lists (engine._is_refusal, council pat, debate._NEG, eval ABST), kept
|
| 39 |
+
# as lowercase substrings. Grouped only for readability; matching is a flat substring scan over the head.
|
| 40 |
+
_STRONG_PHRASES: tuple[str, ...] = (
|
| 41 |
+
# explicit non-existence / fictional
|
| 42 |
+
"does not exist", "doesn't exist", "do not exist", "did not exist", "no such",
|
| 43 |
+
"not a real", "is not a real", "not a recognized", "no recognized", "not a known", "no known",
|
| 44 |
+
"appears to be fictional", "seems to be fictional", "is fictional", "purely fictional", "a fictional",
|
| 45 |
+
"made up", "made-up", "imaginary", "invented name", "no real-world", "not a genuine", "no actual",
|
| 46 |
+
"there is no", "there's no", "no record of", "no record", "no historical", "no widely known", "no widely",
|
| 47 |
+
"false premise", "flawed premise", "not appear to exist", "no current",
|
| 48 |
+
# the model cannot find / has no information
|
| 49 |
+
"no information", "no reliable information", "don't have information", "do not have information",
|
| 50 |
+
"i don't have information", "i do not have information", "no verifiable", "no reliable",
|
| 51 |
+
"could not find", "couldn't find", "i couldn't find", "i could not find", "unable to find",
|
| 52 |
+
"cannot find", "can't find", "i can't find", "i cannot find", "not finding", "no evidence",
|
| 53 |
+
"not aware of", "i'm not aware", "i am not aware", "not aware of any", "not familiar with",
|
| 54 |
+
"don't have any record", "do not have any record", "no information about", "any information on",
|
| 55 |
+
"any information about", "not something i", "i'm not able to confirm", "not able to confirm",
|
| 56 |
+
# the model cannot verify / confirm
|
| 57 |
+
"unable to verify", "cannot be verified", "can't verify", "cannot verify", "i can't verify",
|
| 58 |
+
"i cannot verify", "not able to verify", "unable to confirm", "cannot confirm", "can't confirm",
|
| 59 |
+
"not able to confirm", "unable to provide", "cannot be known", "no one knows", "unknowable",
|
| 60 |
+
"impossible to",
|
| 61 |
+
# ── 2026-06-10 registry-seed additions: 29 phrasings recovered from a 20-model / 838-answer
|
| 62 |
+
# adjudication (each verified ZERO false positives on 1550 real-entity answers; the lexical
|
| 63 |
+
# reader had missed 333 refusals, e.g. Claude's "doesn't appear in my knowledge base") ��─
|
| 64 |
+
"doesn't appear in my knowledge",
|
| 65 |
+
"does not appear to be a",
|
| 66 |
+
"have any reliable information",
|
| 67 |
+
"not a widely recognized",
|
| 68 |
+
"don't have reliable information",
|
| 69 |
+
"have any specific information",
|
| 70 |
+
"does not correspond to",
|
| 71 |
+
"doesn't appear to be a",
|
| 72 |
+
"don't have specific information",
|
| 73 |
+
"typo in",
|
| 74 |
+
"this name doesn't",
|
| 75 |
+
"might be some confusion",
|
| 76 |
+
"misunderstanding or",
|
| 77 |
+
"not have access to a search",
|
| 78 |
+
"don't have confident information",
|
| 79 |
+
"there isn't a",
|
| 80 |
+
"looks like you might be referring to",
|
| 81 |
+
"not widely recognized",
|
| 82 |
+
"not a well-known",
|
| 83 |
+
"doesn't match any",
|
| 84 |
+
"not a historical figure",
|
| 85 |
+
"isn't a widely",
|
| 86 |
+
"not widely known",
|
| 87 |
+
"not appear to be widely",
|
| 88 |
+
"doesn't correspond to",
|
| 89 |
+
"haven't been able to find",
|
| 90 |
+
"isn't a recognized",
|
| 91 |
+
"do not have specific information",
|
| 92 |
+
"does not appear in any",
|
| 93 |
+
# 2026-06-07 gpt-5.1 family: "not a historical or currently documented real person" (guarded:
|
| 94 |
+
# bare "documented real"/"currently documented" stay grounded — see tests)
|
| 95 |
+
"documented real person", "currently documented real",
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
# ── SOFT: the answer qualifies a claim it still makes (genuine uncertainty, not an off-map admission). ──────
|
| 99 |
+
_SOFT_PHRASES: tuple[str, ...] = (
|
| 100 |
+
"i think", "i believe", "i'm not sure", "i am not sure", "not entirely sure", "not 100% sure",
|
| 101 |
+
"not completely sure", "if i recall", "if i remember", "to the best of my", "as far as i know",
|
| 102 |
+
"i'm not certain", "i am not certain", "not entirely certain", "it may be", "it might be", "may have been",
|
| 103 |
+
"might have been", "could be", "possibly", "perhaps", "i would guess", "my best guess", "roughly",
|
| 104 |
+
"approximately", "i'm not entirely", "i am not entirely", "not sure", "uncertain", "it's possible that",
|
| 105 |
+
"it is possible that", "i'm fairly", "i am fairly", "presumably", "i suspect",
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# ── GUARDS: substrings that, when present in the head, neutralise an otherwise-STRONG hit. ──────────────────
|
| 109 |
+
# These are the few grounded-prose idioms that embed a STRONG token without being a disclaimer:
|
| 110 |
+
# "there is no doubt", "there is no question" → emphatic AFFIRMATION, not a gap.
|
| 111 |
+
# "no record number", "no record label" → 'no record' as a noun phrase, not "no record of X".
|
| 112 |
+
# Keep tiny and specific; over-guarding would re-open the dead spot.
|
| 113 |
+
_STRONG_GUARDS: tuple[str, ...] = (
|
| 114 |
+
"there is no doubt", "there's no doubt", "no doubt that", "there is no question", "there's no question",
|
| 115 |
+
"no question that", "without a doubt", "leaves no doubt", "there is no denying",
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
_HEAD = 280 # disclaimer window: a model that's declining says so up front
|
| 119 |
+
|
| 120 |
+
_WORD = re.compile(r"[a-z0-9']+")
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _norm(text) -> str:
|
| 124 |
+
if not isinstance(text, str):
|
| 125 |
+
return ""
|
| 126 |
+
# fold typographic quotes to ASCII (gpt-5.1 refuses with "can\u2019t find" \u2014 U+2019 broke the match)
|
| 127 |
+
# and strip markdown emphasis asterisks ("there is **no country**"), then collapse whitespace
|
| 128 |
+
text = (text.replace("\u2019", "'").replace("\u2018", "'")
|
| 129 |
+
.replace("\u201c", '"').replace("\u201d", '"').replace("*", ""))
|
| 130 |
+
return re.sub(r"\s+", " ", text).strip().lower()
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _head(text_norm: str) -> str:
|
| 134 |
+
return text_norm[:_HEAD]
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _matches(haystack: str, phrases: tuple[str, ...]) -> list[str]:
|
| 138 |
+
return [p for p in phrases if p in haystack]
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def read_hedge(text) -> dict:
|
| 142 |
+
"""Read epistemic-disclaimer language out of a model's answer **text** (output-only, no model).
|
| 143 |
+
|
| 144 |
+
Returns a certificate dict::
|
| 145 |
+
|
| 146 |
+
{"hedge": bool, # any hedge (strong OR soft) detected
|
| 147 |
+
"strength": "strong"|"soft"|"none",
|
| 148 |
+
"off_map": bool, # True only for a STRONG (gap-asserting) hedge
|
| 149 |
+
"band": "off-map"|"uncertain"|"grounded",
|
| 150 |
+
"hedge_score": float, # 0..1 confidence the answer is a hedge (monotone in match count + strength)
|
| 151 |
+
"matched": [str, ...], # the phrases that fired (head window)
|
| 152 |
+
"guarded": [str, ...]} # affirmation idioms that suppressed a strong hit, if any
|
| 153 |
+
|
| 154 |
+
Conservative by construction: STRONG fires only inside the head window and only when no affirmation guard
|
| 155 |
+
is present; an empty/garbage input is "grounded / no hedge" (fail-open — never invents a signal).
|
| 156 |
+
"""
|
| 157 |
+
tn = _norm(text)
|
| 158 |
+
if not tn:
|
| 159 |
+
return {"hedge": False, "strength": "none", "off_map": False, "band": "grounded",
|
| 160 |
+
"hedge_score": 0.0, "matched": [], "guarded": []}
|
| 161 |
+
head = _head(tn)
|
| 162 |
+
guards = _matches(head, _STRONG_GUARDS)
|
| 163 |
+
raw_strong = _matches(head, _STRONG_PHRASES)
|
| 164 |
+
# a strong phrase that is part of an affirmation idiom ("there is no doubt …") does not count
|
| 165 |
+
strong = [p for p in raw_strong if not _guarded(p, head, guards)]
|
| 166 |
+
soft = _matches(head, _SOFT_PHRASES)
|
| 167 |
+
|
| 168 |
+
if strong:
|
| 169 |
+
# monotone, saturating: 1 hit already strong evidence, more hits → closer to 1
|
| 170 |
+
score = min(0.99, 0.80 + 0.06 * (len(strong) - 1) + 0.03 * len(soft))
|
| 171 |
+
return {"hedge": True, "strength": "strong", "off_map": True, "band": "off-map",
|
| 172 |
+
"hedge_score": round(score, 3), "matched": strong, "guarded": guards}
|
| 173 |
+
if soft:
|
| 174 |
+
score = min(0.78, 0.45 + 0.08 * (len(soft) - 1))
|
| 175 |
+
return {"hedge": True, "strength": "soft", "off_map": False, "band": "uncertain",
|
| 176 |
+
"hedge_score": round(score, 3), "matched": soft, "guarded": guards}
|
| 177 |
+
return {"hedge": False, "strength": "none", "off_map": False, "band": "grounded",
|
| 178 |
+
"hedge_score": 0.0, "matched": [], "guarded": guards}
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _guarded(phrase: str, head: str, guards: list[str]) -> bool:
|
| 182 |
+
"""Is this strong `phrase`'s occurrence subsumed by an affirmation guard? Only relevant for the handful
|
| 183 |
+
of phrases the guards are built around ('there is no', 'no record')."""
|
| 184 |
+
if not guards:
|
| 185 |
+
return False
|
| 186 |
+
for g in guards:
|
| 187 |
+
if phrase in g: # e.g. phrase "there is no" ⊂ guard "there is no doubt"
|
| 188 |
+
# only suppress if EVERY occurrence of the phrase sits inside a guard occurrence
|
| 189 |
+
if _all_occurrences_inside(phrase, g, head):
|
| 190 |
+
return True
|
| 191 |
+
return False
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def _all_occurrences_inside(phrase: str, guard: str, head: str) -> bool:
|
| 195 |
+
"""True iff every start index of `phrase` in `head` is covered by an occurrence of `guard`."""
|
| 196 |
+
p_idx = _find_all(head, phrase)
|
| 197 |
+
g_spans = [(i, i + len(guard)) for i in _find_all(head, guard)]
|
| 198 |
+
for pi in p_idx:
|
| 199 |
+
if not any(gs <= pi and pi + len(phrase) <= ge for gs, ge in g_spans):
|
| 200 |
+
return False
|
| 201 |
+
return True
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def _find_all(s: str, sub: str) -> list[int]:
|
| 205 |
+
out, i = [], s.find(sub)
|
| 206 |
+
while i != -1:
|
| 207 |
+
out.append(i)
|
| 208 |
+
i = s.find(sub, i + 1)
|
| 209 |
+
return out
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
if __name__ == "__main__": # quick manual check
|
| 213 |
+
import json
|
| 214 |
+
import sys
|
| 215 |
+
samples = [
|
| 216 |
+
"There is no record of a company called Brindlewick Cabinetry. It may be fictional.",
|
| 217 |
+
"Microsoft was founded by Bill Gates and Paul Allen in 1975.",
|
| 218 |
+
"I think the capital might be around the coast, but I'm not entirely sure.",
|
| 219 |
+
"There is no doubt that William Shakespeare wrote Hamlet.", # guarded — grounded
|
| 220 |
+
sys.argv[1] if len(sys.argv) > 1 else "I couldn't find any information on that film.",
|
| 221 |
+
]
|
| 222 |
+
for s in samples:
|
| 223 |
+
print(json.dumps({"text": s[:60], **read_hedge(s)}))
|
offline_atlas.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline grounding atlas — the existence base (no live API, no rate-limit). An entity is GROUNDED if
|
| 2 |
+
it (or a >=2-significant-token contiguous sub-span of it) is an exact Wikipedia article title. Conservative
|
| 3 |
+
by construction: fabrications have no title to match (structural 0-false-rescue, same property the live
|
| 4 |
+
gate had); but unlike the live string-search it can't be rate-limited and handles descriptive prompts
|
| 5 |
+
(the proper-noun span resolves) + diacritics (folded). The Nomic embedding layer (v2, DGX) adds semantic
|
| 6 |
+
robustness for transliteration/word-order misses.
|
| 7 |
+
|
| 8 |
+
Build: python offline_atlas.py build enwiki-titles.gz wiki_titles.db
|
| 9 |
+
Probe: python offline_atlas.py probe wiki_titles.db ../eval/heldout_battery.json ../eval/heldout_atlas_offline.json
|
| 10 |
+
"""
|
| 11 |
+
import sys, os, re, gzip, sqlite3, unicodedata, json
|
| 12 |
+
|
| 13 |
+
STOP = {"the", "of", "a", "an", "and", "in", "on", "at", "de", "la", "le", "el", "los", "las",
|
| 14 |
+
"von", "van", "der", "di", "du", "do", "da", "for", "to"}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def norm(s):
|
| 18 |
+
s = unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode() # fold diacritics
|
| 19 |
+
s = s.replace("_", " ").lower()
|
| 20 |
+
s = re.sub(r"[^a-z0-9 ]", " ", s)
|
| 21 |
+
return re.sub(r"\s+", " ", s).strip()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _sig(tok):
|
| 25 |
+
return tok not in STOP and len(tok) > 1
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def build(gz_path, db_path):
|
| 29 |
+
if os.path.exists(db_path):
|
| 30 |
+
os.remove(db_path)
|
| 31 |
+
con = sqlite3.connect(db_path)
|
| 32 |
+
con.execute("PRAGMA journal_mode=OFF"); con.execute("PRAGMA synchronous=OFF")
|
| 33 |
+
con.execute("CREATE TABLE t(n TEXT PRIMARY KEY) WITHOUT ROWID")
|
| 34 |
+
batch, total = [], 0
|
| 35 |
+
with gzip.open(gz_path, "rt", encoding="utf-8", errors="ignore") as f:
|
| 36 |
+
first = f.readline()
|
| 37 |
+
if norm(first) and "page_title" not in first: # not a header -> keep it
|
| 38 |
+
batch.append((norm(first),))
|
| 39 |
+
for line in f:
|
| 40 |
+
nm = norm(line)
|
| 41 |
+
if nm:
|
| 42 |
+
batch.append((nm,))
|
| 43 |
+
if len(batch) >= 100000:
|
| 44 |
+
con.executemany("INSERT OR IGNORE INTO t VALUES(?)", batch)
|
| 45 |
+
total += len(batch); batch = []
|
| 46 |
+
if total % 1000000 == 0:
|
| 47 |
+
print(f" {total//1000000}M titles ...", flush=True)
|
| 48 |
+
if batch:
|
| 49 |
+
con.executemany("INSERT OR IGNORE INTO t VALUES(?)", batch); total += len(batch)
|
| 50 |
+
con.commit()
|
| 51 |
+
n = con.execute("SELECT COUNT(*) FROM t").fetchone()[0]
|
| 52 |
+
con.close()
|
| 53 |
+
print(f"built {db_path}: {n} unique normalized titles (from {total} lines)")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class Grounder:
|
| 57 |
+
def __init__(self, db_path):
|
| 58 |
+
self.con = sqlite3.connect(db_path, check_same_thread=False)
|
| 59 |
+
|
| 60 |
+
def _exists(self, nm):
|
| 61 |
+
return self.con.execute("SELECT 1 FROM t WHERE n=? LIMIT 1", (nm,)).fetchone() is not None
|
| 62 |
+
|
| 63 |
+
def _candidates(self, entity):
|
| 64 |
+
# whole-entity candidates (each matched in full, never sub-windowed -> no generic-concept rescue):
|
| 65 |
+
# the entity, the part before a comma (", Country"/disambig), and the pieces of descriptive
|
| 66 |
+
# scaffolding (Work BY Author, Work (Native Title), Author'S Work) — these recover reals without
|
| 67 |
+
# surfacing generic fragments, and fakes aren't formatted this way.
|
| 68 |
+
# SAFE splits only: comma (geo/disambig qualifier) and the text outside parentheses (native-title
|
| 69 |
+
# parentheticals). by/possessive/inside-paren splits surface authors+years that false-rescue, so
|
| 70 |
+
# they're left to the embedding+type layer.
|
| 71 |
+
c = [entity]
|
| 72 |
+
if "," in entity:
|
| 73 |
+
c.append(entity.split(",")[0])
|
| 74 |
+
if " by " in entity:
|
| 75 |
+
c.append(entity.split(" by ")[0]) # the WORK (not the author after "by")
|
| 76 |
+
m = re.search(r"'s\s+(.+)", entity)
|
| 77 |
+
if m:
|
| 78 |
+
c.append(m.group(1)) # the WORK (not the author before "'s")
|
| 79 |
+
c2 = []
|
| 80 |
+
for s in c:
|
| 81 |
+
c2.append(s)
|
| 82 |
+
if "(" in s:
|
| 83 |
+
c2.append(re.sub(r"\([^)]*\)", "", s)) # also the text outside parens
|
| 84 |
+
return [s.strip() for s in c2 if s.strip()]
|
| 85 |
+
|
| 86 |
+
def grounded(self, entity):
|
| 87 |
+
# 1) whole-candidate exact match (entity + comma/by/paren/possessive splits)
|
| 88 |
+
for m in self._candidates(entity):
|
| 89 |
+
nm = norm(m)
|
| 90 |
+
if nm and self._exists(nm):
|
| 91 |
+
return {"matched": True, "hit": nm}
|
| 92 |
+
# 2) coverage-gated sub-windows: a title must cover >=60% of the entity's significant tokens
|
| 93 |
+
# (kills generic-concept rescues like "multi task"; keeps "Matilde Hidalgo"/"Lothar Meyer")
|
| 94 |
+
e = norm(entity); toks = e.split()
|
| 95 |
+
esig = [t for t in toks if _sig(t)]
|
| 96 |
+
if not esig:
|
| 97 |
+
return {"matched": False, "hit": ""}
|
| 98 |
+
for L in range(len(toks), 1, -1):
|
| 99 |
+
for i in range(0, len(toks) - L + 1):
|
| 100 |
+
w = toks[i:i + L]
|
| 101 |
+
wsig = [t for t in w if _sig(t)]
|
| 102 |
+
if len(wsig) >= 2 and len(wsig) / len(esig) >= 0.6:
|
| 103 |
+
wn = " ".join(w)
|
| 104 |
+
if self._exists(wn):
|
| 105 |
+
return {"matched": True, "hit": wn}
|
| 106 |
+
return {"matched": False, "hit": ""}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def probe(db_path, battery_path, out_path):
|
| 110 |
+
g = Grounder(db_path)
|
| 111 |
+
items = json.load(open(battery_path))["items"]
|
| 112 |
+
per = []
|
| 113 |
+
for it in items:
|
| 114 |
+
r = g.grounded(it["entity"])
|
| 115 |
+
per.append({"entity": it["entity"], "label": it["label"], "category": it["category"],
|
| 116 |
+
"matched": r["matched"], "hit": r["hit"]})
|
| 117 |
+
fake = [p for p in per if p["label"] == 1]; real = [p for p in per if p["label"] == 0]
|
| 118 |
+
fr = [(p["entity"], p["hit"]) for p in fake if p["matched"]]
|
| 119 |
+
mr = [p["entity"] for p in real if not p["matched"]]
|
| 120 |
+
print(f"offline atlas on {os.path.basename(battery_path)}:")
|
| 121 |
+
print(f" matched-rate REAL {sum(p['matched'] for p in real)/len(real):.3f} FAKE {sum(p['matched'] for p in fake)/len(fake):.3f}")
|
| 122 |
+
print(f" false-rescues (fakes matched): {len(fr)} {fr[:8]}")
|
| 123 |
+
print(f" still-missed reals: {len(mr)} {mr[:10]}")
|
| 124 |
+
json.dump({"per_item": per}, open(out_path, "w"), indent=1)
|
| 125 |
+
print(f"saved -> {out_path}")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
if __name__ == "__main__":
|
| 129 |
+
cmd = sys.argv[1]
|
| 130 |
+
if cmd == "build":
|
| 131 |
+
build(sys.argv[2], sys.argv[3])
|
| 132 |
+
elif cmd == "probe":
|
| 133 |
+
probe(sys.argv[2], sys.argv[3], sys.argv[4])
|
photon_ollama.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Photon (slim / Ollama tier) — the downloadable honesty layer over stock GGUF models.
|
| 2 |
+
|
| 3 |
+
The universal honesty SPINE (measured in eval/RESULTS_leg_ablation.md, all 4 batteries): the answerer's AND an
|
| 4 |
+
INDEPENDENT-FAMILY lens's own refusal-in-words, fused, plus an offline existence check against the Grounded
|
| 5 |
+
Atlas — Lucidia's OFFLINE existence index (~16.7M real-entity names) baked into the package: no network, no
|
| 6 |
+
API call, swappable for your own domain (compiled from public article-title corpora). ~77-97% recall
|
| 7 |
+
@ 2-10% over-abstain, holds out-of-distribution AND on atlas-uncovered (enterprise) entities. It is WORDS-ONLY,
|
| 8 |
+
so it runs wherever Ollama runs. NO resid probe (that's the Python-served Tier-A booster, +10-18pts on
|
| 9 |
+
atlas-covered domains only). Self-contained: vendored hedge_reader + bloom_atlas.
|
| 10 |
+
|
| 11 |
+
ollama pull qwen2.5:14b-instruct && ollama pull phi3.5
|
| 12 |
+
python photon_ollama.py --bloom grounded_atlas.bloom "Tell me about the drug Velodose"
|
| 13 |
+
python photon_ollama.py --selftest # offline logic check, no Ollama needed
|
| 14 |
+
"""
|
| 15 |
+
import os, re, sys, json, argparse, urllib.request
|
| 16 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 17 |
+
sys.path.insert(0, HERE)
|
| 18 |
+
import hedge_reader as HR
|
| 19 |
+
|
| 20 |
+
OLLAMA = os.environ.get("OLLAMA_HOST", "http://localhost:11434").rstrip("/")
|
| 21 |
+
HEDGE_PREFIX = ("I don't have a grounded record of this — I may be inventing details. "
|
| 22 |
+
"Treat the following as unverified, if it's useful at all:\n\n")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _entity_of(q):
|
| 26 |
+
"""Strip question scaffolding to the claimed entity (for the existence check). Mirrors runtime/lucidia.py."""
|
| 27 |
+
s = re.sub(r"(?i)^\s*(please\s+)?(tell me about|who (is|was|are|were)|what (is|are|was|were)|"
|
| 28 |
+
r"describe|explain|give me|do you know|i'm looking for|can you (describe|tell me))\s+", "", q.strip())
|
| 29 |
+
s = re.sub(r"(?i)\b(the |a |an )?(python |software )?(package|library|drug|medicine|company|paper|"
|
| 30 |
+
r"book|person|place)\b\s+(named|called)?\s*", "", s)
|
| 31 |
+
return s.rstrip(" ?.!").strip() or q.strip()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _generate(model, prompt, n_predict=160, timeout=300):
|
| 35 |
+
body = json.dumps({"model": model, "prompt": prompt, "stream": False,
|
| 36 |
+
"options": {"num_predict": n_predict, "temperature": 0}}).encode()
|
| 37 |
+
req = urllib.request.Request(f"{OLLAMA}/api/generate", data=body,
|
| 38 |
+
headers={"Content-Type": "application/json"})
|
| 39 |
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
| 40 |
+
return json.load(r)["response"].strip()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class PhotonOllama:
|
| 44 |
+
"""Dual-family hedge + offline existence, over Ollama. answerer + an INDEPENDENT-family lens."""
|
| 45 |
+
def __init__(self, answerer="qwen2.5:14b-instruct", lens="phi3.5", bloom=None):
|
| 46 |
+
self.answerer, self.lens = answerer, lens
|
| 47 |
+
self.grounder = None
|
| 48 |
+
if bloom and os.path.exists(bloom):
|
| 49 |
+
from bloom_atlas import BloomGrounder
|
| 50 |
+
self.grounder = BloomGrounder(bloom)
|
| 51 |
+
|
| 52 |
+
def _fuse(self, question, ans_a, ans_l):
|
| 53 |
+
entity = _entity_of(question)
|
| 54 |
+
grounded = bool(self.grounder.grounded(entity)["matched"]) if self.grounder else None
|
| 55 |
+
ha = bool(HR.read_hedge(ans_a)["off_map"])
|
| 56 |
+
hl = bool(HR.read_hedge(ans_l)["off_map"])
|
| 57 |
+
off_map = ha or hl # the dual-family hedge spine (universal leg)
|
| 58 |
+
return {"question": question, "entity": entity, "off_map": off_map,
|
| 59 |
+
"route": ("dual-family refusal" if off_map else ("grounded" if grounded else "answered")),
|
| 60 |
+
"grounded": grounded,
|
| 61 |
+
"answerer": {"model": self.answerer, "refused_in_words": ha, "answer": ans_a},
|
| 62 |
+
"lens": {"model": self.lens, "refused_in_words": hl, "answer": ans_l},
|
| 63 |
+
"governed_answer": (HEDGE_PREFIX + ans_a) if off_map else ans_a,
|
| 64 |
+
"prover": f"verified (independent lens: {self.lens})"}
|
| 65 |
+
|
| 66 |
+
def ask(self, question, n_predict=160):
|
| 67 |
+
ans_a = _generate(self.answerer, question, n_predict)
|
| 68 |
+
ans_l = _generate(self.lens, question, n_predict)
|
| 69 |
+
return self._fuse(question, ans_a, ans_l)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _selftest():
|
| 73 |
+
"""Offline check of the fusion + entity extraction (no Ollama). The hedge reader is the load-bearing leg;
|
| 74 |
+
confirm it flags refusals and passes substantive answers, and that entity extraction + bloom work."""
|
| 75 |
+
p = PhotonOllama(bloom=os.path.join(HERE, "grounded_atlas.bloom"))
|
| 76 |
+
cases = [
|
| 77 |
+
("Tell me about the medicine Velodose",
|
| 78 |
+
"I couldn't find any information on a medicine called \"Velodose\". It may be a typo.",
|
| 79 |
+
"I'm not aware of any medication named Velodose."), # fake -> both refuse
|
| 80 |
+
("Tell me about Marie Curie",
|
| 81 |
+
"Marie Curie was a physicist and chemist who won two Nobel Prizes.",
|
| 82 |
+
"Marie Curie (1867-1934) was a pioneering scientist."), # real -> both answer
|
| 83 |
+
("Tell me about the Python package cachetools",
|
| 84 |
+
"cachetools provides memoizing collections and decorators including TTL caches.",
|
| 85 |
+
"I couldn't find a package named cachetools."), # real-not-in-atlas, model knows
|
| 86 |
+
]
|
| 87 |
+
print("SELFTEST (offline fusion logic):")
|
| 88 |
+
for q, a, l in cases:
|
| 89 |
+
r = p._fuse(q, a, l)
|
| 90 |
+
print(f" entity={r['entity']!r:34s} grounded={str(r['grounded']):5s} "
|
| 91 |
+
f"off_map={str(r['off_map']):5s} route={r['route']}")
|
| 92 |
+
print(" (fake -> off_map True; real -> off_map False; entity extracted; bloom grounded reflects the Grounded Atlas)")
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def main():
|
| 96 |
+
ap = argparse.ArgumentParser()
|
| 97 |
+
ap.add_argument("question", nargs="?")
|
| 98 |
+
ap.add_argument("--answerer", default="qwen2.5:14b-instruct")
|
| 99 |
+
ap.add_argument("--lens", default="phi3.5")
|
| 100 |
+
ap.add_argument("--bloom", default=None)
|
| 101 |
+
ap.add_argument("--selftest", action="store_true")
|
| 102 |
+
a = ap.parse_args()
|
| 103 |
+
if a.selftest:
|
| 104 |
+
_selftest(); return
|
| 105 |
+
p = PhotonOllama(answerer=a.answerer, lens=a.lens, bloom=a.bloom)
|
| 106 |
+
r = p.ask(a.question)
|
| 107 |
+
print(json.dumps({k: v for k, v in r.items() if k != "lens"}, indent=2))
|
| 108 |
+
print(f"\n lens ({r['lens']['model']}) refused_in_words={r['lens']['refused_in_words']}")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
if __name__ == "__main__":
|
| 112 |
+
main()
|
resid_probe_Qwen2.5-14B-Instruct.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c309d88f13e1ce01d667ff879a9239d7076075d7410e5cb9a75a0174eef0f986
|
| 3 |
+
size 124926
|