memory: search by meaning, on a small model on this computer
A memory search now finds what means the same in other words or another
language ("什么时候上线" finds "Releases go out on Tuesdays"), for the
MCP server's memory_search and the Library's Memory tab alike. It is off
until switched on under Memory → Search by meaning, since it downloads
paraphrase-multilingual-MiniLM-L12-v2 (Xenova's int8 ONNX, ~135 MB,
pinned revision, size and sha256 checked); switched off, the model is
deleted.
- internal/pii/guard: the BERT code runs the embedder too (LoadEmbedder,
mean pooling; the tokenizer reads 250,002 pieces and WhitespaceSplit).
Its vectors match ONNX Runtime's int8 to cosine >= 0.995 and are no
further from fp32 than ORT's own; testdata carries both.
- internal/memembed: the switch, the download, vectors.bin keyed by each
memory's sha256 (read once, again when the text changes, a cut-short
file read as none), Keep reading in the backend, the model let go after
10 minutes unused.
- internal/memory: memory.Semantic fuses the meaning ranking with the word
ranking by reciprocal rank; a tie goes to the nearer in meaning, since
a first word hit may hold one common word ("when do we release" had
"Never delete images when..." first). Near 0.30 / Within 0.15 come from
97 real memories and 16 queries, half Chinese for English memories:
12 of 16 sought found with ~4 others each. Rank searches without noting
memories used.
- GUI: the Search by meaning row (download %, memories read, failures),
and the tab's search lists what the backend ranked first
(POST /api/memory/rank), then word matches. zh, zh-TW, ja, de.
- docs/subsystems/memory.md: the section, out of "Not built yet".
Why not multilingual-e5-small, which this was built on first: run for
real, its cosines sat at 0.78-0.89 for everything, and a Chinese search
ranked Chinese memories over the English one it meant. e5-small, e5-base
and MiniLM were compared in ONNX Runtime on the same 97 memories; MiniLM
put the sought one first 9 of 16 and in the top 3 12 of 16, with the
rest at a median cosine of 0.16.
Run before the rebases (mote, on origin/main as of the work):
- gofmt -l internal/ clean; go vet of memembed, memory, pii/..., gui,
library; GOOS=linux and GOOS=windows vet of memembed and pii/guard.
- MAGPIE_EMBED_DIR=~/models/pml go test -run Embedder ./internal/pii/guard:
7 texts (CJK, full width, emoji, digits before runs of spaces) at
0.9962-1.0000 with ORT int8.
- go test memembed, memory, memdistill, pii/..., library, browsermcp.
- Linux (magpie-desktop, -tags nogui, mote's disk was full): go test
memembed, memory, pii/guard, gui (461s), cli (1228s, past the default
10m timeout, so -timeout 30m); gateway -run 'MemoryMCP|OwnMCP'.
- Rebased on origin/main 3ebb1ba2c, on mote at this tree: gofmt -l
internal/ clean; go vet of memembed, memory, pii/..., library, gui,
gateway, and GOOS=linux and GOOS=windows vet of the first four; go
test memembed, memory, pii/..., library, browsermcp (Embedder test on
~/models/pml); gateway -run 'MemoryMCP|OwnMCP'; cli -run
'Settings|Parity|Budget'.
- Rebased again on origin/main 5d6935b11 (title bar, cli parity,
account export, provider catalog): go vet of gui and cli; go test -run
'Settings|Parity|Budget' of cli and gui, ok with the Bark test fix two
commits up (TestSettingsSaveKeepsWhatItDoesNotSend, red on main).
- GUI on mote, this commit plus the next (90f4a377b, which fixes
library-bar-more for #5982): every library-*.test.cjs, i18n-keys and
i18n-en-no-cjk, BROWSER=chromium and webkit, 701/702 each. The red is
library-loading's tab list, which has no "Claude plugins" (6af54dc9a)
and is red alone at origin/main faffb1e95 (#5997). library-bili's
webkit saved count times out about 1 run in 3, on main too (#6015).
- A real switch-on: the pinned files downloaded from Hugging Face and
checked in 11s, 5 memories read; 什么时候上线, 端口被占用怎么办, 清理磁盘,
回复用什么语言 and "when do we release" each find their memory first.
缩进用什么 finds nothing (0.23 to the tabs memory, under Near).
- Broken by hand: without the tie rule, TestSearchFindsByMeaning's new
case is red (images first).
Not run: the whole Go suite and the whole GUI suite; go test of
internal/gui and the whole of internal/cli after the rebases (WSL kept
restarting, and they passed on Linux before).
This commit is contained in:
@@ -210,15 +210,54 @@ off until switched on under Memory → Tidy up every night.
|
||||
and `POST /api/memory/dream/undo`; `GET /api/memory/distill` carries
|
||||
`dreaming`.
|
||||
|
||||
## Not built yet
|
||||
### Search by meaning
|
||||
|
||||
Semantic search is planned; today search is by words (`Search`, CJK
|
||||
split per character, `TestSearch`).
|
||||
[internal/memembed](../../internal/memembed/memembed.go) ranks a search by
|
||||
what it means as well as by its words, so "什么时候上线" finds "Releases go
|
||||
out on Tuesdays". It is off until switched on under Memory → Search by
|
||||
meaning, since it downloads a model (~135 MB).
|
||||
|
||||
- The model is paraphrase-multilingual-MiniLM-L12-v2, Xenova's int8 ONNX
|
||||
at a pinned revision, fetched from Hugging Face with each file's size
|
||||
and sha256 checked (`pii.Fetch`) into
|
||||
`<cache>/paraphrase-multilingual-MiniLM-L12-v2/<rev>`. It
|
||||
runs in Go on the PII guard's BERT code (`guard.LoadEmbedder`); nothing
|
||||
leaves the computer. Its vectors match ONNX Runtime's to cosine 0.995
|
||||
and are no further from fp32 than ONNX Runtime's own
|
||||
(`TestEmbedderMatchesONNXRuntime`). A search and a memory are read the
|
||||
same way, with no prefix. multilingual-e5-small was tried first: its
|
||||
cosines sat in 0.78 to 0.89 for everything, and a Chinese search ranked
|
||||
Chinese memories over the English one it meant.
|
||||
- Switched off, the model folder is deleted (`Set`). The switch is
|
||||
`memory-semantic.json` in the config folder; one that can't be read is
|
||||
off (`TestNotThereIsWords`).
|
||||
- What is read: each active or candidate memory's text and why, as an
|
||||
one text, keyed by its sha256 in `vectors.bin` beside the model, once,
|
||||
and again when its text changes; vectors of texts gone are dropped
|
||||
(`TestIndexReadsOnce`). `Keep` reads them in the backend each minute and
|
||||
on a nudge (`Poke`); a search reads up to 16 missing ones itself, and
|
||||
with none read yet it is by words while Keep reads. The model is let go
|
||||
after 10 minutes unused.
|
||||
- Ranking (`memory.Semantic`, `fuse` in
|
||||
[search.go](../../internal/memory/search.go)): the memories whose
|
||||
cosine with the query passes `Near` (0.30) and is within `Within` (0.15)
|
||||
of the best are fused with the word hits by reciprocal rank (`rrfK` 20),
|
||||
pinned ×1.2 and non-global ×1.1. Calibrated on 97 real memories and 16
|
||||
queries, half in Chinese for English memories: the one sought scored a
|
||||
median 0.47, the rest a median 0.16; 12 of 16 found with ~4 others each
|
||||
(`TestSearchFindsByMeaning`).
|
||||
- Every search goes through it: the MCP server's `memory_search` and the
|
||||
Memory tab, which asks `POST /api/memory/rank` `{q, status}` (ids, best
|
||||
first, not noted as used; null while off) and lists what it ranked
|
||||
first, then what holds the words. `GET`/`POST /api/memory/semantic`
|
||||
`{on}` give the row its state: the download's progress, the memories
|
||||
read, and why either failed.
|
||||
|
||||
## Verification
|
||||
|
||||
```sh
|
||||
mote-run go test ./internal/memory ./internal/memdistill ./internal/library
|
||||
mote-run go test ./internal/memory ./internal/memdistill ./internal/memembed ./internal/library
|
||||
mote-run sh -c 'MAGPIE_EMBED_DIR=$HOME/models/pml go test -run Embedder ./internal/pii/guard'
|
||||
mote-run go test -run 'Distill|Dream' ./internal/gui
|
||||
mote-run go test -tags nogui -run 'MemoryMCP|OwnMCP' ./internal/gateway
|
||||
mote-run go test ./internal/browsermcp ./internal/cli
|
||||
|
||||
@@ -402,6 +402,9 @@ var notYet = map[string]string{
|
||||
"POST /api/memory/dream": L, // memory_distill.go
|
||||
"POST /api/memory/dream/run": L, // memory_distill.go
|
||||
"POST /api/memory/dream/undo": L, // memory_distill.go
|
||||
"GET /api/memory/semantic": L, // memory_semantic.go
|
||||
"POST /api/memory/semantic": L, // memory_semantic.go
|
||||
"POST /api/memory/rank": L, // memory_semantic.go
|
||||
"POST /api/library/skills/regroup": W, // library.go
|
||||
"GET /api/omarchy/widget": W, // omarchy.go
|
||||
"POST /api/omarchy/widget": W, // omarchy.go
|
||||
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
// search by meaning, when switched on (memory.Semantic)
|
||||
_ "github.com/yetone/magpie/internal/memembed"
|
||||
"github.com/yetone/magpie/internal/memory"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
@@ -607,6 +607,8 @@ func Run(version string, showMain bool, link string) error {
|
||||
}()
|
||||
// conversations read into memory, when switched on (Memory tab)
|
||||
go keepDistilling(backendCtx)
|
||||
// memories read for search by meaning, when switched on
|
||||
go keepEmbedding(backendCtx)
|
||||
|
||||
// before the item is made, which starts as hidden as AppKit kept it
|
||||
hiddenAtStart := bringTrayBack()
|
||||
|
||||
@@ -959,6 +959,10 @@ magpie.plugin("library", (ctx) => {
|
||||
let mem = null; // /api/memory
|
||||
let dist = null; // /api/memory/distill: conversations read into memory
|
||||
let distPoll = 0;
|
||||
let sem = null; // /api/memory/semantic: search by meaning (memembed)
|
||||
let semPoll = 0;
|
||||
let memRank = null; // {q, status, ids}: the search's ranking by meaning, best first
|
||||
let rankT = 0;
|
||||
let memLoading = false;
|
||||
let memQ = ""; // the search typed
|
||||
let memStatus = "active";
|
||||
@@ -988,13 +992,15 @@ magpie.plugin("library", (ctx) => {
|
||||
if (memLoading) return;
|
||||
memLoading = true;
|
||||
try {
|
||||
[mem, dist] = await Promise.all([api("memory"), api("memory/distill").catch(() => null)]);
|
||||
[mem, dist, sem] = await Promise.all([api("memory"), api("memory/distill").catch(() => null), api("memory/semantic").catch(() => null)]);
|
||||
} catch (e) {
|
||||
status(e.message, "err");
|
||||
}
|
||||
memLoading = false;
|
||||
if (tab === "memory" && mem) render();
|
||||
distWatch();
|
||||
semWatch();
|
||||
rankSoon();
|
||||
}
|
||||
function memDirty() {
|
||||
if (!memOpen || !memDraft) return false;
|
||||
@@ -1069,6 +1075,7 @@ magpie.plugin("library", (ctx) => {
|
||||
row.append(glyph(GLYPH.doc), who, sw);
|
||||
card.append(row);
|
||||
if (dist) card.append(distillRow(), dreamRow());
|
||||
if (sem) card.append(semRow());
|
||||
if (!lib.servers.some((s) => s.name === "magpie-memory")) {
|
||||
const r = el("div", "row lib-row lib-memtools");
|
||||
const w = el("div", "who");
|
||||
@@ -1085,21 +1092,25 @@ magpie.plugin("library", (ctx) => {
|
||||
q.type = "search";
|
||||
q.className = "lib-memq";
|
||||
q.dataset.lib = "memq";
|
||||
q.oninput = () => { memQ = q.value; render(); };
|
||||
q.oninput = () => { memQ = q.value; render(); rankSoon(); };
|
||||
q.onkeydown = (e) => e.stopPropagation();
|
||||
const sugg = count("candidate");
|
||||
const st = segs([
|
||||
["active", t("In use") + (count("active") ? " · " + count("active") : "")],
|
||||
...(sugg || memStatus === "candidate" ? [["candidate", t("To review") + (sugg ? " · " + sugg : "")]] : []),
|
||||
["archived", t("Archived") + (count("archived") ? " · " + count("archived") : "")],
|
||||
], memStatus, (v) => { memStatus = v; memOpen = null; render(); });
|
||||
], memStatus, (v) => { memStatus = v; memOpen = null; render(); rankSoon(); });
|
||||
st.classList.add("lib-memstatus");
|
||||
const sc = menuButton(memScope ? scopeName(memScope) : t("All"), "lib-memscope", () => openProtoMenu(sc, [{ v: "", name: t("Everywhere and every project"), literalName: true, note: "" }, ...memScopes(true).filter((s) => all.some((m) => m.scope === s)).map((s) => ({ v: s, name: scopeName(s), literalName: true, note: "" }))], memScope, (v) => { memScope = v; render(); }, "Where it applies"));
|
||||
const words = memQ.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
||||
// with search by meaning on, what it ranked comes first, best first,
|
||||
// then what holds the words typed and it didn't rank
|
||||
const ranked = memRank && memRank.q === memQ && memRank.status === memStatus ? memRank.ids : [];
|
||||
const at = new Map(ranked.map((id, i) => [id, i]));
|
||||
const shown = all.filter((m) => (memStatus === "archived" ? m.status === "archived" || m.status === "superseded" : m.status === memStatus)
|
||||
&& (!memScope || m.scope === memScope)
|
||||
&& words.every((w) => [m.text, m.why || "", ...(m.tags || []), kindName(m.kind), scopeName(m.scope)].join(" ").toLowerCase().includes(w)))
|
||||
.sort((a, b) => (!!b.pinned - !!a.pinned) || (b.updated > a.updated ? 1 : b.updated < a.updated ? -1 : 0));
|
||||
&& (at.has(m.id) || words.every((w) => [m.text, m.why || "", ...(m.tags || []), kindName(m.kind), scopeName(m.scope)].join(" ").toLowerCase().includes(w))))
|
||||
.sort((a, b) => (at.has(b.id) - at.has(a.id)) || (at.get(a.id) - at.get(b.id)) || (!!b.pinned - !!a.pinned) || (b.updated > a.updated ? 1 : b.updated < a.updated ? -1 : 0));
|
||||
// what's picked is what's listed: a search, a filter or another
|
||||
// status leaves the rest unpicked, and an empty list ends Select
|
||||
memShown = shown;
|
||||
@@ -1325,6 +1336,67 @@ magpie.plugin("library", (ctx) => {
|
||||
r.append(glyph(GLYPH.backup), w, acts);
|
||||
return r;
|
||||
}
|
||||
// Search by meaning (memembed): a small model on this computer reads
|
||||
// each memory once, and the search finds what means the same in other
|
||||
// words or another language. Switched off, the model is deleted.
|
||||
function semRow() {
|
||||
const s = sem;
|
||||
const r = el("div", "row lib-row lib-memsem");
|
||||
const w = el("div", "who");
|
||||
w.append(el("div", "name", t("Search by meaning")));
|
||||
let line = t("Finds memories that mean what you search for, in any language. Downloads a {size} model that runs on this computer.", { size: Math.round(s.size / 1e6) + " MB" });
|
||||
let err = false;
|
||||
if (s.on && s.downloading) line = t("Downloading the model · {p}%", { p: Math.floor(100 * s.done / (s.size || 1)) });
|
||||
else if (s.on && s.error && !s.installed) { line = t("Couldn't download the model: {error}", { error: s.error }); err = true; }
|
||||
else if (s.on && s.failed) { line = t("Couldn't read the memories: {error}", { error: s.failed }); err = true; }
|
||||
else if (s.on && s.installed && s.read < s.of) line = t("Reading the memories · {n} of {m}", { n: s.read, m: s.of });
|
||||
else if (s.on && s.installed) line = t("Finds memories that mean what you search for, in any language, on this computer.");
|
||||
w.append(el("div", "sub" + (err ? " err" : ""), line));
|
||||
const acts = el("div", "lib-acts");
|
||||
if (s.on && s.error && !s.installed && !s.downloading) acts.append(button(t("Try again"), "action lib-semretry", () => semChange(true)));
|
||||
acts.append(toggle(s.on, t("Search by meaning"), (on) => semChange(on)));
|
||||
r.append(glyph(GLYPH.search), w, acts);
|
||||
return r;
|
||||
}
|
||||
async function semChange(on) {
|
||||
try {
|
||||
sem = await api("memory/semantic", { on });
|
||||
} catch (e) {
|
||||
status(e.message, "err", 6000);
|
||||
}
|
||||
memRank = null;
|
||||
render();
|
||||
semWatch();
|
||||
rankSoon();
|
||||
}
|
||||
// while the model downloads or the memories are read, the row is read
|
||||
// again every 2s
|
||||
function semWatch() {
|
||||
clearTimeout(semPoll);
|
||||
const s = sem;
|
||||
if (!s?.on || !(s.downloading || s.reading || (s.installed && s.read < s.of && !s.failed))) return;
|
||||
semPoll = setTimeout(async () => {
|
||||
if (tab !== "memory") return;
|
||||
const was = s.installed;
|
||||
try { sem = await api("memory/semantic"); } catch {}
|
||||
render();
|
||||
semWatch();
|
||||
if (!was && sem.installed) rankSoon();
|
||||
}, 2000);
|
||||
}
|
||||
// the search, ranked by meaning a moment after the typing stops
|
||||
function rankSoon() {
|
||||
clearTimeout(rankT);
|
||||
if (!sem?.on || !sem.installed || !memQ.trim()) { memRank = null; return; }
|
||||
rankT = setTimeout(async () => {
|
||||
const q = memQ, st = memStatus;
|
||||
let r;
|
||||
try { r = await api("memory/rank", { q, status: st }); } catch { return; }
|
||||
if (q !== memQ || st !== memStatus || tab !== "memory") return;
|
||||
memRank = r.ids ? { q, status: st, ids: r.ids } : null;
|
||||
render();
|
||||
}, 250);
|
||||
}
|
||||
async function distChange(path, body, reload) {
|
||||
try {
|
||||
dist = await api(path, body);
|
||||
|
||||
@@ -30,6 +30,13 @@ magpie.strings({
|
||||
"Merges memories that repeat and sets aside ones out of date. What you wrote or pinned stays.": "合并重复的记忆,归档过时的记忆。你写的和置顶的保持不变。",
|
||||
"Tidying…": "正在整理…",
|
||||
"Couldn't tidy: {error}": "未能整理:{error}",
|
||||
"Search by meaning": "按意思搜索",
|
||||
"Finds memories that mean what you search for, in any language. Downloads a {size} model that runs on this computer.": "按意思找到相关的记忆,不限语言。会下载一个 {size} 的模型,在这台电脑上运行。",
|
||||
"Downloading the model · {p}%": "正在下载模型 · {p}%",
|
||||
"Couldn't download the model: {error}": "未能下载模型:{error}",
|
||||
"Couldn't read the memories: {error}": "未能读取记忆:{error}",
|
||||
"Reading the memories · {n} of {m}": "正在读取记忆 · {n}/{m}",
|
||||
"Finds memories that mean what you search for, in any language, on this computer.": "按意思找到相关的记忆,不限语言,在这台电脑上运行。",
|
||||
"Tidied {when} · undone": "{when}整理过 · 已撤销",
|
||||
"Tidied {when} · {m} merged, {a} set aside": "{when}整理过 · 合并 {m} 条,归档 {a} 条",
|
||||
"Nothing to tidy {when}": "{when}没有需要整理的",
|
||||
@@ -986,6 +993,13 @@ magpie.strings({
|
||||
"Merges memories that repeat and sets aside ones out of date. What you wrote or pinned stays.": "合併重複的記憶,封存過時的記憶。你寫的和釘選的保持不變。",
|
||||
"Tidying…": "正在整理…",
|
||||
"Couldn't tidy: {error}": "未能整理:{error}",
|
||||
"Search by meaning": "依意思搜尋",
|
||||
"Finds memories that mean what you search for, in any language. Downloads a {size} model that runs on this computer.": "依意思找到相關的記憶,不限語言。會下載一個 {size} 的模型,在這台電腦上執行。",
|
||||
"Downloading the model · {p}%": "正在下載模型 · {p}%",
|
||||
"Couldn't download the model: {error}": "無法下載模型:{error}",
|
||||
"Couldn't read the memories: {error}": "無法讀取記憶:{error}",
|
||||
"Reading the memories · {n} of {m}": "正在讀取記憶 · {n}/{m}",
|
||||
"Finds memories that mean what you search for, in any language, on this computer.": "依意思找到相關的記憶,不限語言,在這台電腦上執行。",
|
||||
"Tidied {when} · undone": "{when}整理過 · 已復原",
|
||||
"Tidied {when} · {m} merged, {a} set aside": "{when}整理過 · 合併 {m} 則,封存 {a} 則",
|
||||
"Nothing to tidy {when}": "{when}沒有需要整理的",
|
||||
@@ -1942,6 +1956,13 @@ magpie.strings({
|
||||
"Merges memories that repeat and sets aside ones out of date. What you wrote or pinned stays.": "重複したメモリーをまとめ、古くなったものをアーカイブします。自分で書いたものとピン留めしたものはそのままです。",
|
||||
"Tidying…": "整理中…",
|
||||
"Couldn't tidy: {error}": "整理できませんでした:{error}",
|
||||
"Search by meaning": "意味で検索",
|
||||
"Finds memories that mean what you search for, in any language. Downloads a {size} model that runs on this computer.": "意味の近いメモリーを言語を問わず見つけます。このコンピュータで動く {size} のモデルをダウンロードします。",
|
||||
"Downloading the model · {p}%": "モデルをダウンロード中 · {p}%",
|
||||
"Couldn't download the model: {error}": "モデルをダウンロードできませんでした:{error}",
|
||||
"Couldn't read the memories: {error}": "メモリーを読み込めませんでした:{error}",
|
||||
"Reading the memories · {n} of {m}": "メモリーを読み込み中 · {n}/{m}",
|
||||
"Finds memories that mean what you search for, in any language, on this computer.": "意味の近いメモリーを言語を問わず、このコンピュータ上で見つけます。",
|
||||
"Tidied {when} · undone": "{when}に整理 · 取り消し済み",
|
||||
"Tidied {when} · {m} merged, {a} set aside": "{when}に整理 · {m} 件をまとめ、{a} 件をアーカイブ",
|
||||
"Nothing to tidy {when}": "{when}:整理するものなし",
|
||||
@@ -2898,6 +2919,13 @@ magpie.strings({
|
||||
"Merges memories that repeat and sets aside ones out of date. What you wrote or pinned stays.": "Führt doppelte Erinnerungen zusammen und archiviert veraltete. Was du geschrieben oder angeheftet hast, bleibt.",
|
||||
"Tidying…": "Wird aufgeräumt…",
|
||||
"Couldn't tidy: {error}": "Aufräumen fehlgeschlagen: {error}",
|
||||
"Search by meaning": "Nach Bedeutung suchen",
|
||||
"Finds memories that mean what you search for, in any language. Downloads a {size} model that runs on this computer.": "Findet Erinnerungen, die meinen, wonach du suchst, in jeder Sprache. Lädt ein {size} großes Modell, das auf diesem Computer läuft.",
|
||||
"Downloading the model · {p}%": "Modell wird geladen · {p} %",
|
||||
"Couldn't download the model: {error}": "Modell konnte nicht geladen werden: {error}",
|
||||
"Couldn't read the memories: {error}": "Erinnerungen konnten nicht gelesen werden: {error}",
|
||||
"Reading the memories · {n} of {m}": "Erinnerungen werden gelesen · {n} von {m}",
|
||||
"Finds memories that mean what you search for, in any language, on this computer.": "Findet Erinnerungen, die meinen, wonach du suchst, in jeder Sprache, auf diesem Computer.",
|
||||
"Tidied {when} · undone": "{when} aufgeräumt · rückgängig gemacht",
|
||||
"Tidied {when} · {m} merged, {a} set aside": "{when} aufgeräumt · {m} zusammengeführt, {a} archiviert",
|
||||
"Nothing to tidy {when}": "{when} nichts aufzuräumen",
|
||||
|
||||
@@ -177,6 +177,7 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
|
||||
browserRoutes(mux, w)
|
||||
memoryRoutes(mux)
|
||||
memoryDistillRoutes(mux)
|
||||
memorySemanticRoutes(mux)
|
||||
mux.HandleFunc("GET /api/library", func(rw http.ResponseWriter, r *http.Request) {
|
||||
v, err := libraryRead(nil, r.URL.Query().Get("glance") == "1")
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/memembed"
|
||||
"github.com/yetone/magpie/internal/memory"
|
||||
)
|
||||
|
||||
// keepEmbedding reads new memories for search by meaning while the
|
||||
// backend runs, when it is switched on (memembed.Keep).
|
||||
func keepEmbedding(ctx context.Context) { memembed.Keep(ctx, time.Minute) }
|
||||
|
||||
func memorySemanticRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/memory/semantic", func(rw http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(rw, memembed.Now())
|
||||
})
|
||||
// {on}: switched on, the model is fetched when it isn't on disk;
|
||||
// switched off, it is deleted
|
||||
mux.HandleFunc("POST /api/memory/semantic", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
On bool `json:"on"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
if err := memembed.Set(in.On); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, memembed.Now())
|
||||
})
|
||||
// {q, status}: the Memory tab's search, as an agent's: the ids found,
|
||||
// best first, without noting them as used. None when search by
|
||||
// meaning is off: the tab filters by words itself.
|
||||
mux.HandleFunc("POST /api/memory/rank", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Q string `json:"q"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
out := struct {
|
||||
IDs []string `json:"ids"`
|
||||
}{}
|
||||
if strings.TrimSpace(in.Q) == "" || !memembed.On() {
|
||||
writeJSON(rw, out)
|
||||
return
|
||||
}
|
||||
statuses := []string{in.Status}
|
||||
if in.Status == memory.Archived {
|
||||
statuses = append(statuses, memory.Superseded)
|
||||
}
|
||||
out.IDs = []string{}
|
||||
for _, st := range statuses {
|
||||
hits, err := memory.Rank(memory.Query{Text: in.Q, Status: st, Limit: 200})
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
for _, h := range hits {
|
||||
out.IDs = append(out.IDs, h.ID)
|
||||
}
|
||||
}
|
||||
writeJSON(rw, out)
|
||||
})
|
||||
}
|
||||
@@ -7,7 +7,9 @@
|
||||
// a <select>), kept and deleted. Conversations read into memory: switched
|
||||
// on, a model picked through the app's menu, read now, and a run that
|
||||
// stopped says why. The nightly tidy: switched on, with the model picked
|
||||
// on its row while conversations aren't read, tidied now and undone. Every language, wide and narrow, Chromium
|
||||
// on its row while conversations aren't read, tidied now and undone.
|
||||
// Search by meaning: switched on, the download and the read shown, and a
|
||||
// search ranked by the backend; off, by words alone. Every language, wide and narrow, Chromium
|
||||
// and WebKit; no backend, the API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
@@ -45,7 +47,13 @@ function distill() {
|
||||
};
|
||||
}
|
||||
|
||||
function server(lang, state, sent, dist) {
|
||||
// search by meaning, off: switched on, the model downloads, then the
|
||||
// memories are read, one poll a step
|
||||
function semantic() {
|
||||
return { on: false, installed: false, size: 135137323, downloading: false, done: 0, read: 0, of: 0, reading: false, gets: 0 };
|
||||
}
|
||||
|
||||
function server(lang, state, sent, dist, sem) {
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
@@ -66,6 +74,22 @@ function server(lang, state, sent, dist) {
|
||||
else if (url.pathname === "/api/memory/dream/undo") { dist.undone = true; if (m9) m9.status = "candidate"; }
|
||||
return route.fulfill({ json: dist });
|
||||
}
|
||||
if (url.pathname === "/api/memory/semantic") {
|
||||
if (route.request().method() === "POST") {
|
||||
const body = route.request().postDataJSON();
|
||||
sent.push({ path: url.pathname, body });
|
||||
Object.assign(sem, body.on ? { on: true, downloading: true, done: 0, gets: 0 } : semantic());
|
||||
} else if (sem.on && ++sem.gets === 1) Object.assign(sem, { downloading: false, done: sem.size, installed: true, reading: true, read: 1, of: 3 });
|
||||
else if (sem.on) Object.assign(sem, { reading: false, read: 3 });
|
||||
return route.fulfill({ json: sem });
|
||||
}
|
||||
if (url.pathname === "/api/memory/rank") {
|
||||
const body = route.request().postDataJSON();
|
||||
sent.push({ path: url.pathname, body });
|
||||
// "package manager" means the pnpm rule more than the pinned one
|
||||
const ids = !sem.on ? null : body.q === "package manager" && body.status === "active" ? ["m1", "m2"] : [];
|
||||
return route.fulfill({ json: { ids } });
|
||||
}
|
||||
if (url.pathname.startsWith("/api/memory/distill")) {
|
||||
if (route.request().method() === "GET" && dist.dreaming && ++dist.dgets > 1) {
|
||||
// the tidy ends: it set aside the one read in, unreviewed
|
||||
@@ -111,11 +135,11 @@ function server(lang, state, sent, dist) {
|
||||
|
||||
const view = "#view-library";
|
||||
const words = {
|
||||
en: { tab: "Memory", review: "To review", rule: "Rule", fact: "Fact", learn: "Learn from conversations", now: "Read now", tidy: "Tidy up every night" },
|
||||
zh: { tab: "记忆", review: "待确认", rule: "规则", fact: "事实", learn: "从对话中学习", now: "立即读取", tidy: "每晚整理" },
|
||||
"zh-TW": { tab: "記憶", review: "待確認", rule: "規則", fact: "事實", learn: "從對話中學習", now: "立即讀取", tidy: "每晚整理" },
|
||||
ja: { tab: "メモリ", review: "確認待ち", rule: "ルール", fact: "事実", learn: "会話から学ぶ", now: "今すぐ読む", tidy: "毎晩整理する" },
|
||||
de: { tab: "Memory", review: "Zu prüfen", rule: "Regel", fact: "Fakt", learn: "Aus Unterhaltungen lernen", now: "Jetzt lesen", tidy: "Jede Nacht aufräumen" },
|
||||
en: { tab: "Memory", review: "To review", rule: "Rule", fact: "Fact", learn: "Learn from conversations", now: "Read now", tidy: "Tidy up every night", sem: "Search by meaning" },
|
||||
zh: { tab: "记忆", review: "待确认", rule: "规则", fact: "事实", learn: "从对话中学习", now: "立即读取", tidy: "每晚整理", sem: "按意思搜索" },
|
||||
"zh-TW": { tab: "記憶", review: "待確認", rule: "規則", fact: "事實", learn: "從對話中學習", now: "立即讀取", tidy: "每晚整理", sem: "依意思搜尋" },
|
||||
ja: { tab: "メモリ", review: "確認待ち", rule: "ルール", fact: "事実", learn: "会話から学ぶ", now: "今すぐ読む", tidy: "毎晩整理する", sem: "意味で検索" },
|
||||
de: { tab: "Memory", review: "Zu prüfen", rule: "Regel", fact: "Fakt", learn: "Aus Unterhaltungen lernen", now: "Jetzt lesen", tidy: "Jede Nacht aufräumen", sem: "Nach Bedeutung suchen" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
@@ -139,7 +163,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const sent = [];
|
||||
const state = memories();
|
||||
const dist = distill();
|
||||
await page.route("**/*", server(lang, state, sent, dist));
|
||||
const sem = semantic();
|
||||
await page.route("**/*", server(lang, state, sent, dist, sem));
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.locator('button[data-view="library"]').click();
|
||||
const rows = page.locator(`${view} .lib-mems .lib-mem`);
|
||||
@@ -196,6 +221,45 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.locator(`${view} input.lib-memq`).fill("");
|
||||
await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 2);
|
||||
|
||||
// search by meaning: off, it says what it downloads, and a search
|
||||
// is by words alone
|
||||
const srow = page.locator(`${view} .lib-memsem`);
|
||||
assert.match(await srow.locator(".name").textContent(), new RegExp(w.sem));
|
||||
assert.equal(await srow.locator("button.lib-switch").getAttribute("aria-checked"), "false");
|
||||
assert.match(await srow.locator(".sub").textContent(), /135 MB/);
|
||||
await page.locator(`${view} input.lib-memq`).fill("package manager");
|
||||
await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 0);
|
||||
await page.locator(`${view} input.lib-memq`).fill("");
|
||||
await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 2);
|
||||
assert.equal(sent.filter((x) => x.path === "/api/memory/rank").length, 0, "ranked while off");
|
||||
// on: the download's progress, then the memories read
|
||||
await srow.locator("button.lib-switch").click();
|
||||
await srow.locator(".sub", { hasText: /0\s?%/ }).waitFor();
|
||||
assert.deepEqual(sent.findLast((x) => x.path === "/api/memory/semantic").body, { on: true });
|
||||
await srow.locator(".sub", { hasText: /1\D+3/ }).waitFor({ timeout: 8000 });
|
||||
await page.waitForFunction(() => !/\d/.test(document.querySelector("#view-library .lib-memsem .sub")?.textContent || "9"), null, { timeout: 8000 });
|
||||
{
|
||||
const card = await page.locator(`${view} .lib-memcard`).boundingBox();
|
||||
for (const b of await srow.locator(".lib-acts > *").all()) {
|
||||
const r = await b.boundingBox();
|
||||
assert.ok(r.x + r.width <= card.x + card.width + 1, "a control of the meaning row is cut off");
|
||||
}
|
||||
}
|
||||
// a search finds what holds none of its words, best first, the
|
||||
// pinned one too
|
||||
await page.locator(`${view} input.lib-memq`).fill("package manager");
|
||||
await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 2);
|
||||
assert.match(await rows.nth(0).textContent(), /Use pnpm/);
|
||||
assert.match(await rows.nth(1).textContent(), /Answers in Chinese/);
|
||||
assert.deepEqual(sent.findLast((x) => x.path === "/api/memory/rank").body, { q: "package manager", status: "active" });
|
||||
await page.locator(`${view} input.lib-memq`).fill("");
|
||||
await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 2);
|
||||
assert.match(await rows.nth(0).textContent(), /Answers in Chinese/);
|
||||
// off again: the model is deleted, and the row says what it would download
|
||||
await srow.locator("button.lib-switch").click();
|
||||
await srow.locator(".sub", { hasText: /135 MB/ }).waitFor();
|
||||
assert.deepEqual(sent.findLast((x) => x.path === "/api/memory/semantic").body, { on: false });
|
||||
|
||||
if (width === 980) {
|
||||
// edited: the kind through the app's menu
|
||||
await rows.nth(1).click();
|
||||
|
||||
@@ -0,0 +1,495 @@
|
||||
// Package memembed is memory's search by meaning:
|
||||
// paraphrase-multilingual-MiniLM-L12-v2 (sentence-transformers, Apache
|
||||
// 2.0; Xenova's int8 ONNX of it), run in magpie's own process by
|
||||
// internal/pii/guard, gives each memory a place in a space where texts
|
||||
// that say the same are near, in any of 50 languages and across them,
|
||||
// and memory.Search
|
||||
// fuses how near each is to what was searched with its word ranking
|
||||
// (memory.Semantic).
|
||||
//
|
||||
// It is off until switched on, since the model is a 135 MB download.
|
||||
// Switched on, the files are fetched from Hugging Face at the revision
|
||||
// their sha256 were pinned at; switched off, they are deleted. Memories
|
||||
// are read in the background (Keep) and their vectors kept in the model's
|
||||
// folder, keyed by the text read, so an edited memory is read again and a
|
||||
// new revision starts afresh. The model is loaded when first needed and
|
||||
// let go after idleAfter with none.
|
||||
package memembed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/filelock"
|
||||
"github.com/yetone/magpie/internal/memory"
|
||||
"github.com/yetone/magpie/internal/pii"
|
||||
"github.com/yetone/magpie/internal/pii/guard"
|
||||
)
|
||||
|
||||
// rev is the repo's revision the files below were hashed at.
|
||||
const rev = "2c4055b12046f11709e9df2c122e59ffbdc2f900"
|
||||
|
||||
type pinned struct {
|
||||
path string // in the repo; saved under its base name
|
||||
size int64
|
||||
sha string
|
||||
}
|
||||
|
||||
var files = []pinned{
|
||||
{"onnx/model_int8.onnx", 118054609, "d6ea442ff6a891daefed7c83b2f596fc5dc66bf697e4d006236f64f34bbcf4c8"},
|
||||
{"tokenizer.json", 17082913, "b60b6b43406a48bf3638526314f3d232d97058bc93472ff2de930d43686fa441"},
|
||||
}
|
||||
|
||||
// base is where the files are fetched from; a variable for tests.
|
||||
var base = "https://huggingface.co/Xenova/paraphrase-multilingual-MiniLM-L12-v2/resolve/"
|
||||
|
||||
// Root is where the model is kept, in magpie's cache: a folder per
|
||||
// revision. A variable for tests.
|
||||
var Root = func() string { return filepath.Join(appdir.Cache(), "paraphrase-multilingual-MiniLM-L12-v2") }
|
||||
|
||||
func dir() string { return filepath.Join(Root(), rev[:12]) }
|
||||
|
||||
// StatePath is the switch's file; a variable for tests.
|
||||
var StatePath = func() string { return appdir.Join(appdir.Config(), "memory-semantic.json") }
|
||||
|
||||
// Size is the bytes the model downloads.
|
||||
func Size() int64 {
|
||||
var n int64
|
||||
for _, f := range files {
|
||||
n += f.size
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// Installed says every file is on disk at its size.
|
||||
func Installed() bool {
|
||||
for _, f := range files {
|
||||
fi, err := os.Stat(filepath.Join(dir(), filepath.Base(f.path)))
|
||||
if err != nil || fi.Size() != f.size {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type state struct {
|
||||
On bool `json:"on"`
|
||||
}
|
||||
|
||||
var stateMu sync.Mutex
|
||||
|
||||
func load() (state, error) {
|
||||
var s state
|
||||
b, err := os.ReadFile(StatePath())
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return s, nil
|
||||
}
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
return s, json.Unmarshal(b, &s)
|
||||
}
|
||||
|
||||
// On says search by meaning is switched on. A switch file that can't be
|
||||
// read is off: the model isn't loaded on a guess.
|
||||
func On() bool {
|
||||
s, err := load()
|
||||
return err == nil && s.On
|
||||
}
|
||||
|
||||
// Status is what the Memory tab shows of it.
|
||||
type Status struct {
|
||||
On bool `json:"on"`
|
||||
Installed bool `json:"installed"`
|
||||
Size int64 `json:"size"`
|
||||
Downloading bool `json:"downloading"`
|
||||
Done int64 `json:"done"`
|
||||
Error string `json:"error,omitempty"`
|
||||
// Read of Of are the memories read (with a vector), of all there are
|
||||
Read int `json:"read"`
|
||||
Of int `json:"of"`
|
||||
// Reading is a background read going
|
||||
Reading bool `json:"reading"`
|
||||
// Failed is why the last read failed, "" when it worked
|
||||
Failed string `json:"failed,omitempty"`
|
||||
}
|
||||
|
||||
// Now is its status.
|
||||
func Now() Status {
|
||||
st := Status{On: On(), Installed: Installed(), Size: Size()}
|
||||
dl.mu.Lock()
|
||||
st.Downloading, st.Error = dl.cancel != nil, dl.err
|
||||
dl.mu.Unlock()
|
||||
st.Done = dl.done.Load()
|
||||
if st.Installed {
|
||||
st.Done = st.Size
|
||||
}
|
||||
st.Reading = reading.Load()
|
||||
idx.mu.Lock()
|
||||
st.Failed = idx.failed
|
||||
idx.mu.Unlock()
|
||||
if st.On && st.Installed {
|
||||
if all, _, err := memory.All(); err == nil {
|
||||
vs := vectors()
|
||||
for _, m := range all {
|
||||
if !searched(m) {
|
||||
continue
|
||||
}
|
||||
st.Of++
|
||||
if _, ok := vs.get(key(m)); ok {
|
||||
st.Read++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// Set switches it on, fetching the model when it isn't on disk, or off,
|
||||
// stopping a download and deleting the model and what it read.
|
||||
func Set(on bool) error {
|
||||
stateMu.Lock()
|
||||
defer stateMu.Unlock()
|
||||
p := StatePath()
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
b, _ := json.Marshal(state{On: on})
|
||||
if err := edit.WriteAtomic(p, b); err != nil {
|
||||
return err
|
||||
}
|
||||
if on {
|
||||
if !Installed() {
|
||||
dl.start()
|
||||
} else {
|
||||
Poke()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
dl.stop()
|
||||
unload()
|
||||
store.mu.Lock()
|
||||
store.v = nil
|
||||
store.mu.Unlock()
|
||||
return os.RemoveAll(Root())
|
||||
}
|
||||
|
||||
// ---------- the download ----------
|
||||
|
||||
type download struct {
|
||||
mu sync.Mutex
|
||||
cancel context.CancelFunc // nil when none is under way
|
||||
err string // the last one's, "" when it worked
|
||||
done atomic.Int64
|
||||
}
|
||||
|
||||
var dl download
|
||||
|
||||
// start fetches the model in the background unless a download is under
|
||||
// way, and reads the memories once it is on disk.
|
||||
func (d *download) start() {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if d.cancel != nil {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
d.cancel, d.err = cancel, ""
|
||||
d.done.Store(0)
|
||||
go func() {
|
||||
err := fetchModel(ctx)
|
||||
d.mu.Lock()
|
||||
d.cancel = nil
|
||||
if err != nil && ctx.Err() == nil {
|
||||
d.err = err.Error()
|
||||
}
|
||||
d.mu.Unlock()
|
||||
cancel()
|
||||
if err == nil {
|
||||
Poke()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// stop ends the download under way.
|
||||
func (d *download) stop() {
|
||||
d.mu.Lock()
|
||||
if d.cancel != nil {
|
||||
d.cancel()
|
||||
}
|
||||
d.mu.Unlock()
|
||||
}
|
||||
|
||||
// fetchModel fetches the files not on disk yet, each checked against
|
||||
// its sha256.
|
||||
func fetchModel(ctx context.Context) error {
|
||||
if err := os.MkdirAll(dir(), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
var at int64
|
||||
for _, f := range files {
|
||||
path := filepath.Join(dir(), filepath.Base(f.path))
|
||||
if fi, err := os.Stat(path); err != nil || fi.Size() != f.size {
|
||||
var n atomic.Int64
|
||||
stop := make(chan struct{})
|
||||
go func() {
|
||||
t := time.NewTicker(200 * time.Millisecond)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-t.C:
|
||||
dl.done.Store(at + n.Load())
|
||||
}
|
||||
}
|
||||
}()
|
||||
err := pii.Fetch(ctx, base+rev+"/"+f.path, path, f.size, f.sha, &n)
|
||||
close(stop)
|
||||
if err != nil {
|
||||
return fmt.Errorf("downloading %s: %w", filepath.Base(f.path), err)
|
||||
}
|
||||
}
|
||||
at += f.size
|
||||
dl.done.Store(at)
|
||||
}
|
||||
// the folders of revisions pinned before
|
||||
es, _ := os.ReadDir(Root())
|
||||
for _, e := range es {
|
||||
if e.IsDir() && e.Name() != filepath.Base(dir()) {
|
||||
os.RemoveAll(filepath.Join(Root(), e.Name()))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---------- the model ----------
|
||||
|
||||
// idleAfter is how long the model stays loaded with nothing to read.
|
||||
var idleAfter = 10 * time.Minute
|
||||
|
||||
// loadModel reads the model; a variable for tests, which give a fake.
|
||||
var loadModel = func(dir string) (embedder, error) { return guard.LoadEmbedder(dir) }
|
||||
|
||||
type embedder interface {
|
||||
Embed(text string) []float32
|
||||
}
|
||||
|
||||
var mod struct {
|
||||
mu sync.Mutex // held while it loads
|
||||
e embedder
|
||||
idle *time.Timer
|
||||
}
|
||||
|
||||
// model is the model, loaded unless it is, kept for idleAfter more.
|
||||
func model() (embedder, error) {
|
||||
mod.mu.Lock()
|
||||
defer mod.mu.Unlock()
|
||||
if mod.e == nil {
|
||||
if !Installed() {
|
||||
return nil, errors.New("the model isn't downloaded")
|
||||
}
|
||||
e, err := loadModel(dir())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mod.e = e
|
||||
}
|
||||
if mod.idle != nil {
|
||||
mod.idle.Stop()
|
||||
}
|
||||
mod.idle = time.AfterFunc(idleAfter, unload)
|
||||
return mod.e, nil
|
||||
}
|
||||
|
||||
// unload lets the model go; a read under way finishes with the one it has.
|
||||
func unload() {
|
||||
mod.mu.Lock()
|
||||
if mod.idle != nil {
|
||||
mod.idle.Stop()
|
||||
mod.idle = nil
|
||||
}
|
||||
mod.e = nil
|
||||
mod.mu.Unlock()
|
||||
}
|
||||
|
||||
// ---------- what was read ----------
|
||||
|
||||
// searched says m is one a search can return, and is read.
|
||||
func searched(m *memory.Memory) bool {
|
||||
return m.Status == memory.Active || m.Status == memory.Candidate
|
||||
}
|
||||
|
||||
// passage is what is read of m: its text, and why when it says.
|
||||
func passage(m *memory.Memory) string {
|
||||
if m.Why == "" {
|
||||
return m.Text
|
||||
}
|
||||
return m.Text + "\n" + m.Why
|
||||
}
|
||||
|
||||
func key(m *memory.Memory) [32]byte { return sha256.Sum256([]byte(passage(m))) }
|
||||
|
||||
var reading atomic.Bool
|
||||
|
||||
var idx struct {
|
||||
mu sync.Mutex // one read at a time
|
||||
failed string
|
||||
}
|
||||
|
||||
// pokes wakes Keep for a read now.
|
||||
var pokes = make(chan struct{}, 1)
|
||||
|
||||
// Poke asks Keep to read what is new now, not on its next tick.
|
||||
func Poke() {
|
||||
select {
|
||||
case pokes <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// Keep reads memories not read yet while ctx lasts: every tick and when
|
||||
// poked, while switched on with the model on disk.
|
||||
func Keep(ctx context.Context, tick time.Duration) {
|
||||
t := time.NewTicker(tick)
|
||||
defer t.Stop()
|
||||
for {
|
||||
if On() && Installed() {
|
||||
if _, err := Index(ctx); err != nil && ctx.Err() == nil {
|
||||
idx.mu.Lock()
|
||||
idx.failed = err.Error()
|
||||
idx.mu.Unlock()
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
case <-pokes:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Index reads every memory a search can return that has no vector for its
|
||||
// text yet, keeps the vectors (dropping those of texts gone) and says how
|
||||
// many it read. One goes at a time, in this magpie and across them.
|
||||
func Index(ctx context.Context) (int, error) {
|
||||
idx.mu.Lock()
|
||||
defer idx.mu.Unlock()
|
||||
unlock, held := filelock.Lock(filepath.Join(dir(), "vectors.lock"), 0)
|
||||
if !held {
|
||||
return 0, nil
|
||||
}
|
||||
defer unlock()
|
||||
all, _, err := memory.All()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
vs := vectors()
|
||||
var todo []*memory.Memory
|
||||
keep := map[[32]byte]bool{}
|
||||
for _, m := range all {
|
||||
if !searched(m) {
|
||||
continue
|
||||
}
|
||||
k := key(m)
|
||||
keep[k] = true
|
||||
if _, ok := vs.get(k); !ok {
|
||||
todo = append(todo, m)
|
||||
}
|
||||
}
|
||||
if len(todo) == 0 {
|
||||
if vs.prune(keep) {
|
||||
return 0, vs.save()
|
||||
}
|
||||
idx.failed = ""
|
||||
return 0, nil
|
||||
}
|
||||
reading.Store(true)
|
||||
defer reading.Store(false)
|
||||
e, err := model()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n := 0
|
||||
for _, m := range todo {
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
vs.put(key(m), e.Embed(passage(m)))
|
||||
n++
|
||||
if n%50 == 0 {
|
||||
if err := vs.save(); err != nil {
|
||||
return n, err
|
||||
}
|
||||
}
|
||||
}
|
||||
vs.prune(keep)
|
||||
if err := vs.save(); err != nil {
|
||||
return n, err
|
||||
}
|
||||
idx.failed = ""
|
||||
return n, ctx.Err()
|
||||
}
|
||||
|
||||
// similar is memory.Semantic: each memory of pool with a vector, and its
|
||||
// cosine to text. A memory read since the last Index (a
|
||||
// few at most) is read here, for a search right after it was saved.
|
||||
func similar(text string, pool []*memory.Memory) map[string]float64 {
|
||||
if len(pool) == 0 || !On() || !Installed() {
|
||||
return nil
|
||||
}
|
||||
vs := vectors()
|
||||
var missing []*memory.Memory
|
||||
for _, m := range pool {
|
||||
if _, ok := vs.get(key(m)); !ok {
|
||||
missing = append(missing, m)
|
||||
}
|
||||
}
|
||||
if len(missing) == len(pool) && len(pool) > inline {
|
||||
// nothing read yet: words alone, while Keep reads them
|
||||
Poke()
|
||||
return nil
|
||||
}
|
||||
e, err := model()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if len(missing) > inline {
|
||||
Poke()
|
||||
missing = missing[:inline]
|
||||
}
|
||||
for _, m := range missing {
|
||||
vs.put(key(m), e.Embed(passage(m)))
|
||||
}
|
||||
q := e.Embed(text)
|
||||
out := map[string]float64{}
|
||||
for _, m := range pool {
|
||||
v, ok := vs.get(key(m))
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
var dot float64
|
||||
for i := range q {
|
||||
dot += float64(q[i]) * float64(v[i])
|
||||
}
|
||||
out[m.ID] = dot
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// inline is how many memories not read yet a search reads itself.
|
||||
const inline = 16
|
||||
|
||||
func init() { memory.Semantic = similar }
|
||||
@@ -0,0 +1,194 @@
|
||||
package memembed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/memory"
|
||||
"github.com/yetone/magpie/internal/pii/guard"
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { testenv.Main(m) }
|
||||
|
||||
// fake reads a text as the topics it names, in either language: what a
|
||||
// real model does for a search across languages, without its 135 MB.
|
||||
type fake struct{ calls atomic.Int32 }
|
||||
|
||||
var topics = [][]string{
|
||||
{"release", "ship", "上线", "发布"},
|
||||
{"tabs", "indent", "缩进"},
|
||||
{"port", "端口"},
|
||||
}
|
||||
|
||||
func (f *fake) Embed(text string) []float32 {
|
||||
f.calls.Add(1)
|
||||
v := make([]float32, guard.EmbedDim)
|
||||
v[len(v)-1] = 0.5 // something in common, as real texts have
|
||||
for i, words := range topics {
|
||||
for _, w := range words {
|
||||
if strings.Contains(strings.ToLower(text), w) {
|
||||
v[i] = 1
|
||||
}
|
||||
}
|
||||
}
|
||||
var sq float64
|
||||
for _, x := range v {
|
||||
sq += float64(x) * float64(x)
|
||||
}
|
||||
for i := range v {
|
||||
v[i] /= float32(math.Sqrt(sq))
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// sandbox points memembed and memory at a folder of the test's own, with
|
||||
// the model's files on disk at their sizes (sparse) and a fake model.
|
||||
func sandbox(t *testing.T, installed bool) *fake {
|
||||
t.Helper()
|
||||
d := t.TempDir()
|
||||
oldRoot, oldState, oldMem, oldLoad := Root, StatePath, memory.Path, loadModel
|
||||
Root = func() string { return filepath.Join(d, "model") }
|
||||
StatePath = func() string { return filepath.Join(d, "memory-semantic.json") }
|
||||
memory.Path = func() string { return filepath.Join(d, "memory.json") }
|
||||
f := &fake{}
|
||||
loadModel = func(string) (embedder, error) { return f, nil }
|
||||
t.Cleanup(func() {
|
||||
Root, StatePath, memory.Path, loadModel = oldRoot, oldState, oldMem, oldLoad
|
||||
unload()
|
||||
store.mu.Lock()
|
||||
store.v = nil
|
||||
store.mu.Unlock()
|
||||
})
|
||||
if installed {
|
||||
if err := os.MkdirAll(dir(), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, p := range files {
|
||||
path := filepath.Join(dir(), filepath.Base(p.path))
|
||||
if err := os.WriteFile(path, nil, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Truncate(path, p.size); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
b := []byte(`{"on":true}`)
|
||||
if err := os.WriteFile(StatePath(), b, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func save(t *testing.T, text, status string) *memory.Memory {
|
||||
t.Helper()
|
||||
k, sc := memory.Fact, memory.Global
|
||||
m, _, err := memory.Save(memory.Input{Text: &text, Kind: &k, Scope: &sc, Status: &status}, memory.FromUser, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func ids(hs []memory.Hit) []string {
|
||||
out := []string{}
|
||||
for _, h := range hs {
|
||||
out = append(out, h.Text)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// A search finds what means the same in other words and another language,
|
||||
// beside what holds its words; switched off, by words alone.
|
||||
func TestSearchFindsByMeaning(t *testing.T) {
|
||||
sandbox(t, true)
|
||||
save(t, "Releases go out on Tuesdays", memory.Active)
|
||||
save(t, "Use tabs, never spaces", memory.Active)
|
||||
save(t, "A busy port is someone else's", memory.Active)
|
||||
hits, err := memory.Search(memory.Query{Text: "什么时候上线"})
|
||||
if err != nil || len(hits) != 1 || hits[0].Text != "Releases go out on Tuesdays" {
|
||||
t.Fatalf("%v %v", ids(hits), err)
|
||||
}
|
||||
// found both ways ahead of found one way: "never" is in one, and
|
||||
// both mean 缩进
|
||||
save(t, "Indent Go files with tabs", memory.Active)
|
||||
hits, _ = memory.Search(memory.Query{Text: "never 缩进"})
|
||||
if got := ids(hits); len(got) != 2 || got[0] != "Use tabs, never spaces" || got[1] != "Indent Go files with tabs" {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
// one common word ranks as high as the nearest in meaning; the nearer
|
||||
// in meaning goes first, though the other is newer
|
||||
save(t, "Never delete images when freeing disk space", memory.Active)
|
||||
hits, _ = memory.Search(memory.Query{Text: "when do we release"})
|
||||
if got := ids(hits); len(got) != 2 || got[0] != "Releases go out on Tuesdays" {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
if err := Set(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(Root()); !os.IsNotExist(err) {
|
||||
t.Fatalf("the model is still there: %v", err)
|
||||
}
|
||||
if hits, _ := memory.Search(memory.Query{Text: "什么时候上线"}); len(hits) != 0 {
|
||||
t.Fatalf("off, by meaning: %v", ids(hits))
|
||||
}
|
||||
}
|
||||
|
||||
// Index reads what a search can return and has no vector for its text:
|
||||
// once, again when its text changes, and the old text's vector goes. The
|
||||
// vectors are kept on disk, and a file cut short is read as none.
|
||||
func TestIndexReadsOnce(t *testing.T) {
|
||||
f := sandbox(t, true)
|
||||
a := save(t, "Releases go out on Tuesdays", memory.Active)
|
||||
save(t, "Use tabs", memory.Candidate)
|
||||
save(t, "Old port rule", memory.Archived)
|
||||
if n, err := Index(context.Background()); err != nil || n != 2 {
|
||||
t.Fatalf("%d %v", n, err)
|
||||
}
|
||||
if n, _ := Index(context.Background()); n != 0 || f.calls.Load() != 2 {
|
||||
t.Fatalf("read again: %d, %d calls", n, f.calls.Load())
|
||||
}
|
||||
text := "Releases go out on Wednesdays"
|
||||
if _, err := memory.Edit(a.ID, memory.Input{Text: &text}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n, _ := Index(context.Background()); n != 1 {
|
||||
t.Fatalf("edited: %d", n)
|
||||
}
|
||||
if st := Now(); st.Read != 2 || st.Of != 2 || !st.On || !st.Installed {
|
||||
t.Fatalf("%+v", st)
|
||||
}
|
||||
path := filepath.Join(dir(), "vectors.bin")
|
||||
if got := len(readVecs(path)); got != 2 {
|
||||
t.Fatalf("on disk: %d", got)
|
||||
}
|
||||
b, _ := os.ReadFile(path)
|
||||
if err := os.WriteFile(path, b[:len(b)-1], 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := len(readVecs(path)); got != 0 {
|
||||
t.Fatalf("cut short: %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
// With the model not on disk, or a switch file that can't be read, a
|
||||
// search is by words and nothing is loaded.
|
||||
func TestNotThereIsWords(t *testing.T) {
|
||||
f := sandbox(t, false)
|
||||
save(t, "Releases go out on Tuesdays", memory.Active)
|
||||
if hits, _ := memory.Search(memory.Query{Text: "上线"}); len(hits) != 0 || f.calls.Load() != 0 {
|
||||
t.Fatalf("%v, %d calls", ids(hits), f.calls.Load())
|
||||
}
|
||||
if err := os.WriteFile(StatePath(), []byte("{"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if On() {
|
||||
t.Fatal("a broken switch file is on")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package memembed
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/pii/guard"
|
||||
)
|
||||
|
||||
// vectors.bin, in the model's folder: "MEV1", the vectors' length as a
|
||||
// little-endian uint32, then one record a text read: its sha256 and its
|
||||
// vector, little-endian float32s. A file that can't be read whole is read
|
||||
// as none: the memories are read again, which is all it costs.
|
||||
|
||||
var magic = []byte("MEV1")
|
||||
|
||||
type vecs struct {
|
||||
mu sync.Mutex
|
||||
path string
|
||||
m map[[32]byte][]float32
|
||||
}
|
||||
|
||||
var store struct {
|
||||
mu sync.Mutex
|
||||
v *vecs
|
||||
}
|
||||
|
||||
// vectors is what was read, from vectors.bin on the first call.
|
||||
func vectors() *vecs {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
path := filepath.Join(dir(), "vectors.bin")
|
||||
if store.v == nil || store.v.path != path {
|
||||
store.v = &vecs{path: path, m: readVecs(path)}
|
||||
}
|
||||
return store.v
|
||||
}
|
||||
|
||||
func readVecs(path string) map[[32]byte][]float32 {
|
||||
m := map[[32]byte][]float32{}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil || len(b) < 8 || !bytes.Equal(b[:4], magic) || binary.LittleEndian.Uint32(b[4:8]) != guard.EmbedDim {
|
||||
return m
|
||||
}
|
||||
rec := 32 + 4*guard.EmbedDim
|
||||
b = b[8:]
|
||||
if len(b)%rec != 0 {
|
||||
return map[[32]byte][]float32{}
|
||||
}
|
||||
for ; len(b) > 0; b = b[rec:] {
|
||||
var k [32]byte
|
||||
copy(k[:], b[:32])
|
||||
v := make([]float32, guard.EmbedDim)
|
||||
for i := range v {
|
||||
v[i] = math.Float32frombits(binary.LittleEndian.Uint32(b[32+4*i:]))
|
||||
}
|
||||
m[k] = v
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (vs *vecs) get(k [32]byte) ([]float32, bool) {
|
||||
vs.mu.Lock()
|
||||
defer vs.mu.Unlock()
|
||||
v, ok := vs.m[k]
|
||||
return v, ok
|
||||
}
|
||||
|
||||
func (vs *vecs) put(k [32]byte, v []float32) {
|
||||
vs.mu.Lock()
|
||||
vs.m[k] = v
|
||||
vs.mu.Unlock()
|
||||
}
|
||||
|
||||
// prune drops the vectors of texts not in keep, and says whether it did.
|
||||
func (vs *vecs) prune(keep map[[32]byte]bool) bool {
|
||||
vs.mu.Lock()
|
||||
defer vs.mu.Unlock()
|
||||
gone := false
|
||||
for k := range vs.m {
|
||||
if !keep[k] {
|
||||
delete(vs.m, k)
|
||||
gone = true
|
||||
}
|
||||
}
|
||||
return gone
|
||||
}
|
||||
|
||||
// save writes them through a temp file renamed over the last.
|
||||
func (vs *vecs) save() error {
|
||||
vs.mu.Lock()
|
||||
var b bytes.Buffer
|
||||
b.Write(magic)
|
||||
b.Write(binary.LittleEndian.AppendUint32(nil, guard.EmbedDim))
|
||||
for k, v := range vs.m {
|
||||
b.Write(k[:])
|
||||
for _, f := range v {
|
||||
b.Write(binary.LittleEndian.AppendUint32(nil, math.Float32bits(f)))
|
||||
}
|
||||
}
|
||||
vs.mu.Unlock()
|
||||
if err := os.MkdirAll(filepath.Dir(vs.path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
return edit.WriteAtomic(vs.path, b.Bytes())
|
||||
}
|
||||
+118
-5
@@ -25,17 +25,39 @@ type Hit struct {
|
||||
Score float64 `json:"score"`
|
||||
}
|
||||
|
||||
// Semantic, when set (memembed, with search by meaning switched on), is
|
||||
// how near in meaning each memory of pool is to text, a cosine, for the
|
||||
// ones it has read; nil when it can't say (switched off, the model not
|
||||
// there, or failing), and the search is by words alone.
|
||||
var Semantic func(text string, pool []*Memory) map[string]float64
|
||||
|
||||
// A memory counts as meaning what was searched for at a cosine of Near
|
||||
// or more, and Within of the nearest. Over 97 real memories and 16
|
||||
// searches (half in Chinese, for memories in English), the memory sought
|
||||
// was at a median of 0.47, the rest at a median of 0.16 and a 95th
|
||||
// percentile of 0.36. Near alone let ~11 of the rest in a search; with
|
||||
// Within, 12 of the 16 were found and ~4 of the rest came along, behind
|
||||
// them, and the word ranking finds most of the four it misses.
|
||||
var (
|
||||
Near = 0.30
|
||||
Within = 0.15
|
||||
)
|
||||
|
||||
// rrfK is reciprocal-rank fusion's constant: the word ranking and the
|
||||
// meaning ranking each give a hit 1/(rrfK+rank).
|
||||
const rrfK = 20
|
||||
|
||||
// Search finds memories matching q, best first: every word of the text
|
||||
// counted by how rare it is among the memories, a memory holding the whole
|
||||
// text ahead, pinned ones and a project's or agent's own a little ahead of
|
||||
// the rest. With no text, it lists them by kind and newest change. The
|
||||
// hits are noted as used.
|
||||
// the rest; with search by meaning on (Semantic), the ones that mean the
|
||||
// same in other words too, the two rankings fused. With no text, it lists
|
||||
// them by kind and newest change. The hits are noted as used.
|
||||
func Search(q Query) ([]Hit, error) {
|
||||
f, err := view()
|
||||
hits, err := Rank(q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hits := search(f.Memories, q)
|
||||
ids := make([]string, len(hits))
|
||||
for i, h := range hits {
|
||||
ids[i] = h.ID
|
||||
@@ -46,6 +68,16 @@ func Search(q Query) ([]Hit, error) {
|
||||
return hits, nil
|
||||
}
|
||||
|
||||
// Rank is Search without noting the hits as used: for the Memory tab's
|
||||
// search box, which the user types into.
|
||||
func Rank(q Query) ([]Hit, error) {
|
||||
f, err := view()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return search(f.Memories, q), nil
|
||||
}
|
||||
|
||||
func search(all []*Memory, q Query) []Hit {
|
||||
status := q.Status
|
||||
if status == "" {
|
||||
@@ -86,6 +118,19 @@ func search(all []*Memory, q Query) []Hit {
|
||||
}
|
||||
return out
|
||||
}
|
||||
out := wordHits(pool, text)
|
||||
var sims map[string]float64
|
||||
if Semantic != nil {
|
||||
sims = Semantic(text, pool)
|
||||
}
|
||||
if sims != nil {
|
||||
out = fuse(pool, out, sims)
|
||||
}
|
||||
return out[:min(limit, len(out))]
|
||||
}
|
||||
|
||||
// wordHits are pool's memories holding words of text, best first.
|
||||
func wordHits(pool []*Memory, text string) []Hit {
|
||||
words := Words(text)
|
||||
if len(words) == 0 {
|
||||
return []Hit{}
|
||||
@@ -141,7 +186,75 @@ func search(all []*Memory, q Query) []Hit {
|
||||
}
|
||||
return b.Updated.Compare(a.Updated)
|
||||
})
|
||||
return out[:min(limit, len(out))]
|
||||
return out
|
||||
}
|
||||
|
||||
// fuse is the word hits and the memories near text in meaning (sims, at
|
||||
// Near or more and Within of the nearest) as one ranking: each list gives
|
||||
// a hit 1/(rrfK+rank), and a pinned or a project's or agent's own memory
|
||||
// is a little ahead, as in wordHits. A memory found both ways is ahead of
|
||||
// one found either way, and of two that score the same, the nearer in
|
||||
// meaning: the first word hit may hold one common word of the search.
|
||||
func fuse(pool []*Memory, words []Hit, sims map[string]float64) []Hit {
|
||||
bar := Near
|
||||
for _, s := range sims {
|
||||
bar = max(bar, s-Within)
|
||||
}
|
||||
near := []*Memory{}
|
||||
for _, m := range pool {
|
||||
if s, ok := sims[m.ID]; ok && s >= bar {
|
||||
near = append(near, m)
|
||||
}
|
||||
}
|
||||
slices.SortStableFunc(near, func(a, b *Memory) int {
|
||||
if sims[a.ID] != sims[b.ID] {
|
||||
if sims[a.ID] > sims[b.ID] {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
return b.Updated.Compare(a.Updated)
|
||||
})
|
||||
score := map[string]float64{}
|
||||
byID := map[string]*Memory{}
|
||||
for i, h := range words {
|
||||
score[h.ID] += 1 / float64(rrfK+i+1)
|
||||
byID[h.ID] = h.Memory
|
||||
}
|
||||
for i, m := range near {
|
||||
score[m.ID] += 1 / float64(rrfK+i+1)
|
||||
byID[m.ID] = m
|
||||
}
|
||||
out := make([]Hit, 0, len(score))
|
||||
for id, s := range score {
|
||||
m := byID[id]
|
||||
if m.Pinned {
|
||||
s *= 1.2
|
||||
}
|
||||
if m.Scope != Global {
|
||||
s *= 1.1
|
||||
}
|
||||
out = append(out, Hit{Memory: m, Score: math.Round(s*rrfK*100) / 100})
|
||||
}
|
||||
slices.SortStableFunc(out, func(a, b Hit) int {
|
||||
if a.Score != b.Score {
|
||||
if a.Score > b.Score {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
if sa, sb := sims[a.ID], sims[b.ID]; sa != sb {
|
||||
if sa > sb {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
if c := b.Updated.Compare(a.Updated); c != 0 {
|
||||
return c
|
||||
}
|
||||
return strings.Compare(a.ID, b.ID)
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func kindRank(k string) int {
|
||||
|
||||
@@ -235,6 +235,13 @@ func unzipTo(f *zip.File, path string) error {
|
||||
return out.Close()
|
||||
}
|
||||
|
||||
// Fetch is fetch for another package's pinned file (memembed's model):
|
||||
// through magpie's proxy, taken up where a stopped one left off, and
|
||||
// renamed into place only when its sha256 is want.
|
||||
func Fetch(ctx context.Context, url, path string, size int64, want string, done *atomic.Int64) error {
|
||||
return fetch(ctx, url, path, size, want, done)
|
||||
}
|
||||
|
||||
// fetch downloads url to path through path+".part", taking up a part
|
||||
// already there with a Range request, and renames it to path only when
|
||||
// its sha256 is want (and its size size, unless that is -1). done counts
|
||||
|
||||
@@ -319,6 +319,20 @@ func (nt *net) embed(ids []int, rows int) []float32 {
|
||||
// encode is the classifier's scores for embeddings x of n tokens, over
|
||||
// procs goroutines.
|
||||
func (nt *net) encode(x []float32, n, procs int) []float32 {
|
||||
x = nt.hidden(x, n, procs)
|
||||
out := nt.cls.matmul(x, n, procs)
|
||||
for t := 0; t < n; t++ {
|
||||
row := out[t*nt.labels : t*nt.labels+nt.labels]
|
||||
for i := range row {
|
||||
row[i] = nt.clsBias[i] + row[i]
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// hidden is the encoder's last hidden state for embeddings x of n tokens,
|
||||
// [n, hidden], over procs goroutines.
|
||||
func (nt *net) hidden(x []float32, n, procs int) []float32 {
|
||||
for i := range nt.layers {
|
||||
l := &nt.layers[i]
|
||||
qkv := l.qkv.matmul(x, n, procs)
|
||||
@@ -341,14 +355,7 @@ func (nt *net) encode(x []float32, n, procs int) []float32 {
|
||||
skipNorm(o, x, n, l.downBias, l.ln2w, l.ln2b)
|
||||
x = o
|
||||
}
|
||||
out := nt.cls.matmul(x, n, procs)
|
||||
for t := 0; t < n; t++ {
|
||||
row := out[t*nt.labels : t*nt.labels+nt.labels]
|
||||
for i := range row {
|
||||
row[i] = nt.clsBias[i] + row[i]
|
||||
}
|
||||
}
|
||||
return out
|
||||
return x
|
||||
}
|
||||
|
||||
// skipNorm is SkipLayerNormalization: out = norm(out + skip + bias).
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
package guard
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// paraphrase-multilingual-MiniLM-L12-v2 (sentence-transformers, Apache
|
||||
// 2.0; Xenova's int8 ONNX of it) is the second network bert.go runs: the
|
||||
// same 12-layer BERT, 384 wide, with XLM-RoBERTa's 250,002 pieces and no
|
||||
// classifier. Its last hidden state, averaged over the tokens and scaled
|
||||
// to length 1, is a text's place in a space where texts that say the same
|
||||
// are near, in any of 50 languages and across them: memory's search by
|
||||
// meaning. Its weights are int8 with one scale and zero
|
||||
// point per matrix (AstrLink Guard's have one a column), and its matmuls
|
||||
// unfused; loadEmbedNet lays them out as bert.go reads them.
|
||||
|
||||
const (
|
||||
embVocab = 250002 // the tokenizer's pieces
|
||||
embRows = 250037 // the word embeddings' rows (padded past the pieces)
|
||||
// EmbedDim is the length of an embedding
|
||||
EmbedDim = hidden
|
||||
)
|
||||
|
||||
// EmbedFiles are the files LoadEmbedder reads, in its folder.
|
||||
var EmbedFiles = []string{"model_int8.onnx", "tokenizer.json"}
|
||||
|
||||
// Embedder is paraphrase-multilingual-MiniLM-L12-v2, loaded.
|
||||
type Embedder struct {
|
||||
tok *tokenizer
|
||||
net *net
|
||||
}
|
||||
|
||||
// LoadEmbedder reads the model in dir.
|
||||
func LoadEmbedder(dir string) (*Embedder, error) {
|
||||
tok, err := loadTokenizer(filepath.Join(dir, "tokenizer.json"), embVocab)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tokenizer: %w", err)
|
||||
}
|
||||
nt, err := loadEmbedNet(filepath.Join(dir, "model_int8.onnx"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("model: %w", err)
|
||||
}
|
||||
return &Embedder{tok: tok, net: nt}, nil
|
||||
}
|
||||
|
||||
// Embed is text's embedding, of EmbedDim numbers and length 1: the same
|
||||
// for a search and what it searches. A text past maxPos tokens is read to
|
||||
// there.
|
||||
func (e *Embedder) Embed(text string) []float32 {
|
||||
toks := e.tok.encode(text)
|
||||
ids := make([]int, 0, min(len(toks), maxPos-2)+2)
|
||||
ids = append(ids, 0)
|
||||
for _, t := range toks[:min(len(toks), maxPos-2)] {
|
||||
ids = append(ids, t.id)
|
||||
}
|
||||
ids = append(ids, 2)
|
||||
n := len(ids)
|
||||
procs := take(Cores())
|
||||
defer give(procs)
|
||||
x := e.net.hidden(e.net.embed(ids, 0), n, procs)
|
||||
out := make([]float32, hidden)
|
||||
for t := 0; t < n; t++ {
|
||||
for i, v := range x[t*hidden : t*hidden+hidden] {
|
||||
out[i] += v
|
||||
}
|
||||
}
|
||||
var sq float64
|
||||
for i := range out {
|
||||
out[i] /= float32(n)
|
||||
sq += float64(out[i]) * float64(out[i])
|
||||
}
|
||||
if sq > 0 {
|
||||
inv := float32(1 / math.Sqrt(sq))
|
||||
for i := range out {
|
||||
out[i] *= inv
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// loadEmbedNet reads the model's int8 ONNX into a net: each
|
||||
// per-matrix scale and zero point given to every column, and each layer's
|
||||
// query, key and value matrices side by side as one, as AstrLink Guard's
|
||||
// fused attention has them.
|
||||
func loadEmbedNet(path string) (*net, error) {
|
||||
ts, err := readONNX(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var missing error
|
||||
get := func(name string, dtype int, dims ...int64) *tensor {
|
||||
t := ts[name]
|
||||
if missing != nil {
|
||||
return t
|
||||
}
|
||||
if t == nil {
|
||||
missing = fmt.Errorf("the model has no %s", name)
|
||||
return nil
|
||||
}
|
||||
if t.dtype != dtype || len(t.dims) != len(dims) {
|
||||
missing = fmt.Errorf("%s is %d %v", name, t.dtype, t.dims)
|
||||
return nil
|
||||
}
|
||||
for i, d := range dims {
|
||||
if t.dims[i] != d {
|
||||
missing = fmt.Errorf("%s is %v", name, t.dims)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return t
|
||||
}
|
||||
fl := func(name string, n int64) []float32 {
|
||||
t := get(name, tFloat, n)
|
||||
if t == nil {
|
||||
return nil
|
||||
}
|
||||
return t.floats()
|
||||
}
|
||||
scalar := func(name string) float32 {
|
||||
t := get(name, tFloat)
|
||||
if t == nil {
|
||||
return 0
|
||||
}
|
||||
return t.floats()[0]
|
||||
}
|
||||
// an embedding table: uint8, one scale and zero point
|
||||
embQ := func(name string, rows int64) ([]uint8, []float32, []int32) {
|
||||
q := get(name+".weight_quantized", tUint8, rows, hidden)
|
||||
s := scalar(name + ".weight_scale")
|
||||
z := get(name+".weight_zero_point", tUint8)
|
||||
if missing != nil {
|
||||
return nil, nil, nil
|
||||
}
|
||||
sc, zp := make([]float32, hidden), make([]int32, hidden)
|
||||
for c := range sc {
|
||||
sc[c], zp[c] = s, int32(z.raw[0])
|
||||
}
|
||||
// raw is a slice of the file read whole; the table is most of it
|
||||
return q.raw, sc, zp
|
||||
}
|
||||
emb := func(name string, rows int64) []float32 {
|
||||
q, sc, zp := embQ(name, rows)
|
||||
if q == nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]float32, len(q))
|
||||
for i, b := range q {
|
||||
c := i % hidden
|
||||
out[i] = float32(int32(b)-zp[c]) * sc[c]
|
||||
}
|
||||
return out
|
||||
}
|
||||
// mats are matrices [k, n_i] as one [k, Σn_i], by column
|
||||
mats := func(k int64, names ...string) qmat {
|
||||
var parts []*tensor
|
||||
var scales []float32
|
||||
var zps []int32
|
||||
n := 0
|
||||
for _, name := range names {
|
||||
q := ts[name+"_quantized"]
|
||||
if q == nil || len(q.dims) != 2 {
|
||||
get(name+"_quantized", tInt8, k, -1)
|
||||
return qmat{}
|
||||
}
|
||||
q = get(name+"_quantized", tInt8, k, q.dims[1])
|
||||
s := scalar(name + "_scale")
|
||||
z := get(name+"_zero_point", tInt8)
|
||||
if missing != nil {
|
||||
return qmat{}
|
||||
}
|
||||
parts = append(parts, q)
|
||||
for range q.dims[1] {
|
||||
scales = append(scales, s)
|
||||
zps = append(zps, int32(int8(z.raw[0])))
|
||||
}
|
||||
n += int(q.dims[1])
|
||||
}
|
||||
m := qmat{k: int(k), n: n, w: make([]int8, int(k)*n), scale: scales, zp: zps, sum: make([]int32, n)}
|
||||
c := 0
|
||||
for _, q := range parts {
|
||||
pn := int(q.dims[1])
|
||||
for pc := 0; pc < pn; pc, c = pc+1, c+1 {
|
||||
for r := 0; r < m.k; r++ {
|
||||
v := int8(q.raw[r*pn+pc])
|
||||
m.w[c*m.k+r] = v
|
||||
m.sum[c] += int32(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
nt := &net{}
|
||||
nt.word, nt.wordScale, nt.wordZP = embQ("embeddings.word_embeddings", embRows)
|
||||
nt.pos = emb("embeddings.position_embeddings", maxPos)
|
||||
nt.typ = emb("embeddings.token_type_embeddings", 2)
|
||||
if t := get("embeddings.position_ids", tInt64, 1, maxPos); t != nil {
|
||||
nt.posIDs = t.int64s()
|
||||
}
|
||||
nt.embLNw = fl("embeddings.LayerNorm.weight", hidden)
|
||||
nt.embLNb = fl("embeddings.LayerNorm.bias", hidden)
|
||||
ones := make([]float32, inter)
|
||||
for i := range ones {
|
||||
ones[i] = 1
|
||||
}
|
||||
for i := range nt.layers {
|
||||
l := &nt.layers[i]
|
||||
p := fmt.Sprintf("encoder.layer.%d.", i)
|
||||
// the exporter's names for the layer's six matmuls: query, key,
|
||||
// value, the attention's output, up and down
|
||||
b := 1525 + 13*i
|
||||
name := func(off int) string { return fmt.Sprintf("onnx::MatMul_%d", b+off) }
|
||||
l.qkv = mats(hidden, name(0), name(1), name(4))
|
||||
l.qkvBias = append(append(fl(p+"attention.self.query.bias", hidden), fl(p+"attention.self.key.bias", hidden)...), fl(p+"attention.self.value.bias", hidden)...)
|
||||
l.attnOut = mats(hidden, name(10))
|
||||
l.attnBias = fl(p+"attention.output.dense.bias", hidden)
|
||||
l.ln1w = fl(p+"attention.output.LayerNorm.weight", hidden)
|
||||
l.ln1b = fl(p+"attention.output.LayerNorm.bias", hidden)
|
||||
l.up = mats(hidden, name(11))
|
||||
l.upBias = fl(p+"intermediate.dense.bias", inter)
|
||||
l.smooth = ones
|
||||
l.down = mats(inter, name(12))
|
||||
l.downBias = fl(p+"output.dense.bias", hidden)
|
||||
l.ln2w = fl(p+"output.LayerNorm.weight", hidden)
|
||||
l.ln2b = fl(p+"output.LayerNorm.bias", hidden)
|
||||
if missing == nil && (l.qkv.n != 3*hidden || l.attnOut.n != hidden || l.up.n != inter || l.down.n != hidden) {
|
||||
missing = fmt.Errorf("layer %d's matmuls are %d %d %d %d wide", i, l.qkv.n, l.attnOut.n, l.up.n, l.down.n)
|
||||
}
|
||||
}
|
||||
if missing != nil {
|
||||
return nil, missing
|
||||
}
|
||||
return nt, nil
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package guard
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The embedder reads each text into the pieces Hugging Face's tokenizers
|
||||
// does, and to the embedding ONNX Runtime makes of the same int8 model to
|
||||
// a cosine of 0.995, as near the float32 model's as ONNX Runtime's is
|
||||
// (testdata/embedder.json, from all three). Two int8 runs part a little: each
|
||||
// matmul's input is rounded to 256 steps, so a float rounding apart moves
|
||||
// a step now and then; ONNX Runtime's own graph optimizations move its
|
||||
// result 0.9965, and its int8 is 0.988 to 0.993 from float32.
|
||||
func TestEmbedderMatchesONNXRuntime(t *testing.T) {
|
||||
d := os.Getenv("MAGPIE_EMBED_DIR")
|
||||
if d == "" {
|
||||
t.Skip("MAGPIE_EMBED_DIR is not set")
|
||||
}
|
||||
e, err := LoadEmbedder(d)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := os.ReadFile("testdata/embedder.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var want []struct {
|
||||
Text string
|
||||
IDs []int
|
||||
Vec, FP32 []float32
|
||||
}
|
||||
if err := json.Unmarshal(b, &want); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, w := range want {
|
||||
var ids []int
|
||||
for _, tk := range e.tok.encode(w.Text) {
|
||||
ids = append(ids, tk.id)
|
||||
}
|
||||
if got := append(append([]int{0}, ids...), 2); !equalInts(got, w.IDs) {
|
||||
t.Errorf("%q: pieces %v, want %v", w.Text, got, w.IDs)
|
||||
continue
|
||||
}
|
||||
v := e.Embed(w.Text)
|
||||
ort, fp, ortFP := cosine(v, w.Vec), cosine(v, w.FP32), cosine(w.Vec, w.FP32)
|
||||
t.Logf("%q: %.5f with ONNX Runtime's, %.5f with float32's (ONNX Runtime's %.5f)", w.Text, ort, fp, ortFP)
|
||||
if ort < 0.995 || fp < ortFP-0.002 {
|
||||
t.Errorf("%q: cosine %.5f with ONNX Runtime's, %.5f with float32's, where ONNX Runtime's is %.5f", w.Text, ort, fp, ortFP)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cosine(a, b []float32) float64 {
|
||||
var dot float64
|
||||
for i := range a {
|
||||
dot += float64(a[i]) * float64(b[i])
|
||||
}
|
||||
return dot
|
||||
}
|
||||
|
||||
func equalInts(a, b []int) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -87,7 +87,7 @@ const (
|
||||
|
||||
// Load reads the model in dir.
|
||||
func Load(dir string) (*Model, error) {
|
||||
tok, err := loadTokenizer(filepath.Join(dir, "tokenizer.json"))
|
||||
tok, err := loadTokenizer(filepath.Join(dir, "tokenizer.json"), vocabSize)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tokenizer: %w", err)
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ func dir(t *testing.T) string {
|
||||
// model's tokenizer.json (testdata/tokens.json: ids, and offsets in
|
||||
// characters).
|
||||
func TestTokenizerMatchesHF(t *testing.T) {
|
||||
tk, err := loadTokenizer(filepath.Join(dir(t), "tokenizer.json"))
|
||||
tk, err := loadTokenizer(filepath.Join(dir(t), "tokenizer.json"), vocabSize)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
+1
File diff suppressed because one or more lines are too long
@@ -18,8 +18,9 @@ import (
|
||||
// tokenizers library runs it (XLM-RoBERTa's): special tokens split out
|
||||
// first, then SentencePiece's precompiled normalization (NFKC and the
|
||||
// like), a split at whitespace, Metaspace's "▁", and a Unigram model
|
||||
// over its 40,003 pieces. Each token says which bytes of the text it came
|
||||
// from, as the library's offsets do.
|
||||
// over its pieces. Each token says which bytes of the text it came
|
||||
// from, as the library's offsets do. AstrLink Guard's has 40,003 pieces
|
||||
// (vocabSize), the embedder's 250,002 (embedder.go).
|
||||
|
||||
const vocabSize = 40003
|
||||
|
||||
@@ -32,6 +33,9 @@ type tokenizer struct {
|
||||
special []special
|
||||
trie []uint32 // the charsmap's double array
|
||||
norm []byte // and the strings it points at
|
||||
// dropSpace is a pre-tokenizer that starts with WhitespaceSplit (the
|
||||
// embedder's): every run of whitespace is dropped, after a digit too
|
||||
dropSpace bool
|
||||
}
|
||||
|
||||
type special struct {
|
||||
@@ -47,7 +51,7 @@ type token struct {
|
||||
start, end int
|
||||
}
|
||||
|
||||
func loadTokenizer(path string) (*tokenizer, error) {
|
||||
func loadTokenizer(path string, size int) (*tokenizer, error) {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -67,6 +71,11 @@ func loadTokenizer(path string) (*tokenizer, error) {
|
||||
} `json:"normalizers"`
|
||||
Charmap string `json:"precompiled_charsmap"`
|
||||
} `json:"normalizer"`
|
||||
PreTokenizer struct {
|
||||
Pretokenizers []struct {
|
||||
Type string `json:"type"`
|
||||
} `json:"pretokenizers"`
|
||||
} `json:"pre_tokenizer"`
|
||||
Model struct {
|
||||
Type string `json:"type"`
|
||||
UnkID int `json:"unk_id"`
|
||||
@@ -76,10 +85,10 @@ func loadTokenizer(path string) (*tokenizer, error) {
|
||||
if err := json.Unmarshal(b, &f); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if f.Model.Type != "Unigram" || len(f.Model.Vocab) != vocabSize {
|
||||
if f.Model.Type != "Unigram" || len(f.Model.Vocab) != size {
|
||||
return nil, fmt.Errorf("a %s model of %d pieces", f.Model.Type, len(f.Model.Vocab))
|
||||
}
|
||||
t := &tokenizer{pieces: make(map[string]int, vocabSize), scores: make([]float64, vocabSize), unk: f.Model.UnkID}
|
||||
t := &tokenizer{pieces: make(map[string]int, size), scores: make([]float64, size), unk: f.Model.UnkID}
|
||||
least := 0.0
|
||||
for i, v := range f.Model.Vocab {
|
||||
var p string
|
||||
@@ -105,6 +114,8 @@ func loadTokenizer(path string) (*tokenizer, error) {
|
||||
if f.Normalizer.Type == "Sequence" && len(f.Normalizer.Normalizers) == 1 {
|
||||
cm = f.Normalizer.Normalizers[0].Charmap
|
||||
}
|
||||
pre := f.PreTokenizer.Pretokenizers
|
||||
t.dropSpace = len(pre) > 0 && pre[0].Type == "WhitespaceSplit"
|
||||
raw, err := base64.StdEncoding.DecodeString(cm)
|
||||
if err != nil || len(raw) < 4 {
|
||||
return nil, errors.New("no precompiled charsmap")
|
||||
@@ -177,7 +188,7 @@ func (t *tokenizer) encodePlain(out []token, text string, base int) []token {
|
||||
return out
|
||||
}
|
||||
norm := t.normalize(text, base)
|
||||
for _, piece := range pretokenize(norm) {
|
||||
for _, piece := range pretokenize(norm, t.dropSpace) {
|
||||
// Metaspace: spaces become ▁, the piece starts with one, and each
|
||||
// ▁ starts a word of its own
|
||||
for i := range piece {
|
||||
@@ -200,8 +211,9 @@ func (t *tokenizer) encodePlain(out []token, text string, base int) []token {
|
||||
}
|
||||
|
||||
// pretokenize splits at whitespace: a run of it is dropped, unless it
|
||||
// follows a digit, when each of its characters is a piece of its own.
|
||||
func pretokenize(cs []nchar) [][]nchar {
|
||||
// follows a digit and not drop, when each of its characters is a piece
|
||||
// of its own.
|
||||
func pretokenize(cs []nchar, drop bool) [][]nchar {
|
||||
var out [][]nchar
|
||||
w := -1
|
||||
flush := func(i int) {
|
||||
@@ -223,7 +235,7 @@ func pretokenize(cs []nchar) [][]nchar {
|
||||
for j < len(cs) && unicode.IsSpace(cs[j].r) {
|
||||
j++
|
||||
}
|
||||
if i > 0 && cs[i-1].r >= '0' && cs[i-1].r <= '9' {
|
||||
if !drop && i > 0 && cs[i-1].r >= '0' && cs[i-1].r <= '9' {
|
||||
for k := i; k < j; k++ {
|
||||
out = append(out, cs[k:k+1:k+1])
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user