Files
magpie/internal/pii/guard/embedder_test.go
T
yetone d77eb6d236 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).
2026-11-11 04:14:58 +08:00

74 lines
1.9 KiB
Go

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
}