pii: pin pf-v4, whose pf-serve maps the model on the CPU

kongbai01203 (plugins#853) saw pf-serve hold ~1.82 GB of private memory
on Windows after the first redaction, until it was ended for idling. On
the CPU path pf-v3 read the whole 1.6 GB q8 GGUF into a malloc'd buffer;
the rest is ~200-270 MB of compute buffers. pf-v4 (691a10446,
weights-paged.patch) maps the file read-only instead, so the weights are
file pages the system can drop and share, not pf-serve's own memory.
Metal and Vulkan load as before.

This pins pf-v4's five zips (sha256 checked against the release's
downloads) and keeps pf-v3 in oldTags, so a user with pf-v3 on disk runs
it until upgrade() has fetched pf-v4. The idle unload stays 10 minutes
after the last request (idleAfter); the reporter's ~25 min was that
timer restarting on each request.

Measured, pf-serve on the CPU, private bytes (commit charge):
- Windows (xiaomi-gpu): v3 1,749 MB after load, 1,822 MB after a 78K-char
  text; v4 200 MB and 273 MB. pf-serve-base the same. Working set v4
  1,363 MB, file pages.
- macOS (mote): physical footprint 1.7-1.8 GB on v3, 209-303 MB on v4.
- Spans (text, offsets, score, all hashed) are identical v3 vs v4 for
  pf-serve, pf-serve-base and pf-serve-vulkan on four texts, 261 to
  78,300 chars. Vulkan on the iGPU: ~1.9-2.1 GB private on both, the
  driver's.
- End to end on Windows through pii.Find with a sandbox XDG_CACHE_HOME
  holding pf-v3 and the model, PF_DEVICE=cpu: magpie downloaded pf-v4
  through the pinned sha, ran it at 220 MB private, and removed pf-v3.

Test: TestRealServeOnTheCPUMapsTheModel (PII_REAL_SERVE, PII_REAL_DIR)
starts the real pf-serve on the CPU, checks the first span of a long
text, and fails when its own memory is over half the model. Broken by
hand by pointing it at pf-v3's binary: red on Windows (1,821 MB), WSL
Linux (1,822 MB) and mote (1,843 MB); green on pf-v4 at 272, 276 and
297 MB. It skips without the env vars, so CI doesn't download 1.6 GB.

Run on mote at 691a10446 plus this change: gofmt -l internal/pii
(clean), GOOS=windows/linux go vet ./internal/pii, go test -count=1
./internal/pii, and under lockf suite.lock go test -count=1
-timeout 45m ./...: every package ok, exit 0 (a first try was cut off
when mote rebooted). Main then gained 2fe4e9c70 in internal/pii
(serve.go, not classifyTimeout); rebased onto c66cdbea9 and run again
there: gofmt, the three go vets and go test ./internal/pii ok on mote,
go test ./internal/pii and the real test ok on Windows (272 MB). The
real test on mote at the rebased head ran out of classifyTimeout's 34s
at load 108 (others' suites; 9.5s on Windows, green on mote before at
normal load) and was not rerun there; the full suite was not rerun at
the rebased head.

Not tried: a machine actually under memory pressure (that the pages are
dropped and read back is the OS's doing), CUDA builds (none shipped),
and linux-arm64/darwin-amd64 beyond their checksums.

Reported-by: kongbai01203
This commit is contained in:
yetone
2026-11-08 19:10:44 +08:00
parent 9bef67d420
commit b85475e57e
4 changed files with 144 additions and 8 deletions
+13 -8
View File
@@ -15,7 +15,12 @@
// the sha256 pinned here, and the setting (settings.RedactModel) is saved
// only once both are. pf-serve is started on the first request that needs
// it, on the GPU where there is one (Metal, Vulkan) and else the CPU, and
// is ended after a while with none, which lets its memory go.
// is ended after a while with none (idleAfter), which lets its memory go.
// On the CPU it maps the model's file rather than reading it in
// (native/privacy-filter/patches/weights-paged.patch): the weights are
// the file's pages, which the system can drop under pressure, and what
// pf-serve holds of its own is ~200-300 MB, not 1.8 GB (#853 in
// magpie-community/plugins).
//
// A process of its own, not linked in: 1.7 GB the gateway would otherwise
// hold for good, and a GPU driver's crash that would end the gateway with
@@ -53,15 +58,15 @@ var (
// oldTags are the tags pinned before, newest first: one of theirs on disk
// is run until serveTag's is downloaded (upgrade).
var (
serveTag = "pf-v3"
oldTags = []string{"pf-v2", "pf-v1"}
serveTag = "pf-v4"
oldTags = []string{"pf-v3", "pf-v2", "pf-v1"}
serveBase = "https://github.com/yetone/magpie/releases/download/"
serveSHA = map[string]string{
"darwin-amd64": "5d9277d6852b7e3dcc30d102f43c21bf54a5c3199e0f9f998d965ec7a30ea6d7",
"darwin-arm64": "b45951751bb26633a5ca3827fbf3718f10dfd5c313da6b4f6ba786755353cb4b",
"linux-amd64": "b2b231209d8806648ec8dfe2d7b1a06c4cc273d1de4d50325e7a1638e63c7cc4",
"linux-arm64": "9812356fcb311c351c094aa9a587da3d54166382699b59e9f1c92ab08abae792",
"windows-amd64": "8fd8f7295743197311d13ed34aa9fb7be891f4e2586dfda6c4a3335e6cef52f3",
"darwin-amd64": "dc287579abeafe0be0add35305bde05f9cb06405f6b98dda5d71c9bf2c53c2a0",
"darwin-arm64": "da4c89248937221a880996964e76a3dec18a9f8f80f2ee39e1cf26ef0933ac69",
"linux-amd64": "8a7e61e6deebde68b13fc17009c84aef9da2230ea9e696c9e62b32e79c30db00",
"linux-arm64": "0c29b9fdd1452f75414ee5fc623cfec70f4180af5046a9e669a289db7bf3da08",
"windows-amd64": "4457116e76d5861b28f26fa15613a943a434d35174f30aa3b8488e76bccc6545",
}
)
+44
View File
@@ -0,0 +1,44 @@
//go:build !windows
package pii
import (
"fmt"
"os"
"os/exec"
"regexp"
"runtime"
"strconv"
"strings"
)
// privateBytes is the memory pid holds of its own, not a file's pages:
// Linux's RssAnon, macOS's physical footprint.
func privateBytes(pid int) (int64, bool) {
switch runtime.GOOS {
case "linux":
b, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", pid))
if err != nil {
return 0, false
}
for _, l := range strings.Split(string(b), "\n") {
if f := strings.Fields(l); len(f) == 3 && f[0] == "RssAnon:" {
kb, err := strconv.ParseInt(f[1], 10, 64)
return kb << 10, err == nil
}
}
case "darwin":
out, err := exec.Command("vmmap", "-summary", strconv.Itoa(pid)).Output()
if err != nil {
return 0, false
}
m := regexp.MustCompile(`(?m)^Physical footprint:\s+([\d.]+)([KMG])`).FindSubmatch(out)
if m == nil {
return 0, false
}
v, err := strconv.ParseFloat(string(m[1]), 64)
shift := map[string]uint{"K": 10, "M": 20, "G": 30}[string(m[2])]
return int64(v * float64(int64(1)<<shift)), err == nil
}
return 0, false
}
+57
View File
@@ -0,0 +1,57 @@
package pii
import (
"os"
"path/filepath"
"strings"
"testing"
)
// The real pf-serve and model, where PII_REAL_SERVE names a pf-serve and
// PII_REAL_DIR a folder holding the model under modelName(): both are
// 1.6 GB and more to download, so CI has neither and the test is skipped
// there.
func realServe(t *testing.T) string {
t.Helper()
serve, d := os.Getenv("PII_REAL_SERVE"), os.Getenv("PII_REAL_DIR")
if serve == "" || d == "" {
t.Skip("PII_REAL_SERVE and PII_REAL_DIR name no real pf-serve and model")
}
if fi, err := os.Stat(filepath.Join(d, modelName())); err != nil || fi.Size() != modelSize {
t.Fatalf("no model of %d bytes at %s: %v", modelSize, filepath.Join(d, modelName()), err)
}
old := dir
dir = func() string { return d }
t.Cleanup(func() { dir = old })
return serve
}
// On the CPU pf-serve maps the model's file and computes on its pages,
// rather than reading the 1.6 GB into memory of its own (#853 in
// magpie-community/plugins: 1.82 GB private on Windows). The pages are
// the file's: the system reads them in as they are used and lets them
// go under pressure without writing them anywhere. What the process
// holds of its own is the graph's buffers, a few hundred MB at most.
func TestRealServeOnTheCPUMapsTheModel(t *testing.T) {
h, err := startOne(realServe(t), true, nil)
if err != nil {
t.Fatal(err)
}
defer h.kill()
base := "Hi, I'm Jane Doe (jane.doe@example.com, +1 415 555 0100), living at 221B Baker Street, London. "
got, err := h.classify([]string{strings.Repeat(base, 200)})
if err != nil {
t.Fatal(err)
}
if len(got[0]) == 0 || base[got[0][0].Start:got[0][0].End] != "Jane Doe" {
t.Fatalf("found %v, want Jane Doe first", got[0][:min(len(got[0]), 4)])
}
own, ok := privateBytes(h.cmd.Process.Pid)
if !ok {
t.Skip("this system's private memory isn't read here")
}
t.Logf("pf-serve on the CPU holds %d MB of its own", own>>20)
if own > modelSize/2 {
t.Fatalf("pf-serve holds %d MB of its own, the model is %d MB: it was read into memory, not mapped", own>>20, modelSize>>20)
}
}
+30
View File
@@ -0,0 +1,30 @@
package pii
import (
"unsafe"
"golang.org/x/sys/windows"
)
// privateBytes is pid's commit charge, what Task Manager and
// Get-Process call private memory: PROCESS_MEMORY_COUNTERS'
// PagefileUsage.
func privateBytes(pid int) (int64, bool) {
h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
if err != nil {
return 0, false
}
defer windows.CloseHandle(h)
var c struct {
cb uint32
pageFaultCount uint32
peakWorkingSetSize, workingSetSize uintptr
quotaPeakPagedPoolUsage, quotaPagedPoolUsage uintptr
quotaPeakNonPagedPoolUsage, quotaNonPagedPoolUsage uintptr
pagefileUsage, peakPagefileUsage uintptr
}
c.cb = uint32(unsafe.Sizeof(c))
ok, _, _ := windows.NewLazySystemDLL("kernel32.dll").NewProc("K32GetProcessMemoryInfo").
Call(uintptr(h), uintptr(unsafe.Pointer(&c)), uintptr(c.cb))
return int64(c.pagefileUsage), ok != 0
}