Files
magpie/internal/pii/guard/kernel.go
T
yetone 1c3591b5d1 guard: the local masking model reads text a third faster on amd64 (mrwl666)
mrwl666 (Discord #help, v0.1.2554, Docker on a 2-core EPYC) saw one
core at 100% for 2-3 s on every request with masking and AstrLink Guard
on, and took it for every message of a ~66k-token conversation being
scanned again. It isn't. Probed on the Linux VM (GOMAXPROCS=2, taskset
-c 0,1) with a 50-60 turn Chat session of ~4 KB tool results, ~240-270 KB
a body:

- rules masking (MaskJSON without the model): 5-11 ms a turn;
- the history is cached by hash (LRU + found-<rev>.bin), and a turn
  hands the model only what it added. Bounded caps that at 4 KB;
- the request waits masking's 2 s defaultWait for the model on that
  text, and guard.Cores() is 1 on a 2-core box, so one core runs the
  int8 BERT at about 1 KB a second. That is the spike.

This change makes the model's CPU cheaper; it does not take the 2 s
wait away. AVX2 kernels for the int8 dot products (dot4, attention
scores), exp in softmax and the GELU epilogue, picked at start when
the CPU has AVX2, plus plain compares in place of the builtin float
min/max (a third of the non-matmul time, for their NaN/±0 rules).
Every float op is the same per lane and in the same order as the Go
code (release builds are GOAMD64=v1, no FMA), the int8 sums are exact,
mix32 and the softmax sum keep their order, so the model finds the
same spans with the same scores to the bit.

Numbers, Linux VM (AMD Ryzen AI MAX+ 395), one core of guard:
  guard.Find on 4,247 bytes: 4.05 s before, 2.75 s after (same 20 spans)
  turn 50-57 with the model: MaskJSON wall 2.0 s both (the wait), CPU
  after the wait 0.1-3.0 s before, 0.0-2.0 s after
mote (M5 Pro, arm64, rules path, unchanged by this):
  BenchmarkMaskLongSession chat 10.3-11.7 ms, responses 10.8-13.0 ms,
  messages 12.1-13.9 ms per turn of a ~260 KB body

Tests:
- TestKernelsSameBits: the AVX2 exp/GELU/scores give Float32bits equal
  to the Go code, edge values included. Broken by hand: swapping two
  adds in the asm exp made it red (0x175156d6 vs 0x175156d5).
- TestMaxAndRangeAsBuiltins: maxOf/rangeOf agree with the builtins on
  ±0 and NaN. Red with maxOf's NaN check taken out.
- TestModelSameWithoutAVX2 (needs MAGPIE_GUARD_DIR): the real model
  finds the same spans on ~6 KB of mixed text with AVX2 and with SSE2.
- TestSessionTurnReadsOnlyWhatItAdds (internal/pii): turn 61 of a
  275 KB session, after turn 60, has the model read only turn 61's text
  (5.2 KB for 4.6 KB added). It passes on the old code too: it guards
  the claim above, not this speedup. Red (10.5 KB, earlier turns read
  again) with the cache lookup in known() turned off by hand.
- BenchmarkMaskLongSession (internal/redact): Chat, Responses and
  Messages sessions with large tool results, turn 61 after turn 60.

Run at this tree (7b6b7492a + this):
- mote: go vet ./internal/pii/... ./internal/redact, GOOS=linux amd64
  (-tags nogui), GOOS=windows amd64, GOOS=linux arm64 guard: ok.
  go test -count=1 -timeout 45m ./internal/pii/... ./internal/redact: ok.
- WSL magpie-desktop (amd64, AVX2) with MAGPIE_GUARD_DIR: the same
  packages ok (guard 28.9 s, model tests included); the three kernel
  tests again under GOMAXPROCS=2 taskset: ok.
- Windows xiaomi-gpu: the same packages ok (no model dir there).

Not tried: the reporter's EPYC itself or Docker; AVX-VNNI or AVX-512
(would need the EPYC generation; VPDPWSSD is exact, so it could come
next); mix32 on AVX2 (more accumulators change its sum order, so not
byte-identical); the full ./... suite. For no spike at all, the model
can be turned off with rules masking kept on.
2026-11-01 15:51:18 +08:00

190 lines
4.7 KiB
Go

package guard
import "math"
// dot4fast, where the CPU has the instructions for it (kernel_*.go), sets
// out[j] to the dot product of a with b[j*len(a):(j+1)*len(a)], for
// len(a) a multiple of 32.
var dot4fast func(a, b []int8, out *[4]int32)
// dot4 is dot4fast, or the same in Go.
func dot4(a, b []int8, out *[4]int32) {
k := len(a)
if dot4fast != nil && k%32 == 0 && k > 0 {
dot4fast(a, b, out)
return
}
for j := range out {
out[j] = dot(a, b[j*k:j*k+k])
}
}
func dot(a, b []int8) int32 {
b = b[:len(a)]
var s0, s1, s2, s3 int32
i := 0
for ; i+4 <= len(a); i += 4 {
s0 += int32(a[i]) * int32(b[i])
s1 += int32(a[i+1]) * int32(b[i+1])
s2 += int32(a[i+2]) * int32(b[i+2])
s3 += int32(a[i+3]) * int32(b[i+3])
}
for ; i < len(a); i++ {
s0 += int32(a[i]) * int32(b[i])
}
return s0 + s1 + s2 + s3
}
// dot32 is a·b for one attention head's rows.
func dot32(a, b *[32]float32) float32 {
var s0, s1, s2, s3 float32
for i := 0; i < 32; i += 4 {
s0 += a[i] * b[i]
s1 += a[i+1] * b[i+1]
s2 += a[i+2] * b[i+2]
s3 += a[i+3] * b[i+3]
}
return (s0 + s1) + (s2 + s3)
}
// axpy32 adds w·v to c.
func axpy32(c *[32]float32, w float32, v *[32]float32) {
for i := range c {
c[i] += w * v[i]
}
}
// scoresFast and mixFast, where the CPU has the instructions for them,
// do what scores and mix do.
var (
scoresFast func(q *[32]float32, kt []float32, out []float32)
mixFast func(c *[32]float32, p, v []float32)
)
// scores sets out[u] to Σ q[i]·kt[i*len(out)+u]: q against each key, with
// the keys transposed, len(out) of them (a multiple of 16).
func scores(q *[32]float32, kt []float32, out []float32) {
if scoresFast != nil && len(out) > 0 {
scoresFast(q, kt, out)
return
}
np := len(out)
clear(out)
for i, w := range q {
row := kt[i*np : i*np+np]
for u, x := range row {
out[u] += w * x
}
}
}
// mix adds Σ p[u]·v[u] to c, for v's rows of 32.
func mix(c *[32]float32, p, v []float32) {
if mixFast != nil && len(p) > 0 {
mixFast(c, p, v)
return
}
for u, w := range p {
axpy32(c, w, (*[32]float32)(v[u*32:]))
}
}
// maxOf is the largest of p (-Inf for none), and rangeOf the smallest
// and largest of x and 0: what min and max over them give, but compared
// in a plain loop. The builtins' order of NaN and of -0 against +0 took
// a third of the model's time outside its matrix products. A NaN gives
// NaN as they do; where they would give -0 these may give +0, which
// neither caller tells apart (s-mx and 0-lo/scale come out the same).
func maxOf(p []float32) float32 {
mx := float32(math.Inf(-1))
for _, s := range p {
if s > mx {
mx = s
} else if s != s {
return s
}
}
return mx
}
func rangeOf(x []float32) (lo, hi float32) {
for _, v := range x {
if v < lo {
lo = v
} else if v > hi {
hi = v
} else if v != v {
return v, v
}
}
return lo, hi
}
// expf is e^x in float32, to about an ulp (Cephes' expf), for the
// softmax's x ≤ 0 and the GELU's erf.
func expf(x float32) float32 {
if x < -87.3 {
return 0
}
if x > 88.7 {
return float32(math.Inf(1))
}
n := float32(math.Floor(float64(x*1.44269504088896341 + 0.5)))
x -= n * 0.693359375
x -= n * -2.12194440e-4
z := x * x
y := ((((1.9875691500e-4*x+1.3981999507e-3)*x+8.3334519073e-3)*x+4.1665795894e-2)*x+1.6666665459e-1)*x + 5.0000001201e-1
y = y*z + x + 1
return math.Float32frombits(math.Float32bits(y) + uint32(int32(n))<<23)
}
// expSubFast and geluFast, where the CPU has the instructions for them,
// do what expSub and geluRow do for the first len&^7 of their values, the
// same float32 operations in the same order, so the same bits.
var (
expSubFast func(p []float32, mx float32)
geluFast func(row, bias, smooth []float32)
)
// expSub sets p[u] to expf(p[u]-mx): a softmax row's exponentials.
func expSub(p []float32, mx float32) {
i := 0
if expSubFast != nil && len(p) >= 8 {
i = len(p) &^ 7
expSubFast(p[:i], mx)
}
for ; i < len(p); i++ {
p[i] = expf(p[i] - mx)
}
}
// geluRow sets row[i] to gelu(row[i]+bias[i])·smooth[i]: the feed
// forward's activation.
func geluRow(row, bias, smooth []float32) {
bias, smooth = bias[:len(row)], smooth[:len(row)]
i := 0
if geluFast != nil && len(row) >= 8 {
i = len(row) &^ 7
geluFast(row[:i], bias[:i], smooth[:i])
}
for ; i < len(row); i++ {
row[i] = gelu(row[i]+bias[i]) * smooth[i]
}
}
// gelu is x·Φ(x), with erf from Abramowitz and Stegun 7.1.26 (absolute
// error under 1.5e-7, below float32's own at the values it meets).
func gelu(x float32) float32 {
z := x * 0.70710678118654752
a := z
if a < 0 {
a = -a
}
t := 1 / (1 + 0.3275911*a)
e := 1 - (((((1.061405429*t-1.453152027)*t)+1.421413741)*t-0.284496736)*t+0.254829592)*t*expf(-a*a)
if z < 0 {
e = -e
}
return 0.5 * x * (1 + e)
}