guard: a long text's windows are read at once, one a core (niuniu_8964 on X)

码妞 on X: on a 4-core server in the Docker image, with AstrLink Guard,
Claude Code's requests sat at 脱敏中 for minutes, load 1.78. Guard read a
long text's 510-token windows one after another, and split only each
window's matmuls and attention over GOMAXPROCS-1 goroutines; the layer
norms, biases, GELU and quantizing between them ran on one core. A
2-CPU container got one thread for all of it.

Find now reads every window's logits first, min(GOMAXPROCS, windows) at
once, each with GOMAXPROCS/that many goroutines of its own, then merges
them in window order as before, so what it finds is the same. A window's
procs are passed down (logits, encode, matmul, attention, parallel) in
place of the package's threads. CoreML (a Mac) still reads one window at
a time.

Measured on magpie-desktop (WSL, Ryzen AI Max+ 395), 69,495 bytes of
docs, 22,488 tokens, ~59 windows:
  GOMAXPROCS=4: 23.86s before, 17.90s now
  GOMAXPROCS=2: 48.8s before, 30.50s now
  GOMAXPROCS=1: 50.0s before, 57.0s now (the same code path; noise)

Run:
- wsl-run with MAGPIE_GUARD_DIR at the pinned model (rev 7216b6a3):
  TestWindowsAtOnceReadAsOneByOne (new: 200 synthetic contact lines, over
  4 windows, read at GOMAXPROCS 1 and 4, spans DeepEqual), TestModelFinds,
  TestKernelsMatchGo, TestTokenizerMatchesHF, TestDecodeBIO: ok.
- mote-run: go vet ./internal/pii/..., GOOS=linux and GOOS=windows go vet
  of it, go test -race ./internal/pii/..., go test ./internal/pii/...
  ./internal/redact/...: ok.
- win-run go test ./internal/pii/guard: ok.

Broken by hand: swapping the first two windows' logits after the wait
made the new test red ("windows at once found 800 spans, one by one
800": the same count, different spans).

Not tried: the reporter's own server, or a real Claude Code request
through the Docker image; TestCoreMLMatchesGo (needs the model on a
Mac) was only compiled. The full suite wasn't run: nothing outside
internal/pii/guard calls what changed but Find.
This commit is contained in:
yetone
2026-10-28 17:15:16 +08:00
parent eb6d1d8d97
commit aca0f0d8a1
5 changed files with 108 additions and 36 deletions
File diff suppressed because one or more lines are too long
+25 -20
View File
@@ -207,10 +207,11 @@ func quant(x []float32) (q []uint8, scale float32, zp int32) {
}
// matmul is x [rows, m.k] quantized, times m: float32(Σ (x-xz)(w-wz)) *
// (xs*ws), as MatMulInteger, Cast and Mul do it, in out [rows, m.n]. The
// (xs*ws), as MatMulInteger, Cast and Mul do it, in out [rows, m.n], over
// t goroutines. The
// kernels take int8 on both sides, so x's uint8 q goes as q-128, and
// Σ q·w = Σ (q-128)·w + 128·Σ w.
func (m *qmat) matmul(x []float32, rows int) []float32 {
func (m *qmat) matmul(x []float32, rows, t int) []float32 {
q, xs, xz := quant(x)
s := make([]int8, len(q))
xsum := make([]int32, rows)
@@ -224,7 +225,7 @@ func (m *qmat) matmul(x []float32, rows int) []float32 {
}
out := make([]float32, rows*m.n)
groups := (m.n + 3) / 4
parallel(groups, func(g0, g1 int) {
parallel(t, groups, func(g0, g1 int) {
var acc [4]int32
for g := g0; g < g1; g++ {
c0 := 4 * g
@@ -250,12 +251,13 @@ func (m *qmat) matmul(x []float32, rows int) []float32 {
return out
}
// threads is how many goroutines a matmul is split over.
// threads is how many goroutines the model reads with: a long text's
// windows that many at once, or one window's matmuls split over them.
var threads = max(1, runtime.GOMAXPROCS(0)-1)
// parallel calls f over [0, n) in threads parts at once.
func parallel(n int, f func(a, b int)) {
t := min(threads, n)
// parallel calls f over [0, n) in t parts at once.
func parallel(t, n int, f func(a, b int)) {
t = min(t, n)
if t <= 1 {
f(0, n)
return
@@ -295,9 +297,10 @@ func layerNorm(x []float32, rows int, w, b []float32) {
}
// logits are the classifier's scores for each of ids, a sequence of up to
// maxPos tokens with its <s> and </s>: [len(ids), labels].
func (nt *net) logits(ids []int) []float32 {
return nt.encode(nt.embed(ids, 0), len(ids))
// maxPos tokens with its <s> and </s>: [len(ids), labels], read over procs
// goroutines.
func (nt *net) logits(ids []int, procs int) []float32 {
return nt.encode(nt.embed(ids, 0), len(ids), procs)
}
// embed is the layer-normed embeddings of ids, [len(ids), hidden], in a
@@ -317,22 +320,23 @@ func (nt *net) embed(ids []int, rows int) []float32 {
return x
}
// encode is the classifier's scores for embeddings x of n tokens.
func (nt *net) encode(x []float32, n 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 {
for i := range nt.layers {
l := &nt.layers[i]
qkv := l.qkv.matmul(x, n)
qkv := l.qkv.matmul(x, n, procs)
for t := 0; t < n; t++ {
row := qkv[t*3*hidden : t*3*hidden+3*hidden]
for i, b := range l.qkvBias {
row[i] += b
}
}
ctx := attention(qkv, n)
a := l.attnOut.matmul(ctx, n)
ctx := attention(qkv, n, procs)
a := l.attnOut.matmul(ctx, n, procs)
skipNorm(a, x, n, l.attnBias, l.ln1w, l.ln1b)
x = a
h := l.up.matmul(x, n)
h := l.up.matmul(x, n, procs)
for t := 0; t < n; t++ {
row := h[t*inter : t*inter+inter]
for i, v := range row {
@@ -340,11 +344,11 @@ func (nt *net) encode(x []float32, n int) []float32 {
row[i] = gelu(v) * l.smooth[i]
}
}
o := l.down.matmul(h, n)
o := l.down.matmul(h, n, procs)
skipNorm(o, x, n, l.downBias, l.ln2w, l.ln2b)
x = o
}
out := nt.cls.matmul(x, n)
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 {
@@ -368,7 +372,8 @@ func skipNorm(out, skip []float32, rows int, bias, w, b []float32) {
// attention is the self-attention of qkv [n, 3*hidden] (Q, K, V side by
// side, each head's 32 columns together), every token seeing every other.
func attention(qkv []float32, n int) []float32 {
// It runs over procs goroutines.
func attention(qkv []float32, n, procs int) []float32 {
const d = hidden / heads
scale := float32(1 / math.Sqrt(d))
ctx := make([]float32, n*hidden)
@@ -390,7 +395,7 @@ func attention(qkv []float32, n int) []float32 {
}
}
}
parallel(heads*n, func(a, b int) {
parallel(procs, heads*n, func(a, b int) {
p := make([]float32, np)
var qs, c [d]float32
for j := a; j < b; j++ {
+1 -1
View File
@@ -69,7 +69,7 @@ func TestCoreMLMatchesGo(t *testing.T) {
ids = append(ids, k.id)
}
ids = append(ids, 2)
want := m.net.logits(ids)
want := m.net.logits(ids, threads)
t1 := time.Now()
got, err := coremlLogits(m.ml, m.net, ids)
if err != nil {
+49 -14
View File
@@ -9,6 +9,9 @@ import (
"fmt"
"math"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
"github.com/yetone/magpie/internal/pii/guard/coreml"
)
@@ -78,30 +81,37 @@ func Load(dir string) (*Model, error) {
}
// logits are the network's scores for ids, from CoreML when it is there
// and the window is long enough to gain by it.
func (m *Model) logits(ids []int) []float32 {
// and the window is long enough to gain by it, else over procs goroutines.
func (m *Model) logits(ids []int, procs int) []float32 {
if m.ml != nil && len(ids) >= coremlMin {
if lg, err := coremlLogits(m.ml, m.net, ids); err == nil {
return lg
}
}
return m.net.logits(ids)
return m.net.logits(ids, procs)
}
// Find is what the model finds in text, at Floor, each span with its score.
// A text longer than a window is read a window at a time, overlapping,
// and on the CPU those windows are read at once, one a core: a window's
// own matmuls split over the cores leave most of each idle in the steps
// between them (a 4-core server read a long prompt for minutes).
func (m *Model) Find(text string) []Span {
toks := m.tok.encode(text)
n := len(toks)
if n == 0 {
return nil
}
lab := make([]int, n)
prob := make([]float64, n)
margin := make([]int, n)
for i := range margin {
margin[i] = -1
}
var starts []int
for start := 0; ; start = start + window - overlap {
starts = append(starts, start)
if start+window >= n {
break
}
}
lgs := make([][]float32, len(starts))
read := func(w, procs int) {
start := starts[w]
end := min(start+window, n)
ids := make([]int, 0, end-start+2)
ids = append(ids, 0)
@@ -109,8 +119,36 @@ func (m *Model) Find(text string) []Span {
ids = append(ids, t.id)
}
ids = append(ids, 2)
lg := m.logits(ids)
k := len(labels)
lgs[w] = m.logits(ids, procs)
}
procs := runtime.GOMAXPROCS(0)
at := min(procs, len(starts))
if m.ml != nil || at == 1 {
for w := range starts {
read(w, threads)
}
} else {
var next atomic.Int32
var wg sync.WaitGroup
for range at {
wg.Go(func() {
for w := int(next.Add(1)) - 1; w < len(starts); w = int(next.Add(1)) - 1 {
read(w, max(1, procs/at))
}
})
}
wg.Wait()
}
lab := make([]int, n)
prob := make([]float64, n)
margin := make([]int, n)
for i := range margin {
margin[i] = -1
}
k := len(labels)
for w, start := range starts {
end := min(start+window, n)
lg := lgs[w]
for i := 0; i < end-start; i++ {
j := start + i
mg := min(i, end-start-1-i)
@@ -130,9 +168,6 @@ func (m *Model) Find(text string) []Span {
}
margin[j], lab[j], prob[j] = mg, best, 1/sum
}
if end == n {
break
}
}
return decode(toks, lab, prob)
}
+32
View File
@@ -2,9 +2,12 @@ package guard
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
"unicode/utf8"
)
@@ -110,3 +113,32 @@ func TestModelFinds(t *testing.T) {
t.Fatalf("found %v, want %v", have, want)
}
}
// TestWindowsAtOnceReadAsOneByOne: a text of many windows, read with its
// windows at once, finds what it does read a window at a time.
func TestWindowsAtOnceReadAsOneByOne(t *testing.T) {
m, err := Load(dir(t))
if err != nil {
t.Fatal(err)
}
m.ml = nil
var b strings.Builder
for i := range 200 {
fmt.Fprintf(&b, "第%d位联系人:张三,电话 138%08d,邮箱 user%d@example.com,住在北京市海淀区中关村大街%d号。\n", i, i*7919, i, i)
}
text := b.String()
if n := len(m.tok.encode(text)); n < 4*window {
t.Fatalf("%d tokens, want several windows", n)
}
was := runtime.GOMAXPROCS(1)
one := m.Find(text)
runtime.GOMAXPROCS(max(4, was))
at := m.Find(text)
runtime.GOMAXPROCS(was)
if len(one) == 0 {
t.Fatal("found nothing")
}
if !reflect.DeepEqual(at, one) {
t.Fatalf("windows at once found %d spans, one by one %d", len(at), len(one))
}
}