recallic-engine 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- recallic_engine/__init__.py +10 -0
- recallic_engine/api/__init__.py +0 -0
- recallic_engine/api/deps.py +36 -0
- recallic_engine/brain/__init__.py +0 -0
- recallic_engine/brain/features/__init__.py +1 -0
- recallic_engine/brain/features/aggregation_check.py +796 -0
- recallic_engine/brain/features/answer_check.default.json +23 -0
- recallic_engine/brain/features/answer_check.py +199 -0
- recallic_engine/brain/features/answer_check_learning.py +164 -0
- recallic_engine/brain/features/answer_verify.py +78 -0
- recallic_engine/brain/features/as_of.py +122 -0
- recallic_engine/brain/features/calibration.py +119 -0
- recallic_engine/brain/features/dates.py +124 -0
- recallic_engine/brain/features/facts.py +472 -0
- recallic_engine/brain/features/implicit.py +208 -0
- recallic_engine/brain/features/learned_facts.py +121 -0
- recallic_engine/brain/features/modes.py +70 -0
- recallic_engine/brain/features/query.py +297 -0
- recallic_engine/brain/features/reranker.py +87 -0
- recallic_engine/brain/features/schemas.py +222 -0
- recallic_engine/brain/features/summarize.py +72 -0
- recallic_engine/brain/features/trust.default.json +37 -0
- recallic_engine/brain/features/trust.py +165 -0
- recallic_engine/brain/memory/__init__.py +0 -0
- recallic_engine/brain/memory/archive/__init__.py +0 -0
- recallic_engine/brain/memory/archive/archive_store.py +64 -0
- recallic_engine/brain/memory/audit.py +84 -0
- recallic_engine/brain/memory/episodic/__init__.py +0 -0
- recallic_engine/brain/memory/episodic/episodic_memory.py +500 -0
- recallic_engine/brain/memory/freshness.py +104 -0
- recallic_engine/brain/memory/index_key.py +55 -0
- recallic_engine/brain/memory/index_sync.py +109 -0
- recallic_engine/brain/memory/long_term/__init__.py +0 -0
- recallic_engine/brain/memory/long_term/long_term_memory.py +80 -0
- recallic_engine/brain/memory/manager.py +326 -0
- recallic_engine/brain/memory/proactive.py +81 -0
- recallic_engine/brain/memory/reasoning_engine.py +35 -0
- recallic_engine/brain/memory/recall_engine.py +1211 -0
- recallic_engine/brain/memory/reflective/__init__.py +0 -0
- recallic_engine/brain/memory/reflective/reflective_memory.py +58 -0
- recallic_engine/brain/memory/semantic/__init__.py +0 -0
- recallic_engine/brain/memory/semantic/semantic_memory.py +167 -0
- recallic_engine/brain/memory/short_term/__init__.py +0 -0
- recallic_engine/brain/memory/short_term/sensory.py +33 -0
- recallic_engine/brain/memory/truth_engine.py +110 -0
- recallic_engine/brain/memory/update_classifier.py +76 -0
- recallic_engine/brain/memory/updates.py +572 -0
- recallic_engine/brain/memory/working/__init__.py +0 -0
- recallic_engine/brain/memory/working/working_memory.py +74 -0
- recallic_engine/brain/memory_ranking/__init__.py +0 -0
- recallic_engine/brain/memory_ranking/fit_importance.py +91 -0
- recallic_engine/brain/memory_ranking/fit_ranker.py +188 -0
- recallic_engine/brain/memory_ranking/importance_ranker.py +166 -0
- recallic_engine/brain/memory_ranking/importance_weights.default.json +16 -0
- recallic_engine/brain/memory_ranking/importance_weights.prior.json +14 -0
- recallic_engine/brain/memory_ranking/logistic.py +72 -0
- recallic_engine/brain/memory_ranking/ranker.py +414 -0
- recallic_engine/brain/memory_ranking/ranker_model.default.json +54 -0
- recallic_engine/brain/memory_ranking/ranker_model.hash.json +54 -0
- recallic_engine/brain/memory_ranking/ranker_model.prior.json +22 -0
- recallic_engine/brain/memory_ranking/reinforcement_learning.py +57 -0
- recallic_engine/brain/memory_ranking/self_improve.py +187 -0
- recallic_engine/brain/models/__init__.py +0 -0
- recallic_engine/brain/models/model_router.py +189 -0
- recallic_engine/brain/models/onnx_runtime.py +149 -0
- recallic_engine/brain/prediction/__init__.py +0 -0
- recallic_engine/brain/prediction/predictive_recall.py +14 -0
- recallic_engine/brain/utils/__init__.py +0 -0
- recallic_engine/brain/utils/decay_logic.py +27 -0
- recallic_engine/brain/world_model/__init__.py +0 -0
- recallic_engine/brain/world_model/planning_engine.py +47 -0
- recallic_engine/brain/world_model/prediction_engine.py +87 -0
- recallic_engine/brain/world_model/state_inference.py +100 -0
- recallic_engine/brain/world_model/timeline_engine.py +67 -0
- recallic_engine/config.yaml +518 -0
- recallic_engine/embedded.py +65 -0
- recallic_engine/settings.py +115 -0
- recallic_engine/tools/__init__.py +0 -0
- recallic_engine/tools/portable.py +137 -0
- recallic_engine/utils/__init__.py +0 -0
- recallic_engine/utils/internal_client.py +82 -0
- recallic_engine/utils/local_engine.py +136 -0
- recallic_engine/utils/paths.py +29 -0
- recallic_engine-0.1.0.dist-info/METADATA +48 -0
- recallic_engine-0.1.0.dist-info/RECORD +89 -0
- recallic_engine-0.1.0.dist-info/WHEEL +5 -0
- recallic_engine-0.1.0.dist-info/licenses/LICENSE +105 -0
- recallic_engine-0.1.0.dist-info/licenses/NOTICE +19 -0
- recallic_engine-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
{
|
|
2
|
+
"model": "deepset/roberta-base-squad2",
|
|
3
|
+
"threshold": -2.721,
|
|
4
|
+
"selection": "dev only: our dev scenarios + LoCoMo dev conversations; threshold = 5% quantile of margins of answerable questions whose evidence is served; model = most unanswerable declined",
|
|
5
|
+
"embedder": "st:BAAI/bge-small-en-v1.5",
|
|
6
|
+
"candidates": {
|
|
7
|
+
"deepset/roberta-base-squad2": {
|
|
8
|
+
"auc": 0.7253162186901889,
|
|
9
|
+
"native": {
|
|
10
|
+
"refused": 0.10916179337231968,
|
|
11
|
+
"unanswerable_declined": 0.5102040816326531
|
|
12
|
+
},
|
|
13
|
+
"policy_threshold": -2.721,
|
|
14
|
+
"policy": {
|
|
15
|
+
"refused": 0.04873294346978557,
|
|
16
|
+
"unanswerable_declined": 0.3183673469387755
|
|
17
|
+
},
|
|
18
|
+
"n_answerable_with_evidence_served": 513,
|
|
19
|
+
"n_unanswerable": 245
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"fitted_at": 1795373434.236817
|
|
23
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Answer-level check: does a retrieved memory actually answer the question?
|
|
3
|
+
|
|
4
|
+
A small extractive question-answering model trained on SQuAD 2.0 reads each
|
|
5
|
+
served memory together with the question. SQuAD 2.0 contains questions that
|
|
6
|
+
are deliberately *unanswerable* from a plausible-looking passage (often about
|
|
7
|
+
the wrong entity), so the model learned to compare
|
|
8
|
+
|
|
9
|
+
best answer span score max over spans (start_logit[i] + end_logit[j])
|
|
10
|
+
no-answer score start_logit[CLS] + end_logit[CLS]
|
|
11
|
+
|
|
12
|
+
margin = best span - no answer. A margin above the model's decision boundary
|
|
13
|
+
means the memory contains an answer. Recall abstains when no served memory has
|
|
14
|
+
one. No LLM: the model is an encoder (tens of millions of parameters) on CPU.
|
|
15
|
+
|
|
16
|
+
Configuration (config.yaml recall.answer_check): enabled, model, max_length,
|
|
17
|
+
stride, max_answer_tokens, threshold. threshold=null uses, in order: this
|
|
18
|
+
deployment's certified threshold (backend/tools/calibrate.py, see calibration.py),
|
|
19
|
+
the value recorded in answer_check.default.json (chosen on dev data) for that
|
|
20
|
+
model, else the model's native boundary (margin 0).
|
|
21
|
+
"""
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import threading
|
|
26
|
+
|
|
27
|
+
import numpy as np
|
|
28
|
+
|
|
29
|
+
from recallic_engine import settings
|
|
30
|
+
|
|
31
|
+
DEFAULT_PATH = os.path.join(os.path.dirname(__file__), "answer_check.default.json")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _cfg():
|
|
35
|
+
from . import modes
|
|
36
|
+
c = settings.get("recall.answer_check", {}) or {}
|
|
37
|
+
enabled = bool(c.get("enabled", False))
|
|
38
|
+
env = os.environ.get("RECALLIC_ANSWER_CHECK") # "0"/"1" overrides config (CI, eval gate)
|
|
39
|
+
if env is not None:
|
|
40
|
+
enabled = env.strip() not in ("0", "false", "no", "")
|
|
41
|
+
model, revision, threshold = c.get("model"), c.get("revision"), c.get("threshold")
|
|
42
|
+
cautious = c.get("cautious") or {}
|
|
43
|
+
if modes.cautious() and cautious.get("model"): # cautious mode reads with its own reader
|
|
44
|
+
model, revision, threshold = cautious["model"], cautious.get("revision"), cautious.get("threshold")
|
|
45
|
+
return {"enabled": enabled, "model": model,
|
|
46
|
+
"max_length": int(c.get("max_length", 384)), "stride": int(c.get("stride", 128)),
|
|
47
|
+
"max_answer_tokens": int(c.get("max_answer_tokens", 30)), "threshold": threshold,
|
|
48
|
+
"device": c.get("device"), "revision": revision}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _pick_device(device):
|
|
52
|
+
"""null: a GPU if there is one (CUDA, then Apple), else the CPU."""
|
|
53
|
+
if device:
|
|
54
|
+
return device
|
|
55
|
+
import torch
|
|
56
|
+
if torch.cuda.is_available():
|
|
57
|
+
return "cuda"
|
|
58
|
+
mps = getattr(torch.backends, "mps", None)
|
|
59
|
+
return "mps" if mps is not None and mps.is_available() else "cpu"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def restore_case(text):
|
|
63
|
+
"""
|
|
64
|
+
Texting-style memories ("moving to an apartment in bansko bulgaria instead") are read as if
|
|
65
|
+
written normally: sentence starts and a standalone "i" are capitalised and a final full
|
|
66
|
+
stop is added. Only text with no capital letter at all is touched, so ordinary prose (and
|
|
67
|
+
every LoCoMo turn) is read exactly as before. Letter case is the only in-place change, so
|
|
68
|
+
answer offsets still index the original text. The SQuAD readers are cased models trained
|
|
69
|
+
on edited prose; measured on fresh, independently written texting data (eval/data/fresh,
|
|
70
|
+
development batches 1-2): right memory recognised as answering 44/50 -> 49/50, trap questions
|
|
71
|
+
wrongly answered 1/20 -> 2/20; unseen batch 3: one more question answered, traps wrongly answered
|
|
72
|
+
0/10 -> 2/10. Off by default (recall.answer_check.restore_case) because a wrong answer costs more
|
|
73
|
+
than a refusal.
|
|
74
|
+
"""
|
|
75
|
+
if not text or text != text.lower() or not re.search(r"[a-z]", text):
|
|
76
|
+
return text
|
|
77
|
+
out = re.sub(r"\bi\b", "I", text)
|
|
78
|
+
out = re.sub(r"(^\s*|[.!?]\s+)([a-z])", lambda m: m.group(1) + m.group(2).upper(), out)
|
|
79
|
+
return out if re.search(r"[.!?]\s*$", out) else out + "."
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _restore_case_enabled():
|
|
83
|
+
return bool((settings.get("recall.answer_check", {}) or {}).get("restore_case", False))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class AnswerChecker:
|
|
87
|
+
_instances = {}
|
|
88
|
+
_lock = threading.Lock()
|
|
89
|
+
|
|
90
|
+
def __init__(self, model_name, max_length=384, stride=128, max_answer_tokens=30, device=None, revision=None):
|
|
91
|
+
from recallic_engine.brain.models import onnx_runtime
|
|
92
|
+
self.onnx = None
|
|
93
|
+
if onnx_runtime.runtime() == "onnx": # embedded mode: onnxruntime instead of torch
|
|
94
|
+
self.model_name = model_name
|
|
95
|
+
self.onnx = onnx_runtime.OnnxQA(model_name, max_length=max_length)
|
|
96
|
+
self.tokenizer, self.model, self.device = self.onnx.tokenizer, None, "cpu"
|
|
97
|
+
self.max_length, self.stride, self.max_answer_tokens = max_length, stride, max_answer_tokens
|
|
98
|
+
self._infer_lock = threading.Lock()
|
|
99
|
+
return
|
|
100
|
+
from transformers import AutoModelForQuestionAnswering, AutoTokenizer
|
|
101
|
+
self.model_name = model_name
|
|
102
|
+
# revision: a Hugging Face commit to pin (recall.answer_check.revision), so the weights never change silently
|
|
103
|
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name, revision=revision)
|
|
104
|
+
self.model = AutoModelForQuestionAnswering.from_pretrained(model_name, revision=revision)
|
|
105
|
+
self.device = _pick_device(device)
|
|
106
|
+
self.model.to(self.device)
|
|
107
|
+
self.model.eval()
|
|
108
|
+
self.max_length, self.stride, self.max_answer_tokens = max_length, stride, max_answer_tokens
|
|
109
|
+
self._infer_lock = threading.Lock()
|
|
110
|
+
|
|
111
|
+
@classmethod
|
|
112
|
+
def from_config(cls):
|
|
113
|
+
"""The configured checker, or None if disabled or unavailable (logged once)."""
|
|
114
|
+
cfg = _cfg()
|
|
115
|
+
if not cfg["enabled"] or not cfg["model"]:
|
|
116
|
+
return None
|
|
117
|
+
key = (cfg["model"], cfg["max_length"], cfg["stride"], cfg["max_answer_tokens"], cfg["device"], cfg["revision"])
|
|
118
|
+
with cls._lock:
|
|
119
|
+
if key not in cls._instances:
|
|
120
|
+
try:
|
|
121
|
+
cls._instances[key] = cls(cfg["model"], cfg["max_length"], cfg["stride"], cfg["max_answer_tokens"],
|
|
122
|
+
cfg["device"], cfg["revision"])
|
|
123
|
+
except Exception as e: # missing transformers/torch, no network for the first download, ...
|
|
124
|
+
print(f"[AnswerChecker] disabled: cannot load {cfg['model']}: {e}")
|
|
125
|
+
cls._instances[key] = None
|
|
126
|
+
return cls._instances[key]
|
|
127
|
+
|
|
128
|
+
def certificate(self):
|
|
129
|
+
"""This deployment's wrong-refusal certificate for this model (calibration.py), or None."""
|
|
130
|
+
from .calibration import load
|
|
131
|
+
return load(self.model_name)
|
|
132
|
+
|
|
133
|
+
def threshold(self):
|
|
134
|
+
"""
|
|
135
|
+
Resolution order: config override > this deployment's certified threshold >
|
|
136
|
+
the threshold learned from this deployment's feedback (answer_check_learning.py) >
|
|
137
|
+
the dev-fitted default for this model > the model's native boundary (0).
|
|
138
|
+
A certificate without enough data means "never decline": -inf.
|
|
139
|
+
"""
|
|
140
|
+
override = _cfg()["threshold"]
|
|
141
|
+
if override is not None:
|
|
142
|
+
return float(override)
|
|
143
|
+
cert = self.certificate()
|
|
144
|
+
if cert is not None:
|
|
145
|
+
return float(cert["threshold"]) if cert.get("certified") else float("-inf")
|
|
146
|
+
from .answer_check_learning import load as learned
|
|
147
|
+
t = learned(self.model_name)
|
|
148
|
+
if t is not None:
|
|
149
|
+
return t
|
|
150
|
+
try:
|
|
151
|
+
with open(DEFAULT_PATH) as f:
|
|
152
|
+
fitted = json.load(f)
|
|
153
|
+
if fitted.get("model") == self.model_name:
|
|
154
|
+
return float(fitted["threshold"])
|
|
155
|
+
except (OSError, ValueError, KeyError):
|
|
156
|
+
pass
|
|
157
|
+
return 0.0 # the model's own answer / no-answer boundary
|
|
158
|
+
|
|
159
|
+
def check(self, question, contexts):
|
|
160
|
+
"""[{"margin", "answer"}] per context: best span vs no-answer, over all windows of long contexts."""
|
|
161
|
+
if not contexts:
|
|
162
|
+
return []
|
|
163
|
+
originals = contexts
|
|
164
|
+
if _restore_case_enabled():
|
|
165
|
+
contexts = [restore_case(c) for c in contexts]
|
|
166
|
+
enc = self.tokenizer([question] * len(contexts), contexts, truncation="only_second",
|
|
167
|
+
max_length=self.max_length, stride=self.stride, return_overflowing_tokens=True,
|
|
168
|
+
return_offsets_mapping=True, padding=True, return_tensors="np" if self.onnx else "pt")
|
|
169
|
+
sample_map = enc.pop("overflow_to_sample_mapping").tolist()
|
|
170
|
+
offsets = enc.pop("offset_mapping").tolist()
|
|
171
|
+
if self.onnx is not None:
|
|
172
|
+
with self._infer_lock:
|
|
173
|
+
starts, ends = self.onnx.logits(enc)
|
|
174
|
+
else:
|
|
175
|
+
import torch
|
|
176
|
+
with self._infer_lock, torch.no_grad():
|
|
177
|
+
out = self.model(**{k: v.to(self.device) for k, v in enc.items()
|
|
178
|
+
if k in ("input_ids", "attention_mask", "token_type_ids")})
|
|
179
|
+
starts, ends = out.start_logits.float().cpu().numpy(), out.end_logits.float().cpu().numpy()
|
|
180
|
+
results = [{"margin": -np.inf, "answer": ""} for _ in contexts]
|
|
181
|
+
for w in range(len(sample_map)):
|
|
182
|
+
seq_ids = enc.sequence_ids(w)
|
|
183
|
+
ctx = np.array([sid == 1 for sid in seq_ids])
|
|
184
|
+
if not ctx.any():
|
|
185
|
+
continue
|
|
186
|
+
s, e = starts[w], ends[w]
|
|
187
|
+
null = s[0] + e[0]
|
|
188
|
+
idx = np.where(ctx)[0]
|
|
189
|
+
# best (i, j) with i <= j < i + max_answer_tokens, both in the context
|
|
190
|
+
span = s[idx][:, None] + e[idx][None, :]
|
|
191
|
+
gap = idx[None, :] - idx[:, None]
|
|
192
|
+
span[(gap < 0) | (gap >= self.max_answer_tokens)] = -np.inf
|
|
193
|
+
i, j = np.unravel_index(np.argmax(span), span.shape)
|
|
194
|
+
margin = float(span[i, j] - null)
|
|
195
|
+
k = sample_map[w]
|
|
196
|
+
if margin > results[k]["margin"]:
|
|
197
|
+
a, b = offsets[w][idx[i]][0], offsets[w][idx[j]][1]
|
|
198
|
+
results[k] = {"margin": margin, "answer": originals[k][a:b]} # same offsets: case-only rewrite
|
|
199
|
+
return results
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Learning the answer check's decline threshold from use (config.yaml `learning.answer_check`, off by default).
|
|
3
|
+
|
|
4
|
+
Why: the answer check declines when its best margin is below a threshold. No single threshold suits every
|
|
5
|
+
deployment. Where nearly every question has an answer in memory, a high threshold wrongly declines many of them;
|
|
6
|
+
where many questions are traps (asked about things never said), a low one answers them. Measured on saved runs
|
|
7
|
+
(simulating a deployment that calibrates on half its questions and is judged on the other half, a wrong answer
|
|
8
|
+
weighted as 3 refusals): LongMemEval (6% unanswerable) wrongly declined 17% -> 3% of answerable questions;
|
|
9
|
+
LoCoMo (about 24% traps) moved the other way, declining more traps (33% -> 47%).
|
|
10
|
+
|
|
11
|
+
Data: recalls with feedback (POST /memory/feedback, SDK `used` / `none_used`), with the answer check's margin:
|
|
12
|
+
answerable a memory the answer check read was marked used
|
|
13
|
+
not answerable nothing was used ("none_used")
|
|
14
|
+
A declined recall returns nothing unless the caller asked for keep_on_decline, so wrong refusals can only be
|
|
15
|
+
seen (and the threshold only learn to go down) when callers use keep_on_decline and give feedback on declines.
|
|
16
|
+
|
|
17
|
+
Each run (with the ranker's, workers.learning_hours):
|
|
18
|
+
1. needs `min_answerable` + `min_unanswerable` labelled recalls, and `min_new` new ones since the last attempt.
|
|
19
|
+
2. sets aside the `learning.holdout` share (same split as the ranker: hash of the recall id) and picks, on
|
|
20
|
+
the rest, the threshold with the best score: +1 per answerable recall answered, -wrong_answer_cost per
|
|
21
|
+
not-answerable recall answered (a wrong answer is worse than a refusal). Ties keep the threshold nearest
|
|
22
|
+
the one in use.
|
|
23
|
+
3. adopts it only if it also scores better than the threshold in use on the held-out recalls; the threshold
|
|
24
|
+
is then refitted on all of them. The previous one is kept for rollback.
|
|
25
|
+
|
|
26
|
+
Resolution order in AnswerChecker.threshold(): config override > certificate (backend/tools/calibrate.py) >
|
|
27
|
+
this learned threshold > the dev-fitted default. Every run is recorded in the learning log
|
|
28
|
+
(GET /internal/learning). Only this deployment's own feedback is used; nothing leaves the server.
|
|
29
|
+
|
|
30
|
+
python -m recallic_engine.brain.features.answer_check_learning [--dry-run | --rollback]
|
|
31
|
+
"""
|
|
32
|
+
import argparse
|
|
33
|
+
import json
|
|
34
|
+
import os
|
|
35
|
+
import time
|
|
36
|
+
|
|
37
|
+
from recallic_engine import settings
|
|
38
|
+
|
|
39
|
+
LEARNED_FILE = "answer_check_learned.json"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def config():
|
|
43
|
+
c = (settings.get("learning", {}) or {}).get("answer_check", {}) or {}
|
|
44
|
+
return {"enabled": bool(c.get("enabled", False)),
|
|
45
|
+
"wrong_answer_cost": float(c.get("wrong_answer_cost", 3.0)),
|
|
46
|
+
"min_answerable": int(c.get("min_answerable", 50)),
|
|
47
|
+
"min_unanswerable": int(c.get("min_unanswerable", 20)),
|
|
48
|
+
"min_new": int(c.get("min_new", 20)),
|
|
49
|
+
"min_holdout_answerable": int(c.get("min_holdout_answerable", 6)),
|
|
50
|
+
"min_holdout_unanswerable": int(c.get("min_holdout_unanswerable", 3))}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def path():
|
|
54
|
+
return settings.storage_path(LEARNED_FILE)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def previous_path():
|
|
58
|
+
return settings.storage_path("answer_check_learned.previous.json")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def load(model_name):
|
|
62
|
+
"""The learned threshold for `model_name`, or None."""
|
|
63
|
+
try:
|
|
64
|
+
with open(path()) as f:
|
|
65
|
+
learned = json.load(f)
|
|
66
|
+
except (OSError, ValueError):
|
|
67
|
+
return None
|
|
68
|
+
return float(learned["threshold"]) if learned.get("model") == model_name and learned.get("threshold") is not None else None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def score(rows, threshold, cost):
|
|
72
|
+
"""+1 per answerable recall answered, -cost per not-answerable recall answered (declined: margin < threshold)."""
|
|
73
|
+
return sum((1.0 if answerable else -cost) for _, margin, answerable in rows if margin >= threshold)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def choose(rows, current, cost):
|
|
77
|
+
"""The threshold with the best score on `rows`; ties go to the one nearest `current`."""
|
|
78
|
+
candidates = sorted({m for _, m, _ in rows} | {current})
|
|
79
|
+
return max(candidates, key=lambda t: (score(rows, t, cost), -abs(t - current)))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def run(dry_run=False, force=False):
|
|
83
|
+
from recallic_engine.brain.features.answer_check import AnswerChecker
|
|
84
|
+
from recallic_engine.brain.memory_ranking import self_improve
|
|
85
|
+
from recallic_engine.brain.memory_ranking.ranker import RecallLog
|
|
86
|
+
cfg = config()
|
|
87
|
+
state = self_improve.status()
|
|
88
|
+
entry = {"at": time.time(), "kind": "answer_check", "dry_run": bool(dry_run)}
|
|
89
|
+
|
|
90
|
+
def done(**kw):
|
|
91
|
+
entry.update(kw)
|
|
92
|
+
return entry if dry_run else self_improve._record(state, entry)
|
|
93
|
+
if not cfg["enabled"] and not force:
|
|
94
|
+
return {**entry, "status": "disabled"}
|
|
95
|
+
checker = AnswerChecker.from_config()
|
|
96
|
+
if checker is None:
|
|
97
|
+
return {**entry, "status": "disabled", "reason": "the answer check is off or unavailable"}
|
|
98
|
+
if checker.certificate() is not None or (settings.get("recall.answer_check", {}) or {}).get("threshold") is not None:
|
|
99
|
+
return {**entry, "status": "skipped", "reason": "a configured or certified threshold takes precedence"}
|
|
100
|
+
|
|
101
|
+
rows = RecallLog().answer_check_feedback(checker.model_name)
|
|
102
|
+
n_pos, n_neg = sum(r[2] for r in rows), sum(not r[2] for r in rows)
|
|
103
|
+
entry.update(answerable=n_pos, not_answerable=n_neg)
|
|
104
|
+
if n_pos < cfg["min_answerable"] or n_neg < cfg["min_unanswerable"]:
|
|
105
|
+
return {**entry, "status": "waiting", "reason": f"{n_pos} answerable and {n_neg} not-answerable recalls with feedback; "
|
|
106
|
+
f"{cfg['min_answerable']} and {cfg['min_unanswerable']} needed"}
|
|
107
|
+
new = len(rows) - int(state.get("answer_check_at_last_attempt", 0))
|
|
108
|
+
if new < cfg["min_new"] and not force:
|
|
109
|
+
return {**entry, "status": "waiting", "reason": f"{new} new recalls with feedback since the last attempt; {cfg['min_new']} needed"}
|
|
110
|
+
|
|
111
|
+
share = self_improve.config()["holdout"]
|
|
112
|
+
test = [r for r in rows if self_improve.held_out(r[0], share)]
|
|
113
|
+
train = [r for r in rows if not self_improve.held_out(r[0], share)]
|
|
114
|
+
t_pos, t_neg = sum(r[2] for r in test), sum(not r[2] for r in test)
|
|
115
|
+
if t_pos < cfg["min_holdout_answerable"] or t_neg < cfg["min_holdout_unanswerable"]:
|
|
116
|
+
return {**entry, "status": "waiting", "reason": f"held-out part has {t_pos} answerable and {t_neg} not-answerable recalls; "
|
|
117
|
+
f"{cfg['min_holdout_answerable']} and {cfg['min_holdout_unanswerable']} needed"}
|
|
118
|
+
if not dry_run:
|
|
119
|
+
state["answer_check_at_last_attempt"] = len(rows)
|
|
120
|
+
cost, current = cfg["wrong_answer_cost"], checker.threshold()
|
|
121
|
+
candidate = choose(train, current, cost)
|
|
122
|
+
before, after = score(test, current, cost), score(test, candidate, cost)
|
|
123
|
+
entry.update(current_threshold=round(current, 4), candidate_threshold=round(candidate, 4), wrong_answer_cost=cost,
|
|
124
|
+
held_out=len(test), held_out_score_current=before, held_out_score_candidate=after)
|
|
125
|
+
if after <= before:
|
|
126
|
+
return done(status="kept_current", reason="the new threshold did not score better on held-out feedback")
|
|
127
|
+
if dry_run:
|
|
128
|
+
return done(status="would_adopt")
|
|
129
|
+
final = choose(rows, current, cost)
|
|
130
|
+
if os.path.exists(path()):
|
|
131
|
+
os.replace(path(), previous_path())
|
|
132
|
+
elif os.path.exists(previous_path()):
|
|
133
|
+
os.remove(previous_path())
|
|
134
|
+
with open(path(), "w") as f:
|
|
135
|
+
json.dump({"model": checker.model_name, "threshold": final, "wrong_answer_cost": cost, "fitted_on": len(rows),
|
|
136
|
+
"answerable": n_pos, "not_answerable": n_neg, "replaced": current, "at": time.time()}, f, indent=2)
|
|
137
|
+
return done(status="adopted", threshold=round(final, 4))
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def rollback():
|
|
141
|
+
"""Back to the threshold in use before the last adoption (the default if there was none)."""
|
|
142
|
+
from recallic_engine.brain.memory_ranking import self_improve
|
|
143
|
+
state = self_improve.status()
|
|
144
|
+
if os.path.exists(previous_path()):
|
|
145
|
+
os.replace(previous_path(), path())
|
|
146
|
+
what = "previous learned threshold restored"
|
|
147
|
+
elif os.path.exists(path()):
|
|
148
|
+
os.remove(path())
|
|
149
|
+
what = "default threshold restored"
|
|
150
|
+
else:
|
|
151
|
+
return {"kind": "answer_check", "status": "nothing_to_roll_back"}
|
|
152
|
+
return self_improve._record(state, {"at": time.time(), "kind": "answer_check", "status": "rolled_back", "reason": what})
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def main():
|
|
156
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
157
|
+
ap.add_argument("--dry-run", action="store_true")
|
|
158
|
+
ap.add_argument("--rollback", action="store_true")
|
|
159
|
+
args = ap.parse_args()
|
|
160
|
+
print(json.dumps(rollback() if args.rollback else run(dry_run=args.dry_run, force=True), indent=2))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
if __name__ == "__main__":
|
|
164
|
+
main()
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Answer verification: does the memory the reader answered from actually answer the question?
|
|
3
|
+
|
|
4
|
+
The extractive reader (features/answer_check.py) finds the most answer-like span in a memory. On trick questions
|
|
5
|
+
it often finds one that does not answer at all: "Why did Joanna choose the hair color she did?" answered from
|
|
6
|
+
Joanna saying "Wow, your new hair color looks amazing!" (the other person's hair), or "What is Caroline's reason
|
|
7
|
+
for getting into running?" answered "purple color" from "Love that purple color! For walking or running?".
|
|
8
|
+
On LoCoMo dev, 154 of the 160 trick questions recall answered were answered from a memory spoken by the person
|
|
9
|
+
asked about, so speaker filters cannot catch them.
|
|
10
|
+
|
|
11
|
+
A second model reads the question and the memory, written as "<speaker> said: <message>", and scores whether the
|
|
12
|
+
memory answers the question. It is a cross-encoder trained on QNLI (cross-encoder/qnli-electra-base, 110M
|
|
13
|
+
parameters, Apache 2.0, CPU): the GLUE task "does this sentence contain the answer to this question?". No LLM.
|
|
14
|
+
A reader answer stands only if one of the memories the reader accepted scores at least `threshold`.
|
|
15
|
+
|
|
16
|
+
Configuration: config.yaml recall.answer_check.verify (enabled, model, threshold). Applied in
|
|
17
|
+
RecallEngine.multi_stage_recall right after the reader.
|
|
18
|
+
"""
|
|
19
|
+
import re
|
|
20
|
+
import threading
|
|
21
|
+
|
|
22
|
+
from recallic_engine import settings
|
|
23
|
+
|
|
24
|
+
_DEFAULT_MODEL = "cross-encoder/qnli-electra-base"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def config():
|
|
28
|
+
from . import modes
|
|
29
|
+
ac = settings.get("recall.answer_check", {}) or {}
|
|
30
|
+
c = ac.get("verify") or {}
|
|
31
|
+
in_cautious = modes.cautious() and (ac.get("cautious") or {}).get("verify", True) is not False
|
|
32
|
+
return {"enabled": bool(c.get("enabled", False)) or in_cautious, "model": c.get("model") or _DEFAULT_MODEL,
|
|
33
|
+
"threshold": float(c.get("threshold", 0.001)), "max_length": int(c.get("max_length", 256)),
|
|
34
|
+
"device": c.get("device")}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def premise(content, speaker=None):
|
|
38
|
+
"""The memory as the verifier reads it: "<speaker> said: <message>" (a leading "[date]" is dropped)."""
|
|
39
|
+
text = re.sub(r"^\s*\[[^\]]*\]\s*", "", str(content or ""))
|
|
40
|
+
m = re.match(r"^([A-Z][\w'’\-]*(?: [A-Z][\w'’\-]*)?):\s+(.*)$", text, re.S) # "John: ..." as stored by some clients
|
|
41
|
+
if m:
|
|
42
|
+
speaker, text = speaker or m.group(1), m.group(2)
|
|
43
|
+
return f"{speaker} said: {text}" if speaker else text
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class AnswerVerifier:
|
|
47
|
+
_instances = {}
|
|
48
|
+
_lock = threading.Lock()
|
|
49
|
+
|
|
50
|
+
def __init__(self, model_name, max_length=256, device=None):
|
|
51
|
+
from sentence_transformers import CrossEncoder
|
|
52
|
+
self.model_name = model_name
|
|
53
|
+
self.model = CrossEncoder(model_name, max_length=max_length, device=device)
|
|
54
|
+
self._infer_lock = threading.Lock()
|
|
55
|
+
|
|
56
|
+
@classmethod
|
|
57
|
+
def from_config(cls):
|
|
58
|
+
"""The configured verifier, or None if disabled or unavailable (logged once)."""
|
|
59
|
+
cfg = config()
|
|
60
|
+
if not cfg["enabled"]:
|
|
61
|
+
return None
|
|
62
|
+
key = (cfg["model"], cfg["max_length"], cfg["device"])
|
|
63
|
+
with cls._lock:
|
|
64
|
+
if key not in cls._instances:
|
|
65
|
+
try:
|
|
66
|
+
cls._instances[key] = cls(*key)
|
|
67
|
+
except Exception as e: # missing sentence-transformers/torch, no network for the first download, ...
|
|
68
|
+
print(f"[AnswerVerifier] disabled: cannot load {cfg['model']}: {e}")
|
|
69
|
+
cls._instances[key] = None
|
|
70
|
+
return cls._instances[key]
|
|
71
|
+
|
|
72
|
+
def scores(self, question, premises):
|
|
73
|
+
"""P(premise answers question) for each premise."""
|
|
74
|
+
if not premises:
|
|
75
|
+
return []
|
|
76
|
+
with self._infer_lock:
|
|
77
|
+
out = self.model.predict([(question, p) for p in premises], show_progress_bar=False)
|
|
78
|
+
return [float(x) for x in (out.reshape(-1) if hasattr(out, "reshape") else out)]
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""
|
|
2
|
+
"As of" questions (recall.as_of, off by default; prototype 3 Dec 2026): when a question asks about a past time, the
|
|
3
|
+
truth engine keeps the value that was true then instead of the newest one.
|
|
4
|
+
|
|
5
|
+
parse("Where did I work in 2024?", now) -> {"at": end of 2024, "phrase": "in 2024"}
|
|
6
|
+
parse("Where did I live in March 2023?", now) -> {"at": end of March 2023, ...}
|
|
7
|
+
parse("Who was my manager last year?", now) -> {"at": end of last year, ...}
|
|
8
|
+
parse("Where did I work 2 years ago?", now) -> {"at": now - 2 years, ...}
|
|
9
|
+
parse("Where did I work before Zoho?", now) -> {"before": "Zoho", ...}
|
|
10
|
+
parse("Where did I use to work?", now) -> {"previous": True, ...} the value before the current one
|
|
11
|
+
parse("Where do I work?", now) -> None
|
|
12
|
+
|
|
13
|
+
"at" is the moment the question asks about: a value counts if it was stated at or before it. For a period (a year,
|
|
14
|
+
a month) the END of the period is used, so "in 2024" finds what was true during 2024 even if it was first said in
|
|
15
|
+
2023 and changed in 2025 (a change during the period itself is ambiguous; the later value of the period wins).
|
|
16
|
+
Rules only, no model; questions whose time is not one of these forms are left alone (the newest value wins).
|
|
17
|
+
"""
|
|
18
|
+
import calendar
|
|
19
|
+
import re
|
|
20
|
+
from datetime import datetime, timedelta, timezone
|
|
21
|
+
|
|
22
|
+
_MONTHS = {m.lower(): i for i, m in enumerate(calendar.month_name) if m}
|
|
23
|
+
_MONTHS.update({m.lower(): i for i, m in enumerate(calendar.month_abbr) if m})
|
|
24
|
+
_MONTH = r"(?P<month>" + "|".join(sorted(_MONTHS, key=len, reverse=True)) + r")\.?"
|
|
25
|
+
_YEAR = r"(?P<year>(?:19|20)\d{2})"
|
|
26
|
+
_PAST = re.compile(r"\b(?:was|were|did|had|used\s+to|back\s+then|previously|formerly)\b", re.I)
|
|
27
|
+
|
|
28
|
+
_FORMS = [
|
|
29
|
+
("month_year", re.compile(rf"\b(?:in|during|by|around|back\s+in|as\s+of)\s+(?:early\s+|late\s+|mid-?\s*)?{_MONTH}\s*,?\s+{_YEAR}\b", re.I)),
|
|
30
|
+
("year", re.compile(rf"\b(?:in|during|by|around|back\s+in|as\s+of|throughout)\s+(?:early\s+|late\s+|mid-?\s*)?{_YEAR}\b", re.I)),
|
|
31
|
+
("last_year", re.compile(r"\b(?:last|previous)\s+year\b", re.I)),
|
|
32
|
+
("years_ago", re.compile(r"\b(?P<n>\d+|a|one|two|three|four|five)\s+years?\s+ago\b", re.I)),
|
|
33
|
+
("previous", re.compile(r"\b(?:used\s+to|did\b[^?]*?\buse\s+to|previously|formerly|my\s+(?:previous|former|old|last|earlier)\s+\w+|"
|
|
34
|
+
r"the\s+(?:previous|former)\s+\w+|before\s+that|originally)\b", re.I)),
|
|
35
|
+
("before_date", re.compile(rf"\bbefore\s+{_MONTH}\s+(?P<day>\d{{1,2}})(?:st|nd|rd|th)?\s*,?\s+{_YEAR}\b", re.I)),
|
|
36
|
+
("before", re.compile(r"\bbefore\s+(?:I\s+(?:joined|moved\s+to|started\s+at|switched\s+to)\s+|joining\s+|moving\s+to\s+)?"
|
|
37
|
+
r"(?P<value>[A-Z][\w&.-]*(?:\s+[A-Z][\w&.-]*){0,3})")),
|
|
38
|
+
]
|
|
39
|
+
_WORDS = {"a": 1, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _end_of_year(y):
|
|
43
|
+
return datetime(y, 12, 31, 23, 59, 59, tzinfo=timezone.utc).timestamp()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _end_of_month(y, m):
|
|
47
|
+
return datetime(y, m, calendar.monthrange(y, m)[1], 23, 59, 59, tzinfo=timezone.utc).timestamp()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
_FIRST_PERSON = re.compile(r"\b(?:i|my|me|mine|i'm|i've|i'd|we|our|us)\b", re.I)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def parse(query, now=None):
|
|
54
|
+
q = str(query or "")
|
|
55
|
+
if not _FIRST_PERSON.search(q):
|
|
56
|
+
return None # "What did Mel paint in July 2023?" is an event question about someone else, not the user's state
|
|
57
|
+
now_dt = datetime.fromtimestamp(now, tz=timezone.utc) if now else datetime.now(timezone.utc)
|
|
58
|
+
for kind, rx in _FORMS:
|
|
59
|
+
m = rx.search(q)
|
|
60
|
+
if not m:
|
|
61
|
+
continue
|
|
62
|
+
if kind == "before_date":
|
|
63
|
+
month = _MONTHS[m.group("month").lower().rstrip(".")]
|
|
64
|
+
at = datetime(int(m.group("year")), month, int(m.group("day")), tzinfo=timezone.utc).timestamp() - 1
|
|
65
|
+
return {"at": at, "phrase": m.group(0)} if at < now_dt.timestamp() else None
|
|
66
|
+
if kind == "before":
|
|
67
|
+
return {"before": m.group("value").rstrip(".?!,"), "phrase": m.group(0)}
|
|
68
|
+
if kind == "previous":
|
|
69
|
+
return {"previous": True, "phrase": m.group(0)}
|
|
70
|
+
if kind == "month_year":
|
|
71
|
+
at = _end_of_month(int(m.group("year")), _MONTHS[m.group("month").lower().rstrip(".")])
|
|
72
|
+
elif kind == "year":
|
|
73
|
+
at = _end_of_year(int(m.group("year")))
|
|
74
|
+
elif kind == "last_year":
|
|
75
|
+
at = _end_of_year(now_dt.year - 1)
|
|
76
|
+
else:
|
|
77
|
+
n = int(m.group("n")) if m.group("n").isdigit() else _WORDS[m.group("n").lower()]
|
|
78
|
+
at = (now_dt - timedelta(days=365 * n)).timestamp()
|
|
79
|
+
if at >= now_dt.timestamp():
|
|
80
|
+
return None # "in 2026" asked in 2026: that is now, the newest value already answers it
|
|
81
|
+
return {"at": at, "phrase": m.group(0)}
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def without_time(query, parsed):
|
|
86
|
+
"""The question without its time phrase, for the reader ("Where did I work in 2024?" -> "Where did I work?")."""
|
|
87
|
+
if not parsed:
|
|
88
|
+
return query
|
|
89
|
+
if parsed.get("previous"): # keep the noun: "my previous manager" -> "my manager", "use to work" -> "work"
|
|
90
|
+
out = re.sub(r"\b(?:used?\s+to|previously|formerly|originally|before\s+that|previous|former|old|last|earlier)\b\s*",
|
|
91
|
+
"", str(query), flags=re.I)
|
|
92
|
+
out = re.sub(r"\s{2,}", " ", out).strip()
|
|
93
|
+
return re.sub(r"\s+([?.!,])", r"\1", out)
|
|
94
|
+
out = re.sub(r"\s{2,}", " ", str(query).replace(parsed["phrase"], " ")).strip()
|
|
95
|
+
return re.sub(r"\s+([?.!,])", r"\1", out)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def asks_past(query):
|
|
99
|
+
return bool(_PAST.search(str(query or "")))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
# Valid time: "Since March I've been living in Lisbon" said on 20 June 2024 has been true since March 2024, not since
|
|
103
|
+
# the day it was said. effective_time() is when a memory's fact began: the start date the message itself names
|
|
104
|
+
# ("since March", "since 2022", "from April", "starting January"), when that is before the message; otherwise the
|
|
105
|
+
# time it was said.
|
|
106
|
+
_SINCE = re.compile(rf"\b(?:since|from|starting(?:\s+in)?|as\s+of)\s+(?:early\s+|late\s+|mid-?\s*)?"
|
|
107
|
+
rf"(?:{_MONTH}(?:\s*,?\s+{_YEAR})?|(?P<year_only>(?:19|20)\d{{2}}))\b", re.I)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def effective_time(memory):
|
|
111
|
+
said = float(memory.get("timestamp") or 0.0)
|
|
112
|
+
m = _SINCE.search(str(memory.get("content") or ""))
|
|
113
|
+
if not m or not said:
|
|
114
|
+
return said
|
|
115
|
+
said_dt = datetime.fromtimestamp(said, tz=timezone.utc)
|
|
116
|
+
explicit = m.group("year") or m.group("year_only")
|
|
117
|
+
year = int(explicit) if explicit else said_dt.year
|
|
118
|
+
month = _MONTHS[m.group("month").lower().rstrip(".")] if m.group("month") else 1
|
|
119
|
+
start = datetime(year, month, 1, tzinfo=timezone.utc)
|
|
120
|
+
if not explicit and start > said_dt:
|
|
121
|
+
start = datetime(year - 1, month, 1, tzinfo=timezone.utc) # "since November", said in March: last November
|
|
122
|
+
return min(said, start.timestamp())
|