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).
112 lines
2.4 KiB
Go
112 lines
2.4 KiB
Go
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())
|
|
}
|