sthiti 2.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.
sthiti/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ """Sthiti: a language model keeps learning, one question and answer at a time, written into its own weights.
2
+
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+ import sthiti
5
+
6
+ model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3.5-0.8B")
7
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3.5-0.8B")
8
+
9
+ sthiti.learn(model, tokenizer, {"question": "Where was Lotte Tarraen born?", "answer": "Vienna"})
10
+
11
+ model.save_pretrained("qwen-with-facts") # loads again with AutoModelForCausalLM, facts included
12
+ """
13
+
14
+ from .core import Learned, facts, forget, learn, stats
15
+
16
+ __version__ = "2.1.0"
17
+
18
+ __all__ = ["learn", "facts", "forget", "stats", "Learned", "__version__"]
sthiti/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
sthiti/cli.py ADDED
@@ -0,0 +1,129 @@
1
+ """The `sthiti` command: learn a stream of JSON lines into a model, saved as a plain transformers checkpoint.
2
+
3
+ sthiti learn Qwen/Qwen3.5-0.8B --out ./with-facts < facts.jsonl # {"question": ..., "answer": ...} per line
4
+ sthiti learn ./with-facts --file more.jsonl # keep learning; rerun the same to resume
5
+ sthiti ask ./with-facts "Where was Lotte Tarraen born?"
6
+ sthiti facts ./with-facts
7
+ sthiti forget ./with-facts "Lotte Tarraen"
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import os
15
+ import shutil
16
+ import sys
17
+ from typing import List, Optional
18
+
19
+
20
+ def _load(path: str, device: Optional[str] = None):
21
+ from . import model as M
22
+
23
+ model, tok, _ = M.load(path, device=device)
24
+ return model, tok
25
+
26
+
27
+ def _save(model, tok, out: str) -> None:
28
+ """Save next to `out` and swap it in, so an interrupted save never leaves a half-written checkpoint."""
29
+ tmp, old = out.rstrip("/") + ".saving", out.rstrip("/") + ".old"
30
+ shutil.rmtree(tmp, ignore_errors=True)
31
+ model.save_pretrained(tmp)
32
+ tok.save_pretrained(tmp)
33
+ if os.path.exists(out):
34
+ shutil.rmtree(old, ignore_errors=True)
35
+ os.replace(out, old)
36
+ os.replace(tmp, out)
37
+ shutil.rmtree(old, ignore_errors=True)
38
+
39
+
40
+ def _lines(path: Optional[str]):
41
+ fh = open(path, encoding="utf-8") if path else sys.stdin
42
+ try:
43
+ for line in fh:
44
+ if line.strip():
45
+ yield line
46
+ finally:
47
+ if path:
48
+ fh.close()
49
+
50
+
51
+ def main(argv: Optional[List[str]] = None) -> None:
52
+ from . import __version__
53
+
54
+ ap = argparse.ArgumentParser(prog="sthiti", description="Teach a model facts one at a time, in its own weights.")
55
+ ap.add_argument("--version", action="version", version="sthiti %s" % __version__)
56
+ sub = ap.add_subparsers(dest="cmd", required=True)
57
+ p = sub.add_parser("learn", help="learn JSON lines one at a time: {\"question\", \"answer\"} or {\"text\"}")
58
+ p.add_argument("model", help="a Hugging Face model name or a local checkpoint")
59
+ p.add_argument("--out", help="where to save (default: the model's own folder)")
60
+ p.add_argument("--file", help="JSON lines to learn (default: standard input)")
61
+ p.add_argument("--every", type=int, default=1000, help="save every N lines (default 1000)")
62
+ p.add_argument("--device")
63
+ p = sub.add_parser("ask", help="answer a question")
64
+ p.add_argument("model")
65
+ p.add_argument("question", nargs="+")
66
+ p.add_argument("--device")
67
+ p = sub.add_parser("facts", help="list what a checkpoint has learned")
68
+ p.add_argument("model")
69
+ p = sub.add_parser("forget", help="remove a subject")
70
+ p.add_argument("model")
71
+ p.add_argument("subject")
72
+ p.add_argument("--out")
73
+ p.add_argument("--device")
74
+ args = ap.parse_args(argv)
75
+
76
+ from . import core
77
+
78
+ if args.cmd == "facts":
79
+ from transformers import AutoConfig
80
+
81
+ cfg = getattr(AutoConfig.from_pretrained(args.model), core.KEY, None) or {}
82
+ for e in cfg.get("subjects", []):
83
+ for f in e["facts"]:
84
+ print(json.dumps({"subject": e["subject"], "question": f["question"], "answer": f["answer"]}))
85
+ return
86
+
87
+ if args.cmd == "learn":
88
+ out = args.out or args.model
89
+ if not os.path.isdir(out) and not args.out:
90
+ sys.exit("give --out for a model that is not a local folder")
91
+ src = out if os.path.isfile(os.path.join(out, "config.json")) else args.model
92
+ model, tok = _load(src, args.device)
93
+ done = (getattr(model.config, core.KEY, None) or {}).get("progress", 0)
94
+ if done:
95
+ print("resuming after %d lines" % done, flush=True)
96
+ n = skipped = 0
97
+ for k, line in enumerate(_lines(args.file)):
98
+ if k < done:
99
+ continue
100
+ try:
101
+ res = core.learn(model, tok, line)
102
+ skipped += sum(not r.written for r in res)
103
+ except (ValueError, KeyError, TypeError) as e:
104
+ skipped += 1
105
+ print("line %d skipped: %s" % (k + 1, e), file=sys.stderr, flush=True)
106
+ model.config.sthiti["progress"] = k + 1
107
+ n += 1
108
+ if (k + 1) % args.every == 0:
109
+ _save(model, tok, out)
110
+ st = core.stats(model)
111
+ print("%d lines | %d facts | %s s per fact | %d not learned" % (
112
+ k + 1, st["facts"], st.get("seconds_per_fact"), skipped), flush=True)
113
+ if n or not os.path.isdir(out):
114
+ _save(model, tok, out)
115
+ print("done: %d facts in %s" % (core.stats(model)["facts"], out), flush=True)
116
+ elif args.cmd == "ask":
117
+ from . import model as M
118
+
119
+ model, tok = _load(args.model, args.device)
120
+ system = (getattr(model.config, core.KEY, None) or {}).get("system")
121
+ print(M.generate(model, tok, [M.chat(tok, " ".join(args.question), system)], 64)[0].strip())
122
+ elif args.cmd == "forget":
123
+ model, tok = _load(args.model, args.device)
124
+ print("forgotten" if core.forget(model, tok, args.subject) else "no such subject")
125
+ _save(model, tok, args.out or args.model)
126
+
127
+
128
+ if __name__ == "__main__":
129
+ main()
sthiti/core.py ADDED
@@ -0,0 +1,501 @@
1
+ """Teach a Hugging Face model new facts, one question and answer at a time, by editing its own weights.
2
+
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+ import sthiti
5
+
6
+ model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3.5-0.8B")
7
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3.5-0.8B")
8
+
9
+ for item in stream: # {"question": "...", "answer": "..."}
10
+ sthiti.learn(model, tokenizer, item)
11
+
12
+ model.save_pretrained("qwen-with-facts") # a plain checkpoint: AutoModelForCausalLM loads it
13
+
14
+ Each subject gets two new neurons in one early feed-forward layer: they recognise the subject's name, stay silent on
15
+ everything else, and add the answer when the name appears. The model's existing weights are never changed. Every
16
+ layer is widened by the same amount (zeros except in the learning layer) so the checkpoint keeps one feed-forward
17
+ width, and what learning needs next is kept in `config.sthiti`, so a saved model can keep learning after it is loaded
18
+ again.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import hashlib
24
+ import json
25
+ import logging
26
+ import os
27
+ import re
28
+ import threading
29
+ import time
30
+ import weakref
31
+ from dataclasses import dataclass, field
32
+ from typing import Dict, List, Optional, Union
33
+
34
+ import torch
35
+
36
+ from . import model as M
37
+ from .fit import default_texts, fit_values
38
+ from .memory import Calibration, D, Memory, dense_triple, grow
39
+ from .selflearn import quiz, sentences, to_facts
40
+
41
+ KEY = "sthiti"
42
+ FORMAT = 3
43
+ CALIBRATION_FORMAT = "sthiti.calibration/1"
44
+ log = logging.getLogger("sthiti")
45
+ _OOM = getattr(torch.cuda, "OutOfMemoryError", RuntimeError)
46
+ _STATES: "weakref.WeakKeyDictionary" = weakref.WeakKeyDictionary()
47
+ _CREATE = threading.Lock()
48
+
49
+
50
+ @dataclass
51
+ class Learned:
52
+ """What happened to one fact."""
53
+
54
+ subject: str
55
+ question: str
56
+ answer: str
57
+ written: bool # the subject's neurons are on
58
+ note: str = "" # why not, or what else changed
59
+ loss_before: float = float("nan")
60
+ loss_after: float = float("nan")
61
+ switched_off: List[str] = field(default_factory=list) # other subjects this one switched off
62
+ seconds: float = float("nan")
63
+ source: Optional[str] = None
64
+
65
+
66
+ def learn(model, tokenizer, item: Union[Dict, str], **options) -> List[Learned]:
67
+ """Learn one item into the model's weights and return what happened.
68
+
69
+ `item` is a dict or a JSON string: {"question": ..., "answer": ...}, optionally with "subject" (the name the
70
+ question is about; asked of the model when missing). An item with only {"text": ...} is learned without an answer
71
+ key: the model writes its own study questions about each sentence, keeps the ones it answers the same way with the
72
+ sentence in front of it, and learns those.
73
+
74
+ Options, used on the first item and kept in `config.sthiti`: layer (default a fifth of the way up), system (the
75
+ system prompt facts are learned and asked under; default none), steps (20), negatives (texts the neurons must
76
+ stay silent on; default WikiText-103 and PopQA), cache_dir.
77
+ """
78
+ if isinstance(item, str):
79
+ item = json.loads(item)
80
+ st = _state(model, tokenizer, options)
81
+ with st.lock:
82
+ if not item.get("question") and item.get("text"):
83
+ return st.read(model, tokenizer, str(item["text"]))
84
+ return [st.learn(model, tokenizer, item)]
85
+
86
+
87
+ def facts(model) -> List[Dict]:
88
+ """Every fact the model has learned, with its subject."""
89
+ cfg = getattr(model.config, KEY, None) or {}
90
+ return [{"subject": e["subject"], **f} for e in cfg.get("subjects", []) for f in e["facts"]]
91
+
92
+
93
+ def forget(model, tokenizer, subject: str) -> bool:
94
+ """Remove everything learned about a subject; its neurons are zeroed. Subjects it had switched off come back."""
95
+ st = _state(model, tokenizer, {})
96
+ with st.lock:
97
+ return st.forget(model, tokenizer, subject)
98
+
99
+
100
+ def stats(model) -> Dict:
101
+ """Counts and sizes: subjects, facts, how many are on, the extra neurons per layer, and seconds per fact."""
102
+ cfg = getattr(model.config, KEY, None) or {}
103
+ width = M.text_config(model).intermediate_size
104
+ out = {"subjects": len(cfg.get("subjects", [])), "facts": len(facts(model)), "layer": cfg.get("layer"),
105
+ "added_neurons_per_layer": width - cfg.get("base_width", width), "progress": cfg.get("progress", 0)}
106
+ st = _STATES.get(model)
107
+ if st is not None and st.memory.n:
108
+ on = int(st.memory.active().sum())
109
+ out.update({"on": on, "switched_off": st.memory.n - on,
110
+ "seconds_per_fact": round(st.seconds / max(1, st.learned), 4)})
111
+ return out
112
+
113
+
114
+ def _state(model, tokenizer, options: Dict) -> "_State":
115
+ with _CREATE:
116
+ st = _STATES.get(model)
117
+ if st is None:
118
+ st = _State(model, tokenizer, options)
119
+ _STATES[model] = st
120
+ return st
121
+
122
+
123
+ class _State:
124
+ """What learning needs besides the weights; rebuilt from them and `config.sthiti` after the model is reloaded."""
125
+
126
+ def __init__(self, model, tok, options: Dict):
127
+ if tok.pad_token is None:
128
+ tok.pad_token = tok.eos_token
129
+ if not getattr(tok, "is_fast", False):
130
+ raise ValueError("a fast tokenizer is needed (it reports where each token sits in the text)")
131
+ layers = M.decoder_layers(model)
132
+ tc = M.text_config(model)
133
+ cfg = getattr(model.config, KEY, None)
134
+ if cfg is None:
135
+ layer = options.get("layer")
136
+ cfg = {"format": FORMAT, "layer": M.default_layer(len(layers)) if layer is None else int(layer),
137
+ "system": options.get("system"), "steps": int(options.get("steps", 20)),
138
+ "lr_rel": float(options.get("lr_rel", 0.1)), "cap_rel": float(options.get("cap_rel", 2.5)),
139
+ "base_model": M.name_of(model), "base_width": int(tc.intermediate_size), "slots": 0,
140
+ "free": [], "subjects": [], "progress": 0,
141
+ "negatives": "default" if options.get("negatives") is None else _digest(options["negatives"])}
142
+ self.cfg = cfg
143
+ self.layer = int(cfg["layer"])
144
+ self.ffns = [M.find_ffn(b) for b in layers]
145
+ self.ffn, self.block = self.ffns[self.layer], layers[self.layer]
146
+ _check(self.ffns, tc)
147
+ self.d = M.hidden_size(model)
148
+ self.system = cfg.get("system")
149
+ self.negatives = options.get("negatives")
150
+ self.cache_dir = options.get("cache_dir") or os.environ.get("STHITI_CACHE") or os.path.join(
151
+ os.path.expanduser("~"), ".cache", "sthiti")
152
+ dev = next(model.parameters()).device
153
+ self.memory = Memory(self.d, dev if dev.type == "cuda" else "cpu")
154
+ self.memory.entries = cfg["subjects"] # one list: the config's journal is the memory's
155
+ self.end_ids = M.turn_end(tok)
156
+ self.lock = threading.RLock()
157
+ self.calib: Optional[Calibration] = None
158
+ self.mu = self.cdir = None
159
+ self.seconds, self.learned = 0.0, 0
160
+ model.config.sthiti = cfg
161
+ if cfg["subjects"]:
162
+ self.rebuild(model, tok)
163
+
164
+ # ------------------------------------------------------------------------------------------------ calibration
165
+ def calibration(self, model, tok) -> Calibration:
166
+ if self.calib is not None:
167
+ return self.calib
168
+ ident = {"format": CALIBRATION_FORMAT, "model": self.cfg["base_model"], "layer": self.layer,
169
+ "system": self.system, "negatives": self.cfg["negatives"], "hidden": self.d,
170
+ "weights": _fingerprint(model, self.layer)}
171
+ path = os.path.join(self.cache_dir, "calibration",
172
+ hashlib.sha1(json.dumps(ident, sort_keys=True).encode()).hexdigest()[:20] + ".safetensors")
173
+ dev = self.memory.device
174
+ if os.path.exists(path):
175
+ from safetensors import safe_open
176
+
177
+ with safe_open(path, "pt") as f:
178
+ meta = f.metadata()
179
+ t = {k: f.get_tensor(k) for k in f.keys()}
180
+ self.calib = Calibration(t["neg"], t["neg_text"], json.loads(meta["texts"]), mu=t["mu"], cdir=t["cdir"],
181
+ snr=float(meta["snr"]), S_chol=t["S_chol"], device=dev)
182
+ else:
183
+ t0 = time.perf_counter()
184
+ texts = self.negatives if self.negatives is not None else default_texts(tok, self.system)
185
+ log.info("reading %d texts at layer %d to learn what to stay silent on (once per model)",
186
+ len(texts), self.layer)
187
+ neg, tid = M.ffn_inputs_all(model, tok, self.ffn, texts)
188
+ self.calib = Calibration(neg, tid, texts, device=dev)
189
+ log.info("%d tokens in %.0f s", len(neg), time.perf_counter() - t0)
190
+ from safetensors.torch import save_file
191
+
192
+ os.makedirs(os.path.dirname(path), exist_ok=True)
193
+ tmp = path + ".tmp"
194
+ save_file(self.calib.tensors(), tmp, metadata={"format": CALIBRATION_FORMAT, "snr": str(self.calib.snr),
195
+ "texts": json.dumps(self.calib.texts)})
196
+ os.replace(tmp, path)
197
+ self.mu, self.cdir = self.calib.mu.to(dev), self.calib.cdir.to(dev)
198
+ return self.calib
199
+
200
+ # ------------------------------------------------------------------------------------------------ weights
201
+ def _cols(self, slots) -> torch.Tensor:
202
+ return torch.tensor([self.cfg["base_width"] + 2 * s for s in slots], dtype=torch.long)
203
+
204
+ def _slot(self, model) -> int:
205
+ cfg = self.cfg
206
+ if cfg["free"]:
207
+ return cfg["free"].pop(0)
208
+ slot = cfg["slots"]
209
+ tc = M.text_config(model)
210
+ capacity = (tc.intermediate_size - cfg["base_width"]) // 2
211
+ if slot >= capacity: # widen every layer, in steps of a quarter or 64 slots
212
+ extra = 2 * max(64, capacity // 4)
213
+ for f in self.ffns:
214
+ grow(f, extra)
215
+ tc.intermediate_size = tc.intermediate_size + extra
216
+ cfg["slots"] = slot + 1
217
+ return slot
218
+
219
+ @torch.no_grad()
220
+ def write(self, rows) -> None:
221
+ """Write the neuron pairs of these subjects (memory rows) into the learning layer: zeros when switched off."""
222
+ rows = list(rows)
223
+ if not rows:
224
+ return
225
+ mem = self.memory
226
+ idx = torch.tensor(rows, dtype=torch.long, device=mem.device)
227
+ on = mem.active()[idx]
228
+ G = mem.gate_rows(rows, self.mu, self.cdir)
229
+ V = mem.V[idx] * on[:, None]
230
+ cd = self.cdir[None, :].expand(len(rows), -1) * on[:, None]
231
+ _, (g, u, d) = dense_triple(self.ffn)
232
+ dev, dt = g.weight.device, g.weight.dtype
233
+ a = self._cols([mem.entries[i]["slot"] for i in rows]).to(dev)
234
+ g.weight[a] = G.to(dev, dt)
235
+ g.weight[a + 1] = (G - D * cd).to(dev, dt)
236
+ u.weight[a] = cd.to(dev, dt)
237
+ u.weight[a + 1] = cd.to(dev, dt)
238
+ d.weight[:, a] = (V.T / D).to(dev, dt)
239
+ d.weight[:, a + 1] = (-V.T / D).to(dev, dt)
240
+
241
+ @torch.no_grad()
242
+ def silence(self, rows) -> None:
243
+ _, (g, u, d) = dense_triple(self.ffn)
244
+ a = self._cols([self.memory.entries[i]["slot"] for i in rows]).to(d.weight.device)
245
+ d.weight[:, a] = 0
246
+ d.weight[:, a + 1] = 0
247
+
248
+ # ------------------------------------------------------------------------------------------------ learning
249
+ def _keys(self, model, tok, words) -> torch.Tensor:
250
+ """Centred inputs of the learning layer at the last token of each subject: words = [(subject, wording)]."""
251
+ prompts = [M.chat(tok, w, self.system) for _, w in words]
252
+ pos = [M.subject_last_token(tok, p, s, w) for p, (s, w) in zip(prompts, words)]
253
+ return M.ffn_inputs_at(model, tok, self.ffn, prompts, pos).to(self.memory.device) - self.mu
254
+
255
+ def _fit(self, model, tok, rows) -> Dict[int, tuple]:
256
+ mem = self.memory
257
+ rows = list(rows)
258
+ if not rows:
259
+ return {}
260
+ self.silence(rows)
261
+ items = [(mem.entries[i]["subject"],
262
+ [(w, f["answer"]) for f in mem.entries[i]["facts"]
263
+ for w in [f["question"], "Answer briefly. " + f["question"]] + list(f.get("rephrasings", []))])
264
+ for i in rows]
265
+ batch = 16
266
+ trainable = [p for p in model.parameters() if p.requires_grad] # only the value is fitted
267
+ for p in trainable:
268
+ p.requires_grad_(False)
269
+ try:
270
+ while True:
271
+ try:
272
+ V, lb, la = fit_values(model, tok, self.block, self.ffn, items, steps=self.cfg["steps"],
273
+ lr_rel=self.cfg["lr_rel"], cap_rel=self.cfg["cap_rel"], batch=batch,
274
+ system=self.system, end_ids=self.end_ids)
275
+ break
276
+ except _OOM:
277
+ if batch == 1:
278
+ raise
279
+ torch.cuda.empty_cache()
280
+ batch = max(1, batch // 2)
281
+ log.warning("out of GPU memory while fitting values; retrying %d at a time", batch)
282
+ finally:
283
+ for p in trainable:
284
+ p.requires_grad_(True)
285
+ for k, i in enumerate(rows):
286
+ mem.V[i] = V[k].to(mem.device)
287
+ return {i: (float(lb[k]), float(la[k])) for k, i in enumerate(rows)}
288
+
289
+ def learn(self, model, tok, item: Dict) -> Learned:
290
+ t0 = time.perf_counter()
291
+ q, a = str(item.get("question") or "").strip(), str(item.get("answer") or "").strip()
292
+ if not q or not a:
293
+ raise ValueError("an item needs a question and an answer (or a text)")
294
+ subj = str(item.get("subject") or "").strip() or _subject_of(model, tok, q)
295
+ reph = [str(r).strip() for r in (item.get("rephrasings") or []) if str(r).strip()]
296
+ for w in [q] + reph:
297
+ if subj.lower() not in w.lower():
298
+ raise ValueError("the subject %r must appear in every wording; it is not in %r" % (subj, w))
299
+ cal = self.calibration(model, tok)
300
+ mem, mu = self.memory, self.mu
301
+ before = mem.active().clone()
302
+ i = mem.find(subj)
303
+ if i is None:
304
+ slot = self._slot(model)
305
+ i = mem.add_entry(subj)
306
+ mem.entries[i]["slot"] = slot
307
+ fact = {"question": q, "answer": a, "rephrasings": reph}
308
+ if item.get("source"):
309
+ fact["source"] = item["source"]
310
+ mem.entries[i]["facts"].append(fact)
311
+ words = list(dict.fromkeys([q] + reph[:1]))
312
+ kc = self._keys(model, tok, [(subj, w) for w in words])
313
+ mem.T_sum[i] += kc[0]
314
+ mem.T_cnt[i] += 1
315
+ mem.W[i] = cal.solve((mem.T_sum[i] / mem.T_cnt[i])[None, :])[0]
316
+ rows = mem.add_keys(i, kc)
317
+ mem.lo[i] = (mem.own_keys(i) @ mem.W[i]).min()
318
+ mem.hi_base[i] = cal.ceiling(mem.W[i:i + 1], [subj], mu)[0].to(mem.device)
319
+ raised = mem.update_ceilings([i], rows)
320
+ active = mem.active()
321
+ losses = self._fit(model, tok, [i]) if bool(active[i]) else {}
322
+ self.write(sorted({i} | set(raised)))
323
+ lost = sorted(mem.entries[j]["subject"] for j in raised
324
+ if j < len(before) and bool(before[j]) and not bool(active[j]))
325
+ dt = time.perf_counter() - t0
326
+ self.seconds += dt
327
+ self.learned += 1
328
+ note = "" if bool(active[i]) else "switched off: cannot be told apart from %s" % self._blocker(i)
329
+ lb, la = losses.get(i, (float("nan"), float("nan")))
330
+ return Learned(subj, q, a, bool(active[i]), note, lb, la, lost, dt, item.get("source"))
331
+
332
+ def read(self, model, tok, text: str) -> List[Learned]:
333
+ sents = sentences(text)
334
+ if not sents:
335
+ return []
336
+ out = []
337
+ for s, kept in zip(sents, quiz(model, tok, sents, self.system)):
338
+ fs = to_facts(s, kept)
339
+ if not fs:
340
+ out.append(Learned("", "", "", False, "no study question passed its own check", source=s))
341
+ for f in fs:
342
+ out.append(self.learn(model, tok, f))
343
+ return out
344
+
345
+ def forget(self, model, tok, subject: str) -> bool:
346
+ mem = self.memory
347
+ i = mem.find(subject)
348
+ if i is None:
349
+ return False
350
+ self.calibration(model, tok)
351
+ _, (g, u, d) = dense_triple(self.ffn)
352
+ a = self._cols([mem.entries[i]["slot"]]).to(g.weight.device)
353
+ with torch.no_grad():
354
+ for t in (g.weight, u.weight):
355
+ t[a] = 0
356
+ t[a + 1] = 0
357
+ d.weight[:, a] = 0
358
+ d.weight[:, a + 1] = 0
359
+ self.cfg["free"].append(mem.entries[i]["slot"])
360
+ mem.remove(i)
361
+ if mem.n:
362
+ mem.recompute_ceilings()
363
+ active = mem.active()
364
+ back = [j for j in range(mem.n) if bool(active[j]) and float(mem.V[j].abs().sum()) == 0.0]
365
+ self._fit(model, tok, back)
366
+ self.write(range(mem.n))
367
+ return True
368
+
369
+ def _blocker(self, i: int) -> str:
370
+ mem = self.memory
371
+ if mem.m:
372
+ sc = mem.Kc[:mem.m] @ mem.W[i]
373
+ sc[mem.key_rows[i]] = -1e30
374
+ j = int(sc.argmax())
375
+ if sc[j] >= mem.lo[i]:
376
+ return mem.entries[int(mem.K_owner[j])]["subject"]
377
+ return "ordinary text"
378
+
379
+ def rebuild(self, model, tok) -> None:
380
+ """After a reload: the keys and thresholds again from the facts' wordings, the values from the weights."""
381
+ t0 = time.perf_counter()
382
+ cal = self.calibration(model, tok)
383
+ mem, entries = self.memory, self.cfg["subjects"]
384
+ n = len(entries)
385
+ words, owner, taught = [], [], []
386
+ for i, e in enumerate(entries):
387
+ for f in e["facts"]:
388
+ for k, w in enumerate(dict.fromkeys([f["question"]] + list(f.get("rephrasings", []))[:1])):
389
+ words.append((e["subject"], w))
390
+ owner.append(i)
391
+ taught.append(k == 0)
392
+ kc = self._keys(model, tok, words)
393
+ mem.n, mem.m = 0, 0
394
+ mem._ensure(max(n, 1), max(len(words), 1))
395
+ own = torch.tensor(owner, device=mem.device)
396
+ t = torch.tensor(taught, device=mem.device)
397
+ mem.T_sum[:n] = torch.zeros(n, self.d, device=mem.device).index_add_(0, own[t], kc[t])
398
+ mem.T_cnt[:n] = torch.bincount(own[t], minlength=n).float()
399
+ mem.W[:n] = cal.solve(mem.T_sum[:n] / mem.T_cnt[:n, None].clamp(min=1))
400
+ mem.Kc[:len(words)] = kc
401
+ mem.K_owner[:len(words)] = own
402
+ mem.n, mem.m = n, len(words)
403
+ mem.on[:n] = True
404
+ mem._reindex()
405
+ lo = torch.full((n,), 1e30, device=mem.device)
406
+ mem.lo[:n] = lo.scatter_reduce(0, own, (kc * mem.W[own]).sum(-1), reduce="amin")
407
+ mem.hi_base[:n] = cal.ceiling(mem.W[:n], [e["subject"] for e in entries], self.mu).to(mem.device)
408
+ mem.recompute_ceilings()
409
+ _, (g, u, d) = dense_triple(self.ffn)
410
+ a = self._cols([e["slot"] for e in entries]).to(d.weight.device)
411
+ mem.V[:n] = (d.weight[:, a].detach().T.float() * D).to(mem.device)
412
+ self.write(range(n))
413
+ log.info("%d subjects ready to keep learning in %.1f s", n, time.perf_counter() - t0)
414
+
415
+
416
+ def _check(ffns, tc) -> None:
417
+ act = str(getattr(tc, "hidden_act", getattr(tc, "hidden_activation", ""))).lower()
418
+ width = getattr(tc, "intermediate_size", None)
419
+ if act not in ("silu", "swish") or not isinstance(width, int):
420
+ raise NotImplementedError("sthiti writes into gated SiLU feed-forward layers of one width (Llama, Qwen, "
421
+ "Mistral and similar); this model has activation %r" % act)
422
+ for k, f in enumerate(ffns):
423
+ names, mods = dense_triple(f)
424
+ if names is None or mods[0].out_features != width:
425
+ raise NotImplementedError("sthiti writes into dense gated feed-forward layers; layer %d of this model is "
426
+ "%s" % (k, type(f).__name__))
427
+
428
+
429
+ _QUESTION_WORDS = {"who", "what", "where", "when", "which", "why", "how", "whose", "whom", "in", "on", "at", "for",
430
+ "from", "to", "by", "with", "of", "is", "was", "are", "were", "did", "does", "do", "has", "have",
431
+ "had", "name", "tell", "give", "list", "the", "a", "an"}
432
+ _JOINERS = {"van", "von", "de", "der", "den", "da", "di", "du", "del", "della", "la", "le", "of", "the", "and", "y",
433
+ "bin", "ibn", "al", "el"}
434
+
435
+
436
+ def candidate_names(question: str) -> List[str]:
437
+ """Spans of the question that look like names: capitalised words, with joining words (van, de, of...) inside."""
438
+ words = re.findall(r"[^\s?!,;:()\"\u201c\u201d]+", question)
439
+ spans, cur = [], []
440
+ for k, w in enumerate(words):
441
+ bare = w.strip(".'\u2019")
442
+ first = bare[:1]
443
+ if first.isupper() and not (k == 0 and bare.lower() in _QUESTION_WORDS):
444
+ cur.append(w)
445
+ elif cur and (bare.lower() in _JOINERS or first.isdigit()):
446
+ cur.append(w)
447
+ elif cur:
448
+ spans.append(cur)
449
+ cur = []
450
+ if cur:
451
+ spans.append(cur)
452
+ out = []
453
+ for sp in spans:
454
+ while sp and sp[-1].strip(".'\u2019").lower() in _JOINERS:
455
+ sp = sp[:-1]
456
+ while sp and sp[0].strip(".'\u2019").lower() in _JOINERS:
457
+ sp = sp[1:]
458
+ name = re.sub(r"['\u2019]s$", "", " ".join(sp)).strip(".")
459
+ if name and name.lower() in question.lower():
460
+ out.append(name)
461
+ return out
462
+
463
+
464
+ def _clean_name(text: str) -> str:
465
+ text = text.strip().split("\n")[0]
466
+ text = re.sub(r"^(?:name|subject|answer)\s*:\s*", "", text, flags=re.IGNORECASE)
467
+ text = re.sub(r"[*_`\"\u201c\u201d\u2018]", "", text)
468
+ return text.strip().strip("'\u2019.?!:;, ")
469
+
470
+
471
+ def _subject_of(model, tok, question: str) -> str:
472
+ """The name the question is about: the model is asked; its reply is matched to a name in the question."""
473
+ p = M.chat(tok, "Which name or title is this question about? Reply with only that name, exactly as written in "
474
+ "the question.\n\nQuestion: %s" % question, system=None)
475
+ out = _clean_name(M.generate(model, tok, [p], 24)[0])
476
+ low = question.lower()
477
+ cands = candidate_names(question)
478
+ if out and out.lower() in low:
479
+ inside = [c for c in cands if c.lower() in out.lower()]
480
+ if inside: # "the novel Salt Roads" -> "Salt Roads", one name per subject
481
+ return max(inside, key=len)
482
+ if not cands or any(ch.isupper() or ch.isdigit() for ch in out):
483
+ i = low.find(out.lower())
484
+ return question[i:i + len(out)]
485
+ hit = [c for c in cands if out and (c.lower() in out.lower() or out.lower() in c.lower())]
486
+ if hit or cands:
487
+ return max(hit or cands, key=len)
488
+ raise ValueError("could not tell what %r is about; add \"subject\" to the item" % question)
489
+
490
+
491
+ def _digest(texts) -> str:
492
+ return hashlib.sha1("\n\0".join(texts).encode()).hexdigest()
493
+
494
+
495
+ def _fingerprint(model, layer: int) -> str:
496
+ """A few weights the learning layer's input depends on, so a cached calibration is never used for another model."""
497
+ emb = model.get_input_embeddings().weight
498
+ blk = M.decoder_layers(model)[max(0, layer - 1)]
499
+ p = next(blk.parameters())
500
+ sample = torch.cat([emb[:4, :16].detach().flatten().float().cpu(), p.detach().flatten()[:64].float().cpu()])
501
+ return hashlib.sha1(sample.numpy().tobytes()).hexdigest()[:16]