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.
This commit is contained in:
yetone
2026-11-01 15:51:18 +08:00
parent 647323409e
commit 1c3591b5d1
8 changed files with 735 additions and 16 deletions
+5 -15
View File
@@ -187,10 +187,7 @@ func loadNet(path string) (*net, error) {
// quant is DynamicQuantizeLinear: x as uint8 over its range (0 always in
// it), with its scale and zero point, as ONNX Runtime computes them.
func quant(x []float32) (q []uint8, scale float32, zp int32) {
lo, hi := float32(0), float32(0)
for _, v := range x {
lo, hi = min(lo, v), max(hi, v)
}
lo, hi := rangeOf(x)
scale = float32(1)
if hi != lo {
scale = (hi - lo) / 255
@@ -338,10 +335,7 @@ func (nt *net) encode(x []float32, n, procs int) []float32 {
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 {
v += l.upBias[i]
row[i] = gelu(v) * l.smooth[i]
}
geluRow(row, l.upBias, l.smooth)
}
o := l.down.matmul(h, n, procs)
skipNorm(o, x, n, l.downBias, l.ln2w, l.ln2b)
@@ -404,14 +398,10 @@ func attention(qkv []float32, n, procs int) []float32 {
}
scores(&qs, kt[h*d*np:(h+1)*d*np], p)
ps := p[:n]
mx := float32(math.Inf(-1))
for _, s := range ps {
mx = max(mx, s)
}
mx := maxOf(ps)
expSub(ps, mx)
var sum float32
for u, s := range ps {
e := expf(s - mx)
ps[u] = e
for _, e := range ps {
sum += e
}
inv := 1 / sum
+65
View File
@@ -89,6 +89,37 @@ func mix(c *[32]float32, p, v []float32) {
}
}
// 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 {
@@ -107,6 +138,40 @@ func expf(x float32) float32 {
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 {
+67 -1
View File
@@ -1,5 +1,11 @@
package guard
import (
"math"
"golang.org/x/sys/cpu"
)
//go:noescape
func dot4sse(a, b *int8, k int, out *[4]int32)
@@ -9,7 +15,44 @@ func scoresT(q, kt *float32, np int, out *float32)
//go:noescape
func mix32(c, p, v *float32, n int)
func init() {
//go:noescape
func dot4avx2(a, b *int8, k int, out *[4]int32)
//go:noescape
func scoresAVX2(q, kt *float32, np int, out *float32)
//go:noescape
func expSubAVX2(p *float32, n int, mx float32, k *[23][8]uint32)
//go:noescape
func geluAVX2(row, bias, smooth *float32, n int, k *[23][8]uint32)
// avxK are expf's and gelu's constants as float32 bits, eight lanes each,
// in the order kernel_amd64.s reads them.
var avxK = func() (k [23][8]uint32) {
f := math.Float32bits
for i, v := range [23]uint32{
f(1.44269504088896341), f(0.5), f(0.693359375), f(-2.12194440e-4),
f(1.9875691500e-4), f(1.3981999507e-3), f(8.3334519073e-3), f(4.1665795894e-2), f(1.6666665459e-1), f(5.0000001201e-1),
f(1), f(-87.3), f(88.7), 0x7f800000, 0x80000000,
f(0.70710678118654752), f(0.3275911),
f(1.061405429), f(1.453152027), f(1.421413741), f(0.284496736), f(0.254829592),
0x7fffffff,
} {
for j := range k[i] {
k[i][j] = v
}
}
return
}()
// useAVX2 says the kernels below run on AVX2: a var for tests.
var useAVX2 = cpu.X86.HasAVX2
func init() { pickKernels() }
// pickKernels sets the fast kernels for this CPU.
func pickKernels() {
dot4fast = func(a, b []int8, out *[4]int32) {
_ = b[4*len(a)-1]
dot4sse(&a[0], &b[0], len(a), out)
@@ -22,4 +65,27 @@ func init() {
_ = v[32*len(p)-1]
mix32(&c[0], &p[0], &v[0], len(p))
}
expSubFast, geluFast = nil, nil
// AVX2 (Haswell, Zen and later): twice the lanes for the int8 dot
// products, the scores, the softmax's exponentials and the GELU, where
// a 2-core server read 4 KB of a tool result in about 4 s on SSE2
// (mrwl666 on Discord, 11-01: a core at 100% for 2-3 s a request).
if !useAVX2 {
return
}
dot4fast = func(a, b []int8, out *[4]int32) {
_ = b[4*len(a)-1]
dot4avx2(&a[0], &b[0], len(a), out)
}
scoresFast = func(q *[32]float32, kt []float32, out []float32) {
_ = kt[32*len(out)-1]
scoresAVX2(&q[0], &kt[0], len(out), &out[0])
}
expSubFast = func(p []float32, mx float32) {
expSubAVX2(&p[0], len(p), mx, &avxK)
}
geluFast = func(row, bias, smooth []float32) {
_, _ = bias[len(row)-1], smooth[len(row)-1]
geluAVX2(&row[0], &bias[0], &smooth[0], len(row), &avxK)
}
}
+254
View File
@@ -203,3 +203,257 @@ mdone:
MOVUPS X6, 96(DI)
MOVUPS X7, 112(DI)
RET
// The kernels below need AVX2 (kernel_amd64.go checks for it). Each does
// what the one above it, or the Go in kernel.go, does: the int8 sums
// exactly, the float32 ones lane by lane with the same operations in the
// same order and no fused multiply-add, so the same bits.
// func dot4avx2(a, b *int8, k int, out *[4]int32)
// out[j] = Σ a[i]*b[j*k+i] for i < k, k a multiple of 32.
TEXT ·dot4avx2(SB), NOSPLIT, $0-32
MOVQ a+0(FP), BX
MOVQ b+8(FP), SI
MOVQ k+16(FP), DX
MOVQ out+24(FP), DI
LEAQ (SI)(DX*1), R8
LEAQ (R8)(DX*1), R9
LEAQ (R9)(DX*1), R10
VPXOR Y8, Y8, Y8
VPXOR Y9, Y9, Y9
VPXOR Y10, Y10, Y10
VPXOR Y11, Y11, Y11
XORQ CX, CX
TESTQ DX, DX
JEQ vdone
vloop:
VPMOVSXBW (BX)(CX*1), Y0
VPMOVSXBW 16(BX)(CX*1), Y1
VPMOVSXBW (SI)(CX*1), Y2
VPMOVSXBW 16(SI)(CX*1), Y3
VPMADDWD Y0, Y2, Y2
VPMADDWD Y1, Y3, Y3
VPADDD Y2, Y8, Y8
VPADDD Y3, Y8, Y8
VPMOVSXBW (R8)(CX*1), Y4
VPMOVSXBW 16(R8)(CX*1), Y5
VPMADDWD Y0, Y4, Y4
VPMADDWD Y1, Y5, Y5
VPADDD Y4, Y9, Y9
VPADDD Y5, Y9, Y9
VPMOVSXBW (R9)(CX*1), Y2
VPMOVSXBW 16(R9)(CX*1), Y3
VPMADDWD Y0, Y2, Y2
VPMADDWD Y1, Y3, Y3
VPADDD Y2, Y10, Y10
VPADDD Y3, Y10, Y10
VPMOVSXBW (R10)(CX*1), Y4
VPMOVSXBW 16(R10)(CX*1), Y5
VPMADDWD Y0, Y4, Y4
VPMADDWD Y1, Y5, Y5
VPADDD Y4, Y11, Y11
VPADDD Y5, Y11, Y11
ADDQ $32, CX
CMPQ CX, DX
JLT vloop
vdone:
VEXTRACTI128 $1, Y8, X0
VPADDD X0, X8, X8
VPSHUFD $0x4e, X8, X0
VPADDD X0, X8, X8
VPSHUFD $0xb1, X8, X0
VPADDD X0, X8, X8
VMOVD X8, 0(DI)
VEXTRACTI128 $1, Y9, X0
VPADDD X0, X9, X9
VPSHUFD $0x4e, X9, X0
VPADDD X0, X9, X9
VPSHUFD $0xb1, X9, X0
VPADDD X0, X9, X9
VMOVD X9, 4(DI)
VEXTRACTI128 $1, Y10, X0
VPADDD X0, X10, X10
VPSHUFD $0x4e, X10, X0
VPADDD X0, X10, X10
VPSHUFD $0xb1, X10, X0
VPADDD X0, X10, X10
VMOVD X10, 8(DI)
VEXTRACTI128 $1, Y11, X0
VPADDD X0, X11, X11
VPSHUFD $0x4e, X11, X0
VPADDD X0, X11, X11
VPSHUFD $0xb1, X11, X0
VPADDD X0, X11, X11
VMOVD X11, 12(DI)
VZEROUPPER
RET
// func scoresAVX2(q, kt *float32, np int, out *float32)
// scoresT, 32 keys a block where it can, 16 where not.
TEXT ·scoresAVX2(SB), NOSPLIT, $0-32
MOVQ q+0(FP), SI
MOVQ kt+8(FP), BX
MOVQ np+16(FP), DX
MOVQ out+24(FP), DI
MOVQ DX, R8
SHLQ $2, R8 // a row of kt in bytes
sblock:
CMPQ DX, $32
JLT shalf
VXORPS Y0, Y0, Y0
VXORPS Y1, Y1, Y1
VXORPS Y2, Y2, Y2
VXORPS Y3, Y3, Y3
MOVQ SI, R9
MOVQ BX, R10
MOVQ $32, CX
srow:
VBROADCASTSS (R9), Y4
VMULPS (R10), Y4, Y5
VMULPS 32(R10), Y4, Y6
VMULPS 64(R10), Y4, Y7
VMULPS 96(R10), Y4, Y8
VADDPS Y5, Y0, Y0
VADDPS Y6, Y1, Y1
VADDPS Y7, Y2, Y2
VADDPS Y8, Y3, Y3
ADDQ $4, R9
ADDQ R8, R10
DECQ CX
JNE srow
VMOVUPS Y0, (DI)
VMOVUPS Y1, 32(DI)
VMOVUPS Y2, 64(DI)
VMOVUPS Y3, 96(DI)
ADDQ $128, DI
ADDQ $128, BX
SUBQ $32, DX
JMP sblock
shalf:
TESTQ DX, DX
JEQ sdone
VXORPS Y0, Y0, Y0
VXORPS Y1, Y1, Y1
MOVQ SI, R9
MOVQ BX, R10
MOVQ $32, CX
shrow:
VBROADCASTSS (R9), Y4
VMULPS (R10), Y4, Y5
VMULPS 32(R10), Y4, Y6
VADDPS Y5, Y0, Y0
VADDPS Y6, Y1, Y1
ADDQ $4, R9
ADDQ R8, R10
DECQ CX
JNE shrow
VMOVUPS Y0, (DI)
VMOVUPS Y1, 32(DI)
sdone:
VZEROUPPER
RET
// EXPF sets R to expf(X), lane by lane, as kernel.go's expf: k (R11) holds
// avxK's constants, eight lanes each. T1..T3 are overwritten.
#define EXPF(X, R, T1, T2, T3) \
VMULPS 0(R11), X, T1 \
; VADDPS 32(R11), T1, T1 \
; VROUNDPS $1, T1, T1 \
; VMULPS 64(R11), T1, T2 \
; VSUBPS T2, X, T2 \
; VMULPS 96(R11), T1, T3 \
; VSUBPS T3, T2, T2 \
; VMULPS 128(R11), T2, R \
; VADDPS 160(R11), R, R \
; VMULPS T2, R, R \
; VADDPS 192(R11), R, R \
; VMULPS T2, R, R \
; VADDPS 224(R11), R, R \
; VMULPS T2, R, R \
; VADDPS 256(R11), R, R \
; VMULPS T2, R, R \
; VADDPS 288(R11), R, R \
; VMULPS T2, T2, T3 \
; VMULPS T3, R, R \
; VADDPS T2, R, R \
; VADDPS 320(R11), R, R \
; VCVTTPS2DQ T1, T1 \
; VPSLLD $23, T1, T1 \
; VPADDD T1, R, R \
; VCMPPS $1, 352(R11), X, T3 \
; VANDNPS R, T3, R \
; VCMPPS $14, 384(R11), X, T3 \
; VBLENDVPS T3, 416(R11), R, R
// func expSubAVX2(p *float32, n int, mx float32, k *[23][8]uint32)
// p[u] = expf(p[u]-mx) for u < n, n a multiple of 8.
TEXT ·expSubAVX2(SB), NOSPLIT, $0-32
MOVQ p+0(FP), DI
MOVQ n+8(FP), CX
VBROADCASTSS mx+16(FP), Y7
MOVQ k+24(FP), R11
TESTQ CX, CX
JEQ edone
eloop:
VMOVUPS (DI), Y0
VSUBPS Y7, Y0, Y0
EXPF(Y0, Y1, Y2, Y3, Y4)
VMOVUPS Y1, (DI)
ADDQ $32, DI
SUBQ $8, CX
JNE eloop
edone:
VZEROUPPER
RET
// func geluAVX2(row, bias, smooth *float32, n int, k *[23][8]uint32)
// row[i] = gelu(row[i]+bias[i])*smooth[i] for i < n, n a multiple of 8.
TEXT ·geluAVX2(SB), NOSPLIT, $0-40
MOVQ row+0(FP), DI
MOVQ bias+8(FP), SI
MOVQ smooth+16(FP), DX
MOVQ n+24(FP), CX
MOVQ k+32(FP), R11
TESTQ CX, CX
JEQ gdone
gloop:
VMOVUPS (DI), Y0
VADDPS (SI), Y0, Y0 // x = row + bias
VMULPS 480(R11), Y0, Y5 // z = x·(1/√2)
VANDPS 704(R11), Y5, Y6 // a = |z|
VMULPS 512(R11), Y6, Y8
VADDPS 320(R11), Y8, Y8
VMOVUPS 320(R11), Y9
VDIVPS Y8, Y9, Y9 // t = 1/(1+p·a)
VMULPS 544(R11), Y9, Y10
VSUBPS 576(R11), Y10, Y10
VMULPS Y9, Y10, Y10
VADDPS 608(R11), Y10, Y10
VMULPS Y9, Y10, Y10
VSUBPS 640(R11), Y10, Y10
VMULPS Y9, Y10, Y10
VADDPS 672(R11), Y10, Y10
VMULPS Y9, Y10, Y10 // poly·t
VMULPS Y6, Y6, Y1
VXORPS 448(R11), Y1, Y1 // -a·a
EXPF(Y1, Y2, Y3, Y4, Y11)
VMULPS Y2, Y10, Y10
VMOVUPS 320(R11), Y12
VSUBPS Y10, Y12, Y12 // e = 1 - poly·t·expf(-a·a)
VXORPS Y13, Y13, Y13
VCMPPS $1, Y13, Y5, Y13 // z < 0
VANDPS 448(R11), Y13, Y13
VXORPS Y13, Y12, Y12 // e = -e there
VMULPS 32(R11), Y0, Y0 // 0.5·x
VADDPS 320(R11), Y12, Y12 // 1 + e
VMULPS Y12, Y0, Y0
VMULPS (DX), Y0, Y0 // ·smooth
VMOVUPS Y0, (DI)
ADDQ $32, DI
ADDQ $32, SI
ADDQ $32, DX
SUBQ $8, CX
JNE gloop
gdone:
VZEROUPPER
RET
+41
View File
@@ -0,0 +1,41 @@
package guard
import (
"fmt"
"reflect"
"strings"
"testing"
)
// The model finds the same spans with the same scores, to the bit, with
// the AVX2 kernels and with SSE2 alone: a CPU with AVX2 masks a request
// as one without it does.
func TestModelSameWithoutAVX2(t *testing.T) {
if !useAVX2 {
t.Skip("no AVX2 on this CPU")
}
m, err := Load(dir(t))
if err != nil {
t.Fatal(err)
}
m.ml = nil
var b strings.Builder
for i := 0; b.Len() < 6<<10; i++ {
fmt.Fprintf(&b, "/home/mrwl/projects/api/store_%d.go:%d: db.QueryRow(\"SELECT email FROM users WHERE id = $1\")\n", i, 40+i)
fmt.Fprintf(&b, "Author: Wei Zhang <wei.zhang@example.com> postgres://app:S3cr3tPassw0rd%d@db.internal:5432/orders\n", i)
fmt.Fprintf(&b, "联系人:张三,电话 138%08d,住在北京市海淀区中关村大街%d号。\n", i*7919, i)
}
text := b.String()
with := m.Find(text)
useAVX2 = false
pickKernels()
without := m.Find(text)
useAVX2 = true
pickKernels()
if len(with) == 0 {
t.Fatal("found nothing")
}
if !reflect.DeepEqual(with, without) {
t.Fatalf("AVX2 found %d spans, SSE2 %d:\n%v\n%v", len(with), len(without), with, without)
}
}
+106
View File
@@ -1,6 +1,7 @@
package guard
import (
"fmt"
"math"
"math/rand"
"testing"
@@ -95,3 +96,108 @@ func TestExpfAndGelu(t *testing.T) {
}
}
}
// The softmax's exponentials, the GELU and the scores give the Go's very
// bits with the kernels (AVX2 on amd64), not only values near them: what
// the model finds, and so what is masked, is the same on every CPU.
func TestKernelsSameBits(t *testing.T) {
if expSubFast == nil || geluFast == nil {
t.Log("no exp or gelu kernel on this CPU; the Go runs both sides")
}
r := rand.New(rand.NewSource(2))
same := func(what string, got, want []float32) {
t.Helper()
for i := range got {
if math.Float32bits(got[i]) != math.Float32bits(want[i]) {
t.Fatalf("%s [%d]: %v (%#x), Go %v (%#x)", what, i, got[i], math.Float32bits(got[i]), want[i], math.Float32bits(want[i]))
}
}
}
edges := []float32{0, float32(math.Copysign(0, -1)), -87.2, -87.3, -87.4, -100, -1e30, 88.6, 88.7, 88.8, 1e-40, -1e-40, 1, -1}
for _, n := range []int{1, 8, 13, 512, 1536 + 5} {
x := make([]float32, n)
for i := range x {
switch {
case i < len(edges) && n > len(edges):
x[i] = edges[i]
case i%3 == 0:
x[i] = -r.Float32() * 90
default:
x[i] = (r.Float32()*2 - 1) * 12
}
}
mx := float32(r.Float32())
got, want := append([]float32(nil), x...), append([]float32(nil), x...)
expSub(got, mx)
f := expSubFast
expSubFast = nil
expSub(want, mx)
expSubFast = f
same(fmt.Sprintf("expSub over %d", n), got, want)
bias, smooth := make([]float32, n), make([]float32, n)
for i := range bias {
bias[i] = r.Float32()*0.2 - 0.1
smooth[i] = r.Float32() + 0.5
}
got, want = append([]float32(nil), x...), append([]float32(nil), x...)
geluRow(got, bias, smooth)
g := geluFast
geluFast = nil
geluRow(want, bias, smooth)
geluFast = g
same(fmt.Sprintf("geluRow over %d", n), got, want)
}
for _, n := range []int{1, 16, 17, 33, 48, 512} {
np := (n + 15) &^ 15
var q [32]float32
for i := range q {
q[i] = r.Float32()*2 - 1
}
kt := make([]float32, 32*np)
for i := range kt {
kt[i] = r.Float32()*2 - 1
}
got, want := make([]float32, np), make([]float32, np)
scores(&q, kt, got)
f := scoresFast
scoresFast = nil
scores(&q, kt, want)
scoresFast = f
same(fmt.Sprintf("scores over %d keys", n), got, want)
}
}
// maxOf and rangeOf give what the builtins give, to a zero's sign: NaN
// for a NaN anywhere.
func TestMaxAndRangeAsBuiltins(t *testing.T) {
r := rand.New(rand.NewSource(3))
nan, neg0 := float32(math.NaN()), float32(math.Copysign(0, -1))
for c := 0; c < 2000; c++ {
x := make([]float32, r.Intn(40))
for i := range x {
switch r.Intn(12) {
case 0:
x[i] = 0
case 1:
x[i] = neg0
case 2:
if c%10 == 0 {
x[i] = nan
}
default:
x[i] = (r.Float32()*2 - 1) * 50
}
}
mx, lo, hi := float32(math.Inf(-1)), float32(0), float32(0)
for _, v := range x {
mx = max(mx, v)
lo, hi = min(lo, v), max(hi, v)
}
eq := func(a, b float32) bool { return a == b || a != a && b != b }
gl, gh := rangeOf(x)
if !eq(maxOf(x), mx) || !eq(gl, lo) || !eq(gh, hi) {
t.Fatalf("%v: maxOf %v rangeOf %v %v, builtins %v %v %v", x, maxOf(x), gl, gh, mx, lo, hi)
}
}
}
+79
View File
@@ -0,0 +1,79 @@
package pii
import (
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/yetone/magpie/internal/redact"
)
// sessionBody is turn n of an agent's Chat Completions session, as a
// gateway gets it: the whole conversation again, a tool result of about
// 4 KB a turn.
func sessionBody(n int) []byte {
msgs := []any{map[string]any{"role": "system", "content": "You are a coding agent working in /home/mrwl/projects/api. " + strings.Repeat("Run the tests, keep changes small. ", 40)}}
for i := 0; i < n; i++ {
var out strings.Builder
for k := 0; out.Len() < 4<<10; k++ {
fmt.Fprintf(&out, "/home/mrwl/projects/api/store_%d_%d.go:%d: db.QueryRow(\"SELECT email FROM users WHERE id = $1\") // Alice %d\n", i, k, 40+k, k)
}
msgs = append(msgs,
map[string]any{"role": "user", "content": fmt.Sprintf("step %d: the webhook still fails on retries", i)},
map[string]any{"role": "assistant", "content": "", "tool_calls": []any{map[string]any{"id": fmt.Sprintf("call_%d", i), "type": "function", "function": map[string]any{"name": "shell", "arguments": fmt.Sprintf(`{"command":"grep -rn webhook . | head -%d"}`, 50+i)}}}},
map[string]any{"role": "tool", "tool_call_id": fmt.Sprintf("call_%d", i), "content": out.String()},
)
}
b, _ := json.Marshal(map[string]any{"model": "gpt-6-luna", "stream": true, "messages": msgs})
return b
}
// A long conversation's request has the local model read what that turn
// added, not the conversation again: masking turn 61 of a ~260 KB session
// after turn 60 reads the new turn's few KB. mrwl666 on Discord (11-01)
// took the 2-3 s at 100% of a core a request for every message read
// again; it is the model reading the new turn's tool result, on the CPU
// about a KB a second a core.
func TestSessionTurnReadsOnlyWhatItAdds(t *testing.T) {
r := newReader(t, guardChunk)
o := redact.Options{Secrets: true, Personal: true, Route: "openai"}
mask := func(body []byte) []byte {
oo := o
oo.Model = func(texts []string) [][]redact.Found {
got, err := r.find(Bounded(context.Background()), texts)
if err != nil {
t.Fatal(err)
}
return got
}
out, _ := redact.MaskJSON(body, oo)
return out
}
const turns = 60
mask(sessionBody(turns))
first, reads := r.bytes()
body := sessionBody(turns + 1)
added := len(body) - len(sessionBody(turns))
out := mask(body)
n, _ := r.bytes()
// what it adds is a tool result read in two pieces, which overlap
if read := n - first; read == 0 || read > 2*added {
t.Fatalf("turn %d of a %d KB session had the model read %d bytes; the turn added %d", turns+1, len(body)>>10, read, added)
}
for _, a := range r.asked[reads:] {
if !strings.Contains(a, fmt.Sprintf("store_%d_", turns)) && !strings.Contains(a, fmt.Sprintf("step %d:", turns)) {
t.Fatalf("turn %d had the model read text of an earlier turn again: %.80q", turns+1, a)
}
}
// and it is masked as the turn before had it: the same history, the
// same placeholders
again := mask(body)
if string(out) != string(again) {
t.Fatal("masking the same turn twice gave different bodies")
}
if first < 200<<10 {
t.Fatalf("the first request read %d bytes: not the whole session", first)
}
}
+118
View File
@@ -0,0 +1,118 @@
package redact
import (
"encoding/json"
"fmt"
"strings"
"testing"
)
// A long agent session as it reaches the gateway: every turn sends the
// whole conversation again, a few KB of tool output a turn, with what the
// rules look for here and there in it (paths with a user's name, an
// email, an address, a key in a config file, a UUID, a log's IPs).
// toolOutput is turn i's tool output, about kb KB of it.
func toolOutput(i, kb int) string {
var b strings.Builder
for n := 0; b.Len() < kb*1024; n++ {
switch (i + n) % 6 {
case 0:
fmt.Fprintf(&b, "%d:func (s *Server) handle%d(w http.ResponseWriter, r *http.Request) {\n\tctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)\n\tdefer cancel()\n\tif err := s.store.Put(ctx, r.URL.Query().Get(\"id\"), body); err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t}\n}\n", n, i*100+n)
case 1:
fmt.Fprintf(&b, "/home/mrwl/projects/api/internal/store/store_%d.go:%d:\terr := db.QueryRowContext(ctx, \"SELECT id, name, email FROM users WHERE id = $1\", id).Scan(&u.ID, &u.Name, &u.Email)\n", n, 40+n)
case 2:
fmt.Fprintf(&b, "2026-10-31T12:%02d:%02d.%03dZ INFO request id=%08x-1f2e-4d3c-9b8a-%012x method=POST path=/v1/orders/%d status=200 dur=%dms remote=10.0.%d.%d\n", n%60, i%60, n%1000, i*7919+n, n*104729, n, 3+n%90, n%255, i%255)
case 3:
fmt.Fprintf(&b, " --- PASS: TestOrderFlow/case_%d (0.%02ds)\n order_test.go:%d: created order %d for customer %d, total 129.%02d EUR\n", n, n%100, 100+n, 5000+n, 300+i, n%100)
case 4:
fmt.Fprintf(&b, " config.yaml:%d database_url: postgres://app:%s@db.internal:5432/orders # turn %d\n", n, "S3cr3tPassw0rd2026", i)
case 5:
fmt.Fprintf(&b, "Author: Wei Zhang <wei.zhang@example.com> commit %040x\n fix: retry the payment webhook when the upstream answers 502 (#%d)\n", i*31337+n, 1000+n)
}
}
return b.String()
}
// chatSession is a Chat Completions request on turn n, as an agent on a
// gateway sends gpt-6-luna one: a system prompt, then each turn a user
// message, an assistant tool call and its tool output.
func chatSession(n, kb int) []byte {
msgs := []any{map[string]any{"role": "system", "content": "You are a coding agent working in /home/mrwl/projects/api. " + strings.Repeat("Follow the repository's conventions, run the tests, keep changes small. ", 60)}}
for i := 0; i < n; i++ {
msgs = append(msgs,
map[string]any{"role": "user", "content": fmt.Sprintf("step %d: the order webhook still fails on retries, look at the logs and fix it", i)},
map[string]any{"role": "assistant", "content": "", "tool_calls": []any{map[string]any{"id": fmt.Sprintf("call_%d", i), "type": "function", "function": map[string]any{"name": "shell", "arguments": fmt.Sprintf(`{"command":"grep -rn webhook /home/mrwl/projects/api | head -%d"}`, 50+i)}}}},
map[string]any{"role": "tool", "tool_call_id": fmt.Sprintf("call_%d", i), "content": toolOutput(i, kb)},
)
}
b, _ := json.Marshal(map[string]any{"model": "gpt-6-luna", "stream": true, "messages": msgs,
"tools": []any{map[string]any{"type": "function", "function": map[string]any{"name": "shell", "description": "Run a shell command", "parameters": map[string]any{"type": "object", "properties": map[string]any{"command": map[string]any{"type": "string"}}}}}}})
return b
}
// claudeSession is a Messages request on turn n, as Claude Code sends one:
// tool_use and tool_result blocks, thinking signed by the vendor.
func claudeSession(n, kb int) []byte {
msgs := []any{}
for i := 0; i < n; i++ {
msgs = append(msgs,
map[string]any{"role": "user", "content": []any{map[string]any{"type": "text", "text": fmt.Sprintf("step %d: fix the failing webhook retry", i)}}},
map[string]any{"role": "assistant", "content": []any{
map[string]any{"type": "thinking", "thinking": fmt.Sprintf("I should grep for the webhook handler, turn %d.", i), "signature": strings.Repeat("EqQBCkYIBxgCKkA", 20)},
map[string]any{"type": "tool_use", "id": fmt.Sprintf("toolu_%024d", i), "name": "Bash", "input": map[string]any{"command": fmt.Sprintf("grep -rn webhook /home/mrwl/projects/api | head -%d", 50+i)}},
}},
map[string]any{"role": "user", "content": []any{map[string]any{"type": "tool_result", "tool_use_id": fmt.Sprintf("toolu_%024d", i), "content": toolOutput(i, kb)}}},
)
}
b, _ := json.Marshal(map[string]any{"model": "claude-opus-5-5", "stream": true, "system": []any{map[string]any{"type": "text", "text": strings.Repeat("You are Claude Code. Use the tools to work in the user's repository. ", 60)}}, "messages": msgs})
return b
}
// sessions are the three protocols' bodies on turn n, ~66k tokens (about
// 260 KB) at n = 60 and 4 KB of tool output a turn.
var sessions = []struct {
name string
body func(n, kb int) []byte
}{
{"chat", chatSession},
{"responses", func(n, kb int) []byte { return codexSession(n, kb) }},
{"messages", claudeSession},
}
// codexSession is a Responses request on turn n, as Codex sends one.
func codexSession(n, kb int) []byte {
var items []any
for i := 0; i < n; i++ {
items = append(items,
map[string]any{"type": "message", "role": "user", "content": []any{map[string]any{"type": "input_text", "text": fmt.Sprintf("step %d: fix the failing webhook retry", i)}}},
map[string]any{"type": "reasoning", "summary": []any{}, "encrypted_content": strings.Repeat("gAAAAABo", 40)},
map[string]any{"type": "function_call", "name": "shell", "arguments": fmt.Sprintf(`{"command":["bash","-lc","grep -rn webhook /home/mrwl/projects/api | head -%d"]}`, 50+i), "call_id": fmt.Sprintf("call_%d", i)},
map[string]any{"type": "function_call_output", "call_id": fmt.Sprintf("call_%d", i), "output": toolOutput(i, kb)},
)
}
b, _ := json.Marshal(map[string]any{"model": "gpt-6-luna", "instructions": strings.Repeat("You are Codex, a coding agent. ", 100), "input": items, "stream": true, "prompt_cache_key": "0199a0b2-5c3d-7e8f-9a0b-1c2d3e4f5a6b"})
return b
}
// BenchmarkMaskLongSession is masking one turn of a ~66k-token session
// whose turns before it were masked already, as each request of a long
// conversation is: the history is the same, one turn is new.
func BenchmarkMaskLongSession(b *testing.B) {
for _, s := range sessions {
b.Run(s.name, func(b *testing.B) {
Forget()
resetRuleMemo()
o := Options{Secrets: true, Personal: true, Route: "openai"}
const turns, kb = 60, 4
MaskJSON(s.body(turns, kb), o)
body := s.body(turns+1, kb)
b.SetBytes(int64(len(body)))
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
MaskJSON(body, o)
}
})
}
}