Files
magpie/internal/pii/guard/embedder.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

236 lines
6.9 KiB
Go

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
}